Use statement exprs instead of local function
[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   {
1143     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1144                 "Adding header %s: %s to MHD response\n",
1145                 hdr_type,
1146                 hdr_val);
1147     GNUNET_break (MHD_YES ==
1148                   MHD_add_response_header (s5r->response,
1149                                            hdr_type,
1150                                            hdr_val));
1151   }
1152   GNUNET_free (ndup);
1153   GNUNET_free_non_null (new_cookie_hdr);
1154   GNUNET_free_non_null (new_location);
1155   return bytes;
1156 }
1157
1158
1159 /**
1160  * Handle response payload data from cURL.  Copies it into our `io_buf` to make
1161  * it available to MHD.
1162  *
1163  * @param ptr pointer to the data
1164  * @param size number of blocks of data
1165  * @param nmemb blocksize
1166  * @param ctx our `struct Socks5Request *`
1167  * @return number of bytes handled
1168  */
1169 static size_t
1170 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1171 {
1172   struct Socks5Request *s5r = ctx;
1173   size_t total = size * nmemb;
1174
1175   if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1176        (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1177   {
1178     /* we're still not done with the upload, do not yet
1179        start the download, the IO buffer is still full
1180        with upload data. */
1181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1182                 "Pausing CURL download, waiting for UPLOAD to finish\n");
1183     return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1184   }
1185   if (sizeof (s5r->io_buf) - s5r->io_len < total)
1186   {
1187     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1188                 "Pausing CURL download, not enough space\n");
1189     return CURL_WRITEFUNC_PAUSE; /* not enough space */
1190   }
1191   GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1192           ptr,
1193           total);
1194   s5r->io_len += total;
1195   if (s5r->io_len == total)
1196     run_mhd_now (s5r->hd);
1197   return total;
1198 }
1199
1200
1201 /**
1202  * cURL callback for uploaded (PUT/POST) data.  Copies it into our `io_buf`
1203  * to make it available to MHD.
1204  *
1205  * @param buf where to write the data
1206  * @param size number of bytes per member
1207  * @param nmemb number of members available in @a buf
1208  * @param cls our `struct Socks5Request` that generated the data
1209  * @return number of bytes copied to @a buf
1210  */
1211 static size_t
1212 curl_upload_cb (void *buf, size_t size, size_t nmemb, void *cls)
1213 {
1214   struct Socks5Request *s5r = cls;
1215   size_t len = size * nmemb;
1216   size_t to_copy;
1217
1218   if ( (0 == s5r->io_len) &&
1219        (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1220   {
1221     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1222                 "Pausing CURL UPLOAD, need more data\n");
1223     return CURL_READFUNC_PAUSE;
1224   }
1225   if ( (0 == s5r->io_len) &&
1226        (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1227   {
1228     s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1229     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1230                 "Completed CURL UPLOAD\n");
1231     return 0; /* upload finished, can now download */
1232   }
1233   if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
1234        (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1235   {
1236     GNUNET_break (0);
1237     return CURL_READFUNC_ABORT;
1238   }
1239   to_copy = GNUNET_MIN (s5r->io_len,
1240                         len);
1241   GNUNET_memcpy (buf, s5r->io_buf, to_copy);
1242   memmove (s5r->io_buf,
1243            &s5r->io_buf[to_copy],
1244            s5r->io_len - to_copy);
1245   s5r->io_len -= to_copy;
1246   if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1247     run_mhd_now (s5r->hd); /* got more space for upload now */
1248   return to_copy;
1249 }
1250
1251
1252 /* ************************** main loop of cURL interaction ****************** */
1253
1254
1255 /**
1256  * Task that is run when we are ready to receive more data
1257  * from curl
1258  *
1259  * @param cls closure
1260  */
1261 static void
1262 curl_task_download (void *cls);
1263
1264
1265 /**
1266  * Ask cURL for the select() sets and schedule cURL operations.
1267  */
1268 static void
1269 curl_download_prepare ()
1270 {
1271   CURLMcode mret;
1272   fd_set rs;
1273   fd_set ws;
1274   fd_set es;
1275   int max;
1276   struct GNUNET_NETWORK_FDSet *grs;
1277   struct GNUNET_NETWORK_FDSet *gws;
1278   long to;
1279   struct GNUNET_TIME_Relative rtime;
1280
1281   if (NULL != curl_download_task)
1282   {
1283     GNUNET_SCHEDULER_cancel (curl_download_task);
1284     curl_download_task = NULL;
1285   }
1286   max = -1;
1287   FD_ZERO (&rs);
1288   FD_ZERO (&ws);
1289   FD_ZERO (&es);
1290   if (CURLM_OK != (mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max)))
1291   {
1292     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1293                 "%s failed at %s:%d: `%s'\n",
1294                 "curl_multi_fdset", __FILE__, __LINE__,
1295                 curl_multi_strerror (mret));
1296     return;
1297   }
1298   to = -1;
1299   GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
1300   if (-1 == to)
1301     rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1302   else
1303     rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1304   if (-1 != max)
1305   {
1306     grs = GNUNET_NETWORK_fdset_create ();
1307     gws = GNUNET_NETWORK_fdset_create ();
1308     GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1309     GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1310     curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1311                                                       rtime,
1312                                                       grs, gws,
1313                                                       &curl_task_download, curl_multi);
1314     GNUNET_NETWORK_fdset_destroy (gws);
1315     GNUNET_NETWORK_fdset_destroy (grs);
1316   }
1317   else
1318   {
1319     curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1320                                                        &curl_task_download,
1321                                                        curl_multi);
1322   }
1323 }
1324
1325
1326 /**
1327  * Task that is run when we are ready to receive more data from curl.
1328  *
1329  * @param cls closure, NULL
1330  */
1331 static void
1332 curl_task_download (void *cls)
1333 {
1334   int running;
1335   int msgnum;
1336   struct CURLMsg *msg;
1337   CURLMcode mret;
1338   struct Socks5Request *s5r;
1339
1340   curl_download_task = NULL;
1341   do
1342   {
1343     running = 0;
1344     mret = curl_multi_perform (curl_multi, &running);
1345     while (NULL != (msg = curl_multi_info_read (curl_multi, &msgnum)))
1346     {
1347       GNUNET_break (CURLE_OK ==
1348                     curl_easy_getinfo (msg->easy_handle,
1349                                        CURLINFO_PRIVATE,
1350                                        (char **) &s5r ));
1351       if (NULL == s5r)
1352       {
1353         GNUNET_break (0);
1354         continue;
1355       }
1356       switch (msg->msg)
1357       {
1358       case CURLMSG_NONE:
1359         /* documentation says this is not used */
1360         GNUNET_break (0);
1361         break;
1362       case CURLMSG_DONE:
1363         switch (msg->data.result)
1364         {
1365         case CURLE_OK:
1366         case CURLE_GOT_NOTHING:
1367           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1368                       "CURL download completed.\n");
1369           s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1370           run_mhd_now (s5r->hd);
1371           break;
1372         default:
1373           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1374                       "Download curl failed: %s\n",
1375                       curl_easy_strerror (msg->data.result));
1376           /* FIXME: indicate error somehow? close MHD connection badly as well? */
1377           s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1378           run_mhd_now (s5r->hd);
1379           break;
1380         }
1381         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1382                     "Cleaning up cURL handle\n");
1383         curl_multi_remove_handle (curl_multi, s5r->curl);
1384         curl_easy_cleanup (s5r->curl);
1385         s5r->curl = NULL;
1386         if (NULL == s5r->response)
1387           s5r->response = curl_failure_response;
1388         break;
1389       case CURLMSG_LAST:
1390         /* documentation says this is not used */
1391         GNUNET_break (0);
1392         break;
1393       default:
1394         /* unexpected status code */
1395         GNUNET_break (0);
1396         break;
1397       }
1398     };
1399   } while (mret == CURLM_CALL_MULTI_PERFORM);
1400   if (CURLM_OK != mret)
1401     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1402                 "%s failed at %s:%d: `%s'\n",
1403                 "curl_multi_perform", __FILE__, __LINE__,
1404                 curl_multi_strerror (mret));
1405   if (0 == running)
1406   {
1407     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1408                 "Suspending cURL multi loop, no more events pending\n");
1409     return; /* nothing more in progress */
1410   }
1411   curl_download_prepare ();
1412 }
1413
1414
1415 /* ********************************* MHD response generation ******************* */
1416
1417
1418 /**
1419  * Read HTTP request header field from the request.  Copies the fields
1420  * over to the 'headers' that will be given to curl.  However, 'Host'
1421  * is substituted with the LEHO if present.  We also change the
1422  * 'Connection' header value to "close" as the proxy does not support
1423  * pipelining.
1424  *
1425  * @param cls our `struct Socks5Request`
1426  * @param kind value kind
1427  * @param key field key
1428  * @param value field value
1429  * @return MHD_YES to continue to iterate
1430  */
1431 static int
1432 con_val_iter (void *cls,
1433               enum MHD_ValueKind kind,
1434               const char *key,
1435               const char *value)
1436 {
1437   struct Socks5Request *s5r = cls;
1438   char *hdr;
1439
1440   if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1441        (NULL != s5r->leho) )
1442     value = s5r->leho;
1443   if (0 == strcasecmp (MHD_HTTP_HEADER_CONNECTION, key))
1444     value = "Close";
1445   GNUNET_asprintf (&hdr,
1446                    "%s: %s",
1447                    key,
1448                    value);
1449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450               "Adding HEADER `%s' to HTTP request\n",
1451               hdr);
1452   s5r->headers = curl_slist_append (s5r->headers,
1453                                     hdr);
1454   GNUNET_free (hdr);
1455   return MHD_YES;
1456 }
1457
1458
1459 /**
1460  * Main MHD callback for handling requests.
1461  *
1462  * @param cls unused
1463  * @param con MHD connection handle
1464  * @param url the url in the request
1465  * @param meth the HTTP method used ("GET", "PUT", etc.)
1466  * @param ver the HTTP version string (i.e. "HTTP/1.1")
1467  * @param upload_data the data being uploaded (excluding HEADERS,
1468  *        for a POST that fits into memory and that is encoded
1469  *        with a supported encoding, the POST data will NOT be
1470  *        given in upload_data and is instead available as
1471  *        part of MHD_get_connection_values; very large POST
1472  *        data *will* be made available incrementally in
1473  *        upload_data)
1474  * @param upload_data_size set initially to the size of the
1475  *        @a upload_data provided; the method must update this
1476  *        value to the number of bytes NOT processed;
1477  * @param con_cls pointer to location where we store the 'struct Request'
1478  * @return MHD_YES if the connection was handled successfully,
1479  *         MHD_NO if the socket must be closed due to a serious
1480  *         error while handling the request
1481  */
1482 static int
1483 create_response (void *cls,
1484                  struct MHD_Connection *con,
1485                  const char *url,
1486                  const char *meth,
1487                  const char *ver,
1488                  const char *upload_data,
1489                  size_t *upload_data_size,
1490                  void **con_cls)
1491 {
1492   struct Socks5Request *s5r = *con_cls;
1493   char *curlurl;
1494   char *curl_hosts;
1495   char ipstring[INET6_ADDRSTRLEN];
1496   char ipaddr[INET6_ADDRSTRLEN + 2];
1497   const struct sockaddr *sa;
1498   const struct sockaddr_in *s4;
1499   const struct sockaddr_in6 *s6;
1500   uint16_t port;
1501   size_t left;
1502
1503   if (NULL == s5r)
1504   {
1505     GNUNET_break (0);
1506     return MHD_NO;
1507   }
1508   if ( (NULL == s5r->curl) &&
1509        (SOCKS5_SOCKET_WITH_MHD == s5r->state) )
1510   {
1511     /* first time here, initialize curl handle */
1512     sa = (const struct sockaddr *) &s5r->destination_address;
1513     switch (sa->sa_family)
1514     {
1515     case AF_INET:
1516       s4 = (const struct sockaddr_in *) &s5r->destination_address;
1517       if (NULL == inet_ntop (AF_INET,
1518                              &s4->sin_addr,
1519                              ipstring,
1520                              sizeof (ipstring)))
1521       {
1522         GNUNET_break (0);
1523         return MHD_NO;
1524       }
1525       GNUNET_snprintf (ipaddr,
1526                        sizeof (ipaddr),
1527                        "%s",
1528                        ipstring);
1529       port = ntohs (s4->sin_port);
1530       break;
1531     case AF_INET6:
1532       s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1533       if (NULL == inet_ntop (AF_INET6,
1534                              &s6->sin6_addr,
1535                              ipstring,
1536                              sizeof (ipstring)))
1537       {
1538         GNUNET_break (0);
1539         return MHD_NO;
1540       }
1541       GNUNET_snprintf (ipaddr,
1542                        sizeof (ipaddr),
1543                        "[%s]",
1544                        ipstring);
1545       port = ntohs (s6->sin6_port);
1546       break;
1547     default:
1548       GNUNET_break (0);
1549       return MHD_NO;
1550     }
1551     s5r->curl = curl_easy_init ();
1552     if (NULL == s5r->curl)
1553       return MHD_queue_response (con,
1554                                  MHD_HTTP_INTERNAL_SERVER_ERROR,
1555                                  curl_failure_response);
1556     curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1557     curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1558     curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1559     curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1560     curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1561     curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1562     curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1563     curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1564     curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1565     curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1566     curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1567     curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0);
1568     /**
1569      * Pre-populate cache to resolve Hostname.
1570      * This is necessary as the DNS name in the CURLOPT_URL is used
1571      * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1572      */
1573     if (NULL != s5r->leho)
1574     {
1575         GNUNET_asprintf (&curl_hosts,
1576                          "%s:%d:%s",
1577                          s5r->leho,
1578                          port,
1579                          ipaddr);
1580         s5r->hosts = curl_slist_append(NULL, curl_hosts);
1581         curl_easy_setopt(s5r->curl, CURLOPT_RESOLVE, s5r->hosts);
1582         GNUNET_free (curl_hosts);
1583     }
1584     GNUNET_asprintf (&curlurl,
1585                      (HTTPS_PORT != s5r->port)
1586                      ? "http://%s:%d%s"
1587                      : "https://%s:%d%s",
1588                      (NULL != s5r->leho)
1589                      ? s5r->leho
1590                      : ipaddr,
1591                      port,
1592                      s5r->url);
1593     curl_easy_setopt (s5r->curl,
1594                       CURLOPT_URL,
1595                       curlurl);
1596     GNUNET_free (curlurl);
1597
1598     if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1599     {
1600       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1601       curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
1602       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1603       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1604       curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1605       curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1606     }
1607     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1608     {
1609       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1610       curl_easy_setopt (s5r->curl, CURLOPT_POST, 1);
1611       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1612       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1613       curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1614       curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1615     }
1616     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1617     {
1618       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1619       curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
1620     }
1621     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1622     {
1623       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1624       curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
1625       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1626       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1627     }
1628     else
1629     {
1630       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1631                   _("Unsupported HTTP method `%s'\n"),
1632                   meth);
1633       curl_easy_cleanup (s5r->curl);
1634       s5r->curl = NULL;
1635       return MHD_NO;
1636     }
1637
1638     if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1639     {
1640       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1641     }
1642     else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1643     {
1644       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1645     }
1646     else
1647     {
1648       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1649     }
1650
1651     if (HTTPS_PORT == s5r->port)
1652     {
1653       curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1654       curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1655       /* Disable cURL checking the hostname, as we will check ourselves
1656          as only we have the domain name or the LEHO or the DANE record */
1657       curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
1658     }
1659     else
1660     {
1661       curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
1662     }
1663
1664     if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
1665     {
1666       GNUNET_break (0);
1667       curl_easy_cleanup (s5r->curl);
1668       s5r->curl = NULL;
1669       return MHD_NO;
1670     }
1671     MHD_get_connection_values (con,
1672                                MHD_HEADER_KIND,
1673                                &con_val_iter, s5r);
1674     curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
1675     curl_download_prepare ();
1676     return MHD_YES;
1677   }
1678
1679   /* continuing to process request */
1680   if (0 != *upload_data_size)
1681   {
1682     left = GNUNET_MIN (*upload_data_size,
1683                        sizeof (s5r->io_buf) - s5r->io_len);
1684     GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1685             upload_data,
1686             left);
1687     s5r->io_len += left;
1688     *upload_data_size -= left;
1689     GNUNET_assert (NULL != s5r->curl);
1690     curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
1691     curl_download_prepare ();
1692     return MHD_YES;
1693   }
1694   if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
1695   {
1696     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1697                 "Finished processing UPLOAD\n");
1698     s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1699   }
1700   if (NULL == s5r->response)
1701     return MHD_YES; /* too early to queue response, did not yet get headers from cURL */
1702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1703               "Queueing response with MHD\n");
1704   return MHD_queue_response (con,
1705                              s5r->response_code,
1706                              s5r->response);
1707 }
1708
1709
1710 /* ******************** MHD HTTP setup and event loop ******************** */
1711
1712
1713 /**
1714  * Function called when MHD decides that we are done with a connection.
1715  *
1716  * @param cls NULL
1717  * @param connection connection handle
1718  * @param con_cls value as set by the last call to
1719  *        the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
1720  * @param toe reason for request termination (ignored)
1721  */
1722 static void
1723 mhd_completed_cb (void *cls,
1724                   struct MHD_Connection *connection,
1725                   void **con_cls,
1726                   enum MHD_RequestTerminationCode toe)
1727 {
1728   struct Socks5Request *s5r = *con_cls;
1729
1730   if (NULL == s5r)
1731     return;
1732   if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
1733     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1734                 "MHD encountered error handling request: %d\n",
1735                 toe);
1736   cleanup_s5r (s5r);
1737   curl_download_prepare();
1738   *con_cls = NULL;
1739 }
1740
1741
1742 /**
1743  * Function called when MHD first processes an incoming connection.
1744  * Gives us the respective URI information.
1745  *
1746  * We use this to associate the `struct MHD_Connection` with our
1747  * internal `struct Socks5Request` data structure (by checking
1748  * for matching sockets).
1749  *
1750  * @param cls the HTTP server handle (a `struct MhdHttpList`)
1751  * @param url the URL that is being requested
1752  * @param connection MHD connection object for the request
1753  * @return the `struct Socks5Request` that this @a connection is for
1754  */
1755 static void *
1756 mhd_log_callback (void *cls,
1757                   const char *url,
1758                   struct MHD_Connection *connection)
1759 {
1760   struct Socks5Request *s5r;
1761   const union MHD_ConnectionInfo *ci;
1762   int sock;
1763
1764   ci = MHD_get_connection_info (connection,
1765                                 MHD_CONNECTION_INFO_CONNECTION_FD);
1766   if (NULL == ci)
1767   {
1768     GNUNET_break (0);
1769     return NULL;
1770   }
1771   sock = ci->connect_fd;
1772   for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1773   {
1774     if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1775     {
1776       if (NULL != s5r->url)
1777       {
1778         GNUNET_break (0);
1779         return NULL;
1780       }
1781       s5r->url = GNUNET_strdup (url);
1782       GNUNET_SCHEDULER_cancel (s5r->timeout_task);
1783       s5r->timeout_task = NULL;
1784       return s5r;
1785     }
1786   }
1787   GNUNET_break (0);
1788   return NULL;
1789 }
1790
1791
1792 /**
1793  * Kill the given MHD daemon.
1794  *
1795  * @param hd daemon to stop
1796  */
1797 static void
1798 kill_httpd (struct MhdHttpList *hd)
1799 {
1800   GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1801                                mhd_httpd_tail,
1802                                hd);
1803   GNUNET_free_non_null (hd->domain);
1804   MHD_stop_daemon (hd->daemon);
1805   if (NULL != hd->httpd_task)
1806   {
1807     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1808     hd->httpd_task = NULL;
1809   }
1810   GNUNET_free_non_null (hd->proxy_cert);
1811   if (hd == httpd)
1812     httpd = NULL;
1813   GNUNET_free (hd);
1814 }
1815
1816
1817 /**
1818  * Task run whenever HTTP server is idle for too long. Kill it.
1819  *
1820  * @param cls the `struct MhdHttpList *`
1821  */
1822 static void
1823 kill_httpd_task (void *cls)
1824 {
1825   struct MhdHttpList *hd = cls;
1826
1827   hd->httpd_task = NULL;
1828   kill_httpd (hd);
1829 }
1830
1831
1832 /**
1833  * Task run whenever HTTP server operations are pending.
1834  *
1835  * @param cls the `struct MhdHttpList *` of the daemon that is being run
1836  */
1837 static void
1838 do_httpd (void *cls);
1839
1840
1841 /**
1842  * Schedule MHD.  This function should be called initially when an
1843  * MHD is first getting its client socket, and will then automatically
1844  * always be called later whenever there is work to be done.
1845  *
1846  * @param hd the daemon to schedule
1847  */
1848 static void
1849 schedule_httpd (struct MhdHttpList *hd)
1850 {
1851   fd_set rs;
1852   fd_set ws;
1853   fd_set es;
1854   struct GNUNET_NETWORK_FDSet *wrs;
1855   struct GNUNET_NETWORK_FDSet *wws;
1856   int max;
1857   int haveto;
1858   MHD_UNSIGNED_LONG_LONG timeout;
1859   struct GNUNET_TIME_Relative tv;
1860
1861   FD_ZERO (&rs);
1862   FD_ZERO (&ws);
1863   FD_ZERO (&es);
1864   max = -1;
1865   if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1866   {
1867     kill_httpd (hd);
1868     return;
1869   }
1870   haveto = MHD_get_timeout (hd->daemon, &timeout);
1871   if (MHD_YES == haveto)
1872     tv.rel_value_us = (uint64_t) timeout * 1000LL;
1873   else
1874     tv = GNUNET_TIME_UNIT_FOREVER_REL;
1875   if (-1 != max)
1876   {
1877     wrs = GNUNET_NETWORK_fdset_create ();
1878     wws = GNUNET_NETWORK_fdset_create ();
1879     GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1880     GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1881   }
1882   else
1883   {
1884     wrs = NULL;
1885     wws = NULL;
1886   }
1887   if (NULL != hd->httpd_task)
1888     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1889   if ( (MHD_YES != haveto) &&
1890        (-1 == max) &&
1891        (hd != httpd) )
1892   {
1893     /* daemon is idle, kill after timeout */
1894     hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
1895                                                    &kill_httpd_task,
1896                                                    hd);
1897   }
1898   else
1899   {
1900     hd->httpd_task =
1901       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1902                                    tv, wrs, wws,
1903                                    &do_httpd, hd);
1904   }
1905   if (NULL != wrs)
1906     GNUNET_NETWORK_fdset_destroy (wrs);
1907   if (NULL != wws)
1908     GNUNET_NETWORK_fdset_destroy (wws);
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   struct MhdHttpList *hd = cls;
1921
1922   hd->httpd_task = NULL;
1923   MHD_run (hd->daemon);
1924   schedule_httpd (hd);
1925 }
1926
1927
1928 /**
1929  * Run MHD now, we have extra data ready for the callback.
1930  *
1931  * @param hd the daemon to run now.
1932  */
1933 static void
1934 run_mhd_now (struct MhdHttpList *hd)
1935 {
1936   if (NULL !=
1937       hd->httpd_task)
1938     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1939   hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
1940                                              hd);
1941 }
1942
1943
1944 /**
1945  * Read file in filename
1946  *
1947  * @param filename file to read
1948  * @param size pointer where filesize is stored
1949  * @return NULL on error
1950  */
1951 static void*
1952 load_file (const char* filename,
1953            unsigned int* size)
1954 {
1955   void *buffer;
1956   uint64_t fsize;
1957
1958   if (GNUNET_OK !=
1959       GNUNET_DISK_file_size (filename, &fsize,
1960                              GNUNET_YES, GNUNET_YES))
1961     return NULL;
1962   if (fsize > MAX_PEM_SIZE)
1963     return NULL;
1964   *size = (unsigned int) fsize;
1965   buffer = GNUNET_malloc (*size);
1966   if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
1967   {
1968     GNUNET_free (buffer);
1969     return NULL;
1970   }
1971   return buffer;
1972 }
1973
1974
1975 /**
1976  * Load PEM key from file
1977  *
1978  * @param key where to store the data
1979  * @param keyfile path to the PEM file
1980  * @return #GNUNET_OK on success
1981  */
1982 static int
1983 load_key_from_file (gnutls_x509_privkey_t key,
1984                     const char* keyfile)
1985 {
1986   gnutls_datum_t key_data;
1987   int ret;
1988
1989   key_data.data = load_file (keyfile, &key_data.size);
1990   if (NULL == key_data.data)
1991     return GNUNET_SYSERR;
1992   ret = gnutls_x509_privkey_import (key, &key_data,
1993                                     GNUTLS_X509_FMT_PEM);
1994   if (GNUTLS_E_SUCCESS != ret)
1995   {
1996     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1997                 _("Unable to import private key from file `%s'\n"),
1998                 keyfile);
1999   }
2000   GNUNET_free_non_null (key_data.data);
2001   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2002 }
2003
2004
2005 /**
2006  * Load cert from file
2007  *
2008  * @param crt struct to store data in
2009  * @param certfile path to pem file
2010  * @return #GNUNET_OK on success
2011  */
2012 static int
2013 load_cert_from_file (gnutls_x509_crt_t crt,
2014                      const char* certfile)
2015 {
2016   gnutls_datum_t cert_data;
2017   int ret;
2018
2019   cert_data.data = load_file (certfile, &cert_data.size);
2020   if (NULL == cert_data.data)
2021     return GNUNET_SYSERR;
2022   ret = gnutls_x509_crt_import (crt, &cert_data,
2023                                 GNUTLS_X509_FMT_PEM);
2024   if (GNUTLS_E_SUCCESS != ret)
2025   {
2026     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2027                _("Unable to import certificate %s\n"), certfile);
2028   }
2029   GNUNET_free_non_null (cert_data.data);
2030   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2031 }
2032
2033
2034 /**
2035  * Generate new certificate for specific name
2036  *
2037  * @param name the subject name to generate a cert for
2038  * @return a struct holding the PEM data, NULL on error
2039  */
2040 static struct ProxyGNSCertificate *
2041 generate_gns_certificate (const char *name)
2042 {
2043   unsigned int serial;
2044   size_t key_buf_size;
2045   size_t cert_buf_size;
2046   gnutls_x509_crt_t request;
2047   time_t etime;
2048   struct tm *tm_data;
2049   struct ProxyGNSCertificate *pgc;
2050
2051   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2052               "Generating TLS/SSL certificate for `%s'\n",
2053               name);
2054   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2055   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2056   pgc = GNUNET_new (struct ProxyGNSCertificate);
2057   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2058                                  0, "ZZ", 2);
2059   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2060                                  0, "GNU Name System", 4);
2061   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2062                                  0, name, strlen (name));
2063   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
2064   gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2065   gnutls_x509_crt_set_serial (request,
2066                               &serial,
2067                               sizeof (serial));
2068   etime = time (NULL);
2069   tm_data = localtime (&etime);
2070   gnutls_x509_crt_set_activation_time (request,
2071                                        etime);
2072   tm_data->tm_year++;
2073   etime = mktime (tm_data);
2074   gnutls_x509_crt_set_expiration_time (request,
2075                                        etime);
2076   gnutls_x509_crt_sign (request,
2077                         proxy_ca.cert,
2078                         proxy_ca.key);
2079   key_buf_size = sizeof (pgc->key);
2080   cert_buf_size = sizeof (pgc->cert);
2081   gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2082                           pgc->cert, &cert_buf_size);
2083   gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2084                               pgc->key, &key_buf_size);
2085   gnutls_x509_crt_deinit (request);
2086   return pgc;
2087 }
2088
2089
2090 /**
2091  * Function called by MHD with errors, suppresses them all.
2092  *
2093  * @param cls closure
2094  * @param fm format string (`printf()`-style)
2095  * @param ap arguments to @a fm
2096  */
2097 static void
2098 mhd_error_log_callback (void *cls,
2099                         const char *fm,
2100                         va_list ap)
2101 {
2102   /* do nothing */
2103 }
2104
2105
2106 /**
2107  * Lookup (or create) an SSL MHD instance for a particular domain.
2108  *
2109  * @param domain the domain the SSL daemon has to serve
2110  * @return NULL on error
2111  */
2112 static struct MhdHttpList *
2113 lookup_ssl_httpd (const char* domain)
2114 {
2115   struct MhdHttpList *hd;
2116   struct ProxyGNSCertificate *pgc;
2117
2118   if (NULL == domain)
2119   {
2120     GNUNET_break (0);
2121     return NULL;
2122   }
2123   for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2124     if ( (NULL != hd->domain) &&
2125          (0 == strcmp (hd->domain, domain)) )
2126       return hd;
2127   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2128               "Starting fresh MHD HTTPS instance for domain `%s'\n",
2129               domain);
2130   pgc = generate_gns_certificate (domain);
2131   hd = GNUNET_new (struct MhdHttpList);
2132   hd->is_ssl = GNUNET_YES;
2133   hd->domain = GNUNET_strdup (domain);
2134   hd->proxy_cert = pgc;
2135   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
2136                                  0,
2137                                  NULL, NULL,
2138                                  &create_response, hd,
2139                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2140                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2141                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2142                                  MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2143                                  MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2144                                  MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2145                                  MHD_OPTION_END);
2146   if (NULL == hd->daemon)
2147   {
2148     GNUNET_free (pgc);
2149     GNUNET_free (hd);
2150     return NULL;
2151   }
2152   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2153                                mhd_httpd_tail,
2154                                hd);
2155   return hd;
2156 }
2157
2158
2159 /**
2160  * Task run when a Socks5Request somehow fails to be associated with
2161  * an MHD connection (i.e. because the client never speaks HTTP after
2162  * the SOCKS5 handshake).  Clean up.
2163  *
2164  * @param cls the `struct Socks5Request *`
2165  */
2166 static void
2167 timeout_s5r_handshake (void *cls)
2168 {
2169   struct Socks5Request *s5r = cls;
2170
2171   s5r->timeout_task = NULL;
2172   cleanup_s5r (s5r);
2173 }
2174
2175
2176 /**
2177  * We're done with the Socks5 protocol, now we need to pass the
2178  * connection data through to the final destination, either
2179  * direct (if the protocol might not be HTTP), or via MHD
2180  * (if the port looks like it should be HTTP).
2181  *
2182  * @param s5r socks request that has reached the final stage
2183  */
2184 static void
2185 setup_data_transfer (struct Socks5Request *s5r)
2186 {
2187   struct MhdHttpList *hd;
2188   int fd;
2189   const struct sockaddr *addr;
2190   socklen_t len;
2191
2192   switch (s5r->port)
2193   {
2194   case HTTPS_PORT:
2195     hd = lookup_ssl_httpd (s5r->domain);
2196     if (NULL == hd)
2197     {
2198       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2199                   _("Failed to start HTTPS server for `%s'\n"),
2200                   s5r->domain);
2201       cleanup_s5r (s5r);
2202       return;
2203     }
2204     break;
2205   case HTTP_PORT:
2206   default:
2207     GNUNET_assert (NULL != httpd);
2208     hd = httpd;
2209     break;
2210   }
2211   fd = GNUNET_NETWORK_get_fd (s5r->sock);
2212   addr = GNUNET_NETWORK_get_addr (s5r->sock);
2213   len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2214   s5r->state = SOCKS5_SOCKET_WITH_MHD;
2215   if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
2216   {
2217     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2218                 _("Failed to pass client to MHD\n"));
2219     cleanup_s5r (s5r);
2220     return;
2221   }
2222   s5r->hd = hd;
2223   schedule_httpd (hd);
2224   s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2225                                                     &timeout_s5r_handshake,
2226                                                     s5r);
2227 }
2228
2229
2230 /* ********************* SOCKS handling ************************* */
2231
2232
2233 /**
2234  * Write data from buffer to socks5 client, then continue with state machine.
2235  *
2236  * @param cls the closure with the `struct Socks5Request`
2237  */
2238 static void
2239 do_write (void *cls)
2240 {
2241   struct Socks5Request *s5r = cls;
2242   ssize_t len;
2243
2244   s5r->wtask = NULL;
2245   len = GNUNET_NETWORK_socket_send (s5r->sock,
2246                                     s5r->wbuf,
2247                                     s5r->wbuf_len);
2248   if (len <= 0)
2249   {
2250     /* write error: connection closed, shutdown, etc.; just clean up */
2251     cleanup_s5r (s5r);
2252     return;
2253   }
2254   memmove (s5r->wbuf,
2255            &s5r->wbuf[len],
2256            s5r->wbuf_len - len);
2257   s5r->wbuf_len -= len;
2258   if (s5r->wbuf_len > 0)
2259   {
2260     /* not done writing */
2261     s5r->wtask =
2262       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2263                                       s5r->sock,
2264                                       &do_write, s5r);
2265     return;
2266   }
2267
2268   /* we're done writing, continue with state machine! */
2269
2270   switch (s5r->state)
2271   {
2272   case SOCKS5_INIT:
2273     GNUNET_assert (0);
2274     break;
2275   case SOCKS5_REQUEST:
2276     GNUNET_assert (NULL != s5r->rtask);
2277     break;
2278   case SOCKS5_DATA_TRANSFER:
2279     setup_data_transfer (s5r);
2280     return;
2281   case SOCKS5_WRITE_THEN_CLEANUP:
2282     cleanup_s5r (s5r);
2283     return;
2284   default:
2285     GNUNET_break (0);
2286     break;
2287   }
2288 }
2289
2290
2291 /**
2292  * Return a server response message indicating a failure to the client.
2293  *
2294  * @param s5r request to return failure code for
2295  * @param sc status code to return
2296  */
2297 static void
2298 signal_socks_failure (struct Socks5Request *s5r,
2299                       enum Socks5StatusCode sc)
2300 {
2301   struct Socks5ServerResponseMessage *s_resp;
2302
2303   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2304   memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2305   s_resp->version = SOCKS_VERSION_5;
2306   s_resp->reply = sc;
2307   s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2308   if (NULL != s5r->wtask)
2309     s5r->wtask =
2310       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2311                                       s5r->sock,
2312                                       &do_write, s5r);
2313 }
2314
2315
2316 /**
2317  * Return a server response message indicating success.
2318  *
2319  * @param s5r request to return success status message for
2320  */
2321 static void
2322 signal_socks_success (struct Socks5Request *s5r)
2323 {
2324   struct Socks5ServerResponseMessage *s_resp;
2325
2326   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2327   s_resp->version = SOCKS_VERSION_5;
2328   s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2329   s_resp->reserved = 0;
2330   s_resp->addr_type = SOCKS5_AT_IPV4;
2331   /* zero out IPv4 address and port */
2332   memset (&s_resp[1],
2333           0,
2334           sizeof (struct in_addr) + sizeof (uint16_t));
2335   s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2336     sizeof (struct in_addr) + sizeof (uint16_t);
2337   if (NULL == s5r->wtask)
2338     s5r->wtask =
2339       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2340                                       s5r->sock,
2341                                       &do_write, s5r);
2342 }
2343
2344
2345 /**
2346  * Process GNS results for target domain.
2347  *
2348  * @param cls the `struct Socks5Request *`
2349  * @param rd_count number of records returned
2350  * @param rd record data
2351  */
2352 static void
2353 handle_gns_result (void *cls,
2354                    uint32_t rd_count,
2355                    const struct GNUNET_GNSRECORD_Data *rd)
2356 {
2357   struct Socks5Request *s5r = cls;
2358   uint32_t i;
2359   const struct GNUNET_GNSRECORD_Data *r;
2360   int got_ip;
2361
2362   s5r->gns_lookup = NULL;
2363   got_ip = GNUNET_NO;
2364   for (i=0;i<rd_count;i++)
2365   {
2366     r = &rd[i];
2367     switch (r->record_type)
2368     {
2369     case GNUNET_DNSPARSER_TYPE_A:
2370       {
2371         struct sockaddr_in *in;
2372
2373         if (sizeof (struct in_addr) != r->data_size)
2374         {
2375           GNUNET_break_op (0);
2376           break;
2377         }
2378         if (GNUNET_YES == got_ip)
2379           break;
2380         if (GNUNET_OK !=
2381             GNUNET_NETWORK_test_pf (PF_INET))
2382           break;
2383         got_ip = GNUNET_YES;
2384         in = (struct sockaddr_in *) &s5r->destination_address;
2385         in->sin_family = AF_INET;
2386         GNUNET_memcpy (&in->sin_addr,
2387                 r->data,
2388                 r->data_size);
2389         in->sin_port = htons (s5r->port);
2390 #if HAVE_SOCKADDR_IN_SIN_LEN
2391         in->sin_len = sizeof (*in);
2392 #endif
2393       }
2394       break;
2395     case GNUNET_DNSPARSER_TYPE_AAAA:
2396       {
2397         struct sockaddr_in6 *in;
2398
2399         if (sizeof (struct in6_addr) != r->data_size)
2400         {
2401           GNUNET_break_op (0);
2402           break;
2403         }
2404         if (GNUNET_YES == got_ip)
2405           break;
2406         if (GNUNET_OK !=
2407             GNUNET_NETWORK_test_pf (PF_INET))
2408           break;
2409         /* FIXME: allow user to disable IPv6 per configuration option... */
2410         got_ip = GNUNET_YES;
2411         in = (struct sockaddr_in6 *) &s5r->destination_address;
2412         in->sin6_family = AF_INET6;
2413         GNUNET_memcpy (&in->sin6_addr,
2414                 r->data,
2415                 r->data_size);
2416         in->sin6_port = htons (s5r->port);
2417 #if HAVE_SOCKADDR_IN_SIN_LEN
2418         in->sin6_len = sizeof (*in);
2419 #endif
2420       }
2421       break;
2422     case GNUNET_GNSRECORD_TYPE_VPN:
2423       GNUNET_break (0); /* should have been translated within GNS */
2424       break;
2425     case GNUNET_GNSRECORD_TYPE_LEHO:
2426       GNUNET_free_non_null (s5r->leho);
2427       s5r->leho = GNUNET_strndup (r->data,
2428                                   r->data_size);
2429       break;
2430     case GNUNET_GNSRECORD_TYPE_BOX:
2431       {
2432         const struct GNUNET_GNSRECORD_BoxRecord *box;
2433
2434         if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
2435         {
2436           GNUNET_break_op (0);
2437           break;
2438         }
2439         box = r->data;
2440         if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
2441              (ntohs (box->protocol) != IPPROTO_TCP) ||
2442              (ntohs (box->service) != s5r->port) )
2443           break; /* BOX record does not apply */
2444         GNUNET_free_non_null (s5r->dane_data);
2445         s5r->dane_data_len = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
2446         s5r->dane_data = GNUNET_malloc (s5r->dane_data_len);
2447         GNUNET_memcpy (s5r->dane_data,
2448                 &box[1],
2449                 s5r->dane_data_len);
2450         break;
2451       }
2452     default:
2453       /* don't care */
2454       break;
2455     }
2456   }
2457   if (GNUNET_YES != got_ip)
2458   {
2459     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2460                 "Name resolution failed to yield useful IP address.\n");
2461     signal_socks_failure (s5r,
2462                           SOCKS5_STATUS_GENERAL_FAILURE);
2463     return;
2464   }
2465   s5r->state = SOCKS5_DATA_TRANSFER;
2466   signal_socks_success (s5r);
2467 }
2468
2469
2470 /**
2471  * Remove the first @a len bytes from the beginning of the read buffer.
2472  *
2473  * @param s5r the handle clear the read buffer for
2474  * @param len number of bytes in read buffer to advance
2475  */
2476 static void
2477 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2478                      size_t len)
2479 {
2480   GNUNET_assert (len <= s5r->rbuf_len);
2481   memmove (s5r->rbuf,
2482            &s5r->rbuf[len],
2483            s5r->rbuf_len - len);
2484   s5r->rbuf_len -= len;
2485 }
2486
2487
2488 /**
2489  * Read data from incoming Socks5 connection
2490  *
2491  * @param cls the closure with the `struct Socks5Request`
2492  */
2493 static void
2494 do_s5r_read (void *cls)
2495 {
2496   struct Socks5Request *s5r = cls;
2497   const struct Socks5ClientHelloMessage *c_hello;
2498   struct Socks5ServerHelloMessage *s_hello;
2499   const struct Socks5ClientRequestMessage *c_req;
2500   ssize_t rlen;
2501   size_t alen;
2502   const struct GNUNET_SCHEDULER_TaskContext *tc;
2503
2504   s5r->rtask = NULL;
2505   tc = GNUNET_SCHEDULER_get_task_context ();
2506   if ( (NULL != tc->read_ready) &&
2507        (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2508   {
2509     rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2510                                        &s5r->rbuf[s5r->rbuf_len],
2511                                        sizeof (s5r->rbuf) - s5r->rbuf_len);
2512     if (rlen <= 0)
2513     {
2514       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2515                   "socks5 client disconnected.\n");
2516       cleanup_s5r (s5r);
2517       return;
2518     }
2519     s5r->rbuf_len += rlen;
2520   }
2521   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2522                                               s5r->sock,
2523                                               &do_s5r_read, s5r);
2524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2525               "Processing %zu bytes of socks data in state %d\n",
2526               s5r->rbuf_len,
2527               s5r->state);
2528   switch (s5r->state)
2529   {
2530   case SOCKS5_INIT:
2531     c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2532     if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2533          (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2534       return; /* need more data */
2535     if (SOCKS_VERSION_5 != c_hello->version)
2536     {
2537       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2538                   _("Unsupported socks version %d\n"),
2539                   (int) c_hello->version);
2540       cleanup_s5r (s5r);
2541       return;
2542     }
2543     clear_from_s5r_rbuf (s5r,
2544                          sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2545     GNUNET_assert (0 == s5r->wbuf_len);
2546     s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2547     s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2548     s_hello->version = SOCKS_VERSION_5;
2549     s_hello->auth_method = SOCKS_AUTH_NONE;
2550     GNUNET_assert (NULL == s5r->wtask);
2551     s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2552                                                  s5r->sock,
2553                                                  &do_write, s5r);
2554     s5r->state = SOCKS5_REQUEST;
2555     return;
2556   case SOCKS5_REQUEST:
2557     c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2558     if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2559       return;
2560     switch (c_req->command)
2561     {
2562     case SOCKS5_CMD_TCP_STREAM:
2563       /* handled below */
2564       break;
2565     default:
2566       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2567                   _("Unsupported socks command %d\n"),
2568                   (int) c_req->command);
2569       signal_socks_failure (s5r,
2570                             SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2571       return;
2572     }
2573     switch (c_req->addr_type)
2574     {
2575     case SOCKS5_AT_IPV4:
2576       {
2577         const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2578         const uint16_t *port = (const uint16_t *) &v4[1];
2579         struct sockaddr_in *in;
2580
2581         s5r->port = ntohs (*port);
2582         if (HTTPS_PORT == s5r->port)
2583         {
2584           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2585                       _("SSL connection to plain IPv4 address requested\n"));
2586           signal_socks_failure (s5r,
2587                                 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2588           return;
2589         }
2590         alen = sizeof (struct in_addr);
2591         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2592             alen + sizeof (uint16_t))
2593           return; /* need more data */
2594         in = (struct sockaddr_in *) &s5r->destination_address;
2595         in->sin_family = AF_INET;
2596         in->sin_addr = *v4;
2597         in->sin_port = *port;
2598 #if HAVE_SOCKADDR_IN_SIN_LEN
2599         in->sin_len = sizeof (*in);
2600 #endif
2601         s5r->state = SOCKS5_DATA_TRANSFER;
2602       }
2603       break;
2604     case SOCKS5_AT_IPV6:
2605       {
2606         const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2607         const uint16_t *port = (const uint16_t *) &v6[1];
2608         struct sockaddr_in6 *in;
2609
2610         s5r->port = ntohs (*port);
2611         if (HTTPS_PORT == s5r->port)
2612         {
2613           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2614                       _("SSL connection to plain IPv4 address requested\n"));
2615           signal_socks_failure (s5r,
2616                                 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2617           return;
2618         }
2619         alen = sizeof (struct in6_addr);
2620         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2621             alen + sizeof (uint16_t))
2622           return; /* need more data */
2623         in = (struct sockaddr_in6 *) &s5r->destination_address;
2624         in->sin6_family = AF_INET6;
2625         in->sin6_addr = *v6;
2626         in->sin6_port = *port;
2627 #if HAVE_SOCKADDR_IN_SIN_LEN
2628         in->sin6_len = sizeof (*in);
2629 #endif
2630         s5r->state = SOCKS5_DATA_TRANSFER;
2631       }
2632       break;
2633     case SOCKS5_AT_DOMAINNAME:
2634       {
2635         const uint8_t *dom_len;
2636         const char *dom_name;
2637         const uint16_t *port;
2638
2639         dom_len = (const uint8_t *) &c_req[1];
2640         alen = *dom_len + 1;
2641         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2642             alen + sizeof (uint16_t))
2643           return; /* need more data */
2644         dom_name = (const char *) &dom_len[1];
2645         port = (const uint16_t*) &dom_name[*dom_len];
2646         s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2647         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2648                     "Requested connection is to %s:%d\n",
2649                     s5r->domain,
2650                     ntohs (*port));
2651         s5r->state = SOCKS5_RESOLVING;
2652         s5r->port = ntohs (*port);
2653         s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2654                                              s5r->domain,
2655                                              &local_gns_zone,
2656                                              GNUNET_DNSPARSER_TYPE_A,
2657                                              GNUNET_NO /* only cached */,
2658                                              (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2659                                              &handle_gns_result,
2660                                              s5r);
2661         break;
2662       }
2663     default:
2664       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2665                   _("Unsupported socks address type %d\n"),
2666                   (int) c_req->addr_type);
2667       signal_socks_failure (s5r,
2668                             SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2669       return;
2670     }
2671     clear_from_s5r_rbuf (s5r,
2672                          sizeof (struct Socks5ClientRequestMessage) +
2673                          alen + sizeof (uint16_t));
2674     if (0 != s5r->rbuf_len)
2675     {
2676       /* read more bytes than healthy, why did the client send more!? */
2677       GNUNET_break_op (0);
2678       signal_socks_failure (s5r,
2679                             SOCKS5_STATUS_GENERAL_FAILURE);
2680       return;
2681     }
2682     if (SOCKS5_DATA_TRANSFER == s5r->state)
2683     {
2684       /* if we are not waiting for GNS resolution, signal success */
2685       signal_socks_success (s5r);
2686     }
2687     /* We are done reading right now */
2688     GNUNET_SCHEDULER_cancel (s5r->rtask);
2689     s5r->rtask = NULL;
2690     return;
2691   case SOCKS5_RESOLVING:
2692     GNUNET_assert (0);
2693     return;
2694   case SOCKS5_DATA_TRANSFER:
2695     GNUNET_assert (0);
2696     return;
2697   default:
2698     GNUNET_assert (0);
2699     return;
2700   }
2701 }
2702
2703
2704 /**
2705  * Accept new incoming connections
2706  *
2707  * @param cls the closure with the lsock4 or lsock6
2708  * @param tc the scheduler context
2709  */
2710 static void
2711 do_accept (void *cls)
2712 {
2713   struct GNUNET_NETWORK_Handle *lsock = cls;
2714   struct GNUNET_NETWORK_Handle *s;
2715   struct Socks5Request *s5r;
2716
2717   if (lsock == lsock4)
2718     ltask4 = NULL;
2719   else
2720     ltask6 = NULL;
2721   if (lsock == lsock4)
2722     ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2723                                             lsock,
2724                                             &do_accept, lsock);
2725   else
2726     ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2727                                             lsock,
2728                                             &do_accept, lsock);
2729   s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2730   if (NULL == s)
2731   {
2732     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2733     return;
2734   }
2735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2736               "Got an inbound connection, waiting for data\n");
2737   s5r = GNUNET_new (struct Socks5Request);
2738   GNUNET_CONTAINER_DLL_insert (s5r_head,
2739                                s5r_tail,
2740                                s5r);
2741   s5r->sock = s;
2742   s5r->state = SOCKS5_INIT;
2743   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2744                                               s5r->sock,
2745                                               &do_s5r_read, s5r);
2746 }
2747
2748
2749 /* ******************* General / main code ********************* */
2750
2751
2752 /**
2753  * Task run on shutdown
2754  *
2755  * @param cls closure
2756  */
2757 static void
2758 do_shutdown (void *cls)
2759 {
2760   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2761               "Shutting down...\n");
2762   while (NULL != mhd_httpd_head)
2763     kill_httpd (mhd_httpd_head);
2764   while (NULL != s5r_head)
2765     cleanup_s5r (s5r_head);
2766   if (NULL != lsock4)
2767   {
2768     GNUNET_NETWORK_socket_close (lsock4);
2769     lsock4 = NULL;
2770   }
2771   if (NULL != lsock6)
2772   {
2773     GNUNET_NETWORK_socket_close (lsock6);
2774     lsock6 = NULL;
2775   }
2776   if (NULL != id_op)
2777   {
2778     GNUNET_IDENTITY_cancel (id_op);
2779     id_op = NULL;
2780   }
2781   if (NULL != identity)
2782   {
2783     GNUNET_IDENTITY_disconnect (identity);
2784     identity = NULL;
2785   }
2786   if (NULL != curl_multi)
2787   {
2788     curl_multi_cleanup (curl_multi);
2789     curl_multi = NULL;
2790   }
2791   if (NULL != gns_handle)
2792   {
2793     GNUNET_GNS_disconnect (gns_handle);
2794     gns_handle = NULL;
2795   }
2796   if (NULL != curl_download_task)
2797   {
2798     GNUNET_SCHEDULER_cancel (curl_download_task);
2799     curl_download_task = NULL;
2800   }
2801   if (NULL != ltask4)
2802   {
2803     GNUNET_SCHEDULER_cancel (ltask4);
2804     ltask4 = NULL;
2805   }
2806   if (NULL != ltask6)
2807   {
2808     GNUNET_SCHEDULER_cancel (ltask6);
2809     ltask6 = NULL;
2810   }
2811   gnutls_x509_crt_deinit (proxy_ca.cert);
2812   gnutls_x509_privkey_deinit (proxy_ca.key);
2813   gnutls_global_deinit ();
2814 }
2815
2816
2817 /**
2818  * Create an IPv4 listen socket bound to our port.
2819  *
2820  * @return NULL on error
2821  */
2822 static struct GNUNET_NETWORK_Handle *
2823 bind_v4 ()
2824 {
2825   struct GNUNET_NETWORK_Handle *ls;
2826   struct sockaddr_in sa4;
2827   int eno;
2828
2829   memset (&sa4, 0, sizeof (sa4));
2830   sa4.sin_family = AF_INET;
2831   sa4.sin_port = htons (port);
2832 #if HAVE_SOCKADDR_IN_SIN_LEN
2833   sa4.sin_len = sizeof (sa4);
2834 #endif
2835   ls = GNUNET_NETWORK_socket_create (AF_INET,
2836                                      SOCK_STREAM,
2837                                      0);
2838   if (NULL == ls)
2839     return NULL;
2840   if (GNUNET_OK !=
2841       GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
2842                                   sizeof (sa4)))
2843   {
2844     eno = errno;
2845     GNUNET_NETWORK_socket_close (ls);
2846     errno = eno;
2847     return NULL;
2848   }
2849   return ls;
2850 }
2851
2852
2853 /**
2854  * Create an IPv6 listen socket bound to our port.
2855  *
2856  * @return NULL on error
2857  */
2858 static struct GNUNET_NETWORK_Handle *
2859 bind_v6 ()
2860 {
2861   struct GNUNET_NETWORK_Handle *ls;
2862   struct sockaddr_in6 sa6;
2863   int eno;
2864
2865   memset (&sa6, 0, sizeof (sa6));
2866   sa6.sin6_family = AF_INET6;
2867   sa6.sin6_port = htons (port);
2868 #if HAVE_SOCKADDR_IN_SIN_LEN
2869   sa6.sin6_len = sizeof (sa6);
2870 #endif
2871   ls = GNUNET_NETWORK_socket_create (AF_INET6,
2872                                      SOCK_STREAM,
2873                                      0);
2874   if (NULL == ls)
2875     return NULL;
2876   if (GNUNET_OK !=
2877       GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
2878                                   sizeof (sa6)))
2879   {
2880     eno = errno;
2881     GNUNET_NETWORK_socket_close (ls);
2882     errno = eno;
2883     return NULL;
2884   }
2885   return ls;
2886 }
2887
2888
2889 /**
2890  * Continue initialization after we have our zone information.
2891  */
2892 static void
2893 run_cont ()
2894 {
2895   struct MhdHttpList *hd;
2896
2897   /* Open listen socket for socks proxy */
2898   lsock6 = bind_v6 ();
2899   if (NULL == lsock6)
2900     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2901   else
2902   {
2903     if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
2904     {
2905       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2906       GNUNET_NETWORK_socket_close (lsock6);
2907       lsock6 = NULL;
2908     }
2909     else
2910     {
2911       ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2912                                               lsock6, &do_accept, lsock6);
2913     }
2914   }
2915   lsock4 = bind_v4 ();
2916   if (NULL == lsock4)
2917     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2918   else
2919   {
2920     if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
2921     {
2922       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2923       GNUNET_NETWORK_socket_close (lsock4);
2924       lsock4 = NULL;
2925     }
2926     else
2927     {
2928       ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2929                                               lsock4, &do_accept, lsock4);
2930     }
2931   }
2932   if ( (NULL == lsock4) &&
2933        (NULL == lsock6) )
2934   {
2935     GNUNET_SCHEDULER_shutdown ();
2936     return;
2937   }
2938   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
2939   {
2940     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2941                 "cURL global init failed!\n");
2942     GNUNET_SCHEDULER_shutdown ();
2943     return;
2944   }
2945   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2946               "Proxy listens on port %lu\n",
2947               port);
2948
2949   /* start MHD daemon for HTTP */
2950   hd = GNUNET_new (struct MhdHttpList);
2951   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
2952                                  0,
2953                                  NULL, NULL,
2954                                  &create_response, hd,
2955                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2956                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2957                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2958                                  MHD_OPTION_END);
2959   if (NULL == hd->daemon)
2960   {
2961     GNUNET_free (hd);
2962     GNUNET_SCHEDULER_shutdown ();
2963     return;
2964   }
2965   httpd = hd;
2966   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2967 }
2968
2969
2970 /**
2971  * Method called to inform about the egos of the shorten zone of this peer.
2972  *
2973  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2974  * this function is only called ONCE, and 'NULL' being passed in
2975  * @a ego does indicate an error (i.e. name is taken or no default
2976  * value is known).  If @a ego is non-NULL and if '*ctx'
2977  * is set in those callbacks, the value WILL be passed to a subsequent
2978  * call to the identity callback of #GNUNET_IDENTITY_connect (if
2979  * that one was not NULL).
2980  *
2981  * @param cls closure, NULL
2982  * @param ego ego handle
2983  * @param ctx context for application to store data for this ego
2984  *                 (during the lifetime of this process, initially NULL)
2985  * @param name name assigned by the user for this ego,
2986  *                   NULL if the user just deleted the ego and it
2987  *                   must thus no longer be used
2988  */
2989 static void
2990 identity_shorten_cb (void *cls,
2991                      struct GNUNET_IDENTITY_Ego *ego,
2992                      void **ctx,
2993                      const char *name)
2994 {
2995   id_op = NULL;
2996   if (NULL == ego)
2997   {
2998     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2999                 _("No ego configured for `shorten-zone`\n"));
3000   }
3001   else
3002   {
3003     local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
3004     do_shorten = GNUNET_YES;
3005   }
3006   run_cont ();
3007 }
3008
3009
3010 /**
3011  * Method called to inform about the egos of the master zone of this peer.
3012  *
3013  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
3014  * this function is only called ONCE, and 'NULL' being passed in
3015  * @a ego does indicate an error (i.e. name is taken or no default
3016  * value is known).  If @a ego is non-NULL and if '*ctx'
3017  * is set in those callbacks, the value WILL be passed to a subsequent
3018  * call to the identity callback of #GNUNET_IDENTITY_connect (if
3019  * that one was not NULL).
3020  *
3021  * @param cls closure, NULL
3022  * @param ego ego handle
3023  * @param ctx context for application to store data for this ego
3024  *                 (during the lifetime of this process, initially NULL)
3025  * @param name name assigned by the user for this ego,
3026  *                   NULL if the user just deleted the ego and it
3027  *                   must thus no longer be used
3028  */
3029 static void
3030 identity_master_cb (void *cls,
3031                     struct GNUNET_IDENTITY_Ego *ego,
3032                     void **ctx,
3033                     const char *name)
3034 {
3035   id_op = NULL;
3036   if (NULL == ego)
3037   {
3038     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3039                 _("No ego configured for `%s`\n"),
3040                 "gns-proxy");
3041     GNUNET_SCHEDULER_shutdown ();
3042     return;
3043   }
3044   GNUNET_IDENTITY_ego_get_public_key (ego,
3045                                       &local_gns_zone);
3046   id_op = GNUNET_IDENTITY_get (identity,
3047                                "gns-short",
3048                                &identity_shorten_cb,
3049                                NULL);
3050 }
3051
3052
3053 /**
3054  * Main function that will be run
3055  *
3056  * @param cls closure
3057  * @param args remaining command-line arguments
3058  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3059  * @param c configuration
3060  */
3061 static void
3062 run (void *cls, char *const *args, const char *cfgfile,
3063      const struct GNUNET_CONFIGURATION_Handle *c)
3064 {
3065   char* cafile_cfg = NULL;
3066   char* cafile;
3067
3068   cfg = c;
3069
3070   if (NULL == (curl_multi = curl_multi_init ()))
3071   {
3072     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3073                 "Failed to create cURL multi handle!\n");
3074     return;
3075   }
3076   cafile = cafile_opt;
3077   if (NULL == cafile)
3078   {
3079     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3080                                                               "PROXY_CACERT",
3081                                                               &cafile_cfg))
3082     {
3083       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3084                                  "gns-proxy",
3085                                  "PROXY_CACERT");
3086       return;
3087     }
3088     cafile = cafile_cfg;
3089   }
3090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3091               "Using %s as CA\n", cafile);
3092
3093   gnutls_global_init ();
3094   gnutls_x509_crt_init (&proxy_ca.cert);
3095   gnutls_x509_privkey_init (&proxy_ca.key);
3096
3097   if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
3098        (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
3099   {
3100     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3101                 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
3102                 cafile);
3103     gnutls_x509_crt_deinit (proxy_ca.cert);
3104     gnutls_x509_privkey_deinit (proxy_ca.key);
3105     gnutls_global_deinit ();
3106     GNUNET_free_non_null (cafile_cfg);
3107     return;
3108   }
3109   GNUNET_free_non_null (cafile_cfg);
3110   if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3111   {
3112     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3113                 "Unable to connect to GNS!\n");
3114     gnutls_x509_crt_deinit (proxy_ca.cert);
3115     gnutls_x509_privkey_deinit (proxy_ca.key);
3116     gnutls_global_deinit ();
3117     return;
3118   }
3119   identity = GNUNET_IDENTITY_connect (cfg,
3120                                       NULL, NULL);
3121   id_op = GNUNET_IDENTITY_get (identity,
3122                                "gns-proxy",
3123                                &identity_master_cb,
3124                                NULL);
3125   GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
3126 }
3127
3128
3129 /**
3130  * The main function for gnunet-gns-proxy.
3131  *
3132  * @param argc number of arguments from the command line
3133  * @param argv command line arguments
3134  * @return 0 ok, 1 on error
3135  */
3136 int
3137 main (int argc, char *const *argv)
3138 {
3139   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3140     {'p', "port", NULL,
3141      gettext_noop ("listen on specified port (default: 7777)"), 1,
3142      &GNUNET_GETOPT_set_ulong, &port},
3143     {'a', "authority", NULL,
3144       gettext_noop ("pem file to use as CA"), 1,
3145       &GNUNET_GETOPT_set_string, &cafile_opt},
3146     GNUNET_GETOPT_OPTION_END
3147   };
3148   static const char* page =
3149     "<html><head><title>gnunet-gns-proxy</title>"
3150     "</head><body>cURL fail</body></html>";
3151   int ret;
3152
3153   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3154     return 2;
3155   GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3156   curl_failure_response = MHD_create_response_from_buffer (strlen (page),
3157                                                            (void*)page,
3158                                                            MHD_RESPMEM_PERSISTENT);
3159
3160   ret =
3161       (GNUNET_OK ==
3162        GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3163                            _("GNUnet GNS proxy"),
3164                            options,
3165                            &run, NULL)) ? 0 : 1;
3166   MHD_destroy_response (curl_failure_response);
3167   GNUNET_free_non_null ((char *) argv);
3168   GNUNET_CRYPTO_ecdsa_key_clear (&local_shorten_zone);
3169   return ret;
3170 }
3171
3172 /* end of gnunet-gns-proxy.c */