f42bf9af48cda58f5db1a167c8be2c30bd11c75e
[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  * Run MHD now, we have extra data ready for the callback.
669  *
670  * @param hd the daemon to run now.
671  */
672 static void
673 run_mhd_now (struct MhdHttpList *hd);
674
675
676 /**
677  * Clean up s5r handles.
678  *
679  * @param s5r the handle to destroy
680  */
681 static void
682 cleanup_s5r (struct Socks5Request *s5r)
683 {
684   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
685               "Cleaning up socks request\n");   
686   if (NULL != s5r->curl)
687   { 
688     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
689                 "Cleaning up cURL handle\n");   
690     curl_multi_remove_handle (curl_multi, s5r->curl);
691     curl_easy_cleanup (s5r->curl);
692     s5r->curl = NULL;
693   }
694   curl_slist_free_all (s5r->headers);
695   if ( (NULL != s5r->response) &&
696        (curl_failure_response != s5r->response) )
697     MHD_destroy_response (s5r->response);
698   if (GNUNET_SCHEDULER_NO_TASK != s5r->rtask)
699     GNUNET_SCHEDULER_cancel (s5r->rtask);
700   if (GNUNET_SCHEDULER_NO_TASK != s5r->timeout_task)
701     GNUNET_SCHEDULER_cancel (s5r->timeout_task);
702   if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
703     GNUNET_SCHEDULER_cancel (s5r->wtask);
704   if (NULL != s5r->gns_lookup)
705     GNUNET_GNS_lookup_cancel (s5r->gns_lookup);
706   if (NULL != s5r->sock) 
707   {
708     if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
709       GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
710     else
711       GNUNET_NETWORK_socket_close (s5r->sock);
712   }
713   GNUNET_CONTAINER_DLL_remove (s5r_head,
714                                s5r_tail,
715                                s5r);
716   GNUNET_free_non_null (s5r->domain);
717   GNUNET_free_non_null (s5r->leho);
718   GNUNET_free_non_null (s5r->url);
719   GNUNET_free (s5r);
720 }
721
722
723 /* ************************* HTTP handling with cURL *********************** */
724
725
726 /**
727  * Callback for MHD response generation.  This function is called from
728  * MHD whenever MHD expects to get data back.  Copies data from the
729  * io_buf, if available.
730  *
731  * @param cls closure with our `struct Socks5Request`
732  * @param pos in buffer
733  * @param buf where to copy data
734  * @param max available space in @a buf
735  * @return number of bytes written to @a buf
736  */
737 static ssize_t
738 mhd_content_cb (void *cls,
739                 uint64_t pos,
740                 char* buf,
741                 size_t max)
742 {
743   struct Socks5Request *s5r = cls;
744   size_t bytes_to_copy;
745
746   if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
747        (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
748   {
749     /* we're still not done with the upload, do not yet
750        start the download, the IO buffer is still full
751        with upload data. */
752     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
753                 "Pausing MHD download, not yet ready for download\n");
754     return 0; /* not yet ready for data download */
755   }
756   bytes_to_copy = GNUNET_MIN (max,
757                               s5r->io_len);
758   if ( (0 == bytes_to_copy) &&
759        (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
760   {
761     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
762                 "Pausing MHD download, no data available\n");
763     return 0; /* more data later */
764   }
765   if ( (0 == bytes_to_copy) &&
766        (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
767   {
768     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
769                 "Completed MHD download\n");
770     return MHD_CONTENT_READER_END_OF_STREAM;
771   }
772   memcpy (buf, s5r->io_buf, bytes_to_copy);
773   memmove (s5r->io_buf,
774            &s5r->io_buf[bytes_to_copy],
775            s5r->io_len - bytes_to_copy);
776   s5r->io_len -= bytes_to_copy;
777   if (NULL != s5r->curl)
778     curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
779   return bytes_to_copy;
780 }
781
782
783 /**
784  * Check that the website has presented us with a valid SSL certificate.
785  * The certificate must either match the domain name or the LEHO name
786  * (or, if available, the TLSA record).
787  *
788  * @param s5r request to check for.
789  * @return #GNUNET_OK if the certificate is valid
790  */
791 static int
792 check_ssl_certificate (struct Socks5Request *s5r)
793 {
794   union {
795     struct curl_slist    *to_info;
796     struct curl_certinfo *to_certinfo;
797   } ptr;
798   int i;
799   struct curl_slist *slist;
800   
801   ptr.to_info = NULL;  
802   if (CURLE_OK != 
803       curl_easy_getinfo (s5r->curl, 
804                          CURLINFO_CERTINFO, 
805                          &ptr.to_info))
806     return GNUNET_SYSERR;
807   /* FIXME: for now, we just output the certs to stderr, we should
808      check them against LEHO / TLSA record information here! (#3038) */
809   if(NULL != ptr.to_info) 
810   {     
811     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
812                 "Got %d certs!\n", 
813                 ptr.to_certinfo->num_of_certs);      
814     for (i = 0; i < ptr.to_certinfo->num_of_certs; i++) 
815     {    
816       for (slist = ptr.to_certinfo->certinfo[i]; NULL != slist; slist = slist->next)
817         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
818                     "Certificate #%d: %s\n",
819                     i,
820                     slist->data);       
821     }
822   }
823   return GNUNET_OK;
824 }
825
826  
827 /**
828  * We're getting an HTTP response header from cURL.  Convert it to the
829  * MHD response headers.  Mostly copies the headers, but makes special
830  * adjustments to "Set-Cookie" and "Location" headers as those may need
831  * to be changed from the LEHO to the domain the browser expects.
832  *
833  * @param buffer curl buffer with a single line of header data; not 0-terminated!
834  * @param size curl blocksize
835  * @param nmemb curl blocknumber
836  * @param cls our `struct Socks5Request *`
837  * @return size of processed bytes
838  */
839 static size_t
840 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
841 {
842   struct Socks5Request *s5r = cls;
843   size_t bytes = size * nmemb;
844   char *ndup;
845   const char *hdr_type;
846   const char *cookie_domain;
847   char *hdr_val;
848   long resp_code;
849   char *new_cookie_hdr;
850   char *new_location;
851   size_t offset;
852   size_t delta_cdomain;
853   int domain_matched;
854   char *tok;
855
856   if (NULL == s5r->response)
857   {
858     /* first, check SSL certificate */
859     if ( (HTTPS_PORT == s5r->port) &&
860          (GNUNET_OK != check_ssl_certificate (s5r)) )
861       return 0;
862
863     GNUNET_break (CURLE_OK == 
864                   curl_easy_getinfo (s5r->curl,
865                                      CURLINFO_RESPONSE_CODE,
866                                      &resp_code));
867     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
868                 "Creating MHD response with code %d\n",
869                 (int) resp_code);
870     s5r->response_code = resp_code;
871     s5r->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
872                                                        IO_BUFFERSIZE,
873                                                        &mhd_content_cb,
874                                                        s5r,
875                                                        NULL);
876     if (NULL != s5r->leho)
877     {
878       char *cors_hdr;
879       
880       GNUNET_asprintf (&cors_hdr, 
881                        (HTTPS_PORT == s5r->port)
882                        ? "https://%s"
883                        : "http://%s",
884                        s5r->leho);
885       
886       GNUNET_break (MHD_YES == 
887                     MHD_add_response_header (s5r->response,
888                                              MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
889                                              cors_hdr));
890       GNUNET_free (cors_hdr);
891     }
892     /* force connection to be closed after each request, as we 
893        do not support HTTP pipelining */
894     GNUNET_break (MHD_YES == 
895                   MHD_add_response_header (s5r->response,
896                                            MHD_HTTP_HEADER_CONNECTION,
897                                            "close"));
898   }
899   
900   ndup = GNUNET_strndup (buffer, bytes);
901   hdr_type = strtok (ndup, ":");
902   if (NULL == hdr_type)
903   {
904     GNUNET_free (ndup);
905     return bytes;
906   }
907   hdr_val = strtok (NULL, "");
908   if (NULL == hdr_val)
909   {
910     GNUNET_free (ndup);
911     return bytes;
912   }
913   if (' ' == *hdr_val)
914     hdr_val++;
915
916   /* custom logic for certain header types */
917   new_cookie_hdr = NULL;
918   if (0 == strcasecmp (hdr_type,
919                        MHD_HTTP_HEADER_SET_COOKIE))
920   {
921     new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) + 
922                                     strlen (s5r->domain) + 1);
923     offset = 0;
924     domain_matched = GNUNET_NO; /* make sure we match domain at most once */
925     for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
926     {
927       if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
928            (GNUNET_NO == domain_matched) )
929       {
930         domain_matched = GNUNET_YES;
931         cookie_domain = tok + strlen (" domain") + 1;
932         if (strlen (cookie_domain) < strlen (s5r->leho))
933         {
934           delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
935           if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
936           {
937             offset += sprintf (new_cookie_hdr + offset,
938                                " domain=%s;", 
939                                s5r->domain);
940             continue;
941           }
942         }
943         else if (0 == strcmp (cookie_domain, s5r->leho))
944         {
945           offset += sprintf (new_cookie_hdr + offset,
946                              " domain=%s;", 
947                              s5r->domain);
948           continue;          
949         }
950         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
951                     _("Cookie domain `%s' supplied by server is invalid\n"),
952                     tok);
953       }
954       memcpy (new_cookie_hdr + offset, tok, strlen (tok));
955       offset += strlen (tok);
956       new_cookie_hdr[offset++] = ';';
957     }
958     hdr_val = new_cookie_hdr;
959   }
960
961   new_location = NULL;
962   if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
963   {
964     char *leho_host;
965     
966     GNUNET_asprintf (&leho_host,
967                      (HTTPS_PORT != s5r->port)
968                      ? "http://%s"
969                      : "https://%s",
970                      s5r->leho);
971     if (0 == strncmp (leho_host, 
972                       hdr_val, 
973                       strlen (leho_host)))
974     {
975       GNUNET_asprintf (&new_location,
976                        "%s%s%s",
977                        (HTTPS_PORT != s5r->port)
978                        ? "http://"
979                        : "https://",
980                        s5r->domain,
981                        hdr_val + strlen (leho_host));
982       hdr_val = new_location;
983     }
984     GNUNET_free (leho_host);
985   }
986   /* MHD does not allow certain characters in values, remove those */
987   if (NULL != (tok = strchr (hdr_val, '\n')))
988     *tok = '\0';
989   if (NULL != (tok = strchr (hdr_val, '\r')))
990     *tok = '\0';
991   if (NULL != (tok = strchr (hdr_val, '\t')))
992     *tok = '\0';
993   if (0 != strlen (hdr_val))
994   {
995     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
996                 "Adding header %s: %s to MHD response\n",
997                 hdr_type,
998                 hdr_val);
999     GNUNET_break (MHD_YES ==
1000                   MHD_add_response_header (s5r->response,
1001                                            hdr_type,
1002                                            hdr_val));
1003   }
1004   GNUNET_free (ndup);
1005   GNUNET_free_non_null (new_cookie_hdr);
1006   GNUNET_free_non_null (new_location);
1007   return bytes;
1008 }
1009
1010
1011 /**
1012  * Handle response payload data from cURL.  Copies it into our `io_buf` to make
1013  * it available to MHD.
1014  *
1015  * @param ptr pointer to the data
1016  * @param size number of blocks of data
1017  * @param nmemb blocksize
1018  * @param ctx our `struct Socks5Request *`
1019  * @return number of bytes handled
1020  */
1021 static size_t
1022 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1023 {
1024   struct Socks5Request *s5r = ctx;
1025   size_t total = size * nmemb;
1026
1027   if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1028        (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1029   {
1030     /* we're still not done with the upload, do not yet
1031        start the download, the IO buffer is still full
1032        with upload data. */
1033     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1034                 "Pausing CURL download, waiting for UPLOAD to finish\n");
1035     return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1036   }
1037   if (sizeof (s5r->io_buf) - s5r->io_len < total)
1038   {
1039     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1040                 "Pausing CURL download, not enough space\n");
1041     return CURL_WRITEFUNC_PAUSE; /* not enough space */
1042   }
1043   memcpy (&s5r->io_buf[s5r->io_len], 
1044           ptr,
1045           total);
1046   s5r->io_len += total;
1047   if (s5r->io_len == total)
1048     run_mhd_now (s5r->hd);  
1049   return total;
1050 }
1051
1052
1053 /**
1054  * cURL callback for uploaded (PUT/POST) data.  Copies it into our `io_buf`
1055  * to make it available to MHD.
1056  *
1057  * @param buf where to write the data
1058  * @param size number of bytes per member
1059  * @param nmemb number of members available in @a buf
1060  * @param cls our `struct Socks5Request` that generated the data
1061  * @return number of bytes copied to @a buf
1062  */
1063 static size_t
1064 curl_upload_cb (void *buf, size_t size, size_t nmemb, void *cls)
1065 {
1066   struct Socks5Request *s5r = cls;
1067   size_t len = size * nmemb;
1068   size_t to_copy;
1069
1070   if ( (0 == s5r->io_len) &&
1071        (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1072   {
1073     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1074                 "Pausing CURL UPLOAD, need more data\n");
1075     return CURL_READFUNC_PAUSE;
1076   }
1077   if ( (0 == s5r->io_len) &&
1078        (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1079   {
1080     s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1081     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082                 "Completed CURL UPLOAD\n");
1083     return 0; /* upload finished, can now download */
1084   }
1085   if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) ||
1086        (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1087   {
1088     GNUNET_break (0);
1089     return CURL_READFUNC_ABORT;
1090   }
1091   to_copy = GNUNET_MIN (s5r->io_len,
1092                         len);
1093   memcpy (buf, s5r->io_buf, to_copy);
1094   memmove (s5r->io_buf,
1095            &s5r->io_buf[to_copy],
1096            s5r->io_len - to_copy);
1097   s5r->io_len -= to_copy;
1098   if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1099     run_mhd_now (s5r->hd); /* got more space for upload now */
1100   return to_copy;
1101 }
1102
1103
1104 /* ************************** main loop of cURL interaction ****************** */
1105
1106
1107 /**
1108  * Task that is run when we are ready to receive more data
1109  * from curl
1110  *
1111  * @param cls closure
1112  * @param tc task context
1113  */
1114 static void
1115 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1116
1117
1118 /**
1119  * Ask cURL for the select() sets and schedule cURL operations.
1120  */
1121 static void
1122 curl_download_prepare ()
1123 {
1124   CURLMcode mret;
1125   fd_set rs;
1126   fd_set ws;
1127   fd_set es;
1128   int max;
1129   struct GNUNET_NETWORK_FDSet *grs;
1130   struct GNUNET_NETWORK_FDSet *gws;
1131   long to;
1132   struct GNUNET_TIME_Relative rtime;
1133
1134   if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
1135   {
1136     GNUNET_SCHEDULER_cancel (curl_download_task);
1137     curl_download_task = GNUNET_SCHEDULER_NO_TASK;
1138   }
1139   max = -1;
1140   FD_ZERO (&rs);
1141   FD_ZERO (&ws);
1142   FD_ZERO (&es);
1143   if (CURLM_OK != (mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max)))
1144   {
1145     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1146                 "%s failed at %s:%d: `%s'\n",
1147                 "curl_multi_fdset", __FILE__, __LINE__,
1148                 curl_multi_strerror (mret));
1149     return;
1150   }
1151   to = -1;
1152   GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
1153   if (-1 == to)
1154     rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1155   else
1156     rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1157   if (-1 != max)
1158   {
1159     grs = GNUNET_NETWORK_fdset_create ();
1160     gws = GNUNET_NETWORK_fdset_create ();
1161     GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1162     GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1163     curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1164                                                       rtime,
1165                                                       grs, gws,
1166                                                       &curl_task_download, curl_multi);
1167     GNUNET_NETWORK_fdset_destroy (gws);
1168     GNUNET_NETWORK_fdset_destroy (grs);
1169   }
1170   else 
1171   {
1172     curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1173                                                        &curl_task_download,
1174                                                        curl_multi);
1175   }
1176 }
1177
1178
1179 /**
1180  * Task that is run when we are ready to receive more data from curl.
1181  *
1182  * @param cls closure, NULL
1183  * @param tc task context
1184  */
1185 static void
1186 curl_task_download (void *cls, 
1187                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1188 {
1189   int running;
1190   int msgnum;
1191   struct CURLMsg *msg;
1192   CURLMcode mret;
1193   struct Socks5Request *s5r;
1194
1195   curl_download_task = GNUNET_SCHEDULER_NO_TASK;
1196   do
1197   {
1198     running = 0;    
1199     mret = curl_multi_perform (curl_multi, &running);
1200     while (NULL != (msg = curl_multi_info_read (curl_multi, &msgnum)))
1201     {
1202       GNUNET_break (CURLE_OK ==
1203                     curl_easy_getinfo (msg->easy_handle,
1204                                        CURLINFO_PRIVATE,
1205                                        &s5r));
1206       if (NULL == s5r)
1207       {
1208         GNUNET_break (0);
1209         continue;
1210       }
1211       switch (msg->msg)
1212       {
1213       case CURLMSG_NONE:
1214         /* documentation says this is not used */
1215         GNUNET_break (0);
1216         break;
1217       case CURLMSG_DONE:
1218         switch (msg->data.result)
1219         {
1220         case CURLE_OK:
1221         case CURLE_GOT_NOTHING:
1222           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1223                       "CURL download completed.\n");
1224           s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;       
1225           run_mhd_now (s5r->hd);
1226           break;
1227         default:
1228           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1229                       "Download curl failed: %s\n",
1230                       curl_easy_strerror (msg->data.result));
1231           /* FIXME: indicate error somehow? close MHD connection badly as well? */
1232           s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1233           run_mhd_now (s5r->hd);          
1234           break;
1235         }
1236         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1237                     "Cleaning up cURL handle\n");
1238         curl_multi_remove_handle (curl_multi, s5r->curl);
1239         curl_easy_cleanup (s5r->curl);
1240         s5r->curl = NULL;
1241         if (NULL == s5r->response)
1242           s5r->response = curl_failure_response;
1243         break;
1244       case CURLMSG_LAST:
1245         /* documentation says this is not used */
1246         GNUNET_break (0);
1247         break;
1248       default:
1249         /* unexpected status code */
1250         GNUNET_break (0);
1251         break;
1252       }
1253     };
1254   } while (mret == CURLM_CALL_MULTI_PERFORM);  
1255   if (CURLM_OK != mret)
1256     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1257                 "%s failed at %s:%d: `%s'\n",
1258                 "curl_multi_perform", __FILE__, __LINE__,
1259                 curl_multi_strerror (mret));  
1260   if (0 == running)
1261   {
1262     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1263                 "Suspending cURL multi loop, no more events pending\n");
1264     return; /* nothing more in progress */
1265   }
1266   curl_download_prepare();
1267 }
1268
1269
1270 /* ********************************* MHD response generation ******************* */
1271
1272
1273 /**
1274  * Read HTTP request header field from the request.  Copies the fields
1275  * over to the 'headers' that will be given to curl.  However, 'Host'
1276  * is substituted with the LEHO if present.  We also change the
1277  * 'Connection' header value to "close" as the proxy does not support
1278  * pipelining.
1279  *
1280  * @param cls our `struct Socks5Request`
1281  * @param kind value kind
1282  * @param key field key
1283  * @param value field value
1284  * @return #MHD_YES to continue to iterate
1285  */
1286 static int
1287 con_val_iter (void *cls,
1288               enum MHD_ValueKind kind,
1289               const char *key,
1290               const char *value)
1291 {
1292   struct Socks5Request *s5r = cls;
1293   char *hdr;
1294
1295   if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1296        (NULL != s5r->leho) )
1297     value = s5r->leho;
1298   if (0 == strcasecmp (MHD_HTTP_HEADER_CONNECTION, key))
1299     value = "Close";
1300   GNUNET_asprintf (&hdr,
1301                    "%s: %s",
1302                    key,
1303                    value);
1304   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1305               "Adding HEADER `%s' to HTTP request\n",
1306               hdr);
1307   s5r->headers = curl_slist_append (s5r->headers,
1308                                     hdr);
1309   GNUNET_free (hdr);
1310   return MHD_YES;
1311 }
1312
1313
1314 /**
1315  * Main MHD callback for handling requests.
1316  *
1317  * @param cls unused
1318  * @param con MHD connection handle
1319  * @param url the url in the request
1320  * @param meth the HTTP method used ("GET", "PUT", etc.)
1321  * @param ver the HTTP version string (i.e. "HTTP/1.1")
1322  * @param upload_data the data being uploaded (excluding HEADERS,
1323  *        for a POST that fits into memory and that is encoded
1324  *        with a supported encoding, the POST data will NOT be
1325  *        given in upload_data and is instead available as
1326  *        part of MHD_get_connection_values; very large POST
1327  *        data *will* be made available incrementally in
1328  *        upload_data)
1329  * @param upload_data_size set initially to the size of the
1330  *        @a upload_data provided; the method must update this
1331  *        value to the number of bytes NOT processed;
1332  * @param con_cls pointer to location where we store the 'struct Request'
1333  * @return #MHD_YES if the connection was handled successfully,
1334  *         #MHD_NO if the socket must be closed due to a serious
1335  *         error while handling the request
1336  */
1337 static int
1338 create_response (void *cls,
1339                  struct MHD_Connection *con,
1340                  const char *url,
1341                  const char *meth,
1342                  const char *ver,
1343                  const char *upload_data,
1344                  size_t *upload_data_size,
1345                  void **con_cls)
1346 {
1347   /* struct MhdHttpList* hd = cls;  */
1348   struct Socks5Request *s5r = *con_cls;
1349   char *curlurl;
1350   char ipstring[INET6_ADDRSTRLEN];
1351   char ipaddr[INET6_ADDRSTRLEN + 2];
1352   const struct sockaddr *sa;
1353   const struct sockaddr_in *s4;
1354   const struct sockaddr_in6 *s6;
1355   uint16_t port;
1356   size_t left;
1357
1358   if (NULL == s5r)
1359   {
1360     GNUNET_break (0);
1361     return MHD_NO;
1362   }
1363   if ( (NULL == s5r->curl) &&
1364        (SOCKS5_SOCKET_WITH_MHD == s5r->state) )
1365   {
1366     /* first time here, initialize curl handle */
1367     sa = (const struct sockaddr *) &s5r->destination_address;
1368     switch (sa->sa_family)
1369     {
1370     case AF_INET:
1371       s4 = (const struct sockaddr_in *) &s5r->destination_address;
1372       if (NULL == inet_ntop (AF_INET,
1373                              &s4->sin_addr,
1374                              ipstring,
1375                              sizeof (ipstring)))
1376       {
1377         GNUNET_break (0);
1378         return MHD_NO;
1379       }
1380       GNUNET_snprintf (ipaddr,
1381                        sizeof (ipaddr),
1382                        "%s",
1383                        ipstring);
1384       port = ntohs (s4->sin_port);
1385       break;
1386     case AF_INET6:
1387       s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1388       if (NULL == inet_ntop (AF_INET6,
1389                              &s6->sin6_addr,
1390                              ipstring,
1391                              sizeof (ipstring)))
1392       {
1393         GNUNET_break (0);
1394         return MHD_NO;
1395       }
1396       GNUNET_snprintf (ipaddr,
1397                        sizeof (ipaddr),
1398                        "[%s]",
1399                        ipstring);
1400       port = ntohs (s6->sin6_port);
1401       break;
1402     default:
1403       GNUNET_break (0);
1404       return MHD_NO;
1405     }
1406     s5r->curl = curl_easy_init ();
1407     if (NULL == s5r->curl)
1408       return MHD_queue_response (con,
1409                                  MHD_HTTP_INTERNAL_SERVER_ERROR,
1410                                  curl_failure_response);    
1411     curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1412     curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1413     curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1414     curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1415     curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1416     curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1417     curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1418     curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1419     curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1420     curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1421     curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1422     curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0); // FIXME: remove later
1423     GNUNET_asprintf (&curlurl,
1424                      (HTTPS_PORT != s5r->port)
1425                      ? "http://%s:%d%s"
1426                      : "https://%s:%d%s",
1427                      ipaddr,
1428                      port, 
1429                      s5r->url);   
1430     curl_easy_setopt (s5r->curl,
1431                       CURLOPT_URL, 
1432                       curlurl);   
1433     GNUNET_free (curlurl);
1434
1435     if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1436     {
1437       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1438       curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
1439       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1440       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1441       curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1442       curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1443     } 
1444     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1445     {
1446       s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;    
1447       curl_easy_setopt (s5r->curl, CURLOPT_POST, 1);
1448       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1449       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1450       curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1451       curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1452     }
1453     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1454     {
1455       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;    
1456       curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
1457     }
1458     else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1459     {
1460       s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;    
1461       curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
1462       curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1463       curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1464     }
1465     else
1466     {
1467       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1468                   _("Unsupported HTTP method `%s'\n"),
1469                   meth);
1470       curl_easy_cleanup (s5r->curl);
1471       s5r->curl = NULL;      
1472       return MHD_NO;
1473     }
1474     
1475     if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1476     {
1477       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1478     }
1479     else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1480     {
1481       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1482     }
1483     else
1484     {
1485       curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1486     }
1487     
1488     if (HTTPS_PORT == s5r->port)
1489     {
1490       curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1491       curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1492       /* Disable cURL checking the hostname, as we will check ourselves
1493          as only we have the domain name or the LEHO or the DANE record */
1494       curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);      
1495     }
1496     else
1497     {
1498       curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);   
1499     }
1500
1501     if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
1502     {
1503       GNUNET_break (0);
1504       curl_easy_cleanup (s5r->curl);
1505       s5r->curl = NULL;      
1506       return MHD_NO;      
1507     }
1508     MHD_get_connection_values (con,
1509                                MHD_HEADER_KIND,
1510                                &con_val_iter, s5r);
1511     curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
1512     curl_download_prepare ();
1513     return MHD_YES;
1514   } 
1515
1516   /* continuing to process request */
1517   if (0 != *upload_data_size)
1518   {
1519     left = GNUNET_MIN (*upload_data_size,
1520                        sizeof (s5r->io_buf) - s5r->io_len);
1521     memcpy (&s5r->io_buf[s5r->io_len], 
1522             upload_data,
1523             left);
1524     s5r->io_len += left;
1525     *upload_data_size -= left;   
1526     GNUNET_assert (NULL != s5r->curl);
1527     curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
1528     curl_download_prepare ();
1529     return MHD_YES;
1530   }
1531   if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
1532   {
1533     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1534                 "Finished processing UPLOAD\n");
1535     s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1536   }
1537   if (NULL == s5r->response) 
1538     return MHD_YES; /* too early to queue response, did not yet get headers from cURL */
1539   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1540               "Queueing response with MHD\n");
1541   return MHD_queue_response (con,
1542                              s5r->response_code, 
1543                              s5r->response);
1544 }
1545
1546
1547 /* ******************** MHD HTTP setup and event loop ******************** */
1548
1549
1550 /**
1551  * Function called when MHD decides that we are done with a connection.
1552  *
1553  * @param cls NULL
1554  * @param connection connection handle
1555  * @param con_cls value as set by the last call to
1556  *        the #MHD_AccessHandlerCallback, should be our `struct Socks5Request`
1557  * @param toe reason for request termination (ignored)
1558  */
1559 static void
1560 mhd_completed_cb (void *cls,
1561                   struct MHD_Connection *connection,
1562                   void **con_cls,
1563                   enum MHD_RequestTerminationCode toe)
1564 {
1565   struct Socks5Request *s5r = *con_cls;
1566
1567   if (NULL == s5r)
1568     return;
1569   if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
1570     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1571                 "MHD encountered error handling request: %d\n",
1572                 toe);
1573   cleanup_s5r (s5r);
1574   *con_cls = NULL;  
1575 }
1576
1577
1578 /**
1579  * Function called when MHD first processes an incoming connection.
1580  * Gives us the respective URI information.
1581  *
1582  * We use this to associate the `struct MHD_Connection` with our 
1583  * internal `struct Socks5Request` data structure (by checking
1584  * for matching sockets).
1585  *
1586  * @param cls the HTTP server handle (a `struct MhdHttpList`)
1587  * @param url the URL that is being requested
1588  * @param connection MHD connection object for the request
1589  * @return the `struct Socks5Request` that this @a connection is for
1590  */
1591 static void *
1592 mhd_log_callback (void *cls, 
1593                   const char *url,
1594                   struct MHD_Connection *connection)
1595 {
1596   struct Socks5Request *s5r;
1597   const union MHD_ConnectionInfo *ci;
1598   int sock;
1599
1600   ci = MHD_get_connection_info (connection,
1601                                 MHD_CONNECTION_INFO_CONNECTION_FD);
1602   if (NULL == ci) 
1603   {
1604     GNUNET_break (0);
1605     return NULL;
1606   }
1607   sock = ci->connect_fd;
1608   for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1609   {
1610     if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1611     {
1612       if (NULL != s5r->url)
1613       {
1614         GNUNET_break (0);
1615         return NULL;
1616       }
1617       s5r->url = GNUNET_strdup (url);
1618       GNUNET_SCHEDULER_cancel (s5r->timeout_task);
1619       s5r->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1620       return s5r;
1621     }
1622   }
1623   return NULL;
1624 }
1625
1626
1627 /**
1628  * Kill the given MHD daemon.
1629  *
1630  * @param hd daemon to stop
1631  */
1632 static void
1633 kill_httpd (struct MhdHttpList *hd)
1634 {
1635   GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1636                                mhd_httpd_tail,
1637                                hd);
1638   GNUNET_free_non_null (hd->domain);
1639   MHD_stop_daemon (hd->daemon);
1640   if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1641   {
1642     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1643     hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
1644   }
1645   GNUNET_free_non_null (hd->proxy_cert);
1646   if (hd == httpd)
1647     httpd = NULL;
1648   GNUNET_free (hd);
1649 }
1650
1651
1652 /**
1653  * Task run whenever HTTP server is idle for too long. Kill it.
1654  *
1655  * @param cls the `struct MhdHttpList *`
1656  * @param tc sched context
1657  */
1658 static void
1659 kill_httpd_task (void *cls,
1660                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1661 {
1662   struct MhdHttpList *hd = cls;
1663
1664   hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
1665   kill_httpd (hd);
1666 }
1667
1668
1669 /**
1670  * Task run whenever HTTP server operations are pending.
1671  *
1672  * @param cls the `struct MhdHttpList *` of the daemon that is being run
1673  * @param tc sched context
1674  */
1675 static void
1676 do_httpd (void *cls,
1677           const struct GNUNET_SCHEDULER_TaskContext *tc);
1678
1679
1680 /**
1681  * Schedule MHD.  This function should be called initially when an
1682  * MHD is first getting its client socket, and will then automatically
1683  * always be called later whenever there is work to be done.
1684  *
1685  * @param hd the daemon to schedule
1686  */
1687 static void
1688 schedule_httpd (struct MhdHttpList *hd)
1689 {
1690   fd_set rs;
1691   fd_set ws;
1692   fd_set es;
1693   struct GNUNET_NETWORK_FDSet *wrs;
1694   struct GNUNET_NETWORK_FDSet *wws;
1695   int max;
1696   int haveto;
1697   MHD_UNSIGNED_LONG_LONG timeout;
1698   struct GNUNET_TIME_Relative tv;
1699
1700   FD_ZERO (&rs);
1701   FD_ZERO (&ws);
1702   FD_ZERO (&es);
1703   max = -1;
1704   if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1705   {
1706     kill_httpd (hd);
1707     return;
1708   }
1709   haveto = MHD_get_timeout (hd->daemon, &timeout);
1710   if (MHD_YES == haveto)
1711     tv.rel_value_us = (uint64_t) timeout * 1000LL;
1712   else
1713     tv = GNUNET_TIME_UNIT_FOREVER_REL;
1714   if (-1 != max)
1715   {
1716     wrs = GNUNET_NETWORK_fdset_create ();
1717     wws = GNUNET_NETWORK_fdset_create ();
1718     GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1719     GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1720   }
1721   else
1722   {
1723     wrs = NULL;
1724     wws = NULL;
1725   }
1726   if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1727     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1728   if ( (MHD_YES != haveto) &&
1729        (-1 == max) &&
1730        (hd != httpd) )
1731   {
1732     /* daemon is idle, kill after timeout */
1733     hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
1734                                                    &kill_httpd_task,
1735                                                    hd);
1736   }
1737   else
1738   {
1739     hd->httpd_task =
1740       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1741                                    tv, wrs, wws,
1742                                    &do_httpd, hd);
1743   }
1744   if (NULL != wrs)
1745     GNUNET_NETWORK_fdset_destroy (wrs);
1746   if (NULL != wws)
1747     GNUNET_NETWORK_fdset_destroy (wws);
1748 }
1749
1750
1751 /**
1752  * Task run whenever HTTP server operations are pending.
1753  *
1754  * @param cls the `struct MhdHttpList` of the daemon that is being run
1755  * @param tc scheduler context
1756  */
1757 static void
1758 do_httpd (void *cls,
1759           const struct GNUNET_SCHEDULER_TaskContext *tc)
1760 {
1761   struct MhdHttpList *hd = cls;
1762   
1763   hd->httpd_task = GNUNET_SCHEDULER_NO_TASK; 
1764   MHD_run (hd->daemon);
1765   schedule_httpd (hd);
1766 }
1767
1768
1769 /**
1770  * Run MHD now, we have extra data ready for the callback.
1771  *
1772  * @param hd the daemon to run now.
1773  */
1774 static void
1775 run_mhd_now (struct MhdHttpList *hd)
1776 {
1777   if (GNUNET_SCHEDULER_NO_TASK != 
1778       hd->httpd_task)
1779     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1780   hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd, 
1781                                              hd);
1782 }
1783
1784
1785 /**
1786  * Read file in filename
1787  *
1788  * @param filename file to read
1789  * @param size pointer where filesize is stored
1790  * @return NULL on error
1791  */
1792 static void*
1793 load_file (const char* filename, 
1794            unsigned int* size)
1795 {
1796   void *buffer;
1797   uint64_t fsize;
1798
1799   if (GNUNET_OK !=
1800       GNUNET_DISK_file_size (filename, &fsize,
1801                              GNUNET_YES, GNUNET_YES))
1802     return NULL;
1803   if (fsize > MAX_PEM_SIZE)
1804     return NULL;
1805   *size = (unsigned int) fsize;
1806   buffer = GNUNET_malloc (*size);
1807   if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
1808   {
1809     GNUNET_free (buffer);
1810     return NULL;
1811   }
1812   return buffer;
1813 }
1814
1815
1816 /**
1817  * Load PEM key from file
1818  *
1819  * @param key where to store the data
1820  * @param keyfile path to the PEM file
1821  * @return #GNUNET_OK on success
1822  */
1823 static int
1824 load_key_from_file (gnutls_x509_privkey_t key, 
1825                     const char* keyfile)
1826 {
1827   gnutls_datum_t key_data;
1828   int ret;
1829
1830   key_data.data = load_file (keyfile, &key_data.size);
1831   ret = gnutls_x509_privkey_import (key, &key_data,
1832                                     GNUTLS_X509_FMT_PEM);
1833   if (GNUTLS_E_SUCCESS != ret)
1834   {
1835     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1836                 _("Unable to import private key from file `%s'\n"),
1837                 keyfile);
1838   }
1839   GNUNET_free_non_null (key_data.data);
1840   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
1841 }
1842
1843
1844 /**
1845  * Load cert from file
1846  *
1847  * @param crt struct to store data in
1848  * @param certfile path to pem file
1849  * @return #GNUNET_OK on success
1850  */
1851 static int
1852 load_cert_from_file (gnutls_x509_crt_t crt, 
1853                      const char* certfile)
1854 {
1855   gnutls_datum_t cert_data;
1856   int ret;
1857
1858   cert_data.data = load_file (certfile, &cert_data.size);
1859   ret = gnutls_x509_crt_import (crt, &cert_data,
1860                                 GNUTLS_X509_FMT_PEM);
1861   if (GNUTLS_E_SUCCESS != ret)
1862   {
1863     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1864                _("Unable to import certificate %s\n"), certfile);
1865   }
1866   GNUNET_free_non_null (cert_data.data);
1867   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
1868 }
1869
1870
1871 /**
1872  * Generate new certificate for specific name
1873  *
1874  * @param name the subject name to generate a cert for
1875  * @return a struct holding the PEM data, NULL on error
1876  */
1877 static struct ProxyGNSCertificate *
1878 generate_gns_certificate (const char *name)
1879 {
1880   unsigned int serial;
1881   size_t key_buf_size;
1882   size_t cert_buf_size;
1883   gnutls_x509_crt_t request;
1884   time_t etime;
1885   struct tm *tm_data;
1886   struct ProxyGNSCertificate *pgc;
1887
1888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1889               "Generating TLS/SSL certificate for `%s'\n", 
1890               name);
1891   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
1892   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
1893   pgc = GNUNET_new (struct ProxyGNSCertificate);
1894   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
1895                                  0, "TNR", 2);
1896   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
1897                                  0, "GNU Name System", 4);
1898   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
1899                                  0, name, strlen (name));
1900   GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
1901   gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
1902   gnutls_x509_crt_set_serial (request,
1903                               &serial,
1904                               sizeof (serial));
1905   etime = time (NULL);
1906   tm_data = localtime (&etime);  
1907   gnutls_x509_crt_set_activation_time (request,
1908                                        etime);
1909   tm_data->tm_year++;
1910   etime = mktime (tm_data);
1911   gnutls_x509_crt_set_expiration_time (request,
1912                                        etime);
1913   gnutls_x509_crt_sign (request, 
1914                         proxy_ca.cert, 
1915                         proxy_ca.key);
1916   key_buf_size = sizeof (pgc->key);
1917   cert_buf_size = sizeof (pgc->cert);
1918   gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
1919                           pgc->cert, &cert_buf_size);
1920   gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
1921                               pgc->key, &key_buf_size);
1922   gnutls_x509_crt_deinit (request);
1923   return pgc;
1924 }
1925
1926
1927 /**
1928  * Lookup (or create) an SSL MHD instance for a particular domain.
1929  *
1930  * @param domain the domain the SSL daemon has to serve
1931  * @return NULL on errro
1932  */
1933 static struct MhdHttpList *
1934 lookup_ssl_httpd (const char* domain)
1935 {
1936   struct MhdHttpList *hd;
1937   struct ProxyGNSCertificate *pgc;
1938
1939   for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
1940     if ( (NULL != hd->domain) &&
1941          (0 == strcmp (hd->domain, domain)) )
1942       return hd;
1943   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1944               "Starting fresh MHD HTTPS instance for domain `%s'\n",
1945               domain);
1946   pgc = generate_gns_certificate (domain);   
1947   hd = GNUNET_new (struct MhdHttpList);
1948   hd->is_ssl = GNUNET_YES;
1949   hd->domain = GNUNET_strdup (domain); 
1950   hd->proxy_cert = pgc;
1951   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
1952                                  0,
1953                                  NULL, NULL,
1954                                  &create_response, hd,
1955                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
1956                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
1957                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
1958                                  MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
1959                                  MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
1960                                  MHD_OPTION_END);
1961   if (NULL == hd->daemon)
1962   {
1963     GNUNET_free (pgc);
1964     GNUNET_free (hd);
1965     return NULL;
1966   }
1967   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, 
1968                                mhd_httpd_tail, 
1969                                hd);
1970   return hd;
1971 }
1972
1973
1974 /**
1975  * Task run when a Socks5Request somehow fails to be associated with
1976  * an MHD connection (i.e. because the client never speaks HTTP after
1977  * the SOCKS5 handshake).  Clean up.
1978  *
1979  * @param cls the `struct Socks5Request *`
1980  * @param tc sched context
1981  */
1982 static void
1983 timeout_s5r_handshake (void *cls,
1984                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1985 {
1986   struct Socks5Request *s5r = cls;
1987
1988   s5r->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1989   cleanup_s5r (s5r);
1990 }
1991
1992
1993 /**
1994  * We're done with the Socks5 protocol, now we need to pass the
1995  * connection data through to the final destination, either 
1996  * direct (if the protocol might not be HTTP), or via MHD
1997  * (if the port looks like it should be HTTP).
1998  *
1999  * @param s5r socks request that has reached the final stage
2000  */
2001 static void
2002 setup_data_transfer (struct Socks5Request *s5r)
2003 {
2004   struct MhdHttpList *hd;
2005   int fd;
2006   const struct sockaddr *addr;
2007   socklen_t len;
2008
2009   switch (s5r->port)
2010   {
2011   case HTTPS_PORT:
2012     hd = lookup_ssl_httpd (s5r->domain);
2013     if (NULL == hd)
2014     {
2015       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2016                   _("Failed to start HTTPS server for `%s'\n"),
2017                   s5r->domain);
2018       cleanup_s5r (s5r);
2019       return;
2020     }
2021     break;
2022   case HTTP_PORT:
2023   default:
2024     GNUNET_assert (NULL != httpd);
2025     hd = httpd;
2026     break;
2027   }
2028   fd = GNUNET_NETWORK_get_fd (s5r->sock);
2029   addr = GNUNET_NETWORK_get_addr (s5r->sock);
2030   len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2031   s5r->state = SOCKS5_SOCKET_WITH_MHD;
2032   if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
2033   {
2034     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2035                 _("Failed to pass client to MHD\n"));
2036     cleanup_s5r (s5r);
2037     return;
2038   }
2039   s5r->hd = hd;
2040   schedule_httpd (hd);
2041   s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2042                                                     &timeout_s5r_handshake,
2043                                                     s5r);
2044 }
2045
2046
2047 /* ********************* SOCKS handling ************************* */
2048
2049
2050 /**
2051  * Write data from buffer to socks5 client, then continue with state machine.
2052  *
2053  * @param cls the closure with the `struct Socks5Request`
2054  * @param tc scheduler context
2055  */
2056 static void
2057 do_write (void *cls,
2058           const struct GNUNET_SCHEDULER_TaskContext *tc)
2059 {
2060   struct Socks5Request *s5r = cls;
2061   ssize_t len;
2062
2063   s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
2064   len = GNUNET_NETWORK_socket_send (s5r->sock,
2065                                     s5r->wbuf,
2066                                     s5r->wbuf_len);
2067   if (len <= 0)
2068   {
2069     /* write error: connection closed, shutdown, etc.; just clean up */
2070     cleanup_s5r (s5r); 
2071     return;
2072   }
2073   memmove (s5r->wbuf,
2074            &s5r->wbuf[len],
2075            s5r->wbuf_len - len);
2076   s5r->wbuf_len -= len;
2077   if (s5r->wbuf_len > 0)
2078   {
2079     /* not done writing */
2080     s5r->wtask =
2081       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2082                                       s5r->sock,
2083                                       &do_write, s5r);
2084     return;
2085   }
2086
2087   /* we're done writing, continue with state machine! */
2088
2089   switch (s5r->state)
2090   {
2091   case SOCKS5_INIT:    
2092     GNUNET_assert (0);
2093     break;
2094   case SOCKS5_REQUEST:    
2095     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s5r->rtask);
2096     break;
2097   case SOCKS5_DATA_TRANSFER:
2098     setup_data_transfer (s5r);
2099     return;
2100   case SOCKS5_WRITE_THEN_CLEANUP:
2101     cleanup_s5r (s5r);
2102     return;
2103   default:
2104     GNUNET_break (0);
2105     break;
2106   }
2107 }
2108
2109
2110 /**
2111  * Return a server response message indicating a failure to the client.
2112  *
2113  * @param s5r request to return failure code for
2114  * @param sc status code to return
2115  */
2116 static void
2117 signal_socks_failure (struct Socks5Request *s5r,
2118                       enum Socks5StatusCode sc)
2119 {
2120   struct Socks5ServerResponseMessage *s_resp;
2121
2122   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2123   memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2124   s_resp->version = SOCKS_VERSION_5;
2125   s_resp->reply = sc;
2126   s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2127   if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
2128     s5r->wtask = 
2129       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2130                                       s5r->sock,
2131                                       &do_write, s5r);
2132 }
2133
2134
2135 /**
2136  * Return a server response message indicating success.
2137  *
2138  * @param s5r request to return success status message for
2139  */
2140 static void
2141 signal_socks_success (struct Socks5Request *s5r)
2142 {
2143   struct Socks5ServerResponseMessage *s_resp;
2144
2145   s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2146   s_resp->version = SOCKS_VERSION_5;
2147   s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2148   s_resp->reserved = 0;
2149   s_resp->addr_type = SOCKS5_AT_IPV4;
2150   /* zero out IPv4 address and port */
2151   memset (&s_resp[1], 
2152           0, 
2153           sizeof (struct in_addr) + sizeof (uint16_t));
2154   s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2155     sizeof (struct in_addr) + sizeof (uint16_t);  
2156   if (GNUNET_SCHEDULER_NO_TASK == s5r->wtask)      
2157     s5r->wtask =
2158       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2159                                       s5r->sock,
2160                                       &do_write, s5r); 
2161 }
2162
2163
2164 /**
2165  * Process GNS results for target domain.
2166  *
2167  * @param cls the `struct Socks5Request`
2168  * @param rd_count number of records returned
2169  * @param rd record data
2170  */
2171 static void
2172 handle_gns_result (void *cls,
2173                    uint32_t rd_count,
2174                    const struct GNUNET_NAMESTORE_RecordData *rd)
2175 {
2176   struct Socks5Request *s5r = cls;
2177   uint32_t i;
2178   const struct GNUNET_NAMESTORE_RecordData *r;
2179   int got_ip;
2180
2181   s5r->gns_lookup = NULL;
2182   got_ip = GNUNET_NO;
2183   for (i=0;i<rd_count;i++)
2184   {
2185     r = &rd[i];
2186     switch (r->record_type)
2187     {
2188     case GNUNET_DNSPARSER_TYPE_A:
2189       {
2190         struct sockaddr_in *in;
2191
2192         if (sizeof (struct in_addr) != r->data_size)
2193         {
2194           GNUNET_break_op (0);
2195           break;
2196         }
2197         if (GNUNET_YES == got_ip)
2198           break;
2199         if (GNUNET_OK != 
2200             GNUNET_NETWORK_test_pf (PF_INET))
2201           break;
2202         got_ip = GNUNET_YES;
2203         in = (struct sockaddr_in *) &s5r->destination_address;
2204         in->sin_family = AF_INET;
2205         memcpy (&in->sin_addr,
2206                 r->data,
2207                 r->data_size);
2208         in->sin_port = htons (s5r->port);
2209 #if HAVE_SOCKADDR_IN_SIN_LEN
2210         in->sin_len = sizeof (*in);
2211 #endif
2212       }
2213       break;
2214     case GNUNET_DNSPARSER_TYPE_AAAA: 
2215       {
2216         struct sockaddr_in6 *in;
2217
2218         if (sizeof (struct in6_addr) != r->data_size)
2219         {
2220           GNUNET_break_op (0);
2221           break;
2222         }
2223         if (GNUNET_YES == got_ip)
2224           break; 
2225         if (GNUNET_OK != 
2226             GNUNET_NETWORK_test_pf (PF_INET))
2227           break;
2228         /* FIXME: allow user to disable IPv6 per configuration option... */
2229         got_ip = GNUNET_YES;
2230         in = (struct sockaddr_in6 *) &s5r->destination_address;
2231         in->sin6_family = AF_INET6;
2232         memcpy (&in->sin6_addr,
2233                 r->data,
2234                 r->data_size);
2235         in->sin6_port = htons (s5r->port);
2236 #if HAVE_SOCKADDR_IN_SIN_LEN
2237         in->sin6_len = sizeof (*in);
2238 #endif
2239       }
2240       break;      
2241     case GNUNET_NAMESTORE_TYPE_VPN:
2242       GNUNET_break (0); /* should have been translated within GNS */
2243       break;
2244     case GNUNET_NAMESTORE_TYPE_LEHO:
2245       GNUNET_free_non_null (s5r->leho);
2246       s5r->leho = GNUNET_strndup (r->data,
2247                                   r->data_size);
2248       break;
2249     default:
2250       /* don't care */
2251       break;
2252     }
2253   }
2254   if (GNUNET_YES != got_ip)
2255   {
2256     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2257                 "Name resolution failed to yield useful IP address.\n");
2258     signal_socks_failure (s5r,
2259                           SOCKS5_STATUS_GENERAL_FAILURE);
2260     return;
2261   }
2262   s5r->state = SOCKS5_DATA_TRANSFER;
2263   signal_socks_success (s5r);  
2264 }
2265
2266
2267 /**
2268  * Remove the first @a len bytes from the beginning of the read buffer.
2269  *
2270  * @param s5r the handle clear the read buffer for
2271  * @param len number of bytes in read buffer to advance
2272  */
2273 static void
2274 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2275                      size_t len)
2276 {
2277   GNUNET_assert (len <= s5r->rbuf_len);
2278   memmove (s5r->rbuf,
2279            &s5r->rbuf[len],
2280            s5r->rbuf_len - len);
2281   s5r->rbuf_len -= len;
2282 }
2283
2284
2285 /**
2286  * Read data from incoming Socks5 connection
2287  *
2288  * @param cls the closure with the `struct Socks5Request`
2289  * @param tc the scheduler context
2290  */
2291 static void
2292 do_s5r_read (void *cls,
2293              const struct GNUNET_SCHEDULER_TaskContext *tc)
2294 {
2295   struct Socks5Request *s5r = cls;
2296   const struct Socks5ClientHelloMessage *c_hello;
2297   struct Socks5ServerHelloMessage *s_hello;
2298   const struct Socks5ClientRequestMessage *c_req;
2299   ssize_t rlen;
2300   size_t alen;
2301
2302   s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2303   if ( (NULL != tc->read_ready) &&
2304        (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2305   {
2306     rlen = GNUNET_NETWORK_socket_recv (s5r->sock, 
2307                                        &s5r->rbuf[s5r->rbuf_len],
2308                                        sizeof (s5r->rbuf) - s5r->rbuf_len);
2309     if (rlen <= 0)
2310     {
2311       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2312                   "socks5 client disconnected.\n");
2313       cleanup_s5r (s5r);
2314       return;
2315     }
2316     s5r->rbuf_len += rlen;
2317   }
2318   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2319                                               s5r->sock,
2320                                               &do_s5r_read, s5r);
2321   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322               "Processing %u bytes of socks data in state %d\n",
2323               s5r->rbuf_len,
2324               s5r->state);
2325   switch (s5r->state)
2326   {
2327   case SOCKS5_INIT:
2328     c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2329     if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2330          (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2331       return; /* need more data */
2332     if (SOCKS_VERSION_5 != c_hello->version)
2333     {
2334       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2335                   _("Unsupported socks version %d\n"),
2336                   (int) c_hello->version);
2337       cleanup_s5r (s5r);
2338       return;
2339     }
2340     clear_from_s5r_rbuf (s5r,
2341                          sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2342     GNUNET_assert (0 == s5r->wbuf_len);
2343     s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2344     s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2345     s_hello->version = SOCKS_VERSION_5;
2346     s_hello->auth_method = SOCKS_AUTH_NONE;
2347     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s5r->wtask);
2348     s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2349                                                  s5r->sock,
2350                                                  &do_write, s5r);
2351     s5r->state = SOCKS5_REQUEST;
2352     return;
2353   case SOCKS5_REQUEST:
2354     c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2355     if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2356       return;
2357     switch (c_req->command)
2358     {
2359     case SOCKS5_CMD_TCP_STREAM:
2360       /* handled below */
2361       break;
2362     default:
2363       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2364                   _("Unsupported socks command %d\n"),
2365                   (int) c_req->command);
2366       signal_socks_failure (s5r,
2367                             SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2368       return;
2369     }
2370     switch (c_req->addr_type)
2371     {
2372     case SOCKS5_AT_IPV4:
2373       {
2374         const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2375         const uint16_t *port = (const uint16_t *) &v4[1];
2376         struct sockaddr_in *in;
2377
2378         s5r->port = ntohs (*port);
2379         alen = sizeof (struct in_addr);
2380         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2381             alen + sizeof (uint16_t))
2382           return; /* need more data */
2383         in = (struct sockaddr_in *) &s5r->destination_address;
2384         in->sin_family = AF_INET;
2385         in->sin_addr = *v4;
2386         in->sin_port = *port;
2387 #if HAVE_SOCKADDR_IN_SIN_LEN
2388         in->sin_len = sizeof (*in);
2389 #endif
2390         s5r->state = SOCKS5_DATA_TRANSFER;
2391       }
2392       break;
2393     case SOCKS5_AT_IPV6:
2394       {
2395         const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2396         const uint16_t *port = (const uint16_t *) &v6[1];
2397         struct sockaddr_in6 *in;
2398
2399         s5r->port = ntohs (*port);
2400         alen = sizeof (struct in6_addr);
2401         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2402             alen + sizeof (uint16_t))
2403           return; /* need more data */
2404         in = (struct sockaddr_in6 *) &s5r->destination_address;
2405         in->sin6_family = AF_INET6;
2406         in->sin6_addr = *v6;
2407         in->sin6_port = *port;
2408 #if HAVE_SOCKADDR_IN_SIN_LEN
2409         in->sin6_len = sizeof (*in);
2410 #endif
2411         s5r->state = SOCKS5_DATA_TRANSFER;
2412       }
2413       break;
2414     case SOCKS5_AT_DOMAINNAME:
2415       {
2416         const uint8_t *dom_len;
2417         const char *dom_name;
2418         const uint16_t *port;   
2419         
2420         dom_len = (const uint8_t *) &c_req[1];
2421         alen = *dom_len + 1;
2422         if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2423             alen + sizeof (uint16_t))
2424           return; /* need more data */
2425         dom_name = (const char *) &dom_len[1];
2426         port = (const uint16_t*) &dom_name[*dom_len];
2427         s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2428         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2429                     "Requested connection is to %s:%d\n",
2430                     s5r->domain,
2431                     ntohs (*port));
2432         s5r->state = SOCKS5_RESOLVING;
2433         s5r->port = ntohs (*port);
2434         s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2435                                              s5r->domain,
2436                                              &local_gns_zone,
2437                                              GNUNET_DNSPARSER_TYPE_A,
2438                                              GNUNET_NO /* only cached */,
2439                                              (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2440                                              &handle_gns_result,
2441                                              s5r);                                           
2442         break;
2443       }
2444     default:
2445       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2446                   _("Unsupported socks address type %d\n"),
2447                   (int) c_req->addr_type);
2448       signal_socks_failure (s5r,
2449                             SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2450       return;
2451     }
2452     clear_from_s5r_rbuf (s5r,
2453                          sizeof (struct Socks5ClientRequestMessage) +
2454                          alen + sizeof (uint16_t));
2455     if (0 != s5r->rbuf_len)
2456     {
2457       /* read more bytes than healthy, why did the client send more!? */
2458       GNUNET_break_op (0);
2459       signal_socks_failure (s5r,
2460                             SOCKS5_STATUS_GENERAL_FAILURE);
2461       return;       
2462     }
2463     if (SOCKS5_DATA_TRANSFER == s5r->state)
2464     {
2465       /* if we are not waiting for GNS resolution, signal success */
2466       signal_socks_success (s5r);
2467     }
2468     /* We are done reading right now */
2469     GNUNET_SCHEDULER_cancel (s5r->rtask);
2470     s5r->rtask = GNUNET_SCHEDULER_NO_TASK;    
2471     return;
2472   case SOCKS5_RESOLVING:
2473     GNUNET_assert (0);
2474     return;
2475   case SOCKS5_DATA_TRANSFER:
2476     GNUNET_assert (0);
2477     return;
2478   default:
2479     GNUNET_assert (0);
2480     return;
2481   }
2482 }
2483
2484
2485 /**
2486  * Accept new incoming connections
2487  *
2488  * @param cls the closure
2489  * @param tc the scheduler context
2490  */
2491 static void
2492 do_accept (void *cls, 
2493            const struct GNUNET_SCHEDULER_TaskContext *tc)
2494 {
2495   struct GNUNET_NETWORK_Handle *s;
2496   struct Socks5Request *s5r;
2497
2498   ltask = GNUNET_SCHEDULER_NO_TASK;
2499   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2500     return;
2501   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2502                                          lsock,
2503                                          &do_accept, NULL);
2504   s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2505   if (NULL == s)
2506   {
2507     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2508     return;
2509   }
2510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2511               "Got an inbound connection, waiting for data\n");
2512   s5r = GNUNET_new (struct Socks5Request);
2513   GNUNET_CONTAINER_DLL_insert (s5r_head,
2514                                s5r_tail,
2515                                s5r);
2516   s5r->sock = s;
2517   s5r->state = SOCKS5_INIT;
2518   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2519                                               s5r->sock,
2520                                               &do_s5r_read, s5r);
2521 }
2522
2523
2524 /* ******************* General / main code ********************* */
2525
2526
2527 /**
2528  * Task run on shutdown
2529  *
2530  * @param cls closure
2531  * @param tc task context
2532  */
2533 static void
2534 do_shutdown (void *cls,
2535              const struct GNUNET_SCHEDULER_TaskContext *tc)
2536 {
2537   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2538               "Shutting down...\n");
2539   while (NULL != mhd_httpd_head)
2540     kill_httpd (mhd_httpd_head);
2541   while (NULL != s5r_head)
2542     cleanup_s5r (s5r_head);
2543   if (NULL != lsock)
2544   {
2545     GNUNET_NETWORK_socket_close (lsock);
2546     lsock = NULL;
2547   }
2548   if (NULL != id_op)
2549   {
2550     GNUNET_IDENTITY_cancel (id_op);
2551     id_op = NULL;
2552   }
2553   if (NULL != identity)
2554   {
2555     GNUNET_IDENTITY_disconnect (identity);
2556     identity = NULL;
2557   }
2558   if (NULL != curl_multi)
2559   {
2560     curl_multi_cleanup (curl_multi);
2561     curl_multi = NULL;
2562   }
2563   if (NULL != gns_handle)
2564   {
2565     GNUNET_GNS_disconnect (gns_handle);
2566     gns_handle = NULL;
2567   }
2568   if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
2569   {
2570     GNUNET_SCHEDULER_cancel (curl_download_task);
2571     curl_download_task = GNUNET_SCHEDULER_NO_TASK;
2572   }
2573   if (GNUNET_SCHEDULER_NO_TASK != ltask)
2574   {
2575     GNUNET_SCHEDULER_cancel (ltask);
2576     ltask = GNUNET_SCHEDULER_NO_TASK;
2577   }
2578   gnutls_x509_crt_deinit (proxy_ca.cert);
2579   gnutls_x509_privkey_deinit (proxy_ca.key);
2580   gnutls_global_deinit ();
2581 }
2582
2583
2584 /**
2585  * Continue initialization after we have our zone information.
2586  */
2587 static void 
2588 run_cont () 
2589 {
2590   struct MhdHttpList *hd;
2591   struct sockaddr_in sa;
2592
2593   /* Open listen socket for socks proxy */
2594   /* FIXME: support IPv6! */
2595   memset (&sa, 0, sizeof (sa));
2596   sa.sin_family = AF_INET;
2597   sa.sin_port = htons (port);
2598 #if HAVE_SOCKADDR_IN_SIN_LEN
2599   sa.sin_len = sizeof (sa);
2600 #endif
2601   lsock = GNUNET_NETWORK_socket_create (AF_INET,
2602                                         SOCK_STREAM,
2603                                         0);
2604   if (NULL == lsock) 
2605   {
2606     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2607     GNUNET_SCHEDULER_shutdown ();
2608     return;
2609   }
2610   if (GNUNET_OK !=
2611       GNUNET_NETWORK_socket_bind (lsock, (const struct sockaddr *) &sa,
2612                                   sizeof (sa), 0))
2613   {
2614     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2615     GNUNET_SCHEDULER_shutdown ();
2616     return;
2617   }
2618   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock, 5))
2619   {
2620     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2621     return;
2622   }
2623   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2624                                          lsock, &do_accept, NULL);
2625
2626   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
2627   {
2628     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2629                 "cURL global init failed!\n");
2630     GNUNET_SCHEDULER_shutdown ();
2631     return;
2632   }
2633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2634               "Proxy listens on port %u\n",
2635               port);
2636
2637   /* start MHD daemon for HTTP */
2638   hd = GNUNET_new (struct MhdHttpList);
2639   hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
2640                                  0,
2641                                  NULL, NULL,
2642                                  &create_response, hd,
2643                                  MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2644                                  MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2645                                  MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2646                                  MHD_OPTION_END);
2647   if (NULL == hd->daemon)
2648   {
2649     GNUNET_free (hd);
2650     GNUNET_SCHEDULER_shutdown ();
2651     return;
2652   }
2653   httpd = hd;
2654   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2655 }
2656
2657
2658 /** 
2659  * Method called to inform about the egos of the shorten zone of this peer.
2660  *
2661  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2662  * this function is only called ONCE, and 'NULL' being passed in
2663  * @a ego does indicate an error (i.e. name is taken or no default
2664  * value is known).  If @a ego is non-NULL and if '*ctx'
2665  * is set in those callbacks, the value WILL be passed to a subsequent
2666  * call to the identity callback of #GNUNET_IDENTITY_connect (if 
2667  * that one was not NULL).
2668  *
2669  * @param cls closure, NULL
2670  * @param ego ego handle
2671  * @param ctx context for application to store data for this ego
2672  *                 (during the lifetime of this process, initially NULL)
2673  * @param name name assigned by the user for this ego,
2674  *                   NULL if the user just deleted the ego and it
2675  *                   must thus no longer be used
2676  */
2677 static void
2678 identity_shorten_cb (void *cls,
2679                      struct GNUNET_IDENTITY_Ego *ego,
2680                      void **ctx,
2681                      const char *name)
2682 {
2683   id_op = NULL;
2684   if (NULL == ego)
2685   {
2686     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2687                 _("No ego configured for `shorten-zone`\n"));
2688   }
2689   else
2690   {
2691     local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
2692     do_shorten = GNUNET_YES;
2693   }
2694   run_cont ();
2695 }
2696
2697
2698 /** 
2699  * Method called to inform about the egos of the master zone of this peer.
2700  *
2701  * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2702  * this function is only called ONCE, and 'NULL' being passed in
2703  * @a ego does indicate an error (i.e. name is taken or no default
2704  * value is known).  If @a ego is non-NULL and if '*ctx'
2705  * is set in those callbacks, the value WILL be passed to a subsequent
2706  * call to the identity callback of #GNUNET_IDENTITY_connect (if 
2707  * that one was not NULL).
2708  *
2709  * @param cls closure, NULL
2710  * @param ego ego handle
2711  * @param ctx context for application to store data for this ego
2712  *                 (during the lifetime of this process, initially NULL)
2713  * @param name name assigned by the user for this ego,
2714  *                   NULL if the user just deleted the ego and it
2715  *                   must thus no longer be used
2716  */
2717 static void
2718 identity_master_cb (void *cls,
2719                     struct GNUNET_IDENTITY_Ego *ego,
2720                     void **ctx,
2721                     const char *name)
2722 {
2723   id_op = NULL;
2724   if (NULL == ego)
2725   {
2726     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2727                 _("No ego configured for `%s`\n"),
2728                 "gns-proxy");
2729     GNUNET_SCHEDULER_shutdown ();
2730     return;
2731   }
2732   GNUNET_IDENTITY_ego_get_public_key (ego,
2733                                       &local_gns_zone);
2734   id_op = GNUNET_IDENTITY_get (identity,
2735                                "gns-short",
2736                                &identity_shorten_cb,
2737                                NULL);
2738 }
2739
2740
2741 /**
2742  * Main function that will be run
2743  *
2744  * @param cls closure
2745  * @param args remaining command-line arguments
2746  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2747  * @param c configuration
2748  */
2749 static void
2750 run (void *cls, char *const *args, const char *cfgfile,
2751      const struct GNUNET_CONFIGURATION_Handle *c)
2752 {
2753   char* cafile_cfg = NULL;
2754   char* cafile;
2755
2756   cfg = c;
2757   if (NULL == (curl_multi = curl_multi_init ()))
2758   {
2759     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2760                 "Failed to create cURL multi handle!\n");
2761     return;
2762   } 
2763   cafile = cafile_opt;
2764   if (NULL == cafile)
2765   {
2766     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
2767                                                               "PROXY_CACERT",
2768                                                               &cafile_cfg))
2769     {
2770       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2771                                  "gns-proxy",
2772                                  "PROXY_CACERT");
2773       return;
2774     }
2775     cafile = cafile_cfg;
2776   }
2777   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2778               "Using %s as CA\n", cafile);
2779   
2780   gnutls_global_init ();
2781   gnutls_x509_crt_init (&proxy_ca.cert);
2782   gnutls_x509_privkey_init (&proxy_ca.key);
2783   
2784   if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
2785        (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
2786   {
2787     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2788                 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
2789                 cafile);
2790     gnutls_x509_crt_deinit (proxy_ca.cert);
2791     gnutls_x509_privkey_deinit (proxy_ca.key);
2792     gnutls_global_deinit ();
2793     GNUNET_free_non_null (cafile_cfg);  
2794     return;
2795   }
2796   GNUNET_free_non_null (cafile_cfg);
2797   if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
2798   {
2799     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2800                 "Unable to connect to GNS!\n");
2801     gnutls_x509_crt_deinit (proxy_ca.cert);
2802     gnutls_x509_privkey_deinit (proxy_ca.key);
2803     gnutls_global_deinit ();
2804     return;
2805   }
2806   identity = GNUNET_IDENTITY_connect (cfg,
2807                                       NULL, NULL);  
2808   id_op = GNUNET_IDENTITY_get (identity,
2809                                "gns-proxy",
2810                                &identity_master_cb,
2811                                NULL);  
2812   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2813                                 &do_shutdown, NULL);
2814 }
2815
2816
2817 /**
2818  * The main function for gnunet-gns-proxy.
2819  *
2820  * @param argc number of arguments from the command line
2821  * @param argv command line arguments
2822  * @return 0 ok, 1 on error
2823  */
2824 int
2825 main (int argc, char *const *argv)
2826 {
2827   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2828     {'p', "port", NULL,
2829      gettext_noop ("listen on specified port (default: 7777)"), 1,
2830      &GNUNET_GETOPT_set_ulong, &port},
2831     {'a', "authority", NULL,
2832       gettext_noop ("pem file to use as CA"), 1,
2833       &GNUNET_GETOPT_set_string, &cafile_opt},
2834     GNUNET_GETOPT_OPTION_END
2835   };
2836   static const char* page = 
2837     "<html><head><title>gnunet-gns-proxy</title>"
2838     "</head><body>cURL fail</body></html>";
2839   int ret;
2840
2841   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
2842     return 2;
2843   GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
2844   curl_failure_response = MHD_create_response_from_buffer (strlen (page),
2845                                                            (void*)page,
2846                                                            MHD_RESPMEM_PERSISTENT);
2847
2848   ret =
2849       (GNUNET_OK ==
2850        GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
2851                            _("GNUnet GNS proxy"),
2852                            options,
2853                            &run, NULL)) ? 0 : 1;
2854   MHD_destroy_response (curl_failure_response);
2855   GNUNET_free_non_null ((char *) argv);
2856   return ret;
2857 }
2858
2859 /* end of gnunet-gns-proxy.c */