2 This file is part of GNUnet.
3 Copyright (C) 2012-2014 Christian Grothoff (and other contributing authors)
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"
51 #define GNUID_HTTP_HEADER_GNUID_RESPONSE "X-GNUid-Requested-Info"
54 * Default Socks5 listen port.
56 #define GNUNET_GNS_PROXY_PORT 7777
59 * Maximum supported length for a URI.
60 * Should die. @deprecated
62 #define MAX_HTTP_URI_LENGTH 2048
65 * Size of the buffer for the data upload / download. Must be
66 * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
68 #define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE
71 * Size of the read/write buffers for Socks. Uses
72 * 256 bytes for the hostname (at most), plus a few
73 * bytes overhead for the messages.
75 #define SOCKS_BUFFERSIZE (256 + 32)
78 * Port for plaintext HTTP.
85 #define HTTPS_PORT 443
88 * Largest allowed size for a PEM certificate.
90 #define MAX_PEM_SIZE (10 * 1024)
93 * After how long do we clean up unused MHD SSL/TLS instances?
95 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
98 * After how long do we clean up Socks5 handles that failed to show any activity
99 * with their respective MHD instance?
101 #define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
107 * @param level log level
108 * @param fun name of curl_easy-function that gave the error
109 * @param rc return code from curl
111 #define LOG_CURL_EASY(level,fun,rc) GNUNET_log(level, _("%s failed at %s:%d: `%s'\n"), fun, __FILE__, __LINE__, curl_easy_strerror (rc))
114 /* *************** Socks protocol definitions (move to TUN?) ****************** */
117 * Which SOCKS version do we speak?
119 #define SOCKS_VERSION_5 0x05
122 * Flag to set for 'no authentication'.
124 #define SOCKS_AUTH_NONE 0
127 * Enable GNUid functionality
129 #define GNUID_ENABLED 1
132 * Commands in Socks5.
137 * Establish TCP/IP stream.
139 SOCKS5_CMD_TCP_STREAM = 1,
142 * Establish TCP port binding.
144 SOCKS5_CMD_TCP_PORT = 2,
147 * Establish UDP port binding.
149 SOCKS5_CMD_UDP_PORT = 3
154 * Address types in Socks5.
156 enum Socks5AddressType
166 SOCKS5_AT_DOMAINNAME = 3,
177 * Status codes in Socks5 response.
179 enum Socks5StatusCode
181 SOCKS5_STATUS_REQUEST_GRANTED = 0,
182 SOCKS5_STATUS_GENERAL_FAILURE = 1,
183 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
184 SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
185 SOCKS5_STATUS_HOST_UNREACHABLE = 4,
186 SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
187 SOCKS5_STATUS_TTL_EXPIRED = 6,
188 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
189 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
194 * Client hello in Socks5 protocol.
196 struct Socks5ClientHelloMessage
199 * Should be #SOCKS_VERSION_5.
204 * How many authentication methods does the client support.
206 uint8_t num_auth_methods;
208 /* followed by supported authentication methods, 1 byte per method */
214 * Server hello in Socks5 protocol.
216 struct Socks5ServerHelloMessage
219 * Should be #SOCKS_VERSION_5.
224 * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
225 * which skips the authentication step.
232 * Client socks request in Socks5 protocol.
234 struct Socks5ClientRequestMessage
237 * Should be #SOCKS_VERSION_5.
242 * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
247 * Reserved, always zero.
252 * Address type, an `enum Socks5AddressType`.
257 * Followed by either an ip4/ipv6 address or a domain name with a
258 * length field (uint8_t) in front (depending on @e addr_type).
259 * followed by port number in network byte order (uint16_t).
265 * Server response to client requests in Socks5 protocol.
267 struct Socks5ServerResponseMessage
270 * Should be #SOCKS_VERSION_5.
275 * Status code, an `enum Socks5StatusCode`
285 * Address type, an `enum Socks5AddressType`.
290 * Followed by either an ip4/ipv6 address or a domain name with a
291 * length field (uint8_t) in front (depending on @e addr_type).
292 * followed by port number in network byte order (uint16_t).
299 /* *********************** Datastructures for HTTP handling ****************** */
302 * A structure for CA cert/key
309 gnutls_x509_crt_t cert;
314 gnutls_x509_privkey_t key;
319 * Structure for GNS certificates
321 struct ProxyGNSCertificate
324 * The certificate as PEM
326 char cert[MAX_PEM_SIZE];
329 * The private key as PEM
331 char key[MAX_PEM_SIZE];
337 * A structure for all running Httpds
344 struct MhdHttpList *prev;
349 struct MhdHttpList *next;
352 * the domain name to server (only important for SSL)
359 struct MHD_Daemon *daemon;
362 * Optional proxy certificate used
364 struct ProxyGNSCertificate *proxy_cert;
369 struct GNUNET_SCHEDULER_Task * httpd_task;
372 * is this an ssl daemon?
379 /* ***************** Datastructures for Socks handling **************** */
388 * We're waiting to get the client hello.
393 * We're waiting to get the initial request.
398 * We are currently resolving the destination.
403 * We're in transfer mode.
405 SOCKS5_DATA_TRANSFER,
408 * Finish writing the write buffer, then clean up.
410 SOCKS5_WRITE_THEN_CLEANUP,
413 * Socket has been passed to MHD, do not close it anymore.
415 SOCKS5_SOCKET_WITH_MHD,
418 * We've finished receiving upload data from MHD.
420 SOCKS5_SOCKET_UPLOAD_STARTED,
423 * We've finished receiving upload data from MHD.
425 SOCKS5_SOCKET_UPLOAD_DONE,
428 * We've finished uploading data via CURL and can now download.
430 SOCKS5_SOCKET_DOWNLOAD_STARTED,
433 * We've finished receiving download data from cURL.
435 SOCKS5_SOCKET_DOWNLOAD_DONE
441 * A structure for socks requests
449 struct Socks5Request *next;
454 struct Socks5Request *prev;
459 struct GNUNET_NETWORK_Handle *sock;
462 * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
464 struct GNUNET_GNS_LookupRequest *gns_lookup;
467 * Client socket read task
469 struct GNUNET_SCHEDULER_Task * rtask;
472 * Client socket write task
474 struct GNUNET_SCHEDULER_Task * wtask;
479 struct GNUNET_SCHEDULER_Task * timeout_task;
484 char rbuf[SOCKS_BUFFERSIZE];
489 char wbuf[SOCKS_BUFFERSIZE];
492 * Buffer we use for moving data between MHD and curl (in both directions).
494 char io_buf[IO_BUFFERSIZE];
497 * MHD HTTP instance handling this request, NULL for none.
499 struct MhdHttpList *hd;
502 * MHD response object for this request.
504 struct MHD_Response *response;
507 * the domain name to server (only important for SSL)
512 * DNS Legacy Host Name as given by GNS, NULL if not given.
517 * Payload of the (last) DANE record encountered.
532 * HTTP request headers for the curl request.
534 struct curl_slist *headers;
537 * DNS->IP mappings resolved through GNS
539 struct curl_slist *hosts;
542 * Custom response headers
544 struct curl_slist *resp_headers;
549 char* redirect_gnuid;
552 * HTTP response code to give to MHD for the response.
554 unsigned int response_code;
557 * Number of bytes in @e dane_data.
559 size_t dane_data_len;
562 * Number of bytes already in read buffer
567 * Number of bytes already in write buffer
572 * Number of bytes already in the IO buffer.
577 * Once known, what's the target address for the connection?
579 struct sockaddr_storage destination_address;
584 enum SocksPhase state;
587 * Desired destination port.
595 /* *********************** Globals **************************** */
599 * The port the proxy is running on (default 7777)
601 static unsigned long port = GNUNET_GNS_PROXY_PORT;
604 * The CA file (pem) to use for the proxy CA
606 static char *cafile_opt;
609 * The listen socket of the proxy for IPv4
611 static struct GNUNET_NETWORK_Handle *lsock4;
614 * The listen socket of the proxy for IPv6
616 static struct GNUNET_NETWORK_Handle *lsock6;
619 * The listen task ID for IPv4
621 static struct GNUNET_SCHEDULER_Task * ltask4;
624 * The listen task ID for IPv6
626 static struct GNUNET_SCHEDULER_Task * ltask6;
629 * The cURL download task (curl multi API).
631 static struct GNUNET_SCHEDULER_Task * curl_download_task;
634 * The cURL multi handle
636 static CURLM *curl_multi;
639 * Handle to the GNS service
641 static struct GNUNET_GNS_Handle *gns_handle;
644 * DLL for http/https daemons
646 static struct MhdHttpList *mhd_httpd_head;
649 * DLL for http/https daemons
651 static struct MhdHttpList *mhd_httpd_tail;
654 * Daemon for HTTP (we have one per SSL certificate, and then one for
655 * all HTTP connections; this is the one for HTTP, not HTTPS).
657 static struct MhdHttpList *httpd;
660 * DLL of active socks requests.
662 static struct Socks5Request *s5r_head;
665 * DLL of active socks requests.
667 static struct Socks5Request *s5r_tail;
670 * The users local GNS master zone
672 static struct GNUNET_CRYPTO_EcdsaPublicKey local_gns_zone;
675 * The users local shorten zone
677 static struct GNUNET_CRYPTO_EcdsaPrivateKey local_shorten_zone;
680 * Is shortening enabled?
682 static int do_shorten;
685 * The CA for SSL certificate generation
687 static struct ProxyCA proxy_ca;
690 * Response we return on cURL failures.
692 static struct MHD_Response *curl_failure_response;
695 * Connection to identity service.
697 static struct GNUNET_IDENTITY_Handle *identity;
700 * Request for our ego.
702 static struct GNUNET_IDENTITY_Operation *id_op;
707 static const struct GNUNET_CONFIGURATION_Handle *cfg;
710 /* ************************* Global helpers ********************* */
714 * Run MHD now, we have extra data ready for the callback.
716 * @param hd the daemon to run now.
719 run_mhd_now (struct MhdHttpList *hd);
723 * Clean up s5r handles.
725 * @param s5r the handle to destroy
728 cleanup_s5r (struct Socks5Request *s5r)
730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
731 "Cleaning up socks request\n");
732 if (NULL != s5r->curl)
734 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
735 "Cleaning up cURL handle\n");
736 curl_multi_remove_handle (curl_multi, s5r->curl);
737 curl_easy_cleanup (s5r->curl);
740 curl_slist_free_all (s5r->headers);
741 if (NULL != s5r->hosts)
742 curl_slist_free_all (s5r->hosts);
743 if (NULL != s5r->resp_headers)
744 curl_slist_free_all (s5r->resp_headers);
745 if ( (NULL != s5r->response) &&
746 (curl_failure_response != s5r->response) )
747 MHD_destroy_response (s5r->response);
748 if (NULL != s5r->rtask)
749 GNUNET_SCHEDULER_cancel (s5r->rtask);
750 if (NULL != s5r->timeout_task)
751 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
752 if (NULL != s5r->wtask)
753 GNUNET_SCHEDULER_cancel (s5r->wtask);
754 if (NULL != s5r->gns_lookup)
755 GNUNET_GNS_lookup_cancel (s5r->gns_lookup);
756 if (NULL != s5r->sock)
758 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
759 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
761 GNUNET_NETWORK_socket_close (s5r->sock);
763 GNUNET_CONTAINER_DLL_remove (s5r_head,
766 GNUNET_free_non_null (s5r->domain);
767 GNUNET_free_non_null (s5r->leho);
768 GNUNET_free_non_null (s5r->url);
769 GNUNET_free_non_null (s5r->dane_data);
774 /* ************************* HTTP handling with cURL *********************** */
778 * Callback for MHD response generation. This function is called from
779 * MHD whenever MHD expects to get data back. Copies data from the
780 * io_buf, if available.
782 * @param cls closure with our `struct Socks5Request`
783 * @param pos in buffer
784 * @param buf where to copy data
785 * @param max available space in @a buf
786 * @return number of bytes written to @a buf
789 mhd_content_cb (void *cls,
794 struct Socks5Request *s5r = cls;
795 size_t bytes_to_copy;
797 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
798 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
800 /* we're still not done with the upload, do not yet
801 start the download, the IO buffer is still full
803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
804 "Pausing MHD download, not yet ready for download\n");
805 return 0; /* not yet ready for data download */
807 bytes_to_copy = GNUNET_MIN (max,
809 if ( (0 == bytes_to_copy) &&
810 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
812 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
813 "Pausing MHD download, no data available\n");
814 return 0; /* more data later */
816 if ( (0 == bytes_to_copy) &&
817 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
819 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
820 "Completed MHD download\n");
821 return MHD_CONTENT_READER_END_OF_STREAM;
823 memcpy (buf, s5r->io_buf, bytes_to_copy);
824 memmove (s5r->io_buf,
825 &s5r->io_buf[bytes_to_copy],
826 s5r->io_len - bytes_to_copy);
827 s5r->io_len -= bytes_to_copy;
828 if (NULL != s5r->curl)
829 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
830 return bytes_to_copy;
835 * Check that the website has presented us with a valid SSL certificate.
836 * The certificate must either match the domain name or the LEHO name
837 * (or, if available, the TLSA record).
839 * @param s5r request to check for.
840 * @return #GNUNET_OK if the certificate is valid
843 check_ssl_certificate (struct Socks5Request *s5r)
845 unsigned int cert_list_size;
846 const gnutls_datum_t *chainp;
847 const struct curl_tlssessioninfo *tlsinfo;
848 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
850 gnutls_x509_crt_t x509_cert;
855 curl_easy_getinfo (s5r->curl,
856 CURLINFO_TLS_SESSION,
857 (struct curl_slist **) &tlsinfo))
858 return GNUNET_SYSERR;
859 if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
861 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
862 _("Unsupported CURL SSL backend %d\n"),
864 return GNUNET_SYSERR;
866 chainp = gnutls_certificate_get_peers (tlsinfo->internals, &cert_list_size);
867 if ( (! chainp) || (0 == cert_list_size) )
868 return GNUNET_SYSERR;
870 size = sizeof (certdn);
871 /* initialize an X.509 certificate structure. */
872 gnutls_x509_crt_init (&x509_cert);
873 gnutls_x509_crt_import (x509_cert,
875 GNUTLS_X509_FMT_DER);
877 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
878 GNUTLS_OID_X520_COMMON_NAME,
879 0, /* the first and only one */
880 0 /* no DER encoding */,
884 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
885 _("Failed to fetch CN from cert: %s\n"),
886 gnutls_strerror(rc));
887 gnutls_x509_crt_deinit (x509_cert);
888 return GNUNET_SYSERR;
890 /* check for TLSA/DANE records */
892 if (NULL != s5r->dane_data)
894 char *dd[] = { s5r->dane_data, NULL };
895 int dlen[] = { s5r->dane_data_len, 0};
896 dane_state_t dane_state;
897 dane_query_t dane_query;
900 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
901 if (0 != (rc = dane_state_init (&dane_state,
902 #ifdef DANE_F_IGNORE_DNSSEC
903 DANE_F_IGNORE_DNSSEC |
905 DANE_F_IGNORE_LOCAL_RESOLVER)))
907 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
908 _("Failed to initialize DANE: %s\n"),
910 gnutls_x509_crt_deinit (x509_cert);
911 return GNUNET_SYSERR;
913 if (0 != (rc = dane_raw_tlsa (dane_state,
920 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
921 _("Failed to parse DANE record: %s\n"),
923 dane_state_deinit (dane_state);
924 gnutls_x509_crt_deinit (x509_cert);
925 return GNUNET_SYSERR;
927 if (0 != (rc = dane_verify_crt_raw (dane_state,
930 gnutls_certificate_type_get (tlsinfo->internals),
935 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
936 _("Failed to verify TLS connection using DANE: %s\n"),
938 dane_query_deinit (dane_query);
939 dane_state_deinit (dane_state);
940 gnutls_x509_crt_deinit (x509_cert);
941 return GNUNET_SYSERR;
945 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
946 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
948 dane_query_deinit (dane_query);
949 dane_state_deinit (dane_state);
950 gnutls_x509_crt_deinit (x509_cert);
951 return GNUNET_SYSERR;
953 dane_query_deinit (dane_query);
954 dane_state_deinit (dane_state);
960 /* try LEHO or ordinary domain name X509 verification */
962 if (NULL != s5r->leho)
966 if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
969 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
970 _("SSL certificate subject name (%s) does not match `%s'\n"),
973 gnutls_x509_crt_deinit (x509_cert);
974 return GNUNET_SYSERR;
979 /* we did not even have the domain name!? */
981 return GNUNET_SYSERR;
984 gnutls_x509_crt_deinit (x509_cert);
990 * We're getting an HTTP response header from cURL. Convert it to the
991 * MHD response headers. Mostly copies the headers, but makes special
992 * adjustments to "Set-Cookie" and "Location" headers as those may need
993 * to be changed from the LEHO to the domain the browser expects.
995 * @param buffer curl buffer with a single line of header data; not 0-terminated!
996 * @param size curl blocksize
997 * @param nmemb curl blocknumber
998 * @param cls our `struct Socks5Request *`
999 * @return size of processed bytes
1002 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
1004 struct Socks5Request *s5r = cls;
1005 size_t bytes = size * nmemb;
1007 const char *hdr_type;
1008 const char *cookie_domain;
1011 char *new_cookie_hdr;
1014 size_t delta_cdomain;
1018 if (NULL == s5r->response)
1020 /* first, check SSL certificate */
1021 if ( (HTTPS_PORT == s5r->port) &&
1022 (GNUNET_OK != check_ssl_certificate (s5r)) )
1025 GNUNET_break (CURLE_OK ==
1026 curl_easy_getinfo (s5r->curl,
1027 CURLINFO_RESPONSE_CODE,
1029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1030 "Creating MHD response with code %d\n",
1032 s5r->response_code = resp_code;
1033 s5r->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
1038 if (NULL != s5r->leho)
1042 GNUNET_asprintf (&cors_hdr,
1043 (HTTPS_PORT == s5r->port)
1048 GNUNET_break (MHD_YES ==
1049 MHD_add_response_header (s5r->response,
1050 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1052 GNUNET_free (cors_hdr);
1054 /* force connection to be closed after each request, as we
1055 do not support HTTP pipelining (yet, FIXME!) */
1056 GNUNET_break (MHD_YES ==
1057 MHD_add_response_header (s5r->response,
1058 MHD_HTTP_HEADER_CONNECTION,
1062 ndup = GNUNET_strndup (buffer, bytes);
1063 hdr_type = strtok (ndup, ":");
1064 if (NULL == hdr_type)
1069 hdr_val = strtok (NULL, "");
1070 if (NULL == hdr_val)
1075 if (' ' == *hdr_val)
1078 /* custom logic for certain header types */
1079 new_cookie_hdr = NULL;
1080 if ( (NULL != s5r->leho) &&
1081 (0 == strcasecmp (hdr_type,
1082 MHD_HTTP_HEADER_SET_COOKIE)) )
1085 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1086 strlen (s5r->domain) + 1);
1088 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1089 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1091 if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
1092 (GNUNET_NO == domain_matched) )
1094 domain_matched = GNUNET_YES;
1095 cookie_domain = tok + strlen (" domain") + 1;
1096 if (strlen (cookie_domain) < strlen (s5r->leho))
1098 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1099 if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
1101 offset += sprintf (new_cookie_hdr + offset,
1107 else if (0 == strcmp (cookie_domain, s5r->leho))
1109 offset += sprintf (new_cookie_hdr + offset,
1114 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1115 _("Cookie domain `%s' supplied by server is invalid\n"),
1118 memcpy (new_cookie_hdr + offset, tok, strlen (tok));
1119 offset += strlen (tok);
1120 new_cookie_hdr[offset++] = ';';
1122 hdr_val = new_cookie_hdr;
1125 new_location = NULL;
1126 if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
1130 GNUNET_asprintf (&leho_host,
1131 (HTTPS_PORT != s5r->port)
1135 if (0 == strncmp (leho_host,
1137 strlen (leho_host)))
1139 GNUNET_asprintf (&new_location,
1141 (HTTPS_PORT != s5r->port)
1145 hdr_val + strlen (leho_host));
1146 hdr_val = new_location;
1148 GNUNET_free (leho_host);
1152 /* MHD does not allow certain characters in values, remove those */
1153 if (NULL != (tok = strchr (hdr_val, '\n')))
1155 if (NULL != (tok = strchr (hdr_val, '\r')))
1157 if (NULL != (tok = strchr (hdr_val, '\t')))
1161 if (0 == strcasecmp (GNUID_HTTP_HEADER_GNUID_RESPONSE, hdr_type))
1164 GNUNET_asprintf (&redirect,
1165 "%s?requested_by=http://%s:%d%s&requested_infos=%s",
1166 "http://localhost:8000#/identities", //TODO read this from config
1172 s5r->response_code = MHD_HTTP_FOUND;
1173 GNUNET_break (MHD_YES == MHD_add_response_header (s5r->response,
1174 MHD_HTTP_HEADER_LOCATION,
1176 printf ("%s", redirect);
1177 GNUNET_free (redirect);
1180 if (0 != strlen (hdr_val))
1182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1183 "Adding header %s: %s to MHD response\n",
1186 GNUNET_break (MHD_YES ==
1187 MHD_add_response_header (s5r->response,
1192 GNUNET_free_non_null (new_cookie_hdr);
1193 GNUNET_free_non_null (new_location);
1199 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1200 * it available to MHD.
1202 * @param ptr pointer to the data
1203 * @param size number of blocks of data
1204 * @param nmemb blocksize
1205 * @param ctx our `struct Socks5Request *`
1206 * @return number of bytes handled
1209 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1211 struct Socks5Request *s5r = ctx;
1212 size_t total = size * nmemb;
1214 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1215 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1217 /* we're still not done with the upload, do not yet
1218 start the download, the IO buffer is still full
1219 with upload data. */
1220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1221 "Pausing CURL download, waiting for UPLOAD to finish\n");
1222 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1224 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1226 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1227 "Pausing CURL download, not enough space\n");
1228 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1230 memcpy (&s5r->io_buf[s5r->io_len],
1233 s5r->io_len += total;
1234 if (s5r->io_len == total)
1235 run_mhd_now (s5r->hd);
1241 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1242 * to make it available to MHD.
1244 * @param buf where to write the data
1245 * @param size number of bytes per member
1246 * @param nmemb number of members available in @a buf
1247 * @param cls our `struct Socks5Request` that generated the data
1248 * @return number of bytes copied to @a buf
1251 curl_upload_cb (void *buf, size_t size, size_t nmemb, void *cls)
1253 struct Socks5Request *s5r = cls;
1254 size_t len = size * nmemb;
1257 if ( (0 == s5r->io_len) &&
1258 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1261 "Pausing CURL UPLOAD, need more data\n");
1262 return CURL_READFUNC_PAUSE;
1264 if ( (0 == s5r->io_len) &&
1265 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1267 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1269 "Completed CURL UPLOAD\n");
1270 return 0; /* upload finished, can now download */
1272 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) ||
1273 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1276 return CURL_READFUNC_ABORT;
1278 to_copy = GNUNET_MIN (s5r->io_len,
1280 memcpy (buf, s5r->io_buf, to_copy);
1281 memmove (s5r->io_buf,
1282 &s5r->io_buf[to_copy],
1283 s5r->io_len - to_copy);
1284 s5r->io_len -= to_copy;
1285 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1286 run_mhd_now (s5r->hd); /* got more space for upload now */
1291 /* ************************** main loop of cURL interaction ****************** */
1295 * Task that is run when we are ready to receive more data
1298 * @param cls closure
1299 * @param tc task context
1302 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1306 * Ask cURL for the select() sets and schedule cURL operations.
1309 curl_download_prepare ()
1316 struct GNUNET_NETWORK_FDSet *grs;
1317 struct GNUNET_NETWORK_FDSet *gws;
1319 struct GNUNET_TIME_Relative rtime;
1321 if (NULL != curl_download_task)
1323 GNUNET_SCHEDULER_cancel (curl_download_task);
1324 curl_download_task = NULL;
1330 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max)))
1332 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1333 "%s failed at %s:%d: `%s'\n",
1334 "curl_multi_fdset", __FILE__, __LINE__,
1335 curl_multi_strerror (mret));
1339 GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
1341 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1343 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1346 grs = GNUNET_NETWORK_fdset_create ();
1347 gws = GNUNET_NETWORK_fdset_create ();
1348 GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1349 GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1350 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1353 &curl_task_download, curl_multi);
1354 GNUNET_NETWORK_fdset_destroy (gws);
1355 GNUNET_NETWORK_fdset_destroy (grs);
1359 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1360 &curl_task_download,
1367 * Task that is run when we are ready to receive more data from curl.
1369 * @param cls closure, NULL
1370 * @param tc task context
1373 curl_task_download (void *cls,
1374 const struct GNUNET_SCHEDULER_TaskContext *tc)
1378 struct CURLMsg *msg;
1380 struct Socks5Request *s5r;
1382 curl_download_task = NULL;
1386 mret = curl_multi_perform (curl_multi, &running);
1387 while (NULL != (msg = curl_multi_info_read (curl_multi, &msgnum)))
1389 GNUNET_break (CURLE_OK ==
1390 curl_easy_getinfo (msg->easy_handle,
1401 /* documentation says this is not used */
1405 switch (msg->data.result)
1408 case CURLE_GOT_NOTHING:
1409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1410 "CURL download completed.\n");
1411 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1412 run_mhd_now (s5r->hd);
1415 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1416 "Download curl failed: %s\n",
1417 curl_easy_strerror (msg->data.result));
1418 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1419 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1420 run_mhd_now (s5r->hd);
1423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1424 "Cleaning up cURL handle\n");
1425 curl_multi_remove_handle (curl_multi, s5r->curl);
1426 curl_easy_cleanup (s5r->curl);
1428 if (NULL == s5r->response)
1429 s5r->response = curl_failure_response;
1432 /* documentation says this is not used */
1436 /* unexpected status code */
1441 } while (mret == CURLM_CALL_MULTI_PERFORM);
1442 if (CURLM_OK != mret)
1443 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1444 "%s failed at %s:%d: `%s'\n",
1445 "curl_multi_perform", __FILE__, __LINE__,
1446 curl_multi_strerror (mret));
1449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450 "Suspending cURL multi loop, no more events pending\n");
1451 return; /* nothing more in progress */
1453 curl_download_prepare ();
1457 /* ********************************* MHD response generation ******************* */
1461 * Read HTTP request header field from the request. Copies the fields
1462 * over to the 'headers' that will be given to curl. However, 'Host'
1463 * is substituted with the LEHO if present. We also change the
1464 * 'Connection' header value to "close" as the proxy does not support
1467 * @param cls our `struct Socks5Request`
1468 * @param kind value kind
1469 * @param key field key
1470 * @param value field value
1471 * @return MHD_YES to continue to iterate
1474 con_val_iter (void *cls,
1475 enum MHD_ValueKind kind,
1479 struct Socks5Request *s5r = cls;
1482 if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1483 (NULL != s5r->leho) )
1485 if (0 == strcasecmp (MHD_HTTP_HEADER_CONNECTION, key))
1487 GNUNET_asprintf (&hdr,
1491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1492 "Adding HEADER `%s' to HTTP request\n",
1494 s5r->headers = curl_slist_append (s5r->headers,
1502 * Read HTTP request uri from the request.
1504 * @param cls our `struct Socks5Request`
1505 * @param kind value kind
1506 * @param key field key
1507 * @param value field value
1508 * @return MHD_YES to continue to iterate
1511 con_val_uri_iter (void *cls,
1512 enum MHD_ValueKind kind,
1516 struct Socks5Request *s5r = cls;
1519 if (0 == strcasecmp ("gnuid_token", key))
1521 GNUNET_asprintf (&hdr,
1523 MHD_HTTP_HEADER_AUTHORIZATION,
1525 s5r->headers = curl_slist_append (s5r->headers,
1533 * Main MHD callback for handling requests.
1536 * @param con MHD connection handle
1537 * @param url the url in the request
1538 * @param meth the HTTP method used ("GET", "PUT", etc.)
1539 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1540 * @param upload_data the data being uploaded (excluding HEADERS,
1541 * for a POST that fits into memory and that is encoded
1542 * with a supported encoding, the POST data will NOT be
1543 * given in upload_data and is instead available as
1544 * part of MHD_get_connection_values; very large POST
1545 * data *will* be made available incrementally in
1547 * @param upload_data_size set initially to the size of the
1548 * @a upload_data provided; the method must update this
1549 * value to the number of bytes NOT processed;
1550 * @param con_cls pointer to location where we store the 'struct Request'
1551 * @return MHD_YES if the connection was handled successfully,
1552 * MHD_NO if the socket must be closed due to a serious
1553 * error while handling the request
1556 create_response (void *cls,
1557 struct MHD_Connection *con,
1561 const char *upload_data,
1562 size_t *upload_data_size,
1565 struct Socks5Request *s5r = *con_cls;
1569 char ipstring[INET6_ADDRSTRLEN];
1570 char ipaddr[INET6_ADDRSTRLEN + 2];
1571 const struct sockaddr *sa;
1572 const struct sockaddr_in *s4;
1573 const struct sockaddr_in6 *s6;
1582 if ( (NULL == s5r->curl) &&
1583 (SOCKS5_SOCKET_WITH_MHD == s5r->state) )
1585 /* first time here, initialize curl handle */
1586 sa = (const struct sockaddr *) &s5r->destination_address;
1587 switch (sa->sa_family)
1590 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1591 if (NULL == inet_ntop (AF_INET,
1599 GNUNET_snprintf (ipaddr,
1603 port = ntohs (s4->sin_port);
1606 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1607 if (NULL == inet_ntop (AF_INET6,
1615 GNUNET_snprintf (ipaddr,
1619 port = ntohs (s6->sin6_port);
1625 s5r->curl = curl_easy_init ();
1626 if (NULL == s5r->curl)
1627 return MHD_queue_response (con,
1628 MHD_HTTP_INTERNAL_SERVER_ERROR,
1629 curl_failure_response);
1630 curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1631 curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1632 curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1633 curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1634 curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1635 curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1636 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1637 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1638 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1639 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1640 curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1641 curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0);
1644 * Pre-populate cache to resolve Hostname.
1645 * This is necessary as the DNS name in the CURLOPT_URL is used
1646 * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1648 if (NULL != s5r->leho)
1650 GNUNET_asprintf (&curl_hosts,
1655 s5r->hosts = curl_slist_append(NULL, curl_hosts);
1656 curl_easy_setopt(s5r->curl, CURLOPT_RESOLVE, s5r->hosts);
1657 GNUNET_free (curl_hosts);
1659 GNUNET_asprintf (&curlurl,
1660 (HTTPS_PORT != s5r->port)
1662 : "https://%s:%d%s",
1668 curl_easy_setopt (s5r->curl,
1671 GNUNET_free (curlurl);
1673 if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1675 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1676 curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
1677 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1678 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1679 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1680 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1682 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1684 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1685 curl_easy_setopt (s5r->curl, CURLOPT_POST, 1);
1686 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1687 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1688 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1689 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1691 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1693 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1694 curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
1696 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1698 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1699 curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
1700 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1701 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1703 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_OPTIONS))
1705 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1706 curl_easy_setopt (s5r->curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
1707 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1708 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1709 GNUNET_asprintf (&curl_headers,
1713 s5r->headers = curl_slist_append(s5r->headers, curl_headers);
1714 GNUNET_free (curl_headers);
1718 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1719 _("Unsupported HTTP method `%s'\n"),
1721 curl_easy_cleanup (s5r->curl);
1726 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1728 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1730 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1732 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1736 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1739 if (HTTPS_PORT == s5r->port)
1741 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1742 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1743 /* Disable cURL checking the hostname, as we will check ourselves
1744 as only we have the domain name or the LEHO or the DANE record */
1745 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
1749 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
1752 if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
1755 curl_easy_cleanup (s5r->curl);
1759 MHD_get_connection_values (con,
1761 &con_val_iter, s5r);
1764 MHD_get_connection_values (con,
1765 MHD_GET_ARGUMENT_KIND,
1766 &con_val_uri_iter, s5r);
1767 GNUNET_asprintf (&curl_headers,
1769 "X-GNUid-Available",
1771 s5r->headers = curl_slist_append(s5r->headers, curl_headers);
1772 GNUNET_free (curl_headers);
1775 curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
1776 curl_download_prepare ();
1780 /* continuing to process request */
1781 if (0 != *upload_data_size)
1783 left = GNUNET_MIN (*upload_data_size,
1784 sizeof (s5r->io_buf) - s5r->io_len);
1785 memcpy (&s5r->io_buf[s5r->io_len],
1788 s5r->io_len += left;
1789 *upload_data_size -= left;
1790 GNUNET_assert (NULL != s5r->curl);
1791 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
1792 curl_download_prepare ();
1795 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
1797 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1798 "Finished processing UPLOAD\n");
1799 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1801 if (NULL == s5r->response)
1802 return MHD_YES; /* too early to queue response, did not yet get headers from cURL */
1803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1804 "Queueing response with MHD\n");
1805 return MHD_queue_response (con,
1811 /* ******************** MHD HTTP setup and event loop ******************** */
1815 * Function called when MHD decides that we are done with a connection.
1818 * @param connection connection handle
1819 * @param con_cls value as set by the last call to
1820 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
1821 * @param toe reason for request termination (ignored)
1824 mhd_completed_cb (void *cls,
1825 struct MHD_Connection *connection,
1827 enum MHD_RequestTerminationCode toe)
1829 struct Socks5Request *s5r = *con_cls;
1833 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
1834 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1835 "MHD encountered error handling request: %d\n",
1838 curl_download_prepare();
1844 * Function called when MHD first processes an incoming connection.
1845 * Gives us the respective URI information.
1847 * We use this to associate the `struct MHD_Connection` with our
1848 * internal `struct Socks5Request` data structure (by checking
1849 * for matching sockets).
1851 * @param cls the HTTP server handle (a `struct MhdHttpList`)
1852 * @param url the URL that is being requested
1853 * @param connection MHD connection object for the request
1854 * @return the `struct Socks5Request` that this @a connection is for
1857 mhd_log_callback (void *cls,
1859 struct MHD_Connection *connection)
1861 struct Socks5Request *s5r;
1862 const union MHD_ConnectionInfo *ci;
1865 ci = MHD_get_connection_info (connection,
1866 MHD_CONNECTION_INFO_CONNECTION_FD);
1872 sock = ci->connect_fd;
1873 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1875 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1877 if (NULL != s5r->url)
1882 s5r->url = GNUNET_strdup (url);
1883 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
1884 s5r->timeout_task = NULL;
1894 * Kill the given MHD daemon.
1896 * @param hd daemon to stop
1899 kill_httpd (struct MhdHttpList *hd)
1901 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1904 GNUNET_free_non_null (hd->domain);
1905 MHD_stop_daemon (hd->daemon);
1906 if (NULL != hd->httpd_task)
1908 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1909 hd->httpd_task = NULL;
1911 GNUNET_free_non_null (hd->proxy_cert);
1919 * Task run whenever HTTP server is idle for too long. Kill it.
1921 * @param cls the `struct MhdHttpList *`
1922 * @param tc sched context
1925 kill_httpd_task (void *cls,
1926 const struct GNUNET_SCHEDULER_TaskContext *tc)
1928 struct MhdHttpList *hd = cls;
1930 hd->httpd_task = NULL;
1936 * Task run whenever HTTP server operations are pending.
1938 * @param cls the `struct MhdHttpList *` of the daemon that is being run
1939 * @param tc sched context
1942 do_httpd (void *cls,
1943 const struct GNUNET_SCHEDULER_TaskContext *tc);
1947 * Schedule MHD. This function should be called initially when an
1948 * MHD is first getting its client socket, and will then automatically
1949 * always be called later whenever there is work to be done.
1951 * @param hd the daemon to schedule
1954 schedule_httpd (struct MhdHttpList *hd)
1959 struct GNUNET_NETWORK_FDSet *wrs;
1960 struct GNUNET_NETWORK_FDSet *wws;
1963 MHD_UNSIGNED_LONG_LONG timeout;
1964 struct GNUNET_TIME_Relative tv;
1970 if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1975 haveto = MHD_get_timeout (hd->daemon, &timeout);
1976 if (MHD_YES == haveto)
1977 tv.rel_value_us = (uint64_t) timeout * 1000LL;
1979 tv = GNUNET_TIME_UNIT_FOREVER_REL;
1982 wrs = GNUNET_NETWORK_fdset_create ();
1983 wws = GNUNET_NETWORK_fdset_create ();
1984 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1985 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1992 if (NULL != hd->httpd_task)
1993 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1994 if ( (MHD_YES != haveto) &&
1998 /* daemon is idle, kill after timeout */
1999 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
2006 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2011 GNUNET_NETWORK_fdset_destroy (wrs);
2013 GNUNET_NETWORK_fdset_destroy (wws);
2018 * Task run whenever HTTP server operations are pending.
2020 * @param cls the `struct MhdHttpList` of the daemon that is being run
2021 * @param tc scheduler context
2024 do_httpd (void *cls,
2025 const struct GNUNET_SCHEDULER_TaskContext *tc)
2027 struct MhdHttpList *hd = cls;
2029 hd->httpd_task = NULL;
2030 MHD_run (hd->daemon);
2031 schedule_httpd (hd);
2036 * Run MHD now, we have extra data ready for the callback.
2038 * @param hd the daemon to run now.
2041 run_mhd_now (struct MhdHttpList *hd)
2045 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2046 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
2052 * Read file in filename
2054 * @param filename file to read
2055 * @param size pointer where filesize is stored
2056 * @return NULL on error
2059 load_file (const char* filename,
2066 GNUNET_DISK_file_size (filename, &fsize,
2067 GNUNET_YES, GNUNET_YES))
2069 if (fsize > MAX_PEM_SIZE)
2071 *size = (unsigned int) fsize;
2072 buffer = GNUNET_malloc (*size);
2073 if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
2075 GNUNET_free (buffer);
2083 * Load PEM key from file
2085 * @param key where to store the data
2086 * @param keyfile path to the PEM file
2087 * @return #GNUNET_OK on success
2090 load_key_from_file (gnutls_x509_privkey_t key,
2091 const char* keyfile)
2093 gnutls_datum_t key_data;
2096 key_data.data = load_file (keyfile, &key_data.size);
2097 if (NULL == key_data.data)
2098 return GNUNET_SYSERR;
2099 ret = gnutls_x509_privkey_import (key, &key_data,
2100 GNUTLS_X509_FMT_PEM);
2101 if (GNUTLS_E_SUCCESS != ret)
2103 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2104 _("Unable to import private key from file `%s'\n"),
2107 GNUNET_free_non_null (key_data.data);
2108 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2113 * Load cert from file
2115 * @param crt struct to store data in
2116 * @param certfile path to pem file
2117 * @return #GNUNET_OK on success
2120 load_cert_from_file (gnutls_x509_crt_t crt,
2121 const char* certfile)
2123 gnutls_datum_t cert_data;
2126 cert_data.data = load_file (certfile, &cert_data.size);
2127 if (NULL == cert_data.data)
2128 return GNUNET_SYSERR;
2129 ret = gnutls_x509_crt_import (crt, &cert_data,
2130 GNUTLS_X509_FMT_PEM);
2131 if (GNUTLS_E_SUCCESS != ret)
2133 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2134 _("Unable to import certificate %s\n"), certfile);
2136 GNUNET_free_non_null (cert_data.data);
2137 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2142 * Generate new certificate for specific name
2144 * @param name the subject name to generate a cert for
2145 * @return a struct holding the PEM data, NULL on error
2147 static struct ProxyGNSCertificate *
2148 generate_gns_certificate (const char *name)
2150 unsigned int serial;
2151 size_t key_buf_size;
2152 size_t cert_buf_size;
2153 gnutls_x509_crt_t request;
2156 struct ProxyGNSCertificate *pgc;
2158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2159 "Generating TLS/SSL certificate for `%s'\n",
2161 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2162 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2163 pgc = GNUNET_new (struct ProxyGNSCertificate);
2164 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2166 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2167 0, "GNU Name System", 4);
2168 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2169 0, name, strlen (name));
2170 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
2171 gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2172 gnutls_x509_crt_set_serial (request,
2175 etime = time (NULL);
2176 tm_data = localtime (&etime);
2177 gnutls_x509_crt_set_activation_time (request,
2180 etime = mktime (tm_data);
2181 gnutls_x509_crt_set_expiration_time (request,
2183 gnutls_x509_crt_sign (request,
2186 key_buf_size = sizeof (pgc->key);
2187 cert_buf_size = sizeof (pgc->cert);
2188 gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2189 pgc->cert, &cert_buf_size);
2190 gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2191 pgc->key, &key_buf_size);
2192 gnutls_x509_crt_deinit (request);
2198 * Function called by MHD with errors, suppresses them all.
2200 * @param cls closure
2201 * @param fm format string (`printf()`-style)
2202 * @param ap arguments to @a fm
2205 mhd_error_log_callback (void *cls,
2214 * Lookup (or create) an SSL MHD instance for a particular domain.
2216 * @param domain the domain the SSL daemon has to serve
2217 * @return NULL on error
2219 static struct MhdHttpList *
2220 lookup_ssl_httpd (const char* domain)
2222 struct MhdHttpList *hd;
2223 struct ProxyGNSCertificate *pgc;
2230 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2231 if ( (NULL != hd->domain) &&
2232 (0 == strcmp (hd->domain, domain)) )
2234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2235 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2237 pgc = generate_gns_certificate (domain);
2238 hd = GNUNET_new (struct MhdHttpList);
2239 hd->is_ssl = GNUNET_YES;
2240 hd->domain = GNUNET_strdup (domain);
2241 hd->proxy_cert = pgc;
2242 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
2245 &create_response, hd,
2246 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2247 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2248 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2249 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2250 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2251 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2253 if (NULL == hd->daemon)
2259 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2267 * Task run when a Socks5Request somehow fails to be associated with
2268 * an MHD connection (i.e. because the client never speaks HTTP after
2269 * the SOCKS5 handshake). Clean up.
2271 * @param cls the `struct Socks5Request *`
2272 * @param tc sched context
2275 timeout_s5r_handshake (void *cls,
2276 const struct GNUNET_SCHEDULER_TaskContext *tc)
2278 struct Socks5Request *s5r = cls;
2280 s5r->timeout_task = NULL;
2286 * We're done with the Socks5 protocol, now we need to pass the
2287 * connection data through to the final destination, either
2288 * direct (if the protocol might not be HTTP), or via MHD
2289 * (if the port looks like it should be HTTP).
2291 * @param s5r socks request that has reached the final stage
2294 setup_data_transfer (struct Socks5Request *s5r)
2296 struct MhdHttpList *hd;
2298 const struct sockaddr *addr;
2304 hd = lookup_ssl_httpd (s5r->domain);
2307 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2308 _("Failed to start HTTPS server for `%s'\n"),
2316 GNUNET_assert (NULL != httpd);
2320 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2321 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2322 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2323 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2324 if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
2326 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2327 _("Failed to pass client to MHD\n"));
2332 schedule_httpd (hd);
2333 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2334 &timeout_s5r_handshake,
2339 /* ********************* SOCKS handling ************************* */
2343 * Write data from buffer to socks5 client, then continue with state machine.
2345 * @param cls the closure with the `struct Socks5Request`
2346 * @param tc scheduler context
2349 do_write (void *cls,
2350 const struct GNUNET_SCHEDULER_TaskContext *tc)
2352 struct Socks5Request *s5r = cls;
2356 len = GNUNET_NETWORK_socket_send (s5r->sock,
2361 /* write error: connection closed, shutdown, etc.; just clean up */
2367 s5r->wbuf_len - len);
2368 s5r->wbuf_len -= len;
2369 if (s5r->wbuf_len > 0)
2371 /* not done writing */
2373 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2379 /* we're done writing, continue with state machine! */
2386 case SOCKS5_REQUEST:
2387 GNUNET_assert (NULL != s5r->rtask);
2389 case SOCKS5_DATA_TRANSFER:
2390 setup_data_transfer (s5r);
2392 case SOCKS5_WRITE_THEN_CLEANUP:
2403 * Return a server response message indicating a failure to the client.
2405 * @param s5r request to return failure code for
2406 * @param sc status code to return
2409 signal_socks_failure (struct Socks5Request *s5r,
2410 enum Socks5StatusCode sc)
2412 struct Socks5ServerResponseMessage *s_resp;
2414 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2415 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2416 s_resp->version = SOCKS_VERSION_5;
2418 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2419 if (NULL != s5r->wtask)
2421 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2428 * Return a server response message indicating success.
2430 * @param s5r request to return success status message for
2433 signal_socks_success (struct Socks5Request *s5r)
2435 struct Socks5ServerResponseMessage *s_resp;
2437 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2438 s_resp->version = SOCKS_VERSION_5;
2439 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2440 s_resp->reserved = 0;
2441 s_resp->addr_type = SOCKS5_AT_IPV4;
2442 /* zero out IPv4 address and port */
2445 sizeof (struct in_addr) + sizeof (uint16_t));
2446 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2447 sizeof (struct in_addr) + sizeof (uint16_t);
2448 if (NULL == s5r->wtask)
2450 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2457 * Process GNS results for target domain.
2459 * @param cls the `struct Socks5Request *`
2460 * @param rd_count number of records returned
2461 * @param rd record data
2464 handle_gns_result (void *cls,
2466 const struct GNUNET_GNSRECORD_Data *rd)
2468 struct Socks5Request *s5r = cls;
2470 const struct GNUNET_GNSRECORD_Data *r;
2473 s5r->gns_lookup = NULL;
2475 for (i=0;i<rd_count;i++)
2478 switch (r->record_type)
2480 case GNUNET_DNSPARSER_TYPE_A:
2482 struct sockaddr_in *in;
2484 if (sizeof (struct in_addr) != r->data_size)
2486 GNUNET_break_op (0);
2489 if (GNUNET_YES == got_ip)
2492 GNUNET_NETWORK_test_pf (PF_INET))
2494 got_ip = GNUNET_YES;
2495 in = (struct sockaddr_in *) &s5r->destination_address;
2496 in->sin_family = AF_INET;
2497 memcpy (&in->sin_addr,
2500 in->sin_port = htons (s5r->port);
2501 #if HAVE_SOCKADDR_IN_SIN_LEN
2502 in->sin_len = sizeof (*in);
2506 case GNUNET_DNSPARSER_TYPE_AAAA:
2508 struct sockaddr_in6 *in;
2510 if (sizeof (struct in6_addr) != r->data_size)
2512 GNUNET_break_op (0);
2515 if (GNUNET_YES == got_ip)
2518 GNUNET_NETWORK_test_pf (PF_INET))
2520 /* FIXME: allow user to disable IPv6 per configuration option... */
2521 got_ip = GNUNET_YES;
2522 in = (struct sockaddr_in6 *) &s5r->destination_address;
2523 in->sin6_family = AF_INET6;
2524 memcpy (&in->sin6_addr,
2527 in->sin6_port = htons (s5r->port);
2528 #if HAVE_SOCKADDR_IN_SIN_LEN
2529 in->sin6_len = sizeof (*in);
2533 case GNUNET_GNSRECORD_TYPE_VPN:
2534 GNUNET_break (0); /* should have been translated within GNS */
2536 case GNUNET_GNSRECORD_TYPE_LEHO:
2537 GNUNET_free_non_null (s5r->leho);
2538 s5r->leho = GNUNET_strndup (r->data,
2541 case GNUNET_GNSRECORD_TYPE_BOX:
2543 const struct GNUNET_GNSRECORD_BoxRecord *box;
2545 if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
2547 GNUNET_break_op (0);
2551 if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
2552 (ntohs (box->protocol) != IPPROTO_TCP) ||
2553 (ntohs (box->service) != s5r->port) )
2554 break; /* BOX record does not apply */
2555 GNUNET_free_non_null (s5r->dane_data);
2556 s5r->dane_data_len = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
2557 s5r->dane_data = GNUNET_malloc (s5r->dane_data_len);
2558 memcpy (s5r->dane_data,
2560 s5r->dane_data_len);
2568 if (GNUNET_YES != got_ip)
2570 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2571 "Name resolution failed to yield useful IP address.\n");
2572 signal_socks_failure (s5r,
2573 SOCKS5_STATUS_GENERAL_FAILURE);
2576 s5r->state = SOCKS5_DATA_TRANSFER;
2577 signal_socks_success (s5r);
2582 * Remove the first @a len bytes from the beginning of the read buffer.
2584 * @param s5r the handle clear the read buffer for
2585 * @param len number of bytes in read buffer to advance
2588 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2591 GNUNET_assert (len <= s5r->rbuf_len);
2594 s5r->rbuf_len - len);
2595 s5r->rbuf_len -= len;
2600 * Read data from incoming Socks5 connection
2602 * @param cls the closure with the `struct Socks5Request`
2603 * @param tc the scheduler context
2606 do_s5r_read (void *cls,
2607 const struct GNUNET_SCHEDULER_TaskContext *tc)
2609 struct Socks5Request *s5r = cls;
2610 const struct Socks5ClientHelloMessage *c_hello;
2611 struct Socks5ServerHelloMessage *s_hello;
2612 const struct Socks5ClientRequestMessage *c_req;
2617 if ( (NULL != tc->read_ready) &&
2618 (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2620 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2621 &s5r->rbuf[s5r->rbuf_len],
2622 sizeof (s5r->rbuf) - s5r->rbuf_len);
2625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2626 "socks5 client disconnected.\n");
2630 s5r->rbuf_len += rlen;
2632 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2636 "Processing %u bytes of socks data in state %d\n",
2642 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2643 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2644 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2645 return; /* need more data */
2646 if (SOCKS_VERSION_5 != c_hello->version)
2648 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2649 _("Unsupported socks version %d\n"),
2650 (int) c_hello->version);
2654 clear_from_s5r_rbuf (s5r,
2655 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2656 GNUNET_assert (0 == s5r->wbuf_len);
2657 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2658 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2659 s_hello->version = SOCKS_VERSION_5;
2660 s_hello->auth_method = SOCKS_AUTH_NONE;
2661 GNUNET_assert (NULL == s5r->wtask);
2662 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2665 s5r->state = SOCKS5_REQUEST;
2667 case SOCKS5_REQUEST:
2668 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2669 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2671 switch (c_req->command)
2673 case SOCKS5_CMD_TCP_STREAM:
2677 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2678 _("Unsupported socks command %d\n"),
2679 (int) c_req->command);
2680 signal_socks_failure (s5r,
2681 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2684 switch (c_req->addr_type)
2686 case SOCKS5_AT_IPV4:
2688 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2689 const uint16_t *port = (const uint16_t *) &v4[1];
2690 struct sockaddr_in *in;
2692 s5r->port = ntohs (*port);
2693 if (HTTPS_PORT == s5r->port)
2695 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2696 _("SSL connection to plain IPv4 address requested\n"));
2697 signal_socks_failure (s5r,
2698 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2701 alen = sizeof (struct in_addr);
2702 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2703 alen + sizeof (uint16_t))
2704 return; /* need more data */
2705 in = (struct sockaddr_in *) &s5r->destination_address;
2706 in->sin_family = AF_INET;
2708 in->sin_port = *port;
2709 #if HAVE_SOCKADDR_IN_SIN_LEN
2710 in->sin_len = sizeof (*in);
2712 s5r->state = SOCKS5_DATA_TRANSFER;
2715 case SOCKS5_AT_IPV6:
2717 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2718 const uint16_t *port = (const uint16_t *) &v6[1];
2719 struct sockaddr_in6 *in;
2721 s5r->port = ntohs (*port);
2722 if (HTTPS_PORT == s5r->port)
2724 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2725 _("SSL connection to plain IPv4 address requested\n"));
2726 signal_socks_failure (s5r,
2727 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2730 alen = sizeof (struct in6_addr);
2731 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2732 alen + sizeof (uint16_t))
2733 return; /* need more data */
2734 in = (struct sockaddr_in6 *) &s5r->destination_address;
2735 in->sin6_family = AF_INET6;
2736 in->sin6_addr = *v6;
2737 in->sin6_port = *port;
2738 #if HAVE_SOCKADDR_IN_SIN_LEN
2739 in->sin6_len = sizeof (*in);
2741 s5r->state = SOCKS5_DATA_TRANSFER;
2744 case SOCKS5_AT_DOMAINNAME:
2746 const uint8_t *dom_len;
2747 const char *dom_name;
2748 const uint16_t *port;
2750 dom_len = (const uint8_t *) &c_req[1];
2751 alen = *dom_len + 1;
2752 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2753 alen + sizeof (uint16_t))
2754 return; /* need more data */
2755 dom_name = (const char *) &dom_len[1];
2756 port = (const uint16_t*) &dom_name[*dom_len];
2757 s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2759 "Requested connection is to %s:%d\n",
2762 s5r->state = SOCKS5_RESOLVING;
2763 s5r->port = ntohs (*port);
2764 s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2767 GNUNET_DNSPARSER_TYPE_A,
2768 GNUNET_NO /* only cached */,
2769 (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2775 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2776 _("Unsupported socks address type %d\n"),
2777 (int) c_req->addr_type);
2778 signal_socks_failure (s5r,
2779 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2782 clear_from_s5r_rbuf (s5r,
2783 sizeof (struct Socks5ClientRequestMessage) +
2784 alen + sizeof (uint16_t));
2785 if (0 != s5r->rbuf_len)
2787 /* read more bytes than healthy, why did the client send more!? */
2788 GNUNET_break_op (0);
2789 signal_socks_failure (s5r,
2790 SOCKS5_STATUS_GENERAL_FAILURE);
2793 if (SOCKS5_DATA_TRANSFER == s5r->state)
2795 /* if we are not waiting for GNS resolution, signal success */
2796 signal_socks_success (s5r);
2798 /* We are done reading right now */
2799 GNUNET_SCHEDULER_cancel (s5r->rtask);
2802 case SOCKS5_RESOLVING:
2805 case SOCKS5_DATA_TRANSFER:
2816 * Accept new incoming connections
2818 * @param cls the closure with the lsock4 or lsock6
2819 * @param tc the scheduler context
2822 do_accept (void *cls,
2823 const struct GNUNET_SCHEDULER_TaskContext *tc)
2825 struct GNUNET_NETWORK_Handle *lsock = cls;
2826 struct GNUNET_NETWORK_Handle *s;
2827 struct Socks5Request *s5r;
2829 if (lsock == lsock4)
2833 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2835 if (lsock == lsock4)
2836 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2840 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2843 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2846 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2850 "Got an inbound connection, waiting for data\n");
2851 s5r = GNUNET_new (struct Socks5Request);
2852 GNUNET_CONTAINER_DLL_insert (s5r_head,
2856 s5r->state = SOCKS5_INIT;
2857 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2863 /* ******************* General / main code ********************* */
2867 * Task run on shutdown
2869 * @param cls closure
2870 * @param tc task context
2873 do_shutdown (void *cls,
2874 const struct GNUNET_SCHEDULER_TaskContext *tc)
2876 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2877 "Shutting down...\n");
2878 while (NULL != mhd_httpd_head)
2879 kill_httpd (mhd_httpd_head);
2880 while (NULL != s5r_head)
2881 cleanup_s5r (s5r_head);
2884 GNUNET_NETWORK_socket_close (lsock4);
2889 GNUNET_NETWORK_socket_close (lsock6);
2894 GNUNET_IDENTITY_cancel (id_op);
2897 if (NULL != identity)
2899 GNUNET_IDENTITY_disconnect (identity);
2902 if (NULL != curl_multi)
2904 curl_multi_cleanup (curl_multi);
2907 if (NULL != gns_handle)
2909 GNUNET_GNS_disconnect (gns_handle);
2912 if (NULL != curl_download_task)
2914 GNUNET_SCHEDULER_cancel (curl_download_task);
2915 curl_download_task = NULL;
2919 GNUNET_SCHEDULER_cancel (ltask4);
2924 GNUNET_SCHEDULER_cancel (ltask6);
2927 gnutls_x509_crt_deinit (proxy_ca.cert);
2928 gnutls_x509_privkey_deinit (proxy_ca.key);
2929 gnutls_global_deinit ();
2934 * Create an IPv4 listen socket bound to our port.
2936 * @return NULL on error
2938 static struct GNUNET_NETWORK_Handle *
2941 struct GNUNET_NETWORK_Handle *ls;
2942 struct sockaddr_in sa4;
2945 memset (&sa4, 0, sizeof (sa4));
2946 sa4.sin_family = AF_INET;
2947 sa4.sin_port = htons (port);
2948 #if HAVE_SOCKADDR_IN_SIN_LEN
2949 sa4.sin_len = sizeof (sa4);
2951 ls = GNUNET_NETWORK_socket_create (AF_INET,
2957 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
2961 GNUNET_NETWORK_socket_close (ls);
2970 * Create an IPv6 listen socket bound to our port.
2972 * @return NULL on error
2974 static struct GNUNET_NETWORK_Handle *
2977 struct GNUNET_NETWORK_Handle *ls;
2978 struct sockaddr_in6 sa6;
2981 memset (&sa6, 0, sizeof (sa6));
2982 sa6.sin6_family = AF_INET6;
2983 sa6.sin6_port = htons (port);
2984 #if HAVE_SOCKADDR_IN_SIN_LEN
2985 sa6.sin6_len = sizeof (sa6);
2987 ls = GNUNET_NETWORK_socket_create (AF_INET6,
2993 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
2997 GNUNET_NETWORK_socket_close (ls);
3006 * Continue initialization after we have our zone information.
3011 struct MhdHttpList *hd;
3013 /* Open listen socket for socks proxy */
3014 lsock6 = bind_v6 ();
3016 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
3019 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
3021 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
3022 GNUNET_NETWORK_socket_close (lsock6);
3027 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3028 lsock6, &do_accept, lsock6);
3031 lsock4 = bind_v4 ();
3033 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
3036 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
3038 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
3039 GNUNET_NETWORK_socket_close (lsock4);
3044 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3045 lsock4, &do_accept, lsock4);
3048 if ( (NULL == lsock4) &&
3051 GNUNET_SCHEDULER_shutdown ();
3054 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3056 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3057 "cURL global init failed!\n");
3058 GNUNET_SCHEDULER_shutdown ();
3061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3062 "Proxy listens on port %u\n",
3065 /* start MHD daemon for HTTP */
3066 hd = GNUNET_new (struct MhdHttpList);
3067 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
3070 &create_response, hd,
3071 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3072 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3073 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3075 if (NULL == hd->daemon)
3078 GNUNET_SCHEDULER_shutdown ();
3082 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
3087 * Method called to inform about the egos of the shorten zone of this peer.
3089 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
3090 * this function is only called ONCE, and 'NULL' being passed in
3091 * @a ego does indicate an error (i.e. name is taken or no default
3092 * value is known). If @a ego is non-NULL and if '*ctx'
3093 * is set in those callbacks, the value WILL be passed to a subsequent
3094 * call to the identity callback of #GNUNET_IDENTITY_connect (if
3095 * that one was not NULL).
3097 * @param cls closure, NULL
3098 * @param ego ego handle
3099 * @param ctx context for application to store data for this ego
3100 * (during the lifetime of this process, initially NULL)
3101 * @param name name assigned by the user for this ego,
3102 * NULL if the user just deleted the ego and it
3103 * must thus no longer be used
3106 identity_shorten_cb (void *cls,
3107 struct GNUNET_IDENTITY_Ego *ego,
3114 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3115 _("No ego configured for `shorten-zone`\n"));
3119 local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
3120 do_shorten = GNUNET_YES;
3127 * Method called to inform about the egos of the master zone of this peer.
3129 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
3130 * this function is only called ONCE, and 'NULL' being passed in
3131 * @a ego does indicate an error (i.e. name is taken or no default
3132 * value is known). If @a ego is non-NULL and if '*ctx'
3133 * is set in those callbacks, the value WILL be passed to a subsequent
3134 * call to the identity callback of #GNUNET_IDENTITY_connect (if
3135 * that one was not NULL).
3137 * @param cls closure, NULL
3138 * @param ego ego handle
3139 * @param ctx context for application to store data for this ego
3140 * (during the lifetime of this process, initially NULL)
3141 * @param name name assigned by the user for this ego,
3142 * NULL if the user just deleted the ego and it
3143 * must thus no longer be used
3146 identity_master_cb (void *cls,
3147 struct GNUNET_IDENTITY_Ego *ego,
3154 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3155 _("No ego configured for `%s`\n"),
3157 GNUNET_SCHEDULER_shutdown ();
3160 GNUNET_IDENTITY_ego_get_public_key (ego,
3162 id_op = GNUNET_IDENTITY_get (identity,
3164 &identity_shorten_cb,
3170 * Main function that will be run
3172 * @param cls closure
3173 * @param args remaining command-line arguments
3174 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3175 * @param c configuration
3178 run (void *cls, char *const *args, const char *cfgfile,
3179 const struct GNUNET_CONFIGURATION_Handle *c)
3181 char* cafile_cfg = NULL;
3186 if (NULL == (curl_multi = curl_multi_init ()))
3188 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3189 "Failed to create cURL multi handle!\n");
3192 cafile = cafile_opt;
3195 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3199 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3204 cafile = cafile_cfg;
3206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3207 "Using %s as CA\n", cafile);
3209 gnutls_global_init ();
3210 gnutls_x509_crt_init (&proxy_ca.cert);
3211 gnutls_x509_privkey_init (&proxy_ca.key);
3213 if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
3214 (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
3216 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3217 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
3219 gnutls_x509_crt_deinit (proxy_ca.cert);
3220 gnutls_x509_privkey_deinit (proxy_ca.key);
3221 gnutls_global_deinit ();
3222 GNUNET_free_non_null (cafile_cfg);
3225 GNUNET_free_non_null (cafile_cfg);
3226 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3228 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3229 "Unable to connect to GNS!\n");
3230 gnutls_x509_crt_deinit (proxy_ca.cert);
3231 gnutls_x509_privkey_deinit (proxy_ca.key);
3232 gnutls_global_deinit ();
3235 identity = GNUNET_IDENTITY_connect (cfg,
3237 id_op = GNUNET_IDENTITY_get (identity,
3239 &identity_master_cb,
3241 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
3242 &do_shutdown, NULL);
3247 * The main function for gnunet-gns-proxy.
3249 * @param argc number of arguments from the command line
3250 * @param argv command line arguments
3251 * @return 0 ok, 1 on error
3254 main (int argc, char *const *argv)
3256 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3258 gettext_noop ("listen on specified port (default: 7777)"), 1,
3259 &GNUNET_GETOPT_set_ulong, &port},
3260 {'a', "authority", NULL,
3261 gettext_noop ("pem file to use as CA"), 1,
3262 &GNUNET_GETOPT_set_string, &cafile_opt},
3263 GNUNET_GETOPT_OPTION_END
3265 static const char* page =
3266 "<html><head><title>gnunet-gns-proxy</title>"
3267 "</head><body>cURL fail</body></html>";
3270 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3272 GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3273 curl_failure_response = MHD_create_response_from_buffer (strlen (page),
3275 MHD_RESPMEM_PERSISTENT);
3279 GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3280 _("GNUnet GNS proxy"),
3282 &run, NULL)) ? 0 : 1;
3283 MHD_destroy_response (curl_failure_response);
3284 GNUNET_free_non_null ((char *) argv);
3285 GNUNET_CRYPTO_ecdsa_key_clear (&local_shorten_zone);
3289 /* end of gnunet-gns-proxy.c */