2 This file is part of GNUnet.
3 Copyright (C) 2012-2018 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your 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 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
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"
53 * Default Socks5 listen port.
55 #define GNUNET_GNS_PROXY_PORT 7777
58 * Maximum supported length for a URI.
59 * Should die. @deprecated
61 #define MAX_HTTP_URI_LENGTH 2048
64 * Maximum number of DANE records we support
65 * per domain name (and port and protocol).
70 * Size of the buffer for the data upload / download. Must be
71 * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
73 #define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE
76 * Size of the read/write buffers for Socks. Uses
77 * 256 bytes for the hostname (at most), plus a few
78 * bytes overhead for the messages.
80 #define SOCKS_BUFFERSIZE (256 + 32)
83 * Port for plaintext HTTP.
90 #define HTTPS_PORT 443
93 * Largest allowed size for a PEM certificate.
95 #define MAX_PEM_SIZE (10 * 1024)
98 * After how long do we clean up unused MHD TLS instances?
100 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
103 * After how long do we clean up Socks5 handles that failed to show any activity
104 * with their respective MHD instance?
106 #define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
112 * @param level log level
113 * @param fun name of curl_easy-function that gave the error
114 * @param rc return code from curl
116 #define LOG_CURL_EASY(level,fun,rc) \
118 _("%s failed at %s:%d: `%s'\n"), \
122 curl_easy_strerror (rc))
125 /* *************** Socks protocol definitions (move to TUN?) ****************** */
128 * Which SOCKS version do we speak?
130 #define SOCKS_VERSION_5 0x05
133 * Flag to set for 'no authentication'.
135 #define SOCKS_AUTH_NONE 0
139 * Commands in Socks5.
144 * Establish TCP/IP stream.
146 SOCKS5_CMD_TCP_STREAM = 1,
149 * Establish TCP port binding.
151 SOCKS5_CMD_TCP_PORT = 2,
154 * Establish UDP port binding.
156 SOCKS5_CMD_UDP_PORT = 3
161 * Address types in Socks5.
163 enum Socks5AddressType
173 SOCKS5_AT_DOMAINNAME = 3,
184 * Status codes in Socks5 response.
186 enum Socks5StatusCode
188 SOCKS5_STATUS_REQUEST_GRANTED = 0,
189 SOCKS5_STATUS_GENERAL_FAILURE = 1,
190 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
191 SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
192 SOCKS5_STATUS_HOST_UNREACHABLE = 4,
193 SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
194 SOCKS5_STATUS_TTL_EXPIRED = 6,
195 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
196 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
201 * Client hello in Socks5 protocol.
203 struct Socks5ClientHelloMessage
206 * Should be #SOCKS_VERSION_5.
211 * How many authentication methods does the client support.
213 uint8_t num_auth_methods;
215 /* followed by supported authentication methods, 1 byte per method */
221 * Server hello in Socks5 protocol.
223 struct Socks5ServerHelloMessage
226 * Should be #SOCKS_VERSION_5.
231 * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
232 * which skips the authentication step.
239 * Client socks request in Socks5 protocol.
241 struct Socks5ClientRequestMessage
244 * Should be #SOCKS_VERSION_5.
249 * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
254 * Reserved, always zero.
259 * Address type, an `enum Socks5AddressType`.
264 * Followed by either an ip4/ipv6 address or a domain name with a
265 * length field (uint8_t) in front (depending on @e addr_type).
266 * followed by port number in network byte order (uint16_t).
272 * Server response to client requests in Socks5 protocol.
274 struct Socks5ServerResponseMessage
277 * Should be #SOCKS_VERSION_5.
282 * Status code, an `enum Socks5StatusCode`
292 * Address type, an `enum Socks5AddressType`.
297 * Followed by either an ip4/ipv6 address or a domain name with a
298 * length field (uint8_t) in front (depending on @e addr_type).
299 * followed by port number in network byte order (uint16_t).
306 /* *********************** Datastructures for HTTP handling ****************** */
309 * A structure for CA cert/key
316 gnutls_x509_crt_t cert;
321 gnutls_x509_privkey_t key;
326 * Structure for GNS certificates
328 struct ProxyGNSCertificate
331 * The certificate as PEM
333 char cert[MAX_PEM_SIZE];
336 * The private key as PEM
338 char key[MAX_PEM_SIZE];
344 * A structure for all running Httpds
351 struct MhdHttpList *prev;
356 struct MhdHttpList *next;
359 * the domain name to server (only important for TLS)
366 struct MHD_Daemon *daemon;
369 * Optional proxy certificate used
371 struct ProxyGNSCertificate *proxy_cert;
376 struct GNUNET_SCHEDULER_Task *httpd_task;
379 * is this an ssl daemon?
386 /* ***************** Datastructures for Socks handling **************** */
395 * We're waiting to get the client hello.
400 * We're waiting to get the initial request.
405 * We are currently resolving the destination.
410 * We're in transfer mode.
412 SOCKS5_DATA_TRANSFER,
415 * Finish writing the write buffer, then clean up.
417 SOCKS5_WRITE_THEN_CLEANUP,
420 * Socket has been passed to MHD, do not close it anymore.
422 SOCKS5_SOCKET_WITH_MHD,
425 * We've started receiving upload data from MHD.
427 SOCKS5_SOCKET_UPLOAD_STARTED,
430 * We've finished receiving upload data from MHD.
432 SOCKS5_SOCKET_UPLOAD_DONE,
435 * We've finished uploading data via CURL and can now download.
437 SOCKS5_SOCKET_DOWNLOAD_STARTED,
440 * We've finished receiving download data from cURL.
442 SOCKS5_SOCKET_DOWNLOAD_DONE
449 struct HttpResponseHeader
454 struct HttpResponseHeader *next;
459 struct HttpResponseHeader *prev;
473 * A structure for socks requests
481 struct Socks5Request *next;
486 struct Socks5Request *prev;
491 struct GNUNET_NETWORK_Handle *sock;
494 * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
496 struct GNUNET_GNS_LookupWithTldRequest *gns_lookup;
499 * Client socket read task
501 struct GNUNET_SCHEDULER_Task *rtask;
504 * Client socket write task
506 struct GNUNET_SCHEDULER_Task *wtask;
511 struct GNUNET_SCHEDULER_Task *timeout_task;
516 char rbuf[SOCKS_BUFFERSIZE];
521 char wbuf[SOCKS_BUFFERSIZE];
524 * Buffer we use for moving data between MHD and curl (in both directions).
526 char io_buf[IO_BUFFERSIZE];
529 * MHD HTTP instance handling this request, NULL for none.
531 struct MhdHttpList *hd;
534 * MHD connection for this request.
536 struct MHD_Connection *con;
539 * MHD response object for this request.
541 struct MHD_Response *response;
544 * the domain name to server (only important for TLS)
549 * DNS Legacy Host Name as given by GNS, NULL if not given.
554 * Payload of the DANE records encountered.
556 char *dane_data[MAX_DANES + 1];
569 * HTTP request headers for the curl request.
571 struct curl_slist *headers;
574 * DNS->IP mappings resolved through GNS
576 struct curl_slist *hosts;
579 * HTTP response code to give to MHD for the response.
581 unsigned int response_code;
584 * Number of bytes in @e dane_data.
586 int dane_data_len[MAX_DANES + 1];
589 * Number of entries used in @e dane_data_len
592 unsigned int num_danes;
595 * Number of bytes already in read buffer
600 * Number of bytes already in write buffer
605 * Number of bytes already in the IO buffer.
610 * Once known, what's the target address for the connection?
612 struct sockaddr_storage destination_address;
617 enum SocksPhase state;
620 * Desired destination port.
625 * Headers from response
627 struct HttpResponseHeader *header_head;
630 * Headers from response
632 struct HttpResponseHeader *header_tail;
635 * X.509 Certificate status
640 * Was the hostname resolved via GNS?
645 * This is (probably) a TLS connection
650 * Did we suspend MHD processing?
655 * Did we pause CURL processing?
662 /* *********************** Globals **************************** */
665 * The address to bind to
667 static in_addr_t address;
670 * The IPv6 address to bind to
672 static struct in6_addr address6;
675 * The port the proxy is running on (default 7777)
677 static uint16_t port = GNUNET_GNS_PROXY_PORT;
680 * The CA file (pem) to use for the proxy CA
682 static char *cafile_opt;
685 * The listen socket of the proxy for IPv4
687 static struct GNUNET_NETWORK_Handle *lsock4;
690 * The listen socket of the proxy for IPv6
692 static struct GNUNET_NETWORK_Handle *lsock6;
695 * The listen task ID for IPv4
697 static struct GNUNET_SCHEDULER_Task * ltask4;
700 * The listen task ID for IPv6
702 static struct GNUNET_SCHEDULER_Task * ltask6;
705 * The cURL download task (curl multi API).
707 static struct GNUNET_SCHEDULER_Task * curl_download_task;
710 * The cURL multi handle
712 static CURLM *curl_multi;
715 * Handle to the GNS service
717 static struct GNUNET_GNS_Handle *gns_handle;
722 static int disable_v6;
725 * DLL for http/https daemons
727 static struct MhdHttpList *mhd_httpd_head;
730 * DLL for http/https daemons
732 static struct MhdHttpList *mhd_httpd_tail;
735 * Daemon for HTTP (we have one per X.509 certificate, and then one for
736 * all HTTP connections; this is the one for HTTP, not HTTPS).
738 static struct MhdHttpList *httpd;
741 * DLL of active socks requests.
743 static struct Socks5Request *s5r_head;
746 * DLL of active socks requests.
748 static struct Socks5Request *s5r_tail;
751 * The CA for X.509 certificate generation
753 static struct ProxyCA proxy_ca;
756 * Response we return on cURL failures.
758 static struct MHD_Response *curl_failure_response;
763 static const struct GNUNET_CONFIGURATION_Handle *cfg;
766 /* ************************* Global helpers ********************* */
770 * Run MHD now, we have extra data ready for the callback.
772 * @param hd the daemon to run now.
775 run_mhd_now (struct MhdHttpList *hd);
779 * Clean up s5r handles.
781 * @param s5r the handle to destroy
784 cleanup_s5r (struct Socks5Request *s5r)
786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
787 "Cleaning up socks request\n");
788 if (NULL != s5r->curl)
790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
791 "Cleaning up cURL handle\n");
792 curl_multi_remove_handle (curl_multi,
794 curl_easy_cleanup (s5r->curl);
799 s5r->suspended = GNUNET_NO;
800 MHD_resume_connection (s5r->con);
802 curl_slist_free_all (s5r->headers);
803 if (NULL != s5r->hosts)
805 curl_slist_free_all (s5r->hosts);
807 if ( (NULL != s5r->response) &&
808 (curl_failure_response != s5r->response) )
810 MHD_destroy_response (s5r->response);
811 s5r->response = NULL;
813 if (NULL != s5r->rtask)
815 GNUNET_SCHEDULER_cancel (s5r->rtask);
818 if (NULL != s5r->timeout_task)
820 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
821 s5r->timeout_task = NULL;
823 if (NULL != s5r->wtask)
825 GNUNET_SCHEDULER_cancel (s5r->wtask);
828 if (NULL != s5r->gns_lookup)
830 GNUNET_GNS_lookup_with_tld_cancel (s5r->gns_lookup);
831 s5r->gns_lookup = NULL;
833 if (NULL != s5r->sock)
835 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
836 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
838 GNUNET_NETWORK_socket_close (s5r->sock);
841 GNUNET_CONTAINER_DLL_remove (s5r_head,
844 GNUNET_free_non_null (s5r->domain);
845 GNUNET_free_non_null (s5r->leho);
846 GNUNET_free_non_null (s5r->url);
847 for (unsigned int i=0;i<s5r->num_danes;i++)
848 GNUNET_free (s5r->dane_data[i]);
853 /* ************************* HTTP handling with cURL *********************** */
856 curl_download_prepare ();
860 * Callback for MHD response generation. This function is called from
861 * MHD whenever MHD expects to get data back. Copies data from the
862 * io_buf, if available.
864 * @param cls closure with our `struct Socks5Request`
865 * @param pos in buffer
866 * @param buf where to copy data
867 * @param max available space in @a buf
868 * @return number of bytes written to @a buf
871 mhd_content_cb (void *cls,
876 struct Socks5Request *s5r = cls;
877 size_t bytes_to_copy;
879 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
880 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
882 /* we're still not done with the upload, do not yet
883 start the download, the IO buffer is still full
885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
886 "Pausing MHD download %s%s, not yet ready for download\n",
889 return 0; /* not yet ready for data download */
891 bytes_to_copy = GNUNET_MIN (max,
893 if ( (0 == bytes_to_copy) &&
894 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
896 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
897 "Pausing MHD download %s%s, no data available\n",
900 if (NULL != s5r->curl)
902 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
903 "Continuing CURL interaction for %s%s\n",
906 if (GNUNET_YES == s5r->curl_paused)
908 s5r->curl_paused = GNUNET_NO;
909 curl_easy_pause (s5r->curl,
912 curl_download_prepare ();
914 if (GNUNET_NO == s5r->suspended)
916 MHD_suspend_connection (s5r->con);
917 s5r->suspended = GNUNET_YES;
919 return 0; /* more data later */
921 if ( (0 == bytes_to_copy) &&
922 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
925 "Completed MHD download %s%s\n",
928 return MHD_CONTENT_READER_END_OF_STREAM;
930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
931 "Writing %llu/%llu bytes to %s%s\n",
932 (unsigned long long) bytes_to_copy,
933 (unsigned long long) s5r->io_len,
939 memmove (s5r->io_buf,
940 &s5r->io_buf[bytes_to_copy],
941 s5r->io_len - bytes_to_copy);
942 s5r->io_len -= bytes_to_copy;
943 if ( (NULL != s5r->curl) &&
944 (GNUNET_YES == s5r->curl_paused) )
946 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
947 "Continuing CURL interaction for %s%s\n",
950 s5r->curl_paused = GNUNET_NO;
951 curl_easy_pause (s5r->curl,
954 return bytes_to_copy;
959 * Check that the website has presented us with a valid X.509 certificate.
960 * The certificate must either match the domain name or the LEHO name
961 * (or, if available, the TLSA record).
963 * @param s5r request to check for.
964 * @return #GNUNET_OK if the certificate is valid
967 check_ssl_certificate (struct Socks5Request *s5r)
969 unsigned int cert_list_size;
970 const gnutls_datum_t *chainp;
971 const struct curl_tlssessioninfo *tlsinfo;
972 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
974 gnutls_x509_crt_t x509_cert;
978 s5r->ssl_checked = GNUNET_YES;
979 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
980 "Checking X.509 certificate\n");
982 curl_easy_getinfo (s5r->curl,
983 CURLINFO_TLS_SESSION,
985 return GNUNET_SYSERR;
986 if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
988 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
989 _("Unsupported CURL TLS backend %d\n"),
991 return GNUNET_SYSERR;
993 chainp = gnutls_certificate_get_peers (tlsinfo->internals,
996 (0 == cert_list_size) )
997 return GNUNET_SYSERR;
999 size = sizeof (certdn);
1000 /* initialize an X.509 certificate structure. */
1001 gnutls_x509_crt_init (&x509_cert);
1002 gnutls_x509_crt_import (x509_cert,
1004 GNUTLS_X509_FMT_DER);
1006 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
1007 GNUTLS_OID_X520_COMMON_NAME,
1008 0, /* the first and only one */
1009 0 /* no DER encoding */,
1013 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1014 _("Failed to fetch CN from cert: %s\n"),
1015 gnutls_strerror(rc));
1016 gnutls_x509_crt_deinit (x509_cert);
1017 return GNUNET_SYSERR;
1019 /* check for TLSA/DANE records */
1020 #if HAVE_GNUTLS_DANE
1021 if (0 != s5r->num_danes)
1023 dane_state_t dane_state;
1024 dane_query_t dane_query;
1025 unsigned int verify;
1027 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
1028 if (0 != (rc = dane_state_init (&dane_state,
1029 #ifdef DANE_F_IGNORE_DNSSEC
1030 DANE_F_IGNORE_DNSSEC |
1032 DANE_F_IGNORE_LOCAL_RESOLVER)))
1034 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1035 _("Failed to initialize DANE: %s\n"),
1037 gnutls_x509_crt_deinit (x509_cert);
1038 return GNUNET_SYSERR;
1040 s5r->dane_data[s5r->num_danes] = NULL;
1041 s5r->dane_data_len[s5r->num_danes] = 0;
1042 if (0 != (rc = dane_raw_tlsa (dane_state,
1049 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1050 _("Failed to parse DANE record: %s\n"),
1052 dane_state_deinit (dane_state);
1053 gnutls_x509_crt_deinit (x509_cert);
1054 return GNUNET_SYSERR;
1056 if (0 != (rc = dane_verify_crt_raw (dane_state,
1059 gnutls_certificate_type_get (tlsinfo->internals),
1064 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1065 _("Failed to verify TLS connection using DANE: %s\n"),
1067 dane_query_deinit (dane_query);
1068 dane_state_deinit (dane_state);
1069 gnutls_x509_crt_deinit (x509_cert);
1070 return GNUNET_SYSERR;
1074 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1075 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
1077 dane_query_deinit (dane_query);
1078 dane_state_deinit (dane_state);
1079 gnutls_x509_crt_deinit (x509_cert);
1080 return GNUNET_SYSERR;
1082 dane_query_deinit (dane_query);
1083 dane_state_deinit (dane_state);
1089 /* try LEHO or ordinary domain name X509 verification */
1091 if (NULL != s5r->leho)
1095 if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
1098 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1099 _("TLS certificate subject name (%s) does not match `%s': %d\n"),
1103 gnutls_x509_crt_deinit (x509_cert);
1104 return GNUNET_SYSERR;
1109 /* we did not even have the domain name!? */
1111 return GNUNET_SYSERR;
1114 gnutls_x509_crt_deinit (x509_cert);
1120 * We're getting an HTTP response header from cURL. Convert it to the
1121 * MHD response headers. Mostly copies the headers, but makes special
1122 * adjustments to "Set-Cookie" and "Location" headers as those may need
1123 * to be changed from the LEHO to the domain the browser expects.
1125 * @param buffer curl buffer with a single line of header data; not 0-terminated!
1126 * @param size curl blocksize
1127 * @param nmemb curl blocknumber
1128 * @param cls our `struct Socks5Request *`
1129 * @return size of processed bytes
1132 curl_check_hdr (void *buffer,
1137 struct Socks5Request *s5r = cls;
1138 struct HttpResponseHeader *header;
1139 size_t bytes = size * nmemb;
1141 const char *hdr_type;
1142 const char *cookie_domain;
1144 char *new_cookie_hdr;
1147 size_t delta_cdomain;
1151 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1152 "Receiving HTTP response header from CURL\n");
1153 /* first, check TLS certificate */
1154 if ( (GNUNET_YES != s5r->ssl_checked) &&
1155 (GNUNET_YES == s5r->is_tls))
1156 //(HTTPS_PORT == s5r->port))
1158 if (GNUNET_OK != check_ssl_certificate (s5r))
1161 ndup = GNUNET_strndup (buffer,
1163 hdr_type = strtok (ndup,
1165 if (NULL == hdr_type)
1170 hdr_val = strtok (NULL,
1172 if (NULL == hdr_val)
1177 if (' ' == *hdr_val)
1180 /* custom logic for certain header types */
1181 new_cookie_hdr = NULL;
1182 if ( (NULL != s5r->leho) &&
1183 (0 == strcasecmp (hdr_type,
1184 MHD_HTTP_HEADER_SET_COOKIE)) )
1187 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1188 strlen (s5r->domain) + 1);
1190 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1191 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1193 if ( (0 == strncasecmp (tok,
1195 strlen (" domain"))) &&
1196 (GNUNET_NO == domain_matched) )
1198 domain_matched = GNUNET_YES;
1199 cookie_domain = tok + strlen (" domain") + 1;
1200 if (strlen (cookie_domain) < strlen (s5r->leho))
1202 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1203 if (0 == strcasecmp (cookie_domain,
1204 s5r->leho + delta_cdomain))
1206 offset += sprintf (new_cookie_hdr + offset,
1212 else if (0 == strcmp (cookie_domain,
1215 offset += sprintf (new_cookie_hdr + offset,
1220 else if ( ('.' == cookie_domain[0]) &&
1221 (0 == strcmp (&cookie_domain[1],
1224 offset += sprintf (new_cookie_hdr + offset,
1229 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1230 _("Cookie domain `%s' supplied by server is invalid\n"),
1233 GNUNET_memcpy (new_cookie_hdr + offset,
1236 offset += strlen (tok);
1237 new_cookie_hdr[offset++] = ';';
1239 hdr_val = new_cookie_hdr;
1242 new_location = NULL;
1243 if (0 == strcasecmp (MHD_HTTP_HEADER_TRANSFER_ENCODING,
1246 /* Ignore transfer encoding, set automatically by MHD if required */
1249 if ((0 == strcasecmp (MHD_HTTP_HEADER_LOCATION,
1254 GNUNET_asprintf (&leho_host,
1255 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1259 if (0 == strncmp (leho_host,
1261 strlen (leho_host)))
1263 GNUNET_asprintf (&new_location,
1265 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1269 hdr_val + strlen (leho_host));
1270 hdr_val = new_location;
1272 GNUNET_free (leho_host);
1274 if (0 == strcasecmp (MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1279 GNUNET_asprintf (&leho_host,
1280 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1284 if (0 == strncmp (leho_host,
1286 strlen (leho_host)))
1288 GNUNET_asprintf (&new_location,
1290 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1294 hdr_val = new_location;
1296 GNUNET_free (leho_host);
1299 /* MHD does not allow certain characters in values, remove those */
1300 if (NULL != (tok = strchr (hdr_val, '\n')))
1302 if (NULL != (tok = strchr (hdr_val, '\r')))
1304 if (NULL != (tok = strchr (hdr_val, '\t')))
1306 if (0 != strlen (hdr_val)) /* Rely in MHD to set those */
1308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1309 "Adding header %s: %s to MHD response\n",
1312 header = GNUNET_new (struct HttpResponseHeader);
1313 header->type = GNUNET_strdup (hdr_type);
1314 header->value = GNUNET_strdup (hdr_val);
1315 GNUNET_CONTAINER_DLL_insert (s5r->header_head,
1321 GNUNET_free_non_null (new_cookie_hdr);
1322 GNUNET_free_non_null (new_location);
1328 * Create an MHD response object in @a s5r matching the
1329 * information we got from curl.
1331 * @param s5r the request for which we convert the response
1332 * @return #GNUNET_OK on success, #GNUNET_SYSERR if response was
1333 * already initialized before
1336 create_mhd_response_from_s5r (struct Socks5Request *s5r)
1339 double content_length;
1341 if (NULL != s5r->response)
1343 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1344 "Response already set!\n");
1345 return GNUNET_SYSERR;
1348 GNUNET_break (CURLE_OK ==
1349 curl_easy_getinfo (s5r->curl,
1350 CURLINFO_RESPONSE_CODE,
1352 GNUNET_break (CURLE_OK ==
1353 curl_easy_getinfo (s5r->curl,
1354 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
1356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1357 "Creating MHD response with code %d and size %d for %s%s\n",
1359 (int) content_length,
1362 s5r->response_code = resp_code;
1363 s5r->response = MHD_create_response_from_callback ((-1 == content_length)
1370 for (struct HttpResponseHeader *header = s5r->header_head;
1372 header = header->next)
1374 if (0 == strcasecmp (header->type,
1375 MHD_HTTP_HEADER_CONTENT_LENGTH))
1376 continue; /* MHD won't let us mess with those, for good reason */
1377 if ( (0 == strcasecmp (header->type,
1378 MHD_HTTP_HEADER_TRANSFER_ENCODING)) &&
1379 ( (0 == strcasecmp (header->value,
1381 (0 == strcasecmp (header->value,
1383 continue; /* MHD won't let us mess with those, for good reason */
1385 MHD_add_response_header (s5r->response,
1390 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1391 "Failed to add header `%s:%s'\n",
1396 /* force connection to be closed after each request, as we
1397 do not support HTTP pipelining (yet, FIXME!) */
1398 /*GNUNET_break (MHD_YES ==
1399 MHD_add_response_header (s5r->response,
1400 MHD_HTTP_HEADER_CONNECTION,
1402 MHD_resume_connection (s5r->con);
1403 s5r->suspended = GNUNET_NO;
1409 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1410 * it available to MHD.
1412 * @param ptr pointer to the data
1413 * @param size number of blocks of data
1414 * @param nmemb blocksize
1415 * @param ctx our `struct Socks5Request *`
1416 * @return number of bytes handled
1419 curl_download_cb (void *ptr,
1424 struct Socks5Request *s5r = ctx;
1425 size_t total = size * nmemb;
1427 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1428 "Receiving %ux%u bytes for `%s%s' from cURL to download\n",
1429 (unsigned int) size,
1430 (unsigned int) nmemb,
1433 if (NULL == s5r->response)
1434 GNUNET_assert (GNUNET_OK ==
1435 create_mhd_response_from_s5r (s5r));
1436 if ( (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) &&
1439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1440 "Previous upload finished... starting DOWNLOAD.\n");
1441 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1443 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1444 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1446 /* we're still not done with the upload, do not yet
1447 start the download, the IO buffer is still full
1448 with upload data. */
1449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450 "Pausing CURL download `%s%s', waiting for UPLOAD to finish\n",
1453 s5r->curl_paused = GNUNET_YES;
1454 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1456 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1458 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1459 "Pausing CURL `%s%s' download, not enough space %llu %llu %llu\n",
1462 (unsigned long long) sizeof (s5r->io_buf),
1463 (unsigned long long) s5r->io_len,
1464 (unsigned long long) total);
1465 s5r->curl_paused = GNUNET_YES;
1466 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1468 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1471 s5r->io_len += total;
1472 if (GNUNET_YES == s5r->suspended)
1474 MHD_resume_connection (s5r->con);
1475 s5r->suspended = GNUNET_NO;
1477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1478 "Received %llu bytes of payload via cURL from %s\n",
1479 (unsigned long long) total,
1481 if (s5r->io_len == total)
1482 run_mhd_now (s5r->hd);
1488 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1489 * to make it available to MHD.
1491 * @param buf where to write the data
1492 * @param size number of bytes per member
1493 * @param nmemb number of members available in @a buf
1494 * @param cls our `struct Socks5Request` that generated the data
1495 * @return number of bytes copied to @a buf
1498 curl_upload_cb (void *buf,
1503 struct Socks5Request *s5r = cls;
1504 size_t len = size * nmemb;
1507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1508 "Receiving %ux%u bytes for `%s%s' from cURL to upload\n",
1509 (unsigned int) size,
1510 (unsigned int) nmemb,
1514 if ( (0 == s5r->io_len) &&
1515 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1517 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1518 "Pausing CURL UPLOAD %s%s, need more data\n",
1521 return CURL_READFUNC_PAUSE;
1523 if ( (0 == s5r->io_len) &&
1524 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1526 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1527 if (GNUNET_YES == s5r->curl_paused)
1529 s5r->curl_paused = GNUNET_NO;
1530 curl_easy_pause (s5r->curl,
1533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1534 "Completed CURL UPLOAD %s%s\n",
1537 return 0; /* upload finished, can now download */
1539 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
1540 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1543 return CURL_READFUNC_ABORT;
1545 to_copy = GNUNET_MIN (s5r->io_len,
1550 memmove (s5r->io_buf,
1551 &s5r->io_buf[to_copy],
1552 s5r->io_len - to_copy);
1553 s5r->io_len -= to_copy;
1554 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1555 run_mhd_now (s5r->hd); /* got more space for upload now */
1560 /* ************************** main loop of cURL interaction ****************** */
1564 * Task that is run when we are ready to receive more data
1567 * @param cls closure
1570 curl_task_download (void *cls);
1574 * Ask cURL for the select() sets and schedule cURL operations.
1577 curl_download_prepare ()
1584 struct GNUNET_NETWORK_FDSet *grs;
1585 struct GNUNET_NETWORK_FDSet *gws;
1587 struct GNUNET_TIME_Relative rtime;
1589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1590 "Scheduling CURL interaction\n");
1591 if (NULL != curl_download_task)
1593 GNUNET_SCHEDULER_cancel (curl_download_task);
1594 curl_download_task = NULL;
1600 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi,
1606 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1607 "%s failed at %s:%d: `%s'\n",
1608 "curl_multi_fdset", __FILE__, __LINE__,
1609 curl_multi_strerror (mret));
1613 GNUNET_break (CURLM_OK ==
1614 curl_multi_timeout (curl_multi,
1617 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1619 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1623 grs = GNUNET_NETWORK_fdset_create ();
1624 gws = GNUNET_NETWORK_fdset_create ();
1625 GNUNET_NETWORK_fdset_copy_native (grs,
1628 GNUNET_NETWORK_fdset_copy_native (gws,
1631 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1635 &curl_task_download,
1637 GNUNET_NETWORK_fdset_destroy (gws);
1638 GNUNET_NETWORK_fdset_destroy (grs);
1642 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1643 &curl_task_download,
1650 * Task that is run when we are ready to receive more data from curl.
1652 * @param cls closure, NULL
1655 curl_task_download (void *cls)
1659 struct CURLMsg *msg;
1661 struct Socks5Request *s5r;
1663 curl_download_task = NULL;
1664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1665 "Running CURL interaction\n");
1669 mret = curl_multi_perform (curl_multi,
1671 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1672 "Checking CURL multi status: %d\n",
1674 while (NULL != (msg = curl_multi_info_read (curl_multi,
1677 GNUNET_break (CURLE_OK ==
1678 curl_easy_getinfo (msg->easy_handle,
1689 /* documentation says this is not used */
1693 switch (msg->data.result)
1696 case CURLE_GOT_NOTHING:
1697 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1698 "CURL download %s%s completed.\n",
1701 if (NULL == s5r->response)
1703 GNUNET_assert (GNUNET_OK ==
1704 create_mhd_response_from_s5r (s5r));
1706 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1707 if (GNUNET_YES == s5r->suspended)
1709 MHD_resume_connection (s5r->con);
1710 s5r->suspended = GNUNET_NO;
1712 run_mhd_now (s5r->hd);
1715 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1716 "Download curl %s%s failed: %s\n",
1719 curl_easy_strerror (msg->data.result));
1720 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1721 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1722 if (GNUNET_YES == s5r->suspended)
1724 MHD_resume_connection (s5r->con);
1725 s5r->suspended = GNUNET_NO;
1727 run_mhd_now (s5r->hd);
1730 if (NULL == s5r->response)
1731 s5r->response = curl_failure_response;
1734 /* documentation says this is not used */
1738 /* unexpected status code */
1743 } while (mret == CURLM_CALL_MULTI_PERFORM);
1744 if (CURLM_OK != mret)
1745 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1746 "%s failed at %s:%d: `%s'\n",
1747 "curl_multi_perform", __FILE__, __LINE__,
1748 curl_multi_strerror (mret));
1751 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1752 "Suspending cURL multi loop, no more events pending\n");
1753 if (NULL != curl_download_task)
1755 GNUNET_SCHEDULER_cancel (curl_download_task);
1756 curl_download_task = NULL;
1758 return; /* nothing more in progress */
1760 curl_download_prepare ();
1764 /* ********************************* MHD response generation ******************* */
1768 * Read HTTP request header field from the request. Copies the fields
1769 * over to the 'headers' that will be given to curl. However, 'Host'
1770 * is substituted with the LEHO if present. We also change the
1771 * 'Connection' header value to "close" as the proxy does not support
1774 * @param cls our `struct Socks5Request`
1775 * @param kind value kind
1776 * @param key field key
1777 * @param value field value
1778 * @return #MHD_YES to continue to iterate
1781 con_val_iter (void *cls,
1782 enum MHD_ValueKind kind,
1786 struct Socks5Request *s5r = cls;
1789 if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST,
1791 (NULL != s5r->leho) )
1793 GNUNET_asprintf (&hdr,
1797 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1798 "Adding HEADER `%s' to HTTP request\n",
1800 s5r->headers = curl_slist_append (s5r->headers,
1808 * Main MHD callback for handling requests.
1811 * @param con MHD connection handle
1812 * @param url the url in the request
1813 * @param meth the HTTP method used ("GET", "PUT", etc.)
1814 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1815 * @param upload_data the data being uploaded (excluding HEADERS,
1816 * for a POST that fits into memory and that is encoded
1817 * with a supported encoding, the POST data will NOT be
1818 * given in upload_data and is instead available as
1819 * part of MHD_get_connection_values; very large POST
1820 * data *will* be made available incrementally in
1822 * @param upload_data_size set initially to the size of the
1823 * @a upload_data provided; the method must update this
1824 * value to the number of bytes NOT processed;
1825 * @param con_cls pointer to location where we store the `struct Request`
1826 * @return #MHD_YES if the connection was handled successfully,
1827 * #MHD_NO if the socket must be closed due to a serious
1828 * error while handling the request
1831 create_response (void *cls,
1832 struct MHD_Connection *con,
1836 const char *upload_data,
1837 size_t *upload_data_size,
1840 struct Socks5Request *s5r = *con_cls;
1842 char ipstring[INET6_ADDRSTRLEN];
1843 char ipaddr[INET6_ADDRSTRLEN + 2];
1844 const struct sockaddr *sa;
1845 const struct sockaddr_in *s4;
1846 const struct sockaddr_in6 *s6;
1856 /* Fresh connection. */
1857 if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
1859 /* first time here, initialize curl handle */
1862 sa = (const struct sockaddr *) &s5r->destination_address;
1863 switch (sa->sa_family)
1866 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1867 if (NULL == inet_ntop (AF_INET,
1875 GNUNET_snprintf (ipaddr,
1879 port = ntohs (s4->sin_port);
1882 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1883 if (NULL == inet_ntop (AF_INET6,
1891 GNUNET_snprintf (ipaddr,
1895 port = ntohs (s6->sin6_port);
1906 if (NULL == s5r->curl)
1907 s5r->curl = curl_easy_init ();
1908 if (NULL == s5r->curl)
1909 return MHD_queue_response (con,
1910 MHD_HTTP_INTERNAL_SERVER_ERROR,
1911 curl_failure_response);
1912 curl_easy_setopt (s5r->curl,
1913 CURLOPT_HEADERFUNCTION,
1915 curl_easy_setopt (s5r->curl,
1918 curl_easy_setopt (s5r->curl,
1919 CURLOPT_FOLLOWLOCATION,
1922 curl_easy_setopt (s5r->curl,
1925 curl_easy_setopt (s5r->curl,
1926 CURLOPT_CONNECTTIMEOUT,
1928 curl_easy_setopt (s5r->curl,
1931 curl_easy_setopt (s5r->curl,
1934 curl_easy_setopt (s5r->curl,
1935 CURLOPT_HTTP_CONTENT_DECODING,
1937 curl_easy_setopt (s5r->curl,
1940 curl_easy_setopt (s5r->curl,
1943 curl_easy_setopt (s5r->curl,
1947 * Pre-populate cache to resolve Hostname.
1948 * This is necessary as the DNS name in the CURLOPT_URL is used
1949 * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1951 if (NULL != s5r->leho)
1955 GNUNET_asprintf (&curl_hosts,
1960 s5r->hosts = curl_slist_append (NULL,
1962 curl_easy_setopt (s5r->curl,
1965 GNUNET_free (curl_hosts);
1969 GNUNET_asprintf (&curlurl,
1970 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1972 : "https://%s:%d%s",
1981 GNUNET_asprintf (&curlurl,
1982 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1984 : "https://%s:%d%s",
1989 curl_easy_setopt (s5r->curl,
1992 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1993 "Launching %s CURL interaction, fetching `%s'\n",
1994 (s5r->is_gns) ? "GNS" : "DNS",
1996 GNUNET_free (curlurl);
1997 if (0 == strcasecmp (meth,
1998 MHD_HTTP_METHOD_PUT))
2000 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
2001 curl_easy_setopt (s5r->curl,
2004 curl_easy_setopt (s5r->curl,
2005 CURLOPT_WRITEFUNCTION,
2007 curl_easy_setopt (s5r->curl,
2010 GNUNET_assert (CURLE_OK ==
2011 curl_easy_setopt (s5r->curl,
2012 CURLOPT_READFUNCTION,
2014 curl_easy_setopt (s5r->curl,
2019 long upload_size = 0;
2021 us = MHD_lookup_connection_value (con,
2023 MHD_HTTP_HEADER_CONTENT_LENGTH);
2024 if ( (1 == sscanf (us,
2027 (upload_size >= 0) )
2029 curl_easy_setopt (s5r->curl,
2035 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
2037 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
2038 curl_easy_setopt (s5r->curl,
2041 curl_easy_setopt (s5r->curl,
2042 CURLOPT_WRITEFUNCTION,
2044 curl_easy_setopt (s5r->curl,
2047 curl_easy_setopt (s5r->curl,
2048 CURLOPT_READFUNCTION,
2050 curl_easy_setopt (s5r->curl,
2058 us = MHD_lookup_connection_value (con,
2060 MHD_HTTP_HEADER_CONTENT_LENGTH);
2061 if ( (NULL != us) &&
2065 (upload_size >= 0) )
2067 curl_easy_setopt (s5r->curl,
2071 curl_easy_setopt (s5r->curl,
2077 else if (0 == strcasecmp (meth,
2078 MHD_HTTP_METHOD_HEAD))
2080 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2081 curl_easy_setopt (s5r->curl,
2085 else if (0 == strcasecmp (meth,
2086 MHD_HTTP_METHOD_OPTIONS))
2088 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2089 curl_easy_setopt (s5r->curl,
2090 CURLOPT_CUSTOMREQUEST,
2092 curl_easy_setopt (s5r->curl,
2093 CURLOPT_WRITEFUNCTION,
2095 curl_easy_setopt (s5r->curl,
2100 else if (0 == strcasecmp (meth,
2101 MHD_HTTP_METHOD_GET))
2103 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2104 curl_easy_setopt (s5r->curl,
2107 curl_easy_setopt (s5r->curl,
2108 CURLOPT_WRITEFUNCTION,
2110 curl_easy_setopt (s5r->curl,
2114 else if (0 == strcasecmp (meth,
2115 MHD_HTTP_METHOD_DELETE))
2117 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2118 curl_easy_setopt (s5r->curl,
2119 CURLOPT_CUSTOMREQUEST,
2121 curl_easy_setopt (s5r->curl,
2122 CURLOPT_WRITEFUNCTION,
2124 curl_easy_setopt (s5r->curl,
2130 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2131 _("Unsupported HTTP method `%s'\n"),
2133 curl_easy_cleanup (s5r->curl);
2138 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
2140 curl_easy_setopt (s5r->curl,
2141 CURLOPT_HTTP_VERSION,
2142 CURL_HTTP_VERSION_1_0);
2144 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
2146 curl_easy_setopt (s5r->curl,
2147 CURLOPT_HTTP_VERSION,
2148 CURL_HTTP_VERSION_1_1);
2152 curl_easy_setopt (s5r->curl,
2153 CURLOPT_HTTP_VERSION,
2154 CURL_HTTP_VERSION_NONE);
2157 if (GNUNET_YES == s5r->is_tls) //(HTTPS_PORT == s5r->port)
2159 curl_easy_setopt (s5r->curl,
2162 if (0 < s5r->num_danes)
2163 curl_easy_setopt (s5r->curl,
2164 CURLOPT_SSL_VERIFYPEER,
2167 curl_easy_setopt (s5r->curl,
2168 CURLOPT_SSL_VERIFYPEER,
2170 /* Disable cURL checking the hostname, as we will check ourselves
2171 as only we have the domain name or the LEHO or the DANE record */
2172 curl_easy_setopt (s5r->curl,
2173 CURLOPT_SSL_VERIFYHOST,
2178 curl_easy_setopt (s5r->curl,
2184 curl_multi_add_handle (curl_multi,
2188 curl_easy_cleanup (s5r->curl);
2192 MHD_get_connection_values (con,
2194 (MHD_KeyValueIterator) &con_val_iter,
2196 curl_easy_setopt (s5r->curl,
2199 curl_download_prepare ();
2203 /* continuing to process request */
2204 if (0 != *upload_data_size)
2206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2207 "Processing %u bytes UPLOAD\n",
2208 (unsigned int) *upload_data_size);
2210 /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else
2211 * upload callback is not called!
2213 curl_easy_setopt (s5r->curl,
2214 CURLOPT_POSTFIELDSIZE,
2217 left = GNUNET_MIN (*upload_data_size,
2218 sizeof (s5r->io_buf) - s5r->io_len);
2219 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
2222 s5r->io_len += left;
2223 *upload_data_size -= left;
2224 GNUNET_assert (NULL != s5r->curl);
2225 if (GNUNET_YES == s5r->curl_paused)
2227 s5r->curl_paused = GNUNET_NO;
2228 curl_easy_pause (s5r->curl,
2233 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
2235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2236 "Finished processing UPLOAD\n");
2237 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
2239 if (NULL == s5r->response)
2241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2242 "Waiting for HTTP response for %s%s...\n",
2245 MHD_suspend_connection (con);
2246 s5r->suspended = GNUNET_YES;
2249 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2250 "Queueing response for %s%s with MHD\n",
2253 run_mhd_now (s5r->hd);
2254 return MHD_queue_response (con,
2260 /* ******************** MHD HTTP setup and event loop ******************** */
2264 * Function called when MHD decides that we are done with a request.
2267 * @param connection connection handle
2268 * @param con_cls value as set by the last call to
2269 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2270 * @param toe reason for request termination (ignored)
2273 mhd_completed_cb (void *cls,
2274 struct MHD_Connection *connection,
2276 enum MHD_RequestTerminationCode toe)
2278 struct Socks5Request *s5r = *con_cls;
2282 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
2283 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2284 "MHD encountered error handling request: %d\n",
2286 if (NULL != s5r->curl)
2288 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2289 "Removing cURL handle (MHD interaction complete)\n");
2290 curl_multi_remove_handle (curl_multi,
2292 curl_slist_free_all (s5r->headers);
2293 s5r->headers = NULL;
2294 curl_easy_reset (s5r->curl);
2298 curl_download_prepare ();
2300 if ( (NULL != s5r->response) &&
2301 (curl_failure_response != s5r->response) )
2302 MHD_destroy_response (s5r->response);
2303 for (struct HttpResponseHeader *header = s5r->header_head;
2305 header = s5r->header_head)
2307 GNUNET_CONTAINER_DLL_remove (s5r->header_head,
2310 GNUNET_free (header->type);
2311 GNUNET_free (header->value);
2312 GNUNET_free (header);
2314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2315 "Finished request for %s\n",
2317 GNUNET_free (s5r->url);
2318 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2320 s5r->response = NULL;
2326 * Function called when MHD connection is opened or closed.
2329 * @param connection connection handle
2330 * @param con_cls value as set by the last call to
2331 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2332 * @param toe connection notification type
2335 mhd_connection_cb (void *cls,
2336 struct MHD_Connection *connection,
2338 enum MHD_ConnectionNotificationCode cnc)
2340 struct Socks5Request *s5r;
2341 const union MHD_ConnectionInfo *ci;
2346 case MHD_CONNECTION_NOTIFY_STARTED:
2347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
2348 ci = MHD_get_connection_info (connection,
2349 MHD_CONNECTION_INFO_CONNECTION_FD);
2355 sock = ci->connect_fd;
2356 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
2358 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
2360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2361 "Context set...\n");
2362 s5r->ssl_checked = GNUNET_NO;
2368 case MHD_CONNECTION_NOTIFY_CLOSED:
2369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2370 "Connection closed... cleaning up\n");
2374 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2375 "Connection stale!\n");
2379 curl_download_prepare ();
2388 * Function called when MHD first processes an incoming connection.
2389 * Gives us the respective URI information.
2391 * We use this to associate the `struct MHD_Connection` with our
2392 * internal `struct Socks5Request` data structure (by checking
2393 * for matching sockets).
2395 * @param cls the HTTP server handle (a `struct MhdHttpList`)
2396 * @param url the URL that is being requested
2397 * @param connection MHD connection object for the request
2398 * @return the `struct Socks5Request` that this @a connection is for
2401 mhd_log_callback (void *cls,
2403 struct MHD_Connection *connection)
2405 struct Socks5Request *s5r;
2406 const union MHD_ConnectionInfo *ci;
2408 ci = MHD_get_connection_info (connection,
2409 MHD_CONNECTION_INFO_SOCKET_CONTEXT);
2410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
2416 s5r = ci->socket_context;
2417 if (NULL != s5r->url)
2422 s5r->url = GNUNET_strdup (url);
2423 if (NULL != s5r->timeout_task)
2425 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
2426 s5r->timeout_task = NULL;
2428 GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD);
2434 * Kill the given MHD daemon.
2436 * @param hd daemon to stop
2439 kill_httpd (struct MhdHttpList *hd)
2441 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
2444 GNUNET_free_non_null (hd->domain);
2445 MHD_stop_daemon (hd->daemon);
2446 if (NULL != hd->httpd_task)
2448 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2449 hd->httpd_task = NULL;
2451 GNUNET_free_non_null (hd->proxy_cert);
2459 * Task run whenever HTTP server is idle for too long. Kill it.
2461 * @param cls the `struct MhdHttpList *`
2464 kill_httpd_task (void *cls)
2466 struct MhdHttpList *hd = cls;
2468 hd->httpd_task = NULL;
2474 * Task run whenever HTTP server operations are pending.
2476 * @param cls the `struct MhdHttpList *` of the daemon that is being run
2479 do_httpd (void *cls);
2483 * Schedule MHD. This function should be called initially when an
2484 * MHD is first getting its client socket, and will then automatically
2485 * always be called later whenever there is work to be done.
2487 * @param hd the daemon to schedule
2490 schedule_httpd (struct MhdHttpList *hd)
2495 struct GNUNET_NETWORK_FDSet *wrs;
2496 struct GNUNET_NETWORK_FDSet *wws;
2499 MHD_UNSIGNED_LONG_LONG timeout;
2500 struct GNUNET_TIME_Relative tv;
2507 MHD_get_fdset (hd->daemon,
2516 haveto = MHD_get_timeout (hd->daemon,
2518 if (MHD_YES == haveto)
2519 tv.rel_value_us = (uint64_t) timeout * 1000LL;
2521 tv = GNUNET_TIME_UNIT_FOREVER_REL;
2524 wrs = GNUNET_NETWORK_fdset_create ();
2525 wws = GNUNET_NETWORK_fdset_create ();
2526 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
2527 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
2534 if (NULL != hd->httpd_task)
2536 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2537 hd->httpd_task = NULL;
2539 if ( (MHD_YES != haveto) &&
2543 /* daemon is idle, kill after timeout */
2544 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
2551 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2556 GNUNET_NETWORK_fdset_destroy (wrs);
2558 GNUNET_NETWORK_fdset_destroy (wws);
2563 * Task run whenever HTTP server operations are pending.
2565 * @param cls the `struct MhdHttpList` of the daemon that is being run
2568 do_httpd (void *cls)
2570 struct MhdHttpList *hd = cls;
2572 hd->httpd_task = NULL;
2573 MHD_run (hd->daemon);
2574 schedule_httpd (hd);
2579 * Run MHD now, we have extra data ready for the callback.
2581 * @param hd the daemon to run now.
2584 run_mhd_now (struct MhdHttpList *hd)
2586 if (NULL != hd->httpd_task)
2587 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2588 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
2594 * Read file in filename
2596 * @param filename file to read
2597 * @param size pointer where filesize is stored
2598 * @return NULL on error
2601 load_file (const char* filename,
2608 GNUNET_DISK_file_size (filename,
2613 if (fsize > MAX_PEM_SIZE)
2615 *size = (unsigned int) fsize;
2616 buffer = GNUNET_malloc (*size);
2618 GNUNET_DISK_fn_read (filename,
2622 GNUNET_free (buffer);
2630 * Load PEM key from file
2632 * @param key where to store the data
2633 * @param keyfile path to the PEM file
2634 * @return #GNUNET_OK on success
2637 load_key_from_file (gnutls_x509_privkey_t key,
2638 const char* keyfile)
2640 gnutls_datum_t key_data;
2643 key_data.data = load_file (keyfile,
2645 if (NULL == key_data.data)
2646 return GNUNET_SYSERR;
2647 ret = gnutls_x509_privkey_import (key, &key_data,
2648 GNUTLS_X509_FMT_PEM);
2649 if (GNUTLS_E_SUCCESS != ret)
2651 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2652 _("Unable to import private key from file `%s'\n"),
2655 GNUNET_free_non_null (key_data.data);
2656 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2661 * Load cert from file
2663 * @param crt struct to store data in
2664 * @param certfile path to pem file
2665 * @return #GNUNET_OK on success
2668 load_cert_from_file (gnutls_x509_crt_t crt,
2669 const char* certfile)
2671 gnutls_datum_t cert_data;
2674 cert_data.data = load_file (certfile,
2676 if (NULL == cert_data.data)
2677 return GNUNET_SYSERR;
2678 ret = gnutls_x509_crt_import (crt,
2680 GNUTLS_X509_FMT_PEM);
2681 if (GNUTLS_E_SUCCESS != ret)
2683 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2684 _("Unable to import certificate from `%s'\n"),
2687 GNUNET_free_non_null (cert_data.data);
2688 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2693 * Generate new certificate for specific name
2695 * @param name the subject name to generate a cert for
2696 * @return a struct holding the PEM data, NULL on error
2698 static struct ProxyGNSCertificate *
2699 generate_gns_certificate (const char *name)
2701 unsigned int serial;
2702 size_t key_buf_size;
2703 size_t cert_buf_size;
2704 gnutls_x509_crt_t request;
2707 struct ProxyGNSCertificate *pgc;
2709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2710 "Generating x.509 certificate for `%s'\n",
2712 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2713 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2714 pgc = GNUNET_new (struct ProxyGNSCertificate);
2715 gnutls_x509_crt_set_dn_by_oid (request,
2716 GNUTLS_OID_X520_COUNTRY_NAME,
2720 gnutls_x509_crt_set_dn_by_oid (request,
2721 GNUTLS_OID_X520_ORGANIZATION_NAME,
2724 strlen ("GNU Name System"));
2725 gnutls_x509_crt_set_dn_by_oid (request,
2726 GNUTLS_OID_X520_COMMON_NAME,
2730 gnutls_x509_crt_set_subject_alternative_name (request,
2733 GNUNET_break (GNUTLS_E_SUCCESS ==
2734 gnutls_x509_crt_set_version (request,
2736 gnutls_rnd (GNUTLS_RND_NONCE,
2739 gnutls_x509_crt_set_serial (request,
2742 etime = time (NULL);
2743 tm_data = localtime (&etime);
2745 etime = mktime(tm_data);
2746 gnutls_x509_crt_set_activation_time (request,
2749 etime = mktime (tm_data);
2750 gnutls_x509_crt_set_expiration_time (request,
2752 gnutls_x509_crt_sign2 (request,
2757 key_buf_size = sizeof (pgc->key);
2758 cert_buf_size = sizeof (pgc->cert);
2759 gnutls_x509_crt_export (request,
2760 GNUTLS_X509_FMT_PEM,
2763 gnutls_x509_privkey_export (proxy_ca.key,
2764 GNUTLS_X509_FMT_PEM,
2767 gnutls_x509_crt_deinit (request);
2773 * Function called by MHD with errors, suppresses them all.
2775 * @param cls closure
2776 * @param fm format string (`printf()`-style)
2777 * @param ap arguments to @a fm
2780 mhd_error_log_callback (void *cls,
2789 * Lookup (or create) an TLS MHD instance for a particular domain.
2791 * @param domain the domain the TLS daemon has to serve
2792 * @return NULL on error
2794 static struct MhdHttpList *
2795 lookup_ssl_httpd (const char* domain)
2797 struct MhdHttpList *hd;
2798 struct ProxyGNSCertificate *pgc;
2805 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2806 if ( (NULL != hd->domain) &&
2807 (0 == strcmp (hd->domain, domain)) )
2809 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2810 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2812 pgc = generate_gns_certificate (domain);
2813 hd = GNUNET_new (struct MhdHttpList);
2814 hd->is_ssl = GNUNET_YES;
2815 hd->domain = GNUNET_strdup (domain);
2816 hd->proxy_cert = pgc;
2817 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
2820 &create_response, hd,
2821 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2822 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2823 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
2824 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2825 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2826 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2827 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2829 if (NULL == hd->daemon)
2835 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2843 * Task run when a Socks5Request somehow fails to be associated with
2844 * an MHD connection (i.e. because the client never speaks HTTP after
2845 * the SOCKS5 handshake). Clean up.
2847 * @param cls the `struct Socks5Request *`
2850 timeout_s5r_handshake (void *cls)
2852 struct Socks5Request *s5r = cls;
2854 s5r->timeout_task = NULL;
2860 * We're done with the Socks5 protocol, now we need to pass the
2861 * connection data through to the final destination, either
2862 * direct (if the protocol might not be HTTP), or via MHD
2863 * (if the port looks like it should be HTTP).
2865 * @param s5r socks request that has reached the final stage
2868 setup_data_transfer (struct Socks5Request *s5r)
2870 struct MhdHttpList *hd;
2872 const struct sockaddr *addr;
2876 if (GNUNET_YES == s5r->is_tls)
2878 GNUNET_asprintf (&domain,
2881 hd = lookup_ssl_httpd (domain);
2884 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2885 _("Failed to start HTTPS server for `%s'\n"),
2888 GNUNET_free (domain);
2893 GNUNET_assert (NULL != httpd);
2896 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2897 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2898 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2899 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2901 MHD_add_connection (hd->daemon,
2906 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2907 _("Failed to pass client to MHD\n"));
2909 GNUNET_free_non_null (domain);
2913 schedule_httpd (hd);
2914 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2915 &timeout_s5r_handshake,
2917 GNUNET_free_non_null (domain);
2921 /* ********************* SOCKS handling ************************* */
2925 * Write data from buffer to socks5 client, then continue with state machine.
2927 * @param cls the closure with the `struct Socks5Request`
2930 do_write (void *cls)
2932 struct Socks5Request *s5r = cls;
2936 len = GNUNET_NETWORK_socket_send (s5r->sock,
2941 /* write error: connection closed, shutdown, etc.; just clean up */
2942 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2949 s5r->wbuf_len - len);
2950 s5r->wbuf_len -= len;
2951 if (s5r->wbuf_len > 0)
2953 /* not done writing */
2955 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2961 /* we're done writing, continue with state machine! */
2968 case SOCKS5_REQUEST:
2969 GNUNET_assert (NULL != s5r->rtask);
2971 case SOCKS5_DATA_TRANSFER:
2972 setup_data_transfer (s5r);
2974 case SOCKS5_WRITE_THEN_CLEANUP:
2985 * Return a server response message indicating a failure to the client.
2987 * @param s5r request to return failure code for
2988 * @param sc status code to return
2991 signal_socks_failure (struct Socks5Request *s5r,
2992 enum Socks5StatusCode sc)
2994 struct Socks5ServerResponseMessage *s_resp;
2996 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2997 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2998 s_resp->version = SOCKS_VERSION_5;
3000 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
3001 if (NULL != s5r->wtask)
3003 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3010 * Return a server response message indicating success.
3012 * @param s5r request to return success status message for
3015 signal_socks_success (struct Socks5Request *s5r)
3017 struct Socks5ServerResponseMessage *s_resp;
3019 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
3020 s_resp->version = SOCKS_VERSION_5;
3021 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
3022 s_resp->reserved = 0;
3023 s_resp->addr_type = SOCKS5_AT_IPV4;
3024 /* zero out IPv4 address and port */
3027 sizeof (struct in_addr) + sizeof (uint16_t));
3028 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
3029 sizeof (struct in_addr) + sizeof (uint16_t);
3030 if (NULL == s5r->wtask)
3032 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3039 * Process GNS results for target domain.
3041 * @param cls the `struct Socks5Request *`
3042 * @param tld #GNUNET_YES if this was a GNS TLD.
3043 * @param rd_count number of records returned
3044 * @param rd record data
3047 handle_gns_result (void *cls,
3050 const struct GNUNET_GNSRECORD_Data *rd)
3052 struct Socks5Request *s5r = cls;
3053 const struct GNUNET_GNSRECORD_Data *r;
3056 s5r->gns_lookup = NULL;
3059 for (uint32_t i=0;i<rd_count;i++)
3062 switch (r->record_type)
3064 case GNUNET_DNSPARSER_TYPE_A:
3066 struct sockaddr_in *in;
3068 if (sizeof (struct in_addr) != r->data_size)
3070 GNUNET_break_op (0);
3073 if (GNUNET_YES == got_ip)
3076 GNUNET_NETWORK_test_pf (PF_INET))
3078 got_ip = GNUNET_YES;
3079 in = (struct sockaddr_in *) &s5r->destination_address;
3080 in->sin_family = AF_INET;
3081 GNUNET_memcpy (&in->sin_addr,
3084 in->sin_port = htons (s5r->port);
3085 #if HAVE_SOCKADDR_IN_SIN_LEN
3086 in->sin_len = sizeof (*in);
3090 case GNUNET_DNSPARSER_TYPE_AAAA:
3092 struct sockaddr_in6 *in;
3094 if (sizeof (struct in6_addr) != r->data_size)
3096 GNUNET_break_op (0);
3099 if (GNUNET_YES == got_ip)
3101 if (GNUNET_YES == disable_v6)
3104 GNUNET_NETWORK_test_pf (PF_INET6))
3106 /* FIXME: allow user to disable IPv6 per configuration option... */
3107 got_ip = GNUNET_YES;
3108 in = (struct sockaddr_in6 *) &s5r->destination_address;
3109 in->sin6_family = AF_INET6;
3110 GNUNET_memcpy (&in->sin6_addr,
3113 in->sin6_port = htons (s5r->port);
3114 #if HAVE_SOCKADDR_IN_SIN_LEN
3115 in->sin6_len = sizeof (*in);
3119 case GNUNET_GNSRECORD_TYPE_VPN:
3120 GNUNET_break (0); /* should have been translated within GNS */
3122 case GNUNET_GNSRECORD_TYPE_LEHO:
3123 GNUNET_free_non_null (s5r->leho);
3124 s5r->leho = GNUNET_strndup (r->data,
3127 case GNUNET_GNSRECORD_TYPE_BOX:
3129 const struct GNUNET_GNSRECORD_BoxRecord *box;
3131 if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
3133 GNUNET_break_op (0);
3137 if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
3138 (ntohs (box->protocol) != IPPROTO_TCP) ||
3139 (ntohs (box->service) != s5r->port) )
3140 break; /* BOX record does not apply */
3141 if (s5r->num_danes >= MAX_DANES)
3143 GNUNET_break (0); /* MAX_DANES too small */
3146 s5r->is_tls = GNUNET_YES; /* This should be TLS */
3147 s5r->dane_data_len[s5r->num_danes]
3148 = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
3149 s5r->dane_data[s5r->num_danes]
3150 = GNUNET_memdup (&box[1],
3151 s5r->dane_data_len[s5r->num_danes]);
3160 if ( (GNUNET_YES != got_ip) &&
3161 (GNUNET_YES == tld) )
3163 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3164 "Name resolution failed to yield useful IP address.\n");
3165 signal_socks_failure (s5r,
3166 SOCKS5_STATUS_GENERAL_FAILURE);
3169 s5r->state = SOCKS5_DATA_TRANSFER;
3170 signal_socks_success (s5r);
3175 * Remove the first @a len bytes from the beginning of the read buffer.
3177 * @param s5r the handle clear the read buffer for
3178 * @param len number of bytes in read buffer to advance
3181 clear_from_s5r_rbuf (struct Socks5Request *s5r,
3184 GNUNET_assert (len <= s5r->rbuf_len);
3187 s5r->rbuf_len - len);
3188 s5r->rbuf_len -= len;
3193 * Read data from incoming Socks5 connection
3195 * @param cls the closure with the `struct Socks5Request`
3198 do_s5r_read (void *cls)
3200 struct Socks5Request *s5r = cls;
3201 const struct Socks5ClientHelloMessage *c_hello;
3202 struct Socks5ServerHelloMessage *s_hello;
3203 const struct Socks5ClientRequestMessage *c_req;
3206 const struct GNUNET_SCHEDULER_TaskContext *tc;
3209 tc = GNUNET_SCHEDULER_get_task_context ();
3210 if ( (NULL != tc->read_ready) &&
3211 (GNUNET_NETWORK_fdset_isset (tc->read_ready,
3214 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
3215 &s5r->rbuf[s5r->rbuf_len],
3216 sizeof (s5r->rbuf) - s5r->rbuf_len);
3219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3220 "socks5 client disconnected.\n");
3224 s5r->rbuf_len += rlen;
3226 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3230 "Processing %zu bytes of socks data in state %d\n",
3236 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
3237 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
3238 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
3239 return; /* need more data */
3240 if (SOCKS_VERSION_5 != c_hello->version)
3242 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3243 _("Unsupported socks version %d\n"),
3244 (int) c_hello->version);
3248 clear_from_s5r_rbuf (s5r,
3249 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
3250 GNUNET_assert (0 == s5r->wbuf_len);
3251 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
3252 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
3253 s_hello->version = SOCKS_VERSION_5;
3254 s_hello->auth_method = SOCKS_AUTH_NONE;
3255 GNUNET_assert (NULL == s5r->wtask);
3256 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3259 s5r->state = SOCKS5_REQUEST;
3261 case SOCKS5_REQUEST:
3262 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
3263 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
3265 switch (c_req->command)
3267 case SOCKS5_CMD_TCP_STREAM:
3271 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3272 _("Unsupported socks command %d\n"),
3273 (int) c_req->command);
3274 signal_socks_failure (s5r,
3275 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
3278 switch (c_req->addr_type)
3280 case SOCKS5_AT_IPV4:
3282 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
3283 const uint16_t *port = (const uint16_t *) &v4[1];
3284 struct sockaddr_in *in;
3286 s5r->port = ntohs (*port);
3287 alen = sizeof (struct in_addr);
3288 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3289 alen + sizeof (uint16_t))
3290 return; /* need more data */
3291 in = (struct sockaddr_in *) &s5r->destination_address;
3292 in->sin_family = AF_INET;
3294 in->sin_port = *port;
3295 #if HAVE_SOCKADDR_IN_SIN_LEN
3296 in->sin_len = sizeof (*in);
3298 s5r->state = SOCKS5_DATA_TRANSFER;
3301 case SOCKS5_AT_IPV6:
3303 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
3304 const uint16_t *port = (const uint16_t *) &v6[1];
3305 struct sockaddr_in6 *in;
3307 s5r->port = ntohs (*port);
3308 alen = sizeof (struct in6_addr);
3309 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3310 alen + sizeof (uint16_t))
3311 return; /* need more data */
3312 in = (struct sockaddr_in6 *) &s5r->destination_address;
3313 in->sin6_family = AF_INET6;
3314 in->sin6_addr = *v6;
3315 in->sin6_port = *port;
3316 #if HAVE_SOCKADDR_IN_SIN_LEN
3317 in->sin6_len = sizeof (*in);
3319 s5r->state = SOCKS5_DATA_TRANSFER;
3322 case SOCKS5_AT_DOMAINNAME:
3324 const uint8_t *dom_len;
3325 const char *dom_name;
3326 const uint16_t *port;
3328 dom_len = (const uint8_t *) &c_req[1];
3329 alen = *dom_len + 1;
3330 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3331 alen + sizeof (uint16_t))
3332 return; /* need more data */
3333 dom_name = (const char *) &dom_len[1];
3334 port = (const uint16_t*) &dom_name[*dom_len];
3335 s5r->domain = GNUNET_strndup (dom_name,
3337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3338 "Requested connection is to %s:%d\n",
3339 //(HTTPS_PORT == s5r->port) ? "s" : "",
3342 s5r->state = SOCKS5_RESOLVING;
3343 s5r->port = ntohs (*port);
3344 s5r->is_tls = (HTTPS_PORT == s5r->port) ? GNUNET_YES : GNUNET_NO;
3345 s5r->gns_lookup = GNUNET_GNS_lookup_with_tld (gns_handle,
3347 GNUNET_DNSPARSER_TYPE_A,
3348 GNUNET_NO /* only cached */,
3354 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3355 _("Unsupported socks address type %d\n"),
3356 (int) c_req->addr_type);
3357 signal_socks_failure (s5r,
3358 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
3361 clear_from_s5r_rbuf (s5r,
3362 sizeof (struct Socks5ClientRequestMessage) +
3363 alen + sizeof (uint16_t));
3364 if (0 != s5r->rbuf_len)
3366 /* read more bytes than healthy, why did the client send more!? */
3367 GNUNET_break_op (0);
3368 signal_socks_failure (s5r,
3369 SOCKS5_STATUS_GENERAL_FAILURE);
3372 if (SOCKS5_DATA_TRANSFER == s5r->state)
3374 /* if we are not waiting for GNS resolution, signal success */
3375 signal_socks_success (s5r);
3377 /* We are done reading right now */
3378 GNUNET_SCHEDULER_cancel (s5r->rtask);
3381 case SOCKS5_RESOLVING:
3384 case SOCKS5_DATA_TRANSFER:
3395 * Accept new incoming connections
3397 * @param cls the closure with the lsock4 or lsock6
3398 * @param tc the scheduler context
3401 do_accept (void *cls)
3403 struct GNUNET_NETWORK_Handle *lsock = cls;
3404 struct GNUNET_NETWORK_Handle *s;
3405 struct Socks5Request *s5r;
3407 GNUNET_assert (NULL != lsock);
3408 if (lsock == lsock4)
3409 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3413 else if (lsock == lsock6)
3414 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3420 s = GNUNET_NETWORK_socket_accept (lsock,
3425 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3429 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3430 "Got an inbound connection, waiting for data\n");
3431 s5r = GNUNET_new (struct Socks5Request);
3432 GNUNET_CONTAINER_DLL_insert (s5r_head,
3436 s5r->state = SOCKS5_INIT;
3437 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3444 /* ******************* General / main code ********************* */
3448 * Task run on shutdown
3450 * @param cls closure
3453 do_shutdown (void *cls)
3455 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3456 "Shutting down...\n");
3457 /* MHD requires resuming before destroying the daemons */
3458 for (struct Socks5Request *s5r = s5r_head;
3464 s5r->suspended = GNUNET_NO;
3465 MHD_resume_connection (s5r->con);
3468 while (NULL != mhd_httpd_head)
3469 kill_httpd (mhd_httpd_head);
3470 while (NULL != s5r_head)
3471 cleanup_s5r (s5r_head);
3474 GNUNET_NETWORK_socket_close (lsock4);
3479 GNUNET_NETWORK_socket_close (lsock6);
3482 if (NULL != curl_multi)
3484 curl_multi_cleanup (curl_multi);
3487 if (NULL != gns_handle)
3489 GNUNET_GNS_disconnect (gns_handle);
3492 if (NULL != curl_download_task)
3494 GNUNET_SCHEDULER_cancel (curl_download_task);
3495 curl_download_task = NULL;
3499 GNUNET_SCHEDULER_cancel (ltask4);
3504 GNUNET_SCHEDULER_cancel (ltask6);
3507 gnutls_x509_crt_deinit (proxy_ca.cert);
3508 gnutls_x509_privkey_deinit (proxy_ca.key);
3509 gnutls_global_deinit ();
3514 * Create an IPv4 listen socket bound to our port.
3516 * @return NULL on error
3518 static struct GNUNET_NETWORK_Handle *
3521 struct GNUNET_NETWORK_Handle *ls;
3522 struct sockaddr_in sa4;
3525 memset (&sa4, 0, sizeof (sa4));
3526 sa4.sin_family = AF_INET;
3527 sa4.sin_port = htons (port);
3528 sa4.sin_addr.s_addr = address;
3529 #if HAVE_SOCKADDR_IN_SIN_LEN
3530 sa4.sin_len = sizeof (sa4);
3532 ls = GNUNET_NETWORK_socket_create (AF_INET,
3538 GNUNET_NETWORK_socket_bind (ls,
3539 (const struct sockaddr *) &sa4,
3543 GNUNET_NETWORK_socket_close (ls);
3552 * Create an IPv6 listen socket bound to our port.
3554 * @return NULL on error
3556 static struct GNUNET_NETWORK_Handle *
3559 struct GNUNET_NETWORK_Handle *ls;
3560 struct sockaddr_in6 sa6;
3563 memset (&sa6, 0, sizeof (sa6));
3564 sa6.sin6_family = AF_INET6;
3565 sa6.sin6_port = htons (port);
3566 sa6.sin6_addr = address6;
3567 #if HAVE_SOCKADDR_IN_SIN_LEN
3568 sa6.sin6_len = sizeof (sa6);
3570 ls = GNUNET_NETWORK_socket_create (AF_INET6,
3576 GNUNET_NETWORK_socket_bind (ls,
3577 (const struct sockaddr *) &sa6,
3581 GNUNET_NETWORK_socket_close (ls);
3590 * Main function that will be run
3592 * @param cls closure
3593 * @param args remaining command-line arguments
3594 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3595 * @param c configuration
3600 const char *cfgfile,
3601 const struct GNUNET_CONFIGURATION_Handle *c)
3603 char* cafile_cfg = NULL;
3606 struct MhdHttpList *hd;
3610 /* Get address to bind to */
3611 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "gns-proxy",
3615 //No address specified
3616 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3617 "Don't know what to bind to...\n");
3618 GNUNET_free (addr_str);
3619 GNUNET_SCHEDULER_shutdown ();
3622 if (1 != inet_pton (AF_INET, addr_str, &address))
3624 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3625 "Unable to parse address %s\n",
3627 GNUNET_free (addr_str);
3628 GNUNET_SCHEDULER_shutdown ();
3631 GNUNET_free (addr_str);
3632 /* Get address to bind to */
3633 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "gns-proxy",
3637 //No address specified
3638 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3639 "Don't know what to bind6 to...\n");
3640 GNUNET_free (addr_str);
3641 GNUNET_SCHEDULER_shutdown ();
3644 if (1 != inet_pton (AF_INET6, addr_str, &address6))
3646 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3647 "Unable to parse IPv6 address %s\n",
3649 GNUNET_free (addr_str);
3650 GNUNET_SCHEDULER_shutdown ();
3653 GNUNET_free (addr_str);
3655 if (NULL == (curl_multi = curl_multi_init ()))
3657 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3658 "Failed to create cURL multi handle!\n");
3661 cafile = cafile_opt;
3665 GNUNET_CONFIGURATION_get_value_filename (cfg,
3670 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3675 cafile = cafile_cfg;
3677 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3678 "Using `%s' as CA\n",
3681 gnutls_global_init ();
3682 gnutls_x509_crt_init (&proxy_ca.cert);
3683 gnutls_x509_privkey_init (&proxy_ca.key);
3686 load_cert_from_file (proxy_ca.cert,
3689 load_key_from_file (proxy_ca.key,
3692 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3693 _("Failed to load X.509 key and certificate from `%s'\n"),
3695 gnutls_x509_crt_deinit (proxy_ca.cert);
3696 gnutls_x509_privkey_deinit (proxy_ca.key);
3697 gnutls_global_deinit ();
3698 GNUNET_free_non_null (cafile_cfg);
3701 GNUNET_free_non_null (cafile_cfg);
3702 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3704 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3705 "Unable to connect to GNS!\n");
3706 gnutls_x509_crt_deinit (proxy_ca.cert);
3707 gnutls_x509_privkey_deinit (proxy_ca.key);
3708 gnutls_global_deinit ();
3711 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
3714 /* Open listen socket for socks proxy */
3715 lsock6 = bind_v6 ();
3718 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3724 GNUNET_NETWORK_socket_listen (lsock6,
3727 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3729 GNUNET_NETWORK_socket_close (lsock6);
3734 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3740 lsock4 = bind_v4 ();
3743 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3749 GNUNET_NETWORK_socket_listen (lsock4,
3752 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3754 GNUNET_NETWORK_socket_close (lsock4);
3759 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3765 if ( (NULL == lsock4) &&
3768 GNUNET_SCHEDULER_shutdown ();
3771 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3773 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3774 "cURL global init failed!\n");
3775 GNUNET_SCHEDULER_shutdown ();
3778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3779 "Proxy listens on port %u\n",
3780 (unsigned int) port);
3782 /* start MHD daemon for HTTP */
3783 hd = GNUNET_new (struct MhdHttpList);
3784 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
3787 &create_response, hd,
3788 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3789 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3790 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
3791 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3793 if (NULL == hd->daemon)
3796 GNUNET_SCHEDULER_shutdown ();
3800 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
3807 * The main function for gnunet-gns-proxy.
3809 * @param argc number of arguments from the command line
3810 * @param argv command line arguments
3811 * @return 0 ok, 1 on error
3817 struct GNUNET_GETOPT_CommandLineOption options[] = {
3818 GNUNET_GETOPT_option_uint16 ('p',
3821 gettext_noop ("listen on specified port (default: 7777)"),
3823 GNUNET_GETOPT_option_string ('a',
3826 gettext_noop ("pem file to use as CA"),
3828 GNUNET_GETOPT_option_flag ('6',
3830 gettext_noop ("disable use of IPv6"),
3833 GNUNET_GETOPT_OPTION_END
3835 static const char* page =
3836 "<html><head><title>gnunet-gns-proxy</title>"
3837 "</head><body>cURL fail</body></html>";
3841 GNUNET_STRINGS_get_utf8_args (argc, argv,
3844 GNUNET_log_setup ("gnunet-gns-proxy",
3847 curl_failure_response
3848 = MHD_create_response_from_buffer (strlen (page),
3850 MHD_RESPMEM_PERSISTENT);
3854 GNUNET_PROGRAM_run (argc, argv,
3856 _("GNUnet GNS proxy"),
3858 &run, NULL)) ? 0 : 1;
3859 MHD_destroy_response (curl_failure_response);
3860 GNUNET_free_non_null ((char *) argv);
3864 /* end of gnunet-gns-proxy.c */