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