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