fix some compiler warnings
[oweals/gnunet.git] / src / gns / gnunet-gns-proxy.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012-2018 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20 /**
21  * @author Martin Schanzenbach
22  * @author Christian Grothoff
23  * @file src/gns/gnunet-gns-proxy.c
24  * @brief HTTP(S) proxy that rewrites URIs and fakes certificats to make GNS work
25  *        with legacy browsers
26  *
27  * TODO:
28  * - double-check queueing logic
29  */
30 #include "platform.h"
31 #include <microhttpd.h>
32 #if HAVE_CURL_CURL_H
33 #include <curl/curl.h>
34 #elif HAVE_GNURL_CURL_H
35 #include <gnurl/curl.h>
36 #endif
37 #include <gnutls/gnutls.h>
38 #include <gnutls/x509.h>
39 #include <gnutls/abstract.h>
40 #include <gnutls/crypto.h>
41 #if HAVE_GNUTLS_DANE
42 #include <gnutls/dane.h>
43 #endif
44 #include <regex.h>
45 #include "gnunet_util_lib.h"
46 #include "gnunet_gns_service.h"
47 #include "gnunet_identity_service.h"
48 #include "gns.h"
49
50
51
52 /**
53  * Default Socks5 listen port.
54  */
55 #define GNUNET_GNS_PROXY_PORT 7777
56
57 /**
58  * Maximum supported length for a URI.
59  * Should die. @deprecated
60  */
61 #define MAX_HTTP_URI_LENGTH 2048
62
63 /**
64  * Maximum number of DANE records we support
65  * per domain name (and port and protocol).
66  */
67 #define MAX_DANES 32
68
69 /**
70  * Size of the buffer for the data upload / download.  Must be
71  * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
72  */
73 #define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE
74
75 /**
76  * Size of the read/write buffers for Socks.   Uses
77  * 256 bytes for the hostname (at most), plus a few
78  * bytes overhead for the messages.
79  */
80 #define SOCKS_BUFFERSIZE (256 + 32)
81
82 /**
83  * Port for plaintext HTTP.
84  */
85 #define HTTP_PORT 80
86
87 /**
88  * Port for HTTPS.
89  */
90 #define HTTPS_PORT 443
91
92 /**
93  * Largest allowed size for a PEM certificate.
94  */
95 #define MAX_PEM_SIZE (10 * 1024)
96
97 /**
98  * After how long do we clean up unused MHD TLS instances?
99  */
100 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
101
102 /**
103  * After how long do we clean up Socks5 handles that failed to show any activity
104  * with their respective MHD instance?
105  */
106 #define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
107
108
109 /**
110  * Log curl error.
111  *
112  * @param level log level
113  * @param fun name of curl_easy-function that gave the error
114  * @param rc return code from curl
115  */
116 #define LOG_CURL_EASY(level,fun,rc) \
117    GNUNET_log (level, \
118                _("%s failed at %s:%d: `%s'\n"), \
119                fun, \
120                __FILE__, \
121                __LINE__, \
122                curl_easy_strerror (rc))
123
124
125 /* *************** Socks protocol definitions (move to TUN?) ****************** */
126
127 /**
128  * Which SOCKS version do we speak?
129  */
130 #define SOCKS_VERSION_5 0x05
131
132 /**
133  * Flag to set for 'no authentication'.
134  */
135 #define SOCKS_AUTH_NONE 0
136
137
138 /**
139  * Commands in Socks5.
140  */
141 enum Socks5Commands
142 {
143   /**
144    * Establish TCP/IP stream.
145    */
146   SOCKS5_CMD_TCP_STREAM = 1,
147
148   /**
149    * Establish TCP port binding.
150    */
151   SOCKS5_CMD_TCP_PORT = 2,
152
153   /**
154    * Establish UDP port binding.
155    */
156   SOCKS5_CMD_UDP_PORT = 3
157 };
158
159
160 /**
161  * Address types in Socks5.
162  */
163 enum Socks5AddressType
164 {
165   /**
166    * IPv4 address.
167    */
168   SOCKS5_AT_IPV4 = 1,
169
170   /**
171    * IPv4 address.
172    */
173   SOCKS5_AT_DOMAINNAME = 3,
174
175   /**
176    * IPv6 address.
177    */
178   SOCKS5_AT_IPV6 = 4
179
180 };
181
182
183 /**
184  * Status codes in Socks5 response.
185  */
186 enum Socks5StatusCode
187 {
188   SOCKS5_STATUS_REQUEST_GRANTED = 0,
189   SOCKS5_STATUS_GENERAL_FAILURE = 1,
190   SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
191   SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
192   SOCKS5_STATUS_HOST_UNREACHABLE = 4,
193   SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
194   SOCKS5_STATUS_TTL_EXPIRED = 6,
195   SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
196   SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
197 };
198
199
200 /**
201  * Client hello in Socks5 protocol.
202  */
203 struct Socks5ClientHelloMessage
204 {
205   /**
206    * Should be #SOCKS_VERSION_5.
207    */
208   uint8_t version;
209
210   /**
211    * How many authentication methods does the client support.
212    */
213   uint8_t num_auth_methods;
214
215   /* followed by supported authentication methods, 1 byte per method */
216
217 };
218
219
220 /**
221  * Server hello in Socks5 protocol.
222  */
223 struct Socks5ServerHelloMessage
224 {
225   /**
226    * Should be #SOCKS_VERSION_5.
227    */
228   uint8_t version;
229
230   /**
231    * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
232    * which skips the authentication step.
233    */
234   uint8_t auth_method;
235 };
236
237
238 /**
239  * Client socks request in Socks5 protocol.
240  */
241 struct Socks5ClientRequestMessage
242 {
243   /**
244    * Should be #SOCKS_VERSION_5.
245    */
246   uint8_t version;
247
248   /**
249    * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
250    */
251   uint8_t command;
252
253   /**
254    * Reserved, always zero.
255    */
256   uint8_t resvd;
257
258   /**
259    * Address type, an `enum Socks5AddressType`.
260    */
261   uint8_t addr_type;
262
263   /*
264    * Followed by either an ip4/ipv6 address or a domain name with a
265    * length field (uint8_t) in front (depending on @e addr_type).
266    * followed by port number in network byte order (uint16_t).
267    */
268 };
269
270
271 /**
272  * Server response to client requests in Socks5 protocol.
273  */
274 struct Socks5ServerResponseMessage
275 {
276   /**
277    * Should be #SOCKS_VERSION_5.
278    */
279   uint8_t version;
280
281   /**
282    * Status code, an `enum Socks5StatusCode`
283    */
284   uint8_t reply;
285
286   /**
287    * Always zero.
288    */
289   uint8_t reserved;
290
291   /**
292    * Address type, an `enum Socks5AddressType`.
293    */
294   uint8_t addr_type;
295
296   /*
297    * Followed by either an ip4/ipv6 address or a domain name with a
298    * length field (uint8_t) in front (depending on @e addr_type).
299    * followed by port number in network byte order (uint16_t).
300    */
301
302 };
303
304
305
306 /* *********************** Datastructures for HTTP handling ****************** */
307
308 /**
309  * A structure for CA cert/key
310  */
311 struct ProxyCA
312 {
313   /**
314    * The certificate
315    */
316   gnutls_x509_crt_t cert;
317
318   /**
319    * The private key
320    */
321   gnutls_x509_privkey_t key;
322 };
323
324
325 /**
326  * Structure for GNS certificates
327  */
328 struct ProxyGNSCertificate
329 {
330   /**
331    * The certificate as PEM
332    */
333   char cert[MAX_PEM_SIZE];
334
335   /**
336    * The private key as PEM
337    */
338   char key[MAX_PEM_SIZE];
339 };
340
341
342
343 /**
344  * A structure for all running Httpds
345  */
346 struct MhdHttpList
347 {
348   /**
349    * DLL for httpds
350    */
351   struct MhdHttpList *prev;
352
353   /**
354    * DLL for httpds
355    */
356   struct MhdHttpList *next;
357
358   /**
359    * the domain name to server (only important for TLS)
360    */
361   char *domain;
362
363   /**
364    * The daemon handle
365    */
366   struct MHD_Daemon *daemon;
367
368   /**
369    * Optional proxy certificate used
370    */
371   struct ProxyGNSCertificate *proxy_cert;
372
373   /**
374    * The task ID
375    */
376   struct GNUNET_SCHEDULER_Task *httpd_task;
377
378   /**
379    * is this an ssl daemon?
380    */
381   int is_ssl;
382
383 };
384
385
386 /* ***************** Datastructures for Socks handling **************** */
387
388
389 /**
390  * The socks phases.
391  */
392 enum SocksPhase
393 {
394   /**
395    * We're waiting to get the client hello.
396    */
397   SOCKS5_INIT,
398
399   /**
400    * We're waiting to get the initial request.
401    */
402   SOCKS5_REQUEST,
403
404   /**
405    * We are currently resolving the destination.
406    */
407   SOCKS5_RESOLVING,
408
409   /**
410    * We're in transfer mode.
411    */
412   SOCKS5_DATA_TRANSFER,
413
414   /**
415    * Finish writing the write buffer, then clean up.
416    */
417   SOCKS5_WRITE_THEN_CLEANUP,
418
419   /**
420    * Socket has been passed to MHD, do not close it anymore.
421    */
422   SOCKS5_SOCKET_WITH_MHD,
423
424   /**
425    * We've started receiving upload data from MHD.
426    */
427   SOCKS5_SOCKET_UPLOAD_STARTED,
428
429   /**
430    * We've finished receiving upload data from MHD.
431    */
432   SOCKS5_SOCKET_UPLOAD_DONE,
433
434   /**
435    * We've finished uploading data via CURL and can now download.
436    */
437   SOCKS5_SOCKET_DOWNLOAD_STARTED,
438
439   /**
440    * We've finished receiving download data from cURL.
441    */
442   SOCKS5_SOCKET_DOWNLOAD_DONE
443 };
444
445
446 /**
447  * A header list
448  */
449 struct HttpResponseHeader
450 {
451   /**
452    * DLL
453    */
454   struct HttpResponseHeader *next;
455
456   /**
457    * DLL
458    */
459   struct HttpResponseHeader *prev;
460
461   /**
462    * Header type
463    */
464   char *type;
465
466   /**
467    * Header value
468    */
469   char *value;
470 };
471
472 /**
473  * A structure for socks requests
474  */
475 struct Socks5Request
476 {
477
478   /**
479    * DLL.
480    */
481   struct Socks5Request *next;
482
483   /**
484    * DLL.
485    */
486   struct Socks5Request *prev;
487
488   /**
489    * The client socket
490    */
491   struct GNUNET_NETWORK_Handle *sock;
492
493   /**
494    * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
495    */
496   struct GNUNET_GNS_LookupWithTldRequest *gns_lookup;
497
498   /**
499    * Client socket read task
500    */
501   struct GNUNET_SCHEDULER_Task *rtask;
502
503   /**
504    * Client socket write task
505    */
506   struct GNUNET_SCHEDULER_Task *wtask;
507
508   /**
509    * Timeout task
510    */
511   struct GNUNET_SCHEDULER_Task *timeout_task;
512
513   /**
514    * Read buffer
515    */
516   char rbuf[SOCKS_BUFFERSIZE];
517
518   /**
519    * Write buffer
520    */
521   char wbuf[SOCKS_BUFFERSIZE];
522
523   /**
524    * Buffer we use for moving data between MHD and curl (in both directions).
525    */
526   char io_buf[IO_BUFFERSIZE];
527
528   /**
529    * MHD HTTP instance handling this request, NULL for none.
530    */
531   struct MhdHttpList *hd;
532
533   /**
534    * MHD connection for this request.
535    */
536   struct MHD_Connection *con;
537
538   /**
539    * MHD response object for this request.
540    */
541   struct MHD_Response *response;
542
543   /**
544    * the domain name to server (only important for TLS)
545    */
546   char *domain;
547
548   /**
549    * DNS Legacy Host Name as given by GNS, NULL if not given.
550    */
551   char *leho;
552
553   /**
554    * Payload of the DANE records encountered.
555    */
556   char *dane_data[MAX_DANES + 1];
557
558   /**
559    * The URL to fetch
560    */
561   char *url;
562
563   /**
564    * Handle to cURL
565    */
566   CURL *curl;
567
568   /**
569    * HTTP request headers for the curl request.
570    */
571   struct curl_slist *headers;
572
573   /**
574    * DNS->IP mappings resolved through GNS
575    */
576   struct curl_slist *hosts;
577
578   /**
579    * HTTP response code to give to MHD for the response.
580    */
581   unsigned int response_code;
582
583   /**
584    * Number of bytes in @e dane_data.
585    */
586   int dane_data_len[MAX_DANES + 1];
587
588   /**
589    * Number of entries used in @e dane_data_len
590    * and @e dane_data.
591    */
592   unsigned int num_danes;
593
594   /**
595    * Number of bytes already in read buffer
596    */
597   size_t rbuf_len;
598
599   /**
600    * Number of bytes already in write buffer
601    */
602   size_t wbuf_len;
603
604   /**
605    * Number of bytes already in the IO buffer.
606    */
607   size_t io_len;
608
609   /**
610    * Once known, what's the target address for the connection?
611    */
612   struct sockaddr_storage destination_address;
613
614   /**
615    * The socks state
616    */
617   enum SocksPhase state;
618
619   /**
620    * Desired destination port.
621    */
622   uint16_t port;
623
624   /**
625    * Headers from response
626    */
627   struct HttpResponseHeader *header_head;
628
629   /**
630    * Headers from response
631    */
632   struct HttpResponseHeader *header_tail;
633
634   /**
635    * X.509 Certificate status
636    */
637   int ssl_checked;
638
639   /**
640    * Was the hostname resolved via GNS?
641    */
642   int is_gns;
643
644   /**
645    * This is (probably) a TLS connection
646    */
647   int is_tls;
648
649   /**
650    * Did we suspend MHD processing?
651    */
652   int suspended;
653
654   /**
655    * Did we pause CURL processing?
656    */
657   int curl_paused;
658 };
659
660
661
662 /* *********************** Globals **************************** */
663
664
665 /**
666  * The port the proxy is running on (default 7777)
667  */
668 static uint16_t port = GNUNET_GNS_PROXY_PORT;
669
670 /**
671  * The CA file (pem) to use for the proxy CA
672  */
673 static char *cafile_opt;
674
675 /**
676  * The listen socket of the proxy for IPv4
677  */
678 static struct GNUNET_NETWORK_Handle *lsock4;
679
680 /**
681  * The listen socket of the proxy for IPv6
682  */
683 static struct GNUNET_NETWORK_Handle *lsock6;
684
685 /**
686  * The listen task ID for IPv4
687  */
688 static struct GNUNET_SCHEDULER_Task * ltask4;
689
690 /**
691  * The listen task ID for IPv6
692  */
693 static struct GNUNET_SCHEDULER_Task * ltask6;
694
695 /**
696  * The cURL download task (curl multi API).
697  */
698 static struct GNUNET_SCHEDULER_Task * curl_download_task;
699
700 /**
701  * The cURL multi handle
702  */
703 static CURLM *curl_multi;
704
705 /**
706  * Handle to the GNS service
707  */
708 static struct GNUNET_GNS_Handle *gns_handle;
709
710 /**
711  * Disable IPv6.
712  */
713 static int disable_v6;
714
715 /**
716  * DLL for http/https daemons
717  */
718 static struct MhdHttpList *mhd_httpd_head;
719
720 /**
721  * DLL for http/https daemons
722  */
723 static struct MhdHttpList *mhd_httpd_tail;
724
725 /**
726  * Daemon for HTTP (we have one per X.509 certificate, and then one for
727  * all HTTP connections; this is the one for HTTP, not HTTPS).
728  */
729 static struct MhdHttpList *httpd;
730
731 /**
732  * DLL of active socks requests.
733  */
734 static struct Socks5Request *s5r_head;
735
736 /**
737  * DLL of active socks requests.
738  */
739 static struct Socks5Request *s5r_tail;
740
741 /**
742  * The CA for X.509 certificate generation
743  */
744 static struct ProxyCA proxy_ca;
745
746 /**
747  * Response we return on cURL failures.
748  */
749 static struct MHD_Response *curl_failure_response;
750
751 /**
752  * Our configuration.
753  */
754 static const struct GNUNET_CONFIGURATION_Handle *cfg;
755
756
757 /* ************************* Global helpers ********************* */
758
759
760 /**
761  * Run MHD now, we have extra data ready for the callback.
762  *
763  * @param hd the daemon to run now.
764  */
765 static void
766 run_mhd_now (struct MhdHttpList *hd);
767
768
769 /**
770  * Clean up s5r handles.
771  *
772  * @param s5r the handle to destroy
773  */
774 static void
775 cleanup_s5r (struct Socks5Request *s5r)
776 {
777   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
778               "Cleaning up socks request\n");
779   if (NULL != s5r->curl)
780   {
781     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
782                 "Cleaning up cURL handle\n");
783     curl_multi_remove_handle (curl_multi,
784                               s5r->curl);
785     curl_easy_cleanup (s5r->curl);
786     s5r->curl = NULL;
787   }
788   if (s5r->suspended)
789   {
790     s5r->suspended = GNUNET_NO;
791     MHD_resume_connection (s5r->con);
792   }
793   curl_slist_free_all (s5r->headers);
794   if (NULL != s5r->hosts)
795   {
796     curl_slist_free_all (s5r->hosts);
797   }
798   if ( (NULL != s5r->response) &&
799        (curl_failure_response != s5r->response) )
800   {
801     MHD_destroy_response (s5r->response);
802     s5r->response = NULL;
803   }
804   if (NULL != s5r->rtask)
805   {
806     GNUNET_SCHEDULER_cancel (s5r->rtask);
807     s5r->rtask = NULL;
808   }
809   if (NULL != s5r->timeout_task)
810   {
811     GNUNET_SCHEDULER_cancel (s5r->timeout_task);
812     s5r->timeout_task = NULL;
813   }
814   if (NULL != s5r->wtask)
815   {
816     GNUNET_SCHEDULER_cancel (s5r->wtask);
817     s5r->wtask = NULL;
818   }
819   if (NULL != s5r->gns_lookup)
820   {
821     GNUNET_GNS_lookup_with_tld_cancel (s5r->gns_lookup);
822     s5r->gns_lookup = NULL;
823   }
824   if (NULL != s5r->sock)
825   {
826     if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
827       GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
828     else
829       GNUNET_NETWORK_socket_close (s5r->sock);
830     s5r->sock = NULL;
831   }
832   GNUNET_CONTAINER_DLL_remove (s5r_head,
833                                s5r_tail,
834                                s5r);
835   GNUNET_free_non_null (s5r->domain);
836   GNUNET_free_non_null (s5r->leho);
837   GNUNET_free_non_null (s5r->url);
838   for (unsigned int i=0;i<s5r->num_danes;i++)
839     GNUNET_free (s5r->dane_data[i]);
840   GNUNET_free (s5r);
841 }
842
843
844 /* ************************* HTTP handling with cURL *********************** */
845
846 static void
847 curl_download_prepare ();
848
849
850 /**
851  * Callback for MHD response generation.  This function is called from
852  * MHD whenever MHD expects to get data back.  Copies data from the
853  * io_buf, if available.
854  *
855  * @param cls closure with our `struct Socks5Request`
856  * @param pos in buffer
857  * @param buf where to copy data
858  * @param max available space in @a buf
859  * @return number of bytes written to @a buf
860  */
861 static ssize_t
862 mhd_content_cb (void *cls,
863                 uint64_t pos,
864                 char* buf,
865                 size_t max)
866 {
867   struct Socks5Request *s5r = cls;
868   size_t bytes_to_copy;
869
870   if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
871        (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
872   {
873     /* we're still not done with the upload, do not yet
874        start the download, the IO buffer is still full
875        with upload data. */
876     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
877                 "Pausing MHD download %s%s, not yet ready for download\n",
878                 s5r->domain,
879                 s5r->url);
880     return 0; /* not yet ready for data download */
881   }
882   bytes_to_copy = GNUNET_MIN (max,
883                               s5r->io_len);
884   if ( (0 == bytes_to_copy) &&
885        (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
886   {
887     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
888                 "Pausing MHD download %s%s, no data available\n",
889                 s5r->domain,
890                 s5r->url);
891     if (NULL != s5r->curl)
892     {
893       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
894                   "Continuing CURL interaction for %s%s\n",
895                   s5r->domain,
896                   s5r->url);
897       if (GNUNET_YES == s5r->curl_paused)
898       {
899         s5r->curl_paused = GNUNET_NO;
900         curl_easy_pause (s5r->curl,
901                          CURLPAUSE_CONT);
902       }
903       curl_download_prepare ();
904     }
905     if (GNUNET_NO == s5r->suspended)
906     {
907       MHD_suspend_connection (s5r->con);
908       s5r->suspended = GNUNET_YES;
909     }
910     return 0; /* more data later */
911   }
912   if ( (0 == bytes_to_copy) &&
913        (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
914   {
915     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
916                 "Completed MHD download %s%s\n",
917                 s5r->domain,
918                 s5r->url);
919     return MHD_CONTENT_READER_END_OF_STREAM;
920   }
921   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
922               "Writing %llu/%llu bytes to %s%s\n",
923               (unsigned long long) bytes_to_copy,
924               (unsigned long long) s5r->io_len,
925               s5r->domain,
926               s5r->url);
927   GNUNET_memcpy (buf,
928                  s5r->io_buf,
929                  bytes_to_copy);
930   memmove (s5r->io_buf,
931            &s5r->io_buf[bytes_to_copy],
932            s5r->io_len - bytes_to_copy);
933   s5r->io_len -= bytes_to_copy;
934   if ( (NULL != s5r->curl) &&
935        (GNUNET_YES == s5r->curl_paused) )
936   {
937     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938                 "Continuing CURL interaction for %s%s\n",
939                 s5r->domain,
940                 s5r->url);
941     s5r->curl_paused = GNUNET_NO;
942     curl_easy_pause (s5r->curl,
943                      CURLPAUSE_CONT);
944   }
945   return bytes_to_copy;
946 }
947
948
949 /**
950  * Check that the website has presented us with a valid X.509 certificate.
951  * The certificate must either match the domain name or the LEHO name
952  * (or, if available, the TLSA record).
953  *
954  * @param s5r request to check for.
955  * @return #GNUNET_OK if the certificate is valid
956  */
957 static int
958 check_ssl_certificate (struct Socks5Request *s5r)
959 {
960   unsigned int cert_list_size;
961   const gnutls_datum_t *chainp;
962   const struct curl_tlssessioninfo *tlsinfo;
963   char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
964   size_t size;
965   gnutls_x509_crt_t x509_cert;
966   int rc;
967   const char *name;
968
969   s5r->ssl_checked = GNUNET_YES;
970   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
971               "Checking X.509 certificate\n");
972   if (CURLE_OK !=
973       curl_easy_getinfo (s5r->curl,
974                          CURLINFO_TLS_SESSION,
975                          (struct curl_slist **) &tlsinfo))
976     return GNUNET_SYSERR;
977   if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
978   {
979     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
980                 _("Unsupported CURL TLS backend %d\n"),
981                 tlsinfo->backend);
982     return GNUNET_SYSERR;
983   }
984   chainp = gnutls_certificate_get_peers (tlsinfo->internals,
985                                          &cert_list_size);
986   if ( (! chainp) ||
987        (0 == cert_list_size) )
988     return GNUNET_SYSERR;
989
990   size = sizeof (certdn);
991   /* initialize an X.509 certificate structure. */
992   gnutls_x509_crt_init (&x509_cert);
993   gnutls_x509_crt_import (x509_cert,
994                           chainp,
995                           GNUTLS_X509_FMT_DER);
996
997   if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
998                                                 GNUTLS_OID_X520_COMMON_NAME,
999                                                 0, /* the first and only one */
1000                                                 0 /* no DER encoding */,
1001                                                 certdn,
1002                                                 &size)))
1003   {
1004     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1005                 _("Failed to fetch CN from cert: %s\n"),
1006                 gnutls_strerror(rc));
1007     gnutls_x509_crt_deinit (x509_cert);
1008     return GNUNET_SYSERR;
1009   }
1010   /* check for TLSA/DANE records */
1011 #if HAVE_GNUTLS_DANE
1012   if (0 != s5r->num_danes)
1013   {
1014     dane_state_t dane_state;
1015     dane_query_t dane_query;
1016     unsigned int verify;
1017
1018     /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
1019     if (0 != (rc = dane_state_init (&dane_state,
1020 #ifdef DANE_F_IGNORE_DNSSEC
1021                                     DANE_F_IGNORE_DNSSEC |
1022 #endif
1023                                     DANE_F_IGNORE_LOCAL_RESOLVER)))
1024     {
1025       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1026                   _("Failed to initialize DANE: %s\n"),
1027                   dane_strerror(rc));
1028       gnutls_x509_crt_deinit (x509_cert);
1029       return GNUNET_SYSERR;
1030     }
1031     s5r->dane_data[s5r->num_danes] = NULL;
1032     s5r->dane_data_len[s5r->num_danes] = 0;
1033     if (0 != (rc = dane_raw_tlsa (dane_state,
1034                                   &dane_query,
1035                                   s5r->dane_data,
1036                                   s5r->dane_data_len,
1037                                   GNUNET_YES,
1038                                   GNUNET_NO)))
1039     {
1040       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1041                   _("Failed to parse DANE record: %s\n"),
1042                   dane_strerror(rc));
1043       dane_state_deinit (dane_state);
1044       gnutls_x509_crt_deinit (x509_cert);
1045       return GNUNET_SYSERR;
1046     }
1047     if (0 != (rc = dane_verify_crt_raw (dane_state,
1048                                         chainp,
1049                                         cert_list_size,
1050                                         gnutls_certificate_type_get (tlsinfo->internals),
1051                                         dane_query,
1052                                         0, 0,
1053                                         &verify)))
1054     {
1055       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1056                   _("Failed to verify TLS connection using DANE: %s\n"),
1057                   dane_strerror(rc));
1058       dane_query_deinit (dane_query);
1059       dane_state_deinit (dane_state);
1060       gnutls_x509_crt_deinit (x509_cert);
1061       return GNUNET_SYSERR;
1062     }
1063     if (0 != verify)
1064     {
1065       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1066                   _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
1067                   verify);
1068       dane_query_deinit (dane_query);
1069       dane_state_deinit (dane_state);
1070       gnutls_x509_crt_deinit (x509_cert);
1071       return GNUNET_SYSERR;
1072     }
1073     dane_query_deinit (dane_query);
1074     dane_state_deinit (dane_state);
1075     /* success! */
1076   }
1077   else
1078 #endif
1079   {
1080     /* try LEHO or ordinary domain name X509 verification */
1081     name = s5r->domain;
1082     if (NULL != s5r->leho)
1083       name = s5r->leho;
1084     if (NULL != name)
1085     {
1086       if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
1087                                                      name)))
1088       {
1089         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1090                     _("TLS certificate subject name (%s) does not match `%s': %d\n"),
1091                     certdn,
1092                     name,
1093                     rc);
1094         gnutls_x509_crt_deinit (x509_cert);
1095         return GNUNET_SYSERR;
1096       }
1097     }
1098     else
1099     {
1100       /* we did not even have the domain name!? */
1101       GNUNET_break (0);
1102       return GNUNET_SYSERR;
1103     }
1104   }
1105   gnutls_x509_crt_deinit (x509_cert);
1106   return GNUNET_OK;
1107 }
1108
1109
1110 /**
1111  * We're getting an HTTP response header from cURL.  Convert it to the
1112  * MHD response headers.  Mostly copies the headers, but makes special
1113  * adjustments to "Set-Cookie" and "Location" headers as those may need
1114  * to be changed from the LEHO to the domain the browser expects.
1115  *
1116  * @param buffer curl buffer with a single line of header data; not 0-terminated!
1117  * @param size curl blocksize
1118  * @param nmemb curl blocknumber
1119  * @param cls our `struct Socks5Request *`
1120  * @return size of processed bytes
1121  */
1122 static size_t
1123 curl_check_hdr (void *buffer,
1124                 size_t size,
1125                 size_t nmemb,
1126                 void *cls)
1127 {
1128   struct Socks5Request *s5r = cls;
1129   struct HttpResponseHeader *header;
1130   size_t bytes = size * nmemb;
1131   char *ndup;
1132   const char *hdr_type;
1133   const char *cookie_domain;
1134   char *hdr_val;
1135   char *new_cookie_hdr;
1136   char *new_location;
1137   size_t offset;
1138   size_t delta_cdomain;
1139   int domain_matched;
1140   char *tok;
1141
1142   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1143               "Receiving HTTP response header from CURL\n");
1144   /* first, check TLS certificate */
1145   if ( (GNUNET_YES != s5r->ssl_checked) &&
1146        (GNUNET_YES == s5r->is_tls))
1147        //(HTTPS_PORT == s5r->port))
1148   {
1149     if (GNUNET_OK != check_ssl_certificate (s5r))
1150       return 0;
1151   }
1152   ndup = GNUNET_strndup (buffer,
1153                          bytes);
1154   hdr_type = strtok (ndup,
1155                      ":");
1156   if (NULL == hdr_type)
1157   {
1158     GNUNET_free (ndup);
1159     return bytes;
1160   }
1161   hdr_val = strtok (NULL,
1162                     "");
1163   if (NULL == hdr_val)
1164   {
1165     GNUNET_free (ndup);
1166     return bytes;
1167   }
1168   if (' ' == *hdr_val)
1169     hdr_val++;
1170
1171   /* custom logic for certain header types */
1172   new_cookie_hdr = NULL;
1173   if ( (NULL != s5r->leho) &&
1174        (0 == strcasecmp (hdr_type,
1175                          MHD_HTTP_HEADER_SET_COOKIE)) )
1176
1177   {
1178     new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1179                                     strlen (s5r->domain) + 1);
1180     offset = 0;
1181     domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1182     for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1183     {
1184       if ( (0 == strncasecmp (tok,
1185                               " domain",
1186                               strlen (" domain"))) &&
1187            (GNUNET_NO == domain_matched) )
1188       {
1189         domain_matched = GNUNET_YES;
1190         cookie_domain = tok + strlen (" domain") + 1;
1191         if (strlen (cookie_domain) < strlen (s5r->leho))
1192         {
1193           delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1194           if (0 == strcasecmp (cookie_domain,
1195                                s5r->leho + delta_cdomain))
1196           {
1197             offset += sprintf (new_cookie_hdr + offset,
1198                                " domain=%s;",
1199                                s5r->domain);
1200             continue;
1201           }
1202         }
1203         else if (0 == strcmp (cookie_domain,
1204                               s5r->leho))
1205         {
1206           offset += sprintf (new_cookie_hdr + offset,
1207                              " domain=%s;",
1208                              s5r->domain);
1209           continue;
1210         }
1211         else if ( ('.' == cookie_domain[0]) &&
1212                   (0 == strcmp (&cookie_domain[1],
1213                                 s5r->leho)) )
1214         {
1215           offset += sprintf (new_cookie_hdr + offset,
1216                              " domain=.%s;",
1217                              s5r->domain);
1218           continue;
1219         }
1220         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1221                     _("Cookie domain `%s' supplied by server is invalid\n"),
1222                     tok);
1223       }
1224       GNUNET_memcpy (new_cookie_hdr + offset,
1225                      tok,
1226                      strlen (tok));
1227       offset += strlen (tok);
1228       new_cookie_hdr[offset++] = ';';
1229     }
1230     hdr_val = new_cookie_hdr;
1231   }
1232
1233   new_location = NULL;
1234   if (0 == strcasecmp (MHD_HTTP_HEADER_TRANSFER_ENCODING,
1235                        hdr_type))
1236   {
1237     /* Ignore transfer encoding, set automatically by MHD if required */
1238     goto cleanup;
1239   }
1240   if ((0 == strcasecmp (MHD_HTTP_HEADER_LOCATION,
1241                        hdr_type)))
1242   {
1243     char *leho_host;
1244
1245     GNUNET_asprintf (&leho_host,
1246                      (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1247                      ? "http://%s"
1248                      : "https://%s",
1249                      s5r->leho);
1250     if (0 == strncmp (leho_host,
1251                       hdr_val,
1252                       strlen (leho_host)))
1253     {
1254       GNUNET_asprintf (&new_location,
1255                        "%s%s%s",
1256                        (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1257                        ? "http://"
1258                        : "https://",
1259                        s5r->domain,
1260                        hdr_val + strlen (leho_host));
1261       hdr_val = new_location;
1262     }
1263     GNUNET_free (leho_host);
1264   }
1265   if (0 == strcasecmp (MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1266        hdr_type))
1267   {
1268     char *leho_host;
1269
1270     GNUNET_asprintf (&leho_host,
1271                      (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1272                      ? "http://%s"
1273                      : "https://%s",
1274                      s5r->leho);
1275     if (0 == strncmp (leho_host,
1276                       hdr_val,
1277                       strlen (leho_host)))
1278     {
1279       GNUNET_asprintf (&new_location,
1280                        "%s%s",
1281                        (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1282                        ? "http://"
1283                        : "https://",
1284                        s5r->domain);
1285       hdr_val = new_location;
1286     }
1287     GNUNET_free (leho_host);
1288   }
1289
1290   /* MHD does not allow certain characters in values, remove those */
1291   if (NULL != (tok = strchr (hdr_val, '\n')))
1292     *tok = '\0';
1293   if (NULL != (tok = strchr (hdr_val, '\r')))
1294     *tok = '\0';
1295   if (NULL != (tok = strchr (hdr_val, '\t')))
1296     *tok = '\0';
1297   if (0 != strlen (hdr_val)) /* Rely in MHD to set those */
1298   {
1299     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1300                 "Adding header %s: %s to MHD response\n",
1301                 hdr_type,
1302                 hdr_val);
1303     header = GNUNET_new (struct HttpResponseHeader);
1304     header->type = GNUNET_strdup (hdr_type);
1305     header->value = GNUNET_strdup (hdr_val);
1306     GNUNET_CONTAINER_DLL_insert (s5r->header_head,
1307                                  s5r->header_tail,
1308                                  header);
1309   }
1310  cleanup:
1311   GNUNET_free (ndup);
1312   GNUNET_free_non_null (new_cookie_hdr);
1313   GNUNET_free_non_null (new_location);
1314   return bytes;
1315 }
1316
1317
1318 /**
1319  * Create an MHD response object in @a s5r matching the
1320  * information we got from curl.
1321  *
1322  * @param s5r the request for which we convert the response
1323  * @return #GNUNET_OK on success, #GNUNET_SYSERR if response was
1324  *         already initialized before
1325  */
1326 static int
1327 create_mhd_response_from_s5r (struct Socks5Request *s5r)
1328 {
1329   long resp_code;
1330   double content_length;
1331
1332   if (NULL != s5r->response)
1333   {
1334     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1335                 "Response already set!\n");
1336     return GNUNET_SYSERR;
1337   }
1338
1339   GNUNET_break (CURLE_OK ==
1340                 curl_easy_getinfo (s5r->curl,
1341                                    CURLINFO_RESPONSE_CODE,
1342                                    &resp_code));
1343   GNUNET_break (CURLE_OK ==
1344                 curl_easy_getinfo (s5r->curl,
1345                                    CURLINFO_CONTENT_LENGTH_DOWNLOAD,
1346                                    &content_length));
1347   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1348               "Creating MHD response with code %d and size %d for %s%s\n",
1349               (int) resp_code,
1350               (int) content_length,
1351               s5r->domain,
1352               s5r->url);
1353   s5r->response_code = resp_code;
1354   s5r->response = MHD_create_response_from_callback ((-1 == content_length)
1355                                                      ? MHD_SIZE_UNKNOWN
1356                                                      : content_length,
1357                                                      IO_BUFFERSIZE,
1358                                                      &mhd_content_cb,
1359                                                      s5r,
1360                                                      NULL);
1361   for (struct HttpResponseHeader *header = s5r->header_head;
1362        NULL != header;
1363        header = header->next)
1364   {
1365     if (0 == strcasecmp (header->type,
1366                          MHD_HTTP_HEADER_CONTENT_LENGTH))
1367       continue; /* MHD won't let us mess with those, for good reason */
1368     if ( (0 == strcasecmp (header->type,
1369                            MHD_HTTP_HEADER_TRANSFER_ENCODING)) &&
1370          ( (0 == strcasecmp (header->value,
1371                              "identity")) ||
1372            (0 == strcasecmp (header->value,
1373                              "chunked")) ) )
1374       continue; /* MHD won't let us mess with those, for good reason */
1375     if (MHD_YES !=
1376         MHD_add_response_header (s5r->response,
1377                                  header->type,
1378                                  header->value))
1379     {
1380       GNUNET_break (0);
1381       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1382                   "Failed to add header `%s:%s'\n",
1383                   header->type,
1384                   header->value);
1385     }
1386   }
1387   /* force connection to be closed after each request, as we
1388      do not support HTTP pipelining (yet, FIXME!) */
1389   /*GNUNET_break (MHD_YES ==
1390     MHD_add_response_header (s5r->response,
1391     MHD_HTTP_HEADER_CONNECTION,
1392     "close"));*/
1393   MHD_resume_connection (s5r->con);
1394   s5r->suspended = GNUNET_NO;
1395   return GNUNET_OK;
1396 }
1397
1398
1399 /**
1400  * Handle response payload data from cURL.  Copies it into our `io_buf` to make
1401  * it available to MHD.
1402  *
1403  * @param ptr pointer to the data
1404  * @param size number of blocks of data
1405  * @param nmemb blocksize
1406  * @param ctx our `struct Socks5Request *`
1407  * @return number of bytes handled
1408  */
1409 static size_t
1410 curl_download_cb (void *ptr,
1411                   size_t size,
1412                   size_t nmemb,
1413                   void* ctx)
1414 {
1415   struct Socks5Request *s5r = ctx;
1416   size_t total = size * nmemb;
1417
1418   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1419               "Receiving %ux%u bytes for `%s%s' from cURL to download\n",
1420               (unsigned int) size,
1421               (unsigned int) nmemb,
1422               s5r->domain,
1423               s5r->url);
1424   if (NULL == s5r->response)
1425     GNUNET_assert (GNUNET_OK ==
1426                    create_mhd_response_from_s5r (s5r));
1427   if ( (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) &&
1428        (0 == s5r->io_len))
1429   {
1430     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1431                 "Previous upload finished... starting DOWNLOAD.\n");
1432     s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1433   }
1434   if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1435        (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1436   {
1437     /* we're still not done with the upload, do not yet
1438        start the download, the IO buffer is still full
1439        with upload data. */
1440     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1441                 "Pausing CURL download `%s%s', waiting for UPLOAD to finish\n",
1442                 s5r->domain,
1443                 s5r->url);
1444     s5r->curl_paused = GNUNET_YES;
1445     return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1446   }
1447   if (sizeof (s5r->io_buf) - s5r->io_len < total)
1448   {
1449     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450                 "Pausing CURL `%s%s' download, not enough space %llu %llu %llu\n",
1451                 s5r->domain,
1452                 s5r->url,
1453                 (unsigned long long) sizeof (s5r->io_buf),
1454                 (unsigned long long) s5r->io_len,
1455                 (unsigned long long) total);
1456     s5r->curl_paused = GNUNET_YES;
1457     return CURL_WRITEFUNC_PAUSE; /* not enough space */
1458   }
1459   GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1460                  ptr,
1461                  total);
1462   s5r->io_len += total;
1463   if (GNUNET_YES == s5r->suspended)
1464   {
1465     MHD_resume_connection (s5r->con);
1466     s5r->suspended = GNUNET_NO;
1467   }
1468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1469               "Received %llu bytes of payload via cURL from %s\n",
1470               (unsigned long long) total,
1471               s5r->domain);
1472   if (s5r->io_len == total)
1473     run_mhd_now (s5r->hd);
1474   return total;
1475 }
1476
1477
1478 /**
1479  * cURL callback for uploaded (PUT/POST) data.  Copies it into our `io_buf`
1480  * to make it available to MHD.
1481  *
1482  * @param buf where to write the data
1483  * @param size number of bytes per member
1484  * @param nmemb number of members available in @a buf
1485  * @param cls our `struct Socks5Request` that generated the data
1486  * @return number of bytes copied to @a buf
1487  */
1488 static size_t
1489 curl_upload_cb (void *buf,
1490                 size_t size,
1491                 size_t nmemb,
1492                 void *cls)
1493 {
1494   struct Socks5Request *s5r = cls;
1495   size_t len = size * nmemb;
1496   size_t to_copy;
1497
1498   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1499               "Receiving %ux%u bytes for `%s%s' from cURL to upload\n",
1500               (unsigned int) size,
1501               (unsigned int) nmemb,
1502               s5r->domain,
1503               s5r->url);
1504
1505   if ( (0 == s5r->io_len) &&
1506        (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1507   {
1508     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1509                 "Pausing CURL UPLOAD %s%s, need more data\n",
1510                 s5r->domain,
1511                 s5r->url);
1512     return CURL_READFUNC_PAUSE;
1513   }
1514   if ( (0 == s5r->io_len) &&
1515        (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1516   {
1517     s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1518     if (GNUNET_YES == s5r->curl_paused)
1519     {
1520       s5r->curl_paused = GNUNET_NO;
1521       curl_easy_pause (s5r->curl,
1522                        CURLPAUSE_CONT);
1523     }
1524     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1525                 "Completed CURL UPLOAD %s%s\n",
1526                 s5r->domain,
1527                 s5r->url);
1528     return 0; /* upload finished, can now download */
1529   }
1530   if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
1531        (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1532   {
1533     GNUNET_break (0);
1534     return CURL_READFUNC_ABORT;
1535   }
1536   to_copy = GNUNET_MIN (s5r->io_len,
1537                         len);
1538   GNUNET_memcpy (buf,
1539                  s5r->io_buf,
1540                  to_copy);
1541   memmove (s5r->io_buf,
1542            &s5r->io_buf[to_copy],
1543            s5r->io_len - to_copy);
1544   s5r->io_len -= to_copy;
1545   if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1546     run_mhd_now (s5r->hd); /* got more space for upload now */
1547   return to_copy;
1548 }
1549
1550
1551 /* ************************** main loop of cURL interaction ****************** */
1552
1553
1554 /**
1555  * Task that is run when we are ready to receive more data
1556  * from curl
1557  *
1558  * @param cls closure
1559  */
1560 static void
1561 curl_task_download (void *cls);
1562
1563
1564 /**
1565  * Ask cURL for the select() sets and schedule cURL operations.
1566  */
1567 static void
1568 curl_download_prepare ()
1569 {
1570   CURLMcode mret;
1571   fd_set rs;
1572   fd_set ws;
1573   fd_set es;
1574   int max;
1575   struct GNUNET_NETWORK_FDSet *grs;
1576   struct GNUNET_NETWORK_FDSet *gws;
1577   long to;
1578   struct GNUNET_TIME_Relative rtime;
1579
1580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581               "Scheduling CURL interaction\n");
1582   if (NULL != curl_download_task)
1583   {
1584     GNUNET_SCHEDULER_cancel (curl_download_task);
1585     curl_download_task = NULL;
1586   }
1587   max = -1;
1588   FD_ZERO (&rs);
1589   FD_ZERO (&ws);
1590   FD_ZERO (&es);
1591   if (CURLM_OK != (mret = curl_multi_fdset (curl_multi,
1592                                             &rs,
1593                                             &ws,
1594                                             &es,
1595                                             &max)))
1596   {
1597     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1598                 "%s failed at %s:%d: `%s'\n",
1599                 "curl_multi_fdset", __FILE__, __LINE__,
1600                 curl_multi_strerror (mret));
1601     return;
1602   }
1603   to = -1;
1604   GNUNET_break (CURLM_OK ==
1605                 curl_multi_timeout (curl_multi,
1606                                     &to));
1607   if (-1 == to)
1608     rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1609   else
1610     rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1611                                            to);
1612   if (-1 != max)
1613   {
1614     grs = GNUNET_NETWORK_fdset_create ();
1615     gws = GNUNET_NETWORK_fdset_create ();
1616     GNUNET_NETWORK_fdset_copy_native (grs,
1617                                       &rs,
1618                                       max + 1);
1619     GNUNET_NETWORK_fdset_copy_native (gws,
1620                                       &ws,
1621                                       max + 1);
1622     curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1623                                                       rtime,
1624                                                       grs,
1625                                                       gws,
1626                                                       &curl_task_download,
1627                                                       curl_multi);
1628     GNUNET_NETWORK_fdset_destroy (gws);
1629     GNUNET_NETWORK_fdset_destroy (grs);
1630   }
1631   else
1632   {
1633     curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1634                                                        &curl_task_download,
1635                                                        curl_multi);
1636   }
1637 }
1638
1639
1640 /**
1641  * Task that is run when we are ready to receive more data from curl.
1642  *
1643  * @param cls closure, NULL
1644  */
1645 static void
1646 curl_task_download (void *cls)
1647 {
1648   int running;
1649   int msgnum;
1650   struct CURLMsg *msg;
1651   CURLMcode mret;
1652   struct Socks5Request *s5r;
1653
1654   curl_download_task = NULL;
1655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1656               "Running CURL interaction\n");
1657   do
1658   {
1659     running = 0;
1660     mret = curl_multi_perform (curl_multi,
1661                                &running);
1662     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1663                 "Checking CURL multi status: %d\n",
1664                 mret);
1665     while (NULL != (msg = curl_multi_info_read (curl_multi,
1666                                                 &msgnum)))
1667     {
1668       GNUNET_break (CURLE_OK ==
1669                     curl_easy_getinfo (msg->easy_handle,
1670                                        CURLINFO_PRIVATE,
1671                                        (char **) &s5r ));
1672       if (NULL == s5r)
1673       {
1674         GNUNET_break (0);
1675         continue;
1676       }
1677       switch (msg->msg)
1678       {
1679         case CURLMSG_NONE:
1680           /* documentation says this is not used */
1681           GNUNET_break (0);
1682           break;
1683         case CURLMSG_DONE:
1684           switch (msg->data.result)
1685           {
1686             case CURLE_OK:
1687             case CURLE_GOT_NOTHING:
1688               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1689                           "CURL download %s%s completed.\n",
1690                           s5r->domain,
1691                           s5r->url);
1692               if (NULL == s5r->response)
1693               {
1694                 GNUNET_assert (GNUNET_OK ==
1695                                create_mhd_response_from_s5r (s5r));
1696               }
1697               s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1698               if (GNUNET_YES == s5r->suspended)
1699               {
1700                 MHD_resume_connection (s5r->con);
1701                 s5r->suspended = GNUNET_NO;
1702               }
1703               run_mhd_now (s5r->hd);
1704               break;
1705             default:
1706               GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1707                           "Download curl %s%s failed: %s\n",
1708                           s5r->domain,
1709                           s5r->url,
1710                           curl_easy_strerror (msg->data.result));
1711               /* FIXME: indicate error somehow? close MHD connection badly as well? */
1712               s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1713               if (GNUNET_YES == s5r->suspended)
1714               {
1715                 MHD_resume_connection (s5r->con);
1716                 s5r->suspended = GNUNET_NO;
1717               }
1718               run_mhd_now (s5r->hd);
1719               break;
1720           }
1721           if (NULL == s5r->response)
1722             s5r->response = curl_failure_response;
1723           break;
1724         case CURLMSG_LAST:
1725           /* documentation says this is not used */
1726           GNUNET_break (0);
1727           break;
1728         default:
1729           /* unexpected status code */
1730           GNUNET_break (0);
1731           break;
1732       }
1733     };
1734   } while (mret == CURLM_CALL_MULTI_PERFORM);
1735   if (CURLM_OK != mret)
1736     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1737                 "%s failed at %s:%d: `%s'\n",
1738                 "curl_multi_perform", __FILE__, __LINE__,
1739                 curl_multi_strerror (mret));
1740   if (0 == running)
1741   {
1742     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1743                 "Suspending cURL multi loop, no more events pending\n");
1744     if (NULL != curl_download_task)
1745     {
1746       GNUNET_SCHEDULER_cancel (curl_download_task);
1747       curl_download_task = NULL;
1748     }
1749     return; /* nothing more in progress */
1750   }
1751   curl_download_prepare ();
1752 }
1753
1754
1755 /* ********************************* MHD response generation ******************* */
1756
1757
1758 /**
1759  * Read HTTP request header field from the request.  Copies the fields
1760  * over to the 'headers' that will be given to curl.  However, 'Host'
1761  * is substituted with the LEHO if present.  We also change the
1762  * 'Connection' header value to "close" as the proxy does not support
1763  * pipelining.
1764  *
1765  * @param cls our `struct Socks5Request`
1766  * @param kind value kind
1767  * @param key field key
1768  * @param value field value
1769  * @return #MHD_YES to continue to iterate
1770  */
1771 static int
1772 con_val_iter (void *cls,
1773               enum MHD_ValueKind kind,
1774               const char *key,
1775               const char *value)
1776 {
1777   struct Socks5Request *s5r = cls;
1778   char *hdr;
1779
1780   if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST,
1781                          key)) &&
1782        (NULL != s5r->leho) )
1783     value = s5r->leho;
1784   GNUNET_asprintf (&hdr,
1785                    "%s: %s",
1786                    key,
1787                    value);
1788   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1789               "Adding HEADER `%s' to HTTP request\n",
1790               hdr);
1791   s5r->headers = curl_slist_append (s5r->headers,
1792                                     hdr);
1793   GNUNET_free (hdr);
1794   return MHD_YES;
1795 }
1796
1797
1798 /**
1799  * Main MHD callback for handling requests.
1800  *
1801  * @param cls unused
1802  * @param con MHD connection handle
1803  * @param url the url in the request
1804  * @param meth the HTTP method used ("GET", "PUT", etc.)
1805  * @param ver the HTTP version string (i.e. "HTTP/1.1")
1806  * @param upload_data the data being uploaded (excluding HEADERS,
1807  *        for a POST that fits into memory and that is encoded
1808  *        with a supported encoding, the POST data will NOT be
1809  *        given in upload_data and is instead available as
1810  *        part of MHD_get_connection_values; very large POST
1811  *        data *will* be made available incrementally in
1812  *        upload_data)
1813  * @param upload_data_size set initially to the size of the
1814  *        @a upload_data provided; the method must update this
1815  *        value to the number of bytes NOT processed;
1816  * @param con_cls pointer to location where we store the `struct Request`
1817  * @return #MHD_YES if the connection was handled successfully,
1818  *         #MHD_NO if the socket must be closed due to a serious
1819  *         error while handling the request
1820  */
1821 static int
1822 create_response (void *cls,
1823                  struct MHD_Connection *con,
1824                  const char *url,
1825                  const char *meth,
1826                  const char *ver,
1827                  const char *upload_data,
1828                  size_t *upload_data_size,
1829                  void **con_cls)
1830 {
1831   struct Socks5Request *s5r = *con_cls;
1832   char *curlurl;
1833   char ipstring[INET6_ADDRSTRLEN];
1834   char ipaddr[INET6_ADDRSTRLEN + 2];
1835   const struct sockaddr *sa;
1836   const struct sockaddr_in *s4;
1837   const struct sockaddr_in6 *s6;
1838   uint16_t port;
1839   size_t left;
1840
1841   if (NULL == s5r)
1842   {
1843     GNUNET_break (0);
1844     return MHD_NO;
1845   }
1846   s5r->con = con;
1847   /* Fresh connection. */
1848   if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
1849   {
1850     /* first time here, initialize curl handle */
1851     if (s5r->is_gns)
1852     {
1853       sa = (const struct sockaddr *) &s5r->destination_address;
1854       switch (sa->sa_family)
1855       {
1856       case AF_INET:
1857         s4 = (const struct sockaddr_in *) &s5r->destination_address;
1858         if (NULL == inet_ntop (AF_INET,
1859                                &s4->sin_addr,
1860                                ipstring,
1861                                sizeof (ipstring)))
1862         {
1863           GNUNET_break (0);
1864           return MHD_NO;
1865         }
1866         GNUNET_snprintf (ipaddr,
1867                          sizeof (ipaddr),
1868                          "%s",
1869                          ipstring);
1870         port = ntohs (s4->sin_port);
1871         break;
1872       case AF_INET6:
1873         s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1874         if (NULL == inet_ntop (AF_INET6,
1875                                &s6->sin6_addr,
1876                                ipstring,
1877                                sizeof (ipstring)))
1878         {
1879           GNUNET_break (0);
1880           return MHD_NO;
1881         }
1882         GNUNET_snprintf (ipaddr,
1883                          sizeof (ipaddr),
1884                          "%s",
1885                          ipstring);
1886         port = ntohs (s6->sin6_port);
1887         break;
1888       default:
1889         GNUNET_break (0);
1890         return MHD_NO;
1891       }
1892     }
1893     else
1894     {
1895       port = s5r->port;
1896     }
1897     if (NULL == s5r->curl)
1898       s5r->curl = curl_easy_init ();
1899     if (NULL == s5r->curl)
1900       return MHD_queue_response (con,
1901                                  MHD_HTTP_INTERNAL_SERVER_ERROR,
1902                                  curl_failure_response);
1903     curl_easy_setopt (s5r->curl,
1904                       CURLOPT_HEADERFUNCTION,
1905                       &curl_check_hdr);
1906     curl_easy_setopt (s5r->curl,
1907                       CURLOPT_HEADERDATA,
1908                       s5r);
1909     curl_easy_setopt (s5r->curl,
1910                       CURLOPT_FOLLOWLOCATION,
1911                       0);
1912     if (s5r->is_gns)
1913       curl_easy_setopt (s5r->curl,
1914                         CURLOPT_IPRESOLVE,
1915                         CURL_IPRESOLVE_V4);
1916     curl_easy_setopt (s5r->curl,
1917                       CURLOPT_CONNECTTIMEOUT,
1918                       600L);
1919     curl_easy_setopt (s5r->curl,
1920                       CURLOPT_TIMEOUT,
1921                       600L);
1922     curl_easy_setopt (s5r->curl,
1923                       CURLOPT_NOSIGNAL,
1924                       1L);
1925     curl_easy_setopt (s5r->curl,
1926                       CURLOPT_HTTP_CONTENT_DECODING,
1927                       0);
1928     curl_easy_setopt (s5r->curl,
1929                       CURLOPT_NOSIGNAL,
1930                       1L);
1931     curl_easy_setopt (s5r->curl,
1932                       CURLOPT_PRIVATE,
1933                       s5r);
1934     curl_easy_setopt (s5r->curl,
1935                       CURLOPT_VERBOSE,
1936                       0L);
1937     /**
1938      * Pre-populate cache to resolve Hostname.
1939      * This is necessary as the DNS name in the CURLOPT_URL is used
1940      * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1941      */
1942     if (NULL != s5r->leho)
1943     {
1944       char *curl_hosts;
1945
1946       GNUNET_asprintf (&curl_hosts,
1947                        "%s:%d:%s",
1948                        s5r->leho,
1949                        port,
1950                        ipaddr);
1951       s5r->hosts = curl_slist_append (NULL,
1952                                       curl_hosts);
1953       curl_easy_setopt (s5r->curl,
1954                         CURLOPT_RESOLVE,
1955                         s5r->hosts);
1956       GNUNET_free (curl_hosts);
1957     }
1958     if (s5r->is_gns)
1959     {
1960       GNUNET_asprintf (&curlurl,
1961                        (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1962                        ? "http://%s:%d%s"
1963                        : "https://%s:%d%s",
1964                        (NULL != s5r->leho)
1965                        ? s5r->leho
1966                        : ipaddr,
1967                        port,
1968                        s5r->url);
1969     }
1970     else
1971     {
1972       GNUNET_asprintf (&curlurl,
1973                        (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1974                        ? "http://%s:%d%s"
1975                        : "https://%s:%d%s",
1976                        s5r->domain,
1977                        port,
1978                        s5r->url);
1979     }
1980     curl_easy_setopt (s5r->curl,
1981                       CURLOPT_URL,
1982                       curlurl);
1983     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1984                 "Launching %s CURL interaction, fetching `%s'\n",
1985                 (s5r->is_gns) ? "GNS" : "DNS",
1986                 curlurl);
1987     GNUNET_free (curlurl);
1988     if (0 == strcasecmp (meth,
1989                          MHD_HTTP_METHOD_PUT))
1990     {
1991       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1992       curl_easy_setopt (s5r->curl,
1993                         CURLOPT_UPLOAD,
1994                         1L);
1995       curl_easy_setopt (s5r->curl,
1996                         CURLOPT_WRITEFUNCTION,
1997                         &curl_download_cb);
1998       curl_easy_setopt (s5r->curl,
1999                         CURLOPT_WRITEDATA,
2000                         s5r);
2001       GNUNET_assert (CURLE_OK ==
2002                      curl_easy_setopt (s5r->curl,
2003                                        CURLOPT_READFUNCTION,
2004                                        &curl_upload_cb));
2005       curl_easy_setopt (s5r->curl,
2006                         CURLOPT_READDATA,
2007                         s5r);
2008       {
2009         const char *us;
2010         long upload_size = 0;
2011
2012         us = MHD_lookup_connection_value (con,
2013                                           MHD_HEADER_KIND,
2014                                           MHD_HTTP_HEADER_CONTENT_LENGTH);
2015         if ( (1 == sscanf (us,
2016                            "%ld",
2017                            &upload_size)) &&
2018              (upload_size >= 0) )
2019         {
2020           curl_easy_setopt (s5r->curl,
2021                             CURLOPT_INFILESIZE,
2022                             upload_size);
2023         }
2024       }
2025     }
2026     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
2027     {
2028       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
2029       curl_easy_setopt (s5r->curl,
2030                         CURLOPT_POST,
2031                         1L);
2032       curl_easy_setopt (s5r->curl,
2033                         CURLOPT_WRITEFUNCTION,
2034                         &curl_download_cb);
2035       curl_easy_setopt (s5r->curl,
2036                         CURLOPT_WRITEDATA,
2037                         s5r);
2038       curl_easy_setopt (s5r->curl,
2039                         CURLOPT_READFUNCTION,
2040                         &curl_upload_cb);
2041       curl_easy_setopt (s5r->curl,
2042                         CURLOPT_READDATA,
2043                         s5r);
2044       {
2045         const char *us;
2046         long upload_size;
2047
2048         upload_size = 0;
2049         us = MHD_lookup_connection_value (con,
2050                                           MHD_HEADER_KIND,
2051                                           MHD_HTTP_HEADER_CONTENT_LENGTH);
2052         if ( (NULL != us) &&
2053              (1 == sscanf (us,
2054                            "%ld",
2055                            &upload_size)) &&
2056              (upload_size >= 0) )
2057         {
2058           curl_easy_setopt (s5r->curl,
2059                             CURLOPT_INFILESIZE,
2060                             upload_size);
2061         } else {
2062           curl_easy_setopt (s5r->curl,
2063                             CURLOPT_INFILESIZE,
2064                             upload_size);
2065         }
2066       }
2067     }
2068     else if (0 == strcasecmp (meth,
2069                               MHD_HTTP_METHOD_HEAD))
2070     {
2071       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2072       curl_easy_setopt (s5r->curl,
2073                         CURLOPT_NOBODY,
2074                         1L);
2075     }
2076     else if (0 == strcasecmp (meth,
2077                               MHD_HTTP_METHOD_OPTIONS))
2078     {
2079       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2080       curl_easy_setopt (s5r->curl,
2081                         CURLOPT_CUSTOMREQUEST,
2082                         "OPTIONS");
2083       curl_easy_setopt (s5r->curl,
2084                         CURLOPT_WRITEFUNCTION,
2085                         &curl_download_cb);
2086       curl_easy_setopt (s5r->curl,
2087                         CURLOPT_WRITEDATA,
2088                         s5r);
2089
2090     }
2091     else if (0 == strcasecmp (meth,
2092                               MHD_HTTP_METHOD_GET))
2093     {
2094       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2095       curl_easy_setopt (s5r->curl,
2096                         CURLOPT_HTTPGET,
2097                         1L);
2098       curl_easy_setopt (s5r->curl,
2099                         CURLOPT_WRITEFUNCTION,
2100                         &curl_download_cb);
2101       curl_easy_setopt (s5r->curl,
2102                         CURLOPT_WRITEDATA,
2103                         s5r);
2104     }
2105     else if (0 == strcasecmp (meth,
2106                               MHD_HTTP_METHOD_DELETE))
2107     {
2108       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2109       curl_easy_setopt (s5r->curl,
2110                         CURLOPT_CUSTOMREQUEST,
2111                         "DELETE");
2112       curl_easy_setopt (s5r->curl,
2113                         CURLOPT_WRITEFUNCTION,
2114                         &curl_download_cb);
2115       curl_easy_setopt (s5r->curl,
2116                         CURLOPT_WRITEDATA,
2117                         s5r);
2118     }
2119     else
2120     {
2121       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2122                   _("Unsupported HTTP method `%s'\n"),
2123                   meth);
2124       curl_easy_cleanup (s5r->curl);
2125       s5r->curl = NULL;
2126       return MHD_NO;
2127     }
2128
2129     if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
2130     {
2131       curl_easy_setopt (s5r->curl,
2132                         CURLOPT_HTTP_VERSION,
2133                         CURL_HTTP_VERSION_1_0);
2134     }
2135     else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
2136     {
2137       curl_easy_setopt (s5r->curl,
2138                         CURLOPT_HTTP_VERSION,
2139                         CURL_HTTP_VERSION_1_1);
2140     }
2141     else
2142     {
2143       curl_easy_setopt (s5r->curl,
2144                         CURLOPT_HTTP_VERSION,
2145                         CURL_HTTP_VERSION_NONE);
2146     }
2147
2148     if (GNUNET_YES == s5r->is_tls) //(HTTPS_PORT == s5r->port)
2149     {
2150       curl_easy_setopt (s5r->curl,
2151                         CURLOPT_USE_SSL,
2152                         CURLUSESSL_ALL);
2153       if (0 < s5r->num_danes)
2154         curl_easy_setopt (s5r->curl,
2155                           CURLOPT_SSL_VERIFYPEER,
2156                           0L);
2157       else
2158         curl_easy_setopt (s5r->curl,
2159                           CURLOPT_SSL_VERIFYPEER,
2160                           1L);
2161       /* Disable cURL checking the hostname, as we will check ourselves
2162          as only we have the domain name or the LEHO or the DANE record */
2163       curl_easy_setopt (s5r->curl,
2164                         CURLOPT_SSL_VERIFYHOST,
2165                         0L);
2166     }
2167     else
2168     {
2169       curl_easy_setopt (s5r->curl,
2170                         CURLOPT_USE_SSL,
2171                         CURLUSESSL_NONE);
2172     }
2173
2174     if (CURLM_OK !=
2175         curl_multi_add_handle (curl_multi,
2176                                s5r->curl))
2177     {
2178       GNUNET_break (0);
2179       curl_easy_cleanup (s5r->curl);
2180       s5r->curl = NULL;
2181       return MHD_NO;
2182     }
2183     MHD_get_connection_values (con,
2184                                MHD_HEADER_KIND,
2185                                &con_val_iter,
2186                                s5r);
2187     curl_easy_setopt (s5r->curl,
2188                       CURLOPT_HTTPHEADER,
2189                       s5r->headers);
2190     curl_download_prepare ();
2191     return MHD_YES;
2192   }
2193
2194   /* continuing to process request */
2195   if (0 != *upload_data_size)
2196   {
2197     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198                 "Processing %u bytes UPLOAD\n",
2199                 (unsigned int) *upload_data_size);
2200
2201     /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else
2202      * upload callback is not called!
2203      */
2204     curl_easy_setopt (s5r->curl,
2205                       CURLOPT_POSTFIELDSIZE,
2206                       *upload_data_size);
2207
2208     left = GNUNET_MIN (*upload_data_size,
2209                        sizeof (s5r->io_buf) - s5r->io_len);
2210     GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
2211                    upload_data,
2212                    left);
2213     s5r->io_len += left;
2214     *upload_data_size -= left;
2215     GNUNET_assert (NULL != s5r->curl);
2216     if (GNUNET_YES == s5r->curl_paused)
2217     {
2218       s5r->curl_paused = GNUNET_NO;
2219       curl_easy_pause (s5r->curl,
2220                        CURLPAUSE_CONT);
2221     }
2222     return MHD_YES;
2223   }
2224   if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
2225   {
2226     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2227                 "Finished processing UPLOAD\n");
2228     s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
2229   }
2230   if (NULL == s5r->response)
2231   {
2232     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2233                 "Waiting for HTTP response for %s%s...\n",
2234                 s5r->domain,
2235                 s5r->url);
2236     MHD_suspend_connection (con);
2237     s5r->suspended = GNUNET_YES;
2238     return MHD_YES;
2239   }
2240   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2241               "Queueing response for %s%s with MHD\n",
2242               s5r->domain,
2243               s5r->url);
2244   run_mhd_now (s5r->hd);
2245   return MHD_queue_response (con,
2246                              s5r->response_code,
2247                              s5r->response);
2248 }
2249
2250
2251 /* ******************** MHD HTTP setup and event loop ******************** */
2252
2253
2254 /**
2255  * Function called when MHD decides that we are done with a request.
2256  *
2257  * @param cls NULL
2258  * @param connection connection handle
2259  * @param con_cls value as set by the last call to
2260  *        the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2261  * @param toe reason for request termination (ignored)
2262  */
2263 static void
2264 mhd_completed_cb (void *cls,
2265                   struct MHD_Connection *connection,
2266                   void **con_cls,
2267                   enum MHD_RequestTerminationCode toe)
2268 {
2269   struct Socks5Request *s5r = *con_cls;
2270
2271   if (NULL == s5r)
2272     return;
2273   if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
2274     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2275                 "MHD encountered error handling request: %d\n",
2276                 toe);
2277   if (NULL != s5r->curl)
2278   {
2279     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2280                 "Removing cURL handle (MHD interaction complete)\n");
2281     curl_multi_remove_handle (curl_multi,
2282                               s5r->curl);
2283     curl_slist_free_all (s5r->headers);
2284     s5r->headers = NULL;
2285     curl_easy_reset (s5r->curl);
2286     s5r->rbuf_len = 0;
2287     s5r->wbuf_len = 0;
2288     s5r->io_len = 0;
2289     curl_download_prepare ();
2290   }
2291   if ( (NULL != s5r->response) &&
2292        (curl_failure_response != s5r->response) )
2293     MHD_destroy_response (s5r->response);
2294   for (struct HttpResponseHeader *header = s5r->header_head;
2295        NULL != header;
2296        header = s5r->header_head)
2297   {
2298     GNUNET_CONTAINER_DLL_remove (s5r->header_head,
2299                                  s5r->header_tail,
2300                                  header);
2301     GNUNET_free (header->type);
2302     GNUNET_free (header->value);
2303     GNUNET_free (header);
2304   }
2305   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306               "Finished request for %s\n",
2307               s5r->url);
2308   GNUNET_free (s5r->url);
2309   s5r->state = SOCKS5_SOCKET_WITH_MHD;
2310   s5r->url = NULL;
2311   s5r->response = NULL;
2312   *con_cls = NULL;
2313 }
2314
2315
2316 /**
2317  * Function called when MHD connection is opened or closed.
2318  *
2319  * @param cls NULL
2320  * @param connection connection handle
2321  * @param con_cls value as set by the last call to
2322  *        the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2323  * @param toe connection notification type
2324  */
2325 static void
2326 mhd_connection_cb (void *cls,
2327                    struct MHD_Connection *connection,
2328                    void **con_cls,
2329                    enum MHD_ConnectionNotificationCode cnc)
2330 {
2331   struct Socks5Request *s5r;
2332   const union MHD_ConnectionInfo *ci;
2333   int sock;
2334
2335   switch (cnc)
2336   {
2337     case MHD_CONNECTION_NOTIFY_STARTED:
2338       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
2339       ci = MHD_get_connection_info (connection,
2340                                     MHD_CONNECTION_INFO_CONNECTION_FD);
2341       if (NULL == ci)
2342       {
2343         GNUNET_break (0);
2344         return;
2345       }
2346       sock = ci->connect_fd;
2347       for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
2348       {
2349         if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
2350         {
2351           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2352                       "Context set...\n");
2353           s5r->ssl_checked = GNUNET_NO;
2354           *con_cls = s5r;
2355           break;
2356         }
2357       }
2358       break;
2359     case MHD_CONNECTION_NOTIFY_CLOSED:
2360       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2361                   "Connection closed... cleaning up\n");
2362       s5r = *con_cls;
2363       if (NULL == s5r)
2364       {
2365         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2366                     "Connection stale!\n");
2367         return;
2368       }
2369       cleanup_s5r (s5r);
2370       curl_download_prepare ();
2371       *con_cls = NULL;
2372       break;
2373     default:
2374       GNUNET_break (0);
2375   }
2376 }
2377
2378 /**
2379  * Function called when MHD first processes an incoming connection.
2380  * Gives us the respective URI information.
2381  *
2382  * We use this to associate the `struct MHD_Connection` with our
2383  * internal `struct Socks5Request` data structure (by checking
2384  * for matching sockets).
2385  *
2386  * @param cls the HTTP server handle (a `struct MhdHttpList`)
2387  * @param url the URL that is being requested
2388  * @param connection MHD connection object for the request
2389  * @return the `struct Socks5Request` that this @a connection is for
2390  */
2391 static void *
2392 mhd_log_callback (void *cls,
2393                   const char *url,
2394                   struct MHD_Connection *connection)
2395 {
2396   struct Socks5Request *s5r;
2397   const union MHD_ConnectionInfo *ci;
2398
2399   ci = MHD_get_connection_info (connection,
2400                                 MHD_CONNECTION_INFO_SOCKET_CONTEXT);
2401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
2402   if (NULL == ci)
2403   {
2404     GNUNET_break (0);
2405     return NULL;
2406   }
2407   s5r = ci->socket_context;
2408   if (NULL != s5r->url)
2409   {
2410     GNUNET_break (0);
2411     return NULL;
2412   }
2413   s5r->url = GNUNET_strdup (url);
2414   if (NULL != s5r->timeout_task)
2415   {
2416     GNUNET_SCHEDULER_cancel (s5r->timeout_task);
2417     s5r->timeout_task = NULL;
2418   }
2419   GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD);
2420   return s5r;
2421 }
2422
2423
2424 /**
2425  * Kill the given MHD daemon.
2426  *
2427  * @param hd daemon to stop
2428  */
2429 static void
2430 kill_httpd (struct MhdHttpList *hd)
2431 {
2432   GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
2433                                mhd_httpd_tail,
2434                                hd);
2435   GNUNET_free_non_null (hd->domain);
2436   MHD_stop_daemon (hd->daemon);
2437   if (NULL != hd->httpd_task)
2438   {
2439     GNUNET_SCHEDULER_cancel (hd->httpd_task);
2440     hd->httpd_task = NULL;
2441   }
2442   GNUNET_free_non_null (hd->proxy_cert);
2443   if (hd == httpd)
2444     httpd = NULL;
2445   GNUNET_free (hd);
2446 }
2447
2448
2449 /**
2450  * Task run whenever HTTP server is idle for too long. Kill it.
2451  *
2452  * @param cls the `struct MhdHttpList *`
2453  */
2454 static void
2455 kill_httpd_task (void *cls)
2456 {
2457   struct MhdHttpList *hd = cls;
2458
2459   hd->httpd_task = NULL;
2460   kill_httpd (hd);
2461 }
2462
2463
2464 /**
2465  * Task run whenever HTTP server operations are pending.
2466  *
2467  * @param cls the `struct MhdHttpList *` of the daemon that is being run
2468  */
2469 static void
2470 do_httpd (void *cls);
2471
2472
2473 /**
2474  * Schedule MHD.  This function should be called initially when an
2475  * MHD is first getting its client socket, and will then automatically
2476  * always be called later whenever there is work to be done.
2477  *
2478  * @param hd the daemon to schedule
2479  */
2480 static void
2481 schedule_httpd (struct MhdHttpList *hd)
2482 {
2483   fd_set rs;
2484   fd_set ws;
2485   fd_set es;
2486   struct GNUNET_NETWORK_FDSet *wrs;
2487   struct GNUNET_NETWORK_FDSet *wws;
2488   int max;
2489   int haveto;
2490   MHD_UNSIGNED_LONG_LONG timeout;
2491   struct GNUNET_TIME_Relative tv;
2492
2493   FD_ZERO (&rs);
2494   FD_ZERO (&ws);
2495   FD_ZERO (&es);
2496   max = -1;
2497   if (MHD_YES !=
2498       MHD_get_fdset (hd->daemon,
2499                      &rs,
2500                      &ws,
2501                      &es,
2502                      &max))
2503   {
2504     kill_httpd (hd);
2505     return;
2506   }
2507   haveto = MHD_get_timeout (hd->daemon,
2508                             &timeout);
2509   if (MHD_YES == haveto)
2510     tv.rel_value_us = (uint64_t) timeout * 1000LL;
2511   else
2512     tv = GNUNET_TIME_UNIT_FOREVER_REL;
2513   if (-1 != max)
2514   {
2515     wrs = GNUNET_NETWORK_fdset_create ();
2516     wws = GNUNET_NETWORK_fdset_create ();
2517     GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
2518     GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
2519   }
2520   else
2521   {
2522     wrs = NULL;
2523     wws = NULL;
2524   }
2525   if (NULL != hd->httpd_task)
2526   {
2527     GNUNET_SCHEDULER_cancel (hd->httpd_task);
2528     hd->httpd_task = NULL;
2529   }
2530   if ( (MHD_YES != haveto) &&
2531        (-1 == max) &&
2532        (hd != httpd) )
2533   {
2534     /* daemon is idle, kill after timeout */
2535     hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
2536                                                    &kill_httpd_task,
2537                                                    hd);
2538   }
2539   else
2540   {
2541     hd->httpd_task =
2542       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2543                                    tv, wrs, wws,
2544                                    &do_httpd, hd);
2545   }
2546   if (NULL != wrs)
2547     GNUNET_NETWORK_fdset_destroy (wrs);
2548   if (NULL != wws)
2549     GNUNET_NETWORK_fdset_destroy (wws);
2550 }
2551
2552
2553 /**
2554  * Task run whenever HTTP server operations are pending.
2555  *
2556  * @param cls the `struct MhdHttpList` of the daemon that is being run
2557  */
2558 static void
2559 do_httpd (void *cls)
2560 {
2561   struct MhdHttpList *hd = cls;
2562
2563   hd->httpd_task = NULL;
2564   MHD_run (hd->daemon);
2565   schedule_httpd (hd);
2566 }
2567
2568
2569 /**
2570  * Run MHD now, we have extra data ready for the callback.
2571  *
2572  * @param hd the daemon to run now.
2573  */
2574 static void
2575 run_mhd_now (struct MhdHttpList *hd)
2576 {
2577   if (NULL != hd->httpd_task)
2578     GNUNET_SCHEDULER_cancel (hd->httpd_task);
2579   hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
2580                                              hd);
2581 }
2582
2583
2584 /**
2585  * Read file in filename
2586  *
2587  * @param filename file to read
2588  * @param size pointer where filesize is stored
2589  * @return NULL on error
2590  */
2591 static void*
2592 load_file (const char* filename,
2593            unsigned int* size)
2594 {
2595   void *buffer;
2596   uint64_t fsize;
2597
2598   if (GNUNET_OK !=
2599       GNUNET_DISK_file_size (filename,
2600                              &fsize,
2601                              GNUNET_YES,
2602                              GNUNET_YES))
2603     return NULL;
2604   if (fsize > MAX_PEM_SIZE)
2605     return NULL;
2606   *size = (unsigned int) fsize;
2607   buffer = GNUNET_malloc (*size);
2608   if (fsize !=
2609       GNUNET_DISK_fn_read (filename,
2610                            buffer,
2611                            (size_t) fsize))
2612   {
2613     GNUNET_free (buffer);
2614     return NULL;
2615   }
2616   return buffer;
2617 }
2618
2619
2620 /**
2621  * Load PEM key from file
2622  *
2623  * @param key where to store the data
2624  * @param keyfile path to the PEM file
2625  * @return #GNUNET_OK on success
2626  */
2627 static int
2628 load_key_from_file (gnutls_x509_privkey_t key,
2629                     const char* keyfile)
2630 {
2631   gnutls_datum_t key_data;
2632   int ret;
2633
2634   key_data.data = load_file (keyfile,
2635                              &key_data.size);
2636   if (NULL == key_data.data)
2637     return GNUNET_SYSERR;
2638   ret = gnutls_x509_privkey_import (key, &key_data,
2639                                     GNUTLS_X509_FMT_PEM);
2640   if (GNUTLS_E_SUCCESS != ret)
2641   {
2642     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2643                 _("Unable to import private key from file `%s'\n"),
2644                 keyfile);
2645   }
2646   GNUNET_free_non_null (key_data.data);
2647   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2648 }
2649
2650
2651 /**
2652  * Load cert from file
2653  *
2654  * @param crt struct to store data in
2655  * @param certfile path to pem file
2656  * @return #GNUNET_OK on success
2657  */
2658 static int
2659 load_cert_from_file (gnutls_x509_crt_t crt,
2660                      const char* certfile)
2661 {
2662   gnutls_datum_t cert_data;
2663   int ret;
2664
2665   cert_data.data = load_file (certfile,
2666                               &cert_data.size);
2667   if (NULL == cert_data.data)
2668     return GNUNET_SYSERR;
2669   ret = gnutls_x509_crt_import (crt,
2670                                 &cert_data,
2671                                 GNUTLS_X509_FMT_PEM);
2672   if (GNUTLS_E_SUCCESS != ret)
2673   {
2674     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2675                 _("Unable to import certificate from `%s'\n"),
2676                 certfile);
2677   }
2678   GNUNET_free_non_null (cert_data.data);
2679   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2680 }
2681
2682
2683 /**
2684  * Generate new certificate for specific name
2685  *
2686  * @param name the subject name to generate a cert for
2687  * @return a struct holding the PEM data, NULL on error
2688  */
2689 static struct ProxyGNSCertificate *
2690 generate_gns_certificate (const char *name)
2691 {
2692   unsigned int serial;
2693   size_t key_buf_size;
2694   size_t cert_buf_size;
2695   gnutls_x509_crt_t request;
2696   time_t etime;
2697   struct tm *tm_data;
2698   struct ProxyGNSCertificate *pgc;
2699
2700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2701               "Generating x.509 certificate for `%s'\n",
2702               name);
2703   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2704   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2705   pgc = GNUNET_new (struct ProxyGNSCertificate);
2706   gnutls_x509_crt_set_dn_by_oid (request,
2707                                  GNUTLS_OID_X520_COUNTRY_NAME,
2708                                  0,
2709                                  "ZZ",
2710                                  strlen ("ZZ"));
2711   gnutls_x509_crt_set_dn_by_oid (request,
2712                                  GNUTLS_OID_X520_ORGANIZATION_NAME,
2713                                  0,
2714                                  "GNU Name System",
2715                                  strlen ("GNU Name System"));
2716   gnutls_x509_crt_set_dn_by_oid (request,
2717                                  GNUTLS_OID_X520_COMMON_NAME,
2718                                  0,
2719                                  name,
2720                                  strlen (name));
2721   gnutls_x509_crt_set_subject_alternative_name (request,
2722                                         GNUTLS_SAN_DNSNAME,
2723                                         name);
2724   GNUNET_break (GNUTLS_E_SUCCESS ==
2725                 gnutls_x509_crt_set_version (request,
2726                                              3));
2727   gnutls_rnd (GNUTLS_RND_NONCE,
2728               &serial,
2729               sizeof (serial));
2730   gnutls_x509_crt_set_serial (request,
2731                               &serial,
2732                               sizeof (serial));
2733   etime = time (NULL);
2734   tm_data = localtime (&etime);
2735   tm_data->tm_hour--;
2736   etime = mktime(tm_data);
2737   gnutls_x509_crt_set_activation_time (request,
2738                                        etime);
2739   tm_data->tm_year++;
2740   etime = mktime (tm_data);
2741   gnutls_x509_crt_set_expiration_time (request,
2742                                        etime);
2743   gnutls_x509_crt_sign2 (request,
2744                          proxy_ca.cert,
2745                          proxy_ca.key,
2746                          GNUTLS_DIG_SHA512,
2747                          0);
2748   key_buf_size = sizeof (pgc->key);
2749   cert_buf_size = sizeof (pgc->cert);
2750   gnutls_x509_crt_export (request,
2751                           GNUTLS_X509_FMT_PEM,
2752                           pgc->cert,
2753                           &cert_buf_size);
2754   gnutls_x509_privkey_export (proxy_ca.key,
2755                               GNUTLS_X509_FMT_PEM,
2756                               pgc->key,
2757                               &key_buf_size);
2758   gnutls_x509_crt_deinit (request);
2759   return pgc;
2760 }
2761
2762
2763 /**
2764  * Function called by MHD with errors, suppresses them all.
2765  *
2766  * @param cls closure
2767  * @param fm format string (`printf()`-style)
2768  * @param ap arguments to @a fm
2769  */
2770 static void
2771 mhd_error_log_callback (void *cls,
2772                         const char *fm,
2773                         va_list ap)
2774 {
2775   /* do nothing */
2776 }
2777
2778
2779 /**
2780  * Lookup (or create) an TLS MHD instance for a particular domain.
2781  *
2782  * @param domain the domain the TLS daemon has to serve
2783  * @return NULL on error
2784  */
2785 static struct MhdHttpList *
2786 lookup_ssl_httpd (const char* domain)
2787 {
2788   struct MhdHttpList *hd;
2789   struct ProxyGNSCertificate *pgc;
2790
2791   if (NULL == domain)
2792   {
2793     GNUNET_break (0);
2794     return NULL;
2795   }
2796   for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2797     if ( (NULL != hd->domain) &&
2798          (0 == strcmp (hd->domain, domain)) )
2799       return hd;
2800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2801               "Starting fresh MHD HTTPS instance for domain `%s'\n",
2802               domain);
2803   pgc = generate_gns_certificate (domain);
2804   hd = GNUNET_new (struct MhdHttpList);
2805   hd->is_ssl = GNUNET_YES;
2806   hd->domain = GNUNET_strdup (domain);
2807   hd->proxy_cert = pgc;
2808   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
2809                                  0,
2810                                  NULL, NULL,
2811                                  &create_response, hd,
2812                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2813                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2814                                  MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
2815                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2816                                  MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2817                                  MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2818                                  MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2819                                  MHD_OPTION_END);
2820   if (NULL == hd->daemon)
2821   {
2822     GNUNET_free (pgc);
2823     GNUNET_free (hd);
2824     return NULL;
2825   }
2826   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2827                                mhd_httpd_tail,
2828                                hd);
2829   return hd;
2830 }
2831
2832
2833 /**
2834  * Task run when a Socks5Request somehow fails to be associated with
2835  * an MHD connection (i.e. because the client never speaks HTTP after
2836  * the SOCKS5 handshake).  Clean up.
2837  *
2838  * @param cls the `struct Socks5Request *`
2839  */
2840 static void
2841 timeout_s5r_handshake (void *cls)
2842 {
2843   struct Socks5Request *s5r = cls;
2844
2845   s5r->timeout_task = NULL;
2846   cleanup_s5r (s5r);
2847 }
2848
2849
2850 /**
2851  * We're done with the Socks5 protocol, now we need to pass the
2852  * connection data through to the final destination, either
2853  * direct (if the protocol might not be HTTP), or via MHD
2854  * (if the port looks like it should be HTTP).
2855  *
2856  * @param s5r socks request that has reached the final stage
2857  */
2858 static void
2859 setup_data_transfer (struct Socks5Request *s5r)
2860 {
2861   struct MhdHttpList *hd;
2862   int fd;
2863   const struct sockaddr *addr;
2864   socklen_t len;
2865   char *domain;
2866
2867   if (GNUNET_YES == s5r->is_tls)
2868   {
2869     GNUNET_asprintf (&domain,
2870                      "%s",
2871                      s5r->domain);
2872     hd = lookup_ssl_httpd (domain);
2873     if (NULL == hd)
2874     {
2875       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2876                   _("Failed to start HTTPS server for `%s'\n"),
2877                   s5r->domain);
2878       cleanup_s5r (s5r);
2879       GNUNET_free (domain);
2880       return;
2881     }
2882   } else {
2883       domain = NULL;
2884       GNUNET_assert (NULL != httpd);
2885       hd = httpd;
2886   }
2887   fd = GNUNET_NETWORK_get_fd (s5r->sock);
2888   addr = GNUNET_NETWORK_get_addr (s5r->sock);
2889   len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2890   s5r->state = SOCKS5_SOCKET_WITH_MHD;
2891   if (MHD_YES !=
2892       MHD_add_connection (hd->daemon,
2893                           fd,
2894                           addr,
2895                           len))
2896   {
2897     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2898                 _("Failed to pass client to MHD\n"));
2899     cleanup_s5r (s5r);
2900     GNUNET_free_non_null (domain);
2901     return;
2902   }
2903   s5r->hd = hd;
2904   schedule_httpd (hd);
2905   s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2906                                                     &timeout_s5r_handshake,
2907                                                     s5r);
2908   GNUNET_free_non_null (domain);
2909 }
2910
2911
2912 /* ********************* SOCKS handling ************************* */
2913
2914
2915 /**
2916  * Write data from buffer to socks5 client, then continue with state machine.
2917  *
2918  * @param cls the closure with the `struct Socks5Request`
2919  */
2920 static void
2921 do_write (void *cls)
2922 {
2923   struct Socks5Request *s5r = cls;
2924   ssize_t len;
2925
2926   s5r->wtask = NULL;
2927   len = GNUNET_NETWORK_socket_send (s5r->sock,
2928                                     s5r->wbuf,
2929                                     s5r->wbuf_len);
2930   if (len <= 0)
2931   {
2932     /* write error: connection closed, shutdown, etc.; just clean up */
2933     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2934                 "Write Error\n");
2935     cleanup_s5r (s5r);
2936     return;
2937   }
2938   memmove (s5r->wbuf,
2939            &s5r->wbuf[len],
2940            s5r->wbuf_len - len);
2941   s5r->wbuf_len -= len;
2942   if (s5r->wbuf_len > 0)
2943   {
2944     /* not done writing */
2945     s5r->wtask =
2946       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2947                                       s5r->sock,
2948                                       &do_write, s5r);
2949     return;
2950   }
2951
2952   /* we're done writing, continue with state machine! */
2953
2954   switch (s5r->state)
2955   {
2956     case SOCKS5_INIT:
2957       GNUNET_assert (0);
2958       break;
2959     case SOCKS5_REQUEST:
2960       GNUNET_assert (NULL != s5r->rtask);
2961       break;
2962     case SOCKS5_DATA_TRANSFER:
2963       setup_data_transfer (s5r);
2964       return;
2965     case SOCKS5_WRITE_THEN_CLEANUP:
2966       cleanup_s5r (s5r);
2967       return;
2968     default:
2969       GNUNET_break (0);
2970       break;
2971   }
2972 }
2973
2974
2975 /**
2976  * Return a server response message indicating a failure to the client.
2977  *
2978  * @param s5r request to return failure code for
2979  * @param sc status code to return
2980  */
2981 static void
2982 signal_socks_failure (struct Socks5Request *s5r,
2983                       enum Socks5StatusCode sc)
2984 {
2985   struct Socks5ServerResponseMessage *s_resp;
2986
2987   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2988   memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2989   s_resp->version = SOCKS_VERSION_5;
2990   s_resp->reply = sc;
2991   s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2992   if (NULL != s5r->wtask)
2993     s5r->wtask =
2994       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2995                                       s5r->sock,
2996                                       &do_write, s5r);
2997 }
2998
2999
3000 /**
3001  * Return a server response message indicating success.
3002  *
3003  * @param s5r request to return success status message for
3004  */
3005 static void
3006 signal_socks_success (struct Socks5Request *s5r)
3007 {
3008   struct Socks5ServerResponseMessage *s_resp;
3009
3010   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
3011   s_resp->version = SOCKS_VERSION_5;
3012   s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
3013   s_resp->reserved = 0;
3014   s_resp->addr_type = SOCKS5_AT_IPV4;
3015   /* zero out IPv4 address and port */
3016   memset (&s_resp[1],
3017           0,
3018           sizeof (struct in_addr) + sizeof (uint16_t));
3019   s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
3020     sizeof (struct in_addr) + sizeof (uint16_t);
3021   if (NULL == s5r->wtask)
3022     s5r->wtask =
3023       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3024                                       s5r->sock,
3025                                       &do_write, s5r);
3026 }
3027
3028
3029 /**
3030  * Process GNS results for target domain.
3031  *
3032  * @param cls the `struct Socks5Request *`
3033  * @param tld #GNUNET_YES if this was a GNS TLD.
3034  * @param rd_count number of records returned
3035  * @param rd record data
3036  */
3037 static void
3038 handle_gns_result (void *cls,
3039                    int tld,
3040                    uint32_t rd_count,
3041                    const struct GNUNET_GNSRECORD_Data *rd)
3042 {
3043   struct Socks5Request *s5r = cls;
3044   const struct GNUNET_GNSRECORD_Data *r;
3045   int got_ip;
3046
3047   s5r->gns_lookup = NULL;
3048   s5r->is_gns = tld;
3049   got_ip = GNUNET_NO;
3050   for (uint32_t i=0;i<rd_count;i++)
3051   {
3052     r = &rd[i];
3053     switch (r->record_type)
3054     {
3055       case GNUNET_DNSPARSER_TYPE_A:
3056         {
3057           struct sockaddr_in *in;
3058
3059           if (sizeof (struct in_addr) != r->data_size)
3060           {
3061             GNUNET_break_op (0);
3062             break;
3063           }
3064           if (GNUNET_YES == got_ip)
3065             break;
3066           if (GNUNET_OK !=
3067               GNUNET_NETWORK_test_pf (PF_INET))
3068             break;
3069           got_ip = GNUNET_YES;
3070           in = (struct sockaddr_in *) &s5r->destination_address;
3071           in->sin_family = AF_INET;
3072           GNUNET_memcpy (&in->sin_addr,
3073                          r->data,
3074                          r->data_size);
3075           in->sin_port = htons (s5r->port);
3076 #if HAVE_SOCKADDR_IN_SIN_LEN
3077           in->sin_len = sizeof (*in);
3078 #endif
3079         }
3080         break;
3081       case GNUNET_DNSPARSER_TYPE_AAAA:
3082         {
3083           struct sockaddr_in6 *in;
3084
3085           if (sizeof (struct in6_addr) != r->data_size)
3086           {
3087             GNUNET_break_op (0);
3088             break;
3089           }
3090           if (GNUNET_YES == got_ip)
3091             break;
3092           if (GNUNET_YES == disable_v6)
3093             break;
3094           if (GNUNET_OK !=
3095               GNUNET_NETWORK_test_pf (PF_INET6))
3096             break;
3097           /* FIXME: allow user to disable IPv6 per configuration option... */
3098           got_ip = GNUNET_YES;
3099           in = (struct sockaddr_in6 *) &s5r->destination_address;
3100           in->sin6_family = AF_INET6;
3101           GNUNET_memcpy (&in->sin6_addr,
3102                          r->data,
3103                          r->data_size);
3104           in->sin6_port = htons (s5r->port);
3105 #if HAVE_SOCKADDR_IN_SIN_LEN
3106           in->sin6_len = sizeof (*in);
3107 #endif
3108         }
3109         break;
3110       case GNUNET_GNSRECORD_TYPE_VPN:
3111         GNUNET_break (0); /* should have been translated within GNS */
3112         break;
3113       case GNUNET_GNSRECORD_TYPE_LEHO:
3114         GNUNET_free_non_null (s5r->leho);
3115         s5r->leho = GNUNET_strndup (r->data,
3116                                     r->data_size);
3117         break;
3118       case GNUNET_GNSRECORD_TYPE_BOX:
3119         {
3120           const struct GNUNET_GNSRECORD_BoxRecord *box;
3121
3122           if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
3123           {
3124             GNUNET_break_op (0);
3125             break;
3126           }
3127           box = r->data;
3128           if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
3129                (ntohs (box->protocol) != IPPROTO_TCP) ||
3130                (ntohs (box->service) != s5r->port) )
3131             break; /* BOX record does not apply */
3132           if (s5r->num_danes >= MAX_DANES)
3133             {
3134               GNUNET_break (0); /* MAX_DANES too small */
3135               break;
3136             }
3137           s5r->is_tls = GNUNET_YES; /* This should be TLS */
3138           s5r->dane_data_len[s5r->num_danes]
3139             = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
3140           s5r->dane_data[s5r->num_danes]
3141             = GNUNET_memdup (&box[1],
3142                              s5r->dane_data_len[s5r->num_danes]);
3143           s5r->num_danes++;
3144           break;
3145         }
3146       default:
3147         /* don't care */
3148         break;
3149     }
3150   }
3151   if ( (GNUNET_YES != got_ip) &&
3152        (GNUNET_YES == tld) )
3153   {
3154     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3155                 "Name resolution failed to yield useful IP address.\n");
3156     signal_socks_failure (s5r,
3157                           SOCKS5_STATUS_GENERAL_FAILURE);
3158     return;
3159   }
3160   s5r->state = SOCKS5_DATA_TRANSFER;
3161   signal_socks_success (s5r);
3162 }
3163
3164
3165 /**
3166  * Remove the first @a len bytes from the beginning of the read buffer.
3167  *
3168  * @param s5r the handle clear the read buffer for
3169  * @param len number of bytes in read buffer to advance
3170  */
3171 static void
3172 clear_from_s5r_rbuf (struct Socks5Request *s5r,
3173                      size_t len)
3174 {
3175   GNUNET_assert (len <= s5r->rbuf_len);
3176   memmove (s5r->rbuf,
3177            &s5r->rbuf[len],
3178            s5r->rbuf_len - len);
3179   s5r->rbuf_len -= len;
3180 }
3181
3182
3183 /**
3184  * Read data from incoming Socks5 connection
3185  *
3186  * @param cls the closure with the `struct Socks5Request`
3187  */
3188 static void
3189 do_s5r_read (void *cls)
3190 {
3191   struct Socks5Request *s5r = cls;
3192   const struct Socks5ClientHelloMessage *c_hello;
3193   struct Socks5ServerHelloMessage *s_hello;
3194   const struct Socks5ClientRequestMessage *c_req;
3195   ssize_t rlen;
3196   size_t alen;
3197   const struct GNUNET_SCHEDULER_TaskContext *tc;
3198
3199   s5r->rtask = NULL;
3200   tc = GNUNET_SCHEDULER_get_task_context ();
3201   if ( (NULL != tc->read_ready) &&
3202        (GNUNET_NETWORK_fdset_isset (tc->read_ready,
3203                                     s5r->sock)) )
3204   {
3205     rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
3206                                        &s5r->rbuf[s5r->rbuf_len],
3207                                        sizeof (s5r->rbuf) - s5r->rbuf_len);
3208     if (rlen <= 0)
3209     {
3210       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3211                   "socks5 client disconnected.\n");
3212       cleanup_s5r (s5r);
3213       return;
3214     }
3215     s5r->rbuf_len += rlen;
3216   }
3217   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3218                                               s5r->sock,
3219                                               &do_s5r_read, s5r);
3220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3221               "Processing %zu bytes of socks data in state %d\n",
3222               s5r->rbuf_len,
3223               s5r->state);
3224   switch (s5r->state)
3225   {
3226     case SOCKS5_INIT:
3227       c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
3228       if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
3229            (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
3230         return; /* need more data */
3231       if (SOCKS_VERSION_5 != c_hello->version)
3232       {
3233         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3234                     _("Unsupported socks version %d\n"),
3235                     (int) c_hello->version);
3236         cleanup_s5r (s5r);
3237         return;
3238       }
3239       clear_from_s5r_rbuf (s5r,
3240                            sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
3241       GNUNET_assert (0 == s5r->wbuf_len);
3242       s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
3243       s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
3244       s_hello->version = SOCKS_VERSION_5;
3245       s_hello->auth_method = SOCKS_AUTH_NONE;
3246       GNUNET_assert (NULL == s5r->wtask);
3247       s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3248                                                    s5r->sock,
3249                                                    &do_write, s5r);
3250       s5r->state = SOCKS5_REQUEST;
3251       return;
3252     case SOCKS5_REQUEST:
3253       c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
3254       if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
3255         return;
3256       switch (c_req->command)
3257       {
3258         case SOCKS5_CMD_TCP_STREAM:
3259           /* handled below */
3260           break;
3261         default:
3262           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3263                       _("Unsupported socks command %d\n"),
3264                       (int) c_req->command);
3265           signal_socks_failure (s5r,
3266                                 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
3267           return;
3268       }
3269       switch (c_req->addr_type)
3270       {
3271         case SOCKS5_AT_IPV4:
3272           {
3273             const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
3274             const uint16_t *port = (const uint16_t *) &v4[1];
3275             struct sockaddr_in *in;
3276
3277             s5r->port = ntohs (*port);
3278             alen = sizeof (struct in_addr);
3279             if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3280                 alen + sizeof (uint16_t))
3281               return; /* need more data */
3282             in = (struct sockaddr_in *) &s5r->destination_address;
3283             in->sin_family = AF_INET;
3284             in->sin_addr = *v4;
3285             in->sin_port = *port;
3286 #if HAVE_SOCKADDR_IN_SIN_LEN
3287             in->sin_len = sizeof (*in);
3288 #endif
3289             s5r->state = SOCKS5_DATA_TRANSFER;
3290           }
3291           break;
3292         case SOCKS5_AT_IPV6:
3293           {
3294             const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
3295             const uint16_t *port = (const uint16_t *) &v6[1];
3296             struct sockaddr_in6 *in;
3297
3298             s5r->port = ntohs (*port);
3299             alen = sizeof (struct in6_addr);
3300             if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3301                 alen + sizeof (uint16_t))
3302               return; /* need more data */
3303             in = (struct sockaddr_in6 *) &s5r->destination_address;
3304             in->sin6_family = AF_INET6;
3305             in->sin6_addr = *v6;
3306             in->sin6_port = *port;
3307 #if HAVE_SOCKADDR_IN_SIN_LEN
3308             in->sin6_len = sizeof (*in);
3309 #endif
3310             s5r->state = SOCKS5_DATA_TRANSFER;
3311           }
3312           break;
3313         case SOCKS5_AT_DOMAINNAME:
3314           {
3315             const uint8_t *dom_len;
3316             const char *dom_name;
3317             const uint16_t *port;
3318
3319             dom_len = (const uint8_t *) &c_req[1];
3320             alen = *dom_len + 1;
3321             if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3322                 alen + sizeof (uint16_t))
3323               return; /* need more data */
3324             dom_name = (const char *) &dom_len[1];
3325             port = (const uint16_t*) &dom_name[*dom_len];
3326             s5r->domain = GNUNET_strndup (dom_name,
3327                                           *dom_len);
3328             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3329                         "Requested connection is to %s:%d\n",
3330                         //(HTTPS_PORT == s5r->port) ? "s" : "",
3331                         s5r->domain,
3332                         ntohs (*port));
3333             s5r->state = SOCKS5_RESOLVING;
3334             s5r->port = ntohs (*port);
3335             s5r->is_tls = (HTTPS_PORT == s5r->port) ? GNUNET_YES : GNUNET_NO;
3336             s5r->gns_lookup = GNUNET_GNS_lookup_with_tld (gns_handle,
3337                                                           s5r->domain,
3338                                                           GNUNET_DNSPARSER_TYPE_A,
3339                                                           GNUNET_NO /* only cached */,
3340                                                           &handle_gns_result,
3341                                                           s5r);
3342             break;
3343           }
3344         default:
3345           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3346                       _("Unsupported socks address type %d\n"),
3347                       (int) c_req->addr_type);
3348           signal_socks_failure (s5r,
3349                                 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
3350           return;
3351       }
3352       clear_from_s5r_rbuf (s5r,
3353                            sizeof (struct Socks5ClientRequestMessage) +
3354                            alen + sizeof (uint16_t));
3355       if (0 != s5r->rbuf_len)
3356       {
3357         /* read more bytes than healthy, why did the client send more!? */
3358         GNUNET_break_op (0);
3359         signal_socks_failure (s5r,
3360                               SOCKS5_STATUS_GENERAL_FAILURE);
3361         return;
3362       }
3363       if (SOCKS5_DATA_TRANSFER == s5r->state)
3364       {
3365         /* if we are not waiting for GNS resolution, signal success */
3366         signal_socks_success (s5r);
3367       }
3368       /* We are done reading right now */
3369       GNUNET_SCHEDULER_cancel (s5r->rtask);
3370       s5r->rtask = NULL;
3371       return;
3372     case SOCKS5_RESOLVING:
3373       GNUNET_assert (0);
3374       return;
3375     case SOCKS5_DATA_TRANSFER:
3376       GNUNET_assert (0);
3377       return;
3378     default:
3379       GNUNET_assert (0);
3380       return;
3381   }
3382 }
3383
3384
3385 /**
3386  * Accept new incoming connections
3387  *
3388  * @param cls the closure with the lsock4 or lsock6
3389  * @param tc the scheduler context
3390  */
3391 static void
3392 do_accept (void *cls)
3393 {
3394   struct GNUNET_NETWORK_Handle *lsock = cls;
3395   struct GNUNET_NETWORK_Handle *s;
3396   struct Socks5Request *s5r;
3397
3398   GNUNET_assert (NULL != lsock);
3399   if (lsock == lsock4)
3400     ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3401                                             lsock,
3402                                             &do_accept,
3403                                             lsock);
3404   else if (lsock == lsock6)
3405     ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3406                                             lsock,
3407                                             &do_accept,
3408                                             lsock);
3409   else
3410     GNUNET_assert (0);
3411   s = GNUNET_NETWORK_socket_accept (lsock,
3412                                     NULL,
3413                                     NULL);
3414   if (NULL == s)
3415   {
3416     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3417                          "accept");
3418     return;
3419   }
3420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3421               "Got an inbound connection, waiting for data\n");
3422   s5r = GNUNET_new (struct Socks5Request);
3423   GNUNET_CONTAINER_DLL_insert (s5r_head,
3424                                s5r_tail,
3425                                s5r);
3426   s5r->sock = s;
3427   s5r->state = SOCKS5_INIT;
3428   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3429                                               s5r->sock,
3430                                               &do_s5r_read,
3431                                               s5r);
3432 }
3433
3434
3435 /* ******************* General / main code ********************* */
3436
3437
3438 /**
3439  * Task run on shutdown
3440  *
3441  * @param cls closure
3442  */
3443 static void
3444 do_shutdown (void *cls)
3445 {
3446   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3447               "Shutting down...\n");
3448   /* MHD requires resuming before destroying the daemons */
3449   for (struct Socks5Request *s5r = s5r_head;
3450        NULL != s5r;
3451        s5r = s5r->next)
3452   {
3453     if (s5r->suspended)
3454     {
3455       s5r->suspended = GNUNET_NO;
3456       MHD_resume_connection (s5r->con);
3457     }
3458   }
3459   while (NULL != mhd_httpd_head)
3460     kill_httpd (mhd_httpd_head);
3461   while (NULL != s5r_head)
3462     cleanup_s5r (s5r_head);
3463   if (NULL != lsock4)
3464   {
3465     GNUNET_NETWORK_socket_close (lsock4);
3466     lsock4 = NULL;
3467   }
3468   if (NULL != lsock6)
3469   {
3470     GNUNET_NETWORK_socket_close (lsock6);
3471     lsock6 = NULL;
3472   }
3473   if (NULL != curl_multi)
3474   {
3475     curl_multi_cleanup (curl_multi);
3476     curl_multi = NULL;
3477   }
3478   if (NULL != gns_handle)
3479   {
3480     GNUNET_GNS_disconnect (gns_handle);
3481     gns_handle = NULL;
3482   }
3483   if (NULL != curl_download_task)
3484   {
3485     GNUNET_SCHEDULER_cancel (curl_download_task);
3486     curl_download_task = NULL;
3487   }
3488   if (NULL != ltask4)
3489   {
3490     GNUNET_SCHEDULER_cancel (ltask4);
3491     ltask4 = NULL;
3492   }
3493   if (NULL != ltask6)
3494   {
3495     GNUNET_SCHEDULER_cancel (ltask6);
3496     ltask6 = NULL;
3497   }
3498   gnutls_x509_crt_deinit (proxy_ca.cert);
3499   gnutls_x509_privkey_deinit (proxy_ca.key);
3500   gnutls_global_deinit ();
3501 }
3502
3503
3504 /**
3505  * Create an IPv4 listen socket bound to our port.
3506  *
3507  * @return NULL on error
3508  */
3509 static struct GNUNET_NETWORK_Handle *
3510 bind_v4 ()
3511 {
3512   struct GNUNET_NETWORK_Handle *ls;
3513   struct sockaddr_in sa4;
3514   int eno;
3515
3516   memset (&sa4, 0, sizeof (sa4));
3517   sa4.sin_family = AF_INET;
3518   sa4.sin_port = htons (port);
3519 #if HAVE_SOCKADDR_IN_SIN_LEN
3520   sa4.sin_len = sizeof (sa4);
3521 #endif
3522   ls = GNUNET_NETWORK_socket_create (AF_INET,
3523                                      SOCK_STREAM,
3524                                      0);
3525   if (NULL == ls)
3526     return NULL;
3527   if (GNUNET_OK !=
3528       GNUNET_NETWORK_socket_bind (ls,
3529                                   (const struct sockaddr *) &sa4,
3530                                   sizeof (sa4)))
3531   {
3532     eno = errno;
3533     GNUNET_NETWORK_socket_close (ls);
3534     errno = eno;
3535     return NULL;
3536   }
3537   return ls;
3538 }
3539
3540
3541 /**
3542  * Create an IPv6 listen socket bound to our port.
3543  *
3544  * @return NULL on error
3545  */
3546 static struct GNUNET_NETWORK_Handle *
3547 bind_v6 ()
3548 {
3549   struct GNUNET_NETWORK_Handle *ls;
3550   struct sockaddr_in6 sa6;
3551   int eno;
3552
3553   memset (&sa6, 0, sizeof (sa6));
3554   sa6.sin6_family = AF_INET6;
3555   sa6.sin6_port = htons (port);
3556 #if HAVE_SOCKADDR_IN_SIN_LEN
3557   sa6.sin6_len = sizeof (sa6);
3558 #endif
3559   ls = GNUNET_NETWORK_socket_create (AF_INET6,
3560                                      SOCK_STREAM,
3561                                      0);
3562   if (NULL == ls)
3563     return NULL;
3564   if (GNUNET_OK !=
3565       GNUNET_NETWORK_socket_bind (ls,
3566                                   (const struct sockaddr *) &sa6,
3567                                   sizeof (sa6)))
3568   {
3569     eno = errno;
3570     GNUNET_NETWORK_socket_close (ls);
3571     errno = eno;
3572     return NULL;
3573   }
3574   return ls;
3575 }
3576
3577
3578 /**
3579  * Main function that will be run
3580  *
3581  * @param cls closure
3582  * @param args remaining command-line arguments
3583  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3584  * @param c configuration
3585  */
3586 static void
3587 run (void *cls,
3588      char *const *args,
3589      const char *cfgfile,
3590      const struct GNUNET_CONFIGURATION_Handle *c)
3591 {
3592   char* cafile_cfg = NULL;
3593   char* cafile;
3594   struct MhdHttpList *hd;
3595
3596   cfg = c;
3597
3598   if (NULL == (curl_multi = curl_multi_init ()))
3599   {
3600     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3601                 "Failed to create cURL multi handle!\n");
3602     return;
3603   }
3604   cafile = cafile_opt;
3605   if (NULL == cafile)
3606   {
3607     if (GNUNET_OK !=
3608         GNUNET_CONFIGURATION_get_value_filename (cfg,
3609                                                  "gns-proxy",
3610                                                  "PROXY_CACERT",
3611                                                  &cafile_cfg))
3612     {
3613       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3614                                  "gns-proxy",
3615                                  "PROXY_CACERT");
3616       return;
3617     }
3618     cafile = cafile_cfg;
3619   }
3620   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3621               "Using `%s' as CA\n",
3622               cafile);
3623
3624   gnutls_global_init ();
3625   gnutls_x509_crt_init (&proxy_ca.cert);
3626   gnutls_x509_privkey_init (&proxy_ca.key);
3627
3628   if ( (GNUNET_OK !=
3629         load_cert_from_file (proxy_ca.cert,
3630                              cafile)) ||
3631        (GNUNET_OK !=
3632         load_key_from_file (proxy_ca.key,
3633                             cafile)) )
3634   {
3635     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3636                 _("Failed to load X.509 key and certificate from `%s'\n"),
3637                 cafile);
3638     gnutls_x509_crt_deinit (proxy_ca.cert);
3639     gnutls_x509_privkey_deinit (proxy_ca.key);
3640     gnutls_global_deinit ();
3641     GNUNET_free_non_null (cafile_cfg);
3642     return;
3643   }
3644   GNUNET_free_non_null (cafile_cfg);
3645   if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3646   {
3647     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3648                 "Unable to connect to GNS!\n");
3649     gnutls_x509_crt_deinit (proxy_ca.cert);
3650     gnutls_x509_privkey_deinit (proxy_ca.key);
3651     gnutls_global_deinit ();
3652     return;
3653   }
3654   GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
3655                                  NULL);
3656
3657   /* Open listen socket for socks proxy */
3658   lsock6 = bind_v6 ();
3659   if (NULL == lsock6)
3660   {
3661     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3662                          "bind");
3663   }
3664   else
3665   {
3666     if (GNUNET_OK !=
3667         GNUNET_NETWORK_socket_listen (lsock6,
3668                                       5))
3669     {
3670       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3671                            "listen");
3672       GNUNET_NETWORK_socket_close (lsock6);
3673       lsock6 = NULL;
3674     }
3675     else
3676     {
3677       ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3678                                               lsock6,
3679                                               &do_accept,
3680                                               lsock6);
3681     }
3682   }
3683   lsock4 = bind_v4 ();
3684   if (NULL == lsock4)
3685   {
3686     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3687                          "bind");
3688   }
3689   else
3690   {
3691     if (GNUNET_OK !=
3692         GNUNET_NETWORK_socket_listen (lsock4,
3693                                       5))
3694     {
3695       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3696                            "listen");
3697       GNUNET_NETWORK_socket_close (lsock4);
3698       lsock4 = NULL;
3699     }
3700     else
3701     {
3702       ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3703                                               lsock4,
3704                                               &do_accept,
3705                                               lsock4);
3706     }
3707   }
3708   if ( (NULL == lsock4) &&
3709        (NULL == lsock6) )
3710   {
3711     GNUNET_SCHEDULER_shutdown ();
3712     return;
3713   }
3714   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3715   {
3716     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3717                 "cURL global init failed!\n");
3718     GNUNET_SCHEDULER_shutdown ();
3719     return;
3720   }
3721   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3722               "Proxy listens on port %u\n",
3723               (unsigned int) port);
3724
3725   /* start MHD daemon for HTTP */
3726   hd = GNUNET_new (struct MhdHttpList);
3727   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
3728                                  0,
3729                                  NULL, NULL,
3730                                  &create_response, hd,
3731                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3732                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3733                                  MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
3734                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3735                                  MHD_OPTION_END);
3736   if (NULL == hd->daemon)
3737   {
3738     GNUNET_free (hd);
3739     GNUNET_SCHEDULER_shutdown ();
3740     return;
3741   }
3742   httpd = hd;
3743   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
3744                                mhd_httpd_tail,
3745                                hd);
3746 }
3747
3748
3749 /**
3750  * The main function for gnunet-gns-proxy.
3751  *
3752  * @param argc number of arguments from the command line
3753  * @param argv command line arguments
3754  * @return 0 ok, 1 on error
3755  */
3756 int
3757 main (int argc,
3758       char *const *argv)
3759 {
3760   struct GNUNET_GETOPT_CommandLineOption options[] = {
3761     GNUNET_GETOPT_option_uint16 ('p',
3762                                  "port",
3763                                  NULL,
3764                                  gettext_noop ("listen on specified port (default: 7777)"),
3765                                  &port),
3766     GNUNET_GETOPT_option_string ('a',
3767                                  "authority",
3768                                  NULL,
3769                                  gettext_noop ("pem file to use as CA"),
3770                                  &cafile_opt),
3771     GNUNET_GETOPT_option_flag ('6',
3772                                "disable-ivp6",
3773                                gettext_noop ("disable use of IPv6"),
3774                                &disable_v6),
3775
3776     GNUNET_GETOPT_OPTION_END
3777   };
3778   static const char* page =
3779     "<html><head><title>gnunet-gns-proxy</title>"
3780     "</head><body>cURL fail</body></html>";
3781   int ret;
3782
3783   if (GNUNET_OK !=
3784       GNUNET_STRINGS_get_utf8_args (argc, argv,
3785                                     &argc, &argv))
3786     return 2;
3787   GNUNET_log_setup ("gnunet-gns-proxy",
3788                     "WARNING",
3789                     NULL);
3790   curl_failure_response
3791     = MHD_create_response_from_buffer (strlen (page),
3792                                        (void *) page,
3793                                        MHD_RESPMEM_PERSISTENT);
3794
3795   ret =
3796     (GNUNET_OK ==
3797      GNUNET_PROGRAM_run (argc, argv,
3798                          "gnunet-gns-proxy",
3799                          _("GNUnet GNS proxy"),
3800                          options,
3801                          &run, NULL)) ? 0 : 1;
3802   MHD_destroy_response (curl_failure_response);
3803   GNUNET_free_non_null ((char *) argv);
3804   return ret;
3805 }
3806
3807 /* end of gnunet-gns-proxy.c */