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