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