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