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