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