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