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