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