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