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>
32 /* Just included for the right curl.h */
33 #include "gnunet_curl_lib.h"
34 #include <gnutls/gnutls.h>
35 #include <gnutls/x509.h>
36 #include <gnutls/abstract.h>
37 #include <gnutls/crypto.h>
39 #include <gnutls/dane.h>
42 #include "gnunet_util_lib.h"
43 #include "gnunet_gns_service.h"
44 #include "gnunet_identity_service.h"
50 * Default Socks5 listen port.
52 #define GNUNET_GNS_PROXY_PORT 7777
55 * Maximum supported length for a URI.
56 * Should die. @deprecated
58 #define MAX_HTTP_URI_LENGTH 2048
61 * Maximum number of DANE records we support
62 * per domain name (and port and protocol).
67 * Size of the buffer for the data upload / download. Must be
68 * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
70 #define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE
73 * Size of the read/write buffers for Socks. Uses
74 * 256 bytes for the hostname (at most), plus a few
75 * bytes overhead for the messages.
77 #define SOCKS_BUFFERSIZE (256 + 32)
80 * Port for plaintext HTTP.
87 #define HTTPS_PORT 443
90 * Largest allowed size for a PEM certificate.
92 #define MAX_PEM_SIZE (10 * 1024)
95 * After how long do we clean up unused MHD TLS instances?
97 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
100 * After how long do we clean up Socks5 handles that failed to show any activity
101 * with their respective MHD instance?
103 #define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15)
109 * @param level log level
110 * @param fun name of curl_easy-function that gave the error
111 * @param rc return code from curl
113 #define LOG_CURL_EASY(level, fun, rc) \
115 _("%s failed at %s:%d: `%s'\n"), \
119 curl_easy_strerror(rc))
122 /* *************** Socks protocol definitions (move to TUN?) ****************** */
125 * Which SOCKS version do we speak?
127 #define SOCKS_VERSION_5 0x05
130 * Flag to set for 'no authentication'.
132 #define SOCKS_AUTH_NONE 0
136 * Commands in Socks5.
138 enum Socks5Commands {
140 * Establish TCP/IP stream.
142 SOCKS5_CMD_TCP_STREAM = 1,
145 * Establish TCP port binding.
147 SOCKS5_CMD_TCP_PORT = 2,
150 * Establish UDP port binding.
152 SOCKS5_CMD_UDP_PORT = 3
157 * Address types in Socks5.
159 enum Socks5AddressType {
168 SOCKS5_AT_DOMAINNAME = 3,
178 * Status codes in Socks5 response.
180 enum Socks5StatusCode {
181 SOCKS5_STATUS_REQUEST_GRANTED = 0,
182 SOCKS5_STATUS_GENERAL_FAILURE = 1,
183 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
184 SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
185 SOCKS5_STATUS_HOST_UNREACHABLE = 4,
186 SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
187 SOCKS5_STATUS_TTL_EXPIRED = 6,
188 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
189 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
194 * Client hello in Socks5 protocol.
196 struct Socks5ClientHelloMessage {
198 * Should be #SOCKS_VERSION_5.
203 * How many authentication methods does the client support.
205 uint8_t num_auth_methods;
207 /* followed by supported authentication methods, 1 byte per method */
212 * Server hello in Socks5 protocol.
214 struct Socks5ServerHelloMessage {
216 * Should be #SOCKS_VERSION_5.
221 * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
222 * which skips the authentication step.
229 * Client socks request in Socks5 protocol.
231 struct Socks5ClientRequestMessage {
233 * Should be #SOCKS_VERSION_5.
238 * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
243 * Reserved, always zero.
248 * Address type, an `enum Socks5AddressType`.
253 * Followed by either an ip4/ipv6 address or a domain name with a
254 * length field (uint8_t) in front (depending on @e addr_type).
255 * followed by port number in network byte order (uint16_t).
261 * Server response to client requests in Socks5 protocol.
263 struct Socks5ServerResponseMessage {
265 * Should be #SOCKS_VERSION_5.
270 * Status code, an `enum Socks5StatusCode`
280 * Address type, an `enum Socks5AddressType`.
285 * Followed by either an ip4/ipv6 address or a domain name with a
286 * length field (uint8_t) in front (depending on @e addr_type).
287 * followed by port number in network byte order (uint16_t).
293 /* *********************** Datastructures for HTTP handling ****************** */
296 * A structure for CA cert/key
302 gnutls_x509_crt_t cert;
307 gnutls_x509_privkey_t key;
312 * Structure for GNS certificates
314 struct ProxyGNSCertificate {
316 * The certificate as PEM
318 char cert[MAX_PEM_SIZE];
321 * The private key as PEM
323 char key[MAX_PEM_SIZE];
329 * A structure for all running Httpds
335 struct MhdHttpList *prev;
340 struct MhdHttpList *next;
343 * the domain name to server (only important for TLS)
350 struct MHD_Daemon *daemon;
353 * Optional proxy certificate used
355 struct ProxyGNSCertificate *proxy_cert;
360 struct GNUNET_SCHEDULER_Task *httpd_task;
363 * is this an ssl daemon?
369 /* ***************** Datastructures for Socks handling **************** */
377 * We're waiting to get the client hello.
382 * We're waiting to get the initial request.
387 * We are currently resolving the destination.
392 * We're in transfer mode.
394 SOCKS5_DATA_TRANSFER,
397 * Finish writing the write buffer, then clean up.
399 SOCKS5_WRITE_THEN_CLEANUP,
402 * Socket has been passed to MHD, do not close it anymore.
404 SOCKS5_SOCKET_WITH_MHD,
407 * We've started receiving upload data from MHD.
409 SOCKS5_SOCKET_UPLOAD_STARTED,
412 * We've finished receiving upload data from MHD.
414 SOCKS5_SOCKET_UPLOAD_DONE,
417 * We've finished uploading data via CURL and can now download.
419 SOCKS5_SOCKET_DOWNLOAD_STARTED,
422 * We've finished receiving download data from cURL.
424 SOCKS5_SOCKET_DOWNLOAD_DONE
431 struct HttpResponseHeader {
435 struct HttpResponseHeader *next;
440 struct HttpResponseHeader *prev;
454 * A structure for socks requests
456 struct Socks5Request {
460 struct Socks5Request *next;
465 struct Socks5Request *prev;
470 struct GNUNET_NETWORK_Handle *sock;
473 * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
475 struct GNUNET_GNS_LookupWithTldRequest *gns_lookup;
478 * Client socket read task
480 struct GNUNET_SCHEDULER_Task *rtask;
483 * Client socket write task
485 struct GNUNET_SCHEDULER_Task *wtask;
490 struct GNUNET_SCHEDULER_Task *timeout_task;
495 char rbuf[SOCKS_BUFFERSIZE];
500 char wbuf[SOCKS_BUFFERSIZE];
503 * Buffer we use for moving data between MHD and curl (in both directions).
505 char io_buf[IO_BUFFERSIZE];
508 * MHD HTTP instance handling this request, NULL for none.
510 struct MhdHttpList *hd;
513 * MHD connection for this request.
515 struct MHD_Connection *con;
518 * MHD response object for this request.
520 struct MHD_Response *response;
523 * the domain name to server (only important for TLS)
528 * DNS Legacy Host Name as given by GNS, NULL if not given.
533 * Payload of the DANE records encountered.
535 char *dane_data[MAX_DANES + 1];
548 * HTTP request headers for the curl request.
550 struct curl_slist *headers;
553 * DNS->IP mappings resolved through GNS
555 struct curl_slist *hosts;
558 * HTTP response code to give to MHD for the response.
560 unsigned int response_code;
563 * Number of bytes in @e dane_data.
565 int dane_data_len[MAX_DANES + 1];
568 * Number of entries used in @e dane_data_len
571 unsigned int num_danes;
574 * Number of bytes already in read buffer
579 * Number of bytes already in write buffer
584 * Number of bytes already in the IO buffer.
589 * Once known, what's the target address for the connection?
591 struct sockaddr_storage destination_address;
596 enum SocksPhase state;
599 * Desired destination port.
604 * Headers from response
606 struct HttpResponseHeader *header_head;
609 * Headers from response
611 struct HttpResponseHeader *header_tail;
614 * X.509 Certificate status
619 * Was the hostname resolved via GNS?
624 * This is (probably) a TLS connection
629 * Did we suspend MHD processing?
634 * Did we pause CURL processing?
641 /* *********************** Globals **************************** */
644 * The address to bind to
646 static in_addr_t address;
649 * The IPv6 address to bind to
651 static struct in6_addr address6;
654 * The port the proxy is running on (default 7777)
656 static uint16_t port = GNUNET_GNS_PROXY_PORT;
659 * The CA file (pem) to use for the proxy CA
661 static char *cafile_opt;
664 * The listen socket of the proxy for IPv4
666 static struct GNUNET_NETWORK_Handle *lsock4;
669 * The listen socket of the proxy for IPv6
671 static struct GNUNET_NETWORK_Handle *lsock6;
674 * The listen task ID for IPv4
676 static struct GNUNET_SCHEDULER_Task * ltask4;
679 * The listen task ID for IPv6
681 static struct GNUNET_SCHEDULER_Task * ltask6;
684 * The cURL download task (curl multi API).
686 static struct GNUNET_SCHEDULER_Task * curl_download_task;
689 * The cURL multi handle
691 static CURLM *curl_multi;
694 * Handle to the GNS service
696 static struct GNUNET_GNS_Handle *gns_handle;
701 static int disable_v6;
704 * DLL for http/https daemons
706 static struct MhdHttpList *mhd_httpd_head;
709 * DLL for http/https daemons
711 static struct MhdHttpList *mhd_httpd_tail;
714 * Daemon for HTTP (we have one per X.509 certificate, and then one for
715 * all HTTP connections; this is the one for HTTP, not HTTPS).
717 static struct MhdHttpList *httpd;
720 * DLL of active socks requests.
722 static struct Socks5Request *s5r_head;
725 * DLL of active socks requests.
727 static struct Socks5Request *s5r_tail;
730 * The CA for X.509 certificate generation
732 static struct ProxyCA proxy_ca;
735 * Response we return on cURL failures.
737 static struct MHD_Response *curl_failure_response;
742 static const struct GNUNET_CONFIGURATION_Handle *cfg;
745 /* ************************* Global helpers ********************* */
749 * Run MHD now, we have extra data ready for the callback.
751 * @param hd the daemon to run now.
754 run_mhd_now(struct MhdHttpList *hd);
758 * Clean up s5r handles.
760 * @param s5r the handle to destroy
763 cleanup_s5r(struct Socks5Request *s5r)
765 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
766 "Cleaning up socks request\n");
767 if (NULL != s5r->curl)
769 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
770 "Cleaning up cURL handle\n");
771 curl_multi_remove_handle(curl_multi,
773 curl_easy_cleanup(s5r->curl);
778 s5r->suspended = GNUNET_NO;
779 MHD_resume_connection(s5r->con);
781 curl_slist_free_all(s5r->headers);
782 if (NULL != s5r->hosts)
784 curl_slist_free_all(s5r->hosts);
786 if ((NULL != s5r->response) &&
787 (curl_failure_response != s5r->response))
789 MHD_destroy_response(s5r->response);
790 s5r->response = NULL;
792 if (NULL != s5r->rtask)
794 GNUNET_SCHEDULER_cancel(s5r->rtask);
797 if (NULL != s5r->timeout_task)
799 GNUNET_SCHEDULER_cancel(s5r->timeout_task);
800 s5r->timeout_task = NULL;
802 if (NULL != s5r->wtask)
804 GNUNET_SCHEDULER_cancel(s5r->wtask);
807 if (NULL != s5r->gns_lookup)
809 GNUNET_GNS_lookup_with_tld_cancel(s5r->gns_lookup);
810 s5r->gns_lookup = NULL;
812 if (NULL != s5r->sock)
814 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
815 GNUNET_NETWORK_socket_free_memory_only_(s5r->sock);
817 GNUNET_NETWORK_socket_close(s5r->sock);
820 GNUNET_CONTAINER_DLL_remove(s5r_head,
823 GNUNET_free_non_null(s5r->domain);
824 GNUNET_free_non_null(s5r->leho);
825 GNUNET_free_non_null(s5r->url);
826 for (unsigned int i = 0; i < s5r->num_danes; i++)
827 GNUNET_free(s5r->dane_data[i]);
832 /* ************************* HTTP handling with cURL *********************** */
835 curl_download_prepare();
839 * Callback for MHD response generation. This function is called from
840 * MHD whenever MHD expects to get data back. Copies data from the
841 * io_buf, if available.
843 * @param cls closure with our `struct Socks5Request`
844 * @param pos in buffer
845 * @param buf where to copy data
846 * @param max available space in @a buf
847 * @return number of bytes written to @a buf
850 mhd_content_cb(void *cls,
855 struct Socks5Request *s5r = cls;
856 size_t bytes_to_copy;
858 if ((SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
859 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state))
861 /* we're still not done with the upload, do not yet
862 start the download, the IO buffer is still full
864 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
865 "Pausing MHD download %s%s, not yet ready for download\n",
868 return 0; /* not yet ready for data download */
870 bytes_to_copy = GNUNET_MIN(max,
872 if ((0 == bytes_to_copy) &&
873 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state))
875 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
876 "Pausing MHD download %s%s, no data available\n",
879 if (NULL != s5r->curl)
881 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
882 "Continuing CURL interaction for %s%s\n",
885 if (GNUNET_YES == s5r->curl_paused)
887 s5r->curl_paused = GNUNET_NO;
888 curl_easy_pause(s5r->curl,
891 curl_download_prepare();
893 if (GNUNET_NO == s5r->suspended)
895 MHD_suspend_connection(s5r->con);
896 s5r->suspended = GNUNET_YES;
898 return 0; /* more data later */
900 if ((0 == bytes_to_copy) &&
901 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state))
903 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
904 "Completed MHD download %s%s\n",
907 return MHD_CONTENT_READER_END_OF_STREAM;
909 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
910 "Writing %llu/%llu bytes to %s%s\n",
911 (unsigned long long)bytes_to_copy,
912 (unsigned long long)s5r->io_len,
919 &s5r->io_buf[bytes_to_copy],
920 s5r->io_len - bytes_to_copy);
921 s5r->io_len -= bytes_to_copy;
922 if ((NULL != s5r->curl) &&
923 (GNUNET_YES == s5r->curl_paused))
925 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
926 "Continuing CURL interaction for %s%s\n",
929 s5r->curl_paused = GNUNET_NO;
930 curl_easy_pause(s5r->curl,
933 return bytes_to_copy;
938 * Check that the website has presented us with a valid X.509 certificate.
939 * The certificate must either match the domain name or the LEHO name
940 * (or, if available, the TLSA record).
942 * @param s5r request to check for.
943 * @return #GNUNET_OK if the certificate is valid
946 check_ssl_certificate(struct Socks5Request *s5r)
948 unsigned int cert_list_size;
949 const gnutls_datum_t *chainp;
950 const struct curl_tlssessioninfo *tlsinfo;
951 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
953 gnutls_x509_crt_t x509_cert;
957 s5r->ssl_checked = GNUNET_YES;
958 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
959 "Checking X.509 certificate\n");
961 curl_easy_getinfo(s5r->curl,
962 CURLINFO_TLS_SESSION,
964 return GNUNET_SYSERR;
965 if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
967 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
968 _("Unsupported CURL TLS backend %d\n"),
970 return GNUNET_SYSERR;
972 chainp = gnutls_certificate_get_peers(tlsinfo->internals,
975 (0 == cert_list_size))
976 return GNUNET_SYSERR;
978 size = sizeof(certdn);
979 /* initialize an X.509 certificate structure. */
980 gnutls_x509_crt_init(&x509_cert);
981 gnutls_x509_crt_import(x509_cert,
983 GNUTLS_X509_FMT_DER);
985 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid(x509_cert,
986 GNUTLS_OID_X520_COMMON_NAME,
987 0, /* the first and only one */
988 0 /* no DER encoding */,
992 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
993 _("Failed to fetch CN from cert: %s\n"),
994 gnutls_strerror(rc));
995 gnutls_x509_crt_deinit(x509_cert);
996 return GNUNET_SYSERR;
998 /* check for TLSA/DANE records */
1000 if (0 != s5r->num_danes)
1002 dane_state_t dane_state;
1003 dane_query_t dane_query;
1004 unsigned int verify;
1006 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
1007 if (0 != (rc = dane_state_init(&dane_state,
1008 #ifdef DANE_F_IGNORE_DNSSEC
1009 DANE_F_IGNORE_DNSSEC |
1011 DANE_F_IGNORE_LOCAL_RESOLVER)))
1013 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1014 _("Failed to initialize DANE: %s\n"),
1016 gnutls_x509_crt_deinit(x509_cert);
1017 return GNUNET_SYSERR;
1019 s5r->dane_data[s5r->num_danes] = NULL;
1020 s5r->dane_data_len[s5r->num_danes] = 0;
1021 if (0 != (rc = dane_raw_tlsa(dane_state,
1028 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1029 _("Failed to parse DANE record: %s\n"),
1031 dane_state_deinit(dane_state);
1032 gnutls_x509_crt_deinit(x509_cert);
1033 return GNUNET_SYSERR;
1035 if (0 != (rc = dane_verify_crt_raw(dane_state,
1038 gnutls_certificate_type_get(tlsinfo->internals),
1043 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1044 _("Failed to verify TLS connection using DANE: %s\n"),
1046 dane_query_deinit(dane_query);
1047 dane_state_deinit(dane_state);
1048 gnutls_x509_crt_deinit(x509_cert);
1049 return GNUNET_SYSERR;
1053 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1054 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
1056 dane_query_deinit(dane_query);
1057 dane_state_deinit(dane_state);
1058 gnutls_x509_crt_deinit(x509_cert);
1059 return GNUNET_SYSERR;
1061 dane_query_deinit(dane_query);
1062 dane_state_deinit(dane_state);
1068 /* try LEHO or ordinary domain name X509 verification */
1070 if (NULL != s5r->leho)
1074 if (0 == (rc = gnutls_x509_crt_check_hostname(x509_cert,
1077 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1078 _("TLS certificate subject name (%s) does not match `%s': %d\n"),
1082 gnutls_x509_crt_deinit(x509_cert);
1083 return GNUNET_SYSERR;
1088 /* we did not even have the domain name!? */
1090 return GNUNET_SYSERR;
1093 gnutls_x509_crt_deinit(x509_cert);
1099 * We're getting an HTTP response header from cURL. Convert it to the
1100 * MHD response headers. Mostly copies the headers, but makes special
1101 * adjustments to "Set-Cookie" and "Location" headers as those may need
1102 * to be changed from the LEHO to the domain the browser expects.
1104 * @param buffer curl buffer with a single line of header data; not 0-terminated!
1105 * @param size curl blocksize
1106 * @param nmemb curl blocknumber
1107 * @param cls our `struct Socks5Request *`
1108 * @return size of processed bytes
1111 curl_check_hdr(void *buffer,
1116 struct Socks5Request *s5r = cls;
1117 struct HttpResponseHeader *header;
1118 size_t bytes = size * nmemb;
1120 const char *hdr_type;
1121 const char *cookie_domain;
1123 char *new_cookie_hdr;
1126 size_t delta_cdomain;
1130 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1131 "Receiving HTTP response header from CURL\n");
1132 /* first, check TLS certificate */
1133 if ((GNUNET_YES != s5r->ssl_checked) &&
1134 (GNUNET_YES == s5r->is_tls))
1135 //(HTTPS_PORT == s5r->port))
1137 if (GNUNET_OK != check_ssl_certificate(s5r))
1140 ndup = GNUNET_strndup(buffer,
1142 hdr_type = strtok(ndup,
1144 if (NULL == hdr_type)
1149 hdr_val = strtok(NULL,
1151 if (NULL == hdr_val)
1156 if (' ' == *hdr_val)
1159 /* custom logic for certain header types */
1160 new_cookie_hdr = NULL;
1161 if ((NULL != s5r->leho) &&
1162 (0 == strcasecmp(hdr_type,
1163 MHD_HTTP_HEADER_SET_COOKIE)))
1166 new_cookie_hdr = GNUNET_malloc(strlen(hdr_val) +
1167 strlen(s5r->domain) + 1);
1169 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1170 for (tok = strtok(hdr_val, ";"); NULL != tok; tok = strtok(NULL, ";"))
1172 if ((0 == strncasecmp(tok,
1174 strlen(" domain"))) &&
1175 (GNUNET_NO == domain_matched))
1177 domain_matched = GNUNET_YES;
1178 cookie_domain = tok + strlen(" domain") + 1;
1179 if (strlen(cookie_domain) < strlen(s5r->leho))
1181 delta_cdomain = strlen(s5r->leho) - strlen(cookie_domain);
1182 if (0 == strcasecmp(cookie_domain,
1183 s5r->leho + delta_cdomain))
1185 offset += sprintf(new_cookie_hdr + offset,
1191 else if (0 == strcmp(cookie_domain,
1194 offset += sprintf(new_cookie_hdr + offset,
1199 else if (('.' == cookie_domain[0]) &&
1200 (0 == strcmp(&cookie_domain[1],
1203 offset += sprintf(new_cookie_hdr + offset,
1208 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1209 _("Cookie domain `%s' supplied by server is invalid\n"),
1212 GNUNET_memcpy(new_cookie_hdr + offset,
1215 offset += strlen(tok);
1216 new_cookie_hdr[offset++] = ';';
1218 hdr_val = new_cookie_hdr;
1221 new_location = NULL;
1222 if (0 == strcasecmp(MHD_HTTP_HEADER_TRANSFER_ENCODING,
1225 /* Ignore transfer encoding, set automatically by MHD if required */
1228 if ((0 == strcasecmp(MHD_HTTP_HEADER_LOCATION,
1233 GNUNET_asprintf(&leho_host,
1234 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1238 if (0 == strncmp(leho_host,
1242 GNUNET_asprintf(&new_location,
1244 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1248 hdr_val + strlen(leho_host));
1249 hdr_val = new_location;
1251 GNUNET_free(leho_host);
1253 if (0 == strcasecmp(MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1258 GNUNET_asprintf(&leho_host,
1259 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1263 if (0 == strncmp(leho_host,
1267 GNUNET_asprintf(&new_location,
1269 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1273 hdr_val = new_location;
1275 GNUNET_free(leho_host);
1278 /* MHD does not allow certain characters in values, remove those */
1279 if (NULL != (tok = strchr(hdr_val, '\n')))
1281 if (NULL != (tok = strchr(hdr_val, '\r')))
1283 if (NULL != (tok = strchr(hdr_val, '\t')))
1285 if (0 != strlen(hdr_val)) /* Rely in MHD to set those */
1287 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1288 "Adding header %s: %s to MHD response\n",
1291 header = GNUNET_new(struct HttpResponseHeader);
1292 header->type = GNUNET_strdup(hdr_type);
1293 header->value = GNUNET_strdup(hdr_val);
1294 GNUNET_CONTAINER_DLL_insert(s5r->header_head,
1300 GNUNET_free_non_null(new_cookie_hdr);
1301 GNUNET_free_non_null(new_location);
1307 * Create an MHD response object in @a s5r matching the
1308 * information we got from curl.
1310 * @param s5r the request for which we convert the response
1311 * @return #GNUNET_OK on success, #GNUNET_SYSERR if response was
1312 * already initialized before
1315 create_mhd_response_from_s5r(struct Socks5Request *s5r)
1318 double content_length;
1320 if (NULL != s5r->response)
1322 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1323 "Response already set!\n");
1324 return GNUNET_SYSERR;
1327 GNUNET_break(CURLE_OK ==
1328 curl_easy_getinfo(s5r->curl,
1329 CURLINFO_RESPONSE_CODE,
1331 GNUNET_break(CURLE_OK ==
1332 curl_easy_getinfo(s5r->curl,
1333 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
1335 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1336 "Creating MHD response with code %d and size %d for %s%s\n",
1338 (int)content_length,
1341 s5r->response_code = resp_code;
1342 s5r->response = MHD_create_response_from_callback((-1 == content_length)
1349 for (struct HttpResponseHeader *header = s5r->header_head;
1351 header = header->next)
1353 if (0 == strcasecmp(header->type,
1354 MHD_HTTP_HEADER_CONTENT_LENGTH))
1355 continue; /* MHD won't let us mess with those, for good reason */
1356 if ((0 == strcasecmp(header->type,
1357 MHD_HTTP_HEADER_TRANSFER_ENCODING)) &&
1358 ((0 == strcasecmp(header->value,
1360 (0 == strcasecmp(header->value,
1362 continue; /* MHD won't let us mess with those, for good reason */
1364 MHD_add_response_header(s5r->response,
1369 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1370 "Failed to add header `%s:%s'\n",
1375 /* force connection to be closed after each request, as we
1376 do not support HTTP pipelining (yet, FIXME!) */
1377 /*GNUNET_break (MHD_YES ==
1378 MHD_add_response_header (s5r->response,
1379 MHD_HTTP_HEADER_CONNECTION,
1381 MHD_resume_connection(s5r->con);
1382 s5r->suspended = GNUNET_NO;
1388 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1389 * it available to MHD.
1391 * @param ptr pointer to the data
1392 * @param size number of blocks of data
1393 * @param nmemb blocksize
1394 * @param ctx our `struct Socks5Request *`
1395 * @return number of bytes handled
1398 curl_download_cb(void *ptr,
1403 struct Socks5Request *s5r = ctx;
1404 size_t total = size * nmemb;
1406 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1407 "Receiving %ux%u bytes for `%s%s' from cURL to download\n",
1409 (unsigned int)nmemb,
1412 if (NULL == s5r->response)
1413 GNUNET_assert(GNUNET_OK ==
1414 create_mhd_response_from_s5r(s5r));
1415 if ((SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) &&
1418 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1419 "Previous upload finished... starting DOWNLOAD.\n");
1420 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1422 if ((SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1423 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state))
1425 /* we're still not done with the upload, do not yet
1426 start the download, the IO buffer is still full
1427 with upload data. */
1428 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1429 "Pausing CURL download `%s%s', waiting for UPLOAD to finish\n",
1432 s5r->curl_paused = GNUNET_YES;
1433 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1435 if (sizeof(s5r->io_buf) - s5r->io_len < total)
1437 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1438 "Pausing CURL `%s%s' download, not enough space %llu %llu %llu\n",
1441 (unsigned long long)sizeof(s5r->io_buf),
1442 (unsigned long long)s5r->io_len,
1443 (unsigned long long)total);
1444 s5r->curl_paused = GNUNET_YES;
1445 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1447 GNUNET_memcpy(&s5r->io_buf[s5r->io_len],
1450 s5r->io_len += total;
1451 if (GNUNET_YES == s5r->suspended)
1453 MHD_resume_connection(s5r->con);
1454 s5r->suspended = GNUNET_NO;
1456 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1457 "Received %llu bytes of payload via cURL from %s\n",
1458 (unsigned long long)total,
1460 if (s5r->io_len == total)
1461 run_mhd_now(s5r->hd);
1467 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1468 * to make it available to MHD.
1470 * @param buf where to write the data
1471 * @param size number of bytes per member
1472 * @param nmemb number of members available in @a buf
1473 * @param cls our `struct Socks5Request` that generated the data
1474 * @return number of bytes copied to @a buf
1477 curl_upload_cb(void *buf,
1482 struct Socks5Request *s5r = cls;
1483 size_t len = size * nmemb;
1486 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1487 "Receiving %ux%u bytes for `%s%s' from cURL to upload\n",
1489 (unsigned int)nmemb,
1493 if ((0 == s5r->io_len) &&
1494 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state))
1496 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1497 "Pausing CURL UPLOAD %s%s, need more data\n",
1500 return CURL_READFUNC_PAUSE;
1502 if ((0 == s5r->io_len) &&
1503 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state))
1505 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1506 if (GNUNET_YES == s5r->curl_paused)
1508 s5r->curl_paused = GNUNET_NO;
1509 curl_easy_pause(s5r->curl,
1512 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1513 "Completed CURL UPLOAD %s%s\n",
1516 return 0; /* upload finished, can now download */
1518 if ((SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
1519 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state))
1522 return CURL_READFUNC_ABORT;
1524 to_copy = GNUNET_MIN(s5r->io_len,
1529 memmove(s5r->io_buf,
1530 &s5r->io_buf[to_copy],
1531 s5r->io_len - to_copy);
1532 s5r->io_len -= to_copy;
1533 if (s5r->io_len + to_copy == sizeof(s5r->io_buf))
1534 run_mhd_now(s5r->hd); /* got more space for upload now */
1539 /* ************************** main loop of cURL interaction ****************** */
1543 * Task that is run when we are ready to receive more data
1546 * @param cls closure
1549 curl_task_download(void *cls);
1553 * Ask cURL for the select() sets and schedule cURL operations.
1556 curl_download_prepare()
1563 struct GNUNET_NETWORK_FDSet *grs;
1564 struct GNUNET_NETWORK_FDSet *gws;
1566 struct GNUNET_TIME_Relative rtime;
1568 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1569 "Scheduling CURL interaction\n");
1570 if (NULL != curl_download_task)
1572 GNUNET_SCHEDULER_cancel(curl_download_task);
1573 curl_download_task = NULL;
1579 if (CURLM_OK != (mret = curl_multi_fdset(curl_multi,
1585 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1586 "%s failed at %s:%d: `%s'\n",
1587 "curl_multi_fdset", __FILE__, __LINE__,
1588 curl_multi_strerror(mret));
1592 GNUNET_break(CURLM_OK ==
1593 curl_multi_timeout(curl_multi,
1596 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1598 rtime = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS,
1602 grs = GNUNET_NETWORK_fdset_create();
1603 gws = GNUNET_NETWORK_fdset_create();
1604 GNUNET_NETWORK_fdset_copy_native(grs,
1607 GNUNET_NETWORK_fdset_copy_native(gws,
1610 curl_download_task = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1614 &curl_task_download,
1616 GNUNET_NETWORK_fdset_destroy(gws);
1617 GNUNET_NETWORK_fdset_destroy(grs);
1621 curl_download_task = GNUNET_SCHEDULER_add_delayed(rtime,
1622 &curl_task_download,
1629 * Task that is run when we are ready to receive more data from curl.
1631 * @param cls closure, NULL
1634 curl_task_download(void *cls)
1638 struct CURLMsg *msg;
1640 struct Socks5Request *s5r;
1642 curl_download_task = NULL;
1643 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1644 "Running CURL interaction\n");
1648 mret = curl_multi_perform(curl_multi,
1650 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1651 "Checking CURL multi status: %d\n",
1653 while (NULL != (msg = curl_multi_info_read(curl_multi,
1656 GNUNET_break(CURLE_OK ==
1657 curl_easy_getinfo(msg->easy_handle,
1668 /* documentation says this is not used */
1673 switch (msg->data.result)
1676 case CURLE_GOT_NOTHING:
1677 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1678 "CURL download %s%s completed.\n",
1681 if (NULL == s5r->response)
1683 GNUNET_assert(GNUNET_OK ==
1684 create_mhd_response_from_s5r(s5r));
1686 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1687 if (GNUNET_YES == s5r->suspended)
1689 MHD_resume_connection(s5r->con);
1690 s5r->suspended = GNUNET_NO;
1692 run_mhd_now(s5r->hd);
1696 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1697 "Download curl %s%s failed: %s\n",
1700 curl_easy_strerror(msg->data.result));
1701 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1702 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1703 if (GNUNET_YES == s5r->suspended)
1705 MHD_resume_connection(s5r->con);
1706 s5r->suspended = GNUNET_NO;
1708 run_mhd_now(s5r->hd);
1711 if (NULL == s5r->response)
1712 s5r->response = curl_failure_response;
1716 /* documentation says this is not used */
1721 /* unexpected status code */
1728 while (mret == CURLM_CALL_MULTI_PERFORM);
1729 if (CURLM_OK != mret)
1730 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1731 "%s failed at %s:%d: `%s'\n",
1732 "curl_multi_perform", __FILE__, __LINE__,
1733 curl_multi_strerror(mret));
1736 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1737 "Suspending cURL multi loop, no more events pending\n");
1738 if (NULL != curl_download_task)
1740 GNUNET_SCHEDULER_cancel(curl_download_task);
1741 curl_download_task = NULL;
1743 return; /* nothing more in progress */
1745 curl_download_prepare();
1749 /* ********************************* MHD response generation ******************* */
1753 * Read HTTP request header field from the request. Copies the fields
1754 * over to the 'headers' that will be given to curl. However, 'Host'
1755 * is substituted with the LEHO if present. We also change the
1756 * 'Connection' header value to "close" as the proxy does not support
1759 * @param cls our `struct Socks5Request`
1760 * @param kind value kind
1761 * @param key field key
1762 * @param value field value
1763 * @return #MHD_YES to continue to iterate
1766 con_val_iter(void *cls,
1767 enum MHD_ValueKind kind,
1771 struct Socks5Request *s5r = cls;
1774 if ((0 == strcasecmp(MHD_HTTP_HEADER_HOST,
1776 (NULL != s5r->leho))
1778 GNUNET_asprintf(&hdr,
1782 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1783 "Adding HEADER `%s' to HTTP request\n",
1785 s5r->headers = curl_slist_append(s5r->headers,
1793 * Main MHD callback for handling requests.
1796 * @param con MHD connection handle
1797 * @param url the url in the request
1798 * @param meth the HTTP method used ("GET", "PUT", etc.)
1799 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1800 * @param upload_data the data being uploaded (excluding HEADERS,
1801 * for a POST that fits into memory and that is encoded
1802 * with a supported encoding, the POST data will NOT be
1803 * given in upload_data and is instead available as
1804 * part of MHD_get_connection_values; very large POST
1805 * data *will* be made available incrementally in
1807 * @param upload_data_size set initially to the size of the
1808 * @a upload_data provided; the method must update this
1809 * value to the number of bytes NOT processed;
1810 * @param con_cls pointer to location where we store the `struct Request`
1811 * @return #MHD_YES if the connection was handled successfully,
1812 * #MHD_NO if the socket must be closed due to a serious
1813 * error while handling the request
1816 create_response(void *cls,
1817 struct MHD_Connection *con,
1821 const char *upload_data,
1822 size_t *upload_data_size,
1825 struct Socks5Request *s5r = *con_cls;
1827 char ipstring[INET6_ADDRSTRLEN];
1828 char ipaddr[INET6_ADDRSTRLEN + 2];
1829 const struct sockaddr *sa;
1830 const struct sockaddr_in *s4;
1831 const struct sockaddr_in6 *s6;
1841 /* Fresh connection. */
1842 if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
1844 /* first time here, initialize curl handle */
1847 sa = (const struct sockaddr *)&s5r->destination_address;
1848 switch (sa->sa_family)
1851 s4 = (const struct sockaddr_in *)&s5r->destination_address;
1852 if (NULL == inet_ntop(AF_INET,
1860 GNUNET_snprintf(ipaddr,
1864 port = ntohs(s4->sin_port);
1868 s6 = (const struct sockaddr_in6 *)&s5r->destination_address;
1869 if (NULL == inet_ntop(AF_INET6,
1877 GNUNET_snprintf(ipaddr,
1881 port = ntohs(s6->sin6_port);
1893 if (NULL == s5r->curl)
1894 s5r->curl = curl_easy_init();
1895 if (NULL == s5r->curl)
1896 return MHD_queue_response(con,
1897 MHD_HTTP_INTERNAL_SERVER_ERROR,
1898 curl_failure_response);
1899 curl_easy_setopt(s5r->curl,
1900 CURLOPT_HEADERFUNCTION,
1902 curl_easy_setopt(s5r->curl,
1905 curl_easy_setopt(s5r->curl,
1906 CURLOPT_FOLLOWLOCATION,
1909 curl_easy_setopt(s5r->curl,
1912 curl_easy_setopt(s5r->curl,
1913 CURLOPT_CONNECTTIMEOUT,
1915 curl_easy_setopt(s5r->curl,
1918 curl_easy_setopt(s5r->curl,
1921 curl_easy_setopt(s5r->curl,
1922 CURLOPT_HTTP_CONTENT_DECODING,
1924 curl_easy_setopt(s5r->curl,
1927 curl_easy_setopt(s5r->curl,
1930 curl_easy_setopt(s5r->curl,
1934 * Pre-populate cache to resolve Hostname.
1935 * This is necessary as the DNS name in the CURLOPT_URL is used
1936 * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1938 if (NULL != s5r->leho)
1942 GNUNET_asprintf(&curl_hosts,
1947 s5r->hosts = curl_slist_append(NULL,
1949 curl_easy_setopt(s5r->curl,
1952 GNUNET_free(curl_hosts);
1956 GNUNET_asprintf(&curlurl,
1957 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1959 : "https://%s:%d%s",
1968 GNUNET_asprintf(&curlurl,
1969 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1971 : "https://%s:%d%s",
1976 curl_easy_setopt(s5r->curl,
1979 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1980 "Launching %s CURL interaction, fetching `%s'\n",
1981 (s5r->is_gns) ? "GNS" : "DNS",
1983 GNUNET_free(curlurl);
1984 if (0 == strcasecmp(meth,
1985 MHD_HTTP_METHOD_PUT))
1987 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1988 curl_easy_setopt(s5r->curl,
1991 curl_easy_setopt(s5r->curl,
1992 CURLOPT_WRITEFUNCTION,
1994 curl_easy_setopt(s5r->curl,
1997 GNUNET_assert(CURLE_OK ==
1998 curl_easy_setopt(s5r->curl,
1999 CURLOPT_READFUNCTION,
2001 curl_easy_setopt(s5r->curl,
2006 long upload_size = 0;
2008 us = MHD_lookup_connection_value(con,
2010 MHD_HTTP_HEADER_CONTENT_LENGTH);
2011 if ((1 == sscanf(us,
2016 curl_easy_setopt(s5r->curl,
2022 else if (0 == strcasecmp(meth, MHD_HTTP_METHOD_POST))
2024 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
2025 curl_easy_setopt(s5r->curl,
2028 curl_easy_setopt(s5r->curl,
2029 CURLOPT_WRITEFUNCTION,
2031 curl_easy_setopt(s5r->curl,
2034 curl_easy_setopt(s5r->curl,
2035 CURLOPT_READFUNCTION,
2037 curl_easy_setopt(s5r->curl,
2045 us = MHD_lookup_connection_value(con,
2047 MHD_HTTP_HEADER_CONTENT_LENGTH);
2054 curl_easy_setopt(s5r->curl,
2060 curl_easy_setopt(s5r->curl,
2066 else if (0 == strcasecmp(meth,
2067 MHD_HTTP_METHOD_HEAD))
2069 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2070 curl_easy_setopt(s5r->curl,
2074 else if (0 == strcasecmp(meth,
2075 MHD_HTTP_METHOD_OPTIONS))
2077 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2078 curl_easy_setopt(s5r->curl,
2079 CURLOPT_CUSTOMREQUEST,
2081 curl_easy_setopt(s5r->curl,
2082 CURLOPT_WRITEFUNCTION,
2084 curl_easy_setopt(s5r->curl,
2088 else if (0 == strcasecmp(meth,
2089 MHD_HTTP_METHOD_GET))
2091 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2092 curl_easy_setopt(s5r->curl,
2095 curl_easy_setopt(s5r->curl,
2096 CURLOPT_WRITEFUNCTION,
2098 curl_easy_setopt(s5r->curl,
2102 else if (0 == strcasecmp(meth,
2103 MHD_HTTP_METHOD_DELETE))
2105 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2106 curl_easy_setopt(s5r->curl,
2107 CURLOPT_CUSTOMREQUEST,
2109 curl_easy_setopt(s5r->curl,
2110 CURLOPT_WRITEFUNCTION,
2112 curl_easy_setopt(s5r->curl,
2118 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
2119 _("Unsupported HTTP method `%s'\n"),
2121 curl_easy_cleanup(s5r->curl);
2126 if (0 == strcasecmp(ver, MHD_HTTP_VERSION_1_0))
2128 curl_easy_setopt(s5r->curl,
2129 CURLOPT_HTTP_VERSION,
2130 CURL_HTTP_VERSION_1_0);
2132 else if (0 == strcasecmp(ver, MHD_HTTP_VERSION_1_1))
2134 curl_easy_setopt(s5r->curl,
2135 CURLOPT_HTTP_VERSION,
2136 CURL_HTTP_VERSION_1_1);
2140 curl_easy_setopt(s5r->curl,
2141 CURLOPT_HTTP_VERSION,
2142 CURL_HTTP_VERSION_NONE);
2145 if (GNUNET_YES == s5r->is_tls) //(HTTPS_PORT == s5r->port)
2147 curl_easy_setopt(s5r->curl,
2150 if (0 < s5r->num_danes)
2151 curl_easy_setopt(s5r->curl,
2152 CURLOPT_SSL_VERIFYPEER,
2155 curl_easy_setopt(s5r->curl,
2156 CURLOPT_SSL_VERIFYPEER,
2158 /* Disable cURL checking the hostname, as we will check ourselves
2159 as only we have the domain name or the LEHO or the DANE record */
2160 curl_easy_setopt(s5r->curl,
2161 CURLOPT_SSL_VERIFYHOST,
2166 curl_easy_setopt(s5r->curl,
2172 curl_multi_add_handle(curl_multi,
2176 curl_easy_cleanup(s5r->curl);
2180 MHD_get_connection_values(con,
2182 (MHD_KeyValueIterator) & con_val_iter,
2184 curl_easy_setopt(s5r->curl,
2187 curl_download_prepare();
2191 /* continuing to process request */
2192 if (0 != *upload_data_size)
2194 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2195 "Processing %u bytes UPLOAD\n",
2196 (unsigned int)*upload_data_size);
2198 /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else
2199 * upload callback is not called!
2201 curl_easy_setopt(s5r->curl,
2202 CURLOPT_POSTFIELDSIZE,
2205 left = GNUNET_MIN(*upload_data_size,
2206 sizeof(s5r->io_buf) - s5r->io_len);
2207 GNUNET_memcpy(&s5r->io_buf[s5r->io_len],
2210 s5r->io_len += left;
2211 *upload_data_size -= left;
2212 GNUNET_assert(NULL != s5r->curl);
2213 if (GNUNET_YES == s5r->curl_paused)
2215 s5r->curl_paused = GNUNET_NO;
2216 curl_easy_pause(s5r->curl,
2221 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
2223 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2224 "Finished processing UPLOAD\n");
2225 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
2227 if (NULL == s5r->response)
2229 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2230 "Waiting for HTTP response for %s%s...\n",
2233 MHD_suspend_connection(con);
2234 s5r->suspended = GNUNET_YES;
2237 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2238 "Queueing response for %s%s with MHD\n",
2241 run_mhd_now(s5r->hd);
2242 return MHD_queue_response(con,
2248 /* ******************** MHD HTTP setup and event loop ******************** */
2252 * Function called when MHD decides that we are done with a request.
2255 * @param connection connection handle
2256 * @param con_cls value as set by the last call to
2257 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2258 * @param toe reason for request termination (ignored)
2261 mhd_completed_cb(void *cls,
2262 struct MHD_Connection *connection,
2264 enum MHD_RequestTerminationCode toe)
2266 struct Socks5Request *s5r = *con_cls;
2270 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
2271 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
2272 "MHD encountered error handling request: %d\n",
2274 if (NULL != s5r->curl)
2276 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2277 "Removing cURL handle (MHD interaction complete)\n");
2278 curl_multi_remove_handle(curl_multi,
2280 curl_slist_free_all(s5r->headers);
2281 s5r->headers = NULL;
2282 curl_easy_reset(s5r->curl);
2286 curl_download_prepare();
2288 if ((NULL != s5r->response) &&
2289 (curl_failure_response != s5r->response))
2290 MHD_destroy_response(s5r->response);
2291 for (struct HttpResponseHeader *header = s5r->header_head;
2293 header = s5r->header_head)
2295 GNUNET_CONTAINER_DLL_remove(s5r->header_head,
2298 GNUNET_free(header->type);
2299 GNUNET_free(header->value);
2300 GNUNET_free(header);
2302 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2303 "Finished request for %s\n",
2305 GNUNET_free(s5r->url);
2306 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2308 s5r->response = NULL;
2314 * Function called when MHD connection is opened or closed.
2317 * @param connection connection handle
2318 * @param con_cls value as set by the last call to
2319 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2320 * @param toe connection notification type
2323 mhd_connection_cb(void *cls,
2324 struct MHD_Connection *connection,
2326 enum MHD_ConnectionNotificationCode cnc)
2328 struct Socks5Request *s5r;
2329 const union MHD_ConnectionInfo *ci;
2334 case MHD_CONNECTION_NOTIFY_STARTED:
2335 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
2336 ci = MHD_get_connection_info(connection,
2337 MHD_CONNECTION_INFO_CONNECTION_FD);
2343 sock = ci->connect_fd;
2344 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
2346 if (GNUNET_NETWORK_get_fd(s5r->sock) == sock)
2348 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2349 "Context set...\n");
2350 s5r->ssl_checked = GNUNET_NO;
2357 case MHD_CONNECTION_NOTIFY_CLOSED:
2358 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2359 "Connection closed... cleaning up\n");
2363 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2364 "Connection stale!\n");
2368 curl_download_prepare();
2378 * Function called when MHD first processes an incoming connection.
2379 * Gives us the respective URI information.
2381 * We use this to associate the `struct MHD_Connection` with our
2382 * internal `struct Socks5Request` data structure (by checking
2383 * for matching sockets).
2385 * @param cls the HTTP server handle (a `struct MhdHttpList`)
2386 * @param url the URL that is being requested
2387 * @param connection MHD connection object for the request
2388 * @return the `struct Socks5Request` that this @a connection is for
2391 mhd_log_callback(void *cls,
2393 struct MHD_Connection *connection)
2395 struct Socks5Request *s5r;
2396 const union MHD_ConnectionInfo *ci;
2398 ci = MHD_get_connection_info(connection,
2399 MHD_CONNECTION_INFO_SOCKET_CONTEXT);
2400 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
2406 s5r = ci->socket_context;
2407 if (NULL != s5r->url)
2412 s5r->url = GNUNET_strdup(url);
2413 if (NULL != s5r->timeout_task)
2415 GNUNET_SCHEDULER_cancel(s5r->timeout_task);
2416 s5r->timeout_task = NULL;
2418 GNUNET_assert(s5r->state == SOCKS5_SOCKET_WITH_MHD);
2424 * Kill the given MHD daemon.
2426 * @param hd daemon to stop
2429 kill_httpd(struct MhdHttpList *hd)
2431 GNUNET_CONTAINER_DLL_remove(mhd_httpd_head,
2434 GNUNET_free_non_null(hd->domain);
2435 MHD_stop_daemon(hd->daemon);
2436 if (NULL != hd->httpd_task)
2438 GNUNET_SCHEDULER_cancel(hd->httpd_task);
2439 hd->httpd_task = NULL;
2441 GNUNET_free_non_null(hd->proxy_cert);
2449 * Task run whenever HTTP server is idle for too long. Kill it.
2451 * @param cls the `struct MhdHttpList *`
2454 kill_httpd_task(void *cls)
2456 struct MhdHttpList *hd = cls;
2458 hd->httpd_task = NULL;
2464 * Task run whenever HTTP server operations are pending.
2466 * @param cls the `struct MhdHttpList *` of the daemon that is being run
2469 do_httpd(void *cls);
2473 * Schedule MHD. This function should be called initially when an
2474 * MHD is first getting its client socket, and will then automatically
2475 * always be called later whenever there is work to be done.
2477 * @param hd the daemon to schedule
2480 schedule_httpd(struct MhdHttpList *hd)
2485 struct GNUNET_NETWORK_FDSet *wrs;
2486 struct GNUNET_NETWORK_FDSet *wws;
2489 MHD_UNSIGNED_LONG_LONG timeout;
2490 struct GNUNET_TIME_Relative tv;
2497 MHD_get_fdset(hd->daemon,
2506 haveto = MHD_get_timeout(hd->daemon,
2508 if (MHD_YES == haveto)
2509 tv.rel_value_us = (uint64_t)timeout * 1000LL;
2511 tv = GNUNET_TIME_UNIT_FOREVER_REL;
2514 wrs = GNUNET_NETWORK_fdset_create();
2515 wws = GNUNET_NETWORK_fdset_create();
2516 GNUNET_NETWORK_fdset_copy_native(wrs, &rs, max + 1);
2517 GNUNET_NETWORK_fdset_copy_native(wws, &ws, max + 1);
2524 if (NULL != hd->httpd_task)
2526 GNUNET_SCHEDULER_cancel(hd->httpd_task);
2527 hd->httpd_task = NULL;
2529 if ((MHD_YES != haveto) &&
2533 /* daemon is idle, kill after timeout */
2534 hd->httpd_task = GNUNET_SCHEDULER_add_delayed(MHD_CACHE_TIMEOUT,
2541 GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2546 GNUNET_NETWORK_fdset_destroy(wrs);
2548 GNUNET_NETWORK_fdset_destroy(wws);
2553 * Task run whenever HTTP server operations are pending.
2555 * @param cls the `struct MhdHttpList` of the daemon that is being run
2560 struct MhdHttpList *hd = cls;
2562 hd->httpd_task = NULL;
2563 MHD_run(hd->daemon);
2569 * Run MHD now, we have extra data ready for the callback.
2571 * @param hd the daemon to run now.
2574 run_mhd_now(struct MhdHttpList *hd)
2576 if (NULL != hd->httpd_task)
2577 GNUNET_SCHEDULER_cancel(hd->httpd_task);
2578 hd->httpd_task = GNUNET_SCHEDULER_add_now(&do_httpd,
2584 * Read file in filename
2586 * @param filename file to read
2587 * @param size pointer where filesize is stored
2588 * @return NULL on error
2591 load_file(const char* filename,
2598 GNUNET_DISK_file_size(filename,
2603 if (fsize > MAX_PEM_SIZE)
2605 *size = (unsigned int)fsize;
2606 buffer = GNUNET_malloc(*size);
2608 GNUNET_DISK_fn_read(filename,
2612 GNUNET_free(buffer);
2620 * Load PEM key from file
2622 * @param key where to store the data
2623 * @param keyfile path to the PEM file
2624 * @return #GNUNET_OK on success
2627 load_key_from_file(gnutls_x509_privkey_t key,
2628 const char* keyfile)
2630 gnutls_datum_t key_data;
2633 key_data.data = load_file(keyfile,
2635 if (NULL == key_data.data)
2636 return GNUNET_SYSERR;
2637 ret = gnutls_x509_privkey_import(key, &key_data,
2638 GNUTLS_X509_FMT_PEM);
2639 if (GNUTLS_E_SUCCESS != ret)
2641 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2642 _("Unable to import private key from file `%s'\n"),
2645 GNUNET_free_non_null(key_data.data);
2646 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2651 * Load cert from file
2653 * @param crt struct to store data in
2654 * @param certfile path to pem file
2655 * @return #GNUNET_OK on success
2658 load_cert_from_file(gnutls_x509_crt_t crt,
2659 const char* certfile)
2661 gnutls_datum_t cert_data;
2664 cert_data.data = load_file(certfile,
2666 if (NULL == cert_data.data)
2667 return GNUNET_SYSERR;
2668 ret = gnutls_x509_crt_import(crt,
2670 GNUTLS_X509_FMT_PEM);
2671 if (GNUTLS_E_SUCCESS != ret)
2673 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2674 _("Unable to import certificate from `%s'\n"),
2677 GNUNET_free_non_null(cert_data.data);
2678 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2683 * Generate new certificate for specific name
2685 * @param name the subject name to generate a cert for
2686 * @return a struct holding the PEM data, NULL on error
2688 static struct ProxyGNSCertificate *
2689 generate_gns_certificate(const char *name)
2691 unsigned int serial;
2692 size_t key_buf_size;
2693 size_t cert_buf_size;
2694 gnutls_x509_crt_t request;
2697 struct ProxyGNSCertificate *pgc;
2699 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2700 "Generating x.509 certificate for `%s'\n",
2702 GNUNET_break(GNUTLS_E_SUCCESS == gnutls_x509_crt_init(&request));
2703 GNUNET_break(GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key(request, proxy_ca.key));
2704 pgc = GNUNET_new(struct ProxyGNSCertificate);
2705 gnutls_x509_crt_set_dn_by_oid(request,
2706 GNUTLS_OID_X520_COUNTRY_NAME,
2710 gnutls_x509_crt_set_dn_by_oid(request,
2711 GNUTLS_OID_X520_ORGANIZATION_NAME,
2714 strlen("GNU Name System"));
2715 gnutls_x509_crt_set_dn_by_oid(request,
2716 GNUTLS_OID_X520_COMMON_NAME,
2720 gnutls_x509_crt_set_subject_alternative_name(request,
2723 GNUNET_break(GNUTLS_E_SUCCESS ==
2724 gnutls_x509_crt_set_version(request,
2726 gnutls_rnd(GNUTLS_RND_NONCE,
2729 gnutls_x509_crt_set_serial(request,
2733 tm_data = localtime(&etime);
2735 etime = mktime(tm_data);
2736 gnutls_x509_crt_set_activation_time(request,
2739 etime = mktime(tm_data);
2740 gnutls_x509_crt_set_expiration_time(request,
2742 gnutls_x509_crt_sign2(request,
2747 key_buf_size = sizeof(pgc->key);
2748 cert_buf_size = sizeof(pgc->cert);
2749 gnutls_x509_crt_export(request,
2750 GNUTLS_X509_FMT_PEM,
2753 gnutls_x509_privkey_export(proxy_ca.key,
2754 GNUTLS_X509_FMT_PEM,
2757 gnutls_x509_crt_deinit(request);
2763 * Function called by MHD with errors, suppresses them all.
2765 * @param cls closure
2766 * @param fm format string (`printf()`-style)
2767 * @param ap arguments to @a fm
2770 mhd_error_log_callback(void *cls,
2779 * Lookup (or create) an TLS MHD instance for a particular domain.
2781 * @param domain the domain the TLS daemon has to serve
2782 * @return NULL on error
2784 static struct MhdHttpList *
2785 lookup_ssl_httpd(const char* domain)
2787 struct MhdHttpList *hd;
2788 struct ProxyGNSCertificate *pgc;
2795 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2796 if ((NULL != hd->domain) &&
2797 (0 == strcmp(hd->domain, domain)))
2799 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2800 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2802 pgc = generate_gns_certificate(domain);
2803 hd = GNUNET_new(struct MhdHttpList);
2804 hd->is_ssl = GNUNET_YES;
2805 hd->domain = GNUNET_strdup(domain);
2806 hd->proxy_cert = pgc;
2807 hd->daemon = MHD_start_daemon(MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
2810 &create_response, hd,
2811 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)16,
2812 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2813 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
2814 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2815 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2816 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2817 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2819 if (NULL == hd->daemon)
2825 GNUNET_CONTAINER_DLL_insert(mhd_httpd_head,
2833 * Task run when a Socks5Request somehow fails to be associated with
2834 * an MHD connection (i.e. because the client never speaks HTTP after
2835 * the SOCKS5 handshake). Clean up.
2837 * @param cls the `struct Socks5Request *`
2840 timeout_s5r_handshake(void *cls)
2842 struct Socks5Request *s5r = cls;
2844 s5r->timeout_task = NULL;
2850 * We're done with the Socks5 protocol, now we need to pass the
2851 * connection data through to the final destination, either
2852 * direct (if the protocol might not be HTTP), or via MHD
2853 * (if the port looks like it should be HTTP).
2855 * @param s5r socks request that has reached the final stage
2858 setup_data_transfer(struct Socks5Request *s5r)
2860 struct MhdHttpList *hd;
2862 const struct sockaddr *addr;
2866 if (GNUNET_YES == s5r->is_tls)
2868 GNUNET_asprintf(&domain,
2871 hd = lookup_ssl_httpd(domain);
2874 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2875 _("Failed to start HTTPS server for `%s'\n"),
2878 GNUNET_free(domain);
2885 GNUNET_assert(NULL != httpd);
2888 fd = GNUNET_NETWORK_get_fd(s5r->sock);
2889 addr = GNUNET_NETWORK_get_addr(s5r->sock);
2890 len = GNUNET_NETWORK_get_addrlen(s5r->sock);
2891 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2893 MHD_add_connection(hd->daemon,
2898 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
2899 _("Failed to pass client to MHD\n"));
2901 GNUNET_free_non_null(domain);
2906 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed(HTTP_HANDSHAKE_TIMEOUT,
2907 &timeout_s5r_handshake,
2909 GNUNET_free_non_null(domain);
2913 /* ********************* SOCKS handling ************************* */
2917 * Write data from buffer to socks5 client, then continue with state machine.
2919 * @param cls the closure with the `struct Socks5Request`
2924 struct Socks5Request *s5r = cls;
2928 len = GNUNET_NETWORK_socket_send(s5r->sock,
2933 /* write error: connection closed, shutdown, etc.; just clean up */
2934 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2941 s5r->wbuf_len - len);
2942 s5r->wbuf_len -= len;
2943 if (s5r->wbuf_len > 0)
2945 /* not done writing */
2947 GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL,
2953 /* we're done writing, continue with state machine! */
2961 case SOCKS5_REQUEST:
2962 GNUNET_assert(NULL != s5r->rtask);
2965 case SOCKS5_DATA_TRANSFER:
2966 setup_data_transfer(s5r);
2969 case SOCKS5_WRITE_THEN_CLEANUP:
2981 * Return a server response message indicating a failure to the client.
2983 * @param s5r request to return failure code for
2984 * @param sc status code to return
2987 signal_socks_failure(struct Socks5Request *s5r,
2988 enum Socks5StatusCode sc)
2990 struct Socks5ServerResponseMessage *s_resp;
2992 s_resp = (struct Socks5ServerResponseMessage *)&s5r->wbuf[s5r->wbuf_len];
2993 memset(s_resp, 0, sizeof(struct Socks5ServerResponseMessage));
2994 s_resp->version = SOCKS_VERSION_5;
2996 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2997 if (NULL != s5r->wtask)
2999 GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL,
3006 * Return a server response message indicating success.
3008 * @param s5r request to return success status message for
3011 signal_socks_success(struct Socks5Request *s5r)
3013 struct Socks5ServerResponseMessage *s_resp;
3015 s_resp = (struct Socks5ServerResponseMessage *)&s5r->wbuf[s5r->wbuf_len];
3016 s_resp->version = SOCKS_VERSION_5;
3017 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
3018 s_resp->reserved = 0;
3019 s_resp->addr_type = SOCKS5_AT_IPV4;
3020 /* zero out IPv4 address and port */
3023 sizeof(struct in_addr) + sizeof(uint16_t));
3024 s5r->wbuf_len += sizeof(struct Socks5ServerResponseMessage) +
3025 sizeof(struct in_addr) + sizeof(uint16_t);
3026 if (NULL == s5r->wtask)
3028 GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL,
3035 * Process GNS results for target domain.
3037 * @param cls the `struct Socks5Request *`
3038 * @param tld #GNUNET_YES if this was a GNS TLD.
3039 * @param rd_count number of records returned
3040 * @param rd record data
3043 handle_gns_result(void *cls,
3046 const struct GNUNET_GNSRECORD_Data *rd)
3048 struct Socks5Request *s5r = cls;
3049 const struct GNUNET_GNSRECORD_Data *r;
3052 s5r->gns_lookup = NULL;
3055 for (uint32_t i = 0; i < rd_count; i++)
3058 switch (r->record_type)
3060 case GNUNET_DNSPARSER_TYPE_A:
3062 struct sockaddr_in *in;
3064 if (sizeof(struct in_addr) != r->data_size)
3069 if (GNUNET_YES == got_ip)
3072 GNUNET_NETWORK_test_pf(PF_INET))
3074 got_ip = GNUNET_YES;
3075 in = (struct sockaddr_in *)&s5r->destination_address;
3076 in->sin_family = AF_INET;
3077 GNUNET_memcpy(&in->sin_addr,
3080 in->sin_port = htons(s5r->port);
3081 #if HAVE_SOCKADDR_IN_SIN_LEN
3082 in->sin_len = sizeof(*in);
3087 case GNUNET_DNSPARSER_TYPE_AAAA:
3089 struct sockaddr_in6 *in;
3091 if (sizeof(struct in6_addr) != r->data_size)
3096 if (GNUNET_YES == got_ip)
3098 if (GNUNET_YES == disable_v6)
3101 GNUNET_NETWORK_test_pf(PF_INET6))
3103 /* FIXME: allow user to disable IPv6 per configuration option... */
3104 got_ip = GNUNET_YES;
3105 in = (struct sockaddr_in6 *)&s5r->destination_address;
3106 in->sin6_family = AF_INET6;
3107 GNUNET_memcpy(&in->sin6_addr,
3110 in->sin6_port = htons(s5r->port);
3111 #if HAVE_SOCKADDR_IN_SIN_LEN
3112 in->sin6_len = sizeof(*in);
3117 case GNUNET_GNSRECORD_TYPE_VPN:
3118 GNUNET_break(0); /* should have been translated within GNS */
3121 case GNUNET_GNSRECORD_TYPE_LEHO:
3122 GNUNET_free_non_null(s5r->leho);
3123 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))
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]);
3161 if ((GNUNET_YES != got_ip) &&
3162 (GNUNET_YES == tld))
3164 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3165 "Name resolution failed to yield useful IP address.\n");
3166 signal_socks_failure(s5r,
3167 SOCKS5_STATUS_GENERAL_FAILURE);
3170 s5r->state = SOCKS5_DATA_TRANSFER;
3171 signal_socks_success(s5r);
3176 * Remove the first @a len bytes from the beginning of the read buffer.
3178 * @param s5r the handle clear the read buffer for
3179 * @param len number of bytes in read buffer to advance
3182 clear_from_s5r_rbuf(struct Socks5Request *s5r,
3185 GNUNET_assert(len <= s5r->rbuf_len);
3188 s5r->rbuf_len - len);
3189 s5r->rbuf_len -= len;
3194 * Read data from incoming Socks5 connection
3196 * @param cls the closure with the `struct Socks5Request`
3199 do_s5r_read(void *cls)
3201 struct Socks5Request *s5r = cls;
3202 const struct Socks5ClientHelloMessage *c_hello;
3203 struct Socks5ServerHelloMessage *s_hello;
3204 const struct Socks5ClientRequestMessage *c_req;
3207 const struct GNUNET_SCHEDULER_TaskContext *tc;
3210 tc = GNUNET_SCHEDULER_get_task_context();
3211 if ((NULL != tc->read_ready) &&
3212 (GNUNET_NETWORK_fdset_isset(tc->read_ready,
3215 rlen = GNUNET_NETWORK_socket_recv(s5r->sock,
3216 &s5r->rbuf[s5r->rbuf_len],
3217 sizeof(s5r->rbuf) - s5r->rbuf_len);
3220 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3221 "socks5 client disconnected.\n");
3225 s5r->rbuf_len += rlen;
3227 s5r->rtask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
3230 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3231 "Processing %zu bytes of socks data in state %d\n",
3237 c_hello = (const struct Socks5ClientHelloMessage*)&s5r->rbuf;
3238 if ((s5r->rbuf_len < sizeof(struct Socks5ClientHelloMessage)) ||
3239 (s5r->rbuf_len < sizeof(struct Socks5ClientHelloMessage) + c_hello->num_auth_methods))
3240 return; /* need more data */
3241 if (SOCKS_VERSION_5 != c_hello->version)
3243 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3244 _("Unsupported socks version %d\n"),
3245 (int)c_hello->version);
3249 clear_from_s5r_rbuf(s5r,
3250 sizeof(struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
3251 GNUNET_assert(0 == s5r->wbuf_len);
3252 s_hello = (struct Socks5ServerHelloMessage *)&s5r->wbuf;
3253 s5r->wbuf_len = sizeof(struct Socks5ServerHelloMessage);
3254 s_hello->version = SOCKS_VERSION_5;
3255 s_hello->auth_method = SOCKS_AUTH_NONE;
3256 GNUNET_assert(NULL == s5r->wtask);
3257 s5r->wtask = GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL,
3260 s5r->state = SOCKS5_REQUEST;
3263 case SOCKS5_REQUEST:
3264 c_req = (const struct Socks5ClientRequestMessage *)&s5r->rbuf;
3265 if (s5r->rbuf_len < sizeof(struct Socks5ClientRequestMessage))
3267 switch (c_req->command)
3269 case SOCKS5_CMD_TCP_STREAM:
3274 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3275 _("Unsupported socks command %d\n"),
3276 (int)c_req->command);
3277 signal_socks_failure(s5r,
3278 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
3281 switch (c_req->addr_type)
3283 case SOCKS5_AT_IPV4:
3285 const struct in_addr *v4 = (const struct in_addr *)&c_req[1];
3286 const uint16_t *port = (const uint16_t *)&v4[1];
3287 struct sockaddr_in *in;
3289 s5r->port = ntohs(*port);
3290 alen = sizeof(struct in_addr);
3291 if (s5r->rbuf_len < sizeof(struct Socks5ClientRequestMessage) +
3292 alen + sizeof(uint16_t))
3293 return; /* need more data */
3294 in = (struct sockaddr_in *)&s5r->destination_address;
3295 in->sin_family = AF_INET;
3297 in->sin_port = *port;
3298 #if HAVE_SOCKADDR_IN_SIN_LEN
3299 in->sin_len = sizeof(*in);
3301 s5r->state = SOCKS5_DATA_TRANSFER;
3305 case SOCKS5_AT_IPV6:
3307 const struct in6_addr *v6 = (const struct in6_addr *)&c_req[1];
3308 const uint16_t *port = (const uint16_t *)&v6[1];
3309 struct sockaddr_in6 *in;
3311 s5r->port = ntohs(*port);
3312 alen = sizeof(struct in6_addr);
3313 if (s5r->rbuf_len < sizeof(struct Socks5ClientRequestMessage) +
3314 alen + sizeof(uint16_t))
3315 return; /* need more data */
3316 in = (struct sockaddr_in6 *)&s5r->destination_address;
3317 in->sin6_family = AF_INET6;
3318 in->sin6_addr = *v6;
3319 in->sin6_port = *port;
3320 #if HAVE_SOCKADDR_IN_SIN_LEN
3321 in->sin6_len = sizeof(*in);
3323 s5r->state = SOCKS5_DATA_TRANSFER;
3327 case SOCKS5_AT_DOMAINNAME:
3329 const uint8_t *dom_len;
3330 const char *dom_name;
3331 const uint16_t *port;
3333 dom_len = (const uint8_t *)&c_req[1];
3334 alen = *dom_len + 1;
3335 if (s5r->rbuf_len < sizeof(struct Socks5ClientRequestMessage) +
3336 alen + sizeof(uint16_t))
3337 return; /* need more data */
3338 dom_name = (const char *)&dom_len[1];
3339 port = (const uint16_t*)&dom_name[*dom_len];
3340 s5r->domain = GNUNET_strndup(dom_name,
3342 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3343 "Requested connection is to %s:%d\n",
3344 //(HTTPS_PORT == s5r->port) ? "s" : "",
3347 s5r->state = SOCKS5_RESOLVING;
3348 s5r->port = ntohs(*port);
3349 s5r->is_tls = (HTTPS_PORT == s5r->port) ? GNUNET_YES : GNUNET_NO;
3350 s5r->gns_lookup = GNUNET_GNS_lookup_with_tld(gns_handle,
3352 GNUNET_DNSPARSER_TYPE_A,
3353 GNUNET_NO /* only cached */,
3360 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3361 _("Unsupported socks address type %d\n"),
3362 (int)c_req->addr_type);
3363 signal_socks_failure(s5r,
3364 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
3367 clear_from_s5r_rbuf(s5r,
3368 sizeof(struct Socks5ClientRequestMessage) +
3369 alen + sizeof(uint16_t));
3370 if (0 != s5r->rbuf_len)
3372 /* read more bytes than healthy, why did the client send more!? */
3374 signal_socks_failure(s5r,
3375 SOCKS5_STATUS_GENERAL_FAILURE);
3378 if (SOCKS5_DATA_TRANSFER == s5r->state)
3380 /* if we are not waiting for GNS resolution, signal success */
3381 signal_socks_success(s5r);
3383 /* We are done reading right now */
3384 GNUNET_SCHEDULER_cancel(s5r->rtask);
3388 case SOCKS5_RESOLVING:
3392 case SOCKS5_DATA_TRANSFER:
3404 * Accept new incoming connections
3406 * @param cls the closure with the lsock4 or lsock6
3407 * @param tc the scheduler context
3410 do_accept(void *cls)
3412 struct GNUNET_NETWORK_Handle *lsock = cls;
3413 struct GNUNET_NETWORK_Handle *s;
3414 struct Socks5Request *s5r;
3416 GNUNET_assert(NULL != lsock);
3417 if (lsock == lsock4)
3418 ltask4 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
3422 else if (lsock == lsock6)
3423 ltask6 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
3429 s = GNUNET_NETWORK_socket_accept(lsock,
3434 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR,
3438 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3439 "Got an inbound connection, waiting for data\n");
3440 s5r = GNUNET_new(struct Socks5Request);
3441 GNUNET_CONTAINER_DLL_insert(s5r_head,
3445 s5r->state = SOCKS5_INIT;
3446 s5r->rtask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
3453 /* ******************* General / main code ********************* */
3457 * Task run on shutdown
3459 * @param cls closure
3462 do_shutdown(void *cls)
3464 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
3465 "Shutting down...\n");
3466 /* MHD requires resuming before destroying the daemons */
3467 for (struct Socks5Request *s5r = s5r_head;
3473 s5r->suspended = GNUNET_NO;
3474 MHD_resume_connection(s5r->con);
3477 while (NULL != mhd_httpd_head)
3478 kill_httpd(mhd_httpd_head);
3479 while (NULL != s5r_head)
3480 cleanup_s5r(s5r_head);
3483 GNUNET_NETWORK_socket_close(lsock4);
3488 GNUNET_NETWORK_socket_close(lsock6);
3491 if (NULL != curl_multi)
3493 curl_multi_cleanup(curl_multi);
3496 if (NULL != gns_handle)
3498 GNUNET_GNS_disconnect(gns_handle);
3501 if (NULL != curl_download_task)
3503 GNUNET_SCHEDULER_cancel(curl_download_task);
3504 curl_download_task = NULL;
3508 GNUNET_SCHEDULER_cancel(ltask4);
3513 GNUNET_SCHEDULER_cancel(ltask6);
3516 gnutls_x509_crt_deinit(proxy_ca.cert);
3517 gnutls_x509_privkey_deinit(proxy_ca.key);
3518 gnutls_global_deinit();
3523 * Create an IPv4 listen socket bound to our port.
3525 * @return NULL on error
3527 static struct GNUNET_NETWORK_Handle *
3530 struct GNUNET_NETWORK_Handle *ls;
3531 struct sockaddr_in sa4;
3534 memset(&sa4, 0, sizeof(sa4));
3535 sa4.sin_family = AF_INET;
3536 sa4.sin_port = htons(port);
3537 sa4.sin_addr.s_addr = address;
3538 #if HAVE_SOCKADDR_IN_SIN_LEN
3539 sa4.sin_len = sizeof(sa4);
3541 ls = GNUNET_NETWORK_socket_create(AF_INET,
3547 GNUNET_NETWORK_socket_bind(ls,
3548 (const struct sockaddr *)&sa4,
3552 GNUNET_NETWORK_socket_close(ls);
3561 * Create an IPv6 listen socket bound to our port.
3563 * @return NULL on error
3565 static struct GNUNET_NETWORK_Handle *
3568 struct GNUNET_NETWORK_Handle *ls;
3569 struct sockaddr_in6 sa6;
3572 memset(&sa6, 0, sizeof(sa6));
3573 sa6.sin6_family = AF_INET6;
3574 sa6.sin6_port = htons(port);
3575 sa6.sin6_addr = address6;
3576 #if HAVE_SOCKADDR_IN_SIN_LEN
3577 sa6.sin6_len = sizeof(sa6);
3579 ls = GNUNET_NETWORK_socket_create(AF_INET6,
3585 GNUNET_NETWORK_socket_bind(ls,
3586 (const struct sockaddr *)&sa6,
3590 GNUNET_NETWORK_socket_close(ls);
3599 * Main function that will be run
3601 * @param cls closure
3602 * @param args remaining command-line arguments
3603 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3604 * @param c configuration
3609 const char *cfgfile,
3610 const struct GNUNET_CONFIGURATION_Handle *c)
3612 char* cafile_cfg = NULL;
3615 struct MhdHttpList *hd;
3619 /* Get address to bind to */
3620 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, "gns-proxy",
3624 //No address specified
3625 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3626 "Don't know what to bind to...\n");
3627 GNUNET_free(addr_str);
3628 GNUNET_SCHEDULER_shutdown();
3631 if (1 != inet_pton(AF_INET, addr_str, &address))
3633 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3634 "Unable to parse address %s\n",
3636 GNUNET_free(addr_str);
3637 GNUNET_SCHEDULER_shutdown();
3640 GNUNET_free(addr_str);
3641 /* Get address to bind to */
3642 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, "gns-proxy",
3646 //No address specified
3647 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3648 "Don't know what to bind6 to...\n");
3649 GNUNET_free(addr_str);
3650 GNUNET_SCHEDULER_shutdown();
3653 if (1 != inet_pton(AF_INET6, addr_str, &address6))
3655 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3656 "Unable to parse IPv6 address %s\n",
3658 GNUNET_free(addr_str);
3659 GNUNET_SCHEDULER_shutdown();
3662 GNUNET_free(addr_str);
3664 if (NULL == (curl_multi = curl_multi_init()))
3666 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3667 "Failed to create cURL multi handle!\n");
3670 cafile = cafile_opt;
3674 GNUNET_CONFIGURATION_get_value_filename(cfg,
3679 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR,
3684 cafile = cafile_cfg;
3686 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3687 "Using `%s' as CA\n",
3690 gnutls_global_init();
3691 gnutls_x509_crt_init(&proxy_ca.cert);
3692 gnutls_x509_privkey_init(&proxy_ca.key);
3695 load_cert_from_file(proxy_ca.cert,
3698 load_key_from_file(proxy_ca.key,
3701 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3702 _("Failed to load X.509 key and certificate from `%s'\n"),
3704 gnutls_x509_crt_deinit(proxy_ca.cert);
3705 gnutls_x509_privkey_deinit(proxy_ca.key);
3706 gnutls_global_deinit();
3707 GNUNET_free_non_null(cafile_cfg);
3710 GNUNET_free_non_null(cafile_cfg);
3711 if (NULL == (gns_handle = GNUNET_GNS_connect(cfg)))
3713 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3714 "Unable to connect to GNS!\n");
3715 gnutls_x509_crt_deinit(proxy_ca.cert);
3716 gnutls_x509_privkey_deinit(proxy_ca.key);
3717 gnutls_global_deinit();
3720 GNUNET_SCHEDULER_add_shutdown(&do_shutdown,
3723 /* Open listen socket for socks proxy */
3727 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR,
3733 GNUNET_NETWORK_socket_listen(lsock6,
3736 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR,
3738 GNUNET_NETWORK_socket_close(lsock6);
3743 ltask6 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
3752 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR,
3758 GNUNET_NETWORK_socket_listen(lsock4,
3761 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR,
3763 GNUNET_NETWORK_socket_close(lsock4);
3768 ltask4 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
3774 if ((NULL == lsock4) &&
3777 GNUNET_SCHEDULER_shutdown();
3780 if (0 != curl_global_init(CURL_GLOBAL_WIN32))
3782 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
3783 "cURL global init failed!\n");
3784 GNUNET_SCHEDULER_shutdown();
3787 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3788 "Proxy listens on port %u\n",
3789 (unsigned int)port);
3791 /* start MHD daemon for HTTP */
3792 hd = GNUNET_new(struct MhdHttpList);
3793 hd->daemon = MHD_start_daemon(MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
3796 &create_response, hd,
3797 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)16,
3798 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3799 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
3800 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3802 if (NULL == hd->daemon)
3805 GNUNET_SCHEDULER_shutdown();
3809 GNUNET_CONTAINER_DLL_insert(mhd_httpd_head,
3816 * The main function for gnunet-gns-proxy.
3818 * @param argc number of arguments from the command line
3819 * @param argv command line arguments
3820 * @return 0 ok, 1 on error
3826 struct GNUNET_GETOPT_CommandLineOption options[] = {
3827 GNUNET_GETOPT_option_uint16('p',
3830 gettext_noop("listen on specified port (default: 7777)"),
3832 GNUNET_GETOPT_option_string('a',
3835 gettext_noop("pem file to use as CA"),
3837 GNUNET_GETOPT_option_flag('6',
3839 gettext_noop("disable use of IPv6"),
3842 GNUNET_GETOPT_OPTION_END
3844 static const char* page =
3845 "<html><head><title>gnunet-gns-proxy</title>"
3846 "</head><body>cURL fail</body></html>";
3850 GNUNET_STRINGS_get_utf8_args(argc, argv,
3853 GNUNET_log_setup("gnunet-gns-proxy",
3856 curl_failure_response
3857 = MHD_create_response_from_buffer(strlen(page),
3859 MHD_RESPMEM_PERSISTENT);
3863 GNUNET_PROGRAM_run(argc, argv,
3865 _("GNUnet GNS proxy"),
3867 &run, NULL)) ? 0 : 1;
3868 MHD_destroy_response(curl_failure_response);
3869 GNUNET_free_non_null((char *)argv);
3873 /* end of gnunet-gns-proxy.c */