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