2 This file is part of GNUnet.
3 Copyright (C) 2012-2014 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @author Martin Schanzenbach
22 * @author Christian Grothoff
23 * @file src/gns/gnunet-gns-proxy.c
24 * @brief HTTP(S) proxy that rewrites URIs and fakes certificats to make GNS work
25 * with legacy browsers
28 * - double-check queueing logic
31 #include <microhttpd.h>
33 #include <curl/curl.h>
34 #elif HAVE_GNURL_CURL_H
35 #include <gnurl/curl.h>
37 #include <gnutls/gnutls.h>
38 #include <gnutls/x509.h>
39 #include <gnutls/abstract.h>
40 #include <gnutls/crypto.h>
42 #include <gnutls/dane.h>
45 #include "gnunet_util_lib.h"
46 #include "gnunet_gns_service.h"
47 #include "gnunet_identity_service.h"
52 * Default Socks5 listen port.
54 #define GNUNET_GNS_PROXY_PORT 7777
57 * Maximum supported length for a URI.
58 * Should die. @deprecated
60 #define MAX_HTTP_URI_LENGTH 2048
63 * Size of the buffer for the data upload / download. Must be
64 * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
66 #define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE
69 * Size of the read/write buffers for Socks. Uses
70 * 256 bytes for the hostname (at most), plus a few
71 * bytes overhead for the messages.
73 #define SOCKS_BUFFERSIZE (256 + 32)
76 * Port for plaintext HTTP.
83 #define HTTPS_PORT 443
86 * Largest allowed size for a PEM certificate.
88 #define MAX_PEM_SIZE (10 * 1024)
91 * After how long do we clean up unused MHD TLS instances?
93 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
96 * After how long do we clean up Socks5 handles that failed to show any activity
97 * with their respective MHD instance?
99 #define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
105 * @param level log level
106 * @param fun name of curl_easy-function that gave the error
107 * @param rc return code from curl
109 #define LOG_CURL_EASY(level,fun,rc) GNUNET_log(level, _("%s failed at %s:%d: `%s'\n"), fun, __FILE__, __LINE__, curl_easy_strerror (rc))
112 /* *************** Socks protocol definitions (move to TUN?) ****************** */
115 * Which SOCKS version do we speak?
117 #define SOCKS_VERSION_5 0x05
120 * Flag to set for 'no authentication'.
122 #define SOCKS_AUTH_NONE 0
126 * Commands in Socks5.
131 * Establish TCP/IP stream.
133 SOCKS5_CMD_TCP_STREAM = 1,
136 * Establish TCP port binding.
138 SOCKS5_CMD_TCP_PORT = 2,
141 * Establish UDP port binding.
143 SOCKS5_CMD_UDP_PORT = 3
148 * Address types in Socks5.
150 enum Socks5AddressType
160 SOCKS5_AT_DOMAINNAME = 3,
171 * Status codes in Socks5 response.
173 enum Socks5StatusCode
175 SOCKS5_STATUS_REQUEST_GRANTED = 0,
176 SOCKS5_STATUS_GENERAL_FAILURE = 1,
177 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
178 SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
179 SOCKS5_STATUS_HOST_UNREACHABLE = 4,
180 SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
181 SOCKS5_STATUS_TTL_EXPIRED = 6,
182 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
183 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
188 * Client hello in Socks5 protocol.
190 struct Socks5ClientHelloMessage
193 * Should be #SOCKS_VERSION_5.
198 * How many authentication methods does the client support.
200 uint8_t num_auth_methods;
202 /* followed by supported authentication methods, 1 byte per method */
208 * Server hello in Socks5 protocol.
210 struct Socks5ServerHelloMessage
213 * Should be #SOCKS_VERSION_5.
218 * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
219 * which skips the authentication step.
226 * Client socks request in Socks5 protocol.
228 struct Socks5ClientRequestMessage
231 * Should be #SOCKS_VERSION_5.
236 * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
241 * Reserved, always zero.
246 * Address type, an `enum Socks5AddressType`.
251 * Followed by either an ip4/ipv6 address or a domain name with a
252 * length field (uint8_t) in front (depending on @e addr_type).
253 * followed by port number in network byte order (uint16_t).
259 * Server response to client requests in Socks5 protocol.
261 struct Socks5ServerResponseMessage
264 * Should be #SOCKS_VERSION_5.
269 * Status code, an `enum Socks5StatusCode`
279 * Address type, an `enum Socks5AddressType`.
284 * Followed by either an ip4/ipv6 address or a domain name with a
285 * length field (uint8_t) in front (depending on @e addr_type).
286 * followed by port number in network byte order (uint16_t).
293 /* *********************** Datastructures for HTTP handling ****************** */
296 * A structure for CA cert/key
303 gnutls_x509_crt_t cert;
308 gnutls_x509_privkey_t key;
313 * Structure for GNS certificates
315 struct ProxyGNSCertificate
318 * The certificate as PEM
320 char cert[MAX_PEM_SIZE];
323 * The private key as PEM
325 char key[MAX_PEM_SIZE];
331 * A structure for all running Httpds
338 struct MhdHttpList *prev;
343 struct MhdHttpList *next;
346 * the domain name to server (only important for TLS)
353 struct MHD_Daemon *daemon;
356 * Optional proxy certificate used
358 struct ProxyGNSCertificate *proxy_cert;
363 struct GNUNET_SCHEDULER_Task *httpd_task;
366 * is this an ssl daemon?
373 /* ***************** Datastructures for Socks handling **************** */
382 * We're waiting to get the client hello.
387 * We're waiting to get the initial request.
392 * We are currently resolving the destination.
397 * We're in transfer mode.
399 SOCKS5_DATA_TRANSFER,
402 * Finish writing the write buffer, then clean up.
404 SOCKS5_WRITE_THEN_CLEANUP,
407 * Socket has been passed to MHD, do not close it anymore.
409 SOCKS5_SOCKET_WITH_MHD,
412 * We've started receiving upload data from MHD.
414 SOCKS5_SOCKET_UPLOAD_STARTED,
417 * We've finished receiving upload data from MHD.
419 SOCKS5_SOCKET_UPLOAD_DONE,
422 * We've finished uploading data via CURL and can now download.
424 SOCKS5_SOCKET_DOWNLOAD_STARTED,
427 * We've finished receiving download data from cURL.
429 SOCKS5_SOCKET_DOWNLOAD_DONE
436 struct HttpResponseHeader
441 struct HttpResponseHeader *next;
446 struct HttpResponseHeader *prev;
460 * A structure for socks requests
468 struct Socks5Request *next;
473 struct Socks5Request *prev;
478 struct GNUNET_NETWORK_Handle *sock;
481 * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
483 struct GNUNET_GNS_LookupWithTldRequest *gns_lookup;
486 * Client socket read task
488 struct GNUNET_SCHEDULER_Task *rtask;
491 * Client socket write task
493 struct GNUNET_SCHEDULER_Task *wtask;
498 struct GNUNET_SCHEDULER_Task *timeout_task;
503 char rbuf[SOCKS_BUFFERSIZE];
508 char wbuf[SOCKS_BUFFERSIZE];
511 * Buffer we use for moving data between MHD and curl (in both directions).
513 char io_buf[IO_BUFFERSIZE];
516 * MHD HTTP instance handling this request, NULL for none.
518 struct MhdHttpList *hd;
521 * MHD connection for this request.
523 struct MHD_Connection *con;
526 * MHD response object for this request.
528 struct MHD_Response *response;
531 * the domain name to server (only important for TLS)
536 * DNS Legacy Host Name as given by GNS, NULL if not given.
541 * Payload of the (last) DANE record encountered.
556 * HTTP request headers for the curl request.
558 struct curl_slist *headers;
561 * DNS->IP mappings resolved through GNS
563 struct curl_slist *hosts;
566 * HTTP response code to give to MHD for the response.
568 unsigned int response_code;
571 * Number of bytes in @e dane_data.
573 size_t dane_data_len;
576 * Number of bytes already in read buffer
581 * Number of bytes already in write buffer
586 * Number of bytes already in the IO buffer.
591 * Once known, what's the target address for the connection?
593 struct sockaddr_storage destination_address;
598 enum SocksPhase state;
601 * Desired destination port.
606 * Headers from response
608 struct HttpResponseHeader *header_head;
611 * Headers from response
613 struct HttpResponseHeader *header_tail;
616 * X.509 Certificate status
621 * Was the hostname resolved via GNS?
626 * Did we suspend MHD processing?
631 * Did we pause CURL processing?
638 /* *********************** Globals **************************** */
642 * The port the proxy is running on (default 7777)
644 static uint16_t port = GNUNET_GNS_PROXY_PORT;
647 * The CA file (pem) to use for the proxy CA
649 static char *cafile_opt;
652 * The listen socket of the proxy for IPv4
654 static struct GNUNET_NETWORK_Handle *lsock4;
657 * The listen socket of the proxy for IPv6
659 static struct GNUNET_NETWORK_Handle *lsock6;
662 * The listen task ID for IPv4
664 static struct GNUNET_SCHEDULER_Task * ltask4;
667 * The listen task ID for IPv6
669 static struct GNUNET_SCHEDULER_Task * ltask6;
672 * The cURL download task (curl multi API).
674 static struct GNUNET_SCHEDULER_Task * curl_download_task;
677 * The cURL multi handle
679 static CURLM *curl_multi;
682 * Handle to the GNS service
684 static struct GNUNET_GNS_Handle *gns_handle;
687 * DLL for http/https daemons
689 static struct MhdHttpList *mhd_httpd_head;
692 * DLL for http/https daemons
694 static struct MhdHttpList *mhd_httpd_tail;
697 * Daemon for HTTP (we have one per X.509 certificate, and then one for
698 * all HTTP connections; this is the one for HTTP, not HTTPS).
700 static struct MhdHttpList *httpd;
703 * DLL of active socks requests.
705 static struct Socks5Request *s5r_head;
708 * DLL of active socks requests.
710 static struct Socks5Request *s5r_tail;
713 * The CA for X.509 certificate generation
715 static struct ProxyCA proxy_ca;
718 * Response we return on cURL failures.
720 static struct MHD_Response *curl_failure_response;
725 static const struct GNUNET_CONFIGURATION_Handle *cfg;
728 /* ************************* Global helpers ********************* */
732 * Run MHD now, we have extra data ready for the callback.
734 * @param hd the daemon to run now.
737 run_mhd_now (struct MhdHttpList *hd);
741 * Clean up s5r handles.
743 * @param s5r the handle to destroy
746 cleanup_s5r (struct Socks5Request *s5r)
748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
749 "Cleaning up socks request\n");
750 if (NULL != s5r->curl)
752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
753 "Cleaning up cURL handle\n");
754 curl_multi_remove_handle (curl_multi,
756 curl_easy_cleanup (s5r->curl);
761 s5r->suspended = GNUNET_NO;
762 MHD_resume_connection (s5r->con);
764 curl_slist_free_all (s5r->headers);
765 if (NULL != s5r->hosts)
767 curl_slist_free_all (s5r->hosts);
769 if ( (NULL != s5r->response) &&
770 (curl_failure_response != s5r->response) )
771 MHD_destroy_response (s5r->response);
772 if (NULL != s5r->rtask)
773 GNUNET_SCHEDULER_cancel (s5r->rtask);
774 if (NULL != s5r->timeout_task)
775 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
776 if (NULL != s5r->wtask)
777 GNUNET_SCHEDULER_cancel (s5r->wtask);
778 if (NULL != s5r->gns_lookup)
779 GNUNET_GNS_lookup_with_tld_cancel (s5r->gns_lookup);
780 if (NULL != s5r->sock)
782 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
783 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
785 GNUNET_NETWORK_socket_close (s5r->sock);
787 GNUNET_CONTAINER_DLL_remove (s5r_head,
790 GNUNET_free_non_null (s5r->domain);
791 GNUNET_free_non_null (s5r->leho);
792 GNUNET_free_non_null (s5r->url);
793 GNUNET_free_non_null (s5r->dane_data);
798 /* ************************* HTTP handling with cURL *********************** */
801 curl_download_prepare ();
805 * Callback for MHD response generation. This function is called from
806 * MHD whenever MHD expects to get data back. Copies data from the
807 * io_buf, if available.
809 * @param cls closure with our `struct Socks5Request`
810 * @param pos in buffer
811 * @param buf where to copy data
812 * @param max available space in @a buf
813 * @return number of bytes written to @a buf
816 mhd_content_cb (void *cls,
821 struct Socks5Request *s5r = cls;
822 size_t bytes_to_copy;
824 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
825 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
827 /* we're still not done with the upload, do not yet
828 start the download, the IO buffer is still full
830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
831 "Pausing MHD download %s%s, not yet ready for download\n",
834 return 0; /* not yet ready for data download */
836 bytes_to_copy = GNUNET_MIN (max,
838 if ( (0 == bytes_to_copy) &&
839 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
841 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
842 "Pausing MHD download %s%s, no data available\n",
845 if (NULL != s5r->curl)
847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
848 "Continuing CURL interaction for %s%s\n",
851 if (GNUNET_YES == s5r->curl_paused)
853 s5r->curl_paused = GNUNET_NO;
854 curl_easy_pause (s5r->curl,
857 curl_download_prepare ();
859 if (GNUNET_NO == s5r->suspended)
861 MHD_suspend_connection (s5r->con);
862 s5r->suspended = GNUNET_YES;
864 return 0; /* more data later */
866 if ( (0 == bytes_to_copy) &&
867 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
870 "Completed MHD download %s%s\n",
873 return MHD_CONTENT_READER_END_OF_STREAM;
875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
876 "Writing %llu/%llu bytes for %s%s\n",
877 (unsigned long long) bytes_to_copy,
878 (unsigned long long) s5r->io_len,
884 memmove (s5r->io_buf,
885 &s5r->io_buf[bytes_to_copy],
886 s5r->io_len - bytes_to_copy);
887 s5r->io_len -= bytes_to_copy;
888 if ( (NULL != s5r->curl) &&
889 (GNUNET_YES == s5r->curl_paused) )
891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
892 "Continuing CURL interaction for %s%s\n",
895 s5r->curl_paused = GNUNET_NO;
896 curl_easy_pause (s5r->curl,
899 return bytes_to_copy;
904 * Check that the website has presented us with a valid X.509 certificate.
905 * The certificate must either match the domain name or the LEHO name
906 * (or, if available, the TLSA record).
908 * @param s5r request to check for.
909 * @return #GNUNET_OK if the certificate is valid
912 check_ssl_certificate (struct Socks5Request *s5r)
914 unsigned int cert_list_size;
915 const gnutls_datum_t *chainp;
916 const struct curl_tlssessioninfo *tlsinfo;
917 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
919 gnutls_x509_crt_t x509_cert;
923 s5r->ssl_checked = GNUNET_YES;
924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
925 "Checking X.509 certificate\n");
927 curl_easy_getinfo (s5r->curl,
928 CURLINFO_TLS_SESSION,
929 (struct curl_slist **) &tlsinfo))
930 return GNUNET_SYSERR;
931 if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
933 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
934 _("Unsupported CURL TLS backend %d\n"),
936 return GNUNET_SYSERR;
938 chainp = gnutls_certificate_get_peers (tlsinfo->internals, &cert_list_size);
939 if ( (! chainp) || (0 == cert_list_size) )
940 return GNUNET_SYSERR;
942 size = sizeof (certdn);
943 /* initialize an X.509 certificate structure. */
944 gnutls_x509_crt_init (&x509_cert);
945 gnutls_x509_crt_import (x509_cert,
947 GNUTLS_X509_FMT_DER);
949 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
950 GNUTLS_OID_X520_COMMON_NAME,
951 0, /* the first and only one */
952 0 /* no DER encoding */,
956 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
957 _("Failed to fetch CN from cert: %s\n"),
958 gnutls_strerror(rc));
959 gnutls_x509_crt_deinit (x509_cert);
960 return GNUNET_SYSERR;
962 /* check for TLSA/DANE records */
964 if (NULL != s5r->dane_data)
966 char *dd[] = { s5r->dane_data, NULL };
967 int dlen[] = { s5r->dane_data_len, 0};
968 dane_state_t dane_state;
969 dane_query_t dane_query;
972 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
973 if (0 != (rc = dane_state_init (&dane_state,
974 #ifdef DANE_F_IGNORE_DNSSEC
975 DANE_F_IGNORE_DNSSEC |
977 DANE_F_IGNORE_LOCAL_RESOLVER)))
979 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
980 _("Failed to initialize DANE: %s\n"),
982 gnutls_x509_crt_deinit (x509_cert);
983 return GNUNET_SYSERR;
985 if (0 != (rc = dane_raw_tlsa (dane_state,
992 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
993 _("Failed to parse DANE record: %s\n"),
995 dane_state_deinit (dane_state);
996 gnutls_x509_crt_deinit (x509_cert);
997 return GNUNET_SYSERR;
999 if (0 != (rc = dane_verify_crt_raw (dane_state,
1002 gnutls_certificate_type_get (tlsinfo->internals),
1007 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1008 _("Failed to verify TLS connection using DANE: %s\n"),
1010 dane_query_deinit (dane_query);
1011 dane_state_deinit (dane_state);
1012 gnutls_x509_crt_deinit (x509_cert);
1013 return GNUNET_SYSERR;
1017 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1018 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
1020 dane_query_deinit (dane_query);
1021 dane_state_deinit (dane_state);
1022 gnutls_x509_crt_deinit (x509_cert);
1023 return GNUNET_SYSERR;
1025 dane_query_deinit (dane_query);
1026 dane_state_deinit (dane_state);
1032 /* try LEHO or ordinary domain name X509 verification */
1034 if (NULL != s5r->leho)
1038 if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
1041 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1042 _("TLS certificate subject name (%s) does not match `%s'\n"),
1045 gnutls_x509_crt_deinit (x509_cert);
1046 return GNUNET_SYSERR;
1051 /* we did not even have the domain name!? */
1053 return GNUNET_SYSERR;
1056 gnutls_x509_crt_deinit (x509_cert);
1062 * We're getting an HTTP response header from cURL. Convert it to the
1063 * MHD response headers. Mostly copies the headers, but makes special
1064 * adjustments to "Set-Cookie" and "Location" headers as those may need
1065 * to be changed from the LEHO to the domain the browser expects.
1067 * @param buffer curl buffer with a single line of header data; not 0-terminated!
1068 * @param size curl blocksize
1069 * @param nmemb curl blocknumber
1070 * @param cls our `struct Socks5Request *`
1071 * @return size of processed bytes
1074 curl_check_hdr (void *buffer,
1079 struct Socks5Request *s5r = cls;
1080 struct HttpResponseHeader *header;
1081 size_t bytes = size * nmemb;
1083 const char *hdr_type;
1084 const char *cookie_domain;
1086 char *new_cookie_hdr;
1089 size_t delta_cdomain;
1093 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1094 "Receiving HTTP response header from CURL\n");
1095 /* first, check TLS certificate */
1096 if ( (GNUNET_YES != s5r->ssl_checked) &&
1097 (HTTPS_PORT == s5r->port))
1099 if (GNUNET_OK != check_ssl_certificate (s5r))
1103 ndup = GNUNET_strndup (buffer, bytes);
1104 hdr_type = strtok (ndup, ":");
1105 if (NULL == hdr_type)
1110 hdr_val = strtok (NULL, "");
1111 if (NULL == hdr_val)
1116 if (' ' == *hdr_val)
1119 /* custom logic for certain header types */
1120 new_cookie_hdr = NULL;
1121 if ( (NULL != s5r->leho) &&
1122 (0 == strcasecmp (hdr_type,
1123 MHD_HTTP_HEADER_SET_COOKIE)) )
1126 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1127 strlen (s5r->domain) + 1);
1129 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1130 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1132 if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
1133 (GNUNET_NO == domain_matched) )
1135 domain_matched = GNUNET_YES;
1136 cookie_domain = tok + strlen (" domain") + 1;
1137 if (strlen (cookie_domain) < strlen (s5r->leho))
1139 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1140 if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
1142 offset += sprintf (new_cookie_hdr + offset,
1148 else if (0 == strcmp (cookie_domain, s5r->leho))
1150 offset += sprintf (new_cookie_hdr + offset,
1155 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1156 _("Cookie domain `%s' supplied by server is invalid\n"),
1159 GNUNET_memcpy (new_cookie_hdr + offset, tok, strlen (tok));
1160 offset += strlen (tok);
1161 new_cookie_hdr[offset++] = ';';
1163 hdr_val = new_cookie_hdr;
1166 new_location = NULL;
1167 if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
1171 GNUNET_asprintf (&leho_host,
1172 (HTTPS_PORT != s5r->port)
1176 if (0 == strncmp (leho_host,
1178 strlen (leho_host)))
1180 GNUNET_asprintf (&new_location,
1182 (HTTPS_PORT != s5r->port)
1186 hdr_val + strlen (leho_host));
1187 hdr_val = new_location;
1189 GNUNET_free (leho_host);
1191 /* MHD does not allow certain characters in values, remove those */
1192 if (NULL != (tok = strchr (hdr_val, '\n')))
1194 if (NULL != (tok = strchr (hdr_val, '\r')))
1196 if (NULL != (tok = strchr (hdr_val, '\t')))
1198 if (0 != strlen (hdr_val)) /* Rely in MHD to set those */
1200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1201 "Adding header %s: %s to MHD response\n",
1204 header = GNUNET_new (struct HttpResponseHeader);
1205 header->type = GNUNET_strdup (hdr_type);
1206 header->value = GNUNET_strdup (hdr_val);
1207 GNUNET_CONTAINER_DLL_insert (s5r->header_head,
1212 GNUNET_free_non_null (new_cookie_hdr);
1213 GNUNET_free_non_null (new_location);
1219 * Create an MHD response object in @a s5r matching the
1220 * information we got from curl.
1222 * @param s5r the request for which we convert the response
1223 * @return #GNUNET_OK on success, #GNUNET_SYSERR if response was
1224 * already initialized before
1227 create_mhd_response_from_s5r (struct Socks5Request *s5r)
1230 double content_length;
1232 if (NULL != s5r->response)
1234 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1235 "Response already set!\n");
1236 return GNUNET_SYSERR;
1239 GNUNET_break (CURLE_OK ==
1240 curl_easy_getinfo (s5r->curl,
1241 CURLINFO_RESPONSE_CODE,
1243 GNUNET_break (CURLE_OK ==
1244 curl_easy_getinfo (s5r->curl,
1245 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
1247 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1248 "Creating MHD response with code %d and size %d for %s%s\n",
1250 (int) content_length,
1253 s5r->response_code = resp_code;
1254 s5r->response = MHD_create_response_from_callback ((-1 == content_length) ? MHD_SIZE_UNKNOWN : content_length,
1259 for (struct HttpResponseHeader *header = s5r->header_head;
1261 header = header->next)
1263 GNUNET_break (MHD_YES ==
1264 MHD_add_response_header (s5r->response,
1269 if (NULL != s5r->leho)
1273 GNUNET_asprintf (&cors_hdr,
1274 (HTTPS_PORT == s5r->port)
1279 GNUNET_break (MHD_YES ==
1280 MHD_add_response_header (s5r->response,
1281 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1283 GNUNET_free (cors_hdr);
1285 /* force connection to be closed after each request, as we
1286 do not support HTTP pipelining (yet, FIXME!) */
1287 /*GNUNET_break (MHD_YES ==
1288 MHD_add_response_header (s5r->response,
1289 MHD_HTTP_HEADER_CONNECTION,
1291 MHD_resume_connection (s5r->con);
1292 s5r->suspended = GNUNET_NO;
1298 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1299 * it available to MHD.
1301 * @param ptr pointer to the data
1302 * @param size number of blocks of data
1303 * @param nmemb blocksize
1304 * @param ctx our `struct Socks5Request *`
1305 * @return number of bytes handled
1308 curl_download_cb (void *ptr,
1313 struct Socks5Request *s5r = ctx;
1314 size_t total = size * nmemb;
1316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1317 "Receiving %ux%u bytes for `%s%s' from cURL\n",
1318 (unsigned int) size,
1319 (unsigned int) nmemb,
1322 if (NULL == s5r->response)
1323 GNUNET_assert (GNUNET_OK ==
1324 create_mhd_response_from_s5r (s5r));
1326 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1327 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1329 /* we're still not done with the upload, do not yet
1330 start the download, the IO buffer is still full
1331 with upload data. */
1332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1333 "Pausing CURL download `%s%s', waiting for UPLOAD to finish\n",
1336 s5r->curl_paused = GNUNET_YES;
1337 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1339 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1342 "Pausing CURL `%s%s' download, not enough space %llu %llu %llu\n",
1345 (unsigned long long) sizeof (s5r->io_buf),
1346 (unsigned long long) s5r->io_len,
1347 (unsigned long long) total);
1348 s5r->curl_paused = GNUNET_YES;
1349 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1351 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1354 s5r->io_len += total;
1355 if (GNUNET_YES == s5r->suspended)
1357 MHD_resume_connection (s5r->con);
1358 s5r->suspended = GNUNET_NO;
1360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1361 "Received %llu bytes of payload via cURL from %s\n",
1362 (unsigned long long) total,
1364 if (s5r->io_len == total)
1365 run_mhd_now (s5r->hd);
1371 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1372 * to make it available to MHD.
1374 * @param buf where to write the data
1375 * @param size number of bytes per member
1376 * @param nmemb number of members available in @a buf
1377 * @param cls our `struct Socks5Request` that generated the data
1378 * @return number of bytes copied to @a buf
1381 curl_upload_cb (void *buf,
1386 struct Socks5Request *s5r = cls;
1387 size_t len = size * nmemb;
1390 if ( (0 == s5r->io_len) &&
1391 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1394 "Pausing CURL UPLOAD %s%s, need more data\n",
1397 return CURL_READFUNC_PAUSE;
1399 if ( (0 == s5r->io_len) &&
1400 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1402 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1404 "Completed CURL UPLOAD %s%s\n",
1407 return 0; /* upload finished, can now download */
1409 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
1410 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1413 return CURL_READFUNC_ABORT;
1415 to_copy = GNUNET_MIN (s5r->io_len,
1420 memmove (s5r->io_buf,
1421 &s5r->io_buf[to_copy],
1422 s5r->io_len - to_copy);
1423 s5r->io_len -= to_copy;
1424 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1425 run_mhd_now (s5r->hd); /* got more space for upload now */
1430 /* ************************** main loop of cURL interaction ****************** */
1434 * Task that is run when we are ready to receive more data
1437 * @param cls closure
1440 curl_task_download (void *cls);
1444 * Ask cURL for the select() sets and schedule cURL operations.
1447 curl_download_prepare ()
1454 struct GNUNET_NETWORK_FDSet *grs;
1455 struct GNUNET_NETWORK_FDSet *gws;
1457 struct GNUNET_TIME_Relative rtime;
1459 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1460 "Scheduling CURL interaction\n");
1461 if (NULL != curl_download_task)
1463 GNUNET_SCHEDULER_cancel (curl_download_task);
1464 curl_download_task = NULL;
1470 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi,
1476 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1477 "%s failed at %s:%d: `%s'\n",
1478 "curl_multi_fdset", __FILE__, __LINE__,
1479 curl_multi_strerror (mret));
1483 GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
1485 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1487 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1490 grs = GNUNET_NETWORK_fdset_create ();
1491 gws = GNUNET_NETWORK_fdset_create ();
1492 GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1493 GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1494 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1497 &curl_task_download,
1499 GNUNET_NETWORK_fdset_destroy (gws);
1500 GNUNET_NETWORK_fdset_destroy (grs);
1504 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1505 &curl_task_download,
1512 * Task that is run when we are ready to receive more data from curl.
1514 * @param cls closure, NULL
1517 curl_task_download (void *cls)
1521 struct CURLMsg *msg;
1523 struct Socks5Request *s5r;
1525 curl_download_task = NULL;
1526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1527 "Running CURL interaction\n");
1531 mret = curl_multi_perform (curl_multi,
1533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1534 "Checking CURL multi status: %d\n",
1536 while (NULL != (msg = curl_multi_info_read (curl_multi,
1539 GNUNET_break (CURLE_OK ==
1540 curl_easy_getinfo (msg->easy_handle,
1551 /* documentation says this is not used */
1555 switch (msg->data.result)
1558 case CURLE_GOT_NOTHING:
1559 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1560 "CURL download %s%s completed.\n",
1563 if (NULL == s5r->response)
1565 GNUNET_assert (GNUNET_OK ==
1566 create_mhd_response_from_s5r (s5r));
1568 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1569 if (GNUNET_YES == s5r->suspended)
1571 MHD_resume_connection (s5r->con);
1572 s5r->suspended = GNUNET_NO;
1574 run_mhd_now (s5r->hd);
1577 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1578 "Download curl %s%s failed: %s\n",
1581 curl_easy_strerror (msg->data.result));
1582 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1583 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1584 if (GNUNET_YES == s5r->suspended)
1586 MHD_resume_connection (s5r->con);
1587 s5r->suspended = GNUNET_NO;
1589 run_mhd_now (s5r->hd);
1592 if (NULL == s5r->response)
1593 s5r->response = curl_failure_response;
1596 /* documentation says this is not used */
1600 /* unexpected status code */
1605 } while (mret == CURLM_CALL_MULTI_PERFORM);
1606 if (CURLM_OK != mret)
1607 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1608 "%s failed at %s:%d: `%s'\n",
1609 "curl_multi_perform", __FILE__, __LINE__,
1610 curl_multi_strerror (mret));
1613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1614 "Suspending cURL multi loop, no more events pending\n");
1615 if (NULL != curl_download_task)
1617 GNUNET_SCHEDULER_cancel (curl_download_task);
1618 curl_download_task = NULL;
1620 return; /* nothing more in progress */
1622 curl_download_prepare ();
1626 /* ********************************* MHD response generation ******************* */
1630 * Read HTTP request header field from the request. Copies the fields
1631 * over to the 'headers' that will be given to curl. However, 'Host'
1632 * is substituted with the LEHO if present. We also change the
1633 * 'Connection' header value to "close" as the proxy does not support
1636 * @param cls our `struct Socks5Request`
1637 * @param kind value kind
1638 * @param key field key
1639 * @param value field value
1640 * @return #MHD_YES to continue to iterate
1643 con_val_iter (void *cls,
1644 enum MHD_ValueKind kind,
1648 struct Socks5Request *s5r = cls;
1651 if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1652 (NULL != s5r->leho) )
1654 if (0 == strcasecmp (MHD_HTTP_HEADER_CONTENT_LENGTH, key))
1656 if (0 == strcasecmp (MHD_HTTP_HEADER_ACCEPT_ENCODING, key))
1658 GNUNET_asprintf (&hdr,
1662 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1663 "Adding HEADER `%s' to HTTP request\n",
1665 s5r->headers = curl_slist_append (s5r->headers,
1673 * Main MHD callback for handling requests.
1676 * @param con MHD connection handle
1677 * @param url the url in the request
1678 * @param meth the HTTP method used ("GET", "PUT", etc.)
1679 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1680 * @param upload_data the data being uploaded (excluding HEADERS,
1681 * for a POST that fits into memory and that is encoded
1682 * with a supported encoding, the POST data will NOT be
1683 * given in upload_data and is instead available as
1684 * part of MHD_get_connection_values; very large POST
1685 * data *will* be made available incrementally in
1687 * @param upload_data_size set initially to the size of the
1688 * @a upload_data provided; the method must update this
1689 * value to the number of bytes NOT processed;
1690 * @param con_cls pointer to location where we store the `struct Request`
1691 * @return #MHD_YES if the connection was handled successfully,
1692 * #MHD_NO if the socket must be closed due to a serious
1693 * error while handling the request
1696 create_response (void *cls,
1697 struct MHD_Connection *con,
1701 const char *upload_data,
1702 size_t *upload_data_size,
1705 struct Socks5Request *s5r = *con_cls;
1707 char ipstring[INET6_ADDRSTRLEN];
1708 char ipaddr[INET6_ADDRSTRLEN + 2];
1709 const struct sockaddr *sa;
1710 const struct sockaddr_in *s4;
1711 const struct sockaddr_in6 *s6;
1722 if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
1724 /* first time here, initialize curl handle */
1727 sa = (const struct sockaddr *) &s5r->destination_address;
1728 switch (sa->sa_family)
1731 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1732 if (NULL == inet_ntop (AF_INET,
1740 GNUNET_snprintf (ipaddr,
1744 port = ntohs (s4->sin_port);
1747 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1748 if (NULL == inet_ntop (AF_INET6,
1756 GNUNET_snprintf (ipaddr,
1760 port = ntohs (s6->sin6_port);
1771 if (NULL == s5r->curl)
1772 s5r->curl = curl_easy_init ();
1773 if (NULL == s5r->curl)
1774 return MHD_queue_response (con,
1775 MHD_HTTP_INTERNAL_SERVER_ERROR,
1776 curl_failure_response);
1777 curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1778 curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1779 curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1781 curl_easy_setopt (s5r->curl,
1784 curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1785 curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1786 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1787 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1788 // curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1789 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1790 curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1791 curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0L);
1793 * Pre-populate cache to resolve Hostname.
1794 * This is necessary as the DNS name in the CURLOPT_URL is used
1795 * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1797 if (NULL != s5r->leho)
1801 GNUNET_asprintf (&curl_hosts,
1806 s5r->hosts = curl_slist_append (NULL,
1808 curl_easy_setopt (s5r->curl,
1811 GNUNET_free (curl_hosts);
1815 GNUNET_asprintf (&curlurl,
1816 (HTTPS_PORT != s5r->port)
1818 : "https://%s:%d%s",
1827 GNUNET_asprintf (&curlurl,
1828 (HTTPS_PORT != s5r->port)
1830 : "https://%s:%d%s",
1835 curl_easy_setopt (s5r->curl,
1838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1839 "Launching %s CURL interaction, fetching `%s'\n",
1840 (s5r->is_gns) ? "GNS" : "DNS",
1842 GNUNET_free (curlurl);
1843 if (0 == strcasecmp (meth,
1844 MHD_HTTP_METHOD_PUT))
1846 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1847 curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1L);
1848 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1849 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1850 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1851 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1856 us = MHD_lookup_connection_value (con,
1858 MHD_HTTP_HEADER_CONTENT_LENGTH);
1859 if ( (1 == sscanf (us,
1862 (upload_size >= 0) )
1864 curl_easy_setopt (s5r->curl,
1870 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1872 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1873 curl_easy_setopt (s5r->curl, CURLOPT_POST, 1L);
1874 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1875 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1876 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1877 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1882 us = MHD_lookup_connection_value (con,
1884 MHD_HTTP_HEADER_CONTENT_LENGTH);
1885 if ( (1 == sscanf (us,
1888 (upload_size >= 0) )
1890 curl_easy_setopt (s5r->curl,
1896 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1898 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1899 curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1L);
1901 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_OPTIONS))
1903 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1904 curl_easy_setopt (s5r->curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
1906 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1908 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1909 curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1L);
1910 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1911 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1915 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1916 _("Unsupported HTTP method `%s'\n"),
1918 curl_easy_cleanup (s5r->curl);
1923 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1925 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1927 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1929 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1933 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1936 if (HTTPS_PORT == s5r->port)
1938 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1939 if (NULL != s5r->dane_data)
1940 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 0L);
1942 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1943 /* Disable cURL checking the hostname, as we will check ourselves
1944 as only we have the domain name or the LEHO or the DANE record */
1945 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
1949 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
1953 curl_multi_add_handle (curl_multi,
1957 curl_easy_cleanup (s5r->curl);
1961 MHD_get_connection_values (con,
1965 curl_easy_setopt (s5r->curl,
1968 curl_download_prepare ();
1972 /* continuing to process request */
1973 if (0 != *upload_data_size)
1975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1976 "Processing %u bytes UPLOAD\n",
1977 (unsigned int) *upload_data_size);
1979 /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else
1980 * upload callback is not called!
1982 curl_easy_setopt (s5r->curl, CURLOPT_POSTFIELDSIZE, *upload_data_size);
1984 left = GNUNET_MIN (*upload_data_size,
1985 sizeof (s5r->io_buf) - s5r->io_len);
1986 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1989 s5r->io_len += left;
1990 *upload_data_size -= left;
1991 GNUNET_assert (NULL != s5r->curl);
1992 if (GNUNET_YES == s5r->curl_paused)
1994 s5r->curl_paused = GNUNET_NO;
1995 curl_easy_pause (s5r->curl,
2000 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
2002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2003 "Finished processing UPLOAD\n");
2004 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
2006 if (NULL == s5r->response)
2008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2009 "Waiting for HTTP response for %s%s...\n",
2012 MHD_suspend_connection (con);
2013 s5r->suspended = GNUNET_YES;
2016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2017 "Queueing response for %s%s with MHD\n",
2020 run_mhd_now (s5r->hd);
2021 return MHD_queue_response (con,
2027 /* ******************** MHD HTTP setup and event loop ******************** */
2031 * Function called when MHD decides that we are done with a request.
2034 * @param connection connection handle
2035 * @param con_cls value as set by the last call to
2036 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2037 * @param toe reason for request termination (ignored)
2040 mhd_completed_cb (void *cls,
2041 struct MHD_Connection *connection,
2043 enum MHD_RequestTerminationCode toe)
2045 struct Socks5Request *s5r = *con_cls;
2049 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
2050 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2051 "MHD encountered error handling request: %d\n",
2053 if (NULL != s5r->curl)
2055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2056 "Removing cURL handle (MHD interaction complete)\n");
2057 curl_multi_remove_handle (curl_multi,
2059 curl_slist_free_all (s5r->headers);
2060 s5r->headers = NULL;
2061 curl_easy_reset (s5r->curl);
2065 curl_download_prepare ();
2067 if ( (NULL != s5r->response) &&
2068 (curl_failure_response != s5r->response) )
2069 MHD_destroy_response (s5r->response);
2070 for (struct HttpResponseHeader *header = s5r->header_head;
2072 header = s5r->header_head)
2074 GNUNET_CONTAINER_DLL_remove (s5r->header_head,
2077 GNUNET_free (header->type);
2078 GNUNET_free (header->value);
2079 GNUNET_free (header);
2081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2082 "Finished request for %s\n",
2084 GNUNET_free (s5r->url);
2085 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2087 s5r->response = NULL;
2093 * Function called when MHD connection is opened or closed.
2096 * @param connection connection handle
2097 * @param con_cls value as set by the last call to
2098 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
2099 * @param toe connection notification type
2102 mhd_connection_cb (void *cls,
2103 struct MHD_Connection *connection,
2105 enum MHD_ConnectionNotificationCode cnc)
2107 struct Socks5Request *s5r;
2108 const union MHD_ConnectionInfo *ci;
2113 case MHD_CONNECTION_NOTIFY_STARTED:
2114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
2115 ci = MHD_get_connection_info (connection,
2116 MHD_CONNECTION_INFO_CONNECTION_FD);
2122 sock = ci->connect_fd;
2123 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
2125 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
2127 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2128 "Context set...\n");
2129 s5r->ssl_checked = GNUNET_NO;
2135 case MHD_CONNECTION_NOTIFY_CLOSED:
2136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2137 "Connection closed... cleaning up\n");
2141 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2142 "Connection stale!\n");
2146 curl_download_prepare ();
2155 * Function called when MHD first processes an incoming connection.
2156 * Gives us the respective URI information.
2158 * We use this to associate the `struct MHD_Connection` with our
2159 * internal `struct Socks5Request` data structure (by checking
2160 * for matching sockets).
2162 * @param cls the HTTP server handle (a `struct MhdHttpList`)
2163 * @param url the URL that is being requested
2164 * @param connection MHD connection object for the request
2165 * @return the `struct Socks5Request` that this @a connection is for
2168 mhd_log_callback (void *cls,
2170 struct MHD_Connection *connection)
2172 struct Socks5Request *s5r;
2173 const union MHD_ConnectionInfo *ci;
2175 ci = MHD_get_connection_info (connection,
2176 MHD_CONNECTION_INFO_SOCKET_CONTEXT);
2177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
2183 s5r = ci->socket_context;
2184 if (NULL != s5r->url)
2189 s5r->url = GNUNET_strdup (url);
2190 if (NULL != s5r->timeout_task)
2192 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
2193 s5r->timeout_task = NULL;
2195 GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD);
2201 * Kill the given MHD daemon.
2203 * @param hd daemon to stop
2206 kill_httpd (struct MhdHttpList *hd)
2208 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
2211 GNUNET_free_non_null (hd->domain);
2212 MHD_stop_daemon (hd->daemon);
2213 if (NULL != hd->httpd_task)
2215 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2216 hd->httpd_task = NULL;
2218 GNUNET_free_non_null (hd->proxy_cert);
2226 * Task run whenever HTTP server is idle for too long. Kill it.
2228 * @param cls the `struct MhdHttpList *`
2231 kill_httpd_task (void *cls)
2233 struct MhdHttpList *hd = cls;
2235 hd->httpd_task = NULL;
2241 * Task run whenever HTTP server operations are pending.
2243 * @param cls the `struct MhdHttpList *` of the daemon that is being run
2246 do_httpd (void *cls);
2250 * Schedule MHD. This function should be called initially when an
2251 * MHD is first getting its client socket, and will then automatically
2252 * always be called later whenever there is work to be done.
2254 * @param hd the daemon to schedule
2257 schedule_httpd (struct MhdHttpList *hd)
2262 struct GNUNET_NETWORK_FDSet *wrs;
2263 struct GNUNET_NETWORK_FDSet *wws;
2266 MHD_UNSIGNED_LONG_LONG timeout;
2267 struct GNUNET_TIME_Relative tv;
2274 MHD_get_fdset (hd->daemon,
2283 haveto = MHD_get_timeout (hd->daemon,
2285 if (MHD_YES == haveto)
2286 tv.rel_value_us = (uint64_t) timeout * 1000LL;
2288 tv = GNUNET_TIME_UNIT_FOREVER_REL;
2291 wrs = GNUNET_NETWORK_fdset_create ();
2292 wws = GNUNET_NETWORK_fdset_create ();
2293 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
2294 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
2301 if (NULL != hd->httpd_task)
2303 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2304 hd->httpd_task = NULL;
2306 if ( (MHD_YES != haveto) &&
2310 /* daemon is idle, kill after timeout */
2311 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
2318 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2323 GNUNET_NETWORK_fdset_destroy (wrs);
2325 GNUNET_NETWORK_fdset_destroy (wws);
2330 * Task run whenever HTTP server operations are pending.
2332 * @param cls the `struct MhdHttpList` of the daemon that is being run
2335 do_httpd (void *cls)
2337 struct MhdHttpList *hd = cls;
2339 hd->httpd_task = NULL;
2340 MHD_run (hd->daemon);
2341 schedule_httpd (hd);
2346 * Run MHD now, we have extra data ready for the callback.
2348 * @param hd the daemon to run now.
2351 run_mhd_now (struct MhdHttpList *hd)
2353 if (NULL != hd->httpd_task)
2354 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2355 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
2361 * Read file in filename
2363 * @param filename file to read
2364 * @param size pointer where filesize is stored
2365 * @return NULL on error
2368 load_file (const char* filename,
2375 GNUNET_DISK_file_size (filename, &fsize,
2376 GNUNET_YES, GNUNET_YES))
2378 if (fsize > MAX_PEM_SIZE)
2380 *size = (unsigned int) fsize;
2381 buffer = GNUNET_malloc (*size);
2383 GNUNET_DISK_fn_read (filename,
2387 GNUNET_free (buffer);
2395 * Load PEM key from file
2397 * @param key where to store the data
2398 * @param keyfile path to the PEM file
2399 * @return #GNUNET_OK on success
2402 load_key_from_file (gnutls_x509_privkey_t key,
2403 const char* keyfile)
2405 gnutls_datum_t key_data;
2408 key_data.data = load_file (keyfile, &key_data.size);
2409 if (NULL == key_data.data)
2410 return GNUNET_SYSERR;
2411 ret = gnutls_x509_privkey_import (key, &key_data,
2412 GNUTLS_X509_FMT_PEM);
2413 if (GNUTLS_E_SUCCESS != ret)
2415 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2416 _("Unable to import private key from file `%s'\n"),
2419 GNUNET_free_non_null (key_data.data);
2420 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2425 * Load cert from file
2427 * @param crt struct to store data in
2428 * @param certfile path to pem file
2429 * @return #GNUNET_OK on success
2432 load_cert_from_file (gnutls_x509_crt_t crt,
2433 const char* certfile)
2435 gnutls_datum_t cert_data;
2438 cert_data.data = load_file (certfile, &cert_data.size);
2439 if (NULL == cert_data.data)
2440 return GNUNET_SYSERR;
2441 ret = gnutls_x509_crt_import (crt, &cert_data,
2442 GNUTLS_X509_FMT_PEM);
2443 if (GNUTLS_E_SUCCESS != ret)
2445 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2446 _("Unable to import certificate %s\n"), certfile);
2448 GNUNET_free_non_null (cert_data.data);
2449 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2454 * Generate new certificate for specific name
2456 * @param name the subject name to generate a cert for
2457 * @return a struct holding the PEM data, NULL on error
2459 static struct ProxyGNSCertificate *
2460 generate_gns_certificate (const char *name)
2462 unsigned int serial;
2463 size_t key_buf_size;
2464 size_t cert_buf_size;
2465 gnutls_x509_crt_t request;
2468 struct ProxyGNSCertificate *pgc;
2470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2471 "Generating x.509 certificate for `%s'\n",
2473 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2474 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2475 pgc = GNUNET_new (struct ProxyGNSCertificate);
2476 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2478 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2479 0, "GNU Name System", 4);
2480 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2481 0, name, strlen (name));
2482 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
2483 gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2484 gnutls_x509_crt_set_serial (request,
2487 etime = time (NULL);
2488 tm_data = localtime (&etime);
2490 etime = mktime(tm_data);
2491 gnutls_x509_crt_set_activation_time (request,
2494 etime = mktime (tm_data);
2495 gnutls_x509_crt_set_expiration_time (request,
2497 gnutls_x509_crt_sign2 (request,
2502 key_buf_size = sizeof (pgc->key);
2503 cert_buf_size = sizeof (pgc->cert);
2504 gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2505 pgc->cert, &cert_buf_size);
2506 gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2507 pgc->key, &key_buf_size);
2508 gnutls_x509_crt_deinit (request);
2514 * Function called by MHD with errors, suppresses them all.
2516 * @param cls closure
2517 * @param fm format string (`printf()`-style)
2518 * @param ap arguments to @a fm
2521 mhd_error_log_callback (void *cls,
2530 * Lookup (or create) an TLS MHD instance for a particular domain.
2532 * @param domain the domain the TLS daemon has to serve
2533 * @return NULL on error
2535 static struct MhdHttpList *
2536 lookup_ssl_httpd (const char* domain)
2538 struct MhdHttpList *hd;
2539 struct ProxyGNSCertificate *pgc;
2546 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2547 if ( (NULL != hd->domain) &&
2548 (0 == strcmp (hd->domain, domain)) )
2550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2551 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2553 pgc = generate_gns_certificate (domain);
2554 hd = GNUNET_new (struct MhdHttpList);
2555 hd->is_ssl = GNUNET_YES;
2556 hd->domain = GNUNET_strdup (domain);
2557 hd->proxy_cert = pgc;
2558 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
2561 &create_response, hd,
2562 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2563 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2564 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
2565 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2566 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2567 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2568 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2570 if (NULL == hd->daemon)
2576 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2584 * Task run when a Socks5Request somehow fails to be associated with
2585 * an MHD connection (i.e. because the client never speaks HTTP after
2586 * the SOCKS5 handshake). Clean up.
2588 * @param cls the `struct Socks5Request *`
2591 timeout_s5r_handshake (void *cls)
2593 struct Socks5Request *s5r = cls;
2595 s5r->timeout_task = NULL;
2601 * We're done with the Socks5 protocol, now we need to pass the
2602 * connection data through to the final destination, either
2603 * direct (if the protocol might not be HTTP), or via MHD
2604 * (if the port looks like it should be HTTP).
2606 * @param s5r socks request that has reached the final stage
2609 setup_data_transfer (struct Socks5Request *s5r)
2611 struct MhdHttpList *hd;
2613 const struct sockaddr *addr;
2620 GNUNET_asprintf (&domain,
2623 hd = lookup_ssl_httpd (domain);
2626 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2627 _("Failed to start HTTPS server for `%s'\n"),
2630 GNUNET_free (domain);
2637 GNUNET_assert (NULL != httpd);
2641 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2642 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2643 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2644 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2646 MHD_add_connection (hd->daemon,
2651 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2652 _("Failed to pass client to MHD\n"));
2654 GNUNET_free_non_null (domain);
2658 schedule_httpd (hd);
2659 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2660 &timeout_s5r_handshake,
2662 GNUNET_free_non_null (domain);
2666 /* ********************* SOCKS handling ************************* */
2670 * Write data from buffer to socks5 client, then continue with state machine.
2672 * @param cls the closure with the `struct Socks5Request`
2675 do_write (void *cls)
2677 struct Socks5Request *s5r = cls;
2681 len = GNUNET_NETWORK_socket_send (s5r->sock,
2686 /* write error: connection closed, shutdown, etc.; just clean up */
2687 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2694 s5r->wbuf_len - len);
2695 s5r->wbuf_len -= len;
2696 if (s5r->wbuf_len > 0)
2698 /* not done writing */
2700 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2706 /* we're done writing, continue with state machine! */
2713 case SOCKS5_REQUEST:
2714 GNUNET_assert (NULL != s5r->rtask);
2716 case SOCKS5_DATA_TRANSFER:
2717 setup_data_transfer (s5r);
2719 case SOCKS5_WRITE_THEN_CLEANUP:
2730 * Return a server response message indicating a failure to the client.
2732 * @param s5r request to return failure code for
2733 * @param sc status code to return
2736 signal_socks_failure (struct Socks5Request *s5r,
2737 enum Socks5StatusCode sc)
2739 struct Socks5ServerResponseMessage *s_resp;
2741 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2742 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2743 s_resp->version = SOCKS_VERSION_5;
2745 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2746 if (NULL != s5r->wtask)
2748 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2755 * Return a server response message indicating success.
2757 * @param s5r request to return success status message for
2760 signal_socks_success (struct Socks5Request *s5r)
2762 struct Socks5ServerResponseMessage *s_resp;
2764 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2765 s_resp->version = SOCKS_VERSION_5;
2766 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2767 s_resp->reserved = 0;
2768 s_resp->addr_type = SOCKS5_AT_IPV4;
2769 /* zero out IPv4 address and port */
2772 sizeof (struct in_addr) + sizeof (uint16_t));
2773 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2774 sizeof (struct in_addr) + sizeof (uint16_t);
2775 if (NULL == s5r->wtask)
2777 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2784 * Process GNS results for target domain.
2786 * @param cls the `struct Socks5Request *`
2787 * @param tld #GNUNET_YES if this was a GNS TLD.
2788 * @param rd_count number of records returned
2789 * @param rd record data
2792 handle_gns_result (void *cls,
2795 const struct GNUNET_GNSRECORD_Data *rd)
2797 struct Socks5Request *s5r = cls;
2798 const struct GNUNET_GNSRECORD_Data *r;
2801 s5r->gns_lookup = NULL;
2804 for (uint32_t i=0;i<rd_count;i++)
2807 switch (r->record_type)
2809 case GNUNET_DNSPARSER_TYPE_A:
2811 struct sockaddr_in *in;
2813 if (sizeof (struct in_addr) != r->data_size)
2815 GNUNET_break_op (0);
2818 if (GNUNET_YES == got_ip)
2821 GNUNET_NETWORK_test_pf (PF_INET))
2823 got_ip = GNUNET_YES;
2824 in = (struct sockaddr_in *) &s5r->destination_address;
2825 in->sin_family = AF_INET;
2826 GNUNET_memcpy (&in->sin_addr,
2829 in->sin_port = htons (s5r->port);
2830 #if HAVE_SOCKADDR_IN_SIN_LEN
2831 in->sin_len = sizeof (*in);
2835 case GNUNET_DNSPARSER_TYPE_AAAA:
2837 struct sockaddr_in6 *in;
2839 if (sizeof (struct in6_addr) != r->data_size)
2841 GNUNET_break_op (0);
2844 if (GNUNET_YES == got_ip)
2847 GNUNET_NETWORK_test_pf (PF_INET))
2849 /* FIXME: allow user to disable IPv6 per configuration option... */
2850 got_ip = GNUNET_YES;
2851 in = (struct sockaddr_in6 *) &s5r->destination_address;
2852 in->sin6_family = AF_INET6;
2853 GNUNET_memcpy (&in->sin6_addr,
2856 in->sin6_port = htons (s5r->port);
2857 #if HAVE_SOCKADDR_IN_SIN_LEN
2858 in->sin6_len = sizeof (*in);
2862 case GNUNET_GNSRECORD_TYPE_VPN:
2863 GNUNET_break (0); /* should have been translated within GNS */
2865 case GNUNET_GNSRECORD_TYPE_LEHO:
2866 GNUNET_free_non_null (s5r->leho);
2867 s5r->leho = GNUNET_strndup (r->data,
2870 case GNUNET_GNSRECORD_TYPE_BOX:
2872 const struct GNUNET_GNSRECORD_BoxRecord *box;
2874 if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
2876 GNUNET_break_op (0);
2880 if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
2881 (ntohs (box->protocol) != IPPROTO_TCP) ||
2882 (ntohs (box->service) != s5r->port) )
2883 break; /* BOX record does not apply */
2884 GNUNET_free_non_null (s5r->dane_data);
2885 s5r->dane_data_len = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
2886 s5r->dane_data = GNUNET_malloc (s5r->dane_data_len);
2887 GNUNET_memcpy (s5r->dane_data,
2889 s5r->dane_data_len);
2897 if ( (GNUNET_YES != got_ip) &&
2898 (GNUNET_YES == tld) )
2900 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2901 "Name resolution failed to yield useful IP address.\n");
2902 signal_socks_failure (s5r,
2903 SOCKS5_STATUS_GENERAL_FAILURE);
2906 s5r->state = SOCKS5_DATA_TRANSFER;
2907 signal_socks_success (s5r);
2912 * Remove the first @a len bytes from the beginning of the read buffer.
2914 * @param s5r the handle clear the read buffer for
2915 * @param len number of bytes in read buffer to advance
2918 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2921 GNUNET_assert (len <= s5r->rbuf_len);
2924 s5r->rbuf_len - len);
2925 s5r->rbuf_len -= len;
2930 * Read data from incoming Socks5 connection
2932 * @param cls the closure with the `struct Socks5Request`
2935 do_s5r_read (void *cls)
2937 struct Socks5Request *s5r = cls;
2938 const struct Socks5ClientHelloMessage *c_hello;
2939 struct Socks5ServerHelloMessage *s_hello;
2940 const struct Socks5ClientRequestMessage *c_req;
2943 const struct GNUNET_SCHEDULER_TaskContext *tc;
2946 tc = GNUNET_SCHEDULER_get_task_context ();
2947 if ( (NULL != tc->read_ready) &&
2948 (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2950 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2951 &s5r->rbuf[s5r->rbuf_len],
2952 sizeof (s5r->rbuf) - s5r->rbuf_len);
2955 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2956 "socks5 client disconnected.\n");
2960 s5r->rbuf_len += rlen;
2962 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2966 "Processing %zu bytes of socks data in state %d\n",
2972 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2973 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2974 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2975 return; /* need more data */
2976 if (SOCKS_VERSION_5 != c_hello->version)
2978 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2979 _("Unsupported socks version %d\n"),
2980 (int) c_hello->version);
2984 clear_from_s5r_rbuf (s5r,
2985 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2986 GNUNET_assert (0 == s5r->wbuf_len);
2987 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2988 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2989 s_hello->version = SOCKS_VERSION_5;
2990 s_hello->auth_method = SOCKS_AUTH_NONE;
2991 GNUNET_assert (NULL == s5r->wtask);
2992 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2995 s5r->state = SOCKS5_REQUEST;
2997 case SOCKS5_REQUEST:
2998 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2999 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
3001 switch (c_req->command)
3003 case SOCKS5_CMD_TCP_STREAM:
3007 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3008 _("Unsupported socks command %d\n"),
3009 (int) c_req->command);
3010 signal_socks_failure (s5r,
3011 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
3014 switch (c_req->addr_type)
3016 case SOCKS5_AT_IPV4:
3018 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
3019 const uint16_t *port = (const uint16_t *) &v4[1];
3020 struct sockaddr_in *in;
3022 s5r->port = ntohs (*port);
3023 alen = sizeof (struct in_addr);
3024 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3025 alen + sizeof (uint16_t))
3026 return; /* need more data */
3027 in = (struct sockaddr_in *) &s5r->destination_address;
3028 in->sin_family = AF_INET;
3030 in->sin_port = *port;
3031 #if HAVE_SOCKADDR_IN_SIN_LEN
3032 in->sin_len = sizeof (*in);
3034 s5r->state = SOCKS5_DATA_TRANSFER;
3037 case SOCKS5_AT_IPV6:
3039 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
3040 const uint16_t *port = (const uint16_t *) &v6[1];
3041 struct sockaddr_in6 *in;
3043 s5r->port = ntohs (*port);
3044 alen = sizeof (struct in6_addr);
3045 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3046 alen + sizeof (uint16_t))
3047 return; /* need more data */
3048 in = (struct sockaddr_in6 *) &s5r->destination_address;
3049 in->sin6_family = AF_INET6;
3050 in->sin6_addr = *v6;
3051 in->sin6_port = *port;
3052 #if HAVE_SOCKADDR_IN_SIN_LEN
3053 in->sin6_len = sizeof (*in);
3055 s5r->state = SOCKS5_DATA_TRANSFER;
3058 case SOCKS5_AT_DOMAINNAME:
3060 const uint8_t *dom_len;
3061 const char *dom_name;
3062 const uint16_t *port;
3064 dom_len = (const uint8_t *) &c_req[1];
3065 alen = *dom_len + 1;
3066 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
3067 alen + sizeof (uint16_t))
3068 return; /* need more data */
3069 dom_name = (const char *) &dom_len[1];
3070 port = (const uint16_t*) &dom_name[*dom_len];
3071 s5r->domain = GNUNET_strndup (dom_name,
3073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3074 "Requested connection is to %s:%d\n",
3077 s5r->state = SOCKS5_RESOLVING;
3078 s5r->port = ntohs (*port);
3079 s5r->gns_lookup = GNUNET_GNS_lookup_with_tld (gns_handle,
3081 GNUNET_DNSPARSER_TYPE_A,
3082 GNUNET_NO /* only cached */,
3088 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3089 _("Unsupported socks address type %d\n"),
3090 (int) c_req->addr_type);
3091 signal_socks_failure (s5r,
3092 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
3095 clear_from_s5r_rbuf (s5r,
3096 sizeof (struct Socks5ClientRequestMessage) +
3097 alen + sizeof (uint16_t));
3098 if (0 != s5r->rbuf_len)
3100 /* read more bytes than healthy, why did the client send more!? */
3101 GNUNET_break_op (0);
3102 signal_socks_failure (s5r,
3103 SOCKS5_STATUS_GENERAL_FAILURE);
3106 if (SOCKS5_DATA_TRANSFER == s5r->state)
3108 /* if we are not waiting for GNS resolution, signal success */
3109 signal_socks_success (s5r);
3111 /* We are done reading right now */
3112 GNUNET_SCHEDULER_cancel (s5r->rtask);
3115 case SOCKS5_RESOLVING:
3118 case SOCKS5_DATA_TRANSFER:
3129 * Accept new incoming connections
3131 * @param cls the closure with the lsock4 or lsock6
3132 * @param tc the scheduler context
3135 do_accept (void *cls)
3137 struct GNUNET_NETWORK_Handle *lsock = cls;
3138 struct GNUNET_NETWORK_Handle *s;
3139 struct Socks5Request *s5r;
3141 GNUNET_assert (NULL != lsock);
3142 if (lsock == lsock4)
3143 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3146 else if (lsock == lsock6)
3147 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3152 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
3155 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
3158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3159 "Got an inbound connection, waiting for data\n");
3160 s5r = GNUNET_new (struct Socks5Request);
3161 GNUNET_CONTAINER_DLL_insert (s5r_head,
3165 s5r->state = SOCKS5_INIT;
3166 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3172 /* ******************* General / main code ********************* */
3176 * Task run on shutdown
3178 * @param cls closure
3181 do_shutdown (void *cls)
3183 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3184 "Shutting down...\n");
3185 /* MHD requires resuming before destroying the daemons */
3186 for (struct Socks5Request *s5r = s5r_head;
3192 s5r->suspended = GNUNET_NO;
3193 MHD_resume_connection (s5r->con);
3196 while (NULL != mhd_httpd_head)
3197 kill_httpd (mhd_httpd_head);
3198 while (NULL != s5r_head)
3199 cleanup_s5r (s5r_head);
3202 GNUNET_NETWORK_socket_close (lsock4);
3207 GNUNET_NETWORK_socket_close (lsock6);
3210 if (NULL != curl_multi)
3212 curl_multi_cleanup (curl_multi);
3215 if (NULL != gns_handle)
3217 GNUNET_GNS_disconnect (gns_handle);
3220 if (NULL != curl_download_task)
3222 GNUNET_SCHEDULER_cancel (curl_download_task);
3223 curl_download_task = NULL;
3227 GNUNET_SCHEDULER_cancel (ltask4);
3232 GNUNET_SCHEDULER_cancel (ltask6);
3235 gnutls_x509_crt_deinit (proxy_ca.cert);
3236 gnutls_x509_privkey_deinit (proxy_ca.key);
3237 gnutls_global_deinit ();
3242 * Create an IPv4 listen socket bound to our port.
3244 * @return NULL on error
3246 static struct GNUNET_NETWORK_Handle *
3249 struct GNUNET_NETWORK_Handle *ls;
3250 struct sockaddr_in sa4;
3253 memset (&sa4, 0, sizeof (sa4));
3254 sa4.sin_family = AF_INET;
3255 sa4.sin_port = htons (port);
3256 #if HAVE_SOCKADDR_IN_SIN_LEN
3257 sa4.sin_len = sizeof (sa4);
3259 ls = GNUNET_NETWORK_socket_create (AF_INET,
3265 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
3269 GNUNET_NETWORK_socket_close (ls);
3278 * Create an IPv6 listen socket bound to our port.
3280 * @return NULL on error
3282 static struct GNUNET_NETWORK_Handle *
3285 struct GNUNET_NETWORK_Handle *ls;
3286 struct sockaddr_in6 sa6;
3289 memset (&sa6, 0, sizeof (sa6));
3290 sa6.sin6_family = AF_INET6;
3291 sa6.sin6_port = htons (port);
3292 #if HAVE_SOCKADDR_IN_SIN_LEN
3293 sa6.sin6_len = sizeof (sa6);
3295 ls = GNUNET_NETWORK_socket_create (AF_INET6,
3301 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
3305 GNUNET_NETWORK_socket_close (ls);
3314 * Main function that will be run
3316 * @param cls closure
3317 * @param args remaining command-line arguments
3318 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3319 * @param c configuration
3324 const char *cfgfile,
3325 const struct GNUNET_CONFIGURATION_Handle *c)
3327 char* cafile_cfg = NULL;
3329 struct MhdHttpList *hd;
3333 if (NULL == (curl_multi = curl_multi_init ()))
3335 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3336 "Failed to create cURL multi handle!\n");
3339 cafile = cafile_opt;
3343 GNUNET_CONFIGURATION_get_value_filename (cfg,
3348 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3353 cafile = cafile_cfg;
3355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3356 "Using %s as CA\n", cafile);
3358 gnutls_global_init ();
3359 gnutls_x509_crt_init (&proxy_ca.cert);
3360 gnutls_x509_privkey_init (&proxy_ca.key);
3363 load_cert_from_file (proxy_ca.cert,
3366 load_key_from_file (proxy_ca.key,
3369 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3370 _("Failed to load X.509 key and certificate from `%s'\n"),
3372 gnutls_x509_crt_deinit (proxy_ca.cert);
3373 gnutls_x509_privkey_deinit (proxy_ca.key);
3374 gnutls_global_deinit ();
3375 GNUNET_free_non_null (cafile_cfg);
3378 GNUNET_free_non_null (cafile_cfg);
3379 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3381 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3382 "Unable to connect to GNS!\n");
3383 gnutls_x509_crt_deinit (proxy_ca.cert);
3384 gnutls_x509_privkey_deinit (proxy_ca.key);
3385 gnutls_global_deinit ();
3388 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
3391 /* Open listen socket for socks proxy */
3392 lsock6 = bind_v6 ();
3395 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3401 GNUNET_NETWORK_socket_listen (lsock6,
3404 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3406 GNUNET_NETWORK_socket_close (lsock6);
3411 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3417 lsock4 = bind_v4 ();
3420 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3426 GNUNET_NETWORK_socket_listen (lsock4,
3429 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3431 GNUNET_NETWORK_socket_close (lsock4);
3436 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3442 if ( (NULL == lsock4) &&
3445 GNUNET_SCHEDULER_shutdown ();
3448 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3450 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3451 "cURL global init failed!\n");
3452 GNUNET_SCHEDULER_shutdown ();
3455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3456 "Proxy listens on port %u\n",
3457 (unsigned int) port);
3459 /* start MHD daemon for HTTP */
3460 hd = GNUNET_new (struct MhdHttpList);
3461 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME,
3464 &create_response, hd,
3465 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3466 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3467 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
3468 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3470 if (NULL == hd->daemon)
3473 GNUNET_SCHEDULER_shutdown ();
3477 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
3484 * The main function for gnunet-gns-proxy.
3486 * @param argc number of arguments from the command line
3487 * @param argv command line arguments
3488 * @return 0 ok, 1 on error
3491 main (int argc, char *const *argv)
3493 struct GNUNET_GETOPT_CommandLineOption options[] = {
3494 GNUNET_GETOPT_option_uint16 ('p',
3497 gettext_noop ("listen on specified port (default: 7777)"),
3499 GNUNET_GETOPT_option_string ('a',
3502 gettext_noop ("pem file to use as CA"),
3505 GNUNET_GETOPT_OPTION_END
3507 static const char* page =
3508 "<html><head><title>gnunet-gns-proxy</title>"
3509 "</head><body>cURL fail</body></html>";
3512 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv,
3515 GNUNET_log_setup ("gnunet-gns-proxy",
3518 curl_failure_response
3519 = MHD_create_response_from_buffer (strlen (page),
3521 MHD_RESPMEM_PERSISTENT);
3525 GNUNET_PROGRAM_run (argc, argv,
3527 _("GNUnet GNS proxy"),
3529 &run, NULL)) ? 0 : 1;
3530 MHD_destroy_response (curl_failure_response);
3531 GNUNET_free_non_null ((char *) argv);
3535 /* end of gnunet-gns-proxy.c */