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