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