remove \r\n from values before giving them to MHD
[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   /* MHD does not allow certain characters in values, remove those */
969   if (NULL != (tok = strchr (hdr_val, '\n')))
970     *tok = '\0';
971   if (NULL != (tok = strchr (hdr_val, '\r')))
972     *tok = '\0';
973   if (NULL != (tok = strchr (hdr_val, '\t')))
974     *tok = '\0';
975   if (0 != strlen (hdr_val))
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.  We also change the
1238  * 'Connection' header value to "close" as the proxy does not support
1239  * pipelining.
1240  *
1241  * @param cls our `struct Socks5Request`
1242  * @param kind value kind
1243  * @param key field key
1244  * @param value field value
1245  * @return #MHD_YES to continue to iterate
1246  */
1247 static int
1248 con_val_iter (void *cls,
1249               enum MHD_ValueKind kind,
1250               const char *key,
1251               const char *value)
1252 {
1253   struct Socks5Request *s5r = cls;
1254   char *hdr;
1255
1256   if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1257        (NULL != s5r->leho) )
1258     value = s5r->leho;
1259   if (0 == strcasecmp (MHD_HTTP_HEADER_CONNECTION, key))
1260     value = "Close";
1261   GNUNET_asprintf (&hdr,
1262                    "%s: %s",
1263                    key,
1264                    value);
1265   s5r->headers = curl_slist_append (s5r->headers,
1266                                     hdr);
1267   GNUNET_free (hdr);
1268   return MHD_YES;
1269 }
1270
1271
1272 /**
1273  * Main MHD callback for handling requests.
1274  *
1275  * @param cls unused
1276  * @param con MHD connection handle
1277  * @param url the url in the request
1278  * @param meth the HTTP method used ("GET", "PUT", etc.)
1279  * @param ver the HTTP version string (i.e. "HTTP/1.1")
1280  * @param upload_data the data being uploaded (excluding HEADERS,
1281  *        for a POST that fits into memory and that is encoded
1282  *        with a supported encoding, the POST data will NOT be
1283  *        given in upload_data and is instead available as
1284  *        part of MHD_get_connection_values; very large POST
1285  *        data *will* be made available incrementally in
1286  *        upload_data)
1287  * @param upload_data_size set initially to the size of the
1288  *        @a upload_data provided; the method must update this
1289  *        value to the number of bytes NOT processed;
1290  * @param con_cls pointer to location where we store the 'struct Request'
1291  * @return #MHD_YES if the connection was handled successfully,
1292  *         #MHD_NO if the socket must be closed due to a serious
1293  *         error while handling the request
1294  */
1295 static int
1296 create_response (void *cls,
1297                  struct MHD_Connection *con,
1298                  const char *url,
1299                  const char *meth,
1300                  const char *ver,
1301                  const char *upload_data,
1302                  size_t *upload_data_size,
1303                  void **con_cls)
1304 {
1305   /* struct MhdHttpList* hd = cls;  */
1306   struct Socks5Request *s5r = *con_cls;
1307   char *curlurl;
1308   char ipstring[INET6_ADDRSTRLEN];
1309   char ipaddr[INET6_ADDRSTRLEN + 2];
1310   const struct sockaddr *sa;
1311   const struct sockaddr_in *s4;
1312   const struct sockaddr_in6 *s6;
1313   uint16_t port;
1314   size_t left;
1315
1316   if (NULL == s5r)
1317   {
1318     GNUNET_break (0);
1319     return MHD_NO;
1320   }
1321   if (NULL == s5r->curl)
1322   {
1323     /* first time here, initialize curl handle */
1324     sa = (const struct sockaddr *) &s5r->destination_address;
1325     switch (sa->sa_family)
1326     {
1327     case AF_INET:
1328       s4 = (const struct sockaddr_in *) &s5r->destination_address;
1329       if (NULL == inet_ntop (AF_INET,
1330                              &s4->sin_addr,
1331                              ipstring,
1332                              sizeof (ipstring)))
1333       {
1334         GNUNET_break (0);
1335         return MHD_NO;
1336       }
1337       GNUNET_snprintf (ipaddr,
1338                        sizeof (ipaddr),
1339                        "%s",
1340                        ipstring);
1341       port = ntohs (s4->sin_port);
1342       break;
1343     case AF_INET6:
1344       s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1345       if (NULL == inet_ntop (AF_INET6,
1346                              &s6->sin6_addr,
1347                              ipstring,
1348                              sizeof (ipstring)))
1349       {
1350         GNUNET_break (0);
1351         return MHD_NO;
1352       }
1353       GNUNET_snprintf (ipaddr,
1354                        sizeof (ipaddr),
1355                        "[%s]",
1356                        ipstring);
1357       port = ntohs (s6->sin6_port);
1358       break;
1359     default:
1360       GNUNET_break (0);
1361       return MHD_NO;
1362     }
1363     s5r->curl = curl_easy_init ();
1364     if (NULL == s5r->curl)
1365       return MHD_queue_response (con,
1366                                  MHD_HTTP_INTERNAL_SERVER_ERROR,
1367                                  curl_failure_response);    
1368     curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1369     curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1370     curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1371     curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1372     curl_easy_setopt (s5r->curl, CURLOPT_FAILONERROR, 1); /* not sure we want this */
1373     curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1374     curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1375     curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1376     curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1377     curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1378     curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1379     curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1380     curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 1); // FIXME: remove later
1381     GNUNET_asprintf (&curlurl,
1382                      (HTTPS_PORT != s5r->port)
1383                      ? "http://%s:%d%s"
1384                      : "https://%s:%d%s",
1385                      ipaddr,
1386                      port, 
1387                      s5r->url);   
1388     curl_easy_setopt (s5r->curl,
1389                       CURLOPT_URL, 
1390                       curlurl);   
1391     GNUNET_free (curlurl);
1392
1393     if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1394     {
1395       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1396       curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
1397       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1398       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1399       curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1400       curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1401     } 
1402     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1403     {
1404       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;    
1405       curl_easy_setopt (s5r->curl, CURLOPT_POST, 1);
1406       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1407       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1408       curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1409       curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1410     }
1411     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1412     {
1413       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;    
1414       curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
1415     }
1416     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1417     {
1418       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;    
1419       curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
1420       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1421       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1422     }
1423     else
1424     {
1425       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1426                   _("Unsupported HTTP method `%s'\n"),
1427                   meth);
1428       curl_easy_cleanup (s5r->curl);
1429       s5r->curl = NULL;      
1430       return MHD_NO;
1431     }
1432     
1433     if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1434     {
1435       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1436     }
1437     else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1438     {
1439       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1440     }
1441     else
1442     {
1443       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1444     }
1445     
1446     if (HTTPS_PORT == s5r->port)
1447     {
1448       curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1449       curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1450       /* Disable cURL checking the hostname, as we will check ourselves
1451          as only we have the domain name or the LEHO or the DANE record */
1452       curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);      
1453     }
1454     else
1455     {
1456       curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);   
1457     }
1458
1459     if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
1460     {
1461       GNUNET_break (0);
1462       curl_easy_cleanup (s5r->curl);
1463       s5r->curl = NULL;      
1464       return MHD_NO;      
1465     }
1466     MHD_get_connection_values (con,
1467                                MHD_HEADER_KIND,
1468                                &con_val_iter, s5r);
1469     curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
1470     curl_download_prepare ();
1471     return MHD_YES;
1472   } 
1473
1474   /* continuing to process request */
1475   if (0 != *upload_data_size)
1476   {
1477     left = GNUNET_MIN (*upload_data_size,
1478                        sizeof (s5r->io_buf) - s5r->io_len);
1479     memcpy (&s5r->io_buf[s5r->io_len], 
1480             upload_data,
1481             left);
1482     s5r->io_len += left;
1483     *upload_data_size -= left;
1484     if (s5r->io_len == left)
1485       curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
1486     curl_download_prepare ();
1487     return MHD_YES;
1488   }
1489   s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1490   if (NULL == s5r->response) 
1491     return MHD_YES; /* too early to queue response, did not yet get headers from cURL */
1492   return MHD_queue_response (con,
1493                              s5r->response_code, 
1494                              s5r->response);
1495 }
1496
1497
1498 /* ******************** MHD HTTP setup and event loop ******************** */
1499
1500
1501 /**
1502  * Function called when MHD decides that we are done with a connection.
1503  *
1504  * @param cls NULL
1505  * @param connection connection handle
1506  * @param con_cls value as set by the last call to
1507  *        the #MHD_AccessHandlerCallback, should be our `struct Socks5Request`
1508  * @param toe reason for request termination (ignored)
1509  */
1510 static void
1511 mhd_completed_cb (void *cls,
1512                   struct MHD_Connection *connection,
1513                   void **con_cls,
1514                   enum MHD_RequestTerminationCode toe)
1515 {
1516   struct Socks5Request *s5r = *con_cls;
1517
1518   if (NULL == s5r)
1519     return;
1520   cleanup_s5r (s5r);
1521   *con_cls = NULL;  
1522 }
1523
1524
1525 /**
1526  * Function called when MHD first processes an incoming connection.
1527  * Gives us the respective URI information.
1528  *
1529  * We use this to associate the `struct MHD_Connection` with our 
1530  * internal `struct Socks5Request` data structure (by checking
1531  * for matching sockets).
1532  *
1533  * @param cls the HTTP server handle (a `struct MhdHttpList`)
1534  * @param url the URL that is being requested
1535  * @param connection MHD connection object for the request
1536  * @return the `struct Socks5Request` that this @a connection is for
1537  */
1538 static void *
1539 mhd_log_callback (void *cls, 
1540                   const char *url,
1541                   struct MHD_Connection *connection)
1542 {
1543   struct Socks5Request *s5r;
1544   const union MHD_ConnectionInfo *ci;
1545   int sock;
1546
1547   ci = MHD_get_connection_info (connection,
1548                                 MHD_CONNECTION_INFO_CONNECTION_FD);
1549   if (NULL == ci) 
1550   {
1551     GNUNET_break (0);
1552     return NULL;
1553   }
1554   sock = ci->connect_fd;
1555   for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1556   {
1557     if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1558     {
1559       if (NULL != s5r->url)
1560       {
1561         GNUNET_break (0);
1562         return NULL;
1563       }
1564       s5r->url = GNUNET_strdup (url);
1565       return s5r;
1566     }
1567   }
1568   return NULL;
1569 }
1570
1571
1572 /**
1573  * Kill the given MHD daemon.
1574  *
1575  * @param hd daemon to stop
1576  */
1577 static void
1578 kill_httpd (struct MhdHttpList *hd)
1579 {
1580   GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1581                                mhd_httpd_tail,
1582                                hd);
1583   GNUNET_free_non_null (hd->domain);
1584   MHD_stop_daemon (hd->daemon);
1585   if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1586     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1587   GNUNET_free_non_null (hd->proxy_cert);
1588   if (hd == httpd)
1589     httpd = NULL;
1590   GNUNET_free (hd);
1591 }
1592
1593
1594 /**
1595  * Task run whenever HTTP server is idle for too long. Kill it.
1596  *
1597  * @param cls the `struct MhdHttpList *`
1598  * @param tc sched context
1599  */
1600 static void
1601 kill_httpd_task (void *cls,
1602                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1603 {
1604   struct MhdHttpList *hd = cls;
1605   
1606   kill_httpd (hd);
1607 }
1608
1609
1610 /**
1611  * Task run whenever HTTP server operations are pending.
1612  *
1613  * @param cls the `struct MhdHttpList *` of the daemon that is being run
1614  * @param tc sched context
1615  */
1616 static void
1617 do_httpd (void *cls,
1618           const struct GNUNET_SCHEDULER_TaskContext *tc);
1619
1620
1621 /**
1622  * Schedule MHD.  This function should be called initially when an
1623  * MHD is first getting its client socket, and will then automatically
1624  * always be called later whenever there is work to be done.
1625  *
1626  * @param hd the daemon to schedule
1627  */
1628 static void
1629 schedule_httpd (struct MhdHttpList *hd)
1630 {
1631   fd_set rs;
1632   fd_set ws;
1633   fd_set es;
1634   struct GNUNET_NETWORK_FDSet *wrs;
1635   struct GNUNET_NETWORK_FDSet *wws;
1636   int max;
1637   int haveto;
1638   MHD_UNSIGNED_LONG_LONG timeout;
1639   struct GNUNET_TIME_Relative tv;
1640
1641   FD_ZERO (&rs);
1642   FD_ZERO (&ws);
1643   FD_ZERO (&es);
1644   max = -1;
1645   if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1646   {
1647     kill_httpd (hd);
1648     return;
1649   }
1650   haveto = MHD_get_timeout (hd->daemon, &timeout);
1651   if (MHD_YES == haveto)
1652     tv.rel_value_us = (uint64_t) timeout * 1000LL;
1653   else
1654     tv = GNUNET_TIME_UNIT_FOREVER_REL;
1655   if (-1 != max)
1656   {
1657     wrs = GNUNET_NETWORK_fdset_create ();
1658     wws = GNUNET_NETWORK_fdset_create ();
1659     GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1660     GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1661   }
1662   else
1663   {
1664     wrs = NULL;
1665     wws = NULL;
1666   }
1667   if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1668     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1669   if ( (MHD_YES != haveto) &&
1670        (-1 == max) &&
1671        (hd != httpd) )
1672   {
1673     /* daemon is idle, kill after timeout */
1674     hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
1675                                                    &kill_httpd_task,
1676                                                    hd);
1677   }
1678   else
1679   {
1680     hd->httpd_task =
1681       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1682                                    tv, wrs, wws,
1683                                    &do_httpd, hd);
1684   }
1685   if (NULL != wrs)
1686     GNUNET_NETWORK_fdset_destroy (wrs);
1687   if (NULL != wws)
1688     GNUNET_NETWORK_fdset_destroy (wws);
1689 }
1690
1691
1692 /**
1693  * Task run whenever HTTP server operations are pending.
1694  *
1695  * @param cls the `struct MhdHttpList` of the daemon that is being run
1696  * @param tc scheduler context
1697  */
1698 static void
1699 do_httpd (void *cls,
1700           const struct GNUNET_SCHEDULER_TaskContext *tc)
1701 {
1702   struct MhdHttpList *hd = cls;
1703   
1704   hd->httpd_task = GNUNET_SCHEDULER_NO_TASK; 
1705   MHD_run (hd->daemon);
1706   schedule_httpd (hd);
1707 }
1708
1709
1710 /**
1711  * Run MHD now, we have extra data ready for the callback.
1712  *
1713  * @param hd the daemon to run now.
1714  */
1715 static void
1716 run_mhd_now (struct MhdHttpList *hd)
1717 {
1718   if (GNUNET_SCHEDULER_NO_TASK != 
1719       hd->httpd_task)
1720     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1721   hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd, 
1722                                              hd);
1723 }
1724
1725
1726 /**
1727  * Read file in filename
1728  *
1729  * @param filename file to read
1730  * @param size pointer where filesize is stored
1731  * @return NULL on error
1732  */
1733 static void*
1734 load_file (const char* filename, 
1735            unsigned int* size)
1736 {
1737   void *buffer;
1738   uint64_t fsize;
1739
1740   if (GNUNET_OK !=
1741       GNUNET_DISK_file_size (filename, &fsize,
1742                              GNUNET_YES, GNUNET_YES))
1743     return NULL;
1744   if (fsize > MAX_PEM_SIZE)
1745     return NULL;
1746   *size = (unsigned int) fsize;
1747   buffer = GNUNET_malloc (*size);
1748   if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
1749   {
1750     GNUNET_free (buffer);
1751     return NULL;
1752   }
1753   return buffer;
1754 }
1755
1756
1757 /**
1758  * Load PEM key from file
1759  *
1760  * @param key where to store the data
1761  * @param keyfile path to the PEM file
1762  * @return #GNUNET_OK on success
1763  */
1764 static int
1765 load_key_from_file (gnutls_x509_privkey_t key, 
1766                     const char* keyfile)
1767 {
1768   gnutls_datum_t key_data;
1769   int ret;
1770
1771   key_data.data = load_file (keyfile, &key_data.size);
1772   ret = gnutls_x509_privkey_import (key, &key_data,
1773                                     GNUTLS_X509_FMT_PEM);
1774   if (GNUTLS_E_SUCCESS != ret)
1775   {
1776     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1777                 _("Unable to import private key from file `%s'\n"),
1778                 keyfile);
1779   }
1780   GNUNET_free_non_null (key_data.data);
1781   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
1782 }
1783
1784
1785 /**
1786  * Load cert from file
1787  *
1788  * @param crt struct to store data in
1789  * @param certfile path to pem file
1790  * @return #GNUNET_OK on success
1791  */
1792 static int
1793 load_cert_from_file (gnutls_x509_crt_t crt, 
1794                      const char* certfile)
1795 {
1796   gnutls_datum_t cert_data;
1797   int ret;
1798
1799   cert_data.data = load_file (certfile, &cert_data.size);
1800   ret = gnutls_x509_crt_import (crt, &cert_data,
1801                                 GNUTLS_X509_FMT_PEM);
1802   if (GNUTLS_E_SUCCESS != ret)
1803   {
1804     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1805                _("Unable to import certificate %s\n"), certfile);
1806   }
1807   GNUNET_free_non_null (cert_data.data);
1808   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
1809 }
1810
1811
1812 /**
1813  * Generate new certificate for specific name
1814  *
1815  * @param name the subject name to generate a cert for
1816  * @return a struct holding the PEM data, NULL on error
1817  */
1818 static struct ProxyGNSCertificate *
1819 generate_gns_certificate (const char *name)
1820 {
1821   unsigned int serial;
1822   size_t key_buf_size;
1823   size_t cert_buf_size;
1824   gnutls_x509_crt_t request;
1825   time_t etime;
1826   struct tm *tm_data;
1827   struct ProxyGNSCertificate *pgc;
1828
1829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1830               "Generating TLS/SSL certificate for `%s'\n", 
1831               name);
1832   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
1833   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
1834   pgc = GNUNET_new (struct ProxyGNSCertificate);
1835   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
1836                                  0, "TNR", 2);
1837   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
1838                                  0, "GNU Name System", 4);
1839   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
1840                                  0, name, strlen (name));
1841   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
1842   gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
1843   gnutls_x509_crt_set_serial (request,
1844                               &serial,
1845                               sizeof (serial));
1846   etime = time (NULL);
1847   tm_data = localtime (&etime);  
1848   gnutls_x509_crt_set_activation_time (request,
1849                                        etime);
1850   tm_data->tm_year++;
1851   etime = mktime (tm_data);
1852   gnutls_x509_crt_set_expiration_time (request,
1853                                        etime);
1854   gnutls_x509_crt_sign (request, 
1855                         proxy_ca.cert, 
1856                         proxy_ca.key);
1857   key_buf_size = sizeof (pgc->key);
1858   cert_buf_size = sizeof (pgc->cert);
1859   gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
1860                           pgc->cert, &cert_buf_size);
1861   gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
1862                               pgc->key, &key_buf_size);
1863   gnutls_x509_crt_deinit (request);
1864   return pgc;
1865 }
1866
1867
1868 /**
1869  * Lookup (or create) an SSL MHD instance for a particular domain.
1870  *
1871  * @param domain the domain the SSL daemon has to serve
1872  * @return NULL on errro
1873  */
1874 static struct MhdHttpList *
1875 lookup_ssl_httpd (const char* domain)
1876 {
1877   struct MhdHttpList *hd;
1878   struct ProxyGNSCertificate *pgc;
1879
1880   for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
1881     if ( (NULL != hd->domain) &&
1882          (0 == strcmp (hd->domain, domain)) )
1883       return hd;
1884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1885               "Starting fresh MHD HTTPS instance for domain `%s'\n",
1886               domain);
1887   pgc = generate_gns_certificate (domain);   
1888   hd = GNUNET_new (struct MhdHttpList);
1889   hd->is_ssl = GNUNET_YES;
1890   hd->domain = GNUNET_strdup (domain); 
1891   hd->proxy_cert = pgc;
1892   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
1893                                  0,
1894                                  NULL, NULL,
1895                                  &create_response, hd,
1896                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
1897                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
1898                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
1899                                  MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
1900                                  MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
1901                                  MHD_OPTION_END);
1902   if (NULL == hd->daemon)
1903   {
1904     GNUNET_free (pgc);
1905     GNUNET_free (hd);
1906     return NULL;
1907   }
1908   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, 
1909                                mhd_httpd_tail, 
1910                                hd);
1911   return hd;
1912 }
1913
1914
1915 /**
1916  * Task run when a Socks5Request somehow fails to be associated with
1917  * an MHD connection (i.e. because the client never speaks HTTP after
1918  * the SOCKS5 handshake).  Clean up.
1919  *
1920  * @param cls the `struct Socks5Request *`
1921  * @param tc sched context
1922  */
1923 static void
1924 timeout_s5r_handshake (void *cls,
1925                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1926 {
1927   struct Socks5Request *s5r = cls;
1928
1929   s5r->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1930   cleanup_s5r (s5r);
1931 }
1932
1933
1934 /**
1935  * We're done with the Socks5 protocol, now we need to pass the
1936  * connection data through to the final destination, either 
1937  * direct (if the protocol might not be HTTP), or via MHD
1938  * (if the port looks like it should be HTTP).
1939  *
1940  * @param s5r socks request that has reached the final stage
1941  */
1942 static void
1943 setup_data_transfer (struct Socks5Request *s5r)
1944 {
1945   struct MhdHttpList *hd;
1946   int fd;
1947   const struct sockaddr *addr;
1948   socklen_t len;
1949
1950   switch (s5r->port)
1951   {
1952   case HTTPS_PORT:
1953     hd = lookup_ssl_httpd (s5r->domain);
1954     if (NULL == hd)
1955     {
1956       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1957                   _("Failed to start HTTPS server for `%s'\n"),
1958                   s5r->domain);
1959       cleanup_s5r (s5r);
1960       return;
1961     }
1962     break;
1963   case HTTP_PORT:
1964   default:
1965     GNUNET_assert (NULL != httpd);
1966     hd = httpd;
1967     break;
1968   }
1969   fd = GNUNET_NETWORK_get_fd (s5r->sock);
1970   addr = GNUNET_NETWORK_get_addr (s5r->sock);
1971   len = GNUNET_NETWORK_get_addrlen (s5r->sock);
1972   s5r->state = SOCKS5_SOCKET_WITH_MHD;
1973   if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
1974   {
1975     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1976                 _("Failed to pass client to MHD\n"));
1977     cleanup_s5r (s5r);
1978     return;
1979   }
1980   s5r->hd = hd;
1981   schedule_httpd (hd);
1982   s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
1983                                                     &timeout_s5r_handshake,
1984                                                     s5r);
1985 }
1986
1987
1988 /* ********************* SOCKS handling ************************* */
1989
1990
1991 /**
1992  * Write data from buffer to socks5 client, then continue with state machine.
1993  *
1994  * @param cls the closure with the `struct Socks5Request`
1995  * @param tc scheduler context
1996  */
1997 static void
1998 do_write (void *cls,
1999           const struct GNUNET_SCHEDULER_TaskContext *tc)
2000 {
2001   struct Socks5Request *s5r = cls;
2002   ssize_t len;
2003
2004   s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
2005   len = GNUNET_NETWORK_socket_send (s5r->sock,
2006                                     s5r->wbuf,
2007                                     s5r->wbuf_len);
2008   if (len <= 0)
2009   {
2010     /* write error: connection closed, shutdown, etc.; just clean up */
2011     cleanup_s5r (s5r); 
2012     return;
2013   }
2014   memmove (s5r->wbuf,
2015            &s5r->wbuf[len],
2016            s5r->wbuf_len - len);
2017   s5r->wbuf_len -= len;
2018   if (s5r->wbuf_len > 0)
2019   {
2020     /* not done writing */
2021     s5r->wtask =
2022       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2023                                       s5r->sock,
2024                                       &do_write, s5r);
2025     return;
2026   }
2027
2028   /* we're done writing, continue with state machine! */
2029
2030   switch (s5r->state)
2031   {
2032   case SOCKS5_INIT:    
2033     GNUNET_assert (0);
2034     break;
2035   case SOCKS5_REQUEST:    
2036     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s5r->rtask);
2037     break;
2038   case SOCKS5_DATA_TRANSFER:
2039     setup_data_transfer (s5r);
2040     return;
2041   case SOCKS5_WRITE_THEN_CLEANUP:
2042     cleanup_s5r (s5r);
2043     return;
2044   default:
2045     GNUNET_break (0);
2046     break;
2047   }
2048 }
2049
2050
2051 /**
2052  * Return a server response message indicating a failure to the client.
2053  *
2054  * @param s5r request to return failure code for
2055  * @param sc status code to return
2056  */
2057 static void
2058 signal_socks_failure (struct Socks5Request *s5r,
2059                       enum Socks5StatusCode sc)
2060 {
2061   struct Socks5ServerResponseMessage *s_resp;
2062
2063   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2064   memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2065   s_resp->version = SOCKS_VERSION_5;
2066   s_resp->reply = sc;
2067   s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2068   if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
2069     s5r->wtask = 
2070       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2071                                       s5r->sock,
2072                                       &do_write, s5r);
2073 }
2074
2075
2076 /**
2077  * Return a server response message indicating success.
2078  *
2079  * @param s5r request to return success status message for
2080  */
2081 static void
2082 signal_socks_success (struct Socks5Request *s5r)
2083 {
2084   struct Socks5ServerResponseMessage *s_resp;
2085
2086   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2087   s_resp->version = SOCKS_VERSION_5;
2088   s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2089   s_resp->reserved = 0;
2090   s_resp->addr_type = SOCKS5_AT_IPV4;
2091   /* zero out IPv4 address and port */
2092   memset (&s_resp[1], 
2093           0, 
2094           sizeof (struct in_addr) + sizeof (uint16_t));
2095   s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2096     sizeof (struct in_addr) + sizeof (uint16_t);  
2097   if (GNUNET_SCHEDULER_NO_TASK == s5r->wtask)      
2098     s5r->wtask =
2099       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2100                                       s5r->sock,
2101                                       &do_write, s5r); 
2102 }
2103
2104
2105 /**
2106  * Process GNS results for target domain.
2107  *
2108  * @param cls the `struct Socks5Request`
2109  * @param rd_count number of records returned
2110  * @param rd record data
2111  */
2112 static void
2113 handle_gns_result (void *cls,
2114                    uint32_t rd_count,
2115                    const struct GNUNET_NAMESTORE_RecordData *rd)
2116 {
2117   struct Socks5Request *s5r = cls;
2118   uint32_t i;
2119   const struct GNUNET_NAMESTORE_RecordData *r;
2120   int got_ip;
2121
2122   s5r->gns_lookup = NULL;
2123   got_ip = GNUNET_NO;
2124   for (i=0;i<rd_count;i++)
2125   {
2126     r = &rd[i];
2127     switch (r->record_type)
2128     {
2129     case GNUNET_DNSPARSER_TYPE_A:
2130       {
2131         struct sockaddr_in *in;
2132
2133         if (sizeof (struct in_addr) != r->data_size)
2134         {
2135           GNUNET_break_op (0);
2136           break;
2137         }
2138         if (GNUNET_YES == got_ip)
2139           break;
2140         if (GNUNET_OK != 
2141             GNUNET_NETWORK_test_pf (PF_INET))
2142           break;
2143         got_ip = GNUNET_YES;
2144         in = (struct sockaddr_in *) &s5r->destination_address;
2145         in->sin_family = AF_INET;
2146         memcpy (&in->sin_addr,
2147                 r->data,
2148                 r->data_size);
2149         in->sin_port = htons (s5r->port);
2150 #if HAVE_SOCKADDR_IN_SIN_LEN
2151         in->sin_len = sizeof (*in);
2152 #endif
2153       }
2154       break;
2155     case GNUNET_DNSPARSER_TYPE_AAAA: 
2156       {
2157         struct sockaddr_in6 *in;
2158
2159         if (sizeof (struct in6_addr) != r->data_size)
2160         {
2161           GNUNET_break_op (0);
2162           break;
2163         }
2164         if (GNUNET_YES == got_ip)
2165           break; 
2166         if (GNUNET_OK != 
2167             GNUNET_NETWORK_test_pf (PF_INET))
2168           break;
2169         /* FIXME: allow user to disable IPv6 per configuration option... */
2170         got_ip = GNUNET_YES;
2171         in = (struct sockaddr_in6 *) &s5r->destination_address;
2172         in->sin6_family = AF_INET6;
2173         memcpy (&in->sin6_addr,
2174                 r->data,
2175                 r->data_size);
2176         in->sin6_port = htons (s5r->port);
2177 #if HAVE_SOCKADDR_IN_SIN_LEN
2178         in->sin6_len = sizeof (*in);
2179 #endif
2180       }
2181       break;      
2182     case GNUNET_NAMESTORE_TYPE_VPN:
2183       GNUNET_break (0); /* should have been translated within GNS */
2184       break;
2185     case GNUNET_NAMESTORE_TYPE_LEHO:
2186       GNUNET_free_non_null (s5r->leho);
2187       s5r->leho = GNUNET_strndup (r->data,
2188                                   r->data_size);
2189       break;
2190     default:
2191       /* don't care */
2192       break;
2193     }
2194   }
2195   if (GNUNET_YES != got_ip)
2196   {
2197     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2198                 "Name resolution failed to yield useful IP address.\n");
2199     signal_socks_failure (s5r,
2200                           SOCKS5_STATUS_GENERAL_FAILURE);
2201     return;
2202   }
2203   s5r->state = SOCKS5_DATA_TRANSFER;
2204   signal_socks_success (s5r);  
2205 }
2206
2207
2208 /**
2209  * Remove the first @a len bytes from the beginning of the read buffer.
2210  *
2211  * @param s5r the handle clear the read buffer for
2212  * @param len number of bytes in read buffer to advance
2213  */
2214 static void
2215 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2216                      size_t len)
2217 {
2218   GNUNET_assert (len <= s5r->rbuf_len);
2219   memmove (s5r->rbuf,
2220            &s5r->rbuf[len],
2221            s5r->rbuf_len - len);
2222   s5r->rbuf_len -= len;
2223 }
2224
2225
2226 /**
2227  * Read data from incoming Socks5 connection
2228  *
2229  * @param cls the closure with the `struct Socks5Request`
2230  * @param tc the scheduler context
2231  */
2232 static void
2233 do_s5r_read (void *cls,
2234              const struct GNUNET_SCHEDULER_TaskContext *tc)
2235 {
2236   struct Socks5Request *s5r = cls;
2237   const struct Socks5ClientHelloMessage *c_hello;
2238   struct Socks5ServerHelloMessage *s_hello;
2239   const struct Socks5ClientRequestMessage *c_req;
2240   ssize_t rlen;
2241   size_t alen;
2242
2243   s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2244   if ( (NULL != tc->read_ready) &&
2245        (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2246   {
2247     rlen = GNUNET_NETWORK_socket_recv (s5r->sock, 
2248                                        &s5r->rbuf[s5r->rbuf_len],
2249                                        sizeof (s5r->rbuf) - s5r->rbuf_len);
2250     if (rlen <= 0)
2251     {
2252       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2253                   "socks5 client disconnected.\n");
2254       cleanup_s5r (s5r);
2255       return;
2256     }
2257     s5r->rbuf_len += rlen;
2258   }
2259   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2260                                               s5r->sock,
2261                                               &do_s5r_read, s5r);
2262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2263               "Processing %u bytes of socks data in state %d\n",
2264               s5r->rbuf_len,
2265               s5r->state);
2266   switch (s5r->state)
2267   {
2268   case SOCKS5_INIT:
2269     c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2270     if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2271          (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2272       return; /* need more data */
2273     if (SOCKS_VERSION_5 != c_hello->version)
2274     {
2275       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2276                   _("Unsupported socks version %d\n"),
2277                   (int) c_hello->version);
2278       cleanup_s5r (s5r);
2279       return;
2280     }
2281     clear_from_s5r_rbuf (s5r,
2282                          sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2283     GNUNET_assert (0 == s5r->wbuf_len);
2284     s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2285     s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2286     s_hello->version = SOCKS_VERSION_5;
2287     s_hello->auth_method = SOCKS_AUTH_NONE;
2288     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s5r->wtask);
2289     s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2290                                                  s5r->sock,
2291                                                  &do_write, s5r);
2292     s5r->state = SOCKS5_REQUEST;
2293     return;
2294   case SOCKS5_REQUEST:
2295     c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2296     if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2297       return;
2298     switch (c_req->command)
2299     {
2300     case SOCKS5_CMD_TCP_STREAM:
2301       /* handled below */
2302       break;
2303     default:
2304       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2305                   _("Unsupported socks command %d\n"),
2306                   (int) c_req->command);
2307       signal_socks_failure (s5r,
2308                             SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2309       return;
2310     }
2311     switch (c_req->addr_type)
2312     {
2313     case SOCKS5_AT_IPV4:
2314       {
2315         const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2316         const uint16_t *port = (const uint16_t *) &v4[1];
2317         struct sockaddr_in *in;
2318
2319         s5r->port = ntohs (*port);
2320         alen = sizeof (struct in_addr);
2321         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2322             alen + sizeof (uint16_t))
2323           return; /* need more data */
2324         in = (struct sockaddr_in *) &s5r->destination_address;
2325         in->sin_family = AF_INET;
2326         in->sin_addr = *v4;
2327         in->sin_port = *port;
2328 #if HAVE_SOCKADDR_IN_SIN_LEN
2329         in->sin_len = sizeof (*in);
2330 #endif
2331         s5r->state = SOCKS5_DATA_TRANSFER;
2332       }
2333       break;
2334     case SOCKS5_AT_IPV6:
2335       {
2336         const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2337         const uint16_t *port = (const uint16_t *) &v6[1];
2338         struct sockaddr_in6 *in;
2339
2340         s5r->port = ntohs (*port);
2341         alen = sizeof (struct in6_addr);
2342         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2343             alen + sizeof (uint16_t))
2344           return; /* need more data */
2345         in = (struct sockaddr_in6 *) &s5r->destination_address;
2346         in->sin6_family = AF_INET6;
2347         in->sin6_addr = *v6;
2348         in->sin6_port = *port;
2349 #if HAVE_SOCKADDR_IN_SIN_LEN
2350         in->sin6_len = sizeof (*in);
2351 #endif
2352         s5r->state = SOCKS5_DATA_TRANSFER;
2353       }
2354       break;
2355     case SOCKS5_AT_DOMAINNAME:
2356       {
2357         const uint8_t *dom_len;
2358         const char *dom_name;
2359         const uint16_t *port;   
2360         
2361         dom_len = (const uint8_t *) &c_req[1];
2362         alen = *dom_len + 1;
2363         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2364             alen + sizeof (uint16_t))
2365           return; /* need more data */
2366         dom_name = (const char *) &dom_len[1];
2367         port = (const uint16_t*) &dom_name[*dom_len];
2368         s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2369         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2370                     "Requested connection is to %s:%d\n",
2371                     s5r->domain,
2372                     ntohs (*port));
2373         s5r->state = SOCKS5_RESOLVING;
2374         s5r->port = ntohs (*port);
2375         s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2376                                              s5r->domain,
2377                                              &local_gns_zone,
2378                                              GNUNET_DNSPARSER_TYPE_A,
2379                                              GNUNET_NO /* only cached */,
2380                                              (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2381                                              &handle_gns_result,
2382                                              s5r);                                           
2383         break;
2384       }
2385     default:
2386       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2387                   _("Unsupported socks address type %d\n"),
2388                   (int) c_req->addr_type);
2389       signal_socks_failure (s5r,
2390                             SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2391       return;
2392     }
2393     clear_from_s5r_rbuf (s5r,
2394                          sizeof (struct Socks5ClientRequestMessage) +
2395                          alen + sizeof (uint16_t));
2396     if (0 != s5r->rbuf_len)
2397     {
2398       /* read more bytes than healthy, why did the client send more!? */
2399       GNUNET_break_op (0);
2400       signal_socks_failure (s5r,
2401                             SOCKS5_STATUS_GENERAL_FAILURE);
2402       return;       
2403     }
2404     if (SOCKS5_DATA_TRANSFER == s5r->state)
2405     {
2406       /* if we are not waiting for GNS resolution, signal success */
2407       signal_socks_success (s5r);
2408     }
2409     /* We are done reading right now */
2410     GNUNET_SCHEDULER_cancel (s5r->rtask);
2411     s5r->rtask = GNUNET_SCHEDULER_NO_TASK;    
2412     return;
2413   case SOCKS5_RESOLVING:
2414     GNUNET_assert (0);
2415     return;
2416   case SOCKS5_DATA_TRANSFER:
2417     GNUNET_assert (0);
2418     return;
2419   default:
2420     GNUNET_assert (0);
2421     return;
2422   }
2423 }
2424
2425
2426 /**
2427  * Accept new incoming connections
2428  *
2429  * @param cls the closure
2430  * @param tc the scheduler context
2431  */
2432 static void
2433 do_accept (void *cls, 
2434            const struct GNUNET_SCHEDULER_TaskContext *tc)
2435 {
2436   struct GNUNET_NETWORK_Handle *s;
2437   struct Socks5Request *s5r;
2438
2439   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2440                                          lsock,
2441                                          &do_accept, NULL);
2442   s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2443   if (NULL == s)
2444   {
2445     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2446     return;
2447   }
2448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2449               "Got an inbound connection, waiting for data\n");
2450   s5r = GNUNET_new (struct Socks5Request);
2451   GNUNET_CONTAINER_DLL_insert (s5r_head,
2452                                s5r_tail,
2453                                s5r);
2454   s5r->sock = s;
2455   s5r->state = SOCKS5_INIT;
2456   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2457                                               s5r->sock,
2458                                               &do_s5r_read, s5r);
2459 }
2460
2461
2462 /* ******************* General / main code ********************* */
2463
2464
2465 /**
2466  * Task run on shutdown
2467  *
2468  * @param cls closure
2469  * @param tc task context
2470  */
2471 static void
2472 do_shutdown (void *cls,
2473              const struct GNUNET_SCHEDULER_TaskContext *tc)
2474 {
2475   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2476               "Shutting down...\n");
2477   while (NULL != mhd_httpd_head)
2478     kill_httpd (mhd_httpd_head);
2479   if (NULL != lsock)
2480   {
2481     GNUNET_NETWORK_socket_close (lsock);
2482     lsock = NULL;
2483   }
2484   if (NULL != id_op)
2485   {
2486     GNUNET_IDENTITY_cancel (id_op);
2487     id_op = NULL;
2488   }
2489   if (NULL != identity)
2490   {
2491     GNUNET_IDENTITY_disconnect (identity);
2492     identity = NULL;
2493   }
2494   if (NULL != curl_multi)
2495   {
2496     curl_multi_cleanup (curl_multi);
2497     curl_multi = NULL;
2498   }
2499   if (NULL != gns_handle)
2500   {
2501     GNUNET_GNS_disconnect (gns_handle);
2502     gns_handle = NULL;
2503   }
2504   if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
2505   {
2506     GNUNET_SCHEDULER_cancel (curl_download_task);
2507     curl_download_task = GNUNET_SCHEDULER_NO_TASK;
2508   }
2509   if (GNUNET_SCHEDULER_NO_TASK != ltask)
2510   {
2511     GNUNET_SCHEDULER_cancel (ltask);
2512     ltask = GNUNET_SCHEDULER_NO_TASK;
2513   }
2514   gnutls_x509_crt_deinit (proxy_ca.cert);
2515   gnutls_x509_privkey_deinit (proxy_ca.key);
2516   gnutls_global_deinit ();
2517 }
2518
2519
2520 /**
2521  * Continue initialization after we have our zone information.
2522  */
2523 static void 
2524 run_cont () 
2525 {
2526   struct MhdHttpList *hd;
2527   struct sockaddr_in sa;
2528
2529   /* Open listen socket for socks proxy */
2530   /* FIXME: support IPv6! */
2531   memset (&sa, 0, sizeof (sa));
2532   sa.sin_family = AF_INET;
2533   sa.sin_port = htons (port);
2534 #if HAVE_SOCKADDR_IN_SIN_LEN
2535   sa.sin_len = sizeof (sa);
2536 #endif
2537   lsock = GNUNET_NETWORK_socket_create (AF_INET,
2538                                         SOCK_STREAM,
2539                                         0);
2540   if (NULL == lsock) 
2541   {
2542     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2543     GNUNET_SCHEDULER_shutdown ();
2544     return;
2545   }
2546   if (GNUNET_OK !=
2547       GNUNET_NETWORK_socket_bind (lsock, (const struct sockaddr *) &sa,
2548                                   sizeof (sa), 0))
2549   {
2550     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2551     GNUNET_SCHEDULER_shutdown ();
2552     return;
2553   }
2554   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock, 5))
2555   {
2556     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2557     return;
2558   }
2559   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2560                                          lsock, &do_accept, NULL);
2561
2562   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
2563   {
2564     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2565                 "cURL global init failed!\n");
2566     GNUNET_SCHEDULER_shutdown ();
2567     return;
2568   }
2569   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2570               "Proxy listens on port %u\n",
2571               port);
2572
2573   /* start MHD daemon for HTTP */
2574   hd = GNUNET_new (struct MhdHttpList);
2575   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
2576                                  0,
2577                                  NULL, NULL,
2578                                  &create_response, hd,
2579                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2580                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2581                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2582                                  MHD_OPTION_END);
2583   if (NULL == hd->daemon)
2584   {
2585     GNUNET_free (hd);
2586     GNUNET_SCHEDULER_shutdown ();
2587     return;
2588   }
2589   httpd = hd;
2590   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2591 }
2592
2593
2594 /** 
2595  * Method called to inform about the egos of the shorten zone of this peer.
2596  *
2597  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2598  * this function is only called ONCE, and 'NULL' being passed in
2599  * @a ego does indicate an error (i.e. name is taken or no default
2600  * value is known).  If @a ego is non-NULL and if '*ctx'
2601  * is set in those callbacks, the value WILL be passed to a subsequent
2602  * call to the identity callback of #GNUNET_IDENTITY_connect (if 
2603  * that one was not NULL).
2604  *
2605  * @param cls closure, NULL
2606  * @param ego ego handle
2607  * @param ctx context for application to store data for this ego
2608  *                 (during the lifetime of this process, initially NULL)
2609  * @param name name assigned by the user for this ego,
2610  *                   NULL if the user just deleted the ego and it
2611  *                   must thus no longer be used
2612  */
2613 static void
2614 identity_shorten_cb (void *cls,
2615                      struct GNUNET_IDENTITY_Ego *ego,
2616                      void **ctx,
2617                      const char *name)
2618 {
2619   id_op = NULL;
2620   if (NULL == ego)
2621   {
2622     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2623                 _("No ego configured for `shorten-zone`\n"));
2624   }
2625   else
2626   {
2627     local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
2628     do_shorten = GNUNET_YES;
2629   }
2630   run_cont ();
2631 }
2632
2633
2634 /** 
2635  * Method called to inform about the egos of the master zone of this peer.
2636  *
2637  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2638  * this function is only called ONCE, and 'NULL' being passed in
2639  * @a ego does indicate an error (i.e. name is taken or no default
2640  * value is known).  If @a ego is non-NULL and if '*ctx'
2641  * is set in those callbacks, the value WILL be passed to a subsequent
2642  * call to the identity callback of #GNUNET_IDENTITY_connect (if 
2643  * that one was not NULL).
2644  *
2645  * @param cls closure, NULL
2646  * @param ego ego handle
2647  * @param ctx context for application to store data for this ego
2648  *                 (during the lifetime of this process, initially NULL)
2649  * @param name name assigned by the user for this ego,
2650  *                   NULL if the user just deleted the ego and it
2651  *                   must thus no longer be used
2652  */
2653 static void
2654 identity_master_cb (void *cls,
2655                     struct GNUNET_IDENTITY_Ego *ego,
2656                     void **ctx,
2657                     const char *name)
2658 {
2659   id_op = NULL;
2660   if (NULL == ego)
2661   {
2662     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2663                 _("No ego configured for `%s`\n"),
2664                 "gns-proxy");
2665     GNUNET_SCHEDULER_shutdown ();
2666     return;
2667   }
2668   GNUNET_IDENTITY_ego_get_public_key (ego,
2669                                       &local_gns_zone);
2670   id_op = GNUNET_IDENTITY_get (identity,
2671                                "gns-short",
2672                                &identity_shorten_cb,
2673                                NULL);
2674 }
2675
2676
2677 /**
2678  * Main function that will be run
2679  *
2680  * @param cls closure
2681  * @param args remaining command-line arguments
2682  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2683  * @param c configuration
2684  */
2685 static void
2686 run (void *cls, char *const *args, const char *cfgfile,
2687      const struct GNUNET_CONFIGURATION_Handle *c)
2688 {
2689   char* cafile_cfg = NULL;
2690   char* cafile;
2691
2692   cfg = c;
2693   if (NULL == (curl_multi = curl_multi_init ()))
2694   {
2695     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2696                 "Failed to create cURL multi handle!\n");
2697     return;
2698   } 
2699   cafile = cafile_opt;
2700   if (NULL == cafile)
2701   {
2702     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
2703                                                               "PROXY_CACERT",
2704                                                               &cafile_cfg))
2705     {
2706       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2707                                  "gns-proxy",
2708                                  "PROXY_CACERT");
2709       return;
2710     }
2711     cafile = cafile_cfg;
2712   }
2713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2714               "Using %s as CA\n", cafile);
2715   
2716   gnutls_global_init ();
2717   gnutls_x509_crt_init (&proxy_ca.cert);
2718   gnutls_x509_privkey_init (&proxy_ca.key);
2719   
2720   if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
2721        (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
2722   {
2723     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2724                 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
2725                 cafile);
2726     gnutls_x509_crt_deinit (proxy_ca.cert);
2727     gnutls_x509_privkey_deinit (proxy_ca.key);
2728     gnutls_global_deinit ();
2729     GNUNET_free_non_null (cafile_cfg);  
2730     return;
2731   }
2732   GNUNET_free_non_null (cafile_cfg);
2733   if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
2734   {
2735     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2736                 "Unable to connect to GNS!\n");
2737     gnutls_x509_crt_deinit (proxy_ca.cert);
2738     gnutls_x509_privkey_deinit (proxy_ca.key);
2739     gnutls_global_deinit ();
2740     return;
2741   }
2742   identity = GNUNET_IDENTITY_connect (cfg,
2743                                       NULL, NULL);  
2744   id_op = GNUNET_IDENTITY_get (identity,
2745                                "gns-proxy",
2746                                &identity_master_cb,
2747                                NULL);  
2748   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2749                                 &do_shutdown, NULL);
2750 }
2751
2752
2753 /**
2754  * The main function for gnunet-gns-proxy.
2755  *
2756  * @param argc number of arguments from the command line
2757  * @param argv command line arguments
2758  * @return 0 ok, 1 on error
2759  */
2760 int
2761 main (int argc, char *const *argv)
2762 {
2763   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2764     {'p', "port", NULL,
2765      gettext_noop ("listen on specified port (default: 7777)"), 1,
2766      &GNUNET_GETOPT_set_ulong, &port},
2767     {'a', "authority", NULL,
2768       gettext_noop ("pem file to use as CA"), 1,
2769       &GNUNET_GETOPT_set_string, &cafile_opt},
2770     GNUNET_GETOPT_OPTION_END
2771   };
2772   static const char* page = 
2773     "<html><head><title>gnunet-gns-proxy</title>"
2774     "</head><body>cURL fail</body></html>";
2775   int ret;
2776
2777   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
2778     return 2;
2779   GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
2780   curl_failure_response = MHD_create_response_from_buffer (strlen (page),
2781                                                            (void*)page,
2782                                                            MHD_RESPMEM_PERSISTENT);
2783
2784   ret =
2785       (GNUNET_OK ==
2786        GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
2787                            _("GNUnet GNS proxy"),
2788                            options,
2789                            &run, NULL)) ? 0 : 1;
2790   MHD_destroy_response (curl_failure_response);
2791   GNUNET_free_non_null ((char *) argv);
2792   return ret;
2793 }
2794
2795 /* end of gnunet-gns-proxy.c */