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