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