af276cb3ab9e33b4fb1ba104c54848c28b39030d
[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     return MHD_CONTENT_READER_END_OF_STREAM;
806   }
807   GNUNET_memcpy (buf, s5r->io_buf, bytes_to_copy);
808   memmove (s5r->io_buf,
809            &s5r->io_buf[bytes_to_copy],
810            s5r->io_len - bytes_to_copy);
811   s5r->io_len -= bytes_to_copy;
812   if (NULL != s5r->curl)
813     curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
814   return bytes_to_copy;
815 }
816
817
818 /**
819  * Check that the website has presented us with a valid SSL certificate.
820  * The certificate must either match the domain name or the LEHO name
821  * (or, if available, the TLSA record).
822  *
823  * @param s5r request to check for.
824  * @return #GNUNET_OK if the certificate is valid
825  */
826 static int
827 check_ssl_certificate (struct Socks5Request *s5r)
828 {
829   unsigned int cert_list_size;
830   const gnutls_datum_t *chainp;
831   const struct curl_tlssessioninfo *tlsinfo;
832   char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
833   size_t size;
834   gnutls_x509_crt_t x509_cert;
835   int rc;
836   const char *name;
837
838   if (CURLE_OK !=
839       curl_easy_getinfo (s5r->curl,
840                          CURLINFO_TLS_SESSION,
841                          (struct curl_slist **) &tlsinfo))
842     return GNUNET_SYSERR;
843   if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
844   {
845     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
846                 _("Unsupported CURL SSL backend %d\n"),
847                 tlsinfo->backend);
848     return GNUNET_SYSERR;
849   }
850   chainp = gnutls_certificate_get_peers (tlsinfo->internals, &cert_list_size);
851   if ( (! chainp) || (0 == cert_list_size) )
852     return GNUNET_SYSERR;
853
854   size = sizeof (certdn);
855   /* initialize an X.509 certificate structure. */
856   gnutls_x509_crt_init (&x509_cert);
857   gnutls_x509_crt_import (x509_cert,
858                           chainp,
859                           GNUTLS_X509_FMT_DER);
860
861   if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
862                                                 GNUTLS_OID_X520_COMMON_NAME,
863                                                 0, /* the first and only one */
864                                                 0 /* no DER encoding */,
865                                                 certdn,
866                                                 &size)))
867   {
868     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
869                 _("Failed to fetch CN from cert: %s\n"),
870                 gnutls_strerror(rc));
871     gnutls_x509_crt_deinit (x509_cert);
872     return GNUNET_SYSERR;
873   }
874   /* check for TLSA/DANE records */
875 #if HAVE_GNUTLS_DANE
876   if (NULL != s5r->dane_data)
877   {
878     char *dd[] = { s5r->dane_data, NULL };
879     int dlen[] = { s5r->dane_data_len, 0};
880     dane_state_t dane_state;
881     dane_query_t dane_query;
882     unsigned int verify;
883
884     /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
885     if (0 != (rc = dane_state_init (&dane_state,
886 #ifdef DANE_F_IGNORE_DNSSEC
887                                     DANE_F_IGNORE_DNSSEC |
888 #endif
889                                     DANE_F_IGNORE_LOCAL_RESOLVER)))
890     {
891       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
892                   _("Failed to initialize DANE: %s\n"),
893                   dane_strerror(rc));
894       gnutls_x509_crt_deinit (x509_cert);
895       return GNUNET_SYSERR;
896     }
897     if (0 != (rc = dane_raw_tlsa (dane_state,
898                                   &dane_query,
899                                   dd,
900                                   dlen,
901                                   GNUNET_YES,
902                                   GNUNET_NO)))
903     {
904       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
905                   _("Failed to parse DANE record: %s\n"),
906                   dane_strerror(rc));
907       dane_state_deinit (dane_state);
908       gnutls_x509_crt_deinit (x509_cert);
909       return GNUNET_SYSERR;
910     }
911     if (0 != (rc = dane_verify_crt_raw (dane_state,
912                                         chainp,
913                                         cert_list_size,
914                                         gnutls_certificate_type_get (tlsinfo->internals),
915                                         dane_query,
916                                         0, 0,
917                                         &verify)))
918     {
919       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
920                   _("Failed to verify TLS connection using DANE: %s\n"),
921                   dane_strerror(rc));
922       dane_query_deinit (dane_query);
923       dane_state_deinit (dane_state);
924       gnutls_x509_crt_deinit (x509_cert);
925       return GNUNET_SYSERR;
926     }
927     if (0 != verify)
928     {
929       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
930                   _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
931                   verify);
932       dane_query_deinit (dane_query);
933       dane_state_deinit (dane_state);
934       gnutls_x509_crt_deinit (x509_cert);
935       return GNUNET_SYSERR;
936     }
937     dane_query_deinit (dane_query);
938     dane_state_deinit (dane_state);
939     /* success! */
940   }
941   else
942 #endif
943   {
944     /* try LEHO or ordinary domain name X509 verification */
945     name = s5r->domain;
946     if (NULL != s5r->leho)
947       name = s5r->leho;
948     if (NULL != name)
949     {
950       if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
951                                                      name)))
952       {
953         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
954                     _("SSL certificate subject name (%s) does not match `%s'\n"),
955                     certdn,
956                     name);
957         gnutls_x509_crt_deinit (x509_cert);
958         return GNUNET_SYSERR;
959       }
960     }
961     else
962     {
963       /* we did not even have the domain name!? */
964       GNUNET_break (0);
965       return GNUNET_SYSERR;
966     }
967   }
968   gnutls_x509_crt_deinit (x509_cert);
969   return GNUNET_OK;
970 }
971
972
973 /**
974  * We're getting an HTTP response header from cURL.  Convert it to the
975  * MHD response headers.  Mostly copies the headers, but makes special
976  * adjustments to "Set-Cookie" and "Location" headers as those may need
977  * to be changed from the LEHO to the domain the browser expects.
978  *
979  * @param buffer curl buffer with a single line of header data; not 0-terminated!
980  * @param size curl blocksize
981  * @param nmemb curl blocknumber
982  * @param cls our `struct Socks5Request *`
983  * @return size of processed bytes
984  */
985 static size_t
986 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
987 {
988   struct Socks5Request *s5r = cls;
989   size_t bytes = size * nmemb;
990   char *ndup;
991   const char *hdr_type;
992   const char *cookie_domain;
993   char *hdr_val;
994   long resp_code;
995   char *new_cookie_hdr;
996   char *new_location;
997   size_t offset;
998   size_t delta_cdomain;
999   int domain_matched;
1000   char *tok;
1001
1002   if (NULL == s5r->response)
1003   {
1004     /* first, check SSL certificate */
1005     if ( (HTTPS_PORT == s5r->port) &&
1006          (GNUNET_OK != check_ssl_certificate (s5r)) )
1007       return 0;
1008
1009     GNUNET_break (CURLE_OK ==
1010                   curl_easy_getinfo (s5r->curl,
1011                                      CURLINFO_RESPONSE_CODE,
1012                                      &resp_code));
1013     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014                 "Creating MHD response with code %d\n",
1015                 (int) resp_code);
1016     s5r->response_code = resp_code;
1017     s5r->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
1018                                                        IO_BUFFERSIZE,
1019                                                        &mhd_content_cb,
1020                                                        s5r,
1021                                                        NULL);
1022     if (NULL != s5r->leho)
1023     {
1024       char *cors_hdr;
1025
1026       GNUNET_asprintf (&cors_hdr,
1027                        (HTTPS_PORT == s5r->port)
1028                        ? "https://%s"
1029                        : "http://%s",
1030                        s5r->leho);
1031
1032       GNUNET_break (MHD_YES ==
1033                     MHD_add_response_header (s5r->response,
1034                                              MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1035                                              cors_hdr));
1036       GNUNET_free (cors_hdr);
1037     }
1038     /* force connection to be closed after each request, as we
1039        do not support HTTP pipelining (yet, FIXME!) */
1040     /*GNUNET_break (MHD_YES ==
1041                   MHD_add_response_header (s5r->response,
1042                                            MHD_HTTP_HEADER_CONNECTION,
1043                                            "close"));*/
1044   }
1045
1046   ndup = GNUNET_strndup (buffer, bytes);
1047   hdr_type = strtok (ndup, ":");
1048   if (NULL == hdr_type)
1049   {
1050     GNUNET_free (ndup);
1051     return bytes;
1052   }
1053   hdr_val = strtok (NULL, "");
1054   if (NULL == hdr_val)
1055   {
1056     GNUNET_free (ndup);
1057     return bytes;
1058   }
1059   if (' ' == *hdr_val)
1060     hdr_val++;
1061
1062   /* custom logic for certain header types */
1063   new_cookie_hdr = NULL;
1064   if ( (NULL != s5r->leho) &&
1065        (0 == strcasecmp (hdr_type,
1066                          MHD_HTTP_HEADER_SET_COOKIE)) )
1067
1068   {
1069     new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1070                                     strlen (s5r->domain) + 1);
1071     offset = 0;
1072     domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1073     for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1074     {
1075       if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
1076            (GNUNET_NO == domain_matched) )
1077       {
1078         domain_matched = GNUNET_YES;
1079         cookie_domain = tok + strlen (" domain") + 1;
1080         if (strlen (cookie_domain) < strlen (s5r->leho))
1081         {
1082           delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1083           if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
1084           {
1085             offset += sprintf (new_cookie_hdr + offset,
1086                                " domain=%s;",
1087                                s5r->domain);
1088             continue;
1089           }
1090         }
1091         else if (0 == strcmp (cookie_domain, s5r->leho))
1092         {
1093           offset += sprintf (new_cookie_hdr + offset,
1094                              " domain=%s;",
1095                              s5r->domain);
1096           continue;
1097         }
1098         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1099                     _("Cookie domain `%s' supplied by server is invalid\n"),
1100                     tok);
1101       }
1102       GNUNET_memcpy (new_cookie_hdr + offset, tok, strlen (tok));
1103       offset += strlen (tok);
1104       new_cookie_hdr[offset++] = ';';
1105     }
1106     hdr_val = new_cookie_hdr;
1107   }
1108
1109   new_location = NULL;
1110   if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
1111   {
1112     char *leho_host;
1113
1114     GNUNET_asprintf (&leho_host,
1115                      (HTTPS_PORT != s5r->port)
1116                      ? "http://%s"
1117                      : "https://%s",
1118                      s5r->leho);
1119     if (0 == strncmp (leho_host,
1120                       hdr_val,
1121                       strlen (leho_host)))
1122     {
1123       GNUNET_asprintf (&new_location,
1124                        "%s%s%s",
1125                        (HTTPS_PORT != s5r->port)
1126                        ? "http://"
1127                        : "https://",
1128                        s5r->domain,
1129                        hdr_val + strlen (leho_host));
1130       hdr_val = new_location;
1131     }
1132     GNUNET_free (leho_host);
1133   }
1134   /* MHD does not allow certain characters in values, remove those */
1135   if (NULL != (tok = strchr (hdr_val, '\n')))
1136     *tok = '\0';
1137   if (NULL != (tok = strchr (hdr_val, '\r')))
1138     *tok = '\0';
1139   if (NULL != (tok = strchr (hdr_val, '\t')))
1140     *tok = '\0';
1141   if ((0 != strlen (hdr_val) ) &&
1142       (0 != strcasecmp (MHD_HTTP_HEADER_CONTENT_LENGTH, hdr_type)))
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           if (NULL == s5r->response)
1383             s5r->response = curl_failure_response;
1384           break;
1385         case CURLMSG_LAST:
1386           /* documentation says this is not used */
1387           GNUNET_break (0);
1388           break;
1389         default:
1390           /* unexpected status code */
1391           GNUNET_break (0);
1392           break;
1393       }
1394     };
1395   } while (mret == CURLM_CALL_MULTI_PERFORM);
1396   if (CURLM_OK != mret)
1397     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1398                 "%s failed at %s:%d: `%s'\n",
1399                 "curl_multi_perform", __FILE__, __LINE__,
1400                 curl_multi_strerror (mret));
1401   if (0 == running)
1402   {
1403     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1404                 "Suspending cURL multi loop, no more events pending\n");
1405     return; /* nothing more in progress */
1406   }
1407   curl_download_prepare ();
1408 }
1409
1410
1411 /* ********************************* MHD response generation ******************* */
1412
1413
1414 /**
1415  * Read HTTP request header field from the request.  Copies the fields
1416  * over to the 'headers' that will be given to curl.  However, 'Host'
1417  * is substituted with the LEHO if present.  We also change the
1418  * 'Connection' header value to "close" as the proxy does not support
1419  * pipelining.
1420  *
1421  * @param cls our `struct Socks5Request`
1422  * @param kind value kind
1423  * @param key field key
1424  * @param value field value
1425  * @return MHD_YES to continue to iterate
1426  */
1427 static int
1428 con_val_iter (void *cls,
1429               enum MHD_ValueKind kind,
1430               const char *key,
1431               const char *value)
1432 {
1433   struct Socks5Request *s5r = cls;
1434   char *hdr;
1435
1436   if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1437        (NULL != s5r->leho) )
1438     value = s5r->leho;
1439   if (0 == strcasecmp (MHD_HTTP_HEADER_CONTENT_LENGTH, key))
1440     return MHD_YES;
1441   if (0 == strcasecmp (MHD_HTTP_HEADER_ACCEPT_ENCODING, key))
1442     return MHD_YES;
1443   GNUNET_asprintf (&hdr,
1444                    "%s: %s",
1445                    key,
1446                    value);
1447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1448               "Adding HEADER `%s' to HTTP request\n",
1449               hdr);
1450   s5r->headers = curl_slist_append (s5r->headers,
1451                                     hdr);
1452   GNUNET_free (hdr);
1453   return MHD_YES;
1454 }
1455
1456
1457 /**
1458  * Main MHD callback for handling requests.
1459  *
1460  * @param cls unused
1461  * @param con MHD connection handle
1462  * @param url the url in the request
1463  * @param meth the HTTP method used ("GET", "PUT", etc.)
1464  * @param ver the HTTP version string (i.e. "HTTP/1.1")
1465  * @param upload_data the data being uploaded (excluding HEADERS,
1466  *        for a POST that fits into memory and that is encoded
1467  *        with a supported encoding, the POST data will NOT be
1468  *        given in upload_data and is instead available as
1469  *        part of MHD_get_connection_values; very large POST
1470  *        data *will* be made available incrementally in
1471  *        upload_data)
1472  * @param upload_data_size set initially to the size of the
1473  *        @a upload_data provided; the method must update this
1474  *        value to the number of bytes NOT processed;
1475  * @param con_cls pointer to location where we store the 'struct Request'
1476  * @return MHD_YES if the connection was handled successfully,
1477  *         MHD_NO if the socket must be closed due to a serious
1478  *         error while handling the request
1479  */
1480 static int
1481 create_response (void *cls,
1482                  struct MHD_Connection *con,
1483                  const char *url,
1484                  const char *meth,
1485                  const char *ver,
1486                  const char *upload_data,
1487                  size_t *upload_data_size,
1488                  void **con_cls)
1489 {
1490   struct Socks5Request *s5r = *con_cls;
1491   char *curlurl;
1492   char *curl_hosts;
1493   char ipstring[INET6_ADDRSTRLEN];
1494   char ipaddr[INET6_ADDRSTRLEN + 2];
1495   const struct sockaddr *sa;
1496   const struct sockaddr_in *s4;
1497   const struct sockaddr_in6 *s6;
1498   uint16_t port;
1499   size_t left;
1500
1501   if (NULL == s5r)
1502   {
1503     GNUNET_break (0);
1504     return MHD_NO;
1505   }
1506   //Fresh connection.
1507   if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
1508   {
1509     /* first time here, initialize curl handle */
1510     sa = (const struct sockaddr *) &s5r->destination_address;
1511     switch (sa->sa_family)
1512     {
1513       case AF_INET:
1514         s4 = (const struct sockaddr_in *) &s5r->destination_address;
1515         if (NULL == inet_ntop (AF_INET,
1516                                &s4->sin_addr,
1517                                ipstring,
1518                                sizeof (ipstring)))
1519         {
1520           GNUNET_break (0);
1521           return MHD_NO;
1522         }
1523         GNUNET_snprintf (ipaddr,
1524                          sizeof (ipaddr),
1525                          "%s",
1526                          ipstring);
1527         port = ntohs (s4->sin_port);
1528         break;
1529       case AF_INET6:
1530         s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1531         if (NULL == inet_ntop (AF_INET6,
1532                                &s6->sin6_addr,
1533                                ipstring,
1534                                sizeof (ipstring)))
1535         {
1536           GNUNET_break (0);
1537           return MHD_NO;
1538         }
1539         GNUNET_snprintf (ipaddr,
1540                          sizeof (ipaddr),
1541                          "[%s]",
1542                          ipstring);
1543         port = ntohs (s6->sin6_port);
1544         break;
1545       default:
1546         GNUNET_break (0);
1547         return MHD_NO;
1548     }
1549     if (NULL == s5r->curl)
1550       s5r->curl = curl_easy_init ();
1551     if (NULL == s5r->curl)
1552       return MHD_queue_response (con,
1553                                  MHD_HTTP_INTERNAL_SERVER_ERROR,
1554                                  curl_failure_response);
1555     curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1556     curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1557     curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1558     curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1559     curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1560     curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1561     curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1562     curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1563     curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1564     curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1565     curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1566     curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0);
1567     /**
1568      * Pre-populate cache to resolve Hostname.
1569      * This is necessary as the DNS name in the CURLOPT_URL is used
1570      * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1571      */
1572     if (NULL != s5r->leho)
1573     {
1574       GNUNET_asprintf (&curl_hosts,
1575                        "%s:%d:%s",
1576                        s5r->leho,
1577                        port,
1578                        ipaddr);
1579       s5r->hosts = curl_slist_append(NULL, curl_hosts);
1580       curl_easy_setopt(s5r->curl, CURLOPT_RESOLVE, s5r->hosts);
1581       GNUNET_free (curl_hosts);
1582     }
1583     GNUNET_asprintf (&curlurl,
1584                      (HTTPS_PORT != s5r->port)
1585                      ? "http://%s:%d%s"
1586                      : "https://%s:%d%s",
1587                      (NULL != s5r->leho)
1588                      ? s5r->leho
1589                      : ipaddr,
1590                      port,
1591                      s5r->url);
1592     curl_easy_setopt (s5r->curl,
1593                       CURLOPT_URL,
1594                       curlurl);
1595     GNUNET_free (curlurl);
1596     if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1597     {
1598       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1599       curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
1600       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1601       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1602       curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1603       curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1604     }
1605     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1606     {
1607       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1608       curl_easy_setopt (s5r->curl, CURLOPT_POST, 1);
1609       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1610       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1611       curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1612       curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1613     }
1614     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1615     {
1616       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1617       curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
1618     }
1619     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_OPTIONS))
1620     {
1621       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1622       curl_easy_setopt (s5r->curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
1623     }
1624     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1625     {
1626       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1627       curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
1628       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1629       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1630     }
1631     else
1632     {
1633       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1634                   _("Unsupported HTTP method `%s'\n"),
1635                   meth);
1636       curl_easy_cleanup (s5r->curl);
1637       s5r->curl = NULL;
1638       return MHD_NO;
1639     }
1640
1641     if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1642     {
1643       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1644     }
1645     else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1646     {
1647       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1648     }
1649     else
1650     {
1651       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1652     }
1653
1654     if (HTTPS_PORT == s5r->port)
1655     {
1656       curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1657       curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1658       /* Disable cURL checking the hostname, as we will check ourselves
1659          as only we have the domain name or the LEHO or the DANE record */
1660       curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
1661     }
1662     else
1663     {
1664       curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
1665     }
1666
1667     if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
1668     {
1669       GNUNET_break (0);
1670       curl_easy_cleanup (s5r->curl);
1671       s5r->curl = NULL;
1672       return MHD_NO;
1673     }
1674     MHD_get_connection_values (con,
1675                                MHD_HEADER_KIND,
1676                                &con_val_iter, s5r);
1677     //TODO is this sane? Basically we disable cURLs built-in expect:
1678     //100-continue
1679     s5r->headers = curl_slist_append (s5r->headers,
1680                                       "Expect:");
1681     curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
1682     curl_download_prepare ();
1683     return MHD_YES;
1684   }
1685
1686   /* continuing to process request */
1687   if (0 != *upload_data_size)
1688   {
1689     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1690                 "Processing %lu bytes UPLOAD\n", *upload_data_size);
1691     left = GNUNET_MIN (*upload_data_size,
1692                        sizeof (s5r->io_buf) - s5r->io_len);
1693     GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1694                    upload_data,
1695                    left);
1696     s5r->io_len += left;
1697     *upload_data_size -= left;
1698     GNUNET_assert (NULL != s5r->curl);
1699     curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
1700     curl_download_prepare ();
1701     return MHD_YES;
1702   }
1703   if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
1704   {
1705     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1706                 "Finished processing UPLOAD\n");
1707     s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1708   }
1709   if (NULL == s5r->response)
1710     return MHD_YES; /* too early to queue response, did not yet get headers from cURL */
1711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1712               "Queueing response with MHD\n");
1713   run_mhd_now (s5r->hd);
1714   return MHD_queue_response (con,
1715                              s5r->response_code,
1716                              s5r->response);
1717 }
1718
1719
1720 /* ******************** MHD HTTP setup and event loop ******************** */
1721
1722
1723 /**
1724  * Function called when MHD decides that we are done with a request.
1725  *
1726  * @param cls NULL
1727  * @param connection connection handle
1728  * @param con_cls value as set by the last call to
1729  *        the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
1730  * @param toe reason for request termination (ignored)
1731  */
1732 static void
1733 mhd_completed_cb (void *cls,
1734                   struct MHD_Connection *connection,
1735                   void **con_cls,
1736                   enum MHD_RequestTerminationCode toe)
1737 {
1738   struct Socks5Request *s5r = *con_cls;
1739
1740   if (NULL == s5r)
1741     return;
1742   if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
1743     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1744                 "MHD encountered error handling request: %d\n",
1745                 toe);
1746   if (NULL != s5r->curl)
1747   {
1748     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1749                 "Resetting cURL handle\n");
1750     curl_multi_remove_handle (curl_multi, s5r->curl);
1751     curl_slist_free_all (s5r->headers);
1752     s5r->headers = NULL;
1753     curl_easy_reset (s5r->curl);
1754     s5r->rbuf_len = 0;
1755     s5r->wbuf_len = 0;
1756     s5r->io_len = 0;
1757   }
1758   if ( (NULL != s5r->response) &&
1759        (curl_failure_response != s5r->response) )
1760     MHD_destroy_response (s5r->response);
1761   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Finished request for %s\n", s5r->url);
1762   GNUNET_free (s5r->url);
1763   s5r->state = SOCKS5_SOCKET_WITH_MHD;
1764   s5r->url = NULL;
1765   s5r->response = NULL;
1766   *con_cls = NULL;
1767 }
1768
1769
1770 /**
1771  * Function called when MHD connection is opened or closed.
1772  *
1773  * @param cls NULL
1774  * @param connection connection handle
1775  * @param con_cls value as set by the last call to
1776  *        the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
1777  * @param toe connection notification type
1778  */
1779 static void
1780 mhd_connection_cb (void *cls,
1781                    struct MHD_Connection *connection,
1782                    void **con_cls,
1783                    enum MHD_ConnectionNotificationCode cnc)
1784 {
1785   struct Socks5Request *s5r;
1786   const union MHD_ConnectionInfo *ci;
1787   int sock;
1788
1789   if (MHD_CONNECTION_NOTIFY_STARTED == cnc)
1790     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
1791
1792   if (MHD_CONNECTION_NOTIFY_CLOSED != cnc)
1793     return; //Ignore
1794   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection closed... cleaning up\n");
1795
1796   ci = MHD_get_connection_info (connection,
1797                                 MHD_CONNECTION_INFO_CONNECTION_FD);
1798   if (NULL == ci)
1799   {
1800     GNUNET_break (0);
1801     return;
1802   }
1803
1804   sock = ci->connect_fd;
1805   for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1806     if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1807       break;
1808
1809   if (NULL == s5r)
1810   {
1811     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection stale!\n");
1812     return;
1813   }
1814   cleanup_s5r (s5r);
1815   curl_download_prepare ();
1816   *con_cls = NULL;
1817 }
1818
1819 /**
1820  * Function called when MHD first processes an incoming connection.
1821  * Gives us the respective URI information.
1822  *
1823  * We use this to associate the `struct MHD_Connection` with our
1824  * internal `struct Socks5Request` data structure (by checking
1825  * for matching sockets).
1826  *
1827  * @param cls the HTTP server handle (a `struct MhdHttpList`)
1828  * @param url the URL that is being requested
1829  * @param connection MHD connection object for the request
1830  * @return the `struct Socks5Request` that this @a connection is for
1831  */
1832 static void *
1833 mhd_log_callback (void *cls,
1834                   const char *url,
1835                   struct MHD_Connection *connection)
1836 {
1837   struct Socks5Request *s5r;
1838   const union MHD_ConnectionInfo *ci;
1839   int sock;
1840
1841   ci = MHD_get_connection_info (connection,
1842                                 MHD_CONNECTION_INFO_CONNECTION_FD);
1843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
1844   if (NULL == ci)
1845   {
1846     GNUNET_break (0);
1847     return NULL;
1848   }
1849   sock = ci->connect_fd;
1850   for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1851   {
1852     if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1853     {
1854       if (NULL != s5r->url)
1855       {
1856         GNUNET_break (0);
1857         return NULL;
1858       }
1859       s5r->url = GNUNET_strdup (url);
1860       if (NULL != s5r->timeout_task)
1861         GNUNET_SCHEDULER_cancel (s5r->timeout_task);
1862       s5r->timeout_task = NULL;
1863       GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD);
1864       return s5r;
1865     }
1866   }
1867   GNUNET_break (0);
1868   return NULL;
1869 }
1870
1871
1872 /**
1873  * Kill the given MHD daemon.
1874  *
1875  * @param hd daemon to stop
1876  */
1877 static void
1878 kill_httpd (struct MhdHttpList *hd)
1879 {
1880   GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1881                                mhd_httpd_tail,
1882                                hd);
1883   GNUNET_free_non_null (hd->domain);
1884   MHD_stop_daemon (hd->daemon);
1885   if (NULL != hd->httpd_task)
1886   {
1887     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1888     hd->httpd_task = NULL;
1889   }
1890   GNUNET_free_non_null (hd->proxy_cert);
1891   if (hd == httpd)
1892     httpd = NULL;
1893   GNUNET_free (hd);
1894 }
1895
1896
1897 /**
1898  * Task run whenever HTTP server is idle for too long. Kill it.
1899  *
1900  * @param cls the `struct MhdHttpList *`
1901  */
1902 static void
1903 kill_httpd_task (void *cls)
1904 {
1905   struct MhdHttpList *hd = cls;
1906
1907   hd->httpd_task = NULL;
1908   kill_httpd (hd);
1909 }
1910
1911
1912 /**
1913  * Task run whenever HTTP server operations are pending.
1914  *
1915  * @param cls the `struct MhdHttpList *` of the daemon that is being run
1916  */
1917 static void
1918 do_httpd (void *cls);
1919
1920
1921 /**
1922  * Schedule MHD.  This function should be called initially when an
1923  * MHD is first getting its client socket, and will then automatically
1924  * always be called later whenever there is work to be done.
1925  *
1926  * @param hd the daemon to schedule
1927  */
1928 static void
1929 schedule_httpd (struct MhdHttpList *hd)
1930 {
1931   fd_set rs;
1932   fd_set ws;
1933   fd_set es;
1934   struct GNUNET_NETWORK_FDSet *wrs;
1935   struct GNUNET_NETWORK_FDSet *wws;
1936   int max;
1937   int haveto;
1938   MHD_UNSIGNED_LONG_LONG timeout;
1939   struct GNUNET_TIME_Relative tv;
1940
1941   FD_ZERO (&rs);
1942   FD_ZERO (&ws);
1943   FD_ZERO (&es);
1944   max = -1;
1945   if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1946   {
1947     kill_httpd (hd);
1948     return;
1949   }
1950   haveto = MHD_get_timeout (hd->daemon, &timeout);
1951   if (MHD_YES == haveto)
1952     tv.rel_value_us = (uint64_t) timeout * 1000LL;
1953   else
1954     tv = GNUNET_TIME_UNIT_FOREVER_REL;
1955   if (-1 != max)
1956   {
1957     wrs = GNUNET_NETWORK_fdset_create ();
1958     wws = GNUNET_NETWORK_fdset_create ();
1959     GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1960     GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1961   }
1962   else
1963   {
1964     wrs = NULL;
1965     wws = NULL;
1966   }
1967   if (NULL != hd->httpd_task)
1968     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1969   if ( (MHD_YES != haveto) &&
1970        (-1 == max) &&
1971        (hd != httpd) )
1972   {
1973     /* daemon is idle, kill after timeout */
1974     hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
1975                                                    &kill_httpd_task,
1976                                                    hd);
1977   }
1978   else
1979   {
1980     hd->httpd_task =
1981       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1982                                    tv, wrs, wws,
1983                                    &do_httpd, hd);
1984   }
1985   if (NULL != wrs)
1986     GNUNET_NETWORK_fdset_destroy (wrs);
1987   if (NULL != wws)
1988     GNUNET_NETWORK_fdset_destroy (wws);
1989 }
1990
1991
1992 /**
1993  * Task run whenever HTTP server operations are pending.
1994  *
1995  * @param cls the `struct MhdHttpList` of the daemon that is being run
1996  */
1997 static void
1998 do_httpd (void *cls)
1999 {
2000   struct MhdHttpList *hd = cls;
2001
2002   hd->httpd_task = NULL;
2003   MHD_run (hd->daemon);
2004   schedule_httpd (hd);
2005 }
2006
2007
2008 /**
2009  * Run MHD now, we have extra data ready for the callback.
2010  *
2011  * @param hd the daemon to run now.
2012  */
2013 static void
2014 run_mhd_now (struct MhdHttpList *hd)
2015 {
2016   if (NULL !=
2017       hd->httpd_task)
2018     GNUNET_SCHEDULER_cancel (hd->httpd_task);
2019   hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
2020                                              hd);
2021 }
2022
2023
2024 /**
2025  * Read file in filename
2026  *
2027  * @param filename file to read
2028  * @param size pointer where filesize is stored
2029  * @return NULL on error
2030  */
2031 static void*
2032 load_file (const char* filename,
2033            unsigned int* size)
2034 {
2035   void *buffer;
2036   uint64_t fsize;
2037
2038   if (GNUNET_OK !=
2039       GNUNET_DISK_file_size (filename, &fsize,
2040                              GNUNET_YES, GNUNET_YES))
2041     return NULL;
2042   if (fsize > MAX_PEM_SIZE)
2043     return NULL;
2044   *size = (unsigned int) fsize;
2045   buffer = GNUNET_malloc (*size);
2046   if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
2047   {
2048     GNUNET_free (buffer);
2049     return NULL;
2050   }
2051   return buffer;
2052 }
2053
2054
2055 /**
2056  * Load PEM key from file
2057  *
2058  * @param key where to store the data
2059  * @param keyfile path to the PEM file
2060  * @return #GNUNET_OK on success
2061  */
2062 static int
2063 load_key_from_file (gnutls_x509_privkey_t key,
2064                     const char* keyfile)
2065 {
2066   gnutls_datum_t key_data;
2067   int ret;
2068
2069   key_data.data = load_file (keyfile, &key_data.size);
2070   if (NULL == key_data.data)
2071     return GNUNET_SYSERR;
2072   ret = gnutls_x509_privkey_import (key, &key_data,
2073                                     GNUTLS_X509_FMT_PEM);
2074   if (GNUTLS_E_SUCCESS != ret)
2075   {
2076     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2077                 _("Unable to import private key from file `%s'\n"),
2078                 keyfile);
2079   }
2080   GNUNET_free_non_null (key_data.data);
2081   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2082 }
2083
2084
2085 /**
2086  * Load cert from file
2087  *
2088  * @param crt struct to store data in
2089  * @param certfile path to pem file
2090  * @return #GNUNET_OK on success
2091  */
2092 static int
2093 load_cert_from_file (gnutls_x509_crt_t crt,
2094                      const char* certfile)
2095 {
2096   gnutls_datum_t cert_data;
2097   int ret;
2098
2099   cert_data.data = load_file (certfile, &cert_data.size);
2100   if (NULL == cert_data.data)
2101     return GNUNET_SYSERR;
2102   ret = gnutls_x509_crt_import (crt, &cert_data,
2103                                 GNUTLS_X509_FMT_PEM);
2104   if (GNUTLS_E_SUCCESS != ret)
2105   {
2106     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2107                 _("Unable to import certificate %s\n"), certfile);
2108   }
2109   GNUNET_free_non_null (cert_data.data);
2110   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2111 }
2112
2113
2114 /**
2115  * Generate new certificate for specific name
2116  *
2117  * @param name the subject name to generate a cert for
2118  * @return a struct holding the PEM data, NULL on error
2119  */
2120 static struct ProxyGNSCertificate *
2121 generate_gns_certificate (const char *name)
2122 {
2123   unsigned int serial;
2124   size_t key_buf_size;
2125   size_t cert_buf_size;
2126   gnutls_x509_crt_t request;
2127   time_t etime;
2128   struct tm *tm_data;
2129   struct ProxyGNSCertificate *pgc;
2130
2131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2132               "Generating TLS/SSL certificate for `%s'\n",
2133               name);
2134   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2135   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2136   pgc = GNUNET_new (struct ProxyGNSCertificate);
2137   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2138                                  0, "ZZ", 2);
2139   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2140                                  0, "GNU Name System", 4);
2141   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2142                                  0, name, strlen (name));
2143   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
2144   gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2145   gnutls_x509_crt_set_serial (request,
2146                               &serial,
2147                               sizeof (serial));
2148   etime = time (NULL);
2149   tm_data = localtime (&etime);
2150   gnutls_x509_crt_set_activation_time (request,
2151                                        etime);
2152   tm_data->tm_year++;
2153   etime = mktime (tm_data);
2154   gnutls_x509_crt_set_expiration_time (request,
2155                                        etime);
2156   gnutls_x509_crt_sign (request,
2157                         proxy_ca.cert,
2158                         proxy_ca.key);
2159   key_buf_size = sizeof (pgc->key);
2160   cert_buf_size = sizeof (pgc->cert);
2161   gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2162                           pgc->cert, &cert_buf_size);
2163   gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2164                               pgc->key, &key_buf_size);
2165   gnutls_x509_crt_deinit (request);
2166   return pgc;
2167 }
2168
2169
2170 /**
2171  * Function called by MHD with errors, suppresses them all.
2172  *
2173  * @param cls closure
2174  * @param fm format string (`printf()`-style)
2175  * @param ap arguments to @a fm
2176  */
2177 static void
2178 mhd_error_log_callback (void *cls,
2179                         const char *fm,
2180                         va_list ap)
2181 {
2182   /* do nothing */
2183 }
2184
2185
2186 /**
2187  * Lookup (or create) an SSL MHD instance for a particular domain.
2188  *
2189  * @param domain the domain the SSL daemon has to serve
2190  * @return NULL on error
2191  */
2192 static struct MhdHttpList *
2193 lookup_ssl_httpd (const char* domain)
2194 {
2195   struct MhdHttpList *hd;
2196   struct ProxyGNSCertificate *pgc;
2197
2198   if (NULL == domain)
2199   {
2200     GNUNET_break (0);
2201     return NULL;
2202   }
2203   for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2204     if ( (NULL != hd->domain) &&
2205          (0 == strcmp (hd->domain, domain)) )
2206       return hd;
2207   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2208               "Starting fresh MHD HTTPS instance for domain `%s'\n",
2209               domain);
2210   pgc = generate_gns_certificate (domain);
2211   hd = GNUNET_new (struct MhdHttpList);
2212   hd->is_ssl = GNUNET_YES;
2213   hd->domain = GNUNET_strdup (domain);
2214   hd->proxy_cert = pgc;
2215   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
2216                                  0,
2217                                  NULL, NULL,
2218                                  &create_response, hd,
2219                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2220                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2221                                  MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
2222                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2223                                  MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2224                                  MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2225                                  MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2226                                  MHD_OPTION_END);
2227   if (NULL == hd->daemon)
2228   {
2229     GNUNET_free (pgc);
2230     GNUNET_free (hd);
2231     return NULL;
2232   }
2233   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2234                                mhd_httpd_tail,
2235                                hd);
2236   return hd;
2237 }
2238
2239
2240 /**
2241  * Task run when a Socks5Request somehow fails to be associated with
2242  * an MHD connection (i.e. because the client never speaks HTTP after
2243  * the SOCKS5 handshake).  Clean up.
2244  *
2245  * @param cls the `struct Socks5Request *`
2246  */
2247 static void
2248 timeout_s5r_handshake (void *cls)
2249 {
2250   struct Socks5Request *s5r = cls;
2251
2252   s5r->timeout_task = NULL;
2253   cleanup_s5r (s5r);
2254 }
2255
2256
2257 /**
2258  * We're done with the Socks5 protocol, now we need to pass the
2259  * connection data through to the final destination, either
2260  * direct (if the protocol might not be HTTP), or via MHD
2261  * (if the port looks like it should be HTTP).
2262  *
2263  * @param s5r socks request that has reached the final stage
2264  */
2265 static void
2266 setup_data_transfer (struct Socks5Request *s5r)
2267 {
2268   struct MhdHttpList *hd;
2269   int fd;
2270   const struct sockaddr *addr;
2271   socklen_t len;
2272
2273   switch (s5r->port)
2274   {
2275     case HTTPS_PORT:
2276       hd = lookup_ssl_httpd (s5r->domain);
2277       if (NULL == hd)
2278       {
2279         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2280                     _("Failed to start HTTPS server for `%s'\n"),
2281                     s5r->domain);
2282         cleanup_s5r (s5r);
2283         return;
2284       }
2285       break;
2286     case HTTP_PORT:
2287     default:
2288       GNUNET_assert (NULL != httpd);
2289       hd = httpd;
2290       break;
2291   }
2292   fd = GNUNET_NETWORK_get_fd (s5r->sock);
2293   addr = GNUNET_NETWORK_get_addr (s5r->sock);
2294   len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2295   s5r->state = SOCKS5_SOCKET_WITH_MHD;
2296   if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
2297   {
2298     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2299                 _("Failed to pass client to MHD\n"));
2300     cleanup_s5r (s5r);
2301     return;
2302   }
2303   s5r->hd = hd;
2304   schedule_httpd (hd);
2305   s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2306                                                     &timeout_s5r_handshake,
2307                                                     s5r);
2308 }
2309
2310
2311 /* ********************* SOCKS handling ************************* */
2312
2313
2314 /**
2315  * Write data from buffer to socks5 client, then continue with state machine.
2316  *
2317  * @param cls the closure with the `struct Socks5Request`
2318  */
2319 static void
2320 do_write (void *cls)
2321 {
2322   struct Socks5Request *s5r = cls;
2323   ssize_t len;
2324
2325   s5r->wtask = NULL;
2326   len = GNUNET_NETWORK_socket_send (s5r->sock,
2327                                     s5r->wbuf,
2328                                     s5r->wbuf_len);
2329   if (len <= 0)
2330   {
2331     /* write error: connection closed, shutdown, etc.; just clean up */
2332     cleanup_s5r (s5r);
2333     return;
2334   }
2335   memmove (s5r->wbuf,
2336            &s5r->wbuf[len],
2337            s5r->wbuf_len - len);
2338   s5r->wbuf_len -= len;
2339   if (s5r->wbuf_len > 0)
2340   {
2341     /* not done writing */
2342     s5r->wtask =
2343       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2344                                       s5r->sock,
2345                                       &do_write, s5r);
2346     return;
2347   }
2348
2349   /* we're done writing, continue with state machine! */
2350
2351   switch (s5r->state)
2352   {
2353     case SOCKS5_INIT:
2354       GNUNET_assert (0);
2355       break;
2356     case SOCKS5_REQUEST:
2357       GNUNET_assert (NULL != s5r->rtask);
2358       break;
2359     case SOCKS5_DATA_TRANSFER:
2360       setup_data_transfer (s5r);
2361       return;
2362     case SOCKS5_WRITE_THEN_CLEANUP:
2363       cleanup_s5r (s5r);
2364       return;
2365     default:
2366       GNUNET_break (0);
2367       break;
2368   }
2369 }
2370
2371
2372 /**
2373  * Return a server response message indicating a failure to the client.
2374  *
2375  * @param s5r request to return failure code for
2376  * @param sc status code to return
2377  */
2378 static void
2379 signal_socks_failure (struct Socks5Request *s5r,
2380                       enum Socks5StatusCode sc)
2381 {
2382   struct Socks5ServerResponseMessage *s_resp;
2383
2384   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2385   memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2386   s_resp->version = SOCKS_VERSION_5;
2387   s_resp->reply = sc;
2388   s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2389   if (NULL != s5r->wtask)
2390     s5r->wtask =
2391       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2392                                       s5r->sock,
2393                                       &do_write, s5r);
2394 }
2395
2396
2397 /**
2398  * Return a server response message indicating success.
2399  *
2400  * @param s5r request to return success status message for
2401  */
2402 static void
2403 signal_socks_success (struct Socks5Request *s5r)
2404 {
2405   struct Socks5ServerResponseMessage *s_resp;
2406
2407   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2408   s_resp->version = SOCKS_VERSION_5;
2409   s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2410   s_resp->reserved = 0;
2411   s_resp->addr_type = SOCKS5_AT_IPV4;
2412   /* zero out IPv4 address and port */
2413   memset (&s_resp[1],
2414           0,
2415           sizeof (struct in_addr) + sizeof (uint16_t));
2416   s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2417     sizeof (struct in_addr) + sizeof (uint16_t);
2418   if (NULL == s5r->wtask)
2419     s5r->wtask =
2420       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2421                                       s5r->sock,
2422                                       &do_write, s5r);
2423 }
2424
2425
2426 /**
2427  * Process GNS results for target domain.
2428  *
2429  * @param cls the `struct Socks5Request *`
2430  * @param rd_count number of records returned
2431  * @param rd record data
2432  */
2433 static void
2434 handle_gns_result (void *cls,
2435                    uint32_t rd_count,
2436                    const struct GNUNET_GNSRECORD_Data *rd)
2437 {
2438   struct Socks5Request *s5r = cls;
2439   uint32_t i;
2440   const struct GNUNET_GNSRECORD_Data *r;
2441   int got_ip;
2442
2443   s5r->gns_lookup = NULL;
2444   got_ip = GNUNET_NO;
2445   for (i=0;i<rd_count;i++)
2446   {
2447     r = &rd[i];
2448     switch (r->record_type)
2449     {
2450       case GNUNET_DNSPARSER_TYPE_A:
2451         {
2452           struct sockaddr_in *in;
2453
2454           if (sizeof (struct in_addr) != r->data_size)
2455           {
2456             GNUNET_break_op (0);
2457             break;
2458           }
2459           if (GNUNET_YES == got_ip)
2460             break;
2461           if (GNUNET_OK !=
2462               GNUNET_NETWORK_test_pf (PF_INET))
2463             break;
2464           got_ip = GNUNET_YES;
2465           in = (struct sockaddr_in *) &s5r->destination_address;
2466           in->sin_family = AF_INET;
2467           GNUNET_memcpy (&in->sin_addr,
2468                          r->data,
2469                          r->data_size);
2470           in->sin_port = htons (s5r->port);
2471 #if HAVE_SOCKADDR_IN_SIN_LEN
2472           in->sin_len = sizeof (*in);
2473 #endif
2474         }
2475         break;
2476       case GNUNET_DNSPARSER_TYPE_AAAA:
2477         {
2478           struct sockaddr_in6 *in;
2479
2480           if (sizeof (struct in6_addr) != r->data_size)
2481           {
2482             GNUNET_break_op (0);
2483             break;
2484           }
2485           if (GNUNET_YES == got_ip)
2486             break;
2487           if (GNUNET_OK !=
2488               GNUNET_NETWORK_test_pf (PF_INET))
2489             break;
2490           /* FIXME: allow user to disable IPv6 per configuration option... */
2491           got_ip = GNUNET_YES;
2492           in = (struct sockaddr_in6 *) &s5r->destination_address;
2493           in->sin6_family = AF_INET6;
2494           GNUNET_memcpy (&in->sin6_addr,
2495                          r->data,
2496                          r->data_size);
2497           in->sin6_port = htons (s5r->port);
2498 #if HAVE_SOCKADDR_IN_SIN_LEN
2499           in->sin6_len = sizeof (*in);
2500 #endif
2501         }
2502         break;
2503       case GNUNET_GNSRECORD_TYPE_VPN:
2504         GNUNET_break (0); /* should have been translated within GNS */
2505         break;
2506       case GNUNET_GNSRECORD_TYPE_LEHO:
2507         GNUNET_free_non_null (s5r->leho);
2508         s5r->leho = GNUNET_strndup (r->data,
2509                                     r->data_size);
2510         break;
2511       case GNUNET_GNSRECORD_TYPE_BOX:
2512         {
2513           const struct GNUNET_GNSRECORD_BoxRecord *box;
2514
2515           if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
2516           {
2517             GNUNET_break_op (0);
2518             break;
2519           }
2520           box = r->data;
2521           if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
2522                (ntohs (box->protocol) != IPPROTO_TCP) ||
2523                (ntohs (box->service) != s5r->port) )
2524             break; /* BOX record does not apply */
2525           GNUNET_free_non_null (s5r->dane_data);
2526           s5r->dane_data_len = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
2527           s5r->dane_data = GNUNET_malloc (s5r->dane_data_len);
2528           GNUNET_memcpy (s5r->dane_data,
2529                          &box[1],
2530                          s5r->dane_data_len);
2531           break;
2532         }
2533       default:
2534         /* don't care */
2535         break;
2536     }
2537   }
2538   if (GNUNET_YES != got_ip)
2539   {
2540     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541                 "Name resolution failed to yield useful IP address.\n");
2542     signal_socks_failure (s5r,
2543                           SOCKS5_STATUS_GENERAL_FAILURE);
2544     return;
2545   }
2546   s5r->state = SOCKS5_DATA_TRANSFER;
2547   signal_socks_success (s5r);
2548 }
2549
2550
2551 /**
2552  * Remove the first @a len bytes from the beginning of the read buffer.
2553  *
2554  * @param s5r the handle clear the read buffer for
2555  * @param len number of bytes in read buffer to advance
2556  */
2557 static void
2558 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2559                      size_t len)
2560 {
2561   GNUNET_assert (len <= s5r->rbuf_len);
2562   memmove (s5r->rbuf,
2563            &s5r->rbuf[len],
2564            s5r->rbuf_len - len);
2565   s5r->rbuf_len -= len;
2566 }
2567
2568
2569 /**
2570  * Read data from incoming Socks5 connection
2571  *
2572  * @param cls the closure with the `struct Socks5Request`
2573  */
2574 static void
2575 do_s5r_read (void *cls)
2576 {
2577   struct Socks5Request *s5r = cls;
2578   const struct Socks5ClientHelloMessage *c_hello;
2579   struct Socks5ServerHelloMessage *s_hello;
2580   const struct Socks5ClientRequestMessage *c_req;
2581   ssize_t rlen;
2582   size_t alen;
2583   const struct GNUNET_SCHEDULER_TaskContext *tc;
2584
2585   s5r->rtask = NULL;
2586   tc = GNUNET_SCHEDULER_get_task_context ();
2587   if ( (NULL != tc->read_ready) &&
2588        (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2589   {
2590     rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2591                                        &s5r->rbuf[s5r->rbuf_len],
2592                                        sizeof (s5r->rbuf) - s5r->rbuf_len);
2593     if (rlen <= 0)
2594     {
2595       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2596                   "socks5 client disconnected.\n");
2597       cleanup_s5r (s5r);
2598       return;
2599     }
2600     s5r->rbuf_len += rlen;
2601   }
2602   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2603                                               s5r->sock,
2604                                               &do_s5r_read, s5r);
2605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2606               "Processing %zu bytes of socks data in state %d\n",
2607               s5r->rbuf_len,
2608               s5r->state);
2609   switch (s5r->state)
2610   {
2611     case SOCKS5_INIT:
2612       c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2613       if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2614            (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2615         return; /* need more data */
2616       if (SOCKS_VERSION_5 != c_hello->version)
2617       {
2618         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2619                     _("Unsupported socks version %d\n"),
2620                     (int) c_hello->version);
2621         cleanup_s5r (s5r);
2622         return;
2623       }
2624       clear_from_s5r_rbuf (s5r,
2625                            sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2626       GNUNET_assert (0 == s5r->wbuf_len);
2627       s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2628       s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2629       s_hello->version = SOCKS_VERSION_5;
2630       s_hello->auth_method = SOCKS_AUTH_NONE;
2631       GNUNET_assert (NULL == s5r->wtask);
2632       s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2633                                                    s5r->sock,
2634                                                    &do_write, s5r);
2635       s5r->state = SOCKS5_REQUEST;
2636       return;
2637     case SOCKS5_REQUEST:
2638       c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2639       if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2640         return;
2641       switch (c_req->command)
2642       {
2643         case SOCKS5_CMD_TCP_STREAM:
2644           /* handled below */
2645           break;
2646         default:
2647           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2648                       _("Unsupported socks command %d\n"),
2649                       (int) c_req->command);
2650           signal_socks_failure (s5r,
2651                                 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2652           return;
2653       }
2654       switch (c_req->addr_type)
2655       {
2656         case SOCKS5_AT_IPV4:
2657           {
2658             const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2659             const uint16_t *port = (const uint16_t *) &v4[1];
2660             struct sockaddr_in *in;
2661
2662             s5r->port = ntohs (*port);
2663             if (HTTPS_PORT == s5r->port)
2664             {
2665               GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2666                           _("SSL connection to plain IPv4 address requested\n"));
2667               signal_socks_failure (s5r,
2668                                     SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2669               return;
2670             }
2671             alen = sizeof (struct in_addr);
2672             if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2673                 alen + sizeof (uint16_t))
2674               return; /* need more data */
2675             in = (struct sockaddr_in *) &s5r->destination_address;
2676             in->sin_family = AF_INET;
2677             in->sin_addr = *v4;
2678             in->sin_port = *port;
2679 #if HAVE_SOCKADDR_IN_SIN_LEN
2680             in->sin_len = sizeof (*in);
2681 #endif
2682             s5r->state = SOCKS5_DATA_TRANSFER;
2683           }
2684           break;
2685         case SOCKS5_AT_IPV6:
2686           {
2687             const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2688             const uint16_t *port = (const uint16_t *) &v6[1];
2689             struct sockaddr_in6 *in;
2690
2691             s5r->port = ntohs (*port);
2692             if (HTTPS_PORT == s5r->port)
2693             {
2694               GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2695                           _("SSL connection to plain IPv4 address requested\n"));
2696               signal_socks_failure (s5r,
2697                                     SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2698               return;
2699             }
2700             alen = sizeof (struct in6_addr);
2701             if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2702                 alen + sizeof (uint16_t))
2703               return; /* need more data */
2704             in = (struct sockaddr_in6 *) &s5r->destination_address;
2705             in->sin6_family = AF_INET6;
2706             in->sin6_addr = *v6;
2707             in->sin6_port = *port;
2708 #if HAVE_SOCKADDR_IN_SIN_LEN
2709             in->sin6_len = sizeof (*in);
2710 #endif
2711             s5r->state = SOCKS5_DATA_TRANSFER;
2712           }
2713           break;
2714         case SOCKS5_AT_DOMAINNAME:
2715           {
2716             const uint8_t *dom_len;
2717             const char *dom_name;
2718             const uint16_t *port;
2719
2720             dom_len = (const uint8_t *) &c_req[1];
2721             alen = *dom_len + 1;
2722             if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2723                 alen + sizeof (uint16_t))
2724               return; /* need more data */
2725             dom_name = (const char *) &dom_len[1];
2726             port = (const uint16_t*) &dom_name[*dom_len];
2727             s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2728             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2729                         "Requested connection is to %s:%d\n",
2730                         s5r->domain,
2731                         ntohs (*port));
2732             s5r->state = SOCKS5_RESOLVING;
2733             s5r->port = ntohs (*port);
2734             s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2735                                                  s5r->domain,
2736                                                  &local_gns_zone,
2737                                                  GNUNET_DNSPARSER_TYPE_A,
2738                                                  GNUNET_NO /* only cached */,
2739                                                  (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2740                                                  &handle_gns_result,
2741                                                  s5r);
2742             break;
2743           }
2744         default:
2745           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2746                       _("Unsupported socks address type %d\n"),
2747                       (int) c_req->addr_type);
2748           signal_socks_failure (s5r,
2749                                 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2750           return;
2751       }
2752       clear_from_s5r_rbuf (s5r,
2753                            sizeof (struct Socks5ClientRequestMessage) +
2754                            alen + sizeof (uint16_t));
2755       if (0 != s5r->rbuf_len)
2756       {
2757         /* read more bytes than healthy, why did the client send more!? */
2758         GNUNET_break_op (0);
2759         signal_socks_failure (s5r,
2760                               SOCKS5_STATUS_GENERAL_FAILURE);
2761         return;
2762       }
2763       if (SOCKS5_DATA_TRANSFER == s5r->state)
2764       {
2765         /* if we are not waiting for GNS resolution, signal success */
2766         signal_socks_success (s5r);
2767       }
2768       /* We are done reading right now */
2769       GNUNET_SCHEDULER_cancel (s5r->rtask);
2770       s5r->rtask = NULL;
2771       return;
2772     case SOCKS5_RESOLVING:
2773       GNUNET_assert (0);
2774       return;
2775     case SOCKS5_DATA_TRANSFER:
2776       GNUNET_assert (0);
2777       return;
2778     default:
2779       GNUNET_assert (0);
2780       return;
2781   }
2782 }
2783
2784
2785 /**
2786  * Accept new incoming connections
2787  *
2788  * @param cls the closure with the lsock4 or lsock6
2789  * @param tc the scheduler context
2790  */
2791 static void
2792 do_accept (void *cls)
2793 {
2794   struct GNUNET_NETWORK_Handle *lsock = cls;
2795   struct GNUNET_NETWORK_Handle *s;
2796   struct Socks5Request *s5r;
2797
2798   if (lsock == lsock4)
2799     ltask4 = NULL;
2800   else
2801     ltask6 = NULL;
2802   if (lsock == lsock4)
2803     ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2804                                             lsock,
2805                                             &do_accept, lsock);
2806   else
2807     ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2808                                             lsock,
2809                                             &do_accept, lsock);
2810   s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2811   if (NULL == s)
2812   {
2813     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2814     return;
2815   }
2816   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2817               "Got an inbound connection, waiting for data\n");
2818   s5r = GNUNET_new (struct Socks5Request);
2819   GNUNET_CONTAINER_DLL_insert (s5r_head,
2820                                s5r_tail,
2821                                s5r);
2822   s5r->sock = s;
2823   s5r->state = SOCKS5_INIT;
2824   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2825                                               s5r->sock,
2826                                               &do_s5r_read, s5r);
2827 }
2828
2829
2830 /* ******************* General / main code ********************* */
2831
2832
2833 /**
2834  * Task run on shutdown
2835  *
2836  * @param cls closure
2837  */
2838 static void
2839 do_shutdown (void *cls)
2840 {
2841   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2842               "Shutting down...\n");
2843   while (NULL != mhd_httpd_head)
2844     kill_httpd (mhd_httpd_head);
2845   while (NULL != s5r_head)
2846     cleanup_s5r (s5r_head);
2847   if (NULL != lsock4)
2848   {
2849     GNUNET_NETWORK_socket_close (lsock4);
2850     lsock4 = NULL;
2851   }
2852   if (NULL != lsock6)
2853   {
2854     GNUNET_NETWORK_socket_close (lsock6);
2855     lsock6 = NULL;
2856   }
2857   if (NULL != id_op)
2858   {
2859     GNUNET_IDENTITY_cancel (id_op);
2860     id_op = NULL;
2861   }
2862   if (NULL != identity)
2863   {
2864     GNUNET_IDENTITY_disconnect (identity);
2865     identity = NULL;
2866   }
2867   if (NULL != curl_multi)
2868   {
2869     curl_multi_cleanup (curl_multi);
2870     curl_multi = NULL;
2871   }
2872   if (NULL != gns_handle)
2873   {
2874     GNUNET_GNS_disconnect (gns_handle);
2875     gns_handle = NULL;
2876   }
2877   if (NULL != curl_download_task)
2878   {
2879     GNUNET_SCHEDULER_cancel (curl_download_task);
2880     curl_download_task = NULL;
2881   }
2882   if (NULL != ltask4)
2883   {
2884     GNUNET_SCHEDULER_cancel (ltask4);
2885     ltask4 = NULL;
2886   }
2887   if (NULL != ltask6)
2888   {
2889     GNUNET_SCHEDULER_cancel (ltask6);
2890     ltask6 = NULL;
2891   }
2892   gnutls_x509_crt_deinit (proxy_ca.cert);
2893   gnutls_x509_privkey_deinit (proxy_ca.key);
2894   gnutls_global_deinit ();
2895 }
2896
2897
2898 /**
2899  * Create an IPv4 listen socket bound to our port.
2900  *
2901  * @return NULL on error
2902  */
2903 static struct GNUNET_NETWORK_Handle *
2904 bind_v4 ()
2905 {
2906   struct GNUNET_NETWORK_Handle *ls;
2907   struct sockaddr_in sa4;
2908   int eno;
2909
2910   memset (&sa4, 0, sizeof (sa4));
2911   sa4.sin_family = AF_INET;
2912   sa4.sin_port = htons (port);
2913 #if HAVE_SOCKADDR_IN_SIN_LEN
2914   sa4.sin_len = sizeof (sa4);
2915 #endif
2916   ls = GNUNET_NETWORK_socket_create (AF_INET,
2917                                      SOCK_STREAM,
2918                                      0);
2919   if (NULL == ls)
2920     return NULL;
2921   if (GNUNET_OK !=
2922       GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
2923                                   sizeof (sa4)))
2924   {
2925     eno = errno;
2926     GNUNET_NETWORK_socket_close (ls);
2927     errno = eno;
2928     return NULL;
2929   }
2930   return ls;
2931 }
2932
2933
2934 /**
2935  * Create an IPv6 listen socket bound to our port.
2936  *
2937  * @return NULL on error
2938  */
2939 static struct GNUNET_NETWORK_Handle *
2940 bind_v6 ()
2941 {
2942   struct GNUNET_NETWORK_Handle *ls;
2943   struct sockaddr_in6 sa6;
2944   int eno;
2945
2946   memset (&sa6, 0, sizeof (sa6));
2947   sa6.sin6_family = AF_INET6;
2948   sa6.sin6_port = htons (port);
2949 #if HAVE_SOCKADDR_IN_SIN_LEN
2950   sa6.sin6_len = sizeof (sa6);
2951 #endif
2952   ls = GNUNET_NETWORK_socket_create (AF_INET6,
2953                                      SOCK_STREAM,
2954                                      0);
2955   if (NULL == ls)
2956     return NULL;
2957   if (GNUNET_OK !=
2958       GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
2959                                   sizeof (sa6)))
2960   {
2961     eno = errno;
2962     GNUNET_NETWORK_socket_close (ls);
2963     errno = eno;
2964     return NULL;
2965   }
2966   return ls;
2967 }
2968
2969
2970 /**
2971  * Continue initialization after we have our zone information.
2972  */
2973 static void
2974 run_cont ()
2975 {
2976   struct MhdHttpList *hd;
2977
2978   /* Open listen socket for socks proxy */
2979   lsock6 = bind_v6 ();
2980   if (NULL == lsock6)
2981     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2982   else
2983   {
2984     if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
2985     {
2986       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2987       GNUNET_NETWORK_socket_close (lsock6);
2988       lsock6 = NULL;
2989     }
2990     else
2991     {
2992       ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2993                                               lsock6, &do_accept, lsock6);
2994     }
2995   }
2996   lsock4 = bind_v4 ();
2997   if (NULL == lsock4)
2998     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2999   else
3000   {
3001     if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
3002     {
3003       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
3004       GNUNET_NETWORK_socket_close (lsock4);
3005       lsock4 = NULL;
3006     }
3007     else
3008     {
3009       ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3010                                               lsock4, &do_accept, lsock4);
3011     }
3012   }
3013   if ( (NULL == lsock4) &&
3014        (NULL == lsock6) )
3015   {
3016     GNUNET_SCHEDULER_shutdown ();
3017     return;
3018   }
3019   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3020   {
3021     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3022                 "cURL global init failed!\n");
3023     GNUNET_SCHEDULER_shutdown ();
3024     return;
3025   }
3026   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3027               "Proxy listens on port %lu\n",
3028               port);
3029
3030   /* start MHD daemon for HTTP */
3031   hd = GNUNET_new (struct MhdHttpList);
3032   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
3033                                  0,
3034                                  NULL, NULL,
3035                                  &create_response, hd,
3036                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3037                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3038                                  MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
3039                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3040                                  MHD_OPTION_END);
3041   if (NULL == hd->daemon)
3042   {
3043     GNUNET_free (hd);
3044     GNUNET_SCHEDULER_shutdown ();
3045     return;
3046   }
3047   httpd = hd;
3048   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
3049 }
3050
3051
3052 /**
3053  * Method called to inform about the egos of the shorten zone of this peer.
3054  *
3055  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
3056  * this function is only called ONCE, and 'NULL' being passed in
3057  * @a ego does indicate an error (i.e. name is taken or no default
3058  * value is known).  If @a ego is non-NULL and if '*ctx'
3059  * is set in those callbacks, the value WILL be passed to a subsequent
3060  * call to the identity callback of #GNUNET_IDENTITY_connect (if
3061  * that one was not NULL).
3062  *
3063  * @param cls closure, NULL
3064  * @param ego ego handle
3065  * @param ctx context for application to store data for this ego
3066  *                 (during the lifetime of this process, initially NULL)
3067  * @param name name assigned by the user for this ego,
3068  *                   NULL if the user just deleted the ego and it
3069  *                   must thus no longer be used
3070  */
3071 static void
3072 identity_shorten_cb (void *cls,
3073                      struct GNUNET_IDENTITY_Ego *ego,
3074                      void **ctx,
3075                      const char *name)
3076 {
3077   id_op = NULL;
3078   if (NULL == ego)
3079   {
3080     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3081                 _("No ego configured for `shorten-zone`\n"));
3082   }
3083   else
3084   {
3085     local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
3086     do_shorten = GNUNET_YES;
3087   }
3088   run_cont ();
3089 }
3090
3091
3092 /**
3093  * Method called to inform about the egos of the master zone of this peer.
3094  *
3095  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
3096  * this function is only called ONCE, and 'NULL' being passed in
3097  * @a ego does indicate an error (i.e. name is taken or no default
3098  * value is known).  If @a ego is non-NULL and if '*ctx'
3099  * is set in those callbacks, the value WILL be passed to a subsequent
3100  * call to the identity callback of #GNUNET_IDENTITY_connect (if
3101  * that one was not NULL).
3102  *
3103  * @param cls closure, NULL
3104  * @param ego ego handle
3105  * @param ctx context for application to store data for this ego
3106  *                 (during the lifetime of this process, initially NULL)
3107  * @param name name assigned by the user for this ego,
3108  *                   NULL if the user just deleted the ego and it
3109  *                   must thus no longer be used
3110  */
3111 static void
3112 identity_master_cb (void *cls,
3113                     struct GNUNET_IDENTITY_Ego *ego,
3114                     void **ctx,
3115                     const char *name)
3116 {
3117   id_op = NULL;
3118   if (NULL == ego)
3119   {
3120     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3121                 _("No ego configured for `%s`\n"),
3122                 "gns-proxy");
3123     GNUNET_SCHEDULER_shutdown ();
3124     return;
3125   }
3126   GNUNET_IDENTITY_ego_get_public_key (ego,
3127                                       &local_gns_zone);
3128   id_op = GNUNET_IDENTITY_get (identity,
3129                                "gns-short",
3130                                &identity_shorten_cb,
3131                                NULL);
3132 }
3133
3134
3135 /**
3136  * Main function that will be run
3137  *
3138  * @param cls closure
3139  * @param args remaining command-line arguments
3140  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3141  * @param c configuration
3142  */
3143 static void
3144 run (void *cls, char *const *args, const char *cfgfile,
3145      const struct GNUNET_CONFIGURATION_Handle *c)
3146 {
3147   char* cafile_cfg = NULL;
3148   char* cafile;
3149
3150   cfg = c;
3151
3152   if (NULL == (curl_multi = curl_multi_init ()))
3153   {
3154     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3155                 "Failed to create cURL multi handle!\n");
3156     return;
3157   }
3158   cafile = cafile_opt;
3159   if (NULL == cafile)
3160   {
3161     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3162                                                               "PROXY_CACERT",
3163                                                               &cafile_cfg))
3164     {
3165       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3166                                  "gns-proxy",
3167                                  "PROXY_CACERT");
3168       return;
3169     }
3170     cafile = cafile_cfg;
3171   }
3172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3173               "Using %s as CA\n", cafile);
3174
3175   gnutls_global_init ();
3176   gnutls_x509_crt_init (&proxy_ca.cert);
3177   gnutls_x509_privkey_init (&proxy_ca.key);
3178
3179   if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
3180        (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
3181   {
3182     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3183                 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
3184                 cafile);
3185     gnutls_x509_crt_deinit (proxy_ca.cert);
3186     gnutls_x509_privkey_deinit (proxy_ca.key);
3187     gnutls_global_deinit ();
3188     GNUNET_free_non_null (cafile_cfg);
3189     return;
3190   }
3191   GNUNET_free_non_null (cafile_cfg);
3192   if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3193   {
3194     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3195                 "Unable to connect to GNS!\n");
3196     gnutls_x509_crt_deinit (proxy_ca.cert);
3197     gnutls_x509_privkey_deinit (proxy_ca.key);
3198     gnutls_global_deinit ();
3199     return;
3200   }
3201   identity = GNUNET_IDENTITY_connect (cfg,
3202                                       NULL, NULL);
3203   id_op = GNUNET_IDENTITY_get (identity,
3204                                "gns-proxy",
3205                                &identity_master_cb,
3206                                NULL);
3207   GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
3208 }
3209
3210
3211 /**
3212  * The main function for gnunet-gns-proxy.
3213  *
3214  * @param argc number of arguments from the command line
3215  * @param argv command line arguments
3216  * @return 0 ok, 1 on error
3217  */
3218 int
3219 main (int argc, char *const *argv)
3220 {
3221   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3222     {'p', "port", NULL,
3223       gettext_noop ("listen on specified port (default: 7777)"), 1,
3224       &GNUNET_GETOPT_set_ulong, &port},
3225     {'a', "authority", NULL,
3226       gettext_noop ("pem file to use as CA"), 1,
3227       &GNUNET_GETOPT_set_string, &cafile_opt},
3228     GNUNET_GETOPT_OPTION_END
3229   };
3230   static const char* page =
3231     "<html><head><title>gnunet-gns-proxy</title>"
3232     "</head><body>cURL fail</body></html>";
3233   int ret;
3234
3235   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3236     return 2;
3237   GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3238   curl_failure_response = MHD_create_response_from_buffer (strlen (page),
3239                                                            (void*)page,
3240                                                            MHD_RESPMEM_PERSISTENT);
3241
3242   ret =
3243     (GNUNET_OK ==
3244      GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3245                          _("GNUnet GNS proxy"),
3246                          options,
3247                          &run, NULL)) ? 0 : 1;
3248   MHD_destroy_response (curl_failure_response);
3249   GNUNET_free_non_null ((char *) argv);
3250   GNUNET_CRYPTO_ecdsa_key_clear (&local_shorten_zone);
3251   return ret;
3252 }
3253
3254 /* end of gnunet-gns-proxy.c */