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 SSL/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 SSL)
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
435 * A structure for socks requests
443 struct Socks5Request *next;
448 struct Socks5Request *prev;
453 struct GNUNET_NETWORK_Handle *sock;
456 * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
458 struct GNUNET_GNS_LookupRequest *gns_lookup;
461 * Client socket read task
463 struct GNUNET_SCHEDULER_Task * rtask;
466 * Client socket write task
468 struct GNUNET_SCHEDULER_Task * wtask;
473 struct GNUNET_SCHEDULER_Task * timeout_task;
478 char rbuf[SOCKS_BUFFERSIZE];
483 char wbuf[SOCKS_BUFFERSIZE];
486 * Buffer we use for moving data between MHD and curl (in both directions).
488 char io_buf[IO_BUFFERSIZE];
491 * MHD HTTP instance handling this request, NULL for none.
493 struct MhdHttpList *hd;
496 * MHD response object for this request.
498 struct MHD_Response *response;
501 * the domain name to server (only important for SSL)
506 * DNS Legacy Host Name as given by GNS, NULL if not given.
511 * Payload of the (last) DANE record encountered.
526 * HTTP request headers for the curl request.
528 struct curl_slist *headers;
531 * DNS->IP mappings resolved through GNS
533 struct curl_slist *hosts;
536 * HTTP response code to give to MHD for the response.
538 unsigned int response_code;
541 * Number of bytes in @e dane_data.
543 size_t dane_data_len;
546 * Number of bytes already in read buffer
551 * Number of bytes already in write buffer
556 * Number of bytes already in the IO buffer.
561 * Once known, what's the target address for the connection?
563 struct sockaddr_storage destination_address;
568 enum SocksPhase state;
571 * Desired destination port.
579 /* *********************** Globals **************************** */
583 * The port the proxy is running on (default 7777)
585 static unsigned long port = GNUNET_GNS_PROXY_PORT;
588 * The CA file (pem) to use for the proxy CA
590 static char *cafile_opt;
593 * The listen socket of the proxy for IPv4
595 static struct GNUNET_NETWORK_Handle *lsock4;
598 * The listen socket of the proxy for IPv6
600 static struct GNUNET_NETWORK_Handle *lsock6;
603 * The listen task ID for IPv4
605 static struct GNUNET_SCHEDULER_Task * ltask4;
608 * The listen task ID for IPv6
610 static struct GNUNET_SCHEDULER_Task * ltask6;
613 * The cURL download task (curl multi API).
615 static struct GNUNET_SCHEDULER_Task * curl_download_task;
618 * The cURL multi handle
620 static CURLM *curl_multi;
623 * Handle to the GNS service
625 static struct GNUNET_GNS_Handle *gns_handle;
628 * DLL for http/https daemons
630 static struct MhdHttpList *mhd_httpd_head;
633 * DLL for http/https daemons
635 static struct MhdHttpList *mhd_httpd_tail;
638 * Daemon for HTTP (we have one per SSL certificate, and then one for
639 * all HTTP connections; this is the one for HTTP, not HTTPS).
641 static struct MhdHttpList *httpd;
644 * DLL of active socks requests.
646 static struct Socks5Request *s5r_head;
649 * DLL of active socks requests.
651 static struct Socks5Request *s5r_tail;
654 * The users local GNS master zone
656 static struct GNUNET_CRYPTO_EcdsaPublicKey local_gns_zone;
659 * The users local shorten zone
661 static struct GNUNET_CRYPTO_EcdsaPrivateKey local_shorten_zone;
664 * Is shortening enabled?
666 static int do_shorten;
669 * The CA for SSL certificate generation
671 static struct ProxyCA proxy_ca;
674 * Response we return on cURL failures.
676 static struct MHD_Response *curl_failure_response;
679 * Connection to identity service.
681 static struct GNUNET_IDENTITY_Handle *identity;
684 * Request for our ego.
686 static struct GNUNET_IDENTITY_Operation *id_op;
691 static const struct GNUNET_CONFIGURATION_Handle *cfg;
694 /* ************************* Global helpers ********************* */
698 * Run MHD now, we have extra data ready for the callback.
700 * @param hd the daemon to run now.
703 run_mhd_now (struct MhdHttpList *hd);
707 * Clean up s5r handles.
709 * @param s5r the handle to destroy
712 cleanup_s5r (struct Socks5Request *s5r)
714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
715 "Cleaning up socks request\n");
716 if (NULL != s5r->curl)
718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
719 "Cleaning up cURL handle\n");
720 curl_multi_remove_handle (curl_multi, s5r->curl);
721 curl_easy_cleanup (s5r->curl);
724 curl_slist_free_all (s5r->headers);
725 if (NULL != s5r->hosts)
727 curl_slist_free_all (s5r->hosts);
729 if ( (NULL != s5r->response) &&
730 (curl_failure_response != s5r->response) )
731 MHD_destroy_response (s5r->response);
732 if (NULL != s5r->rtask)
733 GNUNET_SCHEDULER_cancel (s5r->rtask);
734 if (NULL != s5r->timeout_task)
735 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
736 if (NULL != s5r->wtask)
737 GNUNET_SCHEDULER_cancel (s5r->wtask);
738 if (NULL != s5r->gns_lookup)
739 GNUNET_GNS_lookup_cancel (s5r->gns_lookup);
740 if (NULL != s5r->sock)
742 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
743 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
745 GNUNET_NETWORK_socket_close (s5r->sock);
747 GNUNET_CONTAINER_DLL_remove (s5r_head,
750 GNUNET_free_non_null (s5r->domain);
751 GNUNET_free_non_null (s5r->leho);
752 GNUNET_free_non_null (s5r->url);
753 GNUNET_free_non_null (s5r->dane_data);
758 /* ************************* HTTP handling with cURL *********************** */
762 * Callback for MHD response generation. This function is called from
763 * MHD whenever MHD expects to get data back. Copies data from the
764 * io_buf, if available.
766 * @param cls closure with our `struct Socks5Request`
767 * @param pos in buffer
768 * @param buf where to copy data
769 * @param max available space in @a buf
770 * @return number of bytes written to @a buf
773 mhd_content_cb (void *cls,
778 struct Socks5Request *s5r = cls;
779 size_t bytes_to_copy;
781 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
782 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
784 /* we're still not done with the upload, do not yet
785 start the download, the IO buffer is still full
787 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
788 "Pausing MHD download, not yet ready for download\n");
789 return 0; /* not yet ready for data download */
791 bytes_to_copy = GNUNET_MIN (max,
793 if ( (0 == bytes_to_copy) &&
794 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
797 "Pausing MHD download, no data available\n");
798 return 0; /* more data later */
800 if ( (0 == bytes_to_copy) &&
801 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
804 "Completed MHD download\n");
805 return MHD_CONTENT_READER_END_OF_STREAM;
807 GNUNET_memcpy (buf, s5r->io_buf, bytes_to_copy);
808 memmove (s5r->io_buf,
809 &s5r->io_buf[bytes_to_copy],
810 s5r->io_len - bytes_to_copy);
811 s5r->io_len -= bytes_to_copy;
812 if (NULL != s5r->curl)
813 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
814 return bytes_to_copy;
819 * Check that the website has presented us with a valid SSL certificate.
820 * The certificate must either match the domain name or the LEHO name
821 * (or, if available, the TLSA record).
823 * @param s5r request to check for.
824 * @return #GNUNET_OK if the certificate is valid
827 check_ssl_certificate (struct Socks5Request *s5r)
829 unsigned int cert_list_size;
830 const gnutls_datum_t *chainp;
831 const struct curl_tlssessioninfo *tlsinfo;
832 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
834 gnutls_x509_crt_t x509_cert;
839 curl_easy_getinfo (s5r->curl,
840 CURLINFO_TLS_SESSION,
841 (struct curl_slist **) &tlsinfo))
842 return GNUNET_SYSERR;
843 if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
845 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
846 _("Unsupported CURL SSL backend %d\n"),
848 return GNUNET_SYSERR;
850 chainp = gnutls_certificate_get_peers (tlsinfo->internals, &cert_list_size);
851 if ( (! chainp) || (0 == cert_list_size) )
852 return GNUNET_SYSERR;
854 size = sizeof (certdn);
855 /* initialize an X.509 certificate structure. */
856 gnutls_x509_crt_init (&x509_cert);
857 gnutls_x509_crt_import (x509_cert,
859 GNUTLS_X509_FMT_DER);
861 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
862 GNUTLS_OID_X520_COMMON_NAME,
863 0, /* the first and only one */
864 0 /* no DER encoding */,
868 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
869 _("Failed to fetch CN from cert: %s\n"),
870 gnutls_strerror(rc));
871 gnutls_x509_crt_deinit (x509_cert);
872 return GNUNET_SYSERR;
874 /* check for TLSA/DANE records */
876 if (NULL != s5r->dane_data)
878 char *dd[] = { s5r->dane_data, NULL };
879 int dlen[] = { s5r->dane_data_len, 0};
880 dane_state_t dane_state;
881 dane_query_t dane_query;
884 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
885 if (0 != (rc = dane_state_init (&dane_state,
886 #ifdef DANE_F_IGNORE_DNSSEC
887 DANE_F_IGNORE_DNSSEC |
889 DANE_F_IGNORE_LOCAL_RESOLVER)))
891 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
892 _("Failed to initialize DANE: %s\n"),
894 gnutls_x509_crt_deinit (x509_cert);
895 return GNUNET_SYSERR;
897 if (0 != (rc = dane_raw_tlsa (dane_state,
904 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
905 _("Failed to parse DANE record: %s\n"),
907 dane_state_deinit (dane_state);
908 gnutls_x509_crt_deinit (x509_cert);
909 return GNUNET_SYSERR;
911 if (0 != (rc = dane_verify_crt_raw (dane_state,
914 gnutls_certificate_type_get (tlsinfo->internals),
919 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
920 _("Failed to verify TLS connection using DANE: %s\n"),
922 dane_query_deinit (dane_query);
923 dane_state_deinit (dane_state);
924 gnutls_x509_crt_deinit (x509_cert);
925 return GNUNET_SYSERR;
929 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
930 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
932 dane_query_deinit (dane_query);
933 dane_state_deinit (dane_state);
934 gnutls_x509_crt_deinit (x509_cert);
935 return GNUNET_SYSERR;
937 dane_query_deinit (dane_query);
938 dane_state_deinit (dane_state);
944 /* try LEHO or ordinary domain name X509 verification */
946 if (NULL != s5r->leho)
950 if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
953 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
954 _("SSL certificate subject name (%s) does not match `%s'\n"),
957 gnutls_x509_crt_deinit (x509_cert);
958 return GNUNET_SYSERR;
963 /* we did not even have the domain name!? */
965 return GNUNET_SYSERR;
968 gnutls_x509_crt_deinit (x509_cert);
974 * We're getting an HTTP response header from cURL. Convert it to the
975 * MHD response headers. Mostly copies the headers, but makes special
976 * adjustments to "Set-Cookie" and "Location" headers as those may need
977 * to be changed from the LEHO to the domain the browser expects.
979 * @param buffer curl buffer with a single line of header data; not 0-terminated!
980 * @param size curl blocksize
981 * @param nmemb curl blocknumber
982 * @param cls our `struct Socks5Request *`
983 * @return size of processed bytes
986 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
988 struct Socks5Request *s5r = cls;
989 size_t bytes = size * nmemb;
991 const char *hdr_type;
992 const char *cookie_domain;
995 char *new_cookie_hdr;
998 size_t delta_cdomain;
1002 if (NULL == s5r->response)
1004 /* first, check SSL certificate */
1005 if ( (HTTPS_PORT == s5r->port) &&
1006 (GNUNET_OK != check_ssl_certificate (s5r)) )
1009 GNUNET_break (CURLE_OK ==
1010 curl_easy_getinfo (s5r->curl,
1011 CURLINFO_RESPONSE_CODE,
1013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014 "Creating MHD response with code %d\n",
1016 s5r->response_code = resp_code;
1017 s5r->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
1022 if (NULL != s5r->leho)
1026 GNUNET_asprintf (&cors_hdr,
1027 (HTTPS_PORT == s5r->port)
1032 GNUNET_break (MHD_YES ==
1033 MHD_add_response_header (s5r->response,
1034 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1036 GNUNET_free (cors_hdr);
1038 /* force connection to be closed after each request, as we
1039 do not support HTTP pipelining (yet, FIXME!) */
1040 /*GNUNET_break (MHD_YES ==
1041 MHD_add_response_header (s5r->response,
1042 MHD_HTTP_HEADER_CONNECTION,
1046 ndup = GNUNET_strndup (buffer, bytes);
1047 hdr_type = strtok (ndup, ":");
1048 if (NULL == hdr_type)
1053 hdr_val = strtok (NULL, "");
1054 if (NULL == hdr_val)
1059 if (' ' == *hdr_val)
1062 /* custom logic for certain header types */
1063 new_cookie_hdr = NULL;
1064 if ( (NULL != s5r->leho) &&
1065 (0 == strcasecmp (hdr_type,
1066 MHD_HTTP_HEADER_SET_COOKIE)) )
1069 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1070 strlen (s5r->domain) + 1);
1072 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1073 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1075 if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
1076 (GNUNET_NO == domain_matched) )
1078 domain_matched = GNUNET_YES;
1079 cookie_domain = tok + strlen (" domain") + 1;
1080 if (strlen (cookie_domain) < strlen (s5r->leho))
1082 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1083 if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
1085 offset += sprintf (new_cookie_hdr + offset,
1091 else if (0 == strcmp (cookie_domain, s5r->leho))
1093 offset += sprintf (new_cookie_hdr + offset,
1098 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1099 _("Cookie domain `%s' supplied by server is invalid\n"),
1102 GNUNET_memcpy (new_cookie_hdr + offset, tok, strlen (tok));
1103 offset += strlen (tok);
1104 new_cookie_hdr[offset++] = ';';
1106 hdr_val = new_cookie_hdr;
1109 new_location = NULL;
1110 if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
1114 GNUNET_asprintf (&leho_host,
1115 (HTTPS_PORT != s5r->port)
1119 if (0 == strncmp (leho_host,
1121 strlen (leho_host)))
1123 GNUNET_asprintf (&new_location,
1125 (HTTPS_PORT != s5r->port)
1129 hdr_val + strlen (leho_host));
1130 hdr_val = new_location;
1132 GNUNET_free (leho_host);
1134 /* MHD does not allow certain characters in values, remove those */
1135 if (NULL != (tok = strchr (hdr_val, '\n')))
1137 if (NULL != (tok = strchr (hdr_val, '\r')))
1139 if (NULL != (tok = strchr (hdr_val, '\t')))
1141 if ((0 != strlen (hdr_val) ) &&
1142 (0 != strcasecmp (MHD_HTTP_HEADER_CONTENT_LENGTH, hdr_type)))
1144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1145 "Adding header %s: %s to MHD response\n",
1148 GNUNET_break (MHD_YES ==
1149 MHD_add_response_header (s5r->response,
1154 GNUNET_free_non_null (new_cookie_hdr);
1155 GNUNET_free_non_null (new_location);
1161 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1162 * it available to MHD.
1164 * @param ptr pointer to the data
1165 * @param size number of blocks of data
1166 * @param nmemb blocksize
1167 * @param ctx our `struct Socks5Request *`
1168 * @return number of bytes handled
1171 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1173 struct Socks5Request *s5r = ctx;
1174 size_t total = size * nmemb;
1176 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1177 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1179 /* we're still not done with the upload, do not yet
1180 start the download, the IO buffer is still full
1181 with upload data. */
1182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1183 "Pausing CURL download, waiting for UPLOAD to finish\n");
1184 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1186 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1189 "Pausing CURL download, not enough space\n");
1190 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1192 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1195 s5r->io_len += total;
1196 if (s5r->io_len == total)
1197 run_mhd_now (s5r->hd);
1203 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1204 * to make it available to MHD.
1206 * @param buf where to write the data
1207 * @param size number of bytes per member
1208 * @param nmemb number of members available in @a buf
1209 * @param cls our `struct Socks5Request` that generated the data
1210 * @return number of bytes copied to @a buf
1213 curl_upload_cb (void *buf, size_t size, size_t nmemb, void *cls)
1215 struct Socks5Request *s5r = cls;
1216 size_t len = size * nmemb;
1219 if ( (0 == s5r->io_len) &&
1220 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1223 "Pausing CURL UPLOAD, need more data\n");
1224 return CURL_READFUNC_PAUSE;
1226 if ( (0 == s5r->io_len) &&
1227 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1229 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1231 "Completed CURL UPLOAD\n");
1232 return 0; /* upload finished, can now download */
1234 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) &&
1235 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1238 return CURL_READFUNC_ABORT;
1240 to_copy = GNUNET_MIN (s5r->io_len,
1242 GNUNET_memcpy (buf, s5r->io_buf, to_copy);
1243 memmove (s5r->io_buf,
1244 &s5r->io_buf[to_copy],
1245 s5r->io_len - to_copy);
1246 s5r->io_len -= to_copy;
1247 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1248 run_mhd_now (s5r->hd); /* got more space for upload now */
1253 /* ************************** main loop of cURL interaction ****************** */
1257 * Task that is run when we are ready to receive more data
1260 * @param cls closure
1263 curl_task_download (void *cls);
1267 * Ask cURL for the select() sets and schedule cURL operations.
1270 curl_download_prepare ()
1277 struct GNUNET_NETWORK_FDSet *grs;
1278 struct GNUNET_NETWORK_FDSet *gws;
1280 struct GNUNET_TIME_Relative rtime;
1282 if (NULL != curl_download_task)
1284 GNUNET_SCHEDULER_cancel (curl_download_task);
1285 curl_download_task = NULL;
1291 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max)))
1293 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1294 "%s failed at %s:%d: `%s'\n",
1295 "curl_multi_fdset", __FILE__, __LINE__,
1296 curl_multi_strerror (mret));
1300 GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
1302 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1304 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1307 grs = GNUNET_NETWORK_fdset_create ();
1308 gws = GNUNET_NETWORK_fdset_create ();
1309 GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1310 GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1311 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1314 &curl_task_download, curl_multi);
1315 GNUNET_NETWORK_fdset_destroy (gws);
1316 GNUNET_NETWORK_fdset_destroy (grs);
1320 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1321 &curl_task_download,
1328 * Task that is run when we are ready to receive more data from curl.
1330 * @param cls closure, NULL
1333 curl_task_download (void *cls)
1337 struct CURLMsg *msg;
1339 struct Socks5Request *s5r;
1341 curl_download_task = NULL;
1345 mret = curl_multi_perform (curl_multi, &running);
1346 while (NULL != (msg = curl_multi_info_read (curl_multi, &msgnum)))
1348 GNUNET_break (CURLE_OK ==
1349 curl_easy_getinfo (msg->easy_handle,
1360 /* documentation says this is not used */
1364 switch (msg->data.result)
1367 case CURLE_GOT_NOTHING:
1368 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1369 "CURL download completed.\n");
1370 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1371 run_mhd_now (s5r->hd);
1374 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1375 "Download curl failed: %s\n",
1376 curl_easy_strerror (msg->data.result));
1377 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1378 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1379 run_mhd_now (s5r->hd);
1382 if (NULL == s5r->response)
1383 s5r->response = curl_failure_response;
1386 /* documentation says this is not used */
1390 /* unexpected status code */
1395 } while (mret == CURLM_CALL_MULTI_PERFORM);
1396 if (CURLM_OK != mret)
1397 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1398 "%s failed at %s:%d: `%s'\n",
1399 "curl_multi_perform", __FILE__, __LINE__,
1400 curl_multi_strerror (mret));
1403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1404 "Suspending cURL multi loop, no more events pending\n");
1405 return; /* nothing more in progress */
1407 curl_download_prepare ();
1411 /* ********************************* MHD response generation ******************* */
1415 * Read HTTP request header field from the request. Copies the fields
1416 * over to the 'headers' that will be given to curl. However, 'Host'
1417 * is substituted with the LEHO if present. We also change the
1418 * 'Connection' header value to "close" as the proxy does not support
1421 * @param cls our `struct Socks5Request`
1422 * @param kind value kind
1423 * @param key field key
1424 * @param value field value
1425 * @return MHD_YES to continue to iterate
1428 con_val_iter (void *cls,
1429 enum MHD_ValueKind kind,
1433 struct Socks5Request *s5r = cls;
1436 if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1437 (NULL != s5r->leho) )
1439 if (0 == strcasecmp (MHD_HTTP_HEADER_CONTENT_LENGTH, key))
1441 GNUNET_asprintf (&hdr,
1445 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1446 "Adding HEADER `%s' to HTTP request\n",
1448 s5r->headers = curl_slist_append (s5r->headers,
1456 * Main MHD callback for handling requests.
1459 * @param con MHD connection handle
1460 * @param url the url in the request
1461 * @param meth the HTTP method used ("GET", "PUT", etc.)
1462 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1463 * @param upload_data the data being uploaded (excluding HEADERS,
1464 * for a POST that fits into memory and that is encoded
1465 * with a supported encoding, the POST data will NOT be
1466 * given in upload_data and is instead available as
1467 * part of MHD_get_connection_values; very large POST
1468 * data *will* be made available incrementally in
1470 * @param upload_data_size set initially to the size of the
1471 * @a upload_data provided; the method must update this
1472 * value to the number of bytes NOT processed;
1473 * @param con_cls pointer to location where we store the 'struct Request'
1474 * @return MHD_YES if the connection was handled successfully,
1475 * MHD_NO if the socket must be closed due to a serious
1476 * error while handling the request
1479 create_response (void *cls,
1480 struct MHD_Connection *con,
1484 const char *upload_data,
1485 size_t *upload_data_size,
1488 struct Socks5Request *s5r = *con_cls;
1491 char ipstring[INET6_ADDRSTRLEN];
1492 char ipaddr[INET6_ADDRSTRLEN + 2];
1493 const struct sockaddr *sa;
1494 const struct sockaddr_in *s4;
1495 const struct sockaddr_in6 *s6;
1505 if (SOCKS5_SOCKET_WITH_MHD == s5r->state)
1507 /* first time here, initialize curl handle */
1508 sa = (const struct sockaddr *) &s5r->destination_address;
1509 switch (sa->sa_family)
1512 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1513 if (NULL == inet_ntop (AF_INET,
1521 GNUNET_snprintf (ipaddr,
1525 port = ntohs (s4->sin_port);
1528 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1529 if (NULL == inet_ntop (AF_INET6,
1537 GNUNET_snprintf (ipaddr,
1541 port = ntohs (s6->sin6_port);
1547 if (NULL == s5r->curl)
1548 s5r->curl = curl_easy_init ();
1549 if (NULL == s5r->curl)
1550 return MHD_queue_response (con,
1551 MHD_HTTP_INTERNAL_SERVER_ERROR,
1552 curl_failure_response);
1553 curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1554 curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1555 curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1556 curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1557 curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1558 curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1559 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1560 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1561 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1562 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1563 curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1564 curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0);
1566 * Pre-populate cache to resolve Hostname.
1567 * This is necessary as the DNS name in the CURLOPT_URL is used
1568 * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1570 if (NULL != s5r->leho)
1572 GNUNET_asprintf (&curl_hosts,
1577 s5r->hosts = curl_slist_append(NULL, curl_hosts);
1578 curl_easy_setopt(s5r->curl, CURLOPT_RESOLVE, s5r->hosts);
1579 GNUNET_free (curl_hosts);
1581 GNUNET_asprintf (&curlurl,
1582 (HTTPS_PORT != s5r->port)
1584 : "https://%s:%d%s",
1590 curl_easy_setopt (s5r->curl,
1593 GNUNET_free (curlurl);
1594 if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1596 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1597 curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
1598 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1599 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1600 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1601 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1603 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1605 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1606 curl_easy_setopt (s5r->curl, CURLOPT_POST, 1);
1607 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1608 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1609 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1610 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1612 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1614 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1615 curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
1617 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_OPTIONS))
1619 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1620 curl_easy_setopt (s5r->curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
1622 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1624 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1625 curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
1626 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1627 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1631 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1632 _("Unsupported HTTP method `%s'\n"),
1634 curl_easy_cleanup (s5r->curl);
1639 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1641 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1643 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1645 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1649 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1652 if (HTTPS_PORT == s5r->port)
1654 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1655 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1656 /* Disable cURL checking the hostname, as we will check ourselves
1657 as only we have the domain name or the LEHO or the DANE record */
1658 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
1662 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
1665 if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
1668 curl_easy_cleanup (s5r->curl);
1672 MHD_get_connection_values (con,
1674 &con_val_iter, s5r);
1675 //TODO is this sane? Basically we disable cURLs built-in expect:
1677 s5r->headers = curl_slist_append (s5r->headers,
1679 curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
1680 curl_download_prepare ();
1684 /* continuing to process request */
1685 if (0 != *upload_data_size)
1687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1688 "Processing %lu bytes UPLOAD\n", *upload_data_size);
1689 left = GNUNET_MIN (*upload_data_size,
1690 sizeof (s5r->io_buf) - s5r->io_len);
1691 GNUNET_memcpy (&s5r->io_buf[s5r->io_len],
1694 s5r->io_len += left;
1695 *upload_data_size -= left;
1696 GNUNET_assert (NULL != s5r->curl);
1697 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
1698 curl_download_prepare ();
1701 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
1703 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1704 "Finished processing UPLOAD\n");
1705 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1707 if (NULL == s5r->response)
1708 return MHD_YES; /* too early to queue response, did not yet get headers from cURL */
1709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1710 "Queueing response with MHD\n");
1711 run_mhd_now (s5r->hd);
1712 return MHD_queue_response (con,
1718 /* ******************** MHD HTTP setup and event loop ******************** */
1722 * Function called when MHD decides that we are done with a request.
1725 * @param connection connection handle
1726 * @param con_cls value as set by the last call to
1727 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
1728 * @param toe reason for request termination (ignored)
1731 mhd_completed_cb (void *cls,
1732 struct MHD_Connection *connection,
1734 enum MHD_RequestTerminationCode toe)
1736 struct Socks5Request *s5r = *con_cls;
1740 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
1741 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1742 "MHD encountered error handling request: %d\n",
1744 if (NULL != s5r->curl)
1746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1747 "Resetting cURL handle\n");
1748 curl_multi_remove_handle (curl_multi, s5r->curl);
1749 curl_slist_free_all (s5r->headers);
1750 s5r->headers = NULL;
1751 curl_easy_reset (s5r->curl);
1756 if ( (NULL != s5r->response) &&
1757 (curl_failure_response != s5r->response) )
1758 MHD_destroy_response (s5r->response);
1759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Finished request for %s\n", s5r->url);
1760 GNUNET_free (s5r->url);
1761 s5r->state = SOCKS5_SOCKET_WITH_MHD;
1763 s5r->response = NULL;
1769 * Function called when MHD connection is opened or closed.
1772 * @param connection connection handle
1773 * @param con_cls value as set by the last call to
1774 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
1775 * @param toe connection notification type
1778 mhd_connection_cb (void *cls,
1779 struct MHD_Connection *connection,
1781 enum MHD_ConnectionNotificationCode cnc)
1783 struct Socks5Request *s5r;
1784 const union MHD_ConnectionInfo *ci;
1787 if (MHD_CONNECTION_NOTIFY_STARTED == cnc)
1788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n");
1790 if (MHD_CONNECTION_NOTIFY_CLOSED != cnc)
1792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection closed... cleaning up\n");
1794 ci = MHD_get_connection_info (connection,
1795 MHD_CONNECTION_INFO_CONNECTION_FD);
1802 sock = ci->connect_fd;
1803 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1804 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1809 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection stale!\n");
1817 * Function called when MHD first processes an incoming connection.
1818 * Gives us the respective URI information.
1820 * We use this to associate the `struct MHD_Connection` with our
1821 * internal `struct Socks5Request` data structure (by checking
1822 * for matching sockets).
1824 * @param cls the HTTP server handle (a `struct MhdHttpList`)
1825 * @param url the URL that is being requested
1826 * @param connection MHD connection object for the request
1827 * @return the `struct Socks5Request` that this @a connection is for
1830 mhd_log_callback (void *cls,
1832 struct MHD_Connection *connection)
1834 struct Socks5Request *s5r;
1835 const union MHD_ConnectionInfo *ci;
1838 ci = MHD_get_connection_info (connection,
1839 MHD_CONNECTION_INFO_CONNECTION_FD);
1840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url);
1846 sock = ci->connect_fd;
1847 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1849 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1851 if (NULL != s5r->url)
1856 s5r->url = GNUNET_strdup (url);
1857 if (NULL != s5r->timeout_task)
1858 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
1859 s5r->timeout_task = NULL;
1860 GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD);
1870 * Kill the given MHD daemon.
1872 * @param hd daemon to stop
1875 kill_httpd (struct MhdHttpList *hd)
1877 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1880 GNUNET_free_non_null (hd->domain);
1881 MHD_stop_daemon (hd->daemon);
1882 if (NULL != hd->httpd_task)
1884 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1885 hd->httpd_task = NULL;
1887 GNUNET_free_non_null (hd->proxy_cert);
1895 * Task run whenever HTTP server is idle for too long. Kill it.
1897 * @param cls the `struct MhdHttpList *`
1900 kill_httpd_task (void *cls)
1902 struct MhdHttpList *hd = cls;
1904 hd->httpd_task = NULL;
1910 * Task run whenever HTTP server operations are pending.
1912 * @param cls the `struct MhdHttpList *` of the daemon that is being run
1915 do_httpd (void *cls);
1919 * Schedule MHD. This function should be called initially when an
1920 * MHD is first getting its client socket, and will then automatically
1921 * always be called later whenever there is work to be done.
1923 * @param hd the daemon to schedule
1926 schedule_httpd (struct MhdHttpList *hd)
1931 struct GNUNET_NETWORK_FDSet *wrs;
1932 struct GNUNET_NETWORK_FDSet *wws;
1935 MHD_UNSIGNED_LONG_LONG timeout;
1936 struct GNUNET_TIME_Relative tv;
1942 if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1947 haveto = MHD_get_timeout (hd->daemon, &timeout);
1948 if (MHD_YES == haveto)
1949 tv.rel_value_us = (uint64_t) timeout * 1000LL;
1951 tv = GNUNET_TIME_UNIT_FOREVER_REL;
1954 wrs = GNUNET_NETWORK_fdset_create ();
1955 wws = GNUNET_NETWORK_fdset_create ();
1956 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1957 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1964 if (NULL != hd->httpd_task)
1965 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1966 if ( (MHD_YES != haveto) &&
1970 /* daemon is idle, kill after timeout */
1971 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
1978 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1983 GNUNET_NETWORK_fdset_destroy (wrs);
1985 GNUNET_NETWORK_fdset_destroy (wws);
1990 * Task run whenever HTTP server operations are pending.
1992 * @param cls the `struct MhdHttpList` of the daemon that is being run
1995 do_httpd (void *cls)
1997 struct MhdHttpList *hd = cls;
1999 hd->httpd_task = NULL;
2000 MHD_run (hd->daemon);
2001 schedule_httpd (hd);
2006 * Run MHD now, we have extra data ready for the callback.
2008 * @param hd the daemon to run now.
2011 run_mhd_now (struct MhdHttpList *hd)
2015 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2016 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
2022 * Read file in filename
2024 * @param filename file to read
2025 * @param size pointer where filesize is stored
2026 * @return NULL on error
2029 load_file (const char* filename,
2036 GNUNET_DISK_file_size (filename, &fsize,
2037 GNUNET_YES, GNUNET_YES))
2039 if (fsize > MAX_PEM_SIZE)
2041 *size = (unsigned int) fsize;
2042 buffer = GNUNET_malloc (*size);
2043 if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
2045 GNUNET_free (buffer);
2053 * Load PEM key from file
2055 * @param key where to store the data
2056 * @param keyfile path to the PEM file
2057 * @return #GNUNET_OK on success
2060 load_key_from_file (gnutls_x509_privkey_t key,
2061 const char* keyfile)
2063 gnutls_datum_t key_data;
2066 key_data.data = load_file (keyfile, &key_data.size);
2067 if (NULL == key_data.data)
2068 return GNUNET_SYSERR;
2069 ret = gnutls_x509_privkey_import (key, &key_data,
2070 GNUTLS_X509_FMT_PEM);
2071 if (GNUTLS_E_SUCCESS != ret)
2073 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2074 _("Unable to import private key from file `%s'\n"),
2077 GNUNET_free_non_null (key_data.data);
2078 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2083 * Load cert from file
2085 * @param crt struct to store data in
2086 * @param certfile path to pem file
2087 * @return #GNUNET_OK on success
2090 load_cert_from_file (gnutls_x509_crt_t crt,
2091 const char* certfile)
2093 gnutls_datum_t cert_data;
2096 cert_data.data = load_file (certfile, &cert_data.size);
2097 if (NULL == cert_data.data)
2098 return GNUNET_SYSERR;
2099 ret = gnutls_x509_crt_import (crt, &cert_data,
2100 GNUTLS_X509_FMT_PEM);
2101 if (GNUTLS_E_SUCCESS != ret)
2103 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2104 _("Unable to import certificate %s\n"), certfile);
2106 GNUNET_free_non_null (cert_data.data);
2107 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2112 * Generate new certificate for specific name
2114 * @param name the subject name to generate a cert for
2115 * @return a struct holding the PEM data, NULL on error
2117 static struct ProxyGNSCertificate *
2118 generate_gns_certificate (const char *name)
2120 unsigned int serial;
2121 size_t key_buf_size;
2122 size_t cert_buf_size;
2123 gnutls_x509_crt_t request;
2126 struct ProxyGNSCertificate *pgc;
2128 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2129 "Generating TLS/SSL certificate for `%s'\n",
2131 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2132 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2133 pgc = GNUNET_new (struct ProxyGNSCertificate);
2134 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2136 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2137 0, "GNU Name System", 4);
2138 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2139 0, name, strlen (name));
2140 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
2141 gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2142 gnutls_x509_crt_set_serial (request,
2145 etime = time (NULL);
2146 tm_data = localtime (&etime);
2147 gnutls_x509_crt_set_activation_time (request,
2150 etime = mktime (tm_data);
2151 gnutls_x509_crt_set_expiration_time (request,
2153 gnutls_x509_crt_sign (request,
2156 key_buf_size = sizeof (pgc->key);
2157 cert_buf_size = sizeof (pgc->cert);
2158 gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2159 pgc->cert, &cert_buf_size);
2160 gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2161 pgc->key, &key_buf_size);
2162 gnutls_x509_crt_deinit (request);
2168 * Function called by MHD with errors, suppresses them all.
2170 * @param cls closure
2171 * @param fm format string (`printf()`-style)
2172 * @param ap arguments to @a fm
2175 mhd_error_log_callback (void *cls,
2184 * Lookup (or create) an SSL MHD instance for a particular domain.
2186 * @param domain the domain the SSL daemon has to serve
2187 * @return NULL on error
2189 static struct MhdHttpList *
2190 lookup_ssl_httpd (const char* domain)
2192 struct MhdHttpList *hd;
2193 struct ProxyGNSCertificate *pgc;
2200 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2201 if ( (NULL != hd->domain) &&
2202 (0 == strcmp (hd->domain, domain)) )
2204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2205 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2207 pgc = generate_gns_certificate (domain);
2208 hd = GNUNET_new (struct MhdHttpList);
2209 hd->is_ssl = GNUNET_YES;
2210 hd->domain = GNUNET_strdup (domain);
2211 hd->proxy_cert = pgc;
2212 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
2215 &create_response, hd,
2216 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2217 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2218 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
2219 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2220 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2221 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2222 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2224 if (NULL == hd->daemon)
2230 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2238 * Task run when a Socks5Request somehow fails to be associated with
2239 * an MHD connection (i.e. because the client never speaks HTTP after
2240 * the SOCKS5 handshake). Clean up.
2242 * @param cls the `struct Socks5Request *`
2245 timeout_s5r_handshake (void *cls)
2247 struct Socks5Request *s5r = cls;
2249 s5r->timeout_task = NULL;
2255 * We're done with the Socks5 protocol, now we need to pass the
2256 * connection data through to the final destination, either
2257 * direct (if the protocol might not be HTTP), or via MHD
2258 * (if the port looks like it should be HTTP).
2260 * @param s5r socks request that has reached the final stage
2263 setup_data_transfer (struct Socks5Request *s5r)
2265 struct MhdHttpList *hd;
2267 const struct sockaddr *addr;
2273 hd = lookup_ssl_httpd (s5r->domain);
2276 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2277 _("Failed to start HTTPS server for `%s'\n"),
2285 GNUNET_assert (NULL != httpd);
2289 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2290 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2291 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2292 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2293 if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
2295 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2296 _("Failed to pass client to MHD\n"));
2301 schedule_httpd (hd);
2302 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2303 &timeout_s5r_handshake,
2308 /* ********************* SOCKS handling ************************* */
2312 * Write data from buffer to socks5 client, then continue with state machine.
2314 * @param cls the closure with the `struct Socks5Request`
2317 do_write (void *cls)
2319 struct Socks5Request *s5r = cls;
2323 len = GNUNET_NETWORK_socket_send (s5r->sock,
2328 /* write error: connection closed, shutdown, etc.; just clean up */
2334 s5r->wbuf_len - len);
2335 s5r->wbuf_len -= len;
2336 if (s5r->wbuf_len > 0)
2338 /* not done writing */
2340 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2346 /* we're done writing, continue with state machine! */
2353 case SOCKS5_REQUEST:
2354 GNUNET_assert (NULL != s5r->rtask);
2356 case SOCKS5_DATA_TRANSFER:
2357 setup_data_transfer (s5r);
2359 case SOCKS5_WRITE_THEN_CLEANUP:
2370 * Return a server response message indicating a failure to the client.
2372 * @param s5r request to return failure code for
2373 * @param sc status code to return
2376 signal_socks_failure (struct Socks5Request *s5r,
2377 enum Socks5StatusCode sc)
2379 struct Socks5ServerResponseMessage *s_resp;
2381 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2382 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2383 s_resp->version = SOCKS_VERSION_5;
2385 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2386 if (NULL != s5r->wtask)
2388 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2395 * Return a server response message indicating success.
2397 * @param s5r request to return success status message for
2400 signal_socks_success (struct Socks5Request *s5r)
2402 struct Socks5ServerResponseMessage *s_resp;
2404 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2405 s_resp->version = SOCKS_VERSION_5;
2406 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2407 s_resp->reserved = 0;
2408 s_resp->addr_type = SOCKS5_AT_IPV4;
2409 /* zero out IPv4 address and port */
2412 sizeof (struct in_addr) + sizeof (uint16_t));
2413 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2414 sizeof (struct in_addr) + sizeof (uint16_t);
2415 if (NULL == s5r->wtask)
2417 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2424 * Process GNS results for target domain.
2426 * @param cls the `struct Socks5Request *`
2427 * @param rd_count number of records returned
2428 * @param rd record data
2431 handle_gns_result (void *cls,
2433 const struct GNUNET_GNSRECORD_Data *rd)
2435 struct Socks5Request *s5r = cls;
2437 const struct GNUNET_GNSRECORD_Data *r;
2440 s5r->gns_lookup = NULL;
2442 for (i=0;i<rd_count;i++)
2445 switch (r->record_type)
2447 case GNUNET_DNSPARSER_TYPE_A:
2449 struct sockaddr_in *in;
2451 if (sizeof (struct in_addr) != r->data_size)
2453 GNUNET_break_op (0);
2456 if (GNUNET_YES == got_ip)
2459 GNUNET_NETWORK_test_pf (PF_INET))
2461 got_ip = GNUNET_YES;
2462 in = (struct sockaddr_in *) &s5r->destination_address;
2463 in->sin_family = AF_INET;
2464 GNUNET_memcpy (&in->sin_addr,
2467 in->sin_port = htons (s5r->port);
2468 #if HAVE_SOCKADDR_IN_SIN_LEN
2469 in->sin_len = sizeof (*in);
2473 case GNUNET_DNSPARSER_TYPE_AAAA:
2475 struct sockaddr_in6 *in;
2477 if (sizeof (struct in6_addr) != r->data_size)
2479 GNUNET_break_op (0);
2482 if (GNUNET_YES == got_ip)
2485 GNUNET_NETWORK_test_pf (PF_INET))
2487 /* FIXME: allow user to disable IPv6 per configuration option... */
2488 got_ip = GNUNET_YES;
2489 in = (struct sockaddr_in6 *) &s5r->destination_address;
2490 in->sin6_family = AF_INET6;
2491 GNUNET_memcpy (&in->sin6_addr,
2494 in->sin6_port = htons (s5r->port);
2495 #if HAVE_SOCKADDR_IN_SIN_LEN
2496 in->sin6_len = sizeof (*in);
2500 case GNUNET_GNSRECORD_TYPE_VPN:
2501 GNUNET_break (0); /* should have been translated within GNS */
2503 case GNUNET_GNSRECORD_TYPE_LEHO:
2504 GNUNET_free_non_null (s5r->leho);
2505 s5r->leho = GNUNET_strndup (r->data,
2508 case GNUNET_GNSRECORD_TYPE_BOX:
2510 const struct GNUNET_GNSRECORD_BoxRecord *box;
2512 if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
2514 GNUNET_break_op (0);
2518 if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
2519 (ntohs (box->protocol) != IPPROTO_TCP) ||
2520 (ntohs (box->service) != s5r->port) )
2521 break; /* BOX record does not apply */
2522 GNUNET_free_non_null (s5r->dane_data);
2523 s5r->dane_data_len = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
2524 s5r->dane_data = GNUNET_malloc (s5r->dane_data_len);
2525 GNUNET_memcpy (s5r->dane_data,
2527 s5r->dane_data_len);
2535 if (GNUNET_YES != got_ip)
2537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2538 "Name resolution failed to yield useful IP address.\n");
2539 signal_socks_failure (s5r,
2540 SOCKS5_STATUS_GENERAL_FAILURE);
2543 s5r->state = SOCKS5_DATA_TRANSFER;
2544 signal_socks_success (s5r);
2549 * Remove the first @a len bytes from the beginning of the read buffer.
2551 * @param s5r the handle clear the read buffer for
2552 * @param len number of bytes in read buffer to advance
2555 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2558 GNUNET_assert (len <= s5r->rbuf_len);
2561 s5r->rbuf_len - len);
2562 s5r->rbuf_len -= len;
2567 * Read data from incoming Socks5 connection
2569 * @param cls the closure with the `struct Socks5Request`
2572 do_s5r_read (void *cls)
2574 struct Socks5Request *s5r = cls;
2575 const struct Socks5ClientHelloMessage *c_hello;
2576 struct Socks5ServerHelloMessage *s_hello;
2577 const struct Socks5ClientRequestMessage *c_req;
2580 const struct GNUNET_SCHEDULER_TaskContext *tc;
2583 tc = GNUNET_SCHEDULER_get_task_context ();
2584 if ( (NULL != tc->read_ready) &&
2585 (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2587 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2588 &s5r->rbuf[s5r->rbuf_len],
2589 sizeof (s5r->rbuf) - s5r->rbuf_len);
2592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593 "socks5 client disconnected.\n");
2597 s5r->rbuf_len += rlen;
2599 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2602 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2603 "Processing %zu bytes of socks data in state %d\n",
2609 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2610 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2611 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2612 return; /* need more data */
2613 if (SOCKS_VERSION_5 != c_hello->version)
2615 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2616 _("Unsupported socks version %d\n"),
2617 (int) c_hello->version);
2621 clear_from_s5r_rbuf (s5r,
2622 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2623 GNUNET_assert (0 == s5r->wbuf_len);
2624 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2625 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2626 s_hello->version = SOCKS_VERSION_5;
2627 s_hello->auth_method = SOCKS_AUTH_NONE;
2628 GNUNET_assert (NULL == s5r->wtask);
2629 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2632 s5r->state = SOCKS5_REQUEST;
2634 case SOCKS5_REQUEST:
2635 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2636 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2638 switch (c_req->command)
2640 case SOCKS5_CMD_TCP_STREAM:
2644 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2645 _("Unsupported socks command %d\n"),
2646 (int) c_req->command);
2647 signal_socks_failure (s5r,
2648 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2651 switch (c_req->addr_type)
2653 case SOCKS5_AT_IPV4:
2655 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2656 const uint16_t *port = (const uint16_t *) &v4[1];
2657 struct sockaddr_in *in;
2659 s5r->port = ntohs (*port);
2660 if (HTTPS_PORT == s5r->port)
2662 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2663 _("SSL connection to plain IPv4 address requested\n"));
2664 signal_socks_failure (s5r,
2665 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2668 alen = sizeof (struct in_addr);
2669 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2670 alen + sizeof (uint16_t))
2671 return; /* need more data */
2672 in = (struct sockaddr_in *) &s5r->destination_address;
2673 in->sin_family = AF_INET;
2675 in->sin_port = *port;
2676 #if HAVE_SOCKADDR_IN_SIN_LEN
2677 in->sin_len = sizeof (*in);
2679 s5r->state = SOCKS5_DATA_TRANSFER;
2682 case SOCKS5_AT_IPV6:
2684 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2685 const uint16_t *port = (const uint16_t *) &v6[1];
2686 struct sockaddr_in6 *in;
2688 s5r->port = ntohs (*port);
2689 if (HTTPS_PORT == s5r->port)
2691 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2692 _("SSL connection to plain IPv4 address requested\n"));
2693 signal_socks_failure (s5r,
2694 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2697 alen = sizeof (struct in6_addr);
2698 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2699 alen + sizeof (uint16_t))
2700 return; /* need more data */
2701 in = (struct sockaddr_in6 *) &s5r->destination_address;
2702 in->sin6_family = AF_INET6;
2703 in->sin6_addr = *v6;
2704 in->sin6_port = *port;
2705 #if HAVE_SOCKADDR_IN_SIN_LEN
2706 in->sin6_len = sizeof (*in);
2708 s5r->state = SOCKS5_DATA_TRANSFER;
2711 case SOCKS5_AT_DOMAINNAME:
2713 const uint8_t *dom_len;
2714 const char *dom_name;
2715 const uint16_t *port;
2717 dom_len = (const uint8_t *) &c_req[1];
2718 alen = *dom_len + 1;
2719 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2720 alen + sizeof (uint16_t))
2721 return; /* need more data */
2722 dom_name = (const char *) &dom_len[1];
2723 port = (const uint16_t*) &dom_name[*dom_len];
2724 s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2726 "Requested connection is to %s:%d\n",
2729 s5r->state = SOCKS5_RESOLVING;
2730 s5r->port = ntohs (*port);
2731 s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2734 GNUNET_DNSPARSER_TYPE_A,
2735 GNUNET_NO /* only cached */,
2736 (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2742 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2743 _("Unsupported socks address type %d\n"),
2744 (int) c_req->addr_type);
2745 signal_socks_failure (s5r,
2746 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2749 clear_from_s5r_rbuf (s5r,
2750 sizeof (struct Socks5ClientRequestMessage) +
2751 alen + sizeof (uint16_t));
2752 if (0 != s5r->rbuf_len)
2754 /* read more bytes than healthy, why did the client send more!? */
2755 GNUNET_break_op (0);
2756 signal_socks_failure (s5r,
2757 SOCKS5_STATUS_GENERAL_FAILURE);
2760 if (SOCKS5_DATA_TRANSFER == s5r->state)
2762 /* if we are not waiting for GNS resolution, signal success */
2763 signal_socks_success (s5r);
2765 /* We are done reading right now */
2766 GNUNET_SCHEDULER_cancel (s5r->rtask);
2769 case SOCKS5_RESOLVING:
2772 case SOCKS5_DATA_TRANSFER:
2783 * Accept new incoming connections
2785 * @param cls the closure with the lsock4 or lsock6
2786 * @param tc the scheduler context
2789 do_accept (void *cls)
2791 struct GNUNET_NETWORK_Handle *lsock = cls;
2792 struct GNUNET_NETWORK_Handle *s;
2793 struct Socks5Request *s5r;
2795 if (lsock == lsock4)
2799 if (lsock == lsock4)
2800 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2804 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2807 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2810 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2814 "Got an inbound connection, waiting for data\n");
2815 s5r = GNUNET_new (struct Socks5Request);
2816 GNUNET_CONTAINER_DLL_insert (s5r_head,
2820 s5r->state = SOCKS5_INIT;
2821 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2827 /* ******************* General / main code ********************* */
2831 * Task run on shutdown
2833 * @param cls closure
2836 do_shutdown (void *cls)
2838 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2839 "Shutting down...\n");
2840 while (NULL != mhd_httpd_head)
2841 kill_httpd (mhd_httpd_head);
2842 while (NULL != s5r_head)
2843 cleanup_s5r (s5r_head);
2846 GNUNET_NETWORK_socket_close (lsock4);
2851 GNUNET_NETWORK_socket_close (lsock6);
2856 GNUNET_IDENTITY_cancel (id_op);
2859 if (NULL != identity)
2861 GNUNET_IDENTITY_disconnect (identity);
2864 if (NULL != curl_multi)
2866 curl_multi_cleanup (curl_multi);
2869 if (NULL != gns_handle)
2871 GNUNET_GNS_disconnect (gns_handle);
2874 if (NULL != curl_download_task)
2876 GNUNET_SCHEDULER_cancel (curl_download_task);
2877 curl_download_task = NULL;
2881 GNUNET_SCHEDULER_cancel (ltask4);
2886 GNUNET_SCHEDULER_cancel (ltask6);
2889 gnutls_x509_crt_deinit (proxy_ca.cert);
2890 gnutls_x509_privkey_deinit (proxy_ca.key);
2891 gnutls_global_deinit ();
2896 * Create an IPv4 listen socket bound to our port.
2898 * @return NULL on error
2900 static struct GNUNET_NETWORK_Handle *
2903 struct GNUNET_NETWORK_Handle *ls;
2904 struct sockaddr_in sa4;
2907 memset (&sa4, 0, sizeof (sa4));
2908 sa4.sin_family = AF_INET;
2909 sa4.sin_port = htons (port);
2910 #if HAVE_SOCKADDR_IN_SIN_LEN
2911 sa4.sin_len = sizeof (sa4);
2913 ls = GNUNET_NETWORK_socket_create (AF_INET,
2919 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
2923 GNUNET_NETWORK_socket_close (ls);
2932 * Create an IPv6 listen socket bound to our port.
2934 * @return NULL on error
2936 static struct GNUNET_NETWORK_Handle *
2939 struct GNUNET_NETWORK_Handle *ls;
2940 struct sockaddr_in6 sa6;
2943 memset (&sa6, 0, sizeof (sa6));
2944 sa6.sin6_family = AF_INET6;
2945 sa6.sin6_port = htons (port);
2946 #if HAVE_SOCKADDR_IN_SIN_LEN
2947 sa6.sin6_len = sizeof (sa6);
2949 ls = GNUNET_NETWORK_socket_create (AF_INET6,
2955 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
2959 GNUNET_NETWORK_socket_close (ls);
2968 * Continue initialization after we have our zone information.
2973 struct MhdHttpList *hd;
2975 /* Open listen socket for socks proxy */
2976 lsock6 = bind_v6 ();
2978 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2981 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
2983 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2984 GNUNET_NETWORK_socket_close (lsock6);
2989 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2990 lsock6, &do_accept, lsock6);
2993 lsock4 = bind_v4 ();
2995 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2998 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
3000 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
3001 GNUNET_NETWORK_socket_close (lsock4);
3006 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3007 lsock4, &do_accept, lsock4);
3010 if ( (NULL == lsock4) &&
3013 GNUNET_SCHEDULER_shutdown ();
3016 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3018 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3019 "cURL global init failed!\n");
3020 GNUNET_SCHEDULER_shutdown ();
3023 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3024 "Proxy listens on port %lu\n",
3027 /* start MHD daemon for HTTP */
3028 hd = GNUNET_new (struct MhdHttpList);
3029 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
3032 &create_response, hd,
3033 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3034 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
3035 MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL,
3036 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
3038 if (NULL == hd->daemon)
3041 GNUNET_SCHEDULER_shutdown ();
3045 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
3050 * Method called to inform about the egos of the shorten zone of this peer.
3052 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
3053 * this function is only called ONCE, and 'NULL' being passed in
3054 * @a ego does indicate an error (i.e. name is taken or no default
3055 * value is known). If @a ego is non-NULL and if '*ctx'
3056 * is set in those callbacks, the value WILL be passed to a subsequent
3057 * call to the identity callback of #GNUNET_IDENTITY_connect (if
3058 * that one was not NULL).
3060 * @param cls closure, NULL
3061 * @param ego ego handle
3062 * @param ctx context for application to store data for this ego
3063 * (during the lifetime of this process, initially NULL)
3064 * @param name name assigned by the user for this ego,
3065 * NULL if the user just deleted the ego and it
3066 * must thus no longer be used
3069 identity_shorten_cb (void *cls,
3070 struct GNUNET_IDENTITY_Ego *ego,
3077 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3078 _("No ego configured for `shorten-zone`\n"));
3082 local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
3083 do_shorten = GNUNET_YES;
3090 * Method called to inform about the egos of the master zone of this peer.
3092 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
3093 * this function is only called ONCE, and 'NULL' being passed in
3094 * @a ego does indicate an error (i.e. name is taken or no default
3095 * value is known). If @a ego is non-NULL and if '*ctx'
3096 * is set in those callbacks, the value WILL be passed to a subsequent
3097 * call to the identity callback of #GNUNET_IDENTITY_connect (if
3098 * that one was not NULL).
3100 * @param cls closure, NULL
3101 * @param ego ego handle
3102 * @param ctx context for application to store data for this ego
3103 * (during the lifetime of this process, initially NULL)
3104 * @param name name assigned by the user for this ego,
3105 * NULL if the user just deleted the ego and it
3106 * must thus no longer be used
3109 identity_master_cb (void *cls,
3110 struct GNUNET_IDENTITY_Ego *ego,
3117 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3118 _("No ego configured for `%s`\n"),
3120 GNUNET_SCHEDULER_shutdown ();
3123 GNUNET_IDENTITY_ego_get_public_key (ego,
3125 id_op = GNUNET_IDENTITY_get (identity,
3127 &identity_shorten_cb,
3133 * Main function that will be run
3135 * @param cls closure
3136 * @param args remaining command-line arguments
3137 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3138 * @param c configuration
3141 run (void *cls, char *const *args, const char *cfgfile,
3142 const struct GNUNET_CONFIGURATION_Handle *c)
3144 char* cafile_cfg = NULL;
3149 if (NULL == (curl_multi = curl_multi_init ()))
3151 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3152 "Failed to create cURL multi handle!\n");
3155 cafile = cafile_opt;
3158 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3162 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3167 cafile = cafile_cfg;
3169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3170 "Using %s as CA\n", cafile);
3172 gnutls_global_init ();
3173 gnutls_x509_crt_init (&proxy_ca.cert);
3174 gnutls_x509_privkey_init (&proxy_ca.key);
3176 if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
3177 (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
3179 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3180 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
3182 gnutls_x509_crt_deinit (proxy_ca.cert);
3183 gnutls_x509_privkey_deinit (proxy_ca.key);
3184 gnutls_global_deinit ();
3185 GNUNET_free_non_null (cafile_cfg);
3188 GNUNET_free_non_null (cafile_cfg);
3189 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3191 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3192 "Unable to connect to GNS!\n");
3193 gnutls_x509_crt_deinit (proxy_ca.cert);
3194 gnutls_x509_privkey_deinit (proxy_ca.key);
3195 gnutls_global_deinit ();
3198 identity = GNUNET_IDENTITY_connect (cfg,
3200 id_op = GNUNET_IDENTITY_get (identity,
3202 &identity_master_cb,
3204 GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
3209 * The main function for gnunet-gns-proxy.
3211 * @param argc number of arguments from the command line
3212 * @param argv command line arguments
3213 * @return 0 ok, 1 on error
3216 main (int argc, char *const *argv)
3218 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3220 gettext_noop ("listen on specified port (default: 7777)"), 1,
3221 &GNUNET_GETOPT_set_ulong, &port},
3222 {'a', "authority", NULL,
3223 gettext_noop ("pem file to use as CA"), 1,
3224 &GNUNET_GETOPT_set_string, &cafile_opt},
3225 GNUNET_GETOPT_OPTION_END
3227 static const char* page =
3228 "<html><head><title>gnunet-gns-proxy</title>"
3229 "</head><body>cURL fail</body></html>";
3232 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3234 GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3235 curl_failure_response = MHD_create_response_from_buffer (strlen (page),
3237 MHD_RESPMEM_PERSISTENT);
3241 GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3242 _("GNUnet GNS proxy"),
3244 &run, NULL)) ? 0 : 1;
3245 MHD_destroy_response (curl_failure_response);
3246 GNUNET_free_non_null ((char *) argv);
3247 GNUNET_CRYPTO_ecdsa_key_clear (&local_shorten_zone);
3251 /* end of gnunet-gns-proxy.c */