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/>.
19 * @author Martin Schanzenbach
20 * @author Christian Grothoff
21 * @file src/gns/gnunet-gns-proxy.c
22 * @brief HTTP(S) proxy that rewrites URIs and fakes certificats to make GNS work
23 * with legacy browsers
26 * - double-check queueing logic
29 #include <microhttpd.h>
31 #include <curl/curl.h>
32 #elif HAVE_GNURL_CURL_H
33 #include <gnurl/curl.h>
35 #include <gnutls/gnutls.h>
36 #include <gnutls/x509.h>
37 #include <gnutls/abstract.h>
38 #include <gnutls/crypto.h>
40 #include <gnutls/dane.h>
43 #include "gnunet_util_lib.h"
44 #include "gnunet_gns_service.h"
45 #include "gnunet_identity_service.h"
51 * Default Socks5 listen port.
53 #define GNUNET_GNS_PROXY_PORT 7777
56 * Maximum supported length for a URI.
57 * Should die. @deprecated
59 #define MAX_HTTP_URI_LENGTH 2048
62 * Maximum number of DANE records we support
63 * per domain name (and port and protocol).
68 * Size of the buffer for the data upload / download. Must be
69 * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
71 #define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE
74 * Size of the read/write buffers for Socks. Uses
75 * 256 bytes for the hostname (at most), plus a few
76 * bytes overhead for the messages.
78 #define SOCKS_BUFFERSIZE (256 + 32)
81 * Port for plaintext HTTP.
88 #define HTTPS_PORT 443
91 * Largest allowed size for a PEM certificate.
93 #define MAX_PEM_SIZE (10 * 1024)
96 * After how long do we clean up unused MHD TLS instances?
98 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
101 * After how long do we clean up Socks5 handles that failed to show any activity
102 * with their respective MHD instance?
104 #define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
110 * @param level log level
111 * @param fun name of curl_easy-function that gave the error
112 * @param rc return code from curl
114 #define LOG_CURL_EASY(level,fun,rc) \
116 _("%s failed at %s:%d: `%s'\n"), \
120 curl_easy_strerror (rc))
123 /* *************** Socks protocol definitions (move to TUN?) ****************** */
126 * Which SOCKS version do we speak?
128 #define SOCKS_VERSION_5 0x05
131 * Flag to set for 'no authentication'.
133 #define SOCKS_AUTH_NONE 0
137 * Commands in Socks5.
142 * Establish TCP/IP stream.
144 SOCKS5_CMD_TCP_STREAM = 1,
147 * Establish TCP port binding.
149 SOCKS5_CMD_TCP_PORT = 2,
152 * Establish UDP port binding.
154 SOCKS5_CMD_UDP_PORT = 3
159 * Address types in Socks5.
161 enum Socks5AddressType
171 SOCKS5_AT_DOMAINNAME = 3,
182 * Status codes in Socks5 response.
184 enum Socks5StatusCode
186 SOCKS5_STATUS_REQUEST_GRANTED = 0,
187 SOCKS5_STATUS_GENERAL_FAILURE = 1,
188 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
189 SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
190 SOCKS5_STATUS_HOST_UNREACHABLE = 4,
191 SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
192 SOCKS5_STATUS_TTL_EXPIRED = 6,
193 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
194 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
199 * Client hello in Socks5 protocol.
201 struct Socks5ClientHelloMessage
204 * Should be #SOCKS_VERSION_5.
209 * How many authentication methods does the client support.
211 uint8_t num_auth_methods;
213 /* followed by supported authentication methods, 1 byte per method */
219 * Server hello in Socks5 protocol.
221 struct Socks5ServerHelloMessage
224 * Should be #SOCKS_VERSION_5.
229 * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
230 * which skips the authentication step.
237 * Client socks request in Socks5 protocol.
239 struct Socks5ClientRequestMessage
242 * Should be #SOCKS_VERSION_5.
247 * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
252 * Reserved, always zero.
257 * Address type, an `enum Socks5AddressType`.
262 * Followed by either an ip4/ipv6 address or a domain name with a
263 * length field (uint8_t) in front (depending on @e addr_type).
264 * followed by port number in network byte order (uint16_t).
270 * Server response to client requests in Socks5 protocol.
272 struct Socks5ServerResponseMessage
275 * Should be #SOCKS_VERSION_5.
280 * Status code, an `enum Socks5StatusCode`
290 * Address type, an `enum Socks5AddressType`.
295 * Followed by either an ip4/ipv6 address or a domain name with a
296 * length field (uint8_t) in front (depending on @e addr_type).
297 * followed by port number in network byte order (uint16_t).
304 /* *********************** Datastructures for HTTP handling ****************** */
307 * A structure for CA cert/key
314 gnutls_x509_crt_t cert;
319 gnutls_x509_privkey_t key;
324 * Structure for GNS certificates
326 struct ProxyGNSCertificate
329 * The certificate as PEM
331 char cert[MAX_PEM_SIZE];
334 * The private key as PEM
336 char key[MAX_PEM_SIZE];
342 * A structure for all running Httpds
349 struct MhdHttpList *prev;
354 struct MhdHttpList *next;
357 * the domain name to server (only important for TLS)
364 struct MHD_Daemon *daemon;
367 * Optional proxy certificate used
369 struct ProxyGNSCertificate *proxy_cert;
374 struct GNUNET_SCHEDULER_Task *httpd_task;
377 * is this an ssl daemon?
384 /* ***************** Datastructures for Socks handling **************** */
393 * We're waiting to get the client hello.
398 * We're waiting to get the initial request.
403 * We are currently resolving the destination.
408 * We're in transfer mode.
410 SOCKS5_DATA_TRANSFER,
413 * Finish writing the write buffer, then clean up.
415 SOCKS5_WRITE_THEN_CLEANUP,
418 * Socket has been passed to MHD, do not close it anymore.
420 SOCKS5_SOCKET_WITH_MHD,
423 * We've started receiving upload data from MHD.
425 SOCKS5_SOCKET_UPLOAD_STARTED,
428 * We've finished receiving upload data from MHD.
430 SOCKS5_SOCKET_UPLOAD_DONE,
433 * We've finished uploading data via CURL and can now download.
435 SOCKS5_SOCKET_DOWNLOAD_STARTED,
438 * We've finished receiving download data from cURL.
440 SOCKS5_SOCKET_DOWNLOAD_DONE
447 struct HttpResponseHeader
452 struct HttpResponseHeader *next;
457 struct HttpResponseHeader *prev;
471 * A structure for socks requests
479 struct Socks5Request *next;
484 struct Socks5Request *prev;
489 struct GNUNET_NETWORK_Handle *sock;
492 * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
494 struct GNUNET_GNS_LookupWithTldRequest *gns_lookup;
497 * Client socket read task
499 struct GNUNET_SCHEDULER_Task *rtask;
502 * Client socket write task
504 struct GNUNET_SCHEDULER_Task *wtask;
509 struct GNUNET_SCHEDULER_Task *timeout_task;
514 char rbuf[SOCKS_BUFFERSIZE];
519 char wbuf[SOCKS_BUFFERSIZE];
522 * Buffer we use for moving data between MHD and curl (in both directions).
524 char io_buf[IO_BUFFERSIZE];
527 * MHD HTTP instance handling this request, NULL for none.
529 struct MhdHttpList *hd;
532 * MHD connection for this request.
534 struct MHD_Connection *con;
537 * MHD response object for this request.
539 struct MHD_Response *response;
542 * the domain name to server (only important for TLS)
547 * DNS Legacy Host Name as given by GNS, NULL if not given.
552 * Payload of the DANE records encountered.
554 char *dane_data[MAX_DANES + 1];
567 * HTTP request headers for the curl request.
569 struct curl_slist *headers;
572 * DNS->IP mappings resolved through GNS
574 struct curl_slist *hosts;
577 * HTTP response code to give to MHD for the response.
579 unsigned int response_code;
582 * Number of bytes in @e dane_data.
584 int dane_data_len[MAX_DANES + 1];
587 * Number of entries used in @e dane_data_len
590 unsigned int num_danes;
593 * Number of bytes already in read buffer
598 * Number of bytes already in write buffer
603 * Number of bytes already in the IO buffer.
608 * Once known, what's the target address for the connection?
610 struct sockaddr_storage destination_address;
615 enum SocksPhase state;
618 * Desired destination port.
623 * Headers from response
625 struct HttpResponseHeader *header_head;
628 * Headers from response
630 struct HttpResponseHeader *header_tail;
633 * X.509 Certificate status
638 * Was the hostname resolved via GNS?
643 * Did we suspend MHD processing?
648 * Did we pause CURL processing?
655 /* *********************** Globals **************************** */
659 * The port the proxy is running on (default 7777)
661 static uint16_t port = GNUNET_GNS_PROXY_PORT;
664 * The CA file (pem) to use for the proxy CA
666 static char *cafile_opt;
669 * The listen socket of the proxy for IPv4
671 static struct GNUNET_NETWORK_Handle *lsock4;
674 * The listen socket of the proxy for IPv6
676 static struct GNUNET_NETWORK_Handle *lsock6;
679 * The listen task ID for IPv4
681 static struct GNUNET_SCHEDULER_Task * ltask4;
684 * The listen task ID for IPv6
686 static struct GNUNET_SCHEDULER_Task * ltask6;
689 * The cURL download task (curl multi API).
691 static struct GNUNET_SCHEDULER_Task * curl_download_task;
694 * The cURL multi handle
696 static CURLM *curl_multi;
699 * Handle to the GNS service
701 static struct GNUNET_GNS_Handle *gns_handle;
706 static int disable_v6;
709 * DLL for http/https daemons
711 static struct MhdHttpList *mhd_httpd_head;
714 * DLL for http/https daemons
716 static struct MhdHttpList *mhd_httpd_tail;
719 * Daemon for HTTP (we have one per X.509 certificate, and then one for
720 * all HTTP connections; this is the one for HTTP, not HTTPS).
722 static struct MhdHttpList *httpd;
725 * DLL of active socks requests.
727 static struct Socks5Request *s5r_head;
730 * DLL of active socks requests.
732 static struct Socks5Request *s5r_tail;
735 * The CA for X.509 certificate generation
737 static struct ProxyCA proxy_ca;
740 * Response we return on cURL failures.
742 static struct MHD_Response *curl_failure_response;
747 static const struct GNUNET_CONFIGURATION_Handle *cfg;
750 /* ************************* Global helpers ********************* */
754 * Run MHD now, we have extra data ready for the callback.
756 * @param hd the daemon to run now.
759 run_mhd_now (struct MhdHttpList *hd);
763 * Clean up s5r handles.
765 * @param s5r the handle to destroy
768 cleanup_s5r (struct Socks5Request *s5r)
770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
771 "Cleaning up socks request\n");
772 if (NULL != s5r->curl)
774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
775 "Cleaning up cURL handle\n");
776 curl_multi_remove_handle (curl_multi,
778 curl_easy_cleanup (s5r->curl);
783 s5r->suspended = GNUNET_NO;
784 MHD_resume_connection (s5r->con);
786 curl_slist_free_all (s5r->headers);
787 if (NULL != s5r->hosts)
789 curl_slist_free_all (s5r->hosts);
791 if ( (NULL != s5r->response) &&
792 (curl_failure_response != s5r->response) )
794 MHD_destroy_response (s5r->response);
795 s5r->response = NULL;
797 if (NULL != s5r->rtask)
799 GNUNET_SCHEDULER_cancel (s5r->rtask);
802 if (NULL != s5r->timeout_task)
804 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
805 s5r->timeout_task = NULL;
807 if (NULL != s5r->wtask)
809 GNUNET_SCHEDULER_cancel (s5r->wtask);
812 if (NULL != s5r->gns_lookup)
814 GNUNET_GNS_lookup_with_tld_cancel (s5r->gns_lookup);
815 s5r->gns_lookup = NULL;
817 if (NULL != s5r->sock)
819 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
820 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
822 GNUNET_NETWORK_socket_close (s5r->sock);
825 GNUNET_CONTAINER_DLL_remove (s5r_head,
828 GNUNET_free_non_null (s5r->domain);
829 GNUNET_free_non_null (s5r->leho);
830 GNUNET_free_non_null (s5r->url);
831 for (unsigned int i=0;i<s5r->num_danes;i++)
832 GNUNET_free (s5r->dane_data[i]);
837 /* ************************* HTTP handling with cURL *********************** */
840 curl_download_prepare ();
844 * Callback for MHD response generation. This function is called from
845 * MHD whenever MHD expects to get data back. Copies data from the
846 * io_buf, if available.
848 * @param cls closure with our `struct Socks5Request`
849 * @param pos in buffer
850 * @param buf where to copy data
851 * @param max available space in @a buf
852 * @return number of bytes written to @a buf
855 mhd_content_cb (void *cls,
860 struct Socks5Request *s5r = cls;
861 size_t bytes_to_copy;
863 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
864 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
866 /* we're still not done with the upload, do not yet
867 start the download, the IO buffer is still full
869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
870 "Pausing MHD download %s%s, not yet ready for download\n",
873 return 0; /* not yet ready for data download */
875 bytes_to_copy = GNUNET_MIN (max,
877 if ( (0 == bytes_to_copy) &&
878 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
880 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881 "Pausing MHD download %s%s, no data available\n",
884 if (NULL != s5r->curl)
886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
887 "Continuing CURL interaction for %s%s\n",
890 if (GNUNET_YES == s5r->curl_paused)
892 s5r->curl_paused = GNUNET_NO;
893 curl_easy_pause (s5r->curl,
896 curl_download_prepare ();
898 if (GNUNET_NO == s5r->suspended)
900 MHD_suspend_connection (s5r->con);
901 s5r->suspended = GNUNET_YES;
903 return 0; /* more data later */
905 if ( (0 == bytes_to_copy) &&
906 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
909 "Completed MHD download %s%s\n",
912 return MHD_CONTENT_READER_END_OF_STREAM;
914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
915 "Writing %llu/%llu bytes to %s%s\n",
916 (unsigned long long) bytes_to_copy,
917 (unsigned long long) s5r->io_len,
923 memmove (s5r->io_buf,
924 &s5r->io_buf[bytes_to_copy],
925 s5r->io_len - bytes_to_copy);
926 s5r->io_len -= bytes_to_copy;
927 if ( (NULL != s5r->curl) &&
928 (GNUNET_YES == s5r->curl_paused) )
930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
931 "Continuing CURL interaction for %s%s\n",
934 s5r->curl_paused = GNUNET_NO;
935 curl_easy_pause (s5r->curl,
938 return bytes_to_copy;
943 * Check that the website has presented us with a valid X.509 certificate.
944 * The certificate must either match the domain name or the LEHO name
945 * (or, if available, the TLSA record).
947 * @param s5r request to check for.
948 * @return #GNUNET_OK if the certificate is valid
951 check_ssl_certificate (struct Socks5Request *s5r)
953 unsigned int cert_list_size;
954 const gnutls_datum_t *chainp;
955 const struct curl_tlssessioninfo *tlsinfo;
956 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
958 gnutls_x509_crt_t x509_cert;
962 s5r->ssl_checked = GNUNET_YES;
963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964 "Checking X.509 certificate\n");
966 curl_easy_getinfo (s5r->curl,
967 CURLINFO_TLS_SESSION,
968 (struct curl_slist **) &tlsinfo))
969 return GNUNET_SYSERR;
970 if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
972 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
973 _("Unsupported CURL TLS backend %d\n"),
975 return GNUNET_SYSERR;
977 chainp = gnutls_certificate_get_peers (tlsinfo->internals,
980 (0 == cert_list_size) )
981 return GNUNET_SYSERR;
983 size = sizeof (certdn);
984 /* initialize an X.509 certificate structure. */
985 gnutls_x509_crt_init (&x509_cert);
986 gnutls_x509_crt_import (x509_cert,
988 GNUTLS_X509_FMT_DER);
990 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
991 GNUTLS_OID_X520_COMMON_NAME,
992 0, /* the first and only one */
993 0 /* no DER encoding */,
997 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
998 _("Failed to fetch CN from cert: %s\n"),
999 gnutls_strerror(rc));
1000 gnutls_x509_crt_deinit (x509_cert);
1001 return GNUNET_SYSERR;
1003 /* check for TLSA/DANE records */
1004 #if HAVE_GNUTLS_DANE
1005 if (0 != s5r->num_danes)
1007 dane_state_t dane_state;
1008 dane_query_t dane_query;
1009 unsigned int verify;
1011 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
1012 if (0 != (rc = dane_state_init (&dane_state,
1013 #ifdef DANE_F_IGNORE_DNSSEC
1014 DANE_F_IGNORE_DNSSEC |
1016 DANE_F_IGNORE_LOCAL_RESOLVER)))
1018 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1019 _("Failed to initialize DANE: %s\n"),
1021 gnutls_x509_crt_deinit (x509_cert);
1022 return GNUNET_SYSERR;
1024 s5r->dane_data[s5r->num_danes] = NULL;
1025 s5r->dane_data_len[s5r->num_danes] = 0;
1026 if (0 != (rc = dane_raw_tlsa (dane_state,
1033 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1034 _("Failed to parse DANE record: %s\n"),
1036 dane_state_deinit (dane_state);
1037 gnutls_x509_crt_deinit (x509_cert);
1038 return GNUNET_SYSERR;
1040 if (0 != (rc = dane_verify_crt_raw (dane_state,
1043 gnutls_certificate_type_get (tlsinfo->internals),
1048 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1049 _("Failed to verify TLS connection using DANE: %s\n"),
1051 dane_query_deinit (dane_query);
1052 dane_state_deinit (dane_state);
1053 gnutls_x509_crt_deinit (x509_cert);
1054 return GNUNET_SYSERR;
1058 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1059 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
1061 dane_query_deinit (dane_query);
1062 dane_state_deinit (dane_state);
1063 gnutls_x509_crt_deinit (x509_cert);
1064 return GNUNET_SYSERR;
1066 dane_query_deinit (dane_query);
1067 dane_state_deinit (dane_state);
1073 /* try LEHO or ordinary domain name X509 verification */
1075 if (NULL != s5r->leho)
1079 if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
1082 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1083 _("TLS certificate subject name (%s) does not match `%s': %d\n"),
1087 gnutls_x509_crt_deinit (x509_cert);
1088 return GNUNET_SYSERR;
1093 /* we did not even have the domain name!? */
1095 return GNUNET_SYSERR;
1098 gnutls_x509_crt_deinit (x509_cert);
1104 * We're getting an HTTP response header from cURL. Convert it to the
1105 * MHD response headers. Mostly copies the headers, but makes special
1106 * adjustments to "Set-Cookie" and "Location" headers as those may need
1107 * to be changed from the LEHO to the domain the browser expects.
1109 * @param buffer curl buffer with a single line of header data; not 0-terminated!
1110 * @param size curl blocksize
1111 * @param nmemb curl blocknumber
1112 * @param cls our `struct Socks5Request *`
1113 * @return size of processed bytes
1116 curl_check_hdr (void *buffer,
1121 struct Socks5Request *s5r = cls;
1122 struct HttpResponseHeader *header;
1123 size_t bytes = size * nmemb;
1125 const char *hdr_type;
1126 const char *cookie_domain;
1128 char *new_cookie_hdr;
1131 size_t delta_cdomain;
1135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1136 "Receiving HTTP response header from CURL\n");
1137 /* first, check TLS certificate */
1138 if ( (GNUNET_YES != s5r->ssl_checked) &&
1139 (HTTPS_PORT == s5r->port))
1141 if (GNUNET_OK != check_ssl_certificate (s5r))
1144 ndup = GNUNET_strndup (buffer,
1146 hdr_type = strtok (ndup,
1148 if (NULL == hdr_type)
1153 hdr_val = strtok (NULL,
1155 if (NULL == hdr_val)
1160 if (' ' == *hdr_val)
1163 /* custom logic for certain header types */
1164 new_cookie_hdr = NULL;
1165 if ( (NULL != s5r->leho) &&
1166 (0 == strcasecmp (hdr_type,
1167 MHD_HTTP_HEADER_SET_COOKIE)) )
1170 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1171 strlen (s5r->domain) + 1);
1173 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1174 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1176 if ( (0 == strncasecmp (tok,
1178 strlen (" domain"))) &&
1179 (GNUNET_NO == domain_matched) )
1181 domain_matched = GNUNET_YES;
1182 cookie_domain = tok + strlen (" domain") + 1;
1183 if (strlen (cookie_domain) < strlen (s5r->leho))
1185 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1186 if (0 == strcasecmp (cookie_domain,
1187 s5r->leho + delta_cdomain))
1189 offset += sprintf (new_cookie_hdr + offset,
1195 else if (0 == strcmp (cookie_domain,
1198 offset += sprintf (new_cookie_hdr + offset,
1203 else if ( ('.' == cookie_domain[0]) &&
1204 (0 == strcmp (&cookie_domain[1],
1207 offset += sprintf (new_cookie_hdr + offset,
1212 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1213 _("Cookie domain `%s' supplied by server is invalid\n"),
1216 GNUNET_memcpy (new_cookie_hdr + offset,
1219 offset += strlen (tok);
1220 new_cookie_hdr[offset++] = ';';
1222 hdr_val = new_cookie_hdr;
1225 new_location = NULL;
1226 if (0 == strcasecmp (MHD_HTTP_HEADER_TRANSFER_ENCODING,
1229 /* Ignore transfer encoding, set automatically by MHD if required */
1232 if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION,
1237 GNUNET_asprintf (&leho_host,
1238 (HTTPS_PORT != s5r->port)
1242 if (0 == strncmp (leho_host,
1244 strlen (leho_host)))
1246 GNUNET_asprintf (&new_location,
1248 (HTTPS_PORT != s5r->port)
1252 hdr_val + strlen (leho_host));
1253 hdr_val = new_location;
1255 GNUNET_free (leho_host);
1257 /* MHD does not allow certain characters in values, remove those */
1258 if (NULL != (tok = strchr (hdr_val, '\n')))
1260 if (NULL != (tok = strchr (hdr_val, '\r')))
1262 if (NULL != (tok = strchr (hdr_val, '\t')))
1264 if (0 != strlen (hdr_val)) /* Rely in MHD to set those */
1266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1267 "Adding header %s: %s to MHD response\n",
1270 header = GNUNET_new (struct HttpResponseHeader);
1271 header->type = GNUNET_strdup (hdr_type);
1272 header->value = GNUNET_strdup (hdr_val);
1273 GNUNET_CONTAINER_DLL_insert (s5r->header_head,
1279 GNUNET_free_non_null (new_cookie_hdr);
1280 GNUNET_free_non_null (new_location);
1286 * Create an MHD response object in @a s5r matching the
1287 * information we got from curl.
1289 * @param s5r the request for which we convert the response
1290 * @return #GNUNET_OK on success, #GNUNET_SYSERR if response was
1291 * already initialized before
1294 create_mhd_response_from_s5r (struct Socks5Request *s5r)
1297 double content_length;
1299 if (NULL != s5r->response)
1301 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1302 "Response already set!\n");
1303 return GNUNET_SYSERR;
1306 GNUNET_break (CURLE_OK ==
1307 curl_easy_getinfo (s5r->curl,
1308 CURLINFO_RESPONSE_CODE,
1310 GNUNET_break (CURLE_OK ==
1311 curl_easy_getinfo (s5r->curl,
1312 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
1314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1315 "Creating MHD response with code %d and size %d for %s%s\n",
1317 (int) content_length,
1320 s5r->response_code = resp_code;
1321 s5r->response = MHD_create_response_from_callback ((-1 == content_length)
1328 for (struct HttpResponseHeader *header = s5r->header_head;
1330 header = header->next)
1332 GNUNET_break (MHD_YES ==
1333 MHD_add_response_header (s5r->response,
1338 if (NULL != s5r->leho)
1342 GNUNET_asprintf (&cors_hdr,
1343 (HTTPS_PORT == s5r->port)
1348 GNUNET_break (MHD_YES ==
1349 MHD_add_response_header (s5r->response,
1350 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1352 GNUNET_free (cors_hdr);
1354 /* force connection to be closed after each request, as we
1355 do not support HTTP pipelining (yet, FIXME!) */
1356 /*GNUNET_break (MHD_YES ==
1357 MHD_add_response_header (s5r->response,
1358 MHD_HTTP_HEADER_CONNECTION,
1360 MHD_resume_connection (s5r->con);
1361 s5r->suspended = GNUNET_NO;
1367 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1368 * it available to MHD.
1370 * @param ptr pointer to the data
1371 * @param size number of blocks of data
1372 * @param nmemb blocksize
1373 * @param ctx our `struct Socks5Request *`
1374 * @return number of bytes handled
1377 curl_download_cb (void *ptr,
1382 struct Socks5Request *s5r = ctx;
1383 size_t total = size * nmemb;
1385 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1386 "Receiving %ux%u bytes for `%s%s' from cURL\n",
1387 (unsigned int) size,
1388 (unsigned int) nmemb,
1391 if (NULL == s5r->response)
1392 GNUNET_assert (GNUNET_OK ==
1393 create_mhd_response_from_s5r (s5r));
1395 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1396 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1398 /* we're still not done with the upload, do not yet
1399 start the download, the IO buffer is still full
1400 with upload data. */
1401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1402 "Pausing CURL download `%s%s', waiting for UPLOAD to finish\n",
1405 s5r->curl_paused = GNUNET_YES;
1406 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1408 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1411 "Pausing CURL `%s%s' download, not enough space %llu %llu %llu\n",
1414 (unsigned long long) sizeof (s5r->io_buf),
1415 (unsigned long long) s5r->io_len,
1416 (unsigned long long) total);
1417 s5r->curl_paused = GNUNET_YES;
1418 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1420 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1423 s5r->io_len += total;
1424 if (GNUNET_YES == s5r->suspended)
1426 MHD_resume_connection (s5r->con);
1427 s5r->suspended = GNUNET_NO;
1429 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1430 "Received %llu bytes of payload via cURL from %s\n",
1431 (unsigned long long) total,
1433 if (s5r->io_len == total)
1434 run_mhd_now (s5r->hd);
1440 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1441 * to make it available to MHD.
1443 * @param buf where to write the data
1444 * @param size number of bytes per member
1445 * @param nmemb number of members available in @a buf
1446 * @param cls our `struct Socks5Request` that generated the data
1447 * @return number of bytes copied to @a buf
1450 curl_upload_cb (void *buf,
1455 struct Socks5Request *s5r = cls;
1456 size_t len = size * nmemb;
1459 if ( (0 == s5r->io_len) &&
1460 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1463 "Pausing CURL UPLOAD %s%s, need more data\n",
1466 return CURL_READFUNC_PAUSE;
1468 if ( (0 == s5r->io_len) &&
1469 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1471 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1472 if (GNUNET_YES == s5r->curl_paused)
1474 s5r->curl_paused = GNUNET_NO;
1475 curl_easy_pause (s5r->curl,
1478 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1479 "Completed CURL UPLOAD %s%s\n",
1482 return 0; /* upload finished, can now download */
1484 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
1485 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1488 return CURL_READFUNC_ABORT;
1490 to_copy = GNUNET_MIN (s5r->io_len,
1495 memmove (s5r->io_buf,
1496 &s5r->io_buf[to_copy],
1497 s5r->io_len - to_copy);
1498 s5r->io_len -= to_copy;
1499 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1500 run_mhd_now (s5r->hd); /* got more space for upload now */
1505 /* ************************** main loop of cURL interaction ****************** */
1509 * Task that is run when we are ready to receive more data
1512 * @param cls closure
1515 curl_task_download (void *cls);
1519 * Ask cURL for the select() sets and schedule cURL operations.
1522 curl_download_prepare ()
1529 struct GNUNET_NETWORK_FDSet *grs;
1530 struct GNUNET_NETWORK_FDSet *gws;
1532 struct GNUNET_TIME_Relative rtime;
1534 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1535 "Scheduling CURL interaction\n");
1536 if (NULL != curl_download_task)
1538 GNUNET_SCHEDULER_cancel (curl_download_task);
1539 curl_download_task = NULL;
1545 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi,
1551 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1552 "%s failed at %s:%d: `%s'\n",
1553 "curl_multi_fdset", __FILE__, __LINE__,
1554 curl_multi_strerror (mret));
1558 GNUNET_break (CURLM_OK ==
1559 curl_multi_timeout (curl_multi,
1562 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1564 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1568 grs = GNUNET_NETWORK_fdset_create ();
1569 gws = GNUNET_NETWORK_fdset_create ();
1570 GNUNET_NETWORK_fdset_copy_native (grs,
1573 GNUNET_NETWORK_fdset_copy_native (gws,
1576 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1580 &curl_task_download,
1582 GNUNET_NETWORK_fdset_destroy (gws);
1583 GNUNET_NETWORK_fdset_destroy (grs);
1587 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1588 &curl_task_download,
1595 * Task that is run when we are ready to receive more data from curl.
1597 * @param cls closure, NULL
1600 curl_task_download (void *cls)
1604 struct CURLMsg *msg;
1606 struct Socks5Request *s5r;
1608 curl_download_task = NULL;
1609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1610 "Running CURL interaction\n");
1614 mret = curl_multi_perform (curl_multi,
1616 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1617 "Checking CURL multi status: %d\n",
1619 while (NULL != (msg = curl_multi_info_read (curl_multi,
1622 GNUNET_break (CURLE_OK ==
1623 curl_easy_getinfo (msg->easy_handle,
1634 /* documentation says this is not used */
1638 switch (msg->data.result)
1641 case CURLE_GOT_NOTHING:
1642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1643 "CURL download %s%s completed.\n",
1646 if (NULL == s5r->response)
1648 GNUNET_assert (GNUNET_OK ==
1649 create_mhd_response_from_s5r (s5r));
1651 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1652 if (GNUNET_YES == s5r->suspended)
1654 MHD_resume_connection (s5r->con);
1655 s5r->suspended = GNUNET_NO;
1657 run_mhd_now (s5r->hd);
1660 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1661 "Download curl %s%s failed: %s\n",
1664 curl_easy_strerror (msg->data.result));
1665 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1666 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1667 if (GNUNET_YES == s5r->suspended)
1669 MHD_resume_connection (s5r->con);
1670 s5r->suspended = GNUNET_NO;
1672 run_mhd_now (s5r->hd);
1675 if (NULL == s5r->response)
1676 s5r->response = curl_failure_response;
1679 /* documentation says this is not used */
1683 /* unexpected status code */
1688 } while (mret == CURLM_CALL_MULTI_PERFORM);
1689 if (CURLM_OK != mret)
1690 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1691 "%s failed at %s:%d: `%s'\n",
1692 "curl_multi_perform", __FILE__, __LINE__,
1693 curl_multi_strerror (mret));
1696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1697 "Suspending cURL multi loop, no more events pending\n");
1698 if (NULL != curl_download_task)
1700 GNUNET_SCHEDULER_cancel (curl_download_task);
1701 curl_download_task = NULL;
1703 return; /* nothing more in progress */
1705 curl_download_prepare ();
1709 /* ********************************* MHD response generation ******************* */
1713 * Read HTTP request header field from the request. Copies the fields
1714 * over to the 'headers' that will be given to curl. However, 'Host'
1715 * is substituted with the LEHO if present. We also change the
1716 * 'Connection' header value to "close" as the proxy does not support
1719 * @param cls our `struct Socks5Request`
1720 * @param kind value kind
1721 * @param key field key
1722 * @param value field value
1723 * @return #MHD_YES to continue to iterate
1726 con_val_iter (void *cls,
1727 enum MHD_ValueKind kind,
1731 struct Socks5Request *s5r = cls;
1734 if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST,
1736 (NULL != s5r->leho) )
1738 GNUNET_asprintf (&hdr,
1742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1743 "Adding HEADER `%s' to HTTP request\n",
1745 s5r->headers = curl_slist_append (s5r->headers,
1753 * Main MHD callback for handling requests.
1756 * @param con MHD connection handle
1757 * @param url the url in the request
1758 * @param meth the HTTP method used ("GET", "PUT", etc.)
1759 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1760 * @param upload_data the data being uploaded (excluding HEADERS,
1761 * for a POST that fits into memory and that is encoded
1762 * with a supported encoding, the POST data will NOT be
1763 * given in upload_data and is instead available as
1764 * part of MHD_get_connection_values; very large POST
1765 * data *will* be made available incrementally in
1767 * @param upload_data_size set initially to the size of the
1768 * @a upload_data provided; the method must update this
1769 * value to the number of bytes NOT processed;
1770 * @param con_cls pointer to location where we store the `struct Request`
1771 * @return #MHD_YES if the connection was handled successfully,
1772 * #MHD_NO if the socket must be closed due to a serious
1773 * error while handling the request
1776 create_response (void *cls,
1777 struct MHD_Connection *con,
1781 const char *upload_data,
1782 size_t *upload_data_size,
1785 struct Socks5Request *s5r = *con_cls;
1787 char ipstring[INET6_ADDRSTRLEN];
1788 char ipaddr[INET6_ADDRSTRLEN + 2];
1789 const struct sockaddr *sa;
1790 const struct sockaddr_in *s4;
1791 const struct sockaddr_in6 *s6;
1801 /* Fresh connection. */
1802 if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
1804 /* first time here, initialize curl handle */
1807 sa = (const struct sockaddr *) &s5r->destination_address;
1808 switch (sa->sa_family)
1811 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1812 if (NULL == inet_ntop (AF_INET,
1820 GNUNET_snprintf (ipaddr,
1824 port = ntohs (s4->sin_port);
1827 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1828 if (NULL == inet_ntop (AF_INET6,
1836 GNUNET_snprintf (ipaddr,
1840 port = ntohs (s6->sin6_port);
1851 if (NULL == s5r->curl)
1852 s5r->curl = curl_easy_init ();
1853 if (NULL == s5r->curl)
1854 return MHD_queue_response (con,
1855 MHD_HTTP_INTERNAL_SERVER_ERROR,
1856 curl_failure_response);
1857 curl_easy_setopt (s5r->curl,
1858 CURLOPT_HEADERFUNCTION,
1860 curl_easy_setopt (s5r->curl,
1863 curl_easy_setopt (s5r->curl,
1864 CURLOPT_FOLLOWLOCATION,
1867 curl_easy_setopt (s5r->curl,
1870 curl_easy_setopt (s5r->curl,
1871 CURLOPT_CONNECTTIMEOUT,
1873 curl_easy_setopt (s5r->curl,
1876 curl_easy_setopt (s5r->curl,
1879 curl_easy_setopt (s5r->curl,
1880 CURLOPT_HTTP_CONTENT_DECODING,
1882 curl_easy_setopt (s5r->curl,
1885 curl_easy_setopt (s5r->curl,
1888 curl_easy_setopt (s5r->curl,
1892 * Pre-populate cache to resolve Hostname.
1893 * This is necessary as the DNS name in the CURLOPT_URL is used
1894 * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1896 if (NULL != s5r->leho)
1900 GNUNET_asprintf (&curl_hosts,
1905 s5r->hosts = curl_slist_append (NULL,
1907 curl_easy_setopt (s5r->curl,
1910 GNUNET_free (curl_hosts);
1914 GNUNET_asprintf (&curlurl,
1915 (HTTPS_PORT != s5r->port)
1917 : "https://%s:%d%s",
1926 GNUNET_asprintf (&curlurl,
1927 (HTTPS_PORT != s5r->port)
1929 : "https://%s:%d%s",
1934 curl_easy_setopt (s5r->curl,
1937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1938 "Launching %s CURL interaction, fetching `%s'\n",
1939 (s5r->is_gns) ? "GNS" : "DNS",
1941 GNUNET_free (curlurl);
1942 if (0 == strcasecmp (meth,
1943 MHD_HTTP_METHOD_PUT))
1945 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1946 curl_easy_setopt (s5r->curl,
1949 curl_easy_setopt (s5r->curl,
1950 CURLOPT_WRITEFUNCTION,
1952 curl_easy_setopt (s5r->curl,
1955 GNUNET_assert (CURLE_OK ==
1956 curl_easy_setopt (s5r->curl,
1957 CURLOPT_READFUNCTION,
1959 curl_easy_setopt (s5r->curl,
1964 long upload_size = 0;
1966 us = MHD_lookup_connection_value (con,
1968 MHD_HTTP_HEADER_CONTENT_LENGTH);
1969 if ( (1 == sscanf (us,
1972 (upload_size >= 0) )
1974 curl_easy_setopt (s5r->curl,
1980 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1982 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1983 curl_easy_setopt (s5r->curl,
1986 curl_easy_setopt (s5r->curl,
1987 CURLOPT_WRITEFUNCTION,
1989 curl_easy_setopt (s5r->curl,
1992 curl_easy_setopt (s5r->curl,
1993 CURLOPT_READFUNCTION,
1995 curl_easy_setopt (s5r->curl,
2002 us = MHD_lookup_connection_value (con,
2004 MHD_HTTP_HEADER_CONTENT_LENGTH);
2005 if ( (NULL != us) &&
2009 (upload_size >= 0) )
2011 curl_easy_setopt (s5r->curl,
2015 curl_easy_setopt (s5r->curl,
2021 else if (0 == strcasecmp (meth,
2022 MHD_HTTP_METHOD_HEAD))
2024 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2025 curl_easy_setopt (s5r->curl,
2029 else if (0 == strcasecmp (meth,
2030 MHD_HTTP_METHOD_OPTIONS))
2032 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2033 curl_easy_setopt (s5r->curl,
2034 CURLOPT_CUSTOMREQUEST,
2036 curl_easy_setopt (s5r->curl,
2037 CURLOPT_WRITEFUNCTION,
2039 curl_easy_setopt (s5r->curl,
2044 else if (0 == strcasecmp (meth,
2045 MHD_HTTP_METHOD_GET))
2047 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2048 curl_easy_setopt (s5r->curl,
2051 curl_easy_setopt (s5r->curl,
2052 CURLOPT_WRITEFUNCTION,
2054 curl_easy_setopt (s5r->curl,
2058 else if (0 == strcasecmp (meth,
2059 MHD_HTTP_METHOD_DELETE))
2061 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
2062 curl_easy_setopt (s5r->curl,
2063 CURLOPT_CUSTOMREQUEST,
2065 curl_easy_setopt (s5r->curl,
2066 CURLOPT_WRITEFUNCTION,
2068 curl_easy_setopt (s5r->curl,
2074 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2075 _("Unsupported HTTP method `%s'\n"),
2077 curl_easy_cleanup (s5r->curl);
2082 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
2084 curl_easy_setopt (s5r->curl,
2085 CURLOPT_HTTP_VERSION,
2086 CURL_HTTP_VERSION_1_0);
2088 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
2090 curl_easy_setopt (s5r->curl,
2091 CURLOPT_HTTP_VERSION,
2092 CURL_HTTP_VERSION_1_1);
2096 curl_easy_setopt (s5r->curl,
2097 CURLOPT_HTTP_VERSION,
2098 CURL_HTTP_VERSION_NONE);
2101 if (HTTPS_PORT == s5r->port)
2103 curl_easy_setopt (s5r->curl,
2106 if (NULL != s5r->dane_data)
2107 curl_easy_setopt (s5r->curl,
2108 CURLOPT_SSL_VERIFYPEER,
2111 curl_easy_setopt (s5r->curl,
2112 CURLOPT_SSL_VERIFYPEER,
2114 /* Disable cURL checking the hostname, as we will check ourselves
2115 as only we have the domain name or the LEHO or the DANE record */
2116 curl_easy_setopt (s5r->curl,
2117 CURLOPT_SSL_VERIFYHOST,
2122 curl_easy_setopt (s5r->curl,
2128 curl_multi_add_handle (curl_multi,
2132 curl_easy_cleanup (s5r->curl);
2136 MHD_get_connection_values (con,
2140 curl_easy_setopt (s5r->curl,
2143 curl_download_prepare ();
2147 /* continuing to process request */
2148 if (0 != *upload_data_size)
2150 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2151 "Processing %u bytes UPLOAD\n",
2152 (unsigned int) *upload_data_size);
2154 /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else
2155 * upload callback is not called!
2157 curl_easy_setopt (s5r->curl,
2158 CURLOPT_POSTFIELDSIZE,
2161 left = GNUNET_MIN (*upload_data_size,
2162 sizeof (s5r->io_buf) - s5r->io_len);
2163 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
2166 s5r->io_len += left;
2167 *upload_data_size -= left;
2168 GNUNET_assert (NULL != s5r->curl);
2169 if (GNUNET_YES == s5r->curl_paused)
2171 s5r->curl_paused = GNUNET_NO;
2172 curl_easy_pause (s5r->curl,
2177 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
2179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2180 "Finished processing UPLOAD\n");
2181 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
2183 if (NULL == s5r->response)
2185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2186 "Waiting for HTTP response for %s%s...\n",
2189 MHD_suspend_connection (con);
2190 s5r->suspended = GNUNET_YES;
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "Queueing response for %s%s with MHD\n",
2197 run_mhd_now (s5r->hd);
2198 return MHD_queue_response (con,
2204 /* ******************** MHD HTTP setup and event loop ******************** */
2208 * Function called when MHD decides that we are done with a request.
2211 * @param connection connection handle
2212 * @param con_cls value as set by the last call to
2213 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2214 * @param toe reason for request termination (ignored)
2217 mhd_completed_cb (void *cls,
2218 struct MHD_Connection *connection,
2220 enum MHD_RequestTerminationCode toe)
2222 struct Socks5Request *s5r = *con_cls;
2226 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
2227 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2228 "MHD encountered error handling request: %d\n",
2230 if (NULL != s5r->curl)
2232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2233 "Removing cURL handle (MHD interaction complete)\n");
2234 curl_multi_remove_handle (curl_multi,
2236 curl_slist_free_all (s5r->headers);
2237 s5r->headers = NULL;
2238 curl_easy_reset (s5r->curl);
2242 curl_download_prepare ();
2244 if ( (NULL != s5r->response) &&
2245 (curl_failure_response != s5r->response) )
2246 MHD_destroy_response (s5r->response);
2247 for (struct HttpResponseHeader *header = s5r->header_head;
2249 header = s5r->header_head)
2251 GNUNET_CONTAINER_DLL_remove (s5r->header_head,
2254 GNUNET_free (header->type);
2255 GNUNET_free (header->value);
2256 GNUNET_free (header);
2258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2259 "Finished request for %s\n",
2261 GNUNET_free (s5r->url);
2262 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2264 s5r->response = NULL;
2270 * Function called when MHD connection is opened or closed.
2273 * @param connection connection handle
2274 * @param con_cls value as set by the last call to
2275 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2276 * @param toe connection notification type
2279 mhd_connection_cb (void *cls,
2280 struct MHD_Connection *connection,
2282 enum MHD_ConnectionNotificationCode cnc)
2284 struct Socks5Request *s5r;
2285 const union MHD_ConnectionInfo *ci;
2290 case MHD_CONNECTION_NOTIFY_STARTED:
2291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
2292 ci = MHD_get_connection_info (connection,
2293 MHD_CONNECTION_INFO_CONNECTION_FD);
2299 sock = ci->connect_fd;
2300 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
2302 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
2304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2305 "Context set...\n");
2306 s5r->ssl_checked = GNUNET_NO;
2312 case MHD_CONNECTION_NOTIFY_CLOSED:
2313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2314 "Connection closed... cleaning up\n");
2318 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2319 "Connection stale!\n");
2323 curl_download_prepare ();
2332 * Function called when MHD first processes an incoming connection.
2333 * Gives us the respective URI information.
2335 * We use this to associate the `struct MHD_Connection` with our
2336 * internal `struct Socks5Request` data structure (by checking
2337 * for matching sockets).
2339 * @param cls the HTTP server handle (a `struct MhdHttpList`)
2340 * @param url the URL that is being requested
2341 * @param connection MHD connection object for the request
2342 * @return the `struct Socks5Request` that this @a connection is for
2345 mhd_log_callback (void *cls,
2347 struct MHD_Connection *connection)
2349 struct Socks5Request *s5r;
2350 const union MHD_ConnectionInfo *ci;
2352 ci = MHD_get_connection_info (connection,
2353 MHD_CONNECTION_INFO_SOCKET_CONTEXT);
2354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
2360 s5r = ci->socket_context;
2361 if (NULL != s5r->url)
2366 s5r->url = GNUNET_strdup (url);
2367 if (NULL != s5r->timeout_task)
2369 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
2370 s5r->timeout_task = NULL;
2372 GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD);
2378 * Kill the given MHD daemon.
2380 * @param hd daemon to stop
2383 kill_httpd (struct MhdHttpList *hd)
2385 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
2388 GNUNET_free_non_null (hd->domain);
2389 MHD_stop_daemon (hd->daemon);
2390 if (NULL != hd->httpd_task)
2392 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2393 hd->httpd_task = NULL;
2395 GNUNET_free_non_null (hd->proxy_cert);
2403 * Task run whenever HTTP server is idle for too long. Kill it.
2405 * @param cls the `struct MhdHttpList *`
2408 kill_httpd_task (void *cls)
2410 struct MhdHttpList *hd = cls;
2412 hd->httpd_task = NULL;
2418 * Task run whenever HTTP server operations are pending.
2420 * @param cls the `struct MhdHttpList *` of the daemon that is being run
2423 do_httpd (void *cls);
2427 * Schedule MHD. This function should be called initially when an
2428 * MHD is first getting its client socket, and will then automatically
2429 * always be called later whenever there is work to be done.
2431 * @param hd the daemon to schedule
2434 schedule_httpd (struct MhdHttpList *hd)
2439 struct GNUNET_NETWORK_FDSet *wrs;
2440 struct GNUNET_NETWORK_FDSet *wws;
2443 MHD_UNSIGNED_LONG_LONG timeout;
2444 struct GNUNET_TIME_Relative tv;
2451 MHD_get_fdset (hd->daemon,
2460 haveto = MHD_get_timeout (hd->daemon,
2462 if (MHD_YES == haveto)
2463 tv.rel_value_us = (uint64_t) timeout * 1000LL;
2465 tv = GNUNET_TIME_UNIT_FOREVER_REL;
2468 wrs = GNUNET_NETWORK_fdset_create ();
2469 wws = GNUNET_NETWORK_fdset_create ();
2470 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
2471 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
2478 if (NULL != hd->httpd_task)
2480 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2481 hd->httpd_task = NULL;
2483 if ( (MHD_YES != haveto) &&
2487 /* daemon is idle, kill after timeout */
2488 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
2495 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2500 GNUNET_NETWORK_fdset_destroy (wrs);
2502 GNUNET_NETWORK_fdset_destroy (wws);
2507 * Task run whenever HTTP server operations are pending.
2509 * @param cls the `struct MhdHttpList` of the daemon that is being run
2512 do_httpd (void *cls)
2514 struct MhdHttpList *hd = cls;
2516 hd->httpd_task = NULL;
2517 MHD_run (hd->daemon);
2518 schedule_httpd (hd);
2523 * Run MHD now, we have extra data ready for the callback.
2525 * @param hd the daemon to run now.
2528 run_mhd_now (struct MhdHttpList *hd)
2530 if (NULL != hd->httpd_task)
2531 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2532 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
2538 * Read file in filename
2540 * @param filename file to read
2541 * @param size pointer where filesize is stored
2542 * @return NULL on error
2545 load_file (const char* filename,
2552 GNUNET_DISK_file_size (filename,
2557 if (fsize > MAX_PEM_SIZE)
2559 *size = (unsigned int) fsize;
2560 buffer = GNUNET_malloc (*size);
2562 GNUNET_DISK_fn_read (filename,
2566 GNUNET_free (buffer);
2574 * Load PEM key from file
2576 * @param key where to store the data
2577 * @param keyfile path to the PEM file
2578 * @return #GNUNET_OK on success
2581 load_key_from_file (gnutls_x509_privkey_t key,
2582 const char* keyfile)
2584 gnutls_datum_t key_data;
2587 key_data.data = load_file (keyfile,
2589 if (NULL == key_data.data)
2590 return GNUNET_SYSERR;
2591 ret = gnutls_x509_privkey_import (key, &key_data,
2592 GNUTLS_X509_FMT_PEM);
2593 if (GNUTLS_E_SUCCESS != ret)
2595 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2596 _("Unable to import private key from file `%s'\n"),
2599 GNUNET_free_non_null (key_data.data);
2600 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2605 * Load cert from file
2607 * @param crt struct to store data in
2608 * @param certfile path to pem file
2609 * @return #GNUNET_OK on success
2612 load_cert_from_file (gnutls_x509_crt_t crt,
2613 const char* certfile)
2615 gnutls_datum_t cert_data;
2618 cert_data.data = load_file (certfile,
2620 if (NULL == cert_data.data)
2621 return GNUNET_SYSERR;
2622 ret = gnutls_x509_crt_import (crt,
2624 GNUTLS_X509_FMT_PEM);
2625 if (GNUTLS_E_SUCCESS != ret)
2627 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2628 _("Unable to import certificate from `%s'\n"),
2631 GNUNET_free_non_null (cert_data.data);
2632 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2637 * Generate new certificate for specific name
2639 * @param name the subject name to generate a cert for
2640 * @return a struct holding the PEM data, NULL on error
2642 static struct ProxyGNSCertificate *
2643 generate_gns_certificate (const char *name)
2645 unsigned int serial;
2646 size_t key_buf_size;
2647 size_t cert_buf_size;
2648 gnutls_x509_crt_t request;
2651 struct ProxyGNSCertificate *pgc;
2653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2654 "Generating x.509 certificate for `%s'\n",
2656 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2657 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2658 pgc = GNUNET_new (struct ProxyGNSCertificate);
2659 gnutls_x509_crt_set_dn_by_oid (request,
2660 GNUTLS_OID_X520_COUNTRY_NAME,
2664 gnutls_x509_crt_set_dn_by_oid (request,
2665 GNUTLS_OID_X520_ORGANIZATION_NAME,
2668 strlen ("GNU Name System"));
2669 gnutls_x509_crt_set_dn_by_oid (request,
2670 GNUTLS_OID_X520_COMMON_NAME,
2674 gnutls_x509_crt_set_subject_alternative_name (request,
2677 GNUNET_break (GNUTLS_E_SUCCESS ==
2678 gnutls_x509_crt_set_version (request,
2680 gnutls_rnd (GNUTLS_RND_NONCE,
2683 gnutls_x509_crt_set_serial (request,
2686 etime = time (NULL);
2687 tm_data = localtime (&etime);
2689 etime = mktime(tm_data);
2690 gnutls_x509_crt_set_activation_time (request,
2693 etime = mktime (tm_data);
2694 gnutls_x509_crt_set_expiration_time (request,
2696 gnutls_x509_crt_sign2 (request,
2701 key_buf_size = sizeof (pgc->key);
2702 cert_buf_size = sizeof (pgc->cert);
2703 gnutls_x509_crt_export (request,
2704 GNUTLS_X509_FMT_PEM,
2707 gnutls_x509_privkey_export (proxy_ca.key,
2708 GNUTLS_X509_FMT_PEM,
2711 gnutls_x509_crt_deinit (request);
2717 * Function called by MHD with errors, suppresses them all.
2719 * @param cls closure
2720 * @param fm format string (`printf()`-style)
2721 * @param ap arguments to @a fm
2724 mhd_error_log_callback (void *cls,
2733 * Lookup (or create) an TLS MHD instance for a particular domain.
2735 * @param domain the domain the TLS daemon has to serve
2736 * @return NULL on error
2738 static struct MhdHttpList *
2739 lookup_ssl_httpd (const char* domain)
2741 struct MhdHttpList *hd;
2742 struct ProxyGNSCertificate *pgc;
2749 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2750 if ( (NULL != hd->domain) &&
2751 (0 == strcmp (hd->domain, domain)) )
2753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2754 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2756 pgc = generate_gns_certificate (domain);
2757 hd = GNUNET_new (struct MhdHttpList);
2758 hd->is_ssl = GNUNET_YES;
2759 hd->domain = GNUNET_strdup (domain);
2760 hd->proxy_cert = pgc;
2761 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
2764 &create_response, hd,
2765 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2766 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2767 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
2768 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2769 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2770 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2771 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2773 if (NULL == hd->daemon)
2779 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2787 * Task run when a Socks5Request somehow fails to be associated with
2788 * an MHD connection (i.e. because the client never speaks HTTP after
2789 * the SOCKS5 handshake). Clean up.
2791 * @param cls the `struct Socks5Request *`
2794 timeout_s5r_handshake (void *cls)
2796 struct Socks5Request *s5r = cls;
2798 s5r->timeout_task = NULL;
2804 * We're done with the Socks5 protocol, now we need to pass the
2805 * connection data through to the final destination, either
2806 * direct (if the protocol might not be HTTP), or via MHD
2807 * (if the port looks like it should be HTTP).
2809 * @param s5r socks request that has reached the final stage
2812 setup_data_transfer (struct Socks5Request *s5r)
2814 struct MhdHttpList *hd;
2816 const struct sockaddr *addr;
2823 GNUNET_asprintf (&domain,
2826 hd = lookup_ssl_httpd (domain);
2829 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2830 _("Failed to start HTTPS server for `%s'\n"),
2833 GNUNET_free (domain);
2840 GNUNET_assert (NULL != httpd);
2844 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2845 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2846 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2847 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2849 MHD_add_connection (hd->daemon,
2854 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2855 _("Failed to pass client to MHD\n"));
2857 GNUNET_free_non_null (domain);
2861 schedule_httpd (hd);
2862 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2863 &timeout_s5r_handshake,
2865 GNUNET_free_non_null (domain);
2869 /* ********************* SOCKS handling ************************* */
2873 * Write data from buffer to socks5 client, then continue with state machine.
2875 * @param cls the closure with the `struct Socks5Request`
2878 do_write (void *cls)
2880 struct Socks5Request *s5r = cls;
2884 len = GNUNET_NETWORK_socket_send (s5r->sock,
2889 /* write error: connection closed, shutdown, etc.; just clean up */
2890 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2897 s5r->wbuf_len - len);
2898 s5r->wbuf_len -= len;
2899 if (s5r->wbuf_len > 0)
2901 /* not done writing */
2903 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2909 /* we're done writing, continue with state machine! */
2916 case SOCKS5_REQUEST:
2917 GNUNET_assert (NULL != s5r->rtask);
2919 case SOCKS5_DATA_TRANSFER:
2920 setup_data_transfer (s5r);
2922 case SOCKS5_WRITE_THEN_CLEANUP:
2933 * Return a server response message indicating a failure to the client.
2935 * @param s5r request to return failure code for
2936 * @param sc status code to return
2939 signal_socks_failure (struct Socks5Request *s5r,
2940 enum Socks5StatusCode sc)
2942 struct Socks5ServerResponseMessage *s_resp;
2944 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2945 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2946 s_resp->version = SOCKS_VERSION_5;
2948 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2949 if (NULL != s5r->wtask)
2951 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2958 * Return a server response message indicating success.
2960 * @param s5r request to return success status message for
2963 signal_socks_success (struct Socks5Request *s5r)
2965 struct Socks5ServerResponseMessage *s_resp;
2967 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2968 s_resp->version = SOCKS_VERSION_5;
2969 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2970 s_resp->reserved = 0;
2971 s_resp->addr_type = SOCKS5_AT_IPV4;
2972 /* zero out IPv4 address and port */
2975 sizeof (struct in_addr) + sizeof (uint16_t));
2976 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2977 sizeof (struct in_addr) + sizeof (uint16_t);
2978 if (NULL == s5r->wtask)
2980 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2987 * Process GNS results for target domain.
2989 * @param cls the `struct Socks5Request *`
2990 * @param tld #GNUNET_YES if this was a GNS TLD.
2991 * @param rd_count number of records returned
2992 * @param rd record data
2995 handle_gns_result (void *cls,
2998 const struct GNUNET_GNSRECORD_Data *rd)
3000 struct Socks5Request *s5r = cls;
3001 const struct GNUNET_GNSRECORD_Data *r;
3004 s5r->gns_lookup = NULL;
3007 for (uint32_t i=0;i<rd_count;i++)
3010 switch (r->record_type)
3012 case GNUNET_DNSPARSER_TYPE_A:
3014 struct sockaddr_in *in;
3016 if (sizeof (struct in_addr) != r->data_size)
3018 GNUNET_break_op (0);
3021 if (GNUNET_YES == got_ip)
3024 GNUNET_NETWORK_test_pf (PF_INET))
3026 got_ip = GNUNET_YES;
3027 in = (struct sockaddr_in *) &s5r->destination_address;
3028 in->sin_family = AF_INET;
3029 GNUNET_memcpy (&in->sin_addr,
3032 in->sin_port = htons (s5r->port);
3033 #if HAVE_SOCKADDR_IN_SIN_LEN
3034 in->sin_len = sizeof (*in);
3038 case GNUNET_DNSPARSER_TYPE_AAAA:
3040 struct sockaddr_in6 *in;
3042 if (sizeof (struct in6_addr) != r->data_size)
3044 GNUNET_break_op (0);
3047 if (GNUNET_YES == got_ip)
3049 if (GNUNET_YES == disable_v6)
3052 GNUNET_NETWORK_test_pf (PF_INET6))
3054 /* FIXME: allow user to disable IPv6 per configuration option... */
3055 got_ip = GNUNET_YES;
3056 in = (struct sockaddr_in6 *) &s5r->destination_address;
3057 in->sin6_family = AF_INET6;
3058 GNUNET_memcpy (&in->sin6_addr,
3061 in->sin6_port = htons (s5r->port);
3062 #if HAVE_SOCKADDR_IN_SIN_LEN
3063 in->sin6_len = sizeof (*in);
3067 case GNUNET_GNSRECORD_TYPE_VPN:
3068 GNUNET_break (0); /* should have been translated within GNS */
3070 case GNUNET_GNSRECORD_TYPE_LEHO:
3071 GNUNET_free_non_null (s5r->leho);
3072 s5r->leho = GNUNET_strndup (r->data,
3075 case GNUNET_GNSRECORD_TYPE_BOX:
3077 const struct GNUNET_GNSRECORD_BoxRecord *box;
3079 if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
3081 GNUNET_break_op (0);
3085 if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
3086 (ntohs (box->protocol) != IPPROTO_TCP) ||
3087 (ntohs (box->service) != s5r->port) )
3088 break; /* BOX record does not apply */
3089 if (s5r->num_danes >= MAX_DANES)
3091 GNUNET_break (0); /* MAX_DANES too small */
3094 s5r->dane_data_len[s5r->num_danes]
3095 = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
3096 s5r->dane_data[s5r->num_danes]
3097 = GNUNET_memdup (&box[1],
3098 s5r->dane_data_len[s5r->num_danes]);
3107 if ( (GNUNET_YES != got_ip) &&
3108 (GNUNET_YES == tld) )
3110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3111 "Name resolution failed to yield useful IP address.\n");
3112 signal_socks_failure (s5r,
3113 SOCKS5_STATUS_GENERAL_FAILURE);
3116 s5r->state = SOCKS5_DATA_TRANSFER;
3117 signal_socks_success (s5r);
3122 * Remove the first @a len bytes from the beginning of the read buffer.
3124 * @param s5r the handle clear the read buffer for
3125 * @param len number of bytes in read buffer to advance
3128 clear_from_s5r_rbuf (struct Socks5Request *s5r,
3131 GNUNET_assert (len <= s5r->rbuf_len);
3134 s5r->rbuf_len - len);
3135 s5r->rbuf_len -= len;
3140 * Read data from incoming Socks5 connection
3142 * @param cls the closure with the `struct Socks5Request`
3145 do_s5r_read (void *cls)
3147 struct Socks5Request *s5r = cls;
3148 const struct Socks5ClientHelloMessage *c_hello;
3149 struct Socks5ServerHelloMessage *s_hello;
3150 const struct Socks5ClientRequestMessage *c_req;
3153 const struct GNUNET_SCHEDULER_TaskContext *tc;
3156 tc = GNUNET_SCHEDULER_get_task_context ();
3157 if ( (NULL != tc->read_ready) &&
3158 (GNUNET_NETWORK_fdset_isset (tc->read_ready,
3161 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
3162 &s5r->rbuf[s5r->rbuf_len],
3163 sizeof (s5r->rbuf) - s5r->rbuf_len);
3166 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3167 "socks5 client disconnected.\n");
3171 s5r->rbuf_len += rlen;
3173 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3177 "Processing %zu bytes of socks data in state %d\n",
3183 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
3184 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
3185 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
3186 return; /* need more data */
3187 if (SOCKS_VERSION_5 != c_hello->version)
3189 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3190 _("Unsupported socks version %d\n"),
3191 (int) c_hello->version);
3195 clear_from_s5r_rbuf (s5r,
3196 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
3197 GNUNET_assert (0 == s5r->wbuf_len);
3198 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
3199 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
3200 s_hello->version = SOCKS_VERSION_5;
3201 s_hello->auth_method = SOCKS_AUTH_NONE;
3202 GNUNET_assert (NULL == s5r->wtask);
3203 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3206 s5r->state = SOCKS5_REQUEST;
3208 case SOCKS5_REQUEST:
3209 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
3210 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
3212 switch (c_req->command)
3214 case SOCKS5_CMD_TCP_STREAM:
3218 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3219 _("Unsupported socks command %d\n"),
3220 (int) c_req->command);
3221 signal_socks_failure (s5r,
3222 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
3225 switch (c_req->addr_type)
3227 case SOCKS5_AT_IPV4:
3229 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
3230 const uint16_t *port = (const uint16_t *) &v4[1];
3231 struct sockaddr_in *in;
3233 s5r->port = ntohs (*port);
3234 alen = sizeof (struct in_addr);
3235 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3236 alen + sizeof (uint16_t))
3237 return; /* need more data */
3238 in = (struct sockaddr_in *) &s5r->destination_address;
3239 in->sin_family = AF_INET;
3241 in->sin_port = *port;
3242 #if HAVE_SOCKADDR_IN_SIN_LEN
3243 in->sin_len = sizeof (*in);
3245 s5r->state = SOCKS5_DATA_TRANSFER;
3248 case SOCKS5_AT_IPV6:
3250 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
3251 const uint16_t *port = (const uint16_t *) &v6[1];
3252 struct sockaddr_in6 *in;
3254 s5r->port = ntohs (*port);
3255 alen = sizeof (struct in6_addr);
3256 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3257 alen + sizeof (uint16_t))
3258 return; /* need more data */
3259 in = (struct sockaddr_in6 *) &s5r->destination_address;
3260 in->sin6_family = AF_INET6;
3261 in->sin6_addr = *v6;
3262 in->sin6_port = *port;
3263 #if HAVE_SOCKADDR_IN_SIN_LEN
3264 in->sin6_len = sizeof (*in);
3266 s5r->state = SOCKS5_DATA_TRANSFER;
3269 case SOCKS5_AT_DOMAINNAME:
3271 const uint8_t *dom_len;
3272 const char *dom_name;
3273 const uint16_t *port;
3275 dom_len = (const uint8_t *) &c_req[1];
3276 alen = *dom_len + 1;
3277 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3278 alen + sizeof (uint16_t))
3279 return; /* need more data */
3280 dom_name = (const char *) &dom_len[1];
3281 port = (const uint16_t*) &dom_name[*dom_len];
3282 s5r->domain = GNUNET_strndup (dom_name,
3284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3285 "Requested connection is to http%s://%s:%d\n",
3286 (HTTPS_PORT == s5r->port) ? "s" : "",
3289 s5r->state = SOCKS5_RESOLVING;
3290 s5r->port = ntohs (*port);
3291 s5r->gns_lookup = GNUNET_GNS_lookup_with_tld (gns_handle,
3293 GNUNET_DNSPARSER_TYPE_A,
3294 GNUNET_NO /* only cached */,
3300 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3301 _("Unsupported socks address type %d\n"),
3302 (int) c_req->addr_type);
3303 signal_socks_failure (s5r,
3304 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
3307 clear_from_s5r_rbuf (s5r,
3308 sizeof (struct Socks5ClientRequestMessage) +
3309 alen + sizeof (uint16_t));
3310 if (0 != s5r->rbuf_len)
3312 /* read more bytes than healthy, why did the client send more!? */
3313 GNUNET_break_op (0);
3314 signal_socks_failure (s5r,
3315 SOCKS5_STATUS_GENERAL_FAILURE);
3318 if (SOCKS5_DATA_TRANSFER == s5r->state)
3320 /* if we are not waiting for GNS resolution, signal success */
3321 signal_socks_success (s5r);
3323 /* We are done reading right now */
3324 GNUNET_SCHEDULER_cancel (s5r->rtask);
3327 case SOCKS5_RESOLVING:
3330 case SOCKS5_DATA_TRANSFER:
3341 * Accept new incoming connections
3343 * @param cls the closure with the lsock4 or lsock6
3344 * @param tc the scheduler context
3347 do_accept (void *cls)
3349 struct GNUNET_NETWORK_Handle *lsock = cls;
3350 struct GNUNET_NETWORK_Handle *s;
3351 struct Socks5Request *s5r;
3353 GNUNET_assert (NULL != lsock);
3354 if (lsock == lsock4)
3355 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3359 else if (lsock == lsock6)
3360 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3366 s = GNUNET_NETWORK_socket_accept (lsock,
3371 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3376 "Got an inbound connection, waiting for data\n");
3377 s5r = GNUNET_new (struct Socks5Request);
3378 GNUNET_CONTAINER_DLL_insert (s5r_head,
3382 s5r->state = SOCKS5_INIT;
3383 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3390 /* ******************* General / main code ********************* */
3394 * Task run on shutdown
3396 * @param cls closure
3399 do_shutdown (void *cls)
3401 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3402 "Shutting down...\n");
3403 /* MHD requires resuming before destroying the daemons */
3404 for (struct Socks5Request *s5r = s5r_head;
3410 s5r->suspended = GNUNET_NO;
3411 MHD_resume_connection (s5r->con);
3414 while (NULL != mhd_httpd_head)
3415 kill_httpd (mhd_httpd_head);
3416 while (NULL != s5r_head)
3417 cleanup_s5r (s5r_head);
3420 GNUNET_NETWORK_socket_close (lsock4);
3425 GNUNET_NETWORK_socket_close (lsock6);
3428 if (NULL != curl_multi)
3430 curl_multi_cleanup (curl_multi);
3433 if (NULL != gns_handle)
3435 GNUNET_GNS_disconnect (gns_handle);
3438 if (NULL != curl_download_task)
3440 GNUNET_SCHEDULER_cancel (curl_download_task);
3441 curl_download_task = NULL;
3445 GNUNET_SCHEDULER_cancel (ltask4);
3450 GNUNET_SCHEDULER_cancel (ltask6);
3453 gnutls_x509_crt_deinit (proxy_ca.cert);
3454 gnutls_x509_privkey_deinit (proxy_ca.key);
3455 gnutls_global_deinit ();
3460 * Create an IPv4 listen socket bound to our port.
3462 * @return NULL on error
3464 static struct GNUNET_NETWORK_Handle *
3467 struct GNUNET_NETWORK_Handle *ls;
3468 struct sockaddr_in sa4;
3471 memset (&sa4, 0, sizeof (sa4));
3472 sa4.sin_family = AF_INET;
3473 sa4.sin_port = htons (port);
3474 #if HAVE_SOCKADDR_IN_SIN_LEN
3475 sa4.sin_len = sizeof (sa4);
3477 ls = GNUNET_NETWORK_socket_create (AF_INET,
3483 GNUNET_NETWORK_socket_bind (ls,
3484 (const struct sockaddr *) &sa4,
3488 GNUNET_NETWORK_socket_close (ls);
3497 * Create an IPv6 listen socket bound to our port.
3499 * @return NULL on error
3501 static struct GNUNET_NETWORK_Handle *
3504 struct GNUNET_NETWORK_Handle *ls;
3505 struct sockaddr_in6 sa6;
3508 memset (&sa6, 0, sizeof (sa6));
3509 sa6.sin6_family = AF_INET6;
3510 sa6.sin6_port = htons (port);
3511 #if HAVE_SOCKADDR_IN_SIN_LEN
3512 sa6.sin6_len = sizeof (sa6);
3514 ls = GNUNET_NETWORK_socket_create (AF_INET6,
3520 GNUNET_NETWORK_socket_bind (ls,
3521 (const struct sockaddr *) &sa6,
3525 GNUNET_NETWORK_socket_close (ls);
3534 * Main function that will be run
3536 * @param cls closure
3537 * @param args remaining command-line arguments
3538 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3539 * @param c configuration
3544 const char *cfgfile,
3545 const struct GNUNET_CONFIGURATION_Handle *c)
3547 char* cafile_cfg = NULL;
3549 struct MhdHttpList *hd;
3553 if (NULL == (curl_multi = curl_multi_init ()))
3555 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3556 "Failed to create cURL multi handle!\n");
3559 cafile = cafile_opt;
3563 GNUNET_CONFIGURATION_get_value_filename (cfg,
3568 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3573 cafile = cafile_cfg;
3575 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3576 "Using `%s' as CA\n",
3579 gnutls_global_init ();
3580 gnutls_x509_crt_init (&proxy_ca.cert);
3581 gnutls_x509_privkey_init (&proxy_ca.key);
3584 load_cert_from_file (proxy_ca.cert,
3587 load_key_from_file (proxy_ca.key,
3590 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3591 _("Failed to load X.509 key and certificate from `%s'\n"),
3593 gnutls_x509_crt_deinit (proxy_ca.cert);
3594 gnutls_x509_privkey_deinit (proxy_ca.key);
3595 gnutls_global_deinit ();
3596 GNUNET_free_non_null (cafile_cfg);
3599 GNUNET_free_non_null (cafile_cfg);
3600 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3602 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3603 "Unable to connect to GNS!\n");
3604 gnutls_x509_crt_deinit (proxy_ca.cert);
3605 gnutls_x509_privkey_deinit (proxy_ca.key);
3606 gnutls_global_deinit ();
3609 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
3612 /* Open listen socket for socks proxy */
3613 lsock6 = bind_v6 ();
3616 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3622 GNUNET_NETWORK_socket_listen (lsock6,
3625 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3627 GNUNET_NETWORK_socket_close (lsock6);
3632 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3638 lsock4 = bind_v4 ();
3641 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3647 GNUNET_NETWORK_socket_listen (lsock4,
3650 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3652 GNUNET_NETWORK_socket_close (lsock4);
3657 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3663 if ( (NULL == lsock4) &&
3666 GNUNET_SCHEDULER_shutdown ();
3669 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3671 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3672 "cURL global init failed!\n");
3673 GNUNET_SCHEDULER_shutdown ();
3676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3677 "Proxy listens on port %u\n",
3678 (unsigned int) port);
3680 /* start MHD daemon for HTTP */
3681 hd = GNUNET_new (struct MhdHttpList);
3682 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
3685 &create_response, hd,
3686 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3687 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3688 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
3689 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3691 if (NULL == hd->daemon)
3694 GNUNET_SCHEDULER_shutdown ();
3698 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
3705 * The main function for gnunet-gns-proxy.
3707 * @param argc number of arguments from the command line
3708 * @param argv command line arguments
3709 * @return 0 ok, 1 on error
3715 struct GNUNET_GETOPT_CommandLineOption options[] = {
3716 GNUNET_GETOPT_option_uint16 ('p',
3719 gettext_noop ("listen on specified port (default: 7777)"),
3721 GNUNET_GETOPT_option_string ('a',
3724 gettext_noop ("pem file to use as CA"),
3726 GNUNET_GETOPT_option_flag ('6',
3728 gettext_noop ("disable use of IPv6"),
3731 GNUNET_GETOPT_OPTION_END
3733 static const char* page =
3734 "<html><head><title>gnunet-gns-proxy</title>"
3735 "</head><body>cURL fail</body></html>";
3739 GNUNET_STRINGS_get_utf8_args (argc, argv,
3742 GNUNET_log_setup ("gnunet-gns-proxy",
3745 curl_failure_response
3746 = MHD_create_response_from_buffer (strlen (page),
3748 MHD_RESPMEM_PERSISTENT);
3752 GNUNET_PROGRAM_run (argc, argv,
3754 _("GNUnet GNS proxy"),
3756 &run, NULL)) ? 0 : 1;
3757 MHD_destroy_response (curl_failure_response);
3758 GNUNET_free_non_null ((char *) argv);
3762 /* end of gnunet-gns-proxy.c */