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., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, 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>
32 #include <curl/curl.h>
33 #include <gnutls/gnutls.h>
34 #include <gnutls/x509.h>
35 #include <gnutls/abstract.h>
36 #include <gnutls/crypto.h>
38 #include <gnutls/dane.h>
41 #include "gnunet_util_lib.h"
42 #include "gnunet_gns_service.h"
43 #include "gnunet_identity_service.h"
48 * Default Socks5 listen port.
50 #define GNUNET_GNS_PROXY_PORT 7777
53 * Maximum supported length for a URI.
54 * Should die. @deprecated
56 #define MAX_HTTP_URI_LENGTH 2048
59 * Size of the buffer for the data upload / download. Must be
60 * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
62 #define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE
65 * Size of the read/write buffers for Socks. Uses
66 * 256 bytes for the hostname (at most), plus a few
67 * bytes overhead for the messages.
69 #define SOCKS_BUFFERSIZE (256 + 32)
72 * Port for plaintext HTTP.
79 #define HTTPS_PORT 443
82 * Largest allowed size for a PEM certificate.
84 #define MAX_PEM_SIZE (10 * 1024)
87 * After how long do we clean up unused MHD SSL/TLS instances?
89 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
92 * After how long do we clean up Socks5 handles that failed to show any activity
93 * with their respective MHD instance?
95 #define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
101 * @param level log level
102 * @param fun name of curl_easy-function that gave the error
103 * @param rc return code from curl
105 #define LOG_CURL_EASY(level,fun,rc) GNUNET_log(level, _("%s failed at %s:%d: `%s'\n"), fun, __FILE__, __LINE__, curl_easy_strerror (rc))
108 /* *************** Socks protocol definitions (move to TUN?) ****************** */
111 * Which SOCKS version do we speak?
113 #define SOCKS_VERSION_5 0x05
116 * Flag to set for 'no authentication'.
118 #define SOCKS_AUTH_NONE 0
122 * Commands in Socks5.
127 * Establish TCP/IP stream.
129 SOCKS5_CMD_TCP_STREAM = 1,
132 * Establish TCP port binding.
134 SOCKS5_CMD_TCP_PORT = 2,
137 * Establish UDP port binding.
139 SOCKS5_CMD_UDP_PORT = 3
144 * Address types in Socks5.
146 enum Socks5AddressType
156 SOCKS5_AT_DOMAINNAME = 3,
167 * Status codes in Socks5 response.
169 enum Socks5StatusCode
171 SOCKS5_STATUS_REQUEST_GRANTED = 0,
172 SOCKS5_STATUS_GENERAL_FAILURE = 1,
173 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
174 SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
175 SOCKS5_STATUS_HOST_UNREACHABLE = 4,
176 SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
177 SOCKS5_STATUS_TTL_EXPIRED = 6,
178 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
179 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
184 * Client hello in Socks5 protocol.
186 struct Socks5ClientHelloMessage
189 * Should be #SOCKS_VERSION_5.
194 * How many authentication methods does the client support.
196 uint8_t num_auth_methods;
198 /* followed by supported authentication methods, 1 byte per method */
204 * Server hello in Socks5 protocol.
206 struct Socks5ServerHelloMessage
209 * Should be #SOCKS_VERSION_5.
214 * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
215 * which skips the authentication step.
222 * Client socks request in Socks5 protocol.
224 struct Socks5ClientRequestMessage
227 * Should be #SOCKS_VERSION_5.
232 * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
237 * Reserved, always zero.
242 * Address type, an `enum Socks5AddressType`.
247 * Followed by either an ip4/ipv6 address or a domain name with a
248 * length field (uint8_t) in front (depending on @e addr_type).
249 * followed by port number in network byte order (uint16_t).
255 * Server response to client requests in Socks5 protocol.
257 struct Socks5ServerResponseMessage
260 * Should be #SOCKS_VERSION_5.
265 * Status code, an `enum Socks5StatusCode`
275 * Address type, an `enum Socks5AddressType`.
280 * Followed by either an ip4/ipv6 address or a domain name with a
281 * length field (uint8_t) in front (depending on @e addr_type).
282 * followed by port number in network byte order (uint16_t).
289 /* *********************** Datastructures for HTTP handling ****************** */
292 * A structure for CA cert/key
299 gnutls_x509_crt_t cert;
304 gnutls_x509_privkey_t key;
309 * Structure for GNS certificates
311 struct ProxyGNSCertificate
314 * The certificate as PEM
316 char cert[MAX_PEM_SIZE];
319 * The private key as PEM
321 char key[MAX_PEM_SIZE];
327 * A structure for all running Httpds
334 struct MhdHttpList *prev;
339 struct MhdHttpList *next;
342 * the domain name to server (only important for SSL)
349 struct MHD_Daemon *daemon;
352 * Optional proxy certificate used
354 struct ProxyGNSCertificate *proxy_cert;
359 struct GNUNET_SCHEDULER_Task * httpd_task;
362 * is this an ssl daemon?
369 /* ***************** Datastructures for Socks handling **************** */
378 * We're waiting to get the client hello.
383 * We're waiting to get the initial request.
388 * We are currently resolving the destination.
393 * We're in transfer mode.
395 SOCKS5_DATA_TRANSFER,
398 * Finish writing the write buffer, then clean up.
400 SOCKS5_WRITE_THEN_CLEANUP,
403 * Socket has been passed to MHD, do not close it anymore.
405 SOCKS5_SOCKET_WITH_MHD,
408 * We've finished receiving upload data from MHD.
410 SOCKS5_SOCKET_UPLOAD_STARTED,
413 * We've finished receiving upload data from MHD.
415 SOCKS5_SOCKET_UPLOAD_DONE,
418 * We've finished uploading data via CURL and can now download.
420 SOCKS5_SOCKET_DOWNLOAD_STARTED,
423 * We've finished receiving download data from cURL.
425 SOCKS5_SOCKET_DOWNLOAD_DONE
431 * A structure for socks requests
439 struct Socks5Request *next;
444 struct Socks5Request *prev;
449 struct GNUNET_NETWORK_Handle *sock;
452 * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
454 struct GNUNET_GNS_LookupRequest *gns_lookup;
457 * Client socket read task
459 struct GNUNET_SCHEDULER_Task * rtask;
462 * Client socket write task
464 struct GNUNET_SCHEDULER_Task * wtask;
469 struct GNUNET_SCHEDULER_Task * timeout_task;
474 char rbuf[SOCKS_BUFFERSIZE];
479 char wbuf[SOCKS_BUFFERSIZE];
482 * Buffer we use for moving data between MHD and curl (in both directions).
484 char io_buf[IO_BUFFERSIZE];
487 * MHD HTTP instance handling this request, NULL for none.
489 struct MhdHttpList *hd;
492 * MHD response object for this request.
494 struct MHD_Response *response;
497 * the domain name to server (only important for SSL)
502 * DNS Legacy Host Name as given by GNS, NULL if not given.
507 * Payload of the (last) DANE record encountered.
522 * HTTP request headers for the curl request.
524 struct curl_slist *headers;
527 * DNS->IP mappings resolved through GNS
529 struct curl_slist *hosts;
532 * HTTP response code to give to MHD for the response.
534 unsigned int response_code;
537 * Number of bytes in @e dane_data.
539 size_t dane_data_len;
542 * Number of bytes already in read buffer
547 * Number of bytes already in write buffer
552 * Number of bytes already in the IO buffer.
557 * Once known, what's the target address for the connection?
559 struct sockaddr_storage destination_address;
564 enum SocksPhase state;
567 * Desired destination port.
575 /* *********************** Globals **************************** */
579 * The port the proxy is running on (default 7777)
581 static unsigned long port = GNUNET_GNS_PROXY_PORT;
584 * The CA file (pem) to use for the proxy CA
586 static char *cafile_opt;
589 * The listen socket of the proxy for IPv4
591 static struct GNUNET_NETWORK_Handle *lsock4;
594 * The listen socket of the proxy for IPv6
596 static struct GNUNET_NETWORK_Handle *lsock6;
599 * The listen task ID for IPv4
601 static struct GNUNET_SCHEDULER_Task * ltask4;
604 * The listen task ID for IPv6
606 static struct GNUNET_SCHEDULER_Task * ltask6;
609 * The cURL download task (curl multi API).
611 static struct GNUNET_SCHEDULER_Task * curl_download_task;
614 * The cURL multi handle
616 static CURLM *curl_multi;
619 * Handle to the GNS service
621 static struct GNUNET_GNS_Handle *gns_handle;
624 * DLL for http/https daemons
626 static struct MhdHttpList *mhd_httpd_head;
629 * DLL for http/https daemons
631 static struct MhdHttpList *mhd_httpd_tail;
634 * Daemon for HTTP (we have one per SSL certificate, and then one for
635 * all HTTP connections; this is the one for HTTP, not HTTPS).
637 static struct MhdHttpList *httpd;
640 * DLL of active socks requests.
642 static struct Socks5Request *s5r_head;
645 * DLL of active socks requests.
647 static struct Socks5Request *s5r_tail;
650 * The users local GNS master zone
652 static struct GNUNET_CRYPTO_EcdsaPublicKey local_gns_zone;
655 * The users local shorten zone
657 static struct GNUNET_CRYPTO_EcdsaPrivateKey local_shorten_zone;
660 * Is shortening enabled?
662 static int do_shorten;
665 * The CA for SSL certificate generation
667 static struct ProxyCA proxy_ca;
670 * Response we return on cURL failures.
672 static struct MHD_Response *curl_failure_response;
675 * Connection to identity service.
677 static struct GNUNET_IDENTITY_Handle *identity;
680 * Request for our ego.
682 static struct GNUNET_IDENTITY_Operation *id_op;
687 static const struct GNUNET_CONFIGURATION_Handle *cfg;
690 /* ************************* Global helpers ********************* */
694 * Run MHD now, we have extra data ready for the callback.
696 * @param hd the daemon to run now.
699 run_mhd_now (struct MhdHttpList *hd);
703 * Clean up s5r handles.
705 * @param s5r the handle to destroy
708 cleanup_s5r (struct Socks5Request *s5r)
710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
711 "Cleaning up socks request\n");
712 if (NULL != s5r->curl)
714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
715 "Cleaning up cURL handle\n");
716 curl_multi_remove_handle (curl_multi, s5r->curl);
717 curl_easy_cleanup (s5r->curl);
720 curl_slist_free_all (s5r->headers);
721 if (NULL != s5r->hosts)
723 curl_slist_free_all (s5r->hosts);
725 if ( (NULL != s5r->response) &&
726 (curl_failure_response != s5r->response) )
727 MHD_destroy_response (s5r->response);
728 if (NULL != s5r->rtask)
729 GNUNET_SCHEDULER_cancel (s5r->rtask);
730 if (NULL != s5r->timeout_task)
731 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
732 if (NULL != s5r->wtask)
733 GNUNET_SCHEDULER_cancel (s5r->wtask);
734 if (NULL != s5r->gns_lookup)
735 GNUNET_GNS_lookup_cancel (s5r->gns_lookup);
736 if (NULL != s5r->sock)
738 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
739 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
741 GNUNET_NETWORK_socket_close (s5r->sock);
743 GNUNET_CONTAINER_DLL_remove (s5r_head,
746 GNUNET_free_non_null (s5r->domain);
747 GNUNET_free_non_null (s5r->leho);
748 GNUNET_free_non_null (s5r->url);
749 GNUNET_free_non_null (s5r->dane_data);
754 /* ************************* HTTP handling with cURL *********************** */
758 * Callback for MHD response generation. This function is called from
759 * MHD whenever MHD expects to get data back. Copies data from the
760 * io_buf, if available.
762 * @param cls closure with our `struct Socks5Request`
763 * @param pos in buffer
764 * @param buf where to copy data
765 * @param max available space in @a buf
766 * @return number of bytes written to @a buf
769 mhd_content_cb (void *cls,
774 struct Socks5Request *s5r = cls;
775 size_t bytes_to_copy;
777 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
778 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
780 /* we're still not done with the upload, do not yet
781 start the download, the IO buffer is still full
783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
784 "Pausing MHD download, not yet ready for download\n");
785 return 0; /* not yet ready for data download */
787 bytes_to_copy = GNUNET_MIN (max,
789 if ( (0 == bytes_to_copy) &&
790 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
793 "Pausing MHD download, no data available\n");
794 return 0; /* more data later */
796 if ( (0 == bytes_to_copy) &&
797 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
800 "Completed MHD download\n");
801 return MHD_CONTENT_READER_END_OF_STREAM;
803 memcpy (buf, s5r->io_buf, bytes_to_copy);
804 memmove (s5r->io_buf,
805 &s5r->io_buf[bytes_to_copy],
806 s5r->io_len - bytes_to_copy);
807 s5r->io_len -= bytes_to_copy;
808 if (NULL != s5r->curl)
809 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
810 return bytes_to_copy;
815 * Check that the website has presented us with a valid SSL certificate.
816 * The certificate must either match the domain name or the LEHO name
817 * (or, if available, the TLSA record).
819 * @param s5r request to check for.
820 * @return #GNUNET_OK if the certificate is valid
823 check_ssl_certificate (struct Socks5Request *s5r)
825 unsigned int cert_list_size;
826 const gnutls_datum_t *chainp;
827 const struct curl_tlssessioninfo *tlsinfo;
828 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
830 gnutls_x509_crt_t x509_cert;
835 curl_easy_getinfo (s5r->curl,
836 CURLINFO_TLS_SESSION,
837 (struct curl_slist **) &tlsinfo))
838 return GNUNET_SYSERR;
839 if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend)
841 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
842 _("Unsupported CURL SSL backend %d\n"),
844 return GNUNET_SYSERR;
846 chainp = gnutls_certificate_get_peers (tlsinfo->internals, &cert_list_size);
847 if ( (! chainp) || (0 == cert_list_size) )
848 return GNUNET_SYSERR;
850 size = sizeof (certdn);
851 /* initialize an X.509 certificate structure. */
852 gnutls_x509_crt_init (&x509_cert);
853 gnutls_x509_crt_import (x509_cert,
855 GNUTLS_X509_FMT_DER);
857 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
858 GNUTLS_OID_X520_COMMON_NAME,
859 0, /* the first and only one */
860 0 /* no DER encoding */,
864 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
865 _("Failed to fetch CN from cert: %s\n"),
866 gnutls_strerror(rc));
867 gnutls_x509_crt_deinit (x509_cert);
868 return GNUNET_SYSERR;
870 /* check for TLSA/DANE records */
872 if (NULL != s5r->dane_data)
874 char *dd[] = { s5r->dane_data, NULL };
875 int dlen[] = { s5r->dane_data_len, 0};
876 dane_state_t dane_state;
877 dane_query_t dane_query;
880 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
881 if (0 != (rc = dane_state_init (&dane_state,
882 #ifdef DANE_F_IGNORE_DNSSEC
883 DANE_F_IGNORE_DNSSEC |
885 DANE_F_IGNORE_LOCAL_RESOLVER)))
887 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
888 _("Failed to initialize DANE: %s\n"),
890 gnutls_x509_crt_deinit (x509_cert);
891 return GNUNET_SYSERR;
893 if (0 != (rc = dane_raw_tlsa (dane_state,
900 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
901 _("Failed to parse DANE record: %s\n"),
903 dane_state_deinit (dane_state);
904 gnutls_x509_crt_deinit (x509_cert);
905 return GNUNET_SYSERR;
907 if (0 != (rc = dane_verify_crt_raw (dane_state,
910 gnutls_certificate_type_get (tlsinfo->internals),
915 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
916 _("Failed to verify TLS connection using DANE: %s\n"),
918 dane_query_deinit (dane_query);
919 dane_state_deinit (dane_state);
920 gnutls_x509_crt_deinit (x509_cert);
921 return GNUNET_SYSERR;
925 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
926 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
928 dane_query_deinit (dane_query);
929 dane_state_deinit (dane_state);
930 gnutls_x509_crt_deinit (x509_cert);
931 return GNUNET_SYSERR;
933 dane_query_deinit (dane_query);
934 dane_state_deinit (dane_state);
940 /* try LEHO or ordinary domain name X509 verification */
942 if (NULL != s5r->leho)
946 if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
949 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
950 _("SSL certificate subject name (%s) does not match `%s'\n"),
953 gnutls_x509_crt_deinit (x509_cert);
954 return GNUNET_SYSERR;
959 /* we did not even have the domain name!? */
961 return GNUNET_SYSERR;
964 gnutls_x509_crt_deinit (x509_cert);
970 * We're getting an HTTP response header from cURL. Convert it to the
971 * MHD response headers. Mostly copies the headers, but makes special
972 * adjustments to "Set-Cookie" and "Location" headers as those may need
973 * to be changed from the LEHO to the domain the browser expects.
975 * @param buffer curl buffer with a single line of header data; not 0-terminated!
976 * @param size curl blocksize
977 * @param nmemb curl blocknumber
978 * @param cls our `struct Socks5Request *`
979 * @return size of processed bytes
982 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
984 struct Socks5Request *s5r = cls;
985 size_t bytes = size * nmemb;
987 const char *hdr_type;
988 const char *cookie_domain;
991 char *new_cookie_hdr;
994 size_t delta_cdomain;
998 if (NULL == s5r->response)
1000 /* first, check SSL certificate */
1001 if ( (HTTPS_PORT == s5r->port) &&
1002 (GNUNET_OK != check_ssl_certificate (s5r)) )
1005 GNUNET_break (CURLE_OK ==
1006 curl_easy_getinfo (s5r->curl,
1007 CURLINFO_RESPONSE_CODE,
1009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1010 "Creating MHD response with code %d\n",
1012 s5r->response_code = resp_code;
1013 s5r->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
1018 if (NULL != s5r->leho)
1022 GNUNET_asprintf (&cors_hdr,
1023 (HTTPS_PORT == s5r->port)
1028 GNUNET_break (MHD_YES ==
1029 MHD_add_response_header (s5r->response,
1030 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1032 GNUNET_free (cors_hdr);
1034 /* force connection to be closed after each request, as we
1035 do not support HTTP pipelining */
1036 GNUNET_break (MHD_YES ==
1037 MHD_add_response_header (s5r->response,
1038 MHD_HTTP_HEADER_CONNECTION,
1042 ndup = GNUNET_strndup (buffer, bytes);
1043 hdr_type = strtok (ndup, ":");
1044 if (NULL == hdr_type)
1049 hdr_val = strtok (NULL, "");
1050 if (NULL == hdr_val)
1055 if (' ' == *hdr_val)
1058 /* custom logic for certain header types */
1059 new_cookie_hdr = NULL;
1060 if ( (NULL != s5r->leho) &&
1061 (0 == strcasecmp (hdr_type,
1062 MHD_HTTP_HEADER_SET_COOKIE)) )
1065 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1066 strlen (s5r->domain) + 1);
1068 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1069 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1071 if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
1072 (GNUNET_NO == domain_matched) )
1074 domain_matched = GNUNET_YES;
1075 cookie_domain = tok + strlen (" domain") + 1;
1076 if (strlen (cookie_domain) < strlen (s5r->leho))
1078 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1079 if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
1081 offset += sprintf (new_cookie_hdr + offset,
1087 else if (0 == strcmp (cookie_domain, s5r->leho))
1089 offset += sprintf (new_cookie_hdr + offset,
1094 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1095 _("Cookie domain `%s' supplied by server is invalid\n"),
1098 memcpy (new_cookie_hdr + offset, tok, strlen (tok));
1099 offset += strlen (tok);
1100 new_cookie_hdr[offset++] = ';';
1102 hdr_val = new_cookie_hdr;
1105 new_location = NULL;
1106 if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
1110 GNUNET_asprintf (&leho_host,
1111 (HTTPS_PORT != s5r->port)
1115 if (0 == strncmp (leho_host,
1117 strlen (leho_host)))
1119 GNUNET_asprintf (&new_location,
1121 (HTTPS_PORT != s5r->port)
1125 hdr_val + strlen (leho_host));
1126 hdr_val = new_location;
1128 GNUNET_free (leho_host);
1130 /* MHD does not allow certain characters in values, remove those */
1131 if (NULL != (tok = strchr (hdr_val, '\n')))
1133 if (NULL != (tok = strchr (hdr_val, '\r')))
1135 if (NULL != (tok = strchr (hdr_val, '\t')))
1137 if (0 != strlen (hdr_val))
1139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1140 "Adding header %s: %s to MHD response\n",
1143 GNUNET_break (MHD_YES ==
1144 MHD_add_response_header (s5r->response,
1149 GNUNET_free_non_null (new_cookie_hdr);
1150 GNUNET_free_non_null (new_location);
1156 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1157 * it available to MHD.
1159 * @param ptr pointer to the data
1160 * @param size number of blocks of data
1161 * @param nmemb blocksize
1162 * @param ctx our `struct Socks5Request *`
1163 * @return number of bytes handled
1166 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1168 struct Socks5Request *s5r = ctx;
1169 size_t total = size * nmemb;
1171 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1172 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1174 /* we're still not done with the upload, do not yet
1175 start the download, the IO buffer is still full
1176 with upload data. */
1177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1178 "Pausing CURL download, waiting for UPLOAD to finish\n");
1179 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1181 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1183 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1184 "Pausing CURL download, not enough space\n");
1185 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1187 memcpy (&s5r->io_buf[s5r->io_len],
1190 s5r->io_len += total;
1191 if (s5r->io_len == total)
1192 run_mhd_now (s5r->hd);
1198 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1199 * to make it available to MHD.
1201 * @param buf where to write the data
1202 * @param size number of bytes per member
1203 * @param nmemb number of members available in @a buf
1204 * @param cls our `struct Socks5Request` that generated the data
1205 * @return number of bytes copied to @a buf
1208 curl_upload_cb (void *buf, size_t size, size_t nmemb, void *cls)
1210 struct Socks5Request *s5r = cls;
1211 size_t len = size * nmemb;
1214 if ( (0 == s5r->io_len) &&
1215 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1217 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1218 "Pausing CURL UPLOAD, need more data\n");
1219 return CURL_READFUNC_PAUSE;
1221 if ( (0 == s5r->io_len) &&
1222 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1224 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1226 "Completed CURL UPLOAD\n");
1227 return 0; /* upload finished, can now download */
1229 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) ||
1230 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1233 return CURL_READFUNC_ABORT;
1235 to_copy = GNUNET_MIN (s5r->io_len,
1237 memcpy (buf, s5r->io_buf, to_copy);
1238 memmove (s5r->io_buf,
1239 &s5r->io_buf[to_copy],
1240 s5r->io_len - to_copy);
1241 s5r->io_len -= to_copy;
1242 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1243 run_mhd_now (s5r->hd); /* got more space for upload now */
1248 /* ************************** main loop of cURL interaction ****************** */
1252 * Task that is run when we are ready to receive more data
1255 * @param cls closure
1256 * @param tc task context
1259 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1263 * Ask cURL for the select() sets and schedule cURL operations.
1266 curl_download_prepare ()
1273 struct GNUNET_NETWORK_FDSet *grs;
1274 struct GNUNET_NETWORK_FDSet *gws;
1276 struct GNUNET_TIME_Relative rtime;
1278 if (NULL != curl_download_task)
1280 GNUNET_SCHEDULER_cancel (curl_download_task);
1281 curl_download_task = NULL;
1287 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max)))
1289 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1290 "%s failed at %s:%d: `%s'\n",
1291 "curl_multi_fdset", __FILE__, __LINE__,
1292 curl_multi_strerror (mret));
1296 GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
1298 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1300 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1303 grs = GNUNET_NETWORK_fdset_create ();
1304 gws = GNUNET_NETWORK_fdset_create ();
1305 GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1306 GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1307 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1310 &curl_task_download, curl_multi);
1311 GNUNET_NETWORK_fdset_destroy (gws);
1312 GNUNET_NETWORK_fdset_destroy (grs);
1316 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1317 &curl_task_download,
1324 * Task that is run when we are ready to receive more data from curl.
1326 * @param cls closure, NULL
1327 * @param tc task context
1330 curl_task_download (void *cls,
1331 const struct GNUNET_SCHEDULER_TaskContext *tc)
1335 struct CURLMsg *msg;
1337 struct Socks5Request *s5r;
1339 curl_download_task = NULL;
1343 mret = curl_multi_perform (curl_multi, &running);
1344 while (NULL != (msg = curl_multi_info_read (curl_multi, &msgnum)))
1346 GNUNET_break (CURLE_OK ==
1347 curl_easy_getinfo (msg->easy_handle,
1358 /* documentation says this is not used */
1362 switch (msg->data.result)
1365 case CURLE_GOT_NOTHING:
1366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1367 "CURL download completed.\n");
1368 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1369 run_mhd_now (s5r->hd);
1372 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1373 "Download curl failed: %s\n",
1374 curl_easy_strerror (msg->data.result));
1375 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1376 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1377 run_mhd_now (s5r->hd);
1380 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1381 "Cleaning up cURL handle\n");
1382 curl_multi_remove_handle (curl_multi, s5r->curl);
1383 curl_easy_cleanup (s5r->curl);
1385 if (NULL == s5r->response)
1386 s5r->response = curl_failure_response;
1389 /* documentation says this is not used */
1393 /* unexpected status code */
1398 } while (mret == CURLM_CALL_MULTI_PERFORM);
1399 if (CURLM_OK != mret)
1400 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1401 "%s failed at %s:%d: `%s'\n",
1402 "curl_multi_perform", __FILE__, __LINE__,
1403 curl_multi_strerror (mret));
1406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1407 "Suspending cURL multi loop, no more events pending\n");
1408 return; /* nothing more in progress */
1410 curl_download_prepare ();
1414 /* ********************************* MHD response generation ******************* */
1418 * Read HTTP request header field from the request. Copies the fields
1419 * over to the 'headers' that will be given to curl. However, 'Host'
1420 * is substituted with the LEHO if present. We also change the
1421 * 'Connection' header value to "close" as the proxy does not support
1424 * @param cls our `struct Socks5Request`
1425 * @param kind value kind
1426 * @param key field key
1427 * @param value field value
1428 * @return MHD_YES to continue to iterate
1431 con_val_iter (void *cls,
1432 enum MHD_ValueKind kind,
1436 struct Socks5Request *s5r = cls;
1439 if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1440 (NULL != s5r->leho) )
1442 if (0 == strcasecmp (MHD_HTTP_HEADER_CONNECTION, key))
1444 GNUNET_asprintf (&hdr,
1448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1449 "Adding HEADER `%s' to HTTP request\n",
1451 s5r->headers = curl_slist_append (s5r->headers,
1459 * Main MHD callback for handling requests.
1462 * @param con MHD connection handle
1463 * @param url the url in the request
1464 * @param meth the HTTP method used ("GET", "PUT", etc.)
1465 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1466 * @param upload_data the data being uploaded (excluding HEADERS,
1467 * for a POST that fits into memory and that is encoded
1468 * with a supported encoding, the POST data will NOT be
1469 * given in upload_data and is instead available as
1470 * part of MHD_get_connection_values; very large POST
1471 * data *will* be made available incrementally in
1473 * @param upload_data_size set initially to the size of the
1474 * @a upload_data provided; the method must update this
1475 * value to the number of bytes NOT processed;
1476 * @param con_cls pointer to location where we store the 'struct Request'
1477 * @return MHD_YES if the connection was handled successfully,
1478 * MHD_NO if the socket must be closed due to a serious
1479 * error while handling the request
1482 create_response (void *cls,
1483 struct MHD_Connection *con,
1487 const char *upload_data,
1488 size_t *upload_data_size,
1491 struct Socks5Request *s5r = *con_cls;
1494 char ipstring[INET6_ADDRSTRLEN];
1495 char ipaddr[INET6_ADDRSTRLEN + 2];
1496 const struct sockaddr *sa;
1497 const struct sockaddr_in *s4;
1498 const struct sockaddr_in6 *s6;
1507 if ( (NULL == s5r->curl) &&
1508 (SOCKS5_SOCKET_WITH_MHD == s5r->state) )
1510 /* first time here, initialize curl handle */
1511 sa = (const struct sockaddr *) &s5r->destination_address;
1512 switch (sa->sa_family)
1515 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1516 if (NULL == inet_ntop (AF_INET,
1524 GNUNET_snprintf (ipaddr,
1528 port = ntohs (s4->sin_port);
1531 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1532 if (NULL == inet_ntop (AF_INET6,
1540 GNUNET_snprintf (ipaddr,
1544 port = ntohs (s6->sin6_port);
1550 s5r->curl = curl_easy_init ();
1551 if (NULL == s5r->curl)
1552 return MHD_queue_response (con,
1553 MHD_HTTP_INTERNAL_SERVER_ERROR,
1554 curl_failure_response);
1555 curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1556 curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1557 curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1558 curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1559 curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1560 curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1561 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1562 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1563 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1564 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1565 curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1566 curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0);
1568 * Pre-populate cache to resolve Hostname.
1569 * This is necessary as the DNS name in the CURLOPT_URL is used
1570 * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication
1572 if (NULL != s5r->leho)
1574 GNUNET_asprintf (&curl_hosts,
1579 s5r->hosts = curl_slist_append(NULL, curl_hosts);
1580 curl_easy_setopt(s5r->curl, CURLOPT_RESOLVE, s5r->hosts);
1581 GNUNET_free (curl_hosts);
1583 GNUNET_asprintf (&curlurl,
1584 (HTTPS_PORT != s5r->port)
1586 : "https://%s:%d%s",
1592 curl_easy_setopt (s5r->curl,
1595 GNUNET_free (curlurl);
1597 if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1599 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1600 curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
1601 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1602 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1603 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1604 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1606 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1608 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1609 curl_easy_setopt (s5r->curl, CURLOPT_POST, 1);
1610 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1611 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1612 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1613 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1615 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1617 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1618 curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
1620 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1622 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1623 curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
1624 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1625 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1629 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1630 _("Unsupported HTTP method `%s'\n"),
1632 curl_easy_cleanup (s5r->curl);
1637 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1639 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1641 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1643 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1647 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1650 if (HTTPS_PORT == s5r->port)
1652 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1653 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1654 /* Disable cURL checking the hostname, as we will check ourselves
1655 as only we have the domain name or the LEHO or the DANE record */
1656 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
1660 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
1663 if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
1666 curl_easy_cleanup (s5r->curl);
1670 MHD_get_connection_values (con,
1672 &con_val_iter, s5r);
1673 curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
1674 curl_download_prepare ();
1678 /* continuing to process request */
1679 if (0 != *upload_data_size)
1681 left = GNUNET_MIN (*upload_data_size,
1682 sizeof (s5r->io_buf) - s5r->io_len);
1683 memcpy (&s5r->io_buf[s5r->io_len],
1686 s5r->io_len += left;
1687 *upload_data_size -= left;
1688 GNUNET_assert (NULL != s5r->curl);
1689 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
1690 curl_download_prepare ();
1693 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
1695 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1696 "Finished processing UPLOAD\n");
1697 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1699 if (NULL == s5r->response)
1700 return MHD_YES; /* too early to queue response, did not yet get headers from cURL */
1701 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1702 "Queueing response with MHD\n");
1703 return MHD_queue_response (con,
1709 /* ******************** MHD HTTP setup and event loop ******************** */
1713 * Function called when MHD decides that we are done with a connection.
1716 * @param connection connection handle
1717 * @param con_cls value as set by the last call to
1718 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request *`
1719 * @param toe reason for request termination (ignored)
1722 mhd_completed_cb (void *cls,
1723 struct MHD_Connection *connection,
1725 enum MHD_RequestTerminationCode toe)
1727 struct Socks5Request *s5r = *con_cls;
1731 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
1732 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1733 "MHD encountered error handling request: %d\n",
1736 curl_download_prepare();
1742 * Function called when MHD first processes an incoming connection.
1743 * Gives us the respective URI information.
1745 * We use this to associate the `struct MHD_Connection` with our
1746 * internal `struct Socks5Request` data structure (by checking
1747 * for matching sockets).
1749 * @param cls the HTTP server handle (a `struct MhdHttpList`)
1750 * @param url the URL that is being requested
1751 * @param connection MHD connection object for the request
1752 * @return the `struct Socks5Request` that this @a connection is for
1755 mhd_log_callback (void *cls,
1757 struct MHD_Connection *connection)
1759 struct Socks5Request *s5r;
1760 const union MHD_ConnectionInfo *ci;
1763 ci = MHD_get_connection_info (connection,
1764 MHD_CONNECTION_INFO_CONNECTION_FD);
1770 sock = ci->connect_fd;
1771 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1773 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1775 if (NULL != s5r->url)
1780 s5r->url = GNUNET_strdup (url);
1781 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
1782 s5r->timeout_task = NULL;
1792 * Kill the given MHD daemon.
1794 * @param hd daemon to stop
1797 kill_httpd (struct MhdHttpList *hd)
1799 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1802 GNUNET_free_non_null (hd->domain);
1803 MHD_stop_daemon (hd->daemon);
1804 if (NULL != hd->httpd_task)
1806 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1807 hd->httpd_task = NULL;
1809 GNUNET_free_non_null (hd->proxy_cert);
1817 * Task run whenever HTTP server is idle for too long. Kill it.
1819 * @param cls the `struct MhdHttpList *`
1820 * @param tc sched context
1823 kill_httpd_task (void *cls,
1824 const struct GNUNET_SCHEDULER_TaskContext *tc)
1826 struct MhdHttpList *hd = cls;
1828 hd->httpd_task = NULL;
1834 * Task run whenever HTTP server operations are pending.
1836 * @param cls the `struct MhdHttpList *` of the daemon that is being run
1837 * @param tc sched context
1840 do_httpd (void *cls,
1841 const struct GNUNET_SCHEDULER_TaskContext *tc);
1845 * Schedule MHD. This function should be called initially when an
1846 * MHD is first getting its client socket, and will then automatically
1847 * always be called later whenever there is work to be done.
1849 * @param hd the daemon to schedule
1852 schedule_httpd (struct MhdHttpList *hd)
1857 struct GNUNET_NETWORK_FDSet *wrs;
1858 struct GNUNET_NETWORK_FDSet *wws;
1861 MHD_UNSIGNED_LONG_LONG timeout;
1862 struct GNUNET_TIME_Relative tv;
1868 if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1873 haveto = MHD_get_timeout (hd->daemon, &timeout);
1874 if (MHD_YES == haveto)
1875 tv.rel_value_us = (uint64_t) timeout * 1000LL;
1877 tv = GNUNET_TIME_UNIT_FOREVER_REL;
1880 wrs = GNUNET_NETWORK_fdset_create ();
1881 wws = GNUNET_NETWORK_fdset_create ();
1882 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1883 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1890 if (NULL != hd->httpd_task)
1891 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1892 if ( (MHD_YES != haveto) &&
1896 /* daemon is idle, kill after timeout */
1897 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
1904 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1909 GNUNET_NETWORK_fdset_destroy (wrs);
1911 GNUNET_NETWORK_fdset_destroy (wws);
1916 * Task run whenever HTTP server operations are pending.
1918 * @param cls the `struct MhdHttpList` of the daemon that is being run
1919 * @param tc scheduler context
1922 do_httpd (void *cls,
1923 const struct GNUNET_SCHEDULER_TaskContext *tc)
1925 struct MhdHttpList *hd = cls;
1927 hd->httpd_task = NULL;
1928 MHD_run (hd->daemon);
1929 schedule_httpd (hd);
1934 * Run MHD now, we have extra data ready for the callback.
1936 * @param hd the daemon to run now.
1939 run_mhd_now (struct MhdHttpList *hd)
1943 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1944 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
1950 * Read file in filename
1952 * @param filename file to read
1953 * @param size pointer where filesize is stored
1954 * @return NULL on error
1957 load_file (const char* filename,
1964 GNUNET_DISK_file_size (filename, &fsize,
1965 GNUNET_YES, GNUNET_YES))
1967 if (fsize > MAX_PEM_SIZE)
1969 *size = (unsigned int) fsize;
1970 buffer = GNUNET_malloc (*size);
1971 if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
1973 GNUNET_free (buffer);
1981 * Load PEM key from file
1983 * @param key where to store the data
1984 * @param keyfile path to the PEM file
1985 * @return #GNUNET_OK on success
1988 load_key_from_file (gnutls_x509_privkey_t key,
1989 const char* keyfile)
1991 gnutls_datum_t key_data;
1994 key_data.data = load_file (keyfile, &key_data.size);
1995 if (NULL == key_data.data)
1996 return GNUNET_SYSERR;
1997 ret = gnutls_x509_privkey_import (key, &key_data,
1998 GNUTLS_X509_FMT_PEM);
1999 if (GNUTLS_E_SUCCESS != ret)
2001 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2002 _("Unable to import private key from file `%s'\n"),
2005 GNUNET_free_non_null (key_data.data);
2006 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2011 * Load cert from file
2013 * @param crt struct to store data in
2014 * @param certfile path to pem file
2015 * @return #GNUNET_OK on success
2018 load_cert_from_file (gnutls_x509_crt_t crt,
2019 const char* certfile)
2021 gnutls_datum_t cert_data;
2024 cert_data.data = load_file (certfile, &cert_data.size);
2025 if (NULL == cert_data.data)
2026 return GNUNET_SYSERR;
2027 ret = gnutls_x509_crt_import (crt, &cert_data,
2028 GNUTLS_X509_FMT_PEM);
2029 if (GNUTLS_E_SUCCESS != ret)
2031 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2032 _("Unable to import certificate %s\n"), certfile);
2034 GNUNET_free_non_null (cert_data.data);
2035 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2040 * Generate new certificate for specific name
2042 * @param name the subject name to generate a cert for
2043 * @return a struct holding the PEM data, NULL on error
2045 static struct ProxyGNSCertificate *
2046 generate_gns_certificate (const char *name)
2048 unsigned int serial;
2049 size_t key_buf_size;
2050 size_t cert_buf_size;
2051 gnutls_x509_crt_t request;
2054 struct ProxyGNSCertificate *pgc;
2056 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2057 "Generating TLS/SSL certificate for `%s'\n",
2059 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2060 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2061 pgc = GNUNET_new (struct ProxyGNSCertificate);
2062 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2064 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2065 0, "GNU Name System", 4);
2066 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2067 0, name, strlen (name));
2068 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
2069 gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2070 gnutls_x509_crt_set_serial (request,
2073 etime = time (NULL);
2074 tm_data = localtime (&etime);
2075 gnutls_x509_crt_set_activation_time (request,
2078 etime = mktime (tm_data);
2079 gnutls_x509_crt_set_expiration_time (request,
2081 gnutls_x509_crt_sign (request,
2084 key_buf_size = sizeof (pgc->key);
2085 cert_buf_size = sizeof (pgc->cert);
2086 gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2087 pgc->cert, &cert_buf_size);
2088 gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2089 pgc->key, &key_buf_size);
2090 gnutls_x509_crt_deinit (request);
2096 * Function called by MHD with errors, suppresses them all.
2098 * @param cls closure
2099 * @param fm format string (`printf()`-style)
2100 * @param ap arguments to @a fm
2103 mhd_error_log_callback (void *cls,
2112 * Lookup (or create) an SSL MHD instance for a particular domain.
2114 * @param domain the domain the SSL daemon has to serve
2115 * @return NULL on error
2117 static struct MhdHttpList *
2118 lookup_ssl_httpd (const char* domain)
2120 struct MhdHttpList *hd;
2121 struct ProxyGNSCertificate *pgc;
2128 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2129 if ( (NULL != hd->domain) &&
2130 (0 == strcmp (hd->domain, domain)) )
2132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2133 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2135 pgc = generate_gns_certificate (domain);
2136 hd = GNUNET_new (struct MhdHttpList);
2137 hd->is_ssl = GNUNET_YES;
2138 hd->domain = GNUNET_strdup (domain);
2139 hd->proxy_cert = pgc;
2140 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
2143 &create_response, hd,
2144 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2145 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2146 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2147 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2148 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2149 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2151 if (NULL == hd->daemon)
2157 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2165 * Task run when a Socks5Request somehow fails to be associated with
2166 * an MHD connection (i.e. because the client never speaks HTTP after
2167 * the SOCKS5 handshake). Clean up.
2169 * @param cls the `struct Socks5Request *`
2170 * @param tc sched context
2173 timeout_s5r_handshake (void *cls,
2174 const struct GNUNET_SCHEDULER_TaskContext *tc)
2176 struct Socks5Request *s5r = cls;
2178 s5r->timeout_task = NULL;
2184 * We're done with the Socks5 protocol, now we need to pass the
2185 * connection data through to the final destination, either
2186 * direct (if the protocol might not be HTTP), or via MHD
2187 * (if the port looks like it should be HTTP).
2189 * @param s5r socks request that has reached the final stage
2192 setup_data_transfer (struct Socks5Request *s5r)
2194 struct MhdHttpList *hd;
2196 const struct sockaddr *addr;
2202 hd = lookup_ssl_httpd (s5r->domain);
2205 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2206 _("Failed to start HTTPS server for `%s'\n"),
2214 GNUNET_assert (NULL != httpd);
2218 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2219 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2220 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2221 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2222 if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
2224 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2225 _("Failed to pass client to MHD\n"));
2230 schedule_httpd (hd);
2231 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2232 &timeout_s5r_handshake,
2237 /* ********************* SOCKS handling ************************* */
2241 * Write data from buffer to socks5 client, then continue with state machine.
2243 * @param cls the closure with the `struct Socks5Request`
2244 * @param tc scheduler context
2247 do_write (void *cls,
2248 const struct GNUNET_SCHEDULER_TaskContext *tc)
2250 struct Socks5Request *s5r = cls;
2254 len = GNUNET_NETWORK_socket_send (s5r->sock,
2259 /* write error: connection closed, shutdown, etc.; just clean up */
2265 s5r->wbuf_len - len);
2266 s5r->wbuf_len -= len;
2267 if (s5r->wbuf_len > 0)
2269 /* not done writing */
2271 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2277 /* we're done writing, continue with state machine! */
2284 case SOCKS5_REQUEST:
2285 GNUNET_assert (NULL != s5r->rtask);
2287 case SOCKS5_DATA_TRANSFER:
2288 setup_data_transfer (s5r);
2290 case SOCKS5_WRITE_THEN_CLEANUP:
2301 * Return a server response message indicating a failure to the client.
2303 * @param s5r request to return failure code for
2304 * @param sc status code to return
2307 signal_socks_failure (struct Socks5Request *s5r,
2308 enum Socks5StatusCode sc)
2310 struct Socks5ServerResponseMessage *s_resp;
2312 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2313 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2314 s_resp->version = SOCKS_VERSION_5;
2316 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2317 if (NULL != s5r->wtask)
2319 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2326 * Return a server response message indicating success.
2328 * @param s5r request to return success status message for
2331 signal_socks_success (struct Socks5Request *s5r)
2333 struct Socks5ServerResponseMessage *s_resp;
2335 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2336 s_resp->version = SOCKS_VERSION_5;
2337 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2338 s_resp->reserved = 0;
2339 s_resp->addr_type = SOCKS5_AT_IPV4;
2340 /* zero out IPv4 address and port */
2343 sizeof (struct in_addr) + sizeof (uint16_t));
2344 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2345 sizeof (struct in_addr) + sizeof (uint16_t);
2346 if (NULL == s5r->wtask)
2348 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2355 * Process GNS results for target domain.
2357 * @param cls the `struct Socks5Request *`
2358 * @param rd_count number of records returned
2359 * @param rd record data
2362 handle_gns_result (void *cls,
2364 const struct GNUNET_GNSRECORD_Data *rd)
2366 struct Socks5Request *s5r = cls;
2368 const struct GNUNET_GNSRECORD_Data *r;
2371 s5r->gns_lookup = NULL;
2373 for (i=0;i<rd_count;i++)
2376 switch (r->record_type)
2378 case GNUNET_DNSPARSER_TYPE_A:
2380 struct sockaddr_in *in;
2382 if (sizeof (struct in_addr) != r->data_size)
2384 GNUNET_break_op (0);
2387 if (GNUNET_YES == got_ip)
2390 GNUNET_NETWORK_test_pf (PF_INET))
2392 got_ip = GNUNET_YES;
2393 in = (struct sockaddr_in *) &s5r->destination_address;
2394 in->sin_family = AF_INET;
2395 memcpy (&in->sin_addr,
2398 in->sin_port = htons (s5r->port);
2399 #if HAVE_SOCKADDR_IN_SIN_LEN
2400 in->sin_len = sizeof (*in);
2404 case GNUNET_DNSPARSER_TYPE_AAAA:
2406 struct sockaddr_in6 *in;
2408 if (sizeof (struct in6_addr) != r->data_size)
2410 GNUNET_break_op (0);
2413 if (GNUNET_YES == got_ip)
2416 GNUNET_NETWORK_test_pf (PF_INET))
2418 /* FIXME: allow user to disable IPv6 per configuration option... */
2419 got_ip = GNUNET_YES;
2420 in = (struct sockaddr_in6 *) &s5r->destination_address;
2421 in->sin6_family = AF_INET6;
2422 memcpy (&in->sin6_addr,
2425 in->sin6_port = htons (s5r->port);
2426 #if HAVE_SOCKADDR_IN_SIN_LEN
2427 in->sin6_len = sizeof (*in);
2431 case GNUNET_GNSRECORD_TYPE_VPN:
2432 GNUNET_break (0); /* should have been translated within GNS */
2434 case GNUNET_GNSRECORD_TYPE_LEHO:
2435 GNUNET_free_non_null (s5r->leho);
2436 s5r->leho = GNUNET_strndup (r->data,
2439 case GNUNET_GNSRECORD_TYPE_BOX:
2441 const struct GNUNET_GNSRECORD_BoxRecord *box;
2443 if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord))
2445 GNUNET_break_op (0);
2449 if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) ||
2450 (ntohs (box->protocol) != IPPROTO_TCP) ||
2451 (ntohs (box->service) != s5r->port) )
2452 break; /* BOX record does not apply */
2453 GNUNET_free_non_null (s5r->dane_data);
2454 s5r->dane_data_len = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord);
2455 s5r->dane_data = GNUNET_malloc (s5r->dane_data_len);
2456 memcpy (s5r->dane_data,
2458 s5r->dane_data_len);
2466 if (GNUNET_YES != got_ip)
2468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2469 "Name resolution failed to yield useful IP address.\n");
2470 signal_socks_failure (s5r,
2471 SOCKS5_STATUS_GENERAL_FAILURE);
2474 s5r->state = SOCKS5_DATA_TRANSFER;
2475 signal_socks_success (s5r);
2480 * Remove the first @a len bytes from the beginning of the read buffer.
2482 * @param s5r the handle clear the read buffer for
2483 * @param len number of bytes in read buffer to advance
2486 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2489 GNUNET_assert (len <= s5r->rbuf_len);
2492 s5r->rbuf_len - len);
2493 s5r->rbuf_len -= len;
2498 * Read data from incoming Socks5 connection
2500 * @param cls the closure with the `struct Socks5Request`
2501 * @param tc the scheduler context
2504 do_s5r_read (void *cls,
2505 const struct GNUNET_SCHEDULER_TaskContext *tc)
2507 struct Socks5Request *s5r = cls;
2508 const struct Socks5ClientHelloMessage *c_hello;
2509 struct Socks5ServerHelloMessage *s_hello;
2510 const struct Socks5ClientRequestMessage *c_req;
2515 if ( (NULL != tc->read_ready) &&
2516 (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2518 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2519 &s5r->rbuf[s5r->rbuf_len],
2520 sizeof (s5r->rbuf) - s5r->rbuf_len);
2523 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2524 "socks5 client disconnected.\n");
2528 s5r->rbuf_len += rlen;
2530 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2534 "Processing %u bytes of socks data in state %d\n",
2540 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2541 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2542 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2543 return; /* need more data */
2544 if (SOCKS_VERSION_5 != c_hello->version)
2546 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2547 _("Unsupported socks version %d\n"),
2548 (int) c_hello->version);
2552 clear_from_s5r_rbuf (s5r,
2553 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2554 GNUNET_assert (0 == s5r->wbuf_len);
2555 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2556 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2557 s_hello->version = SOCKS_VERSION_5;
2558 s_hello->auth_method = SOCKS_AUTH_NONE;
2559 GNUNET_assert (NULL == s5r->wtask);
2560 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2563 s5r->state = SOCKS5_REQUEST;
2565 case SOCKS5_REQUEST:
2566 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2567 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2569 switch (c_req->command)
2571 case SOCKS5_CMD_TCP_STREAM:
2575 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2576 _("Unsupported socks command %d\n"),
2577 (int) c_req->command);
2578 signal_socks_failure (s5r,
2579 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2582 switch (c_req->addr_type)
2584 case SOCKS5_AT_IPV4:
2586 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2587 const uint16_t *port = (const uint16_t *) &v4[1];
2588 struct sockaddr_in *in;
2590 s5r->port = ntohs (*port);
2591 if (HTTPS_PORT == s5r->port)
2593 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2594 _("SSL connection to plain IPv4 address requested\n"));
2595 signal_socks_failure (s5r,
2596 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2599 alen = sizeof (struct in_addr);
2600 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2601 alen + sizeof (uint16_t))
2602 return; /* need more data */
2603 in = (struct sockaddr_in *) &s5r->destination_address;
2604 in->sin_family = AF_INET;
2606 in->sin_port = *port;
2607 #if HAVE_SOCKADDR_IN_SIN_LEN
2608 in->sin_len = sizeof (*in);
2610 s5r->state = SOCKS5_DATA_TRANSFER;
2613 case SOCKS5_AT_IPV6:
2615 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2616 const uint16_t *port = (const uint16_t *) &v6[1];
2617 struct sockaddr_in6 *in;
2619 s5r->port = ntohs (*port);
2620 if (HTTPS_PORT == s5r->port)
2622 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2623 _("SSL connection to plain IPv4 address requested\n"));
2624 signal_socks_failure (s5r,
2625 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2628 alen = sizeof (struct in6_addr);
2629 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2630 alen + sizeof (uint16_t))
2631 return; /* need more data */
2632 in = (struct sockaddr_in6 *) &s5r->destination_address;
2633 in->sin6_family = AF_INET6;
2634 in->sin6_addr = *v6;
2635 in->sin6_port = *port;
2636 #if HAVE_SOCKADDR_IN_SIN_LEN
2637 in->sin6_len = sizeof (*in);
2639 s5r->state = SOCKS5_DATA_TRANSFER;
2642 case SOCKS5_AT_DOMAINNAME:
2644 const uint8_t *dom_len;
2645 const char *dom_name;
2646 const uint16_t *port;
2648 dom_len = (const uint8_t *) &c_req[1];
2649 alen = *dom_len + 1;
2650 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2651 alen + sizeof (uint16_t))
2652 return; /* need more data */
2653 dom_name = (const char *) &dom_len[1];
2654 port = (const uint16_t*) &dom_name[*dom_len];
2655 s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2656 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2657 "Requested connection is to %s:%d\n",
2660 s5r->state = SOCKS5_RESOLVING;
2661 s5r->port = ntohs (*port);
2662 s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2665 GNUNET_DNSPARSER_TYPE_A,
2666 GNUNET_NO /* only cached */,
2667 (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2673 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2674 _("Unsupported socks address type %d\n"),
2675 (int) c_req->addr_type);
2676 signal_socks_failure (s5r,
2677 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2680 clear_from_s5r_rbuf (s5r,
2681 sizeof (struct Socks5ClientRequestMessage) +
2682 alen + sizeof (uint16_t));
2683 if (0 != s5r->rbuf_len)
2685 /* read more bytes than healthy, why did the client send more!? */
2686 GNUNET_break_op (0);
2687 signal_socks_failure (s5r,
2688 SOCKS5_STATUS_GENERAL_FAILURE);
2691 if (SOCKS5_DATA_TRANSFER == s5r->state)
2693 /* if we are not waiting for GNS resolution, signal success */
2694 signal_socks_success (s5r);
2696 /* We are done reading right now */
2697 GNUNET_SCHEDULER_cancel (s5r->rtask);
2700 case SOCKS5_RESOLVING:
2703 case SOCKS5_DATA_TRANSFER:
2714 * Accept new incoming connections
2716 * @param cls the closure with the lsock4 or lsock6
2717 * @param tc the scheduler context
2720 do_accept (void *cls,
2721 const struct GNUNET_SCHEDULER_TaskContext *tc)
2723 struct GNUNET_NETWORK_Handle *lsock = cls;
2724 struct GNUNET_NETWORK_Handle *s;
2725 struct Socks5Request *s5r;
2727 if (lsock == lsock4)
2731 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2733 if (lsock == lsock4)
2734 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2738 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2741 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2744 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2748 "Got an inbound connection, waiting for data\n");
2749 s5r = GNUNET_new (struct Socks5Request);
2750 GNUNET_CONTAINER_DLL_insert (s5r_head,
2754 s5r->state = SOCKS5_INIT;
2755 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2761 /* ******************* General / main code ********************* */
2765 * Task run on shutdown
2767 * @param cls closure
2768 * @param tc task context
2771 do_shutdown (void *cls,
2772 const struct GNUNET_SCHEDULER_TaskContext *tc)
2774 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2775 "Shutting down...\n");
2776 while (NULL != mhd_httpd_head)
2777 kill_httpd (mhd_httpd_head);
2778 while (NULL != s5r_head)
2779 cleanup_s5r (s5r_head);
2782 GNUNET_NETWORK_socket_close (lsock4);
2787 GNUNET_NETWORK_socket_close (lsock6);
2792 GNUNET_IDENTITY_cancel (id_op);
2795 if (NULL != identity)
2797 GNUNET_IDENTITY_disconnect (identity);
2800 if (NULL != curl_multi)
2802 curl_multi_cleanup (curl_multi);
2805 if (NULL != gns_handle)
2807 GNUNET_GNS_disconnect (gns_handle);
2810 if (NULL != curl_download_task)
2812 GNUNET_SCHEDULER_cancel (curl_download_task);
2813 curl_download_task = NULL;
2817 GNUNET_SCHEDULER_cancel (ltask4);
2822 GNUNET_SCHEDULER_cancel (ltask6);
2825 gnutls_x509_crt_deinit (proxy_ca.cert);
2826 gnutls_x509_privkey_deinit (proxy_ca.key);
2827 gnutls_global_deinit ();
2832 * Create an IPv4 listen socket bound to our port.
2834 * @return NULL on error
2836 static struct GNUNET_NETWORK_Handle *
2839 struct GNUNET_NETWORK_Handle *ls;
2840 struct sockaddr_in sa4;
2843 memset (&sa4, 0, sizeof (sa4));
2844 sa4.sin_family = AF_INET;
2845 sa4.sin_port = htons (port);
2846 #if HAVE_SOCKADDR_IN_SIN_LEN
2847 sa4.sin_len = sizeof (sa4);
2849 ls = GNUNET_NETWORK_socket_create (AF_INET,
2855 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
2859 GNUNET_NETWORK_socket_close (ls);
2868 * Create an IPv6 listen socket bound to our port.
2870 * @return NULL on error
2872 static struct GNUNET_NETWORK_Handle *
2875 struct GNUNET_NETWORK_Handle *ls;
2876 struct sockaddr_in6 sa6;
2879 memset (&sa6, 0, sizeof (sa6));
2880 sa6.sin6_family = AF_INET6;
2881 sa6.sin6_port = htons (port);
2882 #if HAVE_SOCKADDR_IN_SIN_LEN
2883 sa6.sin6_len = sizeof (sa6);
2885 ls = GNUNET_NETWORK_socket_create (AF_INET6,
2891 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
2895 GNUNET_NETWORK_socket_close (ls);
2904 * Continue initialization after we have our zone information.
2909 struct MhdHttpList *hd;
2911 /* Open listen socket for socks proxy */
2912 lsock6 = bind_v6 ();
2914 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2917 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
2919 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2920 GNUNET_NETWORK_socket_close (lsock6);
2925 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2926 lsock6, &do_accept, lsock6);
2929 lsock4 = bind_v4 ();
2931 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2934 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
2936 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2937 GNUNET_NETWORK_socket_close (lsock4);
2942 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2943 lsock4, &do_accept, lsock4);
2946 if ( (NULL == lsock4) &&
2949 GNUNET_SCHEDULER_shutdown ();
2952 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
2954 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2955 "cURL global init failed!\n");
2956 GNUNET_SCHEDULER_shutdown ();
2959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2960 "Proxy listens on port %u\n",
2963 /* start MHD daemon for HTTP */
2964 hd = GNUNET_new (struct MhdHttpList);
2965 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
2968 &create_response, hd,
2969 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2970 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2971 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2973 if (NULL == hd->daemon)
2976 GNUNET_SCHEDULER_shutdown ();
2980 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2985 * Method called to inform about the egos of the shorten zone of this peer.
2987 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2988 * this function is only called ONCE, and 'NULL' being passed in
2989 * @a ego does indicate an error (i.e. name is taken or no default
2990 * value is known). If @a ego is non-NULL and if '*ctx'
2991 * is set in those callbacks, the value WILL be passed to a subsequent
2992 * call to the identity callback of #GNUNET_IDENTITY_connect (if
2993 * that one was not NULL).
2995 * @param cls closure, NULL
2996 * @param ego ego handle
2997 * @param ctx context for application to store data for this ego
2998 * (during the lifetime of this process, initially NULL)
2999 * @param name name assigned by the user for this ego,
3000 * NULL if the user just deleted the ego and it
3001 * must thus no longer be used
3004 identity_shorten_cb (void *cls,
3005 struct GNUNET_IDENTITY_Ego *ego,
3012 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3013 _("No ego configured for `shorten-zone`\n"));
3017 local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
3018 do_shorten = GNUNET_YES;
3025 * Method called to inform about the egos of the master zone of this peer.
3027 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
3028 * this function is only called ONCE, and 'NULL' being passed in
3029 * @a ego does indicate an error (i.e. name is taken or no default
3030 * value is known). If @a ego is non-NULL and if '*ctx'
3031 * is set in those callbacks, the value WILL be passed to a subsequent
3032 * call to the identity callback of #GNUNET_IDENTITY_connect (if
3033 * that one was not NULL).
3035 * @param cls closure, NULL
3036 * @param ego ego handle
3037 * @param ctx context for application to store data for this ego
3038 * (during the lifetime of this process, initially NULL)
3039 * @param name name assigned by the user for this ego,
3040 * NULL if the user just deleted the ego and it
3041 * must thus no longer be used
3044 identity_master_cb (void *cls,
3045 struct GNUNET_IDENTITY_Ego *ego,
3052 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3053 _("No ego configured for `%s`\n"),
3055 GNUNET_SCHEDULER_shutdown ();
3058 GNUNET_IDENTITY_ego_get_public_key (ego,
3060 id_op = GNUNET_IDENTITY_get (identity,
3062 &identity_shorten_cb,
3068 * Main function that will be run
3070 * @param cls closure
3071 * @param args remaining command-line arguments
3072 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3073 * @param c configuration
3076 run (void *cls, char *const *args, const char *cfgfile,
3077 const struct GNUNET_CONFIGURATION_Handle *c)
3079 char* cafile_cfg = NULL;
3084 if (NULL == (curl_multi = curl_multi_init ()))
3086 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3087 "Failed to create cURL multi handle!\n");
3090 cafile = cafile_opt;
3093 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3097 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3102 cafile = cafile_cfg;
3104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3105 "Using %s as CA\n", cafile);
3107 gnutls_global_init ();
3108 gnutls_x509_crt_init (&proxy_ca.cert);
3109 gnutls_x509_privkey_init (&proxy_ca.key);
3111 if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
3112 (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
3114 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3115 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
3117 gnutls_x509_crt_deinit (proxy_ca.cert);
3118 gnutls_x509_privkey_deinit (proxy_ca.key);
3119 gnutls_global_deinit ();
3120 GNUNET_free_non_null (cafile_cfg);
3123 GNUNET_free_non_null (cafile_cfg);
3124 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3126 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3127 "Unable to connect to GNS!\n");
3128 gnutls_x509_crt_deinit (proxy_ca.cert);
3129 gnutls_x509_privkey_deinit (proxy_ca.key);
3130 gnutls_global_deinit ();
3133 identity = GNUNET_IDENTITY_connect (cfg,
3135 id_op = GNUNET_IDENTITY_get (identity,
3137 &identity_master_cb,
3139 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
3140 &do_shutdown, NULL);
3145 * The main function for gnunet-gns-proxy.
3147 * @param argc number of arguments from the command line
3148 * @param argv command line arguments
3149 * @return 0 ok, 1 on error
3152 main (int argc, char *const *argv)
3154 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3156 gettext_noop ("listen on specified port (default: 7777)"), 1,
3157 &GNUNET_GETOPT_set_ulong, &port},
3158 {'a', "authority", NULL,
3159 gettext_noop ("pem file to use as CA"), 1,
3160 &GNUNET_GETOPT_set_string, &cafile_opt},
3161 GNUNET_GETOPT_OPTION_END
3163 static const char* page =
3164 "<html><head><title>gnunet-gns-proxy</title>"
3165 "</head><body>cURL fail</body></html>";
3168 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3170 GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3171 curl_failure_response = MHD_create_response_from_buffer (strlen (page),
3173 MHD_RESPMEM_PERSISTENT);
3177 GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3178 _("GNUnet GNS proxy"),
3180 &run, NULL)) ? 0 : 1;
3181 MHD_destroy_response (curl_failure_response);
3182 GNUNET_free_non_null ((char *) argv);
3183 GNUNET_CRYPTO_ecdsa_key_clear (&local_shorten_zone);
3187 /* end of gnunet-gns-proxy.c */