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