2 This file is part of GNUnet.
3 Copyright (C) 2012-2014 GNUnet e.V.
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.
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.
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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
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
28 * - double-check queueing logic
31 #include <microhttpd.h>
33 #include <curl/curl.h>
34 #elif HAVE_GNURL_CURL_H
35 #include <gnurl/curl.h>
37 #include <gnutls/gnutls.h>
38 #include <gnutls/x509.h>
39 #include <gnutls/abstract.h>
40 #include <gnutls/crypto.h>
42 #include <gnutls/dane.h>
45 #include "gnunet_util_lib.h"
46 #include "gnunet_gns_service.h"
47 #include "gnunet_identity_service.h"
52 * Default Socks5 listen port.
54 #define GNUNET_GNS_PROXY_PORT 7777
57 * Maximum supported length for a URI.
58 * Should die. @deprecated
60 #define MAX_HTTP_URI_LENGTH 2048
63 * Size of the buffer for the data upload / download. Must be
64 * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
66 #define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE
69 * Size of the read/write buffers for Socks. Uses
70 * 256 bytes for the hostname (at most), plus a few
71 * bytes overhead for the messages.
73 #define SOCKS_BUFFERSIZE (256 + 32)
76 * Port for plaintext HTTP.
83 #define HTTPS_PORT 443
86 * Largest allowed size for a PEM certificate.
88 #define MAX_PEM_SIZE (10 * 1024)
91 * After how long do we clean up unused MHD TLS instances?
93 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
96 * After how long do we clean up Socks5 handles that failed to show any activity
97 * with their respective MHD instance?
99 #define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
105 * @param level log level
106 * @param fun name of curl_easy-function that gave the error
107 * @param rc return code from curl
109 #define LOG_CURL_EASY(level,fun,rc) GNUNET_log(level, _("%s failed at %s:%d: `%s'\n"), fun, __FILE__, __LINE__, curl_easy_strerror (rc))
112 /* *************** Socks protocol definitions (move to TUN?) ****************** */
115 * Which SOCKS version do we speak?
117 #define SOCKS_VERSION_5 0x05
120 * Flag to set for 'no authentication'.
122 #define SOCKS_AUTH_NONE 0
126 * Commands in Socks5.
131 * Establish TCP/IP stream.
133 SOCKS5_CMD_TCP_STREAM = 1,
136 * Establish TCP port binding.
138 SOCKS5_CMD_TCP_PORT = 2,
141 * Establish UDP port binding.
143 SOCKS5_CMD_UDP_PORT = 3
148 * Address types in Socks5.
150 enum Socks5AddressType
160 SOCKS5_AT_DOMAINNAME = 3,
171 * Status codes in Socks5 response.
173 enum Socks5StatusCode
175 SOCKS5_STATUS_REQUEST_GRANTED = 0,
176 SOCKS5_STATUS_GENERAL_FAILURE = 1,
177 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
178 SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
179 SOCKS5_STATUS_HOST_UNREACHABLE = 4,
180 SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
181 SOCKS5_STATUS_TTL_EXPIRED = 6,
182 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
183 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
188 * Client hello in Socks5 protocol.
190 struct Socks5ClientHelloMessage
193 * Should be #SOCKS_VERSION_5.
198 * How many authentication methods does the client support.
200 uint8_t num_auth_methods;
202 /* followed by supported authentication methods, 1 byte per method */
208 * Server hello in Socks5 protocol.
210 struct Socks5ServerHelloMessage
213 * Should be #SOCKS_VERSION_5.
218 * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
219 * which skips the authentication step.
226 * Client socks request in Socks5 protocol.
228 struct Socks5ClientRequestMessage
231 * Should be #SOCKS_VERSION_5.
236 * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
241 * Reserved, always zero.
246 * Address type, an `enum Socks5AddressType`.
251 * Followed by either an ip4/ipv6 address or a domain name with a
252 * length field (uint8_t) in front (depending on @e addr_type).
253 * followed by port number in network byte order (uint16_t).
259 * Server response to client requests in Socks5 protocol.
261 struct Socks5ServerResponseMessage
264 * Should be #SOCKS_VERSION_5.
269 * Status code, an `enum Socks5StatusCode`
279 * Address type, an `enum Socks5AddressType`.
284 * Followed by either an ip4/ipv6 address or a domain name with a
285 * length field (uint8_t) in front (depending on @e addr_type).
286 * followed by port number in network byte order (uint16_t).
293 /* *********************** Datastructures for HTTP handling ****************** */
296 * A structure for CA cert/key
303 gnutls_x509_crt_t cert;
308 gnutls_x509_privkey_t key;
313 * Structure for GNS certificates
315 struct ProxyGNSCertificate
318 * The certificate as PEM
320 char cert[MAX_PEM_SIZE];
323 * The private key as PEM
325 char key[MAX_PEM_SIZE];
331 * A structure for all running Httpds
338 struct MhdHttpList *prev;
343 struct MhdHttpList *next;
346 * the domain name to server (only important for TLS)
353 struct MHD_Daemon *daemon;
356 * Optional proxy certificate used
358 struct ProxyGNSCertificate *proxy_cert;
363 struct GNUNET_SCHEDULER_Task *httpd_task;
366 * is this an ssl daemon?
373 /* ***************** Datastructures for Socks handling **************** */
382 * We're waiting to get the client hello.
387 * We're waiting to get the initial request.
392 * We are currently resolving the destination.
397 * We're in transfer mode.
399 SOCKS5_DATA_TRANSFER,
402 * Finish writing the write buffer, then clean up.
404 SOCKS5_WRITE_THEN_CLEANUP,
407 * Socket has been passed to MHD, do not close it anymore.
409 SOCKS5_SOCKET_WITH_MHD,
412 * We've started receiving upload data from MHD.
414 SOCKS5_SOCKET_UPLOAD_STARTED,
417 * We've finished receiving upload data from MHD.
419 SOCKS5_SOCKET_UPLOAD_DONE,
422 * We've finished uploading data via CURL and can now download.
424 SOCKS5_SOCKET_DOWNLOAD_STARTED,
427 * We've finished receiving download data from cURL.
429 SOCKS5_SOCKET_DOWNLOAD_DONE
436 struct HttpResponseHeader
441 struct HttpResponseHeader *next;
446 struct HttpResponseHeader *prev;
460 * A structure for socks requests
468 struct Socks5Request *next;
473 struct Socks5Request *prev;
478 struct GNUNET_NETWORK_Handle *sock;
481 * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
483 struct GNUNET_GNS_LookupWithTldRequest *gns_lookup;
486 * Client socket read task
488 struct GNUNET_SCHEDULER_Task *rtask;
491 * Client socket write task
493 struct GNUNET_SCHEDULER_Task *wtask;
498 struct GNUNET_SCHEDULER_Task *timeout_task;
503 char rbuf[SOCKS_BUFFERSIZE];
508 char wbuf[SOCKS_BUFFERSIZE];
511 * Buffer we use for moving data between MHD and curl (in both directions).
513 char io_buf[IO_BUFFERSIZE];
516 * MHD HTTP instance handling this request, NULL for none.
518 struct MhdHttpList *hd;
521 * MHD connection for this request.
523 struct MHD_Connection *con;
526 * MHD response object for this request.
528 struct MHD_Response *response;
531 * the domain name to server (only important for TLS)
536 * DNS Legacy Host Name as given by GNS, NULL if not given.
541 * Payload of the (last) DANE record encountered.
556 * HTTP request headers for the curl request.
558 struct curl_slist *headers;
561 * DNS->IP mappings resolved through GNS
563 struct curl_slist *hosts;
566 * HTTP response code to give to MHD for the response.
568 unsigned int response_code;
571 * Number of bytes in @e dane_data.
573 size_t dane_data_len;
576 * Number of bytes already in read buffer
581 * Number of bytes already in write buffer
586 * Number of bytes already in the IO buffer.
591 * Once known, what's the target address for the connection?
593 struct sockaddr_storage destination_address;
598 enum SocksPhase state;
601 * Desired destination port.
606 * Headers from response
608 struct HttpResponseHeader *header_head;
611 * Headers from response
613 struct HttpResponseHeader *header_tail;
616 * X.509 Certificate status
621 * Was the hostname resolved via GNS?
626 * Did we suspend MHD processing?
633 /* *********************** Globals **************************** */
637 * The port the proxy is running on (default 7777)
639 static unsigned long long port = GNUNET_GNS_PROXY_PORT;
642 * The CA file (pem) to use for the proxy CA
644 static char *cafile_opt;
647 * The listen socket of the proxy for IPv4
649 static struct GNUNET_NETWORK_Handle *lsock4;
652 * The listen socket of the proxy for IPv6
654 static struct GNUNET_NETWORK_Handle *lsock6;
657 * The listen task ID for IPv4
659 static struct GNUNET_SCHEDULER_Task * ltask4;
662 * The listen task ID for IPv6
664 static struct GNUNET_SCHEDULER_Task * ltask6;
667 * The cURL download task (curl multi API).
669 static struct GNUNET_SCHEDULER_Task * curl_download_task;
672 * The cURL multi handle
674 static CURLM *curl_multi;
677 * Handle to the GNS service
679 static struct GNUNET_GNS_Handle *gns_handle;
682 * DLL for http/https daemons
684 static struct MhdHttpList *mhd_httpd_head;
687 * DLL for http/https daemons
689 static struct MhdHttpList *mhd_httpd_tail;
692 * Daemon for HTTP (we have one per X.509 certificate, and then one for
693 * all HTTP connections; this is the one for HTTP, not HTTPS).
695 static struct MhdHttpList *httpd;
698 * DLL of active socks requests.
700 static struct Socks5Request *s5r_head;
703 * DLL of active socks requests.
705 static struct Socks5Request *s5r_tail;
708 * The CA for X.509 certificate generation
710 static struct ProxyCA proxy_ca;
713 * Response we return on cURL failures.
715 static struct MHD_Response *curl_failure_response;
720 static const struct GNUNET_CONFIGURATION_Handle *cfg;
723 /* ************************* Global helpers ********************* */
727 * Run MHD now, we have extra data ready for the callback.
729 * @param hd the daemon to run now.
732 run_mhd_now (struct MhdHttpList *hd);
736 * Clean up s5r handles.
738 * @param s5r the handle to destroy
741 cleanup_s5r (struct Socks5Request *s5r)
743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
744 "Cleaning up socks request\n");
745 if (NULL != s5r->curl)
747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
748 "Cleaning up cURL handle\n");
749 curl_multi_remove_handle (curl_multi,
751 curl_easy_cleanup (s5r->curl);
756 s5r->suspended = GNUNET_NO;
757 MHD_resume_connection (s5r->con);
759 curl_slist_free_all (s5r->headers);
760 if (NULL != s5r->hosts)
762 curl_slist_free_all (s5r->hosts);
764 if ( (NULL != s5r->response) &&
765 (curl_failure_response != s5r->response) )
766 MHD_destroy_response (s5r->response);
767 if (NULL != s5r->rtask)
768 GNUNET_SCHEDULER_cancel (s5r->rtask);
769 if (NULL != s5r->timeout_task)
770 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
771 if (NULL != s5r->wtask)
772 GNUNET_SCHEDULER_cancel (s5r->wtask);
773 if (NULL != s5r->gns_lookup)
774 GNUNET_GNS_lookup_with_tld_cancel (s5r->gns_lookup);
775 if (NULL != s5r->sock)
777 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
778 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
780 GNUNET_NETWORK_socket_close (s5r->sock);
782 GNUNET_CONTAINER_DLL_remove (s5r_head,
785 GNUNET_free_non_null (s5r->domain);
786 GNUNET_free_non_null (s5r->leho);
787 GNUNET_free_non_null (s5r->url);
788 GNUNET_free_non_null (s5r->dane_data);
793 /* ************************* HTTP handling with cURL *********************** */
796 curl_download_prepare ();
800 * Callback for MHD response generation. This function is called from
801 * MHD whenever MHD expects to get data back. Copies data from the
802 * io_buf, if available.
804 * @param cls closure with our `struct Socks5Request`
805 * @param pos in buffer
806 * @param buf where to copy data
807 * @param max available space in @a buf
808 * @return number of bytes written to @a buf
811 mhd_content_cb (void *cls,
816 struct Socks5Request *s5r = cls;
817 size_t bytes_to_copy;
819 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
820 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
822 /* we're still not done with the upload, do not yet
823 start the download, the IO buffer is still full
825 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
826 "Pausing MHD download, not yet ready for download\n");
827 return 0; /* not yet ready for data download */
829 bytes_to_copy = GNUNET_MIN (max,
831 if ( (0 == bytes_to_copy) &&
832 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
834 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
835 "Pausing MHD download, no data available\n");
836 if (NULL != s5r->curl)
838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
839 "Continuing CURL interaction\n");
840 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
841 curl_download_prepare ();
843 if (GNUNET_NO == s5r->suspended)
845 MHD_suspend_connection (s5r->con);
846 s5r->suspended = GNUNET_YES;
848 return 0; /* more data later */
850 if ( (0 == bytes_to_copy) &&
851 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
854 "Completed MHD download\n");
855 return MHD_CONTENT_READER_END_OF_STREAM;
857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
858 "Writing %llu/%llu bytes\n",
859 (unsigned long long) bytes_to_copy,
860 (unsigned long long) s5r->io_len);
864 memmove (s5r->io_buf,
865 &s5r->io_buf[bytes_to_copy],
866 s5r->io_len - bytes_to_copy);
867 s5r->io_len -= bytes_to_copy;
868 if (NULL != s5r->curl)
870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
871 "Continuing CURL interaction\n");
872 curl_easy_pause (s5r->curl,
875 return bytes_to_copy;
880 * Check that the website has presented us with a valid X.509 certificate.
881 * The certificate must either match the domain name or the LEHO name
882 * (or, if available, the TLSA record).
884 * @param s5r request to check for.
885 * @return #GNUNET_OK if the certificate is valid
888 check_ssl_certificate (struct Socks5Request *s5r)
890 unsigned int cert_list_size;
891 const gnutls_datum_t *chainp;
892 const struct curl_tlssessioninfo *tlsinfo;
893 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
895 gnutls_x509_crt_t x509_cert;
899 s5r->ssl_checked = GNUNET_YES;
900 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
901 "Checking X.509 certificate\n");
903 curl_easy_getinfo (s5r->curl,
904 CURLINFO_TLS_SESSION,
905 (struct curl_slist **) &tlsinfo))
906 return GNUNET_SYSERR;
907 if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
909 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
910 _("Unsupported CURL TLS backend %d\n"),
912 return GNUNET_SYSERR;
914 chainp = gnutls_certificate_get_peers (tlsinfo->internals, &cert_list_size);
915 if ( (! chainp) || (0 == cert_list_size) )
916 return GNUNET_SYSERR;
918 size = sizeof (certdn);
919 /* initialize an X.509 certificate structure. */
920 gnutls_x509_crt_init (&x509_cert);
921 gnutls_x509_crt_import (x509_cert,
923 GNUTLS_X509_FMT_DER);
925 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
926 GNUTLS_OID_X520_COMMON_NAME,
927 0, /* the first and only one */
928 0 /* no DER encoding */,
932 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
933 _("Failed to fetch CN from cert: %s\n"),
934 gnutls_strerror(rc));
935 gnutls_x509_crt_deinit (x509_cert);
936 return GNUNET_SYSERR;
938 /* check for TLSA/DANE records */
940 if (NULL != s5r->dane_data)
942 char *dd[] = { s5r->dane_data, NULL };
943 int dlen[] = { s5r->dane_data_len, 0};
944 dane_state_t dane_state;
945 dane_query_t dane_query;
948 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
949 if (0 != (rc = dane_state_init (&dane_state,
950 #ifdef DANE_F_IGNORE_DNSSEC
951 DANE_F_IGNORE_DNSSEC |
953 DANE_F_IGNORE_LOCAL_RESOLVER)))
955 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
956 _("Failed to initialize DANE: %s\n"),
958 gnutls_x509_crt_deinit (x509_cert);
959 return GNUNET_SYSERR;
961 if (0 != (rc = dane_raw_tlsa (dane_state,
968 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
969 _("Failed to parse DANE record: %s\n"),
971 dane_state_deinit (dane_state);
972 gnutls_x509_crt_deinit (x509_cert);
973 return GNUNET_SYSERR;
975 if (0 != (rc = dane_verify_crt_raw (dane_state,
978 gnutls_certificate_type_get (tlsinfo->internals),
983 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
984 _("Failed to verify TLS connection using DANE: %s\n"),
986 dane_query_deinit (dane_query);
987 dane_state_deinit (dane_state);
988 gnutls_x509_crt_deinit (x509_cert);
989 return GNUNET_SYSERR;
993 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
994 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
996 dane_query_deinit (dane_query);
997 dane_state_deinit (dane_state);
998 gnutls_x509_crt_deinit (x509_cert);
999 return GNUNET_SYSERR;
1001 dane_query_deinit (dane_query);
1002 dane_state_deinit (dane_state);
1008 /* try LEHO or ordinary domain name X509 verification */
1010 if (NULL != s5r->leho)
1014 if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
1017 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1018 _("TLS certificate subject name (%s) does not match `%s'\n"),
1021 gnutls_x509_crt_deinit (x509_cert);
1022 return GNUNET_SYSERR;
1027 /* we did not even have the domain name!? */
1029 return GNUNET_SYSERR;
1032 gnutls_x509_crt_deinit (x509_cert);
1038 * We're getting an HTTP response header from cURL. Convert it to the
1039 * MHD response headers. Mostly copies the headers, but makes special
1040 * adjustments to "Set-Cookie" and "Location" headers as those may need
1041 * to be changed from the LEHO to the domain the browser expects.
1043 * @param buffer curl buffer with a single line of header data; not 0-terminated!
1044 * @param size curl blocksize
1045 * @param nmemb curl blocknumber
1046 * @param cls our `struct Socks5Request *`
1047 * @return size of processed bytes
1050 curl_check_hdr (void *buffer,
1055 struct Socks5Request *s5r = cls;
1056 struct HttpResponseHeader *header;
1057 size_t bytes = size * nmemb;
1059 const char *hdr_type;
1060 const char *cookie_domain;
1062 char *new_cookie_hdr;
1065 size_t delta_cdomain;
1069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1070 "Receiving HTTP response header from CURL\n");
1071 /* first, check TLS certificate */
1072 if ( (GNUNET_YES != s5r->ssl_checked) &&
1073 (HTTPS_PORT == s5r->port))
1075 if (GNUNET_OK != check_ssl_certificate (s5r))
1079 ndup = GNUNET_strndup (buffer, bytes);
1080 hdr_type = strtok (ndup, ":");
1081 if (NULL == hdr_type)
1086 hdr_val = strtok (NULL, "");
1087 if (NULL == hdr_val)
1092 if (' ' == *hdr_val)
1095 /* custom logic for certain header types */
1096 new_cookie_hdr = NULL;
1097 if ( (NULL != s5r->leho) &&
1098 (0 == strcasecmp (hdr_type,
1099 MHD_HTTP_HEADER_SET_COOKIE)) )
1102 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1103 strlen (s5r->domain) + 1);
1105 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1106 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1108 if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
1109 (GNUNET_NO == domain_matched) )
1111 domain_matched = GNUNET_YES;
1112 cookie_domain = tok + strlen (" domain") + 1;
1113 if (strlen (cookie_domain) < strlen (s5r->leho))
1115 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1116 if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
1118 offset += sprintf (new_cookie_hdr + offset,
1124 else if (0 == strcmp (cookie_domain, s5r->leho))
1126 offset += sprintf (new_cookie_hdr + offset,
1131 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1132 _("Cookie domain `%s' supplied by server is invalid\n"),
1135 GNUNET_memcpy (new_cookie_hdr + offset, tok, strlen (tok));
1136 offset += strlen (tok);
1137 new_cookie_hdr[offset++] = ';';
1139 hdr_val = new_cookie_hdr;
1142 new_location = NULL;
1143 if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
1147 GNUNET_asprintf (&leho_host,
1148 (HTTPS_PORT != s5r->port)
1152 if (0 == strncmp (leho_host,
1154 strlen (leho_host)))
1156 GNUNET_asprintf (&new_location,
1158 (HTTPS_PORT != s5r->port)
1162 hdr_val + strlen (leho_host));
1163 hdr_val = new_location;
1165 GNUNET_free (leho_host);
1167 /* MHD does not allow certain characters in values, remove those */
1168 if (NULL != (tok = strchr (hdr_val, '\n')))
1170 if (NULL != (tok = strchr (hdr_val, '\r')))
1172 if (NULL != (tok = strchr (hdr_val, '\t')))
1174 if (0 != strlen (hdr_val)) /* Rely in MHD to set those */
1176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1177 "Adding header %s: %s to MHD response\n",
1180 header = GNUNET_new (struct HttpResponseHeader);
1181 header->type = GNUNET_strdup (hdr_type);
1182 header->value = GNUNET_strdup (hdr_val);
1183 GNUNET_CONTAINER_DLL_insert (s5r->header_head,
1188 GNUNET_free_non_null (new_cookie_hdr);
1189 GNUNET_free_non_null (new_location);
1195 * Create an MHD response object in @a s5r matching the
1196 * information we got from curl.
1198 * @param s5r the request for which we convert the response
1199 * @return #GNUNET_OK on success, #GNUNET_SYSERR if response was
1200 * already initialized before
1203 create_mhd_response_from_s5r (struct Socks5Request *s5r)
1206 double content_length;
1208 if (NULL != s5r->response)
1210 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1211 "Response already set!\n");
1212 return GNUNET_SYSERR;
1215 GNUNET_break (CURLE_OK ==
1216 curl_easy_getinfo (s5r->curl,
1217 CURLINFO_RESPONSE_CODE,
1219 GNUNET_break (CURLE_OK ==
1220 curl_easy_getinfo (s5r->curl,
1221 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
1223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1224 "Creating MHD response with code %d and size %d for %s%s\n",
1226 (int) content_length,
1229 s5r->response_code = resp_code;
1230 s5r->response = MHD_create_response_from_callback ((-1 == content_length) ? MHD_SIZE_UNKNOWN : content_length,
1235 for (struct HttpResponseHeader *header = s5r->header_head;
1237 header = header->next)
1239 GNUNET_break (MHD_YES ==
1240 MHD_add_response_header (s5r->response,
1245 if (NULL != s5r->leho)
1249 GNUNET_asprintf (&cors_hdr,
1250 (HTTPS_PORT == s5r->port)
1255 GNUNET_break (MHD_YES ==
1256 MHD_add_response_header (s5r->response,
1257 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1259 GNUNET_free (cors_hdr);
1261 /* force connection to be closed after each request, as we
1262 do not support HTTP pipelining (yet, FIXME!) */
1263 /*GNUNET_break (MHD_YES ==
1264 MHD_add_response_header (s5r->response,
1265 MHD_HTTP_HEADER_CONNECTION,
1267 MHD_resume_connection (s5r->con);
1268 s5r->suspended = GNUNET_NO;
1273 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1274 * it available to MHD.
1276 * @param ptr pointer to the data
1277 * @param size number of blocks of data
1278 * @param nmemb blocksize
1279 * @param ctx our `struct Socks5Request *`
1280 * @return number of bytes handled
1283 curl_download_cb (void *ptr,
1288 struct Socks5Request *s5r = ctx;
1289 size_t total = size * nmemb;
1291 if (NULL == s5r->response)
1292 GNUNET_assert (GNUNET_OK ==
1293 create_mhd_response_from_s5r (s5r));
1295 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1296 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1298 /* we're still not done with the upload, do not yet
1299 start the download, the IO buffer is still full
1300 with upload data. */
1301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1302 "Pausing CURL download `%s%s', waiting for UPLOAD to finish\n",
1305 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1307 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1310 "Pausing CURL `%s%s' download, not enough space %llu %llu %llu\n",
1313 (unsigned long long) sizeof (s5r->io_buf),
1314 (unsigned long long) s5r->io_len,
1315 (unsigned long long) total);
1316 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1318 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1321 s5r->io_len += total;
1322 if (GNUNET_YES == s5r->suspended)
1324 MHD_resume_connection (s5r->con);
1325 s5r->suspended = GNUNET_NO;
1327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328 "Received %llu bytes of payload via cURL from %s\n",
1329 (unsigned long long) total,
1331 if (s5r->io_len == total)
1332 run_mhd_now (s5r->hd);
1338 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1339 * to make it available to MHD.
1341 * @param buf where to write the data
1342 * @param size number of bytes per member
1343 * @param nmemb number of members available in @a buf
1344 * @param cls our `struct Socks5Request` that generated the data
1345 * @return number of bytes copied to @a buf
1348 curl_upload_cb (void *buf,
1353 struct Socks5Request *s5r = cls;
1354 size_t len = size * nmemb;
1357 if ( (0 == s5r->io_len) &&
1358 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1361 "Pausing CURL UPLOAD %s%s, need more data\n",
1364 return CURL_READFUNC_PAUSE;
1366 if ( (0 == s5r->io_len) &&
1367 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1369 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1371 "Completed CURL UPLOAD %s%s\n",
1374 return 0; /* upload finished, can now download */
1376 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
1377 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1380 return CURL_READFUNC_ABORT;
1382 to_copy = GNUNET_MIN (s5r->io_len,
1384 GNUNET_memcpy (buf, s5r->io_buf, to_copy);
1385 memmove (s5r->io_buf,
1386 &s5r->io_buf[to_copy],
1387 s5r->io_len - to_copy);
1388 s5r->io_len -= to_copy;
1389 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1390 run_mhd_now (s5r->hd); /* got more space for upload now */
1395 /* ************************** main loop of cURL interaction ****************** */
1399 * Task that is run when we are ready to receive more data
1402 * @param cls closure
1405 curl_task_download (void *cls);
1409 * Ask cURL for the select() sets and schedule cURL operations.
1412 curl_download_prepare ()
1419 struct GNUNET_NETWORK_FDSet *grs;
1420 struct GNUNET_NETWORK_FDSet *gws;
1422 struct GNUNET_TIME_Relative rtime;
1424 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1425 "Scheduling CURL interaction\n");
1426 if (NULL != curl_download_task)
1428 GNUNET_SCHEDULER_cancel (curl_download_task);
1429 curl_download_task = NULL;
1435 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi,
1441 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1442 "%s failed at %s:%d: `%s'\n",
1443 "curl_multi_fdset", __FILE__, __LINE__,
1444 curl_multi_strerror (mret));
1448 GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
1450 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1452 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1455 grs = GNUNET_NETWORK_fdset_create ();
1456 gws = GNUNET_NETWORK_fdset_create ();
1457 GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1458 GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1459 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1462 &curl_task_download,
1464 GNUNET_NETWORK_fdset_destroy (gws);
1465 GNUNET_NETWORK_fdset_destroy (grs);
1469 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1470 &curl_task_download,
1477 * Task that is run when we are ready to receive more data from curl.
1479 * @param cls closure, NULL
1482 curl_task_download (void *cls)
1486 struct CURLMsg *msg;
1488 struct Socks5Request *s5r;
1490 curl_download_task = NULL;
1491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1492 "Running CURL interaction\n");
1496 mret = curl_multi_perform (curl_multi,
1498 while (NULL != (msg = curl_multi_info_read (curl_multi,
1501 GNUNET_break (CURLE_OK ==
1502 curl_easy_getinfo (msg->easy_handle,
1513 /* documentation says this is not used */
1517 switch (msg->data.result)
1520 case CURLE_GOT_NOTHING:
1521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1522 "CURL download %s%s completed.\n",
1525 if (NULL == s5r->response)
1527 GNUNET_assert (GNUNET_OK ==
1528 create_mhd_response_from_s5r (s5r));
1530 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1531 run_mhd_now (s5r->hd);
1534 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1535 "Download curl %s%s failed: %s\n",
1538 curl_easy_strerror (msg->data.result));
1539 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1540 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1541 run_mhd_now (s5r->hd);
1544 if (NULL == s5r->response)
1545 s5r->response = curl_failure_response;
1548 /* documentation says this is not used */
1552 /* unexpected status code */
1557 } while (mret == CURLM_CALL_MULTI_PERFORM);
1558 if (CURLM_OK != mret)
1559 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1560 "%s failed at %s:%d: `%s'\n",
1561 "curl_multi_perform", __FILE__, __LINE__,
1562 curl_multi_strerror (mret));
1565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1566 "Suspending cURL multi loop, no more events pending\n");
1567 if (NULL != curl_download_task)
1569 GNUNET_SCHEDULER_cancel (curl_download_task);
1570 curl_download_task = NULL;
1572 return; /* nothing more in progress */
1574 curl_download_prepare ();
1578 /* ********************************* MHD response generation ******************* */
1582 * Read HTTP request header field from the request. Copies the fields
1583 * over to the 'headers' that will be given to curl. However, 'Host'
1584 * is substituted with the LEHO if present. We also change the
1585 * 'Connection' header value to "close" as the proxy does not support
1588 * @param cls our `struct Socks5Request`
1589 * @param kind value kind
1590 * @param key field key
1591 * @param value field value
1592 * @return #MHD_YES to continue to iterate
1595 con_val_iter (void *cls,
1596 enum MHD_ValueKind kind,
1600 struct Socks5Request *s5r = cls;
1603 if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1604 (NULL != s5r->leho) )
1606 if (0 == strcasecmp (MHD_HTTP_HEADER_CONTENT_LENGTH, key))
1608 if (0 == strcasecmp (MHD_HTTP_HEADER_ACCEPT_ENCODING, key))
1610 GNUNET_asprintf (&hdr,
1614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1615 "Adding HEADER `%s' to HTTP request\n",
1617 s5r->headers = curl_slist_append (s5r->headers,
1625 * Main MHD callback for handling requests.
1628 * @param con MHD connection handle
1629 * @param url the url in the request
1630 * @param meth the HTTP method used ("GET", "PUT", etc.)
1631 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1632 * @param upload_data the data being uploaded (excluding HEADERS,
1633 * for a POST that fits into memory and that is encoded
1634 * with a supported encoding, the POST data will NOT be
1635 * given in upload_data and is instead available as
1636 * part of MHD_get_connection_values; very large POST
1637 * data *will* be made available incrementally in
1639 * @param upload_data_size set initially to the size of the
1640 * @a upload_data provided; the method must update this
1641 * value to the number of bytes NOT processed;
1642 * @param con_cls pointer to location where we store the `struct Request`
1643 * @return #MHD_YES if the connection was handled successfully,
1644 * #MHD_NO if the socket must be closed due to a serious
1645 * error while handling the request
1648 create_response (void *cls,
1649 struct MHD_Connection *con,
1653 const char *upload_data,
1654 size_t *upload_data_size,
1657 struct Socks5Request *s5r = *con_cls;
1659 char ipstring[INET6_ADDRSTRLEN];
1660 char ipaddr[INET6_ADDRSTRLEN + 2];
1661 const struct sockaddr *sa;
1662 const struct sockaddr_in *s4;
1663 const struct sockaddr_in6 *s6;
1674 if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
1676 /* first time here, initialize curl handle */
1679 sa = (const struct sockaddr *) &s5r->destination_address;
1680 switch (sa->sa_family)
1683 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1684 if (NULL == inet_ntop (AF_INET,
1692 GNUNET_snprintf (ipaddr,
1696 port = ntohs (s4->sin_port);
1699 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1700 if (NULL == inet_ntop (AF_INET6,
1708 GNUNET_snprintf (ipaddr,
1712 port = ntohs (s6->sin6_port);
1723 if (NULL == s5r->curl)
1724 s5r->curl = curl_easy_init ();
1725 if (NULL == s5r->curl)
1726 return MHD_queue_response (con,
1727 MHD_HTTP_INTERNAL_SERVER_ERROR,
1728 curl_failure_response);
1729 curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1730 curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1731 curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1733 curl_easy_setopt (s5r->curl,
1736 curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1737 curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1738 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1739 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1740 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1741 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1742 curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1743 curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0L);
1745 * Pre-populate cache to resolve Hostname.
1746 * This is necessary as the DNS name in the CURLOPT_URL is used
1747 * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1749 if (NULL != s5r->leho)
1753 GNUNET_asprintf (&curl_hosts,
1758 s5r->hosts = curl_slist_append (NULL,
1760 curl_easy_setopt (s5r->curl,
1763 GNUNET_free (curl_hosts);
1767 GNUNET_asprintf (&curlurl,
1768 (HTTPS_PORT != s5r->port)
1770 : "https://%s:%d%s",
1779 GNUNET_asprintf (&curlurl,
1780 (HTTPS_PORT != s5r->port)
1782 : "https://%s:%d%s",
1787 curl_easy_setopt (s5r->curl,
1790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1791 "Launching %s CURL interaction, fetching `%s'\n",
1792 (s5r->is_gns) ? "GNS" : "DNS",
1794 GNUNET_free (curlurl);
1795 if (0 == strcasecmp (meth,
1796 MHD_HTTP_METHOD_PUT))
1798 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1799 curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1L);
1800 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1801 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1802 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1803 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1805 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1807 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1808 curl_easy_setopt (s5r->curl, CURLOPT_POST, 1L);
1809 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1810 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1811 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1812 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1814 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1816 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1817 curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1L);
1819 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_OPTIONS))
1821 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1822 curl_easy_setopt (s5r->curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
1824 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1826 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1827 curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1L);
1828 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1829 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1833 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1834 _("Unsupported HTTP method `%s'\n"),
1836 curl_easy_cleanup (s5r->curl);
1841 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1843 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1845 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1847 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1851 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1854 if (HTTPS_PORT == s5r->port)
1856 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1857 if (NULL != s5r->dane_data)
1858 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 0L);
1860 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1861 /* Disable cURL checking the hostname, as we will check ourselves
1862 as only we have the domain name or the LEHO or the DANE record */
1863 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
1867 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
1871 curl_multi_add_handle (curl_multi,
1875 curl_easy_cleanup (s5r->curl);
1879 MHD_get_connection_values (con,
1883 curl_easy_setopt (s5r->curl,
1886 curl_download_prepare ();
1890 /* continuing to process request */
1891 if (0 != *upload_data_size)
1893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1894 "Processing %u bytes UPLOAD\n",
1895 (unsigned int) *upload_data_size);
1897 /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else
1898 * upload callback is not called!
1900 curl_easy_setopt (s5r->curl, CURLOPT_POSTFIELDSIZE, *upload_data_size);
1902 left = GNUNET_MIN (*upload_data_size,
1903 sizeof (s5r->io_buf) - s5r->io_len);
1904 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1907 s5r->io_len += left;
1908 *upload_data_size -= left;
1909 GNUNET_assert (NULL != s5r->curl);
1910 curl_easy_pause (s5r->curl,
1914 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
1916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1917 "Finished processing UPLOAD\n");
1918 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1920 if (NULL == s5r->response)
1922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1923 "Waiting for HTTP response for %s%s...\n",
1926 MHD_suspend_connection (con);
1927 s5r->suspended = GNUNET_YES;
1930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1931 "Queueing response for %s%s with MHD\n",
1934 run_mhd_now (s5r->hd);
1935 return MHD_queue_response (con,
1941 /* ******************** MHD HTTP setup and event loop ******************** */
1945 * Function called when MHD decides that we are done with a request.
1948 * @param connection connection handle
1949 * @param con_cls value as set by the last call to
1950 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
1951 * @param toe reason for request termination (ignored)
1954 mhd_completed_cb (void *cls,
1955 struct MHD_Connection *connection,
1957 enum MHD_RequestTerminationCode toe)
1959 struct Socks5Request *s5r = *con_cls;
1963 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
1964 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1965 "MHD encountered error handling request: %d\n",
1967 if (NULL != s5r->curl)
1969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1970 "Removing cURL handle (MHD interaction complete)\n");
1971 curl_multi_remove_handle (curl_multi,
1973 curl_slist_free_all (s5r->headers);
1974 s5r->headers = NULL;
1975 curl_easy_reset (s5r->curl);
1979 curl_download_prepare ();
1981 if ( (NULL != s5r->response) &&
1982 (curl_failure_response != s5r->response) )
1983 MHD_destroy_response (s5r->response);
1984 for (struct HttpResponseHeader *header = s5r->header_head;
1986 header = s5r->header_head)
1988 GNUNET_CONTAINER_DLL_remove (s5r->header_head,
1991 GNUNET_free (header->type);
1992 GNUNET_free (header->value);
1993 GNUNET_free (header);
1995 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1996 "Finished request for %s\n",
1998 GNUNET_free (s5r->url);
1999 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2001 s5r->response = NULL;
2007 * Function called when MHD connection is opened or closed.
2010 * @param connection connection handle
2011 * @param con_cls value as set by the last call to
2012 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2013 * @param toe connection notification type
2016 mhd_connection_cb (void *cls,
2017 struct MHD_Connection *connection,
2019 enum MHD_ConnectionNotificationCode cnc)
2021 struct Socks5Request *s5r;
2022 const union MHD_ConnectionInfo *ci;
2027 case MHD_CONNECTION_NOTIFY_STARTED:
2028 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
2029 ci = MHD_get_connection_info (connection,
2030 MHD_CONNECTION_INFO_CONNECTION_FD);
2036 sock = ci->connect_fd;
2037 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
2039 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
2041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2042 "Context set...\n");
2043 s5r->ssl_checked = GNUNET_NO;
2049 case MHD_CONNECTION_NOTIFY_CLOSED:
2050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2051 "Connection closed... cleaning up\n");
2055 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2056 "Connection stale!\n");
2060 curl_download_prepare ();
2069 * Function called when MHD first processes an incoming connection.
2070 * Gives us the respective URI information.
2072 * We use this to associate the `struct MHD_Connection` with our
2073 * internal `struct Socks5Request` data structure (by checking
2074 * for matching sockets).
2076 * @param cls the HTTP server handle (a `struct MhdHttpList`)
2077 * @param url the URL that is being requested
2078 * @param connection MHD connection object for the request
2079 * @return the `struct Socks5Request` that this @a connection is for
2082 mhd_log_callback (void *cls,
2084 struct MHD_Connection *connection)
2086 struct Socks5Request *s5r;
2087 const union MHD_ConnectionInfo *ci;
2089 ci = MHD_get_connection_info (connection,
2090 MHD_CONNECTION_INFO_SOCKET_CONTEXT);
2091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
2097 s5r = ci->socket_context;
2098 if (NULL != s5r->url)
2103 s5r->url = GNUNET_strdup (url);
2104 if (NULL != s5r->timeout_task)
2106 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
2107 s5r->timeout_task = NULL;
2109 GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD);
2115 * Kill the given MHD daemon.
2117 * @param hd daemon to stop
2120 kill_httpd (struct MhdHttpList *hd)
2122 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
2125 GNUNET_free_non_null (hd->domain);
2126 MHD_stop_daemon (hd->daemon);
2127 if (NULL != hd->httpd_task)
2129 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2130 hd->httpd_task = NULL;
2132 GNUNET_free_non_null (hd->proxy_cert);
2140 * Task run whenever HTTP server is idle for too long. Kill it.
2142 * @param cls the `struct MhdHttpList *`
2145 kill_httpd_task (void *cls)
2147 struct MhdHttpList *hd = cls;
2149 hd->httpd_task = NULL;
2155 * Task run whenever HTTP server operations are pending.
2157 * @param cls the `struct MhdHttpList *` of the daemon that is being run
2160 do_httpd (void *cls);
2164 * Schedule MHD. This function should be called initially when an
2165 * MHD is first getting its client socket, and will then automatically
2166 * always be called later whenever there is work to be done.
2168 * @param hd the daemon to schedule
2171 schedule_httpd (struct MhdHttpList *hd)
2176 struct GNUNET_NETWORK_FDSet *wrs;
2177 struct GNUNET_NETWORK_FDSet *wws;
2180 MHD_UNSIGNED_LONG_LONG timeout;
2181 struct GNUNET_TIME_Relative tv;
2188 MHD_get_fdset (hd->daemon,
2197 haveto = MHD_get_timeout (hd->daemon,
2199 if (MHD_YES == haveto)
2200 tv.rel_value_us = (uint64_t) timeout * 1000LL;
2202 tv = GNUNET_TIME_UNIT_FOREVER_REL;
2205 wrs = GNUNET_NETWORK_fdset_create ();
2206 wws = GNUNET_NETWORK_fdset_create ();
2207 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
2208 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
2215 if (NULL != hd->httpd_task)
2217 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2218 hd->httpd_task = NULL;
2220 if ( (MHD_YES != haveto) &&
2224 /* daemon is idle, kill after timeout */
2225 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
2232 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2237 GNUNET_NETWORK_fdset_destroy (wrs);
2239 GNUNET_NETWORK_fdset_destroy (wws);
2244 * Task run whenever HTTP server operations are pending.
2246 * @param cls the `struct MhdHttpList` of the daemon that is being run
2249 do_httpd (void *cls)
2251 struct MhdHttpList *hd = cls;
2253 hd->httpd_task = NULL;
2254 MHD_run (hd->daemon);
2255 schedule_httpd (hd);
2260 * Run MHD now, we have extra data ready for the callback.
2262 * @param hd the daemon to run now.
2265 run_mhd_now (struct MhdHttpList *hd)
2267 if (NULL != hd->httpd_task)
2268 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2269 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
2275 * Read file in filename
2277 * @param filename file to read
2278 * @param size pointer where filesize is stored
2279 * @return NULL on error
2282 load_file (const char* filename,
2289 GNUNET_DISK_file_size (filename, &fsize,
2290 GNUNET_YES, GNUNET_YES))
2292 if (fsize > MAX_PEM_SIZE)
2294 *size = (unsigned int) fsize;
2295 buffer = GNUNET_malloc (*size);
2297 GNUNET_DISK_fn_read (filename,
2301 GNUNET_free (buffer);
2309 * Load PEM key from file
2311 * @param key where to store the data
2312 * @param keyfile path to the PEM file
2313 * @return #GNUNET_OK on success
2316 load_key_from_file (gnutls_x509_privkey_t key,
2317 const char* keyfile)
2319 gnutls_datum_t key_data;
2322 key_data.data = load_file (keyfile, &key_data.size);
2323 if (NULL == key_data.data)
2324 return GNUNET_SYSERR;
2325 ret = gnutls_x509_privkey_import (key, &key_data,
2326 GNUTLS_X509_FMT_PEM);
2327 if (GNUTLS_E_SUCCESS != ret)
2329 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2330 _("Unable to import private key from file `%s'\n"),
2333 GNUNET_free_non_null (key_data.data);
2334 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2339 * Load cert from file
2341 * @param crt struct to store data in
2342 * @param certfile path to pem file
2343 * @return #GNUNET_OK on success
2346 load_cert_from_file (gnutls_x509_crt_t crt,
2347 const char* certfile)
2349 gnutls_datum_t cert_data;
2352 cert_data.data = load_file (certfile, &cert_data.size);
2353 if (NULL == cert_data.data)
2354 return GNUNET_SYSERR;
2355 ret = gnutls_x509_crt_import (crt, &cert_data,
2356 GNUTLS_X509_FMT_PEM);
2357 if (GNUTLS_E_SUCCESS != ret)
2359 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2360 _("Unable to import certificate %s\n"), certfile);
2362 GNUNET_free_non_null (cert_data.data);
2363 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2368 * Generate new certificate for specific name
2370 * @param name the subject name to generate a cert for
2371 * @return a struct holding the PEM data, NULL on error
2373 static struct ProxyGNSCertificate *
2374 generate_gns_certificate (const char *name)
2376 unsigned int serial;
2377 size_t key_buf_size;
2378 size_t cert_buf_size;
2379 gnutls_x509_crt_t request;
2382 struct ProxyGNSCertificate *pgc;
2384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385 "Generating x.509 certificate for `%s'\n",
2387 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2388 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2389 pgc = GNUNET_new (struct ProxyGNSCertificate);
2390 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2392 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2393 0, "GNU Name System", 4);
2394 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2395 0, name, strlen (name));
2396 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
2397 gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2398 gnutls_x509_crt_set_serial (request,
2401 etime = time (NULL);
2402 tm_data = localtime (&etime);
2404 etime = mktime(tm_data);
2405 gnutls_x509_crt_set_activation_time (request,
2408 etime = mktime (tm_data);
2409 gnutls_x509_crt_set_expiration_time (request,
2411 gnutls_x509_crt_sign (request,
2414 key_buf_size = sizeof (pgc->key);
2415 cert_buf_size = sizeof (pgc->cert);
2416 gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2417 pgc->cert, &cert_buf_size);
2418 gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2419 pgc->key, &key_buf_size);
2420 gnutls_x509_crt_deinit (request);
2426 * Function called by MHD with errors, suppresses them all.
2428 * @param cls closure
2429 * @param fm format string (`printf()`-style)
2430 * @param ap arguments to @a fm
2433 mhd_error_log_callback (void *cls,
2442 * Lookup (or create) an TLS MHD instance for a particular domain.
2444 * @param domain the domain the TLS daemon has to serve
2445 * @return NULL on error
2447 static struct MhdHttpList *
2448 lookup_ssl_httpd (const char* domain)
2450 struct MhdHttpList *hd;
2451 struct ProxyGNSCertificate *pgc;
2458 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2459 if ( (NULL != hd->domain) &&
2460 (0 == strcmp (hd->domain, domain)) )
2462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2463 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2465 pgc = generate_gns_certificate (domain);
2466 hd = GNUNET_new (struct MhdHttpList);
2467 hd->is_ssl = GNUNET_YES;
2468 hd->domain = GNUNET_strdup (domain);
2469 hd->proxy_cert = pgc;
2470 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
2473 &create_response, hd,
2474 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2475 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2476 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
2477 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2478 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2479 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2480 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2482 if (NULL == hd->daemon)
2488 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2496 * Task run when a Socks5Request somehow fails to be associated with
2497 * an MHD connection (i.e. because the client never speaks HTTP after
2498 * the SOCKS5 handshake). Clean up.
2500 * @param cls the `struct Socks5Request *`
2503 timeout_s5r_handshake (void *cls)
2505 struct Socks5Request *s5r = cls;
2507 s5r->timeout_task = NULL;
2513 * We're done with the Socks5 protocol, now we need to pass the
2514 * connection data through to the final destination, either
2515 * direct (if the protocol might not be HTTP), or via MHD
2516 * (if the port looks like it should be HTTP).
2518 * @param s5r socks request that has reached the final stage
2521 setup_data_transfer (struct Socks5Request *s5r)
2523 struct MhdHttpList *hd;
2525 const struct sockaddr *addr;
2532 GNUNET_asprintf (&domain,
2535 hd = lookup_ssl_httpd (domain);
2538 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2539 _("Failed to start HTTPS server for `%s'\n"),
2542 GNUNET_free (domain);
2549 GNUNET_assert (NULL != httpd);
2553 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2554 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2555 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2556 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2558 MHD_add_connection (hd->daemon,
2563 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2564 _("Failed to pass client to MHD\n"));
2566 GNUNET_free_non_null (domain);
2570 schedule_httpd (hd);
2571 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2572 &timeout_s5r_handshake,
2574 GNUNET_free_non_null (domain);
2578 /* ********************* SOCKS handling ************************* */
2582 * Write data from buffer to socks5 client, then continue with state machine.
2584 * @param cls the closure with the `struct Socks5Request`
2587 do_write (void *cls)
2589 struct Socks5Request *s5r = cls;
2593 len = GNUNET_NETWORK_socket_send (s5r->sock,
2598 /* write error: connection closed, shutdown, etc.; just clean up */
2599 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2606 s5r->wbuf_len - len);
2607 s5r->wbuf_len -= len;
2608 if (s5r->wbuf_len > 0)
2610 /* not done writing */
2612 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2618 /* we're done writing, continue with state machine! */
2625 case SOCKS5_REQUEST:
2626 GNUNET_assert (NULL != s5r->rtask);
2628 case SOCKS5_DATA_TRANSFER:
2629 setup_data_transfer (s5r);
2631 case SOCKS5_WRITE_THEN_CLEANUP:
2642 * Return a server response message indicating a failure to the client.
2644 * @param s5r request to return failure code for
2645 * @param sc status code to return
2648 signal_socks_failure (struct Socks5Request *s5r,
2649 enum Socks5StatusCode sc)
2651 struct Socks5ServerResponseMessage *s_resp;
2653 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2654 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2655 s_resp->version = SOCKS_VERSION_5;
2657 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2658 if (NULL != s5r->wtask)
2660 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2667 * Return a server response message indicating success.
2669 * @param s5r request to return success status message for
2672 signal_socks_success (struct Socks5Request *s5r)
2674 struct Socks5ServerResponseMessage *s_resp;
2676 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2677 s_resp->version = SOCKS_VERSION_5;
2678 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2679 s_resp->reserved = 0;
2680 s_resp->addr_type = SOCKS5_AT_IPV4;
2681 /* zero out IPv4 address and port */
2684 sizeof (struct in_addr) + sizeof (uint16_t));
2685 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2686 sizeof (struct in_addr) + sizeof (uint16_t);
2687 if (NULL == s5r->wtask)
2689 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2696 * Process GNS results for target domain.
2698 * @param cls the `struct Socks5Request *`
2699 * @param tld #GNUNET_YES if this was a GNS TLD.
2700 * @param rd_count number of records returned
2701 * @param rd record data
2704 handle_gns_result (void *cls,
2707 const struct GNUNET_GNSRECORD_Data *rd)
2709 struct Socks5Request *s5r = cls;
2710 const struct GNUNET_GNSRECORD_Data *r;
2713 s5r->gns_lookup = NULL;
2716 for (uint32_t i=0;i<rd_count;i++)
2719 switch (r->record_type)
2721 case GNUNET_DNSPARSER_TYPE_A:
2723 struct sockaddr_in *in;
2725 if (sizeof (struct in_addr) != r->data_size)
2727 GNUNET_break_op (0);
2730 if (GNUNET_YES == got_ip)
2733 GNUNET_NETWORK_test_pf (PF_INET))
2735 got_ip = GNUNET_YES;
2736 in = (struct sockaddr_in *) &s5r->destination_address;
2737 in->sin_family = AF_INET;
2738 GNUNET_memcpy (&in->sin_addr,
2741 in->sin_port = htons (s5r->port);
2742 #if HAVE_SOCKADDR_IN_SIN_LEN
2743 in->sin_len = sizeof (*in);
2747 case GNUNET_DNSPARSER_TYPE_AAAA:
2749 struct sockaddr_in6 *in;
2751 if (sizeof (struct in6_addr) != r->data_size)
2753 GNUNET_break_op (0);
2756 if (GNUNET_YES == got_ip)
2759 GNUNET_NETWORK_test_pf (PF_INET))
2761 /* FIXME: allow user to disable IPv6 per configuration option... */
2762 got_ip = GNUNET_YES;
2763 in = (struct sockaddr_in6 *) &s5r->destination_address;
2764 in->sin6_family = AF_INET6;
2765 GNUNET_memcpy (&in->sin6_addr,
2768 in->sin6_port = htons (s5r->port);
2769 #if HAVE_SOCKADDR_IN_SIN_LEN
2770 in->sin6_len = sizeof (*in);
2774 case GNUNET_GNSRECORD_TYPE_VPN:
2775 GNUNET_break (0); /* should have been translated within GNS */
2777 case GNUNET_GNSRECORD_TYPE_LEHO:
2778 GNUNET_free_non_null (s5r->leho);
2779 s5r->leho = GNUNET_strndup (r->data,
2782 case GNUNET_GNSRECORD_TYPE_BOX:
2784 const struct GNUNET_GNSRECORD_BoxRecord *box;
2786 if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
2788 GNUNET_break_op (0);
2792 if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
2793 (ntohs (box->protocol) != IPPROTO_TCP) ||
2794 (ntohs (box->service) != s5r->port) )
2795 break; /* BOX record does not apply */
2796 GNUNET_free_non_null (s5r->dane_data);
2797 s5r->dane_data_len = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
2798 s5r->dane_data = GNUNET_malloc (s5r->dane_data_len);
2799 GNUNET_memcpy (s5r->dane_data,
2801 s5r->dane_data_len);
2809 if ( (GNUNET_YES != got_ip) &&
2810 (GNUNET_YES == tld) )
2812 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2813 "Name resolution failed to yield useful IP address.\n");
2814 signal_socks_failure (s5r,
2815 SOCKS5_STATUS_GENERAL_FAILURE);
2818 s5r->state = SOCKS5_DATA_TRANSFER;
2819 signal_socks_success (s5r);
2824 * Remove the first @a len bytes from the beginning of the read buffer.
2826 * @param s5r the handle clear the read buffer for
2827 * @param len number of bytes in read buffer to advance
2830 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2833 GNUNET_assert (len <= s5r->rbuf_len);
2836 s5r->rbuf_len - len);
2837 s5r->rbuf_len -= len;
2842 * Read data from incoming Socks5 connection
2844 * @param cls the closure with the `struct Socks5Request`
2847 do_s5r_read (void *cls)
2849 struct Socks5Request *s5r = cls;
2850 const struct Socks5ClientHelloMessage *c_hello;
2851 struct Socks5ServerHelloMessage *s_hello;
2852 const struct Socks5ClientRequestMessage *c_req;
2855 const struct GNUNET_SCHEDULER_TaskContext *tc;
2858 tc = GNUNET_SCHEDULER_get_task_context ();
2859 if ( (NULL != tc->read_ready) &&
2860 (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2862 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2863 &s5r->rbuf[s5r->rbuf_len],
2864 sizeof (s5r->rbuf) - s5r->rbuf_len);
2867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2868 "socks5 client disconnected.\n");
2872 s5r->rbuf_len += rlen;
2874 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2878 "Processing %zu bytes of socks data in state %d\n",
2884 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2885 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2886 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2887 return; /* need more data */
2888 if (SOCKS_VERSION_5 != c_hello->version)
2890 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2891 _("Unsupported socks version %d\n"),
2892 (int) c_hello->version);
2896 clear_from_s5r_rbuf (s5r,
2897 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2898 GNUNET_assert (0 == s5r->wbuf_len);
2899 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2900 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2901 s_hello->version = SOCKS_VERSION_5;
2902 s_hello->auth_method = SOCKS_AUTH_NONE;
2903 GNUNET_assert (NULL == s5r->wtask);
2904 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2907 s5r->state = SOCKS5_REQUEST;
2909 case SOCKS5_REQUEST:
2910 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2911 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2913 switch (c_req->command)
2915 case SOCKS5_CMD_TCP_STREAM:
2919 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2920 _("Unsupported socks command %d\n"),
2921 (int) c_req->command);
2922 signal_socks_failure (s5r,
2923 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2926 switch (c_req->addr_type)
2928 case SOCKS5_AT_IPV4:
2930 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2931 const uint16_t *port = (const uint16_t *) &v4[1];
2932 struct sockaddr_in *in;
2934 s5r->port = ntohs (*port);
2935 alen = sizeof (struct in_addr);
2936 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2937 alen + sizeof (uint16_t))
2938 return; /* need more data */
2939 in = (struct sockaddr_in *) &s5r->destination_address;
2940 in->sin_family = AF_INET;
2942 in->sin_port = *port;
2943 #if HAVE_SOCKADDR_IN_SIN_LEN
2944 in->sin_len = sizeof (*in);
2946 s5r->state = SOCKS5_DATA_TRANSFER;
2949 case SOCKS5_AT_IPV6:
2951 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2952 const uint16_t *port = (const uint16_t *) &v6[1];
2953 struct sockaddr_in6 *in;
2955 s5r->port = ntohs (*port);
2956 alen = sizeof (struct in6_addr);
2957 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2958 alen + sizeof (uint16_t))
2959 return; /* need more data */
2960 in = (struct sockaddr_in6 *) &s5r->destination_address;
2961 in->sin6_family = AF_INET6;
2962 in->sin6_addr = *v6;
2963 in->sin6_port = *port;
2964 #if HAVE_SOCKADDR_IN_SIN_LEN
2965 in->sin6_len = sizeof (*in);
2967 s5r->state = SOCKS5_DATA_TRANSFER;
2970 case SOCKS5_AT_DOMAINNAME:
2972 const uint8_t *dom_len;
2973 const char *dom_name;
2974 const uint16_t *port;
2976 dom_len = (const uint8_t *) &c_req[1];
2977 alen = *dom_len + 1;
2978 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2979 alen + sizeof (uint16_t))
2980 return; /* need more data */
2981 dom_name = (const char *) &dom_len[1];
2982 port = (const uint16_t*) &dom_name[*dom_len];
2983 s5r->domain = GNUNET_strndup (dom_name,
2985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2986 "Requested connection is to %s:%d\n",
2989 s5r->state = SOCKS5_RESOLVING;
2990 s5r->port = ntohs (*port);
2991 s5r->gns_lookup = GNUNET_GNS_lookup_with_tld (gns_handle,
2993 GNUNET_DNSPARSER_TYPE_A,
2994 GNUNET_NO /* only cached */,
3000 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3001 _("Unsupported socks address type %d\n"),
3002 (int) c_req->addr_type);
3003 signal_socks_failure (s5r,
3004 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
3007 clear_from_s5r_rbuf (s5r,
3008 sizeof (struct Socks5ClientRequestMessage) +
3009 alen + sizeof (uint16_t));
3010 if (0 != s5r->rbuf_len)
3012 /* read more bytes than healthy, why did the client send more!? */
3013 GNUNET_break_op (0);
3014 signal_socks_failure (s5r,
3015 SOCKS5_STATUS_GENERAL_FAILURE);
3018 if (SOCKS5_DATA_TRANSFER == s5r->state)
3020 /* if we are not waiting for GNS resolution, signal success */
3021 signal_socks_success (s5r);
3023 /* We are done reading right now */
3024 GNUNET_SCHEDULER_cancel (s5r->rtask);
3027 case SOCKS5_RESOLVING:
3030 case SOCKS5_DATA_TRANSFER:
3041 * Accept new incoming connections
3043 * @param cls the closure with the lsock4 or lsock6
3044 * @param tc the scheduler context
3047 do_accept (void *cls)
3049 struct GNUNET_NETWORK_Handle *lsock = cls;
3050 struct GNUNET_NETWORK_Handle *s;
3051 struct Socks5Request *s5r;
3053 GNUNET_assert (NULL != lsock);
3054 if (lsock == lsock4)
3055 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3058 else if (lsock == lsock6)
3059 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3064 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
3067 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
3070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3071 "Got an inbound connection, waiting for data\n");
3072 s5r = GNUNET_new (struct Socks5Request);
3073 GNUNET_CONTAINER_DLL_insert (s5r_head,
3077 s5r->state = SOCKS5_INIT;
3078 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3084 /* ******************* General / main code ********************* */
3088 * Task run on shutdown
3090 * @param cls closure
3093 do_shutdown (void *cls)
3095 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3096 "Shutting down...\n");
3097 /* MHD requires resuming before destroying the daemons */
3098 for (struct Socks5Request *s5r = s5r_head;
3104 s5r->suspended = GNUNET_NO;
3105 MHD_resume_connection (s5r->con);
3108 while (NULL != mhd_httpd_head)
3109 kill_httpd (mhd_httpd_head);
3110 while (NULL != s5r_head)
3111 cleanup_s5r (s5r_head);
3114 GNUNET_NETWORK_socket_close (lsock4);
3119 GNUNET_NETWORK_socket_close (lsock6);
3122 if (NULL != curl_multi)
3124 curl_multi_cleanup (curl_multi);
3127 if (NULL != gns_handle)
3129 GNUNET_GNS_disconnect (gns_handle);
3132 if (NULL != curl_download_task)
3134 GNUNET_SCHEDULER_cancel (curl_download_task);
3135 curl_download_task = NULL;
3139 GNUNET_SCHEDULER_cancel (ltask4);
3144 GNUNET_SCHEDULER_cancel (ltask6);
3147 gnutls_x509_crt_deinit (proxy_ca.cert);
3148 gnutls_x509_privkey_deinit (proxy_ca.key);
3149 gnutls_global_deinit ();
3154 * Create an IPv4 listen socket bound to our port.
3156 * @return NULL on error
3158 static struct GNUNET_NETWORK_Handle *
3161 struct GNUNET_NETWORK_Handle *ls;
3162 struct sockaddr_in sa4;
3165 memset (&sa4, 0, sizeof (sa4));
3166 sa4.sin_family = AF_INET;
3167 sa4.sin_port = htons (port);
3168 #if HAVE_SOCKADDR_IN_SIN_LEN
3169 sa4.sin_len = sizeof (sa4);
3171 ls = GNUNET_NETWORK_socket_create (AF_INET,
3177 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
3181 GNUNET_NETWORK_socket_close (ls);
3190 * Create an IPv6 listen socket bound to our port.
3192 * @return NULL on error
3194 static struct GNUNET_NETWORK_Handle *
3197 struct GNUNET_NETWORK_Handle *ls;
3198 struct sockaddr_in6 sa6;
3201 memset (&sa6, 0, sizeof (sa6));
3202 sa6.sin6_family = AF_INET6;
3203 sa6.sin6_port = htons (port);
3204 #if HAVE_SOCKADDR_IN_SIN_LEN
3205 sa6.sin6_len = sizeof (sa6);
3207 ls = GNUNET_NETWORK_socket_create (AF_INET6,
3213 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
3217 GNUNET_NETWORK_socket_close (ls);
3226 * Main function that will be run
3228 * @param cls closure
3229 * @param args remaining command-line arguments
3230 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3231 * @param c configuration
3236 const char *cfgfile,
3237 const struct GNUNET_CONFIGURATION_Handle *c)
3239 char* cafile_cfg = NULL;
3241 struct MhdHttpList *hd;
3245 if (NULL == (curl_multi = curl_multi_init ()))
3247 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3248 "Failed to create cURL multi handle!\n");
3251 cafile = cafile_opt;
3255 GNUNET_CONFIGURATION_get_value_filename (cfg,
3260 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3265 cafile = cafile_cfg;
3267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3268 "Using %s as CA\n", cafile);
3270 gnutls_global_init ();
3271 gnutls_x509_crt_init (&proxy_ca.cert);
3272 gnutls_x509_privkey_init (&proxy_ca.key);
3275 load_cert_from_file (proxy_ca.cert,
3278 load_key_from_file (proxy_ca.key,
3281 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3282 _("Failed to load X.509 key and certificate from `%s'\n"),
3284 gnutls_x509_crt_deinit (proxy_ca.cert);
3285 gnutls_x509_privkey_deinit (proxy_ca.key);
3286 gnutls_global_deinit ();
3287 GNUNET_free_non_null (cafile_cfg);
3290 GNUNET_free_non_null (cafile_cfg);
3291 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3293 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3294 "Unable to connect to GNS!\n");
3295 gnutls_x509_crt_deinit (proxy_ca.cert);
3296 gnutls_x509_privkey_deinit (proxy_ca.key);
3297 gnutls_global_deinit ();
3300 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
3303 /* Open listen socket for socks proxy */
3304 lsock6 = bind_v6 ();
3307 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3313 GNUNET_NETWORK_socket_listen (lsock6,
3316 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3318 GNUNET_NETWORK_socket_close (lsock6);
3323 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3329 lsock4 = bind_v4 ();
3332 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3338 GNUNET_NETWORK_socket_listen (lsock4,
3341 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3343 GNUNET_NETWORK_socket_close (lsock4);
3348 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3354 if ( (NULL == lsock4) &&
3357 GNUNET_SCHEDULER_shutdown ();
3360 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3362 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3363 "cURL global init failed!\n");
3364 GNUNET_SCHEDULER_shutdown ();
3367 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3368 "Proxy listens on port %llu\n",
3371 /* start MHD daemon for HTTP */
3372 hd = GNUNET_new (struct MhdHttpList);
3373 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
3376 &create_response, hd,
3377 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3378 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3379 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
3380 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3382 if (NULL == hd->daemon)
3385 GNUNET_SCHEDULER_shutdown ();
3389 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
3396 * The main function for gnunet-gns-proxy.
3398 * @param argc number of arguments from the command line
3399 * @param argv command line arguments
3400 * @return 0 ok, 1 on error
3403 main (int argc, char *const *argv)
3405 struct GNUNET_GETOPT_CommandLineOption options[] = {
3406 GNUNET_GETOPT_option_ulong ('p',
3409 gettext_noop ("listen on specified port (default: 7777)"),
3411 GNUNET_GETOPT_option_string ('a',
3414 gettext_noop ("pem file to use as CA"),
3417 GNUNET_GETOPT_OPTION_END
3419 static const char* page =
3420 "<html><head><title>gnunet-gns-proxy</title>"
3421 "</head><body>cURL fail</body></html>";
3424 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv,
3427 GNUNET_log_setup ("gnunet-gns-proxy",
3430 curl_failure_response
3431 = MHD_create_response_from_buffer (strlen (page),
3433 MHD_RESPMEM_PERSISTENT);
3437 GNUNET_PROGRAM_run (argc, argv,
3439 _("GNUnet GNS proxy"),
3441 &run, NULL)) ? 0 : 1;
3442 MHD_destroy_response (curl_failure_response);
3443 GNUNET_free_non_null ((char *) argv);
3447 /* end of gnunet-gns-proxy.c */