move ARM/config logic to util/ where it doesn't need to cast away a 'const' and is...
[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 (yet, FIXME!) */
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   curl_download_prepare();
1737   *con_cls = NULL;
1738 }
1739
1740
1741 /**
1742  * Function called when MHD first processes an incoming connection.
1743  * Gives us the respective URI information.
1744  *
1745  * We use this to associate the `struct MHD_Connection` with our
1746  * internal `struct Socks5Request` data structure (by checking
1747  * for matching sockets).
1748  *
1749  * @param cls the HTTP server handle (a `struct MhdHttpList`)
1750  * @param url the URL that is being requested
1751  * @param connection MHD connection object for the request
1752  * @return the `struct Socks5Request` that this @a connection is for
1753  */
1754 static void *
1755 mhd_log_callback (void *cls,
1756                   const char *url,
1757                   struct MHD_Connection *connection)
1758 {
1759   struct Socks5Request *s5r;
1760   const union MHD_ConnectionInfo *ci;
1761   int sock;
1762
1763   ci = MHD_get_connection_info (connection,
1764                                 MHD_CONNECTION_INFO_CONNECTION_FD);
1765   if (NULL == ci)
1766   {
1767     GNUNET_break (0);
1768     return NULL;
1769   }
1770   sock = ci->connect_fd;
1771   for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1772   {
1773     if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1774     {
1775       if (NULL != s5r->url)
1776       {
1777         GNUNET_break (0);
1778         return NULL;
1779       }
1780       s5r->url = GNUNET_strdup (url);
1781       GNUNET_SCHEDULER_cancel (s5r->timeout_task);
1782       s5r->timeout_task = NULL;
1783       return s5r;
1784     }
1785   }
1786   GNUNET_break (0);
1787   return NULL;
1788 }
1789
1790
1791 /**
1792  * Kill the given MHD daemon.
1793  *
1794  * @param hd daemon to stop
1795  */
1796 static void
1797 kill_httpd (struct MhdHttpList *hd)
1798 {
1799   GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1800                                mhd_httpd_tail,
1801                                hd);
1802   GNUNET_free_non_null (hd->domain);
1803   MHD_stop_daemon (hd->daemon);
1804   if (NULL != hd->httpd_task)
1805   {
1806     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1807     hd->httpd_task = NULL;
1808   }
1809   GNUNET_free_non_null (hd->proxy_cert);
1810   if (hd == httpd)
1811     httpd = NULL;
1812   GNUNET_free (hd);
1813 }
1814
1815
1816 /**
1817  * Task run whenever HTTP server is idle for too long. Kill it.
1818  *
1819  * @param cls the `struct MhdHttpList *`
1820  * @param tc sched context
1821  */
1822 static void
1823 kill_httpd_task (void *cls,
1824                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1825 {
1826   struct MhdHttpList *hd = cls;
1827
1828   hd->httpd_task = NULL;
1829   kill_httpd (hd);
1830 }
1831
1832
1833 /**
1834  * Task run whenever HTTP server operations are pending.
1835  *
1836  * @param cls the `struct MhdHttpList *` of the daemon that is being run
1837  * @param tc sched context
1838  */
1839 static void
1840 do_httpd (void *cls,
1841           const struct GNUNET_SCHEDULER_TaskContext *tc);
1842
1843
1844 /**
1845  * Schedule MHD.  This function should be called initially when an
1846  * MHD is first getting its client socket, and will then automatically
1847  * always be called later whenever there is work to be done.
1848  *
1849  * @param hd the daemon to schedule
1850  */
1851 static void
1852 schedule_httpd (struct MhdHttpList *hd)
1853 {
1854   fd_set rs;
1855   fd_set ws;
1856   fd_set es;
1857   struct GNUNET_NETWORK_FDSet *wrs;
1858   struct GNUNET_NETWORK_FDSet *wws;
1859   int max;
1860   int haveto;
1861   MHD_UNSIGNED_LONG_LONG timeout;
1862   struct GNUNET_TIME_Relative tv;
1863
1864   FD_ZERO (&rs);
1865   FD_ZERO (&ws);
1866   FD_ZERO (&es);
1867   max = -1;
1868   if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1869   {
1870     kill_httpd (hd);
1871     return;
1872   }
1873   haveto = MHD_get_timeout (hd->daemon, &timeout);
1874   if (MHD_YES == haveto)
1875     tv.rel_value_us = (uint64_t) timeout * 1000LL;
1876   else
1877     tv = GNUNET_TIME_UNIT_FOREVER_REL;
1878   if (-1 != max)
1879   {
1880     wrs = GNUNET_NETWORK_fdset_create ();
1881     wws = GNUNET_NETWORK_fdset_create ();
1882     GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1883     GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1884   }
1885   else
1886   {
1887     wrs = NULL;
1888     wws = NULL;
1889   }
1890   if (NULL != hd->httpd_task)
1891     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1892   if ( (MHD_YES != haveto) &&
1893        (-1 == max) &&
1894        (hd != httpd) )
1895   {
1896     /* daemon is idle, kill after timeout */
1897     hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
1898                                                    &kill_httpd_task,
1899                                                    hd);
1900   }
1901   else
1902   {
1903     hd->httpd_task =
1904       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1905                                    tv, wrs, wws,
1906                                    &do_httpd, hd);
1907   }
1908   if (NULL != wrs)
1909     GNUNET_NETWORK_fdset_destroy (wrs);
1910   if (NULL != wws)
1911     GNUNET_NETWORK_fdset_destroy (wws);
1912 }
1913
1914
1915 /**
1916  * Task run whenever HTTP server operations are pending.
1917  *
1918  * @param cls the `struct MhdHttpList` of the daemon that is being run
1919  * @param tc scheduler context
1920  */
1921 static void
1922 do_httpd (void *cls,
1923           const struct GNUNET_SCHEDULER_TaskContext *tc)
1924 {
1925   struct MhdHttpList *hd = cls;
1926
1927   hd->httpd_task = NULL;
1928   MHD_run (hd->daemon);
1929   schedule_httpd (hd);
1930 }
1931
1932
1933 /**
1934  * Run MHD now, we have extra data ready for the callback.
1935  *
1936  * @param hd the daemon to run now.
1937  */
1938 static void
1939 run_mhd_now (struct MhdHttpList *hd)
1940 {
1941   if (NULL !=
1942       hd->httpd_task)
1943     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1944   hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
1945                                              hd);
1946 }
1947
1948
1949 /**
1950  * Read file in filename
1951  *
1952  * @param filename file to read
1953  * @param size pointer where filesize is stored
1954  * @return NULL on error
1955  */
1956 static void*
1957 load_file (const char* filename,
1958            unsigned int* size)
1959 {
1960   void *buffer;
1961   uint64_t fsize;
1962
1963   if (GNUNET_OK !=
1964       GNUNET_DISK_file_size (filename, &fsize,
1965                              GNUNET_YES, GNUNET_YES))
1966     return NULL;
1967   if (fsize > MAX_PEM_SIZE)
1968     return NULL;
1969   *size = (unsigned int) fsize;
1970   buffer = GNUNET_malloc (*size);
1971   if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
1972   {
1973     GNUNET_free (buffer);
1974     return NULL;
1975   }
1976   return buffer;
1977 }
1978
1979
1980 /**
1981  * Load PEM key from file
1982  *
1983  * @param key where to store the data
1984  * @param keyfile path to the PEM file
1985  * @return #GNUNET_OK on success
1986  */
1987 static int
1988 load_key_from_file (gnutls_x509_privkey_t key,
1989                     const char* keyfile)
1990 {
1991   gnutls_datum_t key_data;
1992   int ret;
1993
1994   key_data.data = load_file (keyfile, &key_data.size);
1995   if (NULL == key_data.data)
1996     return GNUNET_SYSERR;
1997   ret = gnutls_x509_privkey_import (key, &key_data,
1998                                     GNUTLS_X509_FMT_PEM);
1999   if (GNUTLS_E_SUCCESS != ret)
2000   {
2001     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2002                 _("Unable to import private key from file `%s'\n"),
2003                 keyfile);
2004   }
2005   GNUNET_free_non_null (key_data.data);
2006   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2007 }
2008
2009
2010 /**
2011  * Load cert from file
2012  *
2013  * @param crt struct to store data in
2014  * @param certfile path to pem file
2015  * @return #GNUNET_OK on success
2016  */
2017 static int
2018 load_cert_from_file (gnutls_x509_crt_t crt,
2019                      const char* certfile)
2020 {
2021   gnutls_datum_t cert_data;
2022   int ret;
2023
2024   cert_data.data = load_file (certfile, &cert_data.size);
2025   if (NULL == cert_data.data)
2026     return GNUNET_SYSERR;
2027   ret = gnutls_x509_crt_import (crt, &cert_data,
2028                                 GNUTLS_X509_FMT_PEM);
2029   if (GNUTLS_E_SUCCESS != ret)
2030   {
2031     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2032                _("Unable to import certificate %s\n"), certfile);
2033   }
2034   GNUNET_free_non_null (cert_data.data);
2035   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2036 }
2037
2038
2039 /**
2040  * Generate new certificate for specific name
2041  *
2042  * @param name the subject name to generate a cert for
2043  * @return a struct holding the PEM data, NULL on error
2044  */
2045 static struct ProxyGNSCertificate *
2046 generate_gns_certificate (const char *name)
2047 {
2048   unsigned int serial;
2049   size_t key_buf_size;
2050   size_t cert_buf_size;
2051   gnutls_x509_crt_t request;
2052   time_t etime;
2053   struct tm *tm_data;
2054   struct ProxyGNSCertificate *pgc;
2055
2056   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2057               "Generating TLS/SSL certificate for `%s'\n",
2058               name);
2059   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2060   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2061   pgc = GNUNET_new (struct ProxyGNSCertificate);
2062   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2063                                  0, "ZZ", 2);
2064   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2065                                  0, "GNU Name System", 4);
2066   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2067                                  0, name, strlen (name));
2068   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
2069   gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2070   gnutls_x509_crt_set_serial (request,
2071                               &serial,
2072                               sizeof (serial));
2073   etime = time (NULL);
2074   tm_data = localtime (&etime);
2075   gnutls_x509_crt_set_activation_time (request,
2076                                        etime);
2077   tm_data->tm_year++;
2078   etime = mktime (tm_data);
2079   gnutls_x509_crt_set_expiration_time (request,
2080                                        etime);
2081   gnutls_x509_crt_sign (request,
2082                         proxy_ca.cert,
2083                         proxy_ca.key);
2084   key_buf_size = sizeof (pgc->key);
2085   cert_buf_size = sizeof (pgc->cert);
2086   gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2087                           pgc->cert, &cert_buf_size);
2088   gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2089                               pgc->key, &key_buf_size);
2090   gnutls_x509_crt_deinit (request);
2091   return pgc;
2092 }
2093
2094
2095 /**
2096  * Function called by MHD with errors, suppresses them all.
2097  *
2098  * @param cls closure
2099  * @param fm format string (`printf()`-style)
2100  * @param ap arguments to @a fm
2101  */
2102 static void
2103 mhd_error_log_callback (void *cls,
2104                         const char *fm,
2105                         va_list ap)
2106 {
2107   /* do nothing */
2108 }
2109
2110
2111 /**
2112  * Lookup (or create) an SSL MHD instance for a particular domain.
2113  *
2114  * @param domain the domain the SSL daemon has to serve
2115  * @return NULL on error
2116  */
2117 static struct MhdHttpList *
2118 lookup_ssl_httpd (const char* domain)
2119 {
2120   struct MhdHttpList *hd;
2121   struct ProxyGNSCertificate *pgc;
2122
2123   if (NULL == domain)
2124   {
2125     GNUNET_break (0);
2126     return NULL;
2127   }
2128   for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2129     if ( (NULL != hd->domain) &&
2130          (0 == strcmp (hd->domain, domain)) )
2131       return hd;
2132   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2133               "Starting fresh MHD HTTPS instance for domain `%s'\n",
2134               domain);
2135   pgc = generate_gns_certificate (domain);
2136   hd = GNUNET_new (struct MhdHttpList);
2137   hd->is_ssl = GNUNET_YES;
2138   hd->domain = GNUNET_strdup (domain);
2139   hd->proxy_cert = pgc;
2140   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
2141                                  0,
2142                                  NULL, NULL,
2143                                  &create_response, hd,
2144                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2145                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2146                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2147                                  MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2148                                  MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2149                                  MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2150                                  MHD_OPTION_END);
2151   if (NULL == hd->daemon)
2152   {
2153     GNUNET_free (pgc);
2154     GNUNET_free (hd);
2155     return NULL;
2156   }
2157   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2158                                mhd_httpd_tail,
2159                                hd);
2160   return hd;
2161 }
2162
2163
2164 /**
2165  * Task run when a Socks5Request somehow fails to be associated with
2166  * an MHD connection (i.e. because the client never speaks HTTP after
2167  * the SOCKS5 handshake).  Clean up.
2168  *
2169  * @param cls the `struct Socks5Request *`
2170  * @param tc sched context
2171  */
2172 static void
2173 timeout_s5r_handshake (void *cls,
2174                        const struct GNUNET_SCHEDULER_TaskContext *tc)
2175 {
2176   struct Socks5Request *s5r = cls;
2177
2178   s5r->timeout_task = NULL;
2179   cleanup_s5r (s5r);
2180 }
2181
2182
2183 /**
2184  * We're done with the Socks5 protocol, now we need to pass the
2185  * connection data through to the final destination, either
2186  * direct (if the protocol might not be HTTP), or via MHD
2187  * (if the port looks like it should be HTTP).
2188  *
2189  * @param s5r socks request that has reached the final stage
2190  */
2191 static void
2192 setup_data_transfer (struct Socks5Request *s5r)
2193 {
2194   struct MhdHttpList *hd;
2195   int fd;
2196   const struct sockaddr *addr;
2197   socklen_t len;
2198
2199   switch (s5r->port)
2200   {
2201   case HTTPS_PORT:
2202     hd = lookup_ssl_httpd (s5r->domain);
2203     if (NULL == hd)
2204     {
2205       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2206                   _("Failed to start HTTPS server for `%s'\n"),
2207                   s5r->domain);
2208       cleanup_s5r (s5r);
2209       return;
2210     }
2211     break;
2212   case HTTP_PORT:
2213   default:
2214     GNUNET_assert (NULL != httpd);
2215     hd = httpd;
2216     break;
2217   }
2218   fd = GNUNET_NETWORK_get_fd (s5r->sock);
2219   addr = GNUNET_NETWORK_get_addr (s5r->sock);
2220   len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2221   s5r->state = SOCKS5_SOCKET_WITH_MHD;
2222   if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
2223   {
2224     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2225                 _("Failed to pass client to MHD\n"));
2226     cleanup_s5r (s5r);
2227     return;
2228   }
2229   s5r->hd = hd;
2230   schedule_httpd (hd);
2231   s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2232                                                     &timeout_s5r_handshake,
2233                                                     s5r);
2234 }
2235
2236
2237 /* ********************* SOCKS handling ************************* */
2238
2239
2240 /**
2241  * Write data from buffer to socks5 client, then continue with state machine.
2242  *
2243  * @param cls the closure with the `struct Socks5Request`
2244  * @param tc scheduler context
2245  */
2246 static void
2247 do_write (void *cls,
2248           const struct GNUNET_SCHEDULER_TaskContext *tc)
2249 {
2250   struct Socks5Request *s5r = cls;
2251   ssize_t len;
2252
2253   s5r->wtask = NULL;
2254   len = GNUNET_NETWORK_socket_send (s5r->sock,
2255                                     s5r->wbuf,
2256                                     s5r->wbuf_len);
2257   if (len <= 0)
2258   {
2259     /* write error: connection closed, shutdown, etc.; just clean up */
2260     cleanup_s5r (s5r);
2261     return;
2262   }
2263   memmove (s5r->wbuf,
2264            &s5r->wbuf[len],
2265            s5r->wbuf_len - len);
2266   s5r->wbuf_len -= len;
2267   if (s5r->wbuf_len > 0)
2268   {
2269     /* not done writing */
2270     s5r->wtask =
2271       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2272                                       s5r->sock,
2273                                       &do_write, s5r);
2274     return;
2275   }
2276
2277   /* we're done writing, continue with state machine! */
2278
2279   switch (s5r->state)
2280   {
2281   case SOCKS5_INIT:
2282     GNUNET_assert (0);
2283     break;
2284   case SOCKS5_REQUEST:
2285     GNUNET_assert (NULL != s5r->rtask);
2286     break;
2287   case SOCKS5_DATA_TRANSFER:
2288     setup_data_transfer (s5r);
2289     return;
2290   case SOCKS5_WRITE_THEN_CLEANUP:
2291     cleanup_s5r (s5r);
2292     return;
2293   default:
2294     GNUNET_break (0);
2295     break;
2296   }
2297 }
2298
2299
2300 /**
2301  * Return a server response message indicating a failure to the client.
2302  *
2303  * @param s5r request to return failure code for
2304  * @param sc status code to return
2305  */
2306 static void
2307 signal_socks_failure (struct Socks5Request *s5r,
2308                       enum Socks5StatusCode sc)
2309 {
2310   struct Socks5ServerResponseMessage *s_resp;
2311
2312   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2313   memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2314   s_resp->version = SOCKS_VERSION_5;
2315   s_resp->reply = sc;
2316   s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2317   if (NULL != s5r->wtask)
2318     s5r->wtask =
2319       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2320                                       s5r->sock,
2321                                       &do_write, s5r);
2322 }
2323
2324
2325 /**
2326  * Return a server response message indicating success.
2327  *
2328  * @param s5r request to return success status message for
2329  */
2330 static void
2331 signal_socks_success (struct Socks5Request *s5r)
2332 {
2333   struct Socks5ServerResponseMessage *s_resp;
2334
2335   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2336   s_resp->version = SOCKS_VERSION_5;
2337   s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2338   s_resp->reserved = 0;
2339   s_resp->addr_type = SOCKS5_AT_IPV4;
2340   /* zero out IPv4 address and port */
2341   memset (&s_resp[1],
2342           0,
2343           sizeof (struct in_addr) + sizeof (uint16_t));
2344   s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2345     sizeof (struct in_addr) + sizeof (uint16_t);
2346   if (NULL == s5r->wtask)
2347     s5r->wtask =
2348       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2349                                       s5r->sock,
2350                                       &do_write, s5r);
2351 }
2352
2353
2354 /**
2355  * Process GNS results for target domain.
2356  *
2357  * @param cls the `struct Socks5Request *`
2358  * @param rd_count number of records returned
2359  * @param rd record data
2360  */
2361 static void
2362 handle_gns_result (void *cls,
2363                    uint32_t rd_count,
2364                    const struct GNUNET_GNSRECORD_Data *rd)
2365 {
2366   struct Socks5Request *s5r = cls;
2367   uint32_t i;
2368   const struct GNUNET_GNSRECORD_Data *r;
2369   int got_ip;
2370
2371   s5r->gns_lookup = NULL;
2372   got_ip = GNUNET_NO;
2373   for (i=0;i<rd_count;i++)
2374   {
2375     r = &rd[i];
2376     switch (r->record_type)
2377     {
2378     case GNUNET_DNSPARSER_TYPE_A:
2379       {
2380         struct sockaddr_in *in;
2381
2382         if (sizeof (struct in_addr) != r->data_size)
2383         {
2384           GNUNET_break_op (0);
2385           break;
2386         }
2387         if (GNUNET_YES == got_ip)
2388           break;
2389         if (GNUNET_OK !=
2390             GNUNET_NETWORK_test_pf (PF_INET))
2391           break;
2392         got_ip = GNUNET_YES;
2393         in = (struct sockaddr_in *) &s5r->destination_address;
2394         in->sin_family = AF_INET;
2395         memcpy (&in->sin_addr,
2396                 r->data,
2397                 r->data_size);
2398         in->sin_port = htons (s5r->port);
2399 #if HAVE_SOCKADDR_IN_SIN_LEN
2400         in->sin_len = sizeof (*in);
2401 #endif
2402       }
2403       break;
2404     case GNUNET_DNSPARSER_TYPE_AAAA:
2405       {
2406         struct sockaddr_in6 *in;
2407
2408         if (sizeof (struct in6_addr) != r->data_size)
2409         {
2410           GNUNET_break_op (0);
2411           break;
2412         }
2413         if (GNUNET_YES == got_ip)
2414           break;
2415         if (GNUNET_OK !=
2416             GNUNET_NETWORK_test_pf (PF_INET))
2417           break;
2418         /* FIXME: allow user to disable IPv6 per configuration option... */
2419         got_ip = GNUNET_YES;
2420         in = (struct sockaddr_in6 *) &s5r->destination_address;
2421         in->sin6_family = AF_INET6;
2422         memcpy (&in->sin6_addr,
2423                 r->data,
2424                 r->data_size);
2425         in->sin6_port = htons (s5r->port);
2426 #if HAVE_SOCKADDR_IN_SIN_LEN
2427         in->sin6_len = sizeof (*in);
2428 #endif
2429       }
2430       break;
2431     case GNUNET_GNSRECORD_TYPE_VPN:
2432       GNUNET_break (0); /* should have been translated within GNS */
2433       break;
2434     case GNUNET_GNSRECORD_TYPE_LEHO:
2435       GNUNET_free_non_null (s5r->leho);
2436       s5r->leho = GNUNET_strndup (r->data,
2437                                   r->data_size);
2438       break;
2439     case GNUNET_GNSRECORD_TYPE_BOX:
2440       {
2441         const struct GNUNET_GNSRECORD_BoxRecord *box;
2442
2443         if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
2444         {
2445           GNUNET_break_op (0);
2446           break;
2447         }
2448         box = r->data;
2449         if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
2450              (ntohs (box->protocol) != IPPROTO_TCP) ||
2451              (ntohs (box->service) != s5r->port) )
2452           break; /* BOX record does not apply */
2453         GNUNET_free_non_null (s5r->dane_data);
2454         s5r->dane_data_len = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
2455         s5r->dane_data = GNUNET_malloc (s5r->dane_data_len);
2456         memcpy (s5r->dane_data,
2457                 &box[1],
2458                 s5r->dane_data_len);
2459         break;
2460       }
2461     default:
2462       /* don't care */
2463       break;
2464     }
2465   }
2466   if (GNUNET_YES != got_ip)
2467   {
2468     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2469                 "Name resolution failed to yield useful IP address.\n");
2470     signal_socks_failure (s5r,
2471                           SOCKS5_STATUS_GENERAL_FAILURE);
2472     return;
2473   }
2474   s5r->state = SOCKS5_DATA_TRANSFER;
2475   signal_socks_success (s5r);
2476 }
2477
2478
2479 /**
2480  * Remove the first @a len bytes from the beginning of the read buffer.
2481  *
2482  * @param s5r the handle clear the read buffer for
2483  * @param len number of bytes in read buffer to advance
2484  */
2485 static void
2486 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2487                      size_t len)
2488 {
2489   GNUNET_assert (len <= s5r->rbuf_len);
2490   memmove (s5r->rbuf,
2491            &s5r->rbuf[len],
2492            s5r->rbuf_len - len);
2493   s5r->rbuf_len -= len;
2494 }
2495
2496
2497 /**
2498  * Read data from incoming Socks5 connection
2499  *
2500  * @param cls the closure with the `struct Socks5Request`
2501  * @param tc the scheduler context
2502  */
2503 static void
2504 do_s5r_read (void *cls,
2505              const struct GNUNET_SCHEDULER_TaskContext *tc)
2506 {
2507   struct Socks5Request *s5r = cls;
2508   const struct Socks5ClientHelloMessage *c_hello;
2509   struct Socks5ServerHelloMessage *s_hello;
2510   const struct Socks5ClientRequestMessage *c_req;
2511   ssize_t rlen;
2512   size_t alen;
2513
2514   s5r->rtask = NULL;
2515   if ( (NULL != tc->read_ready) &&
2516        (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2517   {
2518     rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2519                                        &s5r->rbuf[s5r->rbuf_len],
2520                                        sizeof (s5r->rbuf) - s5r->rbuf_len);
2521     if (rlen <= 0)
2522     {
2523       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2524                   "socks5 client disconnected.\n");
2525       cleanup_s5r (s5r);
2526       return;
2527     }
2528     s5r->rbuf_len += rlen;
2529   }
2530   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2531                                               s5r->sock,
2532                                               &do_s5r_read, s5r);
2533   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2534               "Processing %u bytes of socks data in state %d\n",
2535               s5r->rbuf_len,
2536               s5r->state);
2537   switch (s5r->state)
2538   {
2539   case SOCKS5_INIT:
2540     c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2541     if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2542          (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2543       return; /* need more data */
2544     if (SOCKS_VERSION_5 != c_hello->version)
2545     {
2546       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2547                   _("Unsupported socks version %d\n"),
2548                   (int) c_hello->version);
2549       cleanup_s5r (s5r);
2550       return;
2551     }
2552     clear_from_s5r_rbuf (s5r,
2553                          sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2554     GNUNET_assert (0 == s5r->wbuf_len);
2555     s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2556     s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2557     s_hello->version = SOCKS_VERSION_5;
2558     s_hello->auth_method = SOCKS_AUTH_NONE;
2559     GNUNET_assert (NULL == s5r->wtask);
2560     s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2561                                                  s5r->sock,
2562                                                  &do_write, s5r);
2563     s5r->state = SOCKS5_REQUEST;
2564     return;
2565   case SOCKS5_REQUEST:
2566     c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2567     if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2568       return;
2569     switch (c_req->command)
2570     {
2571     case SOCKS5_CMD_TCP_STREAM:
2572       /* handled below */
2573       break;
2574     default:
2575       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2576                   _("Unsupported socks command %d\n"),
2577                   (int) c_req->command);
2578       signal_socks_failure (s5r,
2579                             SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2580       return;
2581     }
2582     switch (c_req->addr_type)
2583     {
2584     case SOCKS5_AT_IPV4:
2585       {
2586         const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2587         const uint16_t *port = (const uint16_t *) &v4[1];
2588         struct sockaddr_in *in;
2589
2590         s5r->port = ntohs (*port);
2591         if (HTTPS_PORT == s5r->port)
2592         {
2593           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2594                       _("SSL connection to plain IPv4 address requested\n"));
2595           signal_socks_failure (s5r,
2596                                 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2597           return;
2598         }
2599         alen = sizeof (struct in_addr);
2600         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2601             alen + sizeof (uint16_t))
2602           return; /* need more data */
2603         in = (struct sockaddr_in *) &s5r->destination_address;
2604         in->sin_family = AF_INET;
2605         in->sin_addr = *v4;
2606         in->sin_port = *port;
2607 #if HAVE_SOCKADDR_IN_SIN_LEN
2608         in->sin_len = sizeof (*in);
2609 #endif
2610         s5r->state = SOCKS5_DATA_TRANSFER;
2611       }
2612       break;
2613     case SOCKS5_AT_IPV6:
2614       {
2615         const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2616         const uint16_t *port = (const uint16_t *) &v6[1];
2617         struct sockaddr_in6 *in;
2618
2619         s5r->port = ntohs (*port);
2620         if (HTTPS_PORT == s5r->port)
2621         {
2622           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2623                       _("SSL connection to plain IPv4 address requested\n"));
2624           signal_socks_failure (s5r,
2625                                 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2626           return;
2627         }
2628         alen = sizeof (struct in6_addr);
2629         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2630             alen + sizeof (uint16_t))
2631           return; /* need more data */
2632         in = (struct sockaddr_in6 *) &s5r->destination_address;
2633         in->sin6_family = AF_INET6;
2634         in->sin6_addr = *v6;
2635         in->sin6_port = *port;
2636 #if HAVE_SOCKADDR_IN_SIN_LEN
2637         in->sin6_len = sizeof (*in);
2638 #endif
2639         s5r->state = SOCKS5_DATA_TRANSFER;
2640       }
2641       break;
2642     case SOCKS5_AT_DOMAINNAME:
2643       {
2644         const uint8_t *dom_len;
2645         const char *dom_name;
2646         const uint16_t *port;
2647
2648         dom_len = (const uint8_t *) &c_req[1];
2649         alen = *dom_len + 1;
2650         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2651             alen + sizeof (uint16_t))
2652           return; /* need more data */
2653         dom_name = (const char *) &dom_len[1];
2654         port = (const uint16_t*) &dom_name[*dom_len];
2655         s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2656         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2657                     "Requested connection is to %s:%d\n",
2658                     s5r->domain,
2659                     ntohs (*port));
2660         s5r->state = SOCKS5_RESOLVING;
2661         s5r->port = ntohs (*port);
2662         s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2663                                              s5r->domain,
2664                                              &local_gns_zone,
2665                                              GNUNET_DNSPARSER_TYPE_A,
2666                                              GNUNET_NO /* only cached */,
2667                                              (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2668                                              &handle_gns_result,
2669                                              s5r);
2670         break;
2671       }
2672     default:
2673       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2674                   _("Unsupported socks address type %d\n"),
2675                   (int) c_req->addr_type);
2676       signal_socks_failure (s5r,
2677                             SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2678       return;
2679     }
2680     clear_from_s5r_rbuf (s5r,
2681                          sizeof (struct Socks5ClientRequestMessage) +
2682                          alen + sizeof (uint16_t));
2683     if (0 != s5r->rbuf_len)
2684     {
2685       /* read more bytes than healthy, why did the client send more!? */
2686       GNUNET_break_op (0);
2687       signal_socks_failure (s5r,
2688                             SOCKS5_STATUS_GENERAL_FAILURE);
2689       return;
2690     }
2691     if (SOCKS5_DATA_TRANSFER == s5r->state)
2692     {
2693       /* if we are not waiting for GNS resolution, signal success */
2694       signal_socks_success (s5r);
2695     }
2696     /* We are done reading right now */
2697     GNUNET_SCHEDULER_cancel (s5r->rtask);
2698     s5r->rtask = NULL;
2699     return;
2700   case SOCKS5_RESOLVING:
2701     GNUNET_assert (0);
2702     return;
2703   case SOCKS5_DATA_TRANSFER:
2704     GNUNET_assert (0);
2705     return;
2706   default:
2707     GNUNET_assert (0);
2708     return;
2709   }
2710 }
2711
2712
2713 /**
2714  * Accept new incoming connections
2715  *
2716  * @param cls the closure with the lsock4 or lsock6
2717  * @param tc the scheduler context
2718  */
2719 static void
2720 do_accept (void *cls,
2721            const struct GNUNET_SCHEDULER_TaskContext *tc)
2722 {
2723   struct GNUNET_NETWORK_Handle *lsock = cls;
2724   struct GNUNET_NETWORK_Handle *s;
2725   struct Socks5Request *s5r;
2726
2727   if (lsock == lsock4)
2728     ltask4 = NULL;
2729   else
2730     ltask6 = NULL;
2731   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2732     return;
2733   if (lsock == lsock4)
2734     ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2735                                             lsock,
2736                                             &do_accept, lsock);
2737   else
2738     ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2739                                             lsock,
2740                                             &do_accept, lsock);
2741   s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2742   if (NULL == s)
2743   {
2744     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2745     return;
2746   }
2747   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2748               "Got an inbound connection, waiting for data\n");
2749   s5r = GNUNET_new (struct Socks5Request);
2750   GNUNET_CONTAINER_DLL_insert (s5r_head,
2751                                s5r_tail,
2752                                s5r);
2753   s5r->sock = s;
2754   s5r->state = SOCKS5_INIT;
2755   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2756                                               s5r->sock,
2757                                               &do_s5r_read, s5r);
2758 }
2759
2760
2761 /* ******************* General / main code ********************* */
2762
2763
2764 /**
2765  * Task run on shutdown
2766  *
2767  * @param cls closure
2768  * @param tc task context
2769  */
2770 static void
2771 do_shutdown (void *cls,
2772              const struct GNUNET_SCHEDULER_TaskContext *tc)
2773 {
2774   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2775               "Shutting down...\n");
2776   while (NULL != mhd_httpd_head)
2777     kill_httpd (mhd_httpd_head);
2778   while (NULL != s5r_head)
2779     cleanup_s5r (s5r_head);
2780   if (NULL != lsock4)
2781   {
2782     GNUNET_NETWORK_socket_close (lsock4);
2783     lsock4 = NULL;
2784   }
2785   if (NULL != lsock6)
2786   {
2787     GNUNET_NETWORK_socket_close (lsock6);
2788     lsock6 = NULL;
2789   }
2790   if (NULL != id_op)
2791   {
2792     GNUNET_IDENTITY_cancel (id_op);
2793     id_op = NULL;
2794   }
2795   if (NULL != identity)
2796   {
2797     GNUNET_IDENTITY_disconnect (identity);
2798     identity = NULL;
2799   }
2800   if (NULL != curl_multi)
2801   {
2802     curl_multi_cleanup (curl_multi);
2803     curl_multi = NULL;
2804   }
2805   if (NULL != gns_handle)
2806   {
2807     GNUNET_GNS_disconnect (gns_handle);
2808     gns_handle = NULL;
2809   }
2810   if (NULL != curl_download_task)
2811   {
2812     GNUNET_SCHEDULER_cancel (curl_download_task);
2813     curl_download_task = NULL;
2814   }
2815   if (NULL != ltask4)
2816   {
2817     GNUNET_SCHEDULER_cancel (ltask4);
2818     ltask4 = NULL;
2819   }
2820   if (NULL != ltask6)
2821   {
2822     GNUNET_SCHEDULER_cancel (ltask6);
2823     ltask6 = NULL;
2824   }
2825   gnutls_x509_crt_deinit (proxy_ca.cert);
2826   gnutls_x509_privkey_deinit (proxy_ca.key);
2827   gnutls_global_deinit ();
2828 }
2829
2830
2831 /**
2832  * Create an IPv4 listen socket bound to our port.
2833  *
2834  * @return NULL on error
2835  */
2836 static struct GNUNET_NETWORK_Handle *
2837 bind_v4 ()
2838 {
2839   struct GNUNET_NETWORK_Handle *ls;
2840   struct sockaddr_in sa4;
2841   int eno;
2842
2843   memset (&sa4, 0, sizeof (sa4));
2844   sa4.sin_family = AF_INET;
2845   sa4.sin_port = htons (port);
2846 #if HAVE_SOCKADDR_IN_SIN_LEN
2847   sa4.sin_len = sizeof (sa4);
2848 #endif
2849   ls = GNUNET_NETWORK_socket_create (AF_INET,
2850                                      SOCK_STREAM,
2851                                      0);
2852   if (NULL == ls)
2853     return NULL;
2854   if (GNUNET_OK !=
2855       GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
2856                                   sizeof (sa4)))
2857   {
2858     eno = errno;
2859     GNUNET_NETWORK_socket_close (ls);
2860     errno = eno;
2861     return NULL;
2862   }
2863   return ls;
2864 }
2865
2866
2867 /**
2868  * Create an IPv6 listen socket bound to our port.
2869  *
2870  * @return NULL on error
2871  */
2872 static struct GNUNET_NETWORK_Handle *
2873 bind_v6 ()
2874 {
2875   struct GNUNET_NETWORK_Handle *ls;
2876   struct sockaddr_in6 sa6;
2877   int eno;
2878
2879   memset (&sa6, 0, sizeof (sa6));
2880   sa6.sin6_family = AF_INET6;
2881   sa6.sin6_port = htons (port);
2882 #if HAVE_SOCKADDR_IN_SIN_LEN
2883   sa6.sin6_len = sizeof (sa6);
2884 #endif
2885   ls = GNUNET_NETWORK_socket_create (AF_INET6,
2886                                      SOCK_STREAM,
2887                                      0);
2888   if (NULL == ls)
2889     return NULL;
2890   if (GNUNET_OK !=
2891       GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
2892                                   sizeof (sa6)))
2893   {
2894     eno = errno;
2895     GNUNET_NETWORK_socket_close (ls);
2896     errno = eno;
2897     return NULL;
2898   }
2899   return ls;
2900 }
2901
2902
2903 /**
2904  * Continue initialization after we have our zone information.
2905  */
2906 static void
2907 run_cont ()
2908 {
2909   struct MhdHttpList *hd;
2910
2911   /* Open listen socket for socks proxy */
2912   lsock6 = bind_v6 ();
2913   if (NULL == lsock6)
2914     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2915   else
2916   {
2917     if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
2918     {
2919       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2920       GNUNET_NETWORK_socket_close (lsock6);
2921       lsock6 = NULL;
2922     }
2923     else
2924     {
2925       ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2926                                               lsock6, &do_accept, lsock6);
2927     }
2928   }
2929   lsock4 = bind_v4 ();
2930   if (NULL == lsock4)
2931     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2932   else
2933   {
2934     if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
2935     {
2936       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2937       GNUNET_NETWORK_socket_close (lsock4);
2938       lsock4 = NULL;
2939     }
2940     else
2941     {
2942       ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2943                                               lsock4, &do_accept, lsock4);
2944     }
2945   }
2946   if ( (NULL == lsock4) &&
2947        (NULL == lsock6) )
2948   {
2949     GNUNET_SCHEDULER_shutdown ();
2950     return;
2951   }
2952   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
2953   {
2954     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2955                 "cURL global init failed!\n");
2956     GNUNET_SCHEDULER_shutdown ();
2957     return;
2958   }
2959   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2960               "Proxy listens on port %u\n",
2961               port);
2962
2963   /* start MHD daemon for HTTP */
2964   hd = GNUNET_new (struct MhdHttpList);
2965   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
2966                                  0,
2967                                  NULL, NULL,
2968                                  &create_response, hd,
2969                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2970                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2971                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2972                                  MHD_OPTION_END);
2973   if (NULL == hd->daemon)
2974   {
2975     GNUNET_free (hd);
2976     GNUNET_SCHEDULER_shutdown ();
2977     return;
2978   }
2979   httpd = hd;
2980   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2981 }
2982
2983
2984 /**
2985  * Method called to inform about the egos of the shorten zone of this peer.
2986  *
2987  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2988  * this function is only called ONCE, and 'NULL' being passed in
2989  * @a ego does indicate an error (i.e. name is taken or no default
2990  * value is known).  If @a ego is non-NULL and if '*ctx'
2991  * is set in those callbacks, the value WILL be passed to a subsequent
2992  * call to the identity callback of #GNUNET_IDENTITY_connect (if
2993  * that one was not NULL).
2994  *
2995  * @param cls closure, NULL
2996  * @param ego ego handle
2997  * @param ctx context for application to store data for this ego
2998  *                 (during the lifetime of this process, initially NULL)
2999  * @param name name assigned by the user for this ego,
3000  *                   NULL if the user just deleted the ego and it
3001  *                   must thus no longer be used
3002  */
3003 static void
3004 identity_shorten_cb (void *cls,
3005                      struct GNUNET_IDENTITY_Ego *ego,
3006                      void **ctx,
3007                      const char *name)
3008 {
3009   id_op = NULL;
3010   if (NULL == ego)
3011   {
3012     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3013                 _("No ego configured for `shorten-zone`\n"));
3014   }
3015   else
3016   {
3017     local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
3018     do_shorten = GNUNET_YES;
3019   }
3020   run_cont ();
3021 }
3022
3023
3024 /**
3025  * Method called to inform about the egos of the master zone of this peer.
3026  *
3027  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
3028  * this function is only called ONCE, and 'NULL' being passed in
3029  * @a ego does indicate an error (i.e. name is taken or no default
3030  * value is known).  If @a ego is non-NULL and if '*ctx'
3031  * is set in those callbacks, the value WILL be passed to a subsequent
3032  * call to the identity callback of #GNUNET_IDENTITY_connect (if
3033  * that one was not NULL).
3034  *
3035  * @param cls closure, NULL
3036  * @param ego ego handle
3037  * @param ctx context for application to store data for this ego
3038  *                 (during the lifetime of this process, initially NULL)
3039  * @param name name assigned by the user for this ego,
3040  *                   NULL if the user just deleted the ego and it
3041  *                   must thus no longer be used
3042  */
3043 static void
3044 identity_master_cb (void *cls,
3045                     struct GNUNET_IDENTITY_Ego *ego,
3046                     void **ctx,
3047                     const char *name)
3048 {
3049   id_op = NULL;
3050   if (NULL == ego)
3051   {
3052     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3053                 _("No ego configured for `%s`\n"),
3054                 "gns-proxy");
3055     GNUNET_SCHEDULER_shutdown ();
3056     return;
3057   }
3058   GNUNET_IDENTITY_ego_get_public_key (ego,
3059                                       &local_gns_zone);
3060   id_op = GNUNET_IDENTITY_get (identity,
3061                                "gns-short",
3062                                &identity_shorten_cb,
3063                                NULL);
3064 }
3065
3066
3067 /**
3068  * Main function that will be run
3069  *
3070  * @param cls closure
3071  * @param args remaining command-line arguments
3072  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3073  * @param c configuration
3074  */
3075 static void
3076 run (void *cls, char *const *args, const char *cfgfile,
3077      const struct GNUNET_CONFIGURATION_Handle *c)
3078 {
3079   char* cafile_cfg = NULL;
3080   char* cafile;
3081
3082   cfg = c;
3083
3084   if (NULL == (curl_multi = curl_multi_init ()))
3085   {
3086     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3087                 "Failed to create cURL multi handle!\n");
3088     return;
3089   }
3090   cafile = cafile_opt;
3091   if (NULL == cafile)
3092   {
3093     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3094                                                               "PROXY_CACERT",
3095                                                               &cafile_cfg))
3096     {
3097       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3098                                  "gns-proxy",
3099                                  "PROXY_CACERT");
3100       return;
3101     }
3102     cafile = cafile_cfg;
3103   }
3104   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3105               "Using %s as CA\n", cafile);
3106
3107   gnutls_global_init ();
3108   gnutls_x509_crt_init (&proxy_ca.cert);
3109   gnutls_x509_privkey_init (&proxy_ca.key);
3110
3111   if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
3112        (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
3113   {
3114     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3115                 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
3116                 cafile);
3117     gnutls_x509_crt_deinit (proxy_ca.cert);
3118     gnutls_x509_privkey_deinit (proxy_ca.key);
3119     gnutls_global_deinit ();
3120     GNUNET_free_non_null (cafile_cfg);
3121     return;
3122   }
3123   GNUNET_free_non_null (cafile_cfg);
3124   if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3125   {
3126     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3127                 "Unable to connect to GNS!\n");
3128     gnutls_x509_crt_deinit (proxy_ca.cert);
3129     gnutls_x509_privkey_deinit (proxy_ca.key);
3130     gnutls_global_deinit ();
3131     return;
3132   }
3133   identity = GNUNET_IDENTITY_connect (cfg,
3134                                       NULL, NULL);
3135   id_op = GNUNET_IDENTITY_get (identity,
3136                                "gns-proxy",
3137                                &identity_master_cb,
3138                                NULL);
3139   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
3140                                 &do_shutdown, NULL);
3141 }
3142
3143
3144 /**
3145  * The main function for gnunet-gns-proxy.
3146  *
3147  * @param argc number of arguments from the command line
3148  * @param argv command line arguments
3149  * @return 0 ok, 1 on error
3150  */
3151 int
3152 main (int argc, char *const *argv)
3153 {
3154   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3155     {'p', "port", NULL,
3156      gettext_noop ("listen on specified port (default: 7777)"), 1,
3157      &GNUNET_GETOPT_set_ulong, &port},
3158     {'a', "authority", NULL,
3159       gettext_noop ("pem file to use as CA"), 1,
3160       &GNUNET_GETOPT_set_string, &cafile_opt},
3161     GNUNET_GETOPT_OPTION_END
3162   };
3163   static const char* page =
3164     "<html><head><title>gnunet-gns-proxy</title>"
3165     "</head><body>cURL fail</body></html>";
3166   int ret;
3167
3168   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3169     return 2;
3170   GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3171   curl_failure_response = MHD_create_response_from_buffer (strlen (page),
3172                                                            (void*)page,
3173                                                            MHD_RESPMEM_PERSISTENT);
3174
3175   ret =
3176       (GNUNET_OK ==
3177        GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3178                            _("GNUnet GNS proxy"),
3179                            options,
3180                            &run, NULL)) ? 0 : 1;
3181   MHD_destroy_response (curl_failure_response);
3182   GNUNET_free_non_null ((char *) argv);
3183   GNUNET_CRYPTO_ecdsa_key_clear (&local_shorten_zone);
3184   return ret;
3185 }
3186
3187 /* end of gnunet-gns-proxy.c */