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 **************************** */
666 * The port the proxy is running on (default 7777)
668 static uint16_t port = GNUNET_GNS_PROXY_PORT;
671 * The CA file (pem) to use for the proxy CA
673 static char *cafile_opt;
676 * The listen socket of the proxy for IPv4
678 static struct GNUNET_NETWORK_Handle *lsock4;
681 * The listen socket of the proxy for IPv6
683 static struct GNUNET_NETWORK_Handle *lsock6;
686 * The listen task ID for IPv4
688 static struct GNUNET_SCHEDULER_Task * ltask4;
691 * The listen task ID for IPv6
693 static struct GNUNET_SCHEDULER_Task * ltask6;
696 * The cURL download task (curl multi API).
698 static struct GNUNET_SCHEDULER_Task * curl_download_task;
701 * The cURL multi handle
703 static CURLM *curl_multi;
706 * Handle to the GNS service
708 static struct GNUNET_GNS_Handle *gns_handle;
713 static int disable_v6;
716 * DLL for http/https daemons
718 static struct MhdHttpList *mhd_httpd_head;
721 * DLL for http/https daemons
723 static struct MhdHttpList *mhd_httpd_tail;
726 * Daemon for HTTP (we have one per X.509 certificate, and then one for
727 * all HTTP connections; this is the one for HTTP, not HTTPS).
729 static struct MhdHttpList *httpd;
732 * DLL of active socks requests.
734 static struct Socks5Request *s5r_head;
737 * DLL of active socks requests.
739 static struct Socks5Request *s5r_tail;
742 * The CA for X.509 certificate generation
744 static struct ProxyCA proxy_ca;
747 * Response we return on cURL failures.
749 static struct MHD_Response *curl_failure_response;
754 static const struct GNUNET_CONFIGURATION_Handle *cfg;
757 /* ************************* Global helpers ********************* */
761 * Run MHD now, we have extra data ready for the callback.
763 * @param hd the daemon to run now.
766 run_mhd_now (struct MhdHttpList *hd);
770 * Clean up s5r handles.
772 * @param s5r the handle to destroy
775 cleanup_s5r (struct Socks5Request *s5r)
777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
778 "Cleaning up socks request\n");
779 if (NULL != s5r->curl)
781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
782 "Cleaning up cURL handle\n");
783 curl_multi_remove_handle (curl_multi,
785 curl_easy_cleanup (s5r->curl);
790 s5r->suspended = GNUNET_NO;
791 MHD_resume_connection (s5r->con);
793 curl_slist_free_all (s5r->headers);
794 if (NULL != s5r->hosts)
796 curl_slist_free_all (s5r->hosts);
798 if ( (NULL != s5r->response) &&
799 (curl_failure_response != s5r->response) )
801 MHD_destroy_response (s5r->response);
802 s5r->response = NULL;
804 if (NULL != s5r->rtask)
806 GNUNET_SCHEDULER_cancel (s5r->rtask);
809 if (NULL != s5r->timeout_task)
811 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
812 s5r->timeout_task = NULL;
814 if (NULL != s5r->wtask)
816 GNUNET_SCHEDULER_cancel (s5r->wtask);
819 if (NULL != s5r->gns_lookup)
821 GNUNET_GNS_lookup_with_tld_cancel (s5r->gns_lookup);
822 s5r->gns_lookup = NULL;
824 if (NULL != s5r->sock)
826 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
827 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
829 GNUNET_NETWORK_socket_close (s5r->sock);
832 GNUNET_CONTAINER_DLL_remove (s5r_head,
835 GNUNET_free_non_null (s5r->domain);
836 GNUNET_free_non_null (s5r->leho);
837 GNUNET_free_non_null (s5r->url);
838 for (unsigned int i=0;i<s5r->num_danes;i++)
839 GNUNET_free (s5r->dane_data[i]);
844 /* ************************* HTTP handling with cURL *********************** */
847 curl_download_prepare ();
851 * Callback for MHD response generation. This function is called from
852 * MHD whenever MHD expects to get data back. Copies data from the
853 * io_buf, if available.
855 * @param cls closure with our `struct Socks5Request`
856 * @param pos in buffer
857 * @param buf where to copy data
858 * @param max available space in @a buf
859 * @return number of bytes written to @a buf
862 mhd_content_cb (void *cls,
867 struct Socks5Request *s5r = cls;
868 size_t bytes_to_copy;
870 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
871 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
873 /* we're still not done with the upload, do not yet
874 start the download, the IO buffer is still full
876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
877 "Pausing MHD download %s%s, not yet ready for download\n",
880 return 0; /* not yet ready for data download */
882 bytes_to_copy = GNUNET_MIN (max,
884 if ( (0 == bytes_to_copy) &&
885 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
887 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
888 "Pausing MHD download %s%s, no data available\n",
891 if (NULL != s5r->curl)
893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
894 "Continuing CURL interaction for %s%s\n",
897 if (GNUNET_YES == s5r->curl_paused)
899 s5r->curl_paused = GNUNET_NO;
900 curl_easy_pause (s5r->curl,
903 curl_download_prepare ();
905 if (GNUNET_NO == s5r->suspended)
907 MHD_suspend_connection (s5r->con);
908 s5r->suspended = GNUNET_YES;
910 return 0; /* more data later */
912 if ( (0 == bytes_to_copy) &&
913 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
915 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
916 "Completed MHD download %s%s\n",
919 return MHD_CONTENT_READER_END_OF_STREAM;
921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
922 "Writing %llu/%llu bytes to %s%s\n",
923 (unsigned long long) bytes_to_copy,
924 (unsigned long long) s5r->io_len,
930 memmove (s5r->io_buf,
931 &s5r->io_buf[bytes_to_copy],
932 s5r->io_len - bytes_to_copy);
933 s5r->io_len -= bytes_to_copy;
934 if ( (NULL != s5r->curl) &&
935 (GNUNET_YES == s5r->curl_paused) )
937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938 "Continuing CURL interaction for %s%s\n",
941 s5r->curl_paused = GNUNET_NO;
942 curl_easy_pause (s5r->curl,
945 return bytes_to_copy;
950 * Check that the website has presented us with a valid X.509 certificate.
951 * The certificate must either match the domain name or the LEHO name
952 * (or, if available, the TLSA record).
954 * @param s5r request to check for.
955 * @return #GNUNET_OK if the certificate is valid
958 check_ssl_certificate (struct Socks5Request *s5r)
960 unsigned int cert_list_size;
961 const gnutls_datum_t *chainp;
962 const struct curl_tlssessioninfo *tlsinfo;
963 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
965 gnutls_x509_crt_t x509_cert;
969 s5r->ssl_checked = GNUNET_YES;
970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
971 "Checking X.509 certificate\n");
973 curl_easy_getinfo (s5r->curl,
974 CURLINFO_TLS_SESSION,
975 (struct curl_slist **) &tlsinfo))
976 return GNUNET_SYSERR;
977 if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
979 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
980 _("Unsupported CURL TLS backend %d\n"),
982 return GNUNET_SYSERR;
984 chainp = gnutls_certificate_get_peers (tlsinfo->internals,
987 (0 == cert_list_size) )
988 return GNUNET_SYSERR;
990 size = sizeof (certdn);
991 /* initialize an X.509 certificate structure. */
992 gnutls_x509_crt_init (&x509_cert);
993 gnutls_x509_crt_import (x509_cert,
995 GNUTLS_X509_FMT_DER);
997 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
998 GNUTLS_OID_X520_COMMON_NAME,
999 0, /* the first and only one */
1000 0 /* no DER encoding */,
1004 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1005 _("Failed to fetch CN from cert: %s\n"),
1006 gnutls_strerror(rc));
1007 gnutls_x509_crt_deinit (x509_cert);
1008 return GNUNET_SYSERR;
1010 /* check for TLSA/DANE records */
1011 #if HAVE_GNUTLS_DANE
1012 if (0 != s5r->num_danes)
1014 dane_state_t dane_state;
1015 dane_query_t dane_query;
1016 unsigned int verify;
1018 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
1019 if (0 != (rc = dane_state_init (&dane_state,
1020 #ifdef DANE_F_IGNORE_DNSSEC
1021 DANE_F_IGNORE_DNSSEC |
1023 DANE_F_IGNORE_LOCAL_RESOLVER)))
1025 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1026 _("Failed to initialize DANE: %s\n"),
1028 gnutls_x509_crt_deinit (x509_cert);
1029 return GNUNET_SYSERR;
1031 s5r->dane_data[s5r->num_danes] = NULL;
1032 s5r->dane_data_len[s5r->num_danes] = 0;
1033 if (0 != (rc = dane_raw_tlsa (dane_state,
1040 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1041 _("Failed to parse DANE record: %s\n"),
1043 dane_state_deinit (dane_state);
1044 gnutls_x509_crt_deinit (x509_cert);
1045 return GNUNET_SYSERR;
1047 if (0 != (rc = dane_verify_crt_raw (dane_state,
1050 gnutls_certificate_type_get (tlsinfo->internals),
1055 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1056 _("Failed to verify TLS connection using DANE: %s\n"),
1058 dane_query_deinit (dane_query);
1059 dane_state_deinit (dane_state);
1060 gnutls_x509_crt_deinit (x509_cert);
1061 return GNUNET_SYSERR;
1065 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1066 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
1068 dane_query_deinit (dane_query);
1069 dane_state_deinit (dane_state);
1070 gnutls_x509_crt_deinit (x509_cert);
1071 return GNUNET_SYSERR;
1073 dane_query_deinit (dane_query);
1074 dane_state_deinit (dane_state);
1080 /* try LEHO or ordinary domain name X509 verification */
1082 if (NULL != s5r->leho)
1086 if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
1089 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1090 _("TLS certificate subject name (%s) does not match `%s': %d\n"),
1094 gnutls_x509_crt_deinit (x509_cert);
1095 return GNUNET_SYSERR;
1100 /* we did not even have the domain name!? */
1102 return GNUNET_SYSERR;
1105 gnutls_x509_crt_deinit (x509_cert);
1111 * We're getting an HTTP response header from cURL. Convert it to the
1112 * MHD response headers. Mostly copies the headers, but makes special
1113 * adjustments to "Set-Cookie" and "Location" headers as those may need
1114 * to be changed from the LEHO to the domain the browser expects.
1116 * @param buffer curl buffer with a single line of header data; not 0-terminated!
1117 * @param size curl blocksize
1118 * @param nmemb curl blocknumber
1119 * @param cls our `struct Socks5Request *`
1120 * @return size of processed bytes
1123 curl_check_hdr (void *buffer,
1128 struct Socks5Request *s5r = cls;
1129 struct HttpResponseHeader *header;
1130 size_t bytes = size * nmemb;
1132 const char *hdr_type;
1133 const char *cookie_domain;
1135 char *new_cookie_hdr;
1138 size_t delta_cdomain;
1142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1143 "Receiving HTTP response header from CURL\n");
1144 /* first, check TLS certificate */
1145 if ( (GNUNET_YES != s5r->ssl_checked) &&
1146 (GNUNET_YES == s5r->is_tls))
1147 //(HTTPS_PORT == s5r->port))
1149 if (GNUNET_OK != check_ssl_certificate (s5r))
1152 ndup = GNUNET_strndup (buffer,
1154 hdr_type = strtok (ndup,
1156 if (NULL == hdr_type)
1161 hdr_val = strtok (NULL,
1163 if (NULL == hdr_val)
1168 if (' ' == *hdr_val)
1171 /* custom logic for certain header types */
1172 new_cookie_hdr = NULL;
1173 if ( (NULL != s5r->leho) &&
1174 (0 == strcasecmp (hdr_type,
1175 MHD_HTTP_HEADER_SET_COOKIE)) )
1178 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1179 strlen (s5r->domain) + 1);
1181 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1182 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1184 if ( (0 == strncasecmp (tok,
1186 strlen (" domain"))) &&
1187 (GNUNET_NO == domain_matched) )
1189 domain_matched = GNUNET_YES;
1190 cookie_domain = tok + strlen (" domain") + 1;
1191 if (strlen (cookie_domain) < strlen (s5r->leho))
1193 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1194 if (0 == strcasecmp (cookie_domain,
1195 s5r->leho + delta_cdomain))
1197 offset += sprintf (new_cookie_hdr + offset,
1203 else if (0 == strcmp (cookie_domain,
1206 offset += sprintf (new_cookie_hdr + offset,
1211 else if ( ('.' == cookie_domain[0]) &&
1212 (0 == strcmp (&cookie_domain[1],
1215 offset += sprintf (new_cookie_hdr + offset,
1220 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1221 _("Cookie domain `%s' supplied by server is invalid\n"),
1224 GNUNET_memcpy (new_cookie_hdr + offset,
1227 offset += strlen (tok);
1228 new_cookie_hdr[offset++] = ';';
1230 hdr_val = new_cookie_hdr;
1233 new_location = NULL;
1234 if (0 == strcasecmp (MHD_HTTP_HEADER_TRANSFER_ENCODING,
1237 /* Ignore transfer encoding, set automatically by MHD if required */
1240 if ((0 == strcasecmp (MHD_HTTP_HEADER_LOCATION,
1245 GNUNET_asprintf (&leho_host,
1246 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1250 if (0 == strncmp (leho_host,
1252 strlen (leho_host)))
1254 GNUNET_asprintf (&new_location,
1256 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1260 hdr_val + strlen (leho_host));
1261 hdr_val = new_location;
1263 GNUNET_free (leho_host);
1265 if (0 == strcasecmp (MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1270 GNUNET_asprintf (&leho_host,
1271 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1275 if (0 == strncmp (leho_host,
1277 strlen (leho_host)))
1279 GNUNET_asprintf (&new_location,
1281 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1285 hdr_val = new_location;
1287 GNUNET_free (leho_host);
1290 /* MHD does not allow certain characters in values, remove those */
1291 if (NULL != (tok = strchr (hdr_val, '\n')))
1293 if (NULL != (tok = strchr (hdr_val, '\r')))
1295 if (NULL != (tok = strchr (hdr_val, '\t')))
1297 if (0 != strlen (hdr_val)) /* Rely in MHD to set those */
1299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1300 "Adding header %s: %s to MHD response\n",
1303 header = GNUNET_new (struct HttpResponseHeader);
1304 header->type = GNUNET_strdup (hdr_type);
1305 header->value = GNUNET_strdup (hdr_val);
1306 GNUNET_CONTAINER_DLL_insert (s5r->header_head,
1312 GNUNET_free_non_null (new_cookie_hdr);
1313 GNUNET_free_non_null (new_location);
1319 * Create an MHD response object in @a s5r matching the
1320 * information we got from curl.
1322 * @param s5r the request for which we convert the response
1323 * @return #GNUNET_OK on success, #GNUNET_SYSERR if response was
1324 * already initialized before
1327 create_mhd_response_from_s5r (struct Socks5Request *s5r)
1330 double content_length;
1332 if (NULL != s5r->response)
1334 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1335 "Response already set!\n");
1336 return GNUNET_SYSERR;
1339 GNUNET_break (CURLE_OK ==
1340 curl_easy_getinfo (s5r->curl,
1341 CURLINFO_RESPONSE_CODE,
1343 GNUNET_break (CURLE_OK ==
1344 curl_easy_getinfo (s5r->curl,
1345 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
1347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1348 "Creating MHD response with code %d and size %d for %s%s\n",
1350 (int) content_length,
1353 s5r->response_code = resp_code;
1354 s5r->response = MHD_create_response_from_callback ((-1 == content_length)
1361 for (struct HttpResponseHeader *header = s5r->header_head;
1363 header = header->next)
1365 GNUNET_break (MHD_YES ==
1366 MHD_add_response_header (s5r->response,
1371 /* force connection to be closed after each request, as we
1372 do not support HTTP pipelining (yet, FIXME!) */
1373 /*GNUNET_break (MHD_YES ==
1374 MHD_add_response_header (s5r->response,
1375 MHD_HTTP_HEADER_CONNECTION,
1377 MHD_resume_connection (s5r->con);
1378 s5r->suspended = GNUNET_NO;
1384 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1385 * it available to MHD.
1387 * @param ptr pointer to the data
1388 * @param size number of blocks of data
1389 * @param nmemb blocksize
1390 * @param ctx our `struct Socks5Request *`
1391 * @return number of bytes handled
1394 curl_download_cb (void *ptr,
1399 struct Socks5Request *s5r = ctx;
1400 size_t total = size * nmemb;
1402 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1403 "Receiving %ux%u bytes for `%s%s' from cURL\n",
1404 (unsigned int) size,
1405 (unsigned int) nmemb,
1408 if (NULL == s5r->response)
1409 GNUNET_assert (GNUNET_OK ==
1410 create_mhd_response_from_s5r (s5r));
1412 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1413 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1415 /* we're still not done with the upload, do not yet
1416 start the download, the IO buffer is still full
1417 with upload data. */
1418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1419 "Pausing CURL download `%s%s', waiting for UPLOAD to finish\n",
1422 s5r->curl_paused = GNUNET_YES;
1423 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1425 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1427 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1428 "Pausing CURL `%s%s' download, not enough space %llu %llu %llu\n",
1431 (unsigned long long) sizeof (s5r->io_buf),
1432 (unsigned long long) s5r->io_len,
1433 (unsigned long long) total);
1434 s5r->curl_paused = GNUNET_YES;
1435 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1437 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1440 s5r->io_len += total;
1441 if (GNUNET_YES == s5r->suspended)
1443 MHD_resume_connection (s5r->con);
1444 s5r->suspended = GNUNET_NO;
1446 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1447 "Received %llu bytes of payload via cURL from %s\n",
1448 (unsigned long long) total,
1450 if (s5r->io_len == total)
1451 run_mhd_now (s5r->hd);
1457 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1458 * to make it available to MHD.
1460 * @param buf where to write the data
1461 * @param size number of bytes per member
1462 * @param nmemb number of members available in @a buf
1463 * @param cls our `struct Socks5Request` that generated the data
1464 * @return number of bytes copied to @a buf
1467 curl_upload_cb (void *buf,
1472 struct Socks5Request *s5r = cls;
1473 size_t len = size * nmemb;
1476 if ( (0 == s5r->io_len) &&
1477 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1479 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1480 "Pausing CURL UPLOAD %s%s, need more data\n",
1483 return CURL_READFUNC_PAUSE;
1485 if ( (0 == s5r->io_len) &&
1486 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1488 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1489 if (GNUNET_YES == s5r->curl_paused)
1491 s5r->curl_paused = GNUNET_NO;
1492 curl_easy_pause (s5r->curl,
1495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1496 "Completed CURL UPLOAD %s%s\n",
1499 return 0; /* upload finished, can now download */
1501 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
1502 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1505 return CURL_READFUNC_ABORT;
1507 to_copy = GNUNET_MIN (s5r->io_len,
1512 memmove (s5r->io_buf,
1513 &s5r->io_buf[to_copy],
1514 s5r->io_len - to_copy);
1515 s5r->io_len -= to_copy;
1516 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1517 run_mhd_now (s5r->hd); /* got more space for upload now */
1522 /* ************************** main loop of cURL interaction ****************** */
1526 * Task that is run when we are ready to receive more data
1529 * @param cls closure
1532 curl_task_download (void *cls);
1536 * Ask cURL for the select() sets and schedule cURL operations.
1539 curl_download_prepare ()
1546 struct GNUNET_NETWORK_FDSet *grs;
1547 struct GNUNET_NETWORK_FDSet *gws;
1549 struct GNUNET_TIME_Relative rtime;
1551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1552 "Scheduling CURL interaction\n");
1553 if (NULL != curl_download_task)
1555 GNUNET_SCHEDULER_cancel (curl_download_task);
1556 curl_download_task = NULL;
1562 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi,
1568 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1569 "%s failed at %s:%d: `%s'\n",
1570 "curl_multi_fdset", __FILE__, __LINE__,
1571 curl_multi_strerror (mret));
1575 GNUNET_break (CURLM_OK ==
1576 curl_multi_timeout (curl_multi,
1579 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1581 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1585 grs = GNUNET_NETWORK_fdset_create ();
1586 gws = GNUNET_NETWORK_fdset_create ();
1587 GNUNET_NETWORK_fdset_copy_native (grs,
1590 GNUNET_NETWORK_fdset_copy_native (gws,
1593 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1597 &curl_task_download,
1599 GNUNET_NETWORK_fdset_destroy (gws);
1600 GNUNET_NETWORK_fdset_destroy (grs);
1604 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1605 &curl_task_download,
1612 * Task that is run when we are ready to receive more data from curl.
1614 * @param cls closure, NULL
1617 curl_task_download (void *cls)
1621 struct CURLMsg *msg;
1623 struct Socks5Request *s5r;
1625 curl_download_task = NULL;
1626 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1627 "Running CURL interaction\n");
1631 mret = curl_multi_perform (curl_multi,
1633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1634 "Checking CURL multi status: %d\n",
1636 while (NULL != (msg = curl_multi_info_read (curl_multi,
1639 GNUNET_break (CURLE_OK ==
1640 curl_easy_getinfo (msg->easy_handle,
1651 /* documentation says this is not used */
1655 switch (msg->data.result)
1658 case CURLE_GOT_NOTHING:
1659 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1660 "CURL download %s%s completed.\n",
1663 if (NULL == s5r->response)
1665 GNUNET_assert (GNUNET_OK ==
1666 create_mhd_response_from_s5r (s5r));
1668 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1669 if (GNUNET_YES == s5r->suspended)
1671 MHD_resume_connection (s5r->con);
1672 s5r->suspended = GNUNET_NO;
1674 run_mhd_now (s5r->hd);
1677 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1678 "Download curl %s%s failed: %s\n",
1681 curl_easy_strerror (msg->data.result));
1682 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1683 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1684 if (GNUNET_YES == s5r->suspended)
1686 MHD_resume_connection (s5r->con);
1687 s5r->suspended = GNUNET_NO;
1689 run_mhd_now (s5r->hd);
1692 if (NULL == s5r->response)
1693 s5r->response = curl_failure_response;
1696 /* documentation says this is not used */
1700 /* unexpected status code */
1705 } while (mret == CURLM_CALL_MULTI_PERFORM);
1706 if (CURLM_OK != mret)
1707 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1708 "%s failed at %s:%d: `%s'\n",
1709 "curl_multi_perform", __FILE__, __LINE__,
1710 curl_multi_strerror (mret));
1713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714 "Suspending cURL multi loop, no more events pending\n");
1715 if (NULL != curl_download_task)
1717 GNUNET_SCHEDULER_cancel (curl_download_task);
1718 curl_download_task = NULL;
1720 return; /* nothing more in progress */
1722 curl_download_prepare ();
1726 /* ********************************* MHD response generation ******************* */
1730 * Read HTTP request header field from the request. Copies the fields
1731 * over to the 'headers' that will be given to curl. However, 'Host'
1732 * is substituted with the LEHO if present. We also change the
1733 * 'Connection' header value to "close" as the proxy does not support
1736 * @param cls our `struct Socks5Request`
1737 * @param kind value kind
1738 * @param key field key
1739 * @param value field value
1740 * @return #MHD_YES to continue to iterate
1743 con_val_iter (void *cls,
1744 enum MHD_ValueKind kind,
1748 struct Socks5Request *s5r = cls;
1751 if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST,
1753 (NULL != s5r->leho) )
1755 GNUNET_asprintf (&hdr,
1759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1760 "Adding HEADER `%s' to HTTP request\n",
1762 s5r->headers = curl_slist_append (s5r->headers,
1770 * Main MHD callback for handling requests.
1773 * @param con MHD connection handle
1774 * @param url the url in the request
1775 * @param meth the HTTP method used ("GET", "PUT", etc.)
1776 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1777 * @param upload_data the data being uploaded (excluding HEADERS,
1778 * for a POST that fits into memory and that is encoded
1779 * with a supported encoding, the POST data will NOT be
1780 * given in upload_data and is instead available as
1781 * part of MHD_get_connection_values; very large POST
1782 * data *will* be made available incrementally in
1784 * @param upload_data_size set initially to the size of the
1785 * @a upload_data provided; the method must update this
1786 * value to the number of bytes NOT processed;
1787 * @param con_cls pointer to location where we store the `struct Request`
1788 * @return #MHD_YES if the connection was handled successfully,
1789 * #MHD_NO if the socket must be closed due to a serious
1790 * error while handling the request
1793 create_response (void *cls,
1794 struct MHD_Connection *con,
1798 const char *upload_data,
1799 size_t *upload_data_size,
1802 struct Socks5Request *s5r = *con_cls;
1804 char ipstring[INET6_ADDRSTRLEN];
1805 char ipaddr[INET6_ADDRSTRLEN + 2];
1806 const struct sockaddr *sa;
1807 const struct sockaddr_in *s4;
1808 const struct sockaddr_in6 *s6;
1818 /* Fresh connection. */
1819 if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
1821 /* first time here, initialize curl handle */
1824 sa = (const struct sockaddr *) &s5r->destination_address;
1825 switch (sa->sa_family)
1828 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1829 if (NULL == inet_ntop (AF_INET,
1837 GNUNET_snprintf (ipaddr,
1841 port = ntohs (s4->sin_port);
1844 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1845 if (NULL == inet_ntop (AF_INET6,
1853 GNUNET_snprintf (ipaddr,
1857 port = ntohs (s6->sin6_port);
1868 if (NULL == s5r->curl)
1869 s5r->curl = curl_easy_init ();
1870 if (NULL == s5r->curl)
1871 return MHD_queue_response (con,
1872 MHD_HTTP_INTERNAL_SERVER_ERROR,
1873 curl_failure_response);
1874 curl_easy_setopt (s5r->curl,
1875 CURLOPT_HEADERFUNCTION,
1877 curl_easy_setopt (s5r->curl,
1880 curl_easy_setopt (s5r->curl,
1881 CURLOPT_FOLLOWLOCATION,
1884 curl_easy_setopt (s5r->curl,
1887 curl_easy_setopt (s5r->curl,
1888 CURLOPT_CONNECTTIMEOUT,
1890 curl_easy_setopt (s5r->curl,
1893 curl_easy_setopt (s5r->curl,
1896 curl_easy_setopt (s5r->curl,
1897 CURLOPT_HTTP_CONTENT_DECODING,
1899 curl_easy_setopt (s5r->curl,
1902 curl_easy_setopt (s5r->curl,
1905 curl_easy_setopt (s5r->curl,
1909 * Pre-populate cache to resolve Hostname.
1910 * This is necessary as the DNS name in the CURLOPT_URL is used
1911 * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1913 if (NULL != s5r->leho)
1917 GNUNET_asprintf (&curl_hosts,
1922 s5r->hosts = curl_slist_append (NULL,
1924 curl_easy_setopt (s5r->curl,
1927 GNUNET_free (curl_hosts);
1931 GNUNET_asprintf (&curlurl,
1932 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1934 : "https://%s:%d%s",
1943 GNUNET_asprintf (&curlurl,
1944 (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port)
1946 : "https://%s:%d%s",
1951 curl_easy_setopt (s5r->curl,
1954 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1955 "Launching %s CURL interaction, fetching `%s'\n",
1956 (s5r->is_gns) ? "GNS" : "DNS",
1958 GNUNET_free (curlurl);
1959 if (0 == strcasecmp (meth,
1960 MHD_HTTP_METHOD_PUT))
1962 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1963 curl_easy_setopt (s5r->curl,
1966 curl_easy_setopt (s5r->curl,
1967 CURLOPT_WRITEFUNCTION,
1969 curl_easy_setopt (s5r->curl,
1972 GNUNET_assert (CURLE_OK ==
1973 curl_easy_setopt (s5r->curl,
1974 CURLOPT_READFUNCTION,
1976 curl_easy_setopt (s5r->curl,
1981 long upload_size = 0;
1983 us = MHD_lookup_connection_value (con,
1985 MHD_HTTP_HEADER_CONTENT_LENGTH);
1986 if ( (1 == sscanf (us,
1989 (upload_size >= 0) )
1991 curl_easy_setopt (s5r->curl,
1997 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1999 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
2000 curl_easy_setopt (s5r->curl,
2003 curl_easy_setopt (s5r->curl,
2004 CURLOPT_WRITEFUNCTION,
2006 curl_easy_setopt (s5r->curl,
2009 curl_easy_setopt (s5r->curl,
2010 CURLOPT_READFUNCTION,
2012 curl_easy_setopt (s5r->curl,
2019 us = MHD_lookup_connection_value (con,
2021 MHD_HTTP_HEADER_CONTENT_LENGTH);
2022 if ( (NULL != us) &&
2026 (upload_size >= 0) )
2028 curl_easy_setopt (s5r->curl,
2032 curl_easy_setopt (s5r->curl,
2038 else if (0 == strcasecmp (meth,
2039 MHD_HTTP_METHOD_HEAD))
2041 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2042 curl_easy_setopt (s5r->curl,
2046 else if (0 == strcasecmp (meth,
2047 MHD_HTTP_METHOD_OPTIONS))
2049 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2050 curl_easy_setopt (s5r->curl,
2051 CURLOPT_CUSTOMREQUEST,
2053 curl_easy_setopt (s5r->curl,
2054 CURLOPT_WRITEFUNCTION,
2056 curl_easy_setopt (s5r->curl,
2061 else if (0 == strcasecmp (meth,
2062 MHD_HTTP_METHOD_GET))
2064 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2065 curl_easy_setopt (s5r->curl,
2068 curl_easy_setopt (s5r->curl,
2069 CURLOPT_WRITEFUNCTION,
2071 curl_easy_setopt (s5r->curl,
2075 else if (0 == strcasecmp (meth,
2076 MHD_HTTP_METHOD_DELETE))
2078 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2079 curl_easy_setopt (s5r->curl,
2080 CURLOPT_CUSTOMREQUEST,
2082 curl_easy_setopt (s5r->curl,
2083 CURLOPT_WRITEFUNCTION,
2085 curl_easy_setopt (s5r->curl,
2091 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2092 _("Unsupported HTTP method `%s'\n"),
2094 curl_easy_cleanup (s5r->curl);
2099 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
2101 curl_easy_setopt (s5r->curl,
2102 CURLOPT_HTTP_VERSION,
2103 CURL_HTTP_VERSION_1_0);
2105 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
2107 curl_easy_setopt (s5r->curl,
2108 CURLOPT_HTTP_VERSION,
2109 CURL_HTTP_VERSION_1_1);
2113 curl_easy_setopt (s5r->curl,
2114 CURLOPT_HTTP_VERSION,
2115 CURL_HTTP_VERSION_NONE);
2118 if (GNUNET_YES == s5r->is_tls) //(HTTPS_PORT == s5r->port)
2120 curl_easy_setopt (s5r->curl,
2123 if (NULL != s5r->dane_data)
2124 curl_easy_setopt (s5r->curl,
2125 CURLOPT_SSL_VERIFYPEER,
2128 curl_easy_setopt (s5r->curl,
2129 CURLOPT_SSL_VERIFYPEER,
2131 /* Disable cURL checking the hostname, as we will check ourselves
2132 as only we have the domain name or the LEHO or the DANE record */
2133 curl_easy_setopt (s5r->curl,
2134 CURLOPT_SSL_VERIFYHOST,
2139 curl_easy_setopt (s5r->curl,
2145 curl_multi_add_handle (curl_multi,
2149 curl_easy_cleanup (s5r->curl);
2153 MHD_get_connection_values (con,
2157 curl_easy_setopt (s5r->curl,
2160 curl_download_prepare ();
2164 /* continuing to process request */
2165 if (0 != *upload_data_size)
2167 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2168 "Processing %u bytes UPLOAD\n",
2169 (unsigned int) *upload_data_size);
2171 /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else
2172 * upload callback is not called!
2174 curl_easy_setopt (s5r->curl,
2175 CURLOPT_POSTFIELDSIZE,
2178 left = GNUNET_MIN (*upload_data_size,
2179 sizeof (s5r->io_buf) - s5r->io_len);
2180 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
2183 s5r->io_len += left;
2184 *upload_data_size -= left;
2185 GNUNET_assert (NULL != s5r->curl);
2186 if (GNUNET_YES == s5r->curl_paused)
2188 s5r->curl_paused = GNUNET_NO;
2189 curl_easy_pause (s5r->curl,
2194 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
2196 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2197 "Finished processing UPLOAD\n");
2198 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
2200 if (NULL == s5r->response)
2202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2203 "Waiting for HTTP response for %s%s...\n",
2206 MHD_suspend_connection (con);
2207 s5r->suspended = GNUNET_YES;
2210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2211 "Queueing response for %s%s with MHD\n",
2214 run_mhd_now (s5r->hd);
2215 return MHD_queue_response (con,
2221 /* ******************** MHD HTTP setup and event loop ******************** */
2225 * Function called when MHD decides that we are done with a request.
2228 * @param connection connection handle
2229 * @param con_cls value as set by the last call to
2230 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2231 * @param toe reason for request termination (ignored)
2234 mhd_completed_cb (void *cls,
2235 struct MHD_Connection *connection,
2237 enum MHD_RequestTerminationCode toe)
2239 struct Socks5Request *s5r = *con_cls;
2243 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
2244 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2245 "MHD encountered error handling request: %d\n",
2247 if (NULL != s5r->curl)
2249 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2250 "Removing cURL handle (MHD interaction complete)\n");
2251 curl_multi_remove_handle (curl_multi,
2253 curl_slist_free_all (s5r->headers);
2254 s5r->headers = NULL;
2255 curl_easy_reset (s5r->curl);
2259 curl_download_prepare ();
2261 if ( (NULL != s5r->response) &&
2262 (curl_failure_response != s5r->response) )
2263 MHD_destroy_response (s5r->response);
2264 for (struct HttpResponseHeader *header = s5r->header_head;
2266 header = s5r->header_head)
2268 GNUNET_CONTAINER_DLL_remove (s5r->header_head,
2271 GNUNET_free (header->type);
2272 GNUNET_free (header->value);
2273 GNUNET_free (header);
2275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2276 "Finished request for %s\n",
2278 GNUNET_free (s5r->url);
2279 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2281 s5r->response = NULL;
2287 * Function called when MHD connection is opened or closed.
2290 * @param connection connection handle
2291 * @param con_cls value as set by the last call to
2292 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2293 * @param toe connection notification type
2296 mhd_connection_cb (void *cls,
2297 struct MHD_Connection *connection,
2299 enum MHD_ConnectionNotificationCode cnc)
2301 struct Socks5Request *s5r;
2302 const union MHD_ConnectionInfo *ci;
2307 case MHD_CONNECTION_NOTIFY_STARTED:
2308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
2309 ci = MHD_get_connection_info (connection,
2310 MHD_CONNECTION_INFO_CONNECTION_FD);
2316 sock = ci->connect_fd;
2317 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
2319 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
2321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322 "Context set...\n");
2323 s5r->ssl_checked = GNUNET_NO;
2329 case MHD_CONNECTION_NOTIFY_CLOSED:
2330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2331 "Connection closed... cleaning up\n");
2335 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2336 "Connection stale!\n");
2340 curl_download_prepare ();
2349 * Function called when MHD first processes an incoming connection.
2350 * Gives us the respective URI information.
2352 * We use this to associate the `struct MHD_Connection` with our
2353 * internal `struct Socks5Request` data structure (by checking
2354 * for matching sockets).
2356 * @param cls the HTTP server handle (a `struct MhdHttpList`)
2357 * @param url the URL that is being requested
2358 * @param connection MHD connection object for the request
2359 * @return the `struct Socks5Request` that this @a connection is for
2362 mhd_log_callback (void *cls,
2364 struct MHD_Connection *connection)
2366 struct Socks5Request *s5r;
2367 const union MHD_ConnectionInfo *ci;
2369 ci = MHD_get_connection_info (connection,
2370 MHD_CONNECTION_INFO_SOCKET_CONTEXT);
2371 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
2377 s5r = ci->socket_context;
2378 if (NULL != s5r->url)
2383 s5r->url = GNUNET_strdup (url);
2384 if (NULL != s5r->timeout_task)
2386 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
2387 s5r->timeout_task = NULL;
2389 GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD);
2395 * Kill the given MHD daemon.
2397 * @param hd daemon to stop
2400 kill_httpd (struct MhdHttpList *hd)
2402 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
2405 GNUNET_free_non_null (hd->domain);
2406 MHD_stop_daemon (hd->daemon);
2407 if (NULL != hd->httpd_task)
2409 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2410 hd->httpd_task = NULL;
2412 GNUNET_free_non_null (hd->proxy_cert);
2420 * Task run whenever HTTP server is idle for too long. Kill it.
2422 * @param cls the `struct MhdHttpList *`
2425 kill_httpd_task (void *cls)
2427 struct MhdHttpList *hd = cls;
2429 hd->httpd_task = NULL;
2435 * Task run whenever HTTP server operations are pending.
2437 * @param cls the `struct MhdHttpList *` of the daemon that is being run
2440 do_httpd (void *cls);
2444 * Schedule MHD. This function should be called initially when an
2445 * MHD is first getting its client socket, and will then automatically
2446 * always be called later whenever there is work to be done.
2448 * @param hd the daemon to schedule
2451 schedule_httpd (struct MhdHttpList *hd)
2456 struct GNUNET_NETWORK_FDSet *wrs;
2457 struct GNUNET_NETWORK_FDSet *wws;
2460 MHD_UNSIGNED_LONG_LONG timeout;
2461 struct GNUNET_TIME_Relative tv;
2468 MHD_get_fdset (hd->daemon,
2477 haveto = MHD_get_timeout (hd->daemon,
2479 if (MHD_YES == haveto)
2480 tv.rel_value_us = (uint64_t) timeout * 1000LL;
2482 tv = GNUNET_TIME_UNIT_FOREVER_REL;
2485 wrs = GNUNET_NETWORK_fdset_create ();
2486 wws = GNUNET_NETWORK_fdset_create ();
2487 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
2488 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
2495 if (NULL != hd->httpd_task)
2497 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2498 hd->httpd_task = NULL;
2500 if ( (MHD_YES != haveto) &&
2504 /* daemon is idle, kill after timeout */
2505 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
2512 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2517 GNUNET_NETWORK_fdset_destroy (wrs);
2519 GNUNET_NETWORK_fdset_destroy (wws);
2524 * Task run whenever HTTP server operations are pending.
2526 * @param cls the `struct MhdHttpList` of the daemon that is being run
2529 do_httpd (void *cls)
2531 struct MhdHttpList *hd = cls;
2533 hd->httpd_task = NULL;
2534 MHD_run (hd->daemon);
2535 schedule_httpd (hd);
2540 * Run MHD now, we have extra data ready for the callback.
2542 * @param hd the daemon to run now.
2545 run_mhd_now (struct MhdHttpList *hd)
2547 if (NULL != hd->httpd_task)
2548 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2549 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
2555 * Read file in filename
2557 * @param filename file to read
2558 * @param size pointer where filesize is stored
2559 * @return NULL on error
2562 load_file (const char* filename,
2569 GNUNET_DISK_file_size (filename,
2574 if (fsize > MAX_PEM_SIZE)
2576 *size = (unsigned int) fsize;
2577 buffer = GNUNET_malloc (*size);
2579 GNUNET_DISK_fn_read (filename,
2583 GNUNET_free (buffer);
2591 * Load PEM key from file
2593 * @param key where to store the data
2594 * @param keyfile path to the PEM file
2595 * @return #GNUNET_OK on success
2598 load_key_from_file (gnutls_x509_privkey_t key,
2599 const char* keyfile)
2601 gnutls_datum_t key_data;
2604 key_data.data = load_file (keyfile,
2606 if (NULL == key_data.data)
2607 return GNUNET_SYSERR;
2608 ret = gnutls_x509_privkey_import (key, &key_data,
2609 GNUTLS_X509_FMT_PEM);
2610 if (GNUTLS_E_SUCCESS != ret)
2612 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2613 _("Unable to import private key from file `%s'\n"),
2616 GNUNET_free_non_null (key_data.data);
2617 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2622 * Load cert from file
2624 * @param crt struct to store data in
2625 * @param certfile path to pem file
2626 * @return #GNUNET_OK on success
2629 load_cert_from_file (gnutls_x509_crt_t crt,
2630 const char* certfile)
2632 gnutls_datum_t cert_data;
2635 cert_data.data = load_file (certfile,
2637 if (NULL == cert_data.data)
2638 return GNUNET_SYSERR;
2639 ret = gnutls_x509_crt_import (crt,
2641 GNUTLS_X509_FMT_PEM);
2642 if (GNUTLS_E_SUCCESS != ret)
2644 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2645 _("Unable to import certificate from `%s'\n"),
2648 GNUNET_free_non_null (cert_data.data);
2649 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2654 * Generate new certificate for specific name
2656 * @param name the subject name to generate a cert for
2657 * @return a struct holding the PEM data, NULL on error
2659 static struct ProxyGNSCertificate *
2660 generate_gns_certificate (const char *name)
2662 unsigned int serial;
2663 size_t key_buf_size;
2664 size_t cert_buf_size;
2665 gnutls_x509_crt_t request;
2668 struct ProxyGNSCertificate *pgc;
2670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2671 "Generating x.509 certificate for `%s'\n",
2673 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2674 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2675 pgc = GNUNET_new (struct ProxyGNSCertificate);
2676 gnutls_x509_crt_set_dn_by_oid (request,
2677 GNUTLS_OID_X520_COUNTRY_NAME,
2681 gnutls_x509_crt_set_dn_by_oid (request,
2682 GNUTLS_OID_X520_ORGANIZATION_NAME,
2685 strlen ("GNU Name System"));
2686 gnutls_x509_crt_set_dn_by_oid (request,
2687 GNUTLS_OID_X520_COMMON_NAME,
2691 gnutls_x509_crt_set_subject_alternative_name (request,
2694 GNUNET_break (GNUTLS_E_SUCCESS ==
2695 gnutls_x509_crt_set_version (request,
2697 gnutls_rnd (GNUTLS_RND_NONCE,
2700 gnutls_x509_crt_set_serial (request,
2703 etime = time (NULL);
2704 tm_data = localtime (&etime);
2706 etime = mktime(tm_data);
2707 gnutls_x509_crt_set_activation_time (request,
2710 etime = mktime (tm_data);
2711 gnutls_x509_crt_set_expiration_time (request,
2713 gnutls_x509_crt_sign2 (request,
2718 key_buf_size = sizeof (pgc->key);
2719 cert_buf_size = sizeof (pgc->cert);
2720 gnutls_x509_crt_export (request,
2721 GNUTLS_X509_FMT_PEM,
2724 gnutls_x509_privkey_export (proxy_ca.key,
2725 GNUTLS_X509_FMT_PEM,
2728 gnutls_x509_crt_deinit (request);
2734 * Function called by MHD with errors, suppresses them all.
2736 * @param cls closure
2737 * @param fm format string (`printf()`-style)
2738 * @param ap arguments to @a fm
2741 mhd_error_log_callback (void *cls,
2750 * Lookup (or create) an TLS MHD instance for a particular domain.
2752 * @param domain the domain the TLS daemon has to serve
2753 * @return NULL on error
2755 static struct MhdHttpList *
2756 lookup_ssl_httpd (const char* domain)
2758 struct MhdHttpList *hd;
2759 struct ProxyGNSCertificate *pgc;
2766 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2767 if ( (NULL != hd->domain) &&
2768 (0 == strcmp (hd->domain, domain)) )
2770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2773 pgc = generate_gns_certificate (domain);
2774 hd = GNUNET_new (struct MhdHttpList);
2775 hd->is_ssl = GNUNET_YES;
2776 hd->domain = GNUNET_strdup (domain);
2777 hd->proxy_cert = pgc;
2778 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
2781 &create_response, hd,
2782 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2783 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2784 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
2785 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2786 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2787 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2788 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2790 if (NULL == hd->daemon)
2796 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2804 * Task run when a Socks5Request somehow fails to be associated with
2805 * an MHD connection (i.e. because the client never speaks HTTP after
2806 * the SOCKS5 handshake). Clean up.
2808 * @param cls the `struct Socks5Request *`
2811 timeout_s5r_handshake (void *cls)
2813 struct Socks5Request *s5r = cls;
2815 s5r->timeout_task = NULL;
2821 * We're done with the Socks5 protocol, now we need to pass the
2822 * connection data through to the final destination, either
2823 * direct (if the protocol might not be HTTP), or via MHD
2824 * (if the port looks like it should be HTTP).
2826 * @param s5r socks request that has reached the final stage
2829 setup_data_transfer (struct Socks5Request *s5r)
2831 struct MhdHttpList *hd;
2833 const struct sockaddr *addr;
2837 if (GNUNET_YES == s5r->is_tls)
2839 GNUNET_asprintf (&domain,
2842 hd = lookup_ssl_httpd (domain);
2845 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2846 _("Failed to start HTTPS server for `%s'\n"),
2849 GNUNET_free (domain);
2854 GNUNET_assert (NULL != httpd);
2857 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2858 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2859 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2860 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2862 MHD_add_connection (hd->daemon,
2867 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2868 _("Failed to pass client to MHD\n"));
2870 GNUNET_free_non_null (domain);
2874 schedule_httpd (hd);
2875 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2876 &timeout_s5r_handshake,
2878 GNUNET_free_non_null (domain);
2882 /* ********************* SOCKS handling ************************* */
2886 * Write data from buffer to socks5 client, then continue with state machine.
2888 * @param cls the closure with the `struct Socks5Request`
2891 do_write (void *cls)
2893 struct Socks5Request *s5r = cls;
2897 len = GNUNET_NETWORK_socket_send (s5r->sock,
2902 /* write error: connection closed, shutdown, etc.; just clean up */
2903 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2910 s5r->wbuf_len - len);
2911 s5r->wbuf_len -= len;
2912 if (s5r->wbuf_len > 0)
2914 /* not done writing */
2916 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2922 /* we're done writing, continue with state machine! */
2929 case SOCKS5_REQUEST:
2930 GNUNET_assert (NULL != s5r->rtask);
2932 case SOCKS5_DATA_TRANSFER:
2933 setup_data_transfer (s5r);
2935 case SOCKS5_WRITE_THEN_CLEANUP:
2946 * Return a server response message indicating a failure to the client.
2948 * @param s5r request to return failure code for
2949 * @param sc status code to return
2952 signal_socks_failure (struct Socks5Request *s5r,
2953 enum Socks5StatusCode sc)
2955 struct Socks5ServerResponseMessage *s_resp;
2957 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2958 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2959 s_resp->version = SOCKS_VERSION_5;
2961 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2962 if (NULL != s5r->wtask)
2964 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2971 * Return a server response message indicating success.
2973 * @param s5r request to return success status message for
2976 signal_socks_success (struct Socks5Request *s5r)
2978 struct Socks5ServerResponseMessage *s_resp;
2980 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2981 s_resp->version = SOCKS_VERSION_5;
2982 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2983 s_resp->reserved = 0;
2984 s_resp->addr_type = SOCKS5_AT_IPV4;
2985 /* zero out IPv4 address and port */
2988 sizeof (struct in_addr) + sizeof (uint16_t));
2989 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2990 sizeof (struct in_addr) + sizeof (uint16_t);
2991 if (NULL == s5r->wtask)
2993 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3000 * Process GNS results for target domain.
3002 * @param cls the `struct Socks5Request *`
3003 * @param tld #GNUNET_YES if this was a GNS TLD.
3004 * @param rd_count number of records returned
3005 * @param rd record data
3008 handle_gns_result (void *cls,
3011 const struct GNUNET_GNSRECORD_Data *rd)
3013 struct Socks5Request *s5r = cls;
3014 const struct GNUNET_GNSRECORD_Data *r;
3017 s5r->gns_lookup = NULL;
3020 for (uint32_t i=0;i<rd_count;i++)
3023 switch (r->record_type)
3025 case GNUNET_DNSPARSER_TYPE_A:
3027 struct sockaddr_in *in;
3029 if (sizeof (struct in_addr) != r->data_size)
3031 GNUNET_break_op (0);
3034 if (GNUNET_YES == got_ip)
3037 GNUNET_NETWORK_test_pf (PF_INET))
3039 got_ip = GNUNET_YES;
3040 in = (struct sockaddr_in *) &s5r->destination_address;
3041 in->sin_family = AF_INET;
3042 GNUNET_memcpy (&in->sin_addr,
3045 in->sin_port = htons (s5r->port);
3046 #if HAVE_SOCKADDR_IN_SIN_LEN
3047 in->sin_len = sizeof (*in);
3051 case GNUNET_DNSPARSER_TYPE_AAAA:
3053 struct sockaddr_in6 *in;
3055 if (sizeof (struct in6_addr) != r->data_size)
3057 GNUNET_break_op (0);
3060 if (GNUNET_YES == got_ip)
3062 if (GNUNET_YES == disable_v6)
3065 GNUNET_NETWORK_test_pf (PF_INET6))
3067 /* FIXME: allow user to disable IPv6 per configuration option... */
3068 got_ip = GNUNET_YES;
3069 in = (struct sockaddr_in6 *) &s5r->destination_address;
3070 in->sin6_family = AF_INET6;
3071 GNUNET_memcpy (&in->sin6_addr,
3074 in->sin6_port = htons (s5r->port);
3075 #if HAVE_SOCKADDR_IN_SIN_LEN
3076 in->sin6_len = sizeof (*in);
3080 case GNUNET_GNSRECORD_TYPE_VPN:
3081 GNUNET_break (0); /* should have been translated within GNS */
3083 case GNUNET_GNSRECORD_TYPE_LEHO:
3084 GNUNET_free_non_null (s5r->leho);
3085 s5r->leho = GNUNET_strndup (r->data,
3088 case GNUNET_GNSRECORD_TYPE_BOX:
3090 const struct GNUNET_GNSRECORD_BoxRecord *box;
3092 if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
3094 GNUNET_break_op (0);
3098 if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
3099 (ntohs (box->protocol) != IPPROTO_TCP) ||
3100 (ntohs (box->service) != s5r->port) )
3101 break; /* BOX record does not apply */
3102 if (s5r->num_danes >= MAX_DANES)
3104 GNUNET_break (0); /* MAX_DANES too small */
3107 s5r->is_tls = GNUNET_YES; /* This should be TLS */
3108 s5r->dane_data_len[s5r->num_danes]
3109 = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
3110 s5r->dane_data[s5r->num_danes]
3111 = GNUNET_memdup (&box[1],
3112 s5r->dane_data_len[s5r->num_danes]);
3121 if ( (GNUNET_YES != got_ip) &&
3122 (GNUNET_YES == tld) )
3124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3125 "Name resolution failed to yield useful IP address.\n");
3126 signal_socks_failure (s5r,
3127 SOCKS5_STATUS_GENERAL_FAILURE);
3130 s5r->state = SOCKS5_DATA_TRANSFER;
3131 signal_socks_success (s5r);
3136 * Remove the first @a len bytes from the beginning of the read buffer.
3138 * @param s5r the handle clear the read buffer for
3139 * @param len number of bytes in read buffer to advance
3142 clear_from_s5r_rbuf (struct Socks5Request *s5r,
3145 GNUNET_assert (len <= s5r->rbuf_len);
3148 s5r->rbuf_len - len);
3149 s5r->rbuf_len -= len;
3154 * Read data from incoming Socks5 connection
3156 * @param cls the closure with the `struct Socks5Request`
3159 do_s5r_read (void *cls)
3161 struct Socks5Request *s5r = cls;
3162 const struct Socks5ClientHelloMessage *c_hello;
3163 struct Socks5ServerHelloMessage *s_hello;
3164 const struct Socks5ClientRequestMessage *c_req;
3167 const struct GNUNET_SCHEDULER_TaskContext *tc;
3170 tc = GNUNET_SCHEDULER_get_task_context ();
3171 if ( (NULL != tc->read_ready) &&
3172 (GNUNET_NETWORK_fdset_isset (tc->read_ready,
3175 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
3176 &s5r->rbuf[s5r->rbuf_len],
3177 sizeof (s5r->rbuf) - s5r->rbuf_len);
3180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3181 "socks5 client disconnected.\n");
3185 s5r->rbuf_len += rlen;
3187 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3191 "Processing %zu bytes of socks data in state %d\n",
3197 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
3198 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
3199 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
3200 return; /* need more data */
3201 if (SOCKS_VERSION_5 != c_hello->version)
3203 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3204 _("Unsupported socks version %d\n"),
3205 (int) c_hello->version);
3209 clear_from_s5r_rbuf (s5r,
3210 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
3211 GNUNET_assert (0 == s5r->wbuf_len);
3212 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
3213 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
3214 s_hello->version = SOCKS_VERSION_5;
3215 s_hello->auth_method = SOCKS_AUTH_NONE;
3216 GNUNET_assert (NULL == s5r->wtask);
3217 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3220 s5r->state = SOCKS5_REQUEST;
3222 case SOCKS5_REQUEST:
3223 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
3224 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
3226 switch (c_req->command)
3228 case SOCKS5_CMD_TCP_STREAM:
3232 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3233 _("Unsupported socks command %d\n"),
3234 (int) c_req->command);
3235 signal_socks_failure (s5r,
3236 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
3239 switch (c_req->addr_type)
3241 case SOCKS5_AT_IPV4:
3243 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
3244 const uint16_t *port = (const uint16_t *) &v4[1];
3245 struct sockaddr_in *in;
3247 s5r->port = ntohs (*port);
3248 alen = sizeof (struct in_addr);
3249 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3250 alen + sizeof (uint16_t))
3251 return; /* need more data */
3252 in = (struct sockaddr_in *) &s5r->destination_address;
3253 in->sin_family = AF_INET;
3255 in->sin_port = *port;
3256 #if HAVE_SOCKADDR_IN_SIN_LEN
3257 in->sin_len = sizeof (*in);
3259 s5r->state = SOCKS5_DATA_TRANSFER;
3262 case SOCKS5_AT_IPV6:
3264 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
3265 const uint16_t *port = (const uint16_t *) &v6[1];
3266 struct sockaddr_in6 *in;
3268 s5r->port = ntohs (*port);
3269 alen = sizeof (struct in6_addr);
3270 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3271 alen + sizeof (uint16_t))
3272 return; /* need more data */
3273 in = (struct sockaddr_in6 *) &s5r->destination_address;
3274 in->sin6_family = AF_INET6;
3275 in->sin6_addr = *v6;
3276 in->sin6_port = *port;
3277 #if HAVE_SOCKADDR_IN_SIN_LEN
3278 in->sin6_len = sizeof (*in);
3280 s5r->state = SOCKS5_DATA_TRANSFER;
3283 case SOCKS5_AT_DOMAINNAME:
3285 const uint8_t *dom_len;
3286 const char *dom_name;
3287 const uint16_t *port;
3289 dom_len = (const uint8_t *) &c_req[1];
3290 alen = *dom_len + 1;
3291 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3292 alen + sizeof (uint16_t))
3293 return; /* need more data */
3294 dom_name = (const char *) &dom_len[1];
3295 port = (const uint16_t*) &dom_name[*dom_len];
3296 s5r->domain = GNUNET_strndup (dom_name,
3298 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3299 "Requested connection is to %s:%d\n",
3300 //(HTTPS_PORT == s5r->port) ? "s" : "",
3303 s5r->state = SOCKS5_RESOLVING;
3304 s5r->port = ntohs (*port);
3305 s5r->is_tls = (HTTPS_PORT == s5r->port) ? GNUNET_YES : GNUNET_NO;
3306 s5r->gns_lookup = GNUNET_GNS_lookup_with_tld (gns_handle,
3308 GNUNET_DNSPARSER_TYPE_A,
3309 GNUNET_NO /* only cached */,
3315 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3316 _("Unsupported socks address type %d\n"),
3317 (int) c_req->addr_type);
3318 signal_socks_failure (s5r,
3319 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
3322 clear_from_s5r_rbuf (s5r,
3323 sizeof (struct Socks5ClientRequestMessage) +
3324 alen + sizeof (uint16_t));
3325 if (0 != s5r->rbuf_len)
3327 /* read more bytes than healthy, why did the client send more!? */
3328 GNUNET_break_op (0);
3329 signal_socks_failure (s5r,
3330 SOCKS5_STATUS_GENERAL_FAILURE);
3333 if (SOCKS5_DATA_TRANSFER == s5r->state)
3335 /* if we are not waiting for GNS resolution, signal success */
3336 signal_socks_success (s5r);
3338 /* We are done reading right now */
3339 GNUNET_SCHEDULER_cancel (s5r->rtask);
3342 case SOCKS5_RESOLVING:
3345 case SOCKS5_DATA_TRANSFER:
3356 * Accept new incoming connections
3358 * @param cls the closure with the lsock4 or lsock6
3359 * @param tc the scheduler context
3362 do_accept (void *cls)
3364 struct GNUNET_NETWORK_Handle *lsock = cls;
3365 struct GNUNET_NETWORK_Handle *s;
3366 struct Socks5Request *s5r;
3368 GNUNET_assert (NULL != lsock);
3369 if (lsock == lsock4)
3370 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3374 else if (lsock == lsock6)
3375 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3381 s = GNUNET_NETWORK_socket_accept (lsock,
3386 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3390 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3391 "Got an inbound connection, waiting for data\n");
3392 s5r = GNUNET_new (struct Socks5Request);
3393 GNUNET_CONTAINER_DLL_insert (s5r_head,
3397 s5r->state = SOCKS5_INIT;
3398 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3405 /* ******************* General / main code ********************* */
3409 * Task run on shutdown
3411 * @param cls closure
3414 do_shutdown (void *cls)
3416 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3417 "Shutting down...\n");
3418 /* MHD requires resuming before destroying the daemons */
3419 for (struct Socks5Request *s5r = s5r_head;
3425 s5r->suspended = GNUNET_NO;
3426 MHD_resume_connection (s5r->con);
3429 while (NULL != mhd_httpd_head)
3430 kill_httpd (mhd_httpd_head);
3431 while (NULL != s5r_head)
3432 cleanup_s5r (s5r_head);
3435 GNUNET_NETWORK_socket_close (lsock4);
3440 GNUNET_NETWORK_socket_close (lsock6);
3443 if (NULL != curl_multi)
3445 curl_multi_cleanup (curl_multi);
3448 if (NULL != gns_handle)
3450 GNUNET_GNS_disconnect (gns_handle);
3453 if (NULL != curl_download_task)
3455 GNUNET_SCHEDULER_cancel (curl_download_task);
3456 curl_download_task = NULL;
3460 GNUNET_SCHEDULER_cancel (ltask4);
3465 GNUNET_SCHEDULER_cancel (ltask6);
3468 gnutls_x509_crt_deinit (proxy_ca.cert);
3469 gnutls_x509_privkey_deinit (proxy_ca.key);
3470 gnutls_global_deinit ();
3475 * Create an IPv4 listen socket bound to our port.
3477 * @return NULL on error
3479 static struct GNUNET_NETWORK_Handle *
3482 struct GNUNET_NETWORK_Handle *ls;
3483 struct sockaddr_in sa4;
3486 memset (&sa4, 0, sizeof (sa4));
3487 sa4.sin_family = AF_INET;
3488 sa4.sin_port = htons (port);
3489 #if HAVE_SOCKADDR_IN_SIN_LEN
3490 sa4.sin_len = sizeof (sa4);
3492 ls = GNUNET_NETWORK_socket_create (AF_INET,
3498 GNUNET_NETWORK_socket_bind (ls,
3499 (const struct sockaddr *) &sa4,
3503 GNUNET_NETWORK_socket_close (ls);
3512 * Create an IPv6 listen socket bound to our port.
3514 * @return NULL on error
3516 static struct GNUNET_NETWORK_Handle *
3519 struct GNUNET_NETWORK_Handle *ls;
3520 struct sockaddr_in6 sa6;
3523 memset (&sa6, 0, sizeof (sa6));
3524 sa6.sin6_family = AF_INET6;
3525 sa6.sin6_port = htons (port);
3526 #if HAVE_SOCKADDR_IN_SIN_LEN
3527 sa6.sin6_len = sizeof (sa6);
3529 ls = GNUNET_NETWORK_socket_create (AF_INET6,
3535 GNUNET_NETWORK_socket_bind (ls,
3536 (const struct sockaddr *) &sa6,
3540 GNUNET_NETWORK_socket_close (ls);
3549 * Main function that will be run
3551 * @param cls closure
3552 * @param args remaining command-line arguments
3553 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3554 * @param c configuration
3559 const char *cfgfile,
3560 const struct GNUNET_CONFIGURATION_Handle *c)
3562 char* cafile_cfg = NULL;
3564 struct MhdHttpList *hd;
3568 if (NULL == (curl_multi = curl_multi_init ()))
3570 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3571 "Failed to create cURL multi handle!\n");
3574 cafile = cafile_opt;
3578 GNUNET_CONFIGURATION_get_value_filename (cfg,
3583 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3588 cafile = cafile_cfg;
3590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3591 "Using `%s' as CA\n",
3594 gnutls_global_init ();
3595 gnutls_x509_crt_init (&proxy_ca.cert);
3596 gnutls_x509_privkey_init (&proxy_ca.key);
3599 load_cert_from_file (proxy_ca.cert,
3602 load_key_from_file (proxy_ca.key,
3605 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3606 _("Failed to load X.509 key and certificate from `%s'\n"),
3608 gnutls_x509_crt_deinit (proxy_ca.cert);
3609 gnutls_x509_privkey_deinit (proxy_ca.key);
3610 gnutls_global_deinit ();
3611 GNUNET_free_non_null (cafile_cfg);
3614 GNUNET_free_non_null (cafile_cfg);
3615 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3617 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3618 "Unable to connect to GNS!\n");
3619 gnutls_x509_crt_deinit (proxy_ca.cert);
3620 gnutls_x509_privkey_deinit (proxy_ca.key);
3621 gnutls_global_deinit ();
3624 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
3627 /* Open listen socket for socks proxy */
3628 lsock6 = bind_v6 ();
3631 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3637 GNUNET_NETWORK_socket_listen (lsock6,
3640 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3642 GNUNET_NETWORK_socket_close (lsock6);
3647 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3653 lsock4 = bind_v4 ();
3656 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3662 GNUNET_NETWORK_socket_listen (lsock4,
3665 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3667 GNUNET_NETWORK_socket_close (lsock4);
3672 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3678 if ( (NULL == lsock4) &&
3681 GNUNET_SCHEDULER_shutdown ();
3684 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3686 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3687 "cURL global init failed!\n");
3688 GNUNET_SCHEDULER_shutdown ();
3691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3692 "Proxy listens on port %u\n",
3693 (unsigned int) port);
3695 /* start MHD daemon for HTTP */
3696 hd = GNUNET_new (struct MhdHttpList);
3697 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
3700 &create_response, hd,
3701 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3702 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3703 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
3704 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3706 if (NULL == hd->daemon)
3709 GNUNET_SCHEDULER_shutdown ();
3713 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
3720 * The main function for gnunet-gns-proxy.
3722 * @param argc number of arguments from the command line
3723 * @param argv command line arguments
3724 * @return 0 ok, 1 on error
3730 struct GNUNET_GETOPT_CommandLineOption options[] = {
3731 GNUNET_GETOPT_option_uint16 ('p',
3734 gettext_noop ("listen on specified port (default: 7777)"),
3736 GNUNET_GETOPT_option_string ('a',
3739 gettext_noop ("pem file to use as CA"),
3741 GNUNET_GETOPT_option_flag ('6',
3743 gettext_noop ("disable use of IPv6"),
3746 GNUNET_GETOPT_OPTION_END
3748 static const char* page =
3749 "<html><head><title>gnunet-gns-proxy</title>"
3750 "</head><body>cURL fail</body></html>";
3754 GNUNET_STRINGS_get_utf8_args (argc, argv,
3757 GNUNET_log_setup ("gnunet-gns-proxy",
3760 curl_failure_response
3761 = MHD_create_response_from_buffer (strlen (page),
3763 MHD_RESPMEM_PERSISTENT);
3767 GNUNET_PROGRAM_run (argc, argv,
3769 _("GNUnet GNS proxy"),
3771 &run, NULL)) ? 0 : 1;
3772 MHD_destroy_response (curl_failure_response);
3773 GNUNET_free_non_null ((char *) argv);
3777 /* end of gnunet-gns-proxy.c */