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