2 This file is part of GNUnet.
3 (C) 2012-2013 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 GNUNET_SCHEDULER_TaskIdentifier 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 GNUNET_SCHEDULER_TaskIdentifier rtask;
462 * Client socket write task
464 GNUNET_SCHEDULER_TaskIdentifier wtask;
469 GNUNET_SCHEDULER_TaskIdentifier 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 * HTTP response code to give to MHD for the response.
529 unsigned int response_code;
532 * Number of bytes in @e dane_data.
534 size_t dane_data_len;
537 * Number of bytes already in read buffer
542 * Number of bytes already in write buffer
547 * Number of bytes already in the IO buffer.
552 * Once known, what's the target address for the connection?
554 struct sockaddr_storage destination_address;
559 enum SocksPhase state;
562 * Desired destination port.
570 /* *********************** Globals **************************** */
574 * The port the proxy is running on (default 7777)
576 static unsigned long port = GNUNET_GNS_PROXY_PORT;
579 * The CA file (pem) to use for the proxy CA
581 static char *cafile_opt;
584 * The listen socket of the proxy for IPv4
586 static struct GNUNET_NETWORK_Handle *lsock4;
589 * The listen socket of the proxy for IPv6
591 static struct GNUNET_NETWORK_Handle *lsock6;
594 * The listen task ID for IPv4
596 static GNUNET_SCHEDULER_TaskIdentifier ltask4;
599 * The listen task ID for IPv6
601 static GNUNET_SCHEDULER_TaskIdentifier ltask6;
604 * The cURL download task (curl multi API).
606 static GNUNET_SCHEDULER_TaskIdentifier curl_download_task;
609 * The cURL multi handle
611 static CURLM *curl_multi;
614 * Handle to the GNS service
616 static struct GNUNET_GNS_Handle *gns_handle;
619 * DLL for http/https daemons
621 static struct MhdHttpList *mhd_httpd_head;
624 * DLL for http/https daemons
626 static struct MhdHttpList *mhd_httpd_tail;
629 * Daemon for HTTP (we have one per SSL certificate, and then one for
630 * all HTTP connections; this is the one for HTTP, not HTTPS).
632 static struct MhdHttpList *httpd;
635 * DLL of active socks requests.
637 static struct Socks5Request *s5r_head;
640 * DLL of active socks requests.
642 static struct Socks5Request *s5r_tail;
645 * The users local GNS master zone
647 static struct GNUNET_CRYPTO_EcdsaPublicKey local_gns_zone;
650 * The users local shorten zone
652 static struct GNUNET_CRYPTO_EcdsaPrivateKey local_shorten_zone;
655 * Is shortening enabled?
657 static int do_shorten;
660 * The CA for SSL certificate generation
662 static struct ProxyCA proxy_ca;
665 * Response we return on cURL failures.
667 static struct MHD_Response *curl_failure_response;
670 * Connection to identity service.
672 static struct GNUNET_IDENTITY_Handle *identity;
675 * Request for our ego.
677 static struct GNUNET_IDENTITY_Operation *id_op;
682 static const struct GNUNET_CONFIGURATION_Handle *cfg;
685 /* ************************* Global helpers ********************* */
689 * Run MHD now, we have extra data ready for the callback.
691 * @param hd the daemon to run now.
694 run_mhd_now (struct MhdHttpList *hd);
698 * Clean up s5r handles.
700 * @param s5r the handle to destroy
703 cleanup_s5r (struct Socks5Request *s5r)
705 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
706 "Cleaning up socks request\n");
707 if (NULL != s5r->curl)
709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
710 "Cleaning up cURL handle\n");
711 curl_multi_remove_handle (curl_multi, s5r->curl);
712 curl_easy_cleanup (s5r->curl);
715 curl_slist_free_all (s5r->headers);
716 if ( (NULL != s5r->response) &&
717 (curl_failure_response != s5r->response) )
718 MHD_destroy_response (s5r->response);
719 if (GNUNET_SCHEDULER_NO_TASK != s5r->rtask)
720 GNUNET_SCHEDULER_cancel (s5r->rtask);
721 if (GNUNET_SCHEDULER_NO_TASK != s5r->timeout_task)
722 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
723 if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
724 GNUNET_SCHEDULER_cancel (s5r->wtask);
725 if (NULL != s5r->gns_lookup)
726 GNUNET_GNS_lookup_cancel (s5r->gns_lookup);
727 if (NULL != s5r->sock)
729 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
730 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
732 GNUNET_NETWORK_socket_close (s5r->sock);
734 GNUNET_CONTAINER_DLL_remove (s5r_head,
737 GNUNET_free_non_null (s5r->domain);
738 GNUNET_free_non_null (s5r->leho);
739 GNUNET_free_non_null (s5r->url);
740 GNUNET_free_non_null (s5r->dane_data);
745 /* ************************* HTTP handling with cURL *********************** */
749 * Callback for MHD response generation. This function is called from
750 * MHD whenever MHD expects to get data back. Copies data from the
751 * io_buf, if available.
753 * @param cls closure with our `struct Socks5Request`
754 * @param pos in buffer
755 * @param buf where to copy data
756 * @param max available space in @a buf
757 * @return number of bytes written to @a buf
760 mhd_content_cb (void *cls,
765 struct Socks5Request *s5r = cls;
766 size_t bytes_to_copy;
768 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
769 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
771 /* we're still not done with the upload, do not yet
772 start the download, the IO buffer is still full
774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
775 "Pausing MHD download, not yet ready for download\n");
776 return 0; /* not yet ready for data download */
778 bytes_to_copy = GNUNET_MIN (max,
780 if ( (0 == bytes_to_copy) &&
781 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
784 "Pausing MHD download, no data available\n");
785 return 0; /* more data later */
787 if ( (0 == bytes_to_copy) &&
788 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
791 "Completed MHD download\n");
792 return MHD_CONTENT_READER_END_OF_STREAM;
794 memcpy (buf, s5r->io_buf, bytes_to_copy);
795 memmove (s5r->io_buf,
796 &s5r->io_buf[bytes_to_copy],
797 s5r->io_len - bytes_to_copy);
798 s5r->io_len -= bytes_to_copy;
799 if (NULL != s5r->curl)
800 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
801 return bytes_to_copy;
806 * Check that the website has presented us with a valid SSL certificate.
807 * The certificate must either match the domain name or the LEHO name
808 * (or, if available, the TLSA record).
810 * @param s5r request to check for.
811 * @return #GNUNET_OK if the certificate is valid
814 check_ssl_certificate (struct Socks5Request *s5r)
816 struct curl_tlsinfo tlsinfo;
817 unsigned int cert_list_size;
818 const gnutls_datum_t *chainp;
820 struct curl_tlsinfo *tlsinfo;
821 struct curl_slist *to_slist;
823 char certdn[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 3];
825 gnutls_x509_crt_t x509_cert;
829 memset (&tlsinfo, 0, sizeof (tlsinfo));
830 gptr.tlsinfo = &tlsinfo;
832 curl_easy_getinfo (s5r->curl,
833 CURLINFO_TLS_SESSION,
835 return GNUNET_SYSERR;
836 if (CURLSSLBACKEND_GNUTLS != tlsinfo.ssl_backend)
838 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
839 _("Unsupported CURL SSL backend %d\n"),
840 tlsinfo.ssl_backend);
841 return GNUNET_SYSERR;
843 chainp = gnutls_certificate_get_peers (tlsinfo.internals, &cert_list_size);
844 if ( (! chainp) || (0 == cert_list_size) )
845 return GNUNET_SYSERR;
847 size = sizeof (certdn);
848 /* initialize an X.509 certificate structure. */
849 gnutls_x509_crt_init (&x509_cert);
850 gnutls_x509_crt_import (x509_cert,
852 GNUTLS_X509_FMT_DER);
854 if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert,
855 GNUTLS_OID_X520_COMMON_NAME,
856 0, /* the first and only one */
857 0 /* no DER encoding */,
861 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
862 _("Failed to fetch CN from cert: %s\n"),
863 gnutls_strerror(rc));
864 gnutls_x509_crt_deinit (x509_cert);
865 return GNUNET_SYSERR;
867 /* check for TLSA/DANE records */
869 if (NULL != s5r->dane_data)
871 char *dd[] = { s5r->dane_data, NULL };
872 int dlen[] = { s5r->dane_data_len, 0};
873 dane_state_t dane_state;
874 dane_query_t dane_query;
877 /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */
878 if (0 != (rc = dane_state_init (&dane_state,
879 #ifdef DANE_F_IGNORE_DNSSEC
880 DANE_F_IGNORE_DNSSEC |
882 DANE_F_IGNORE_LOCAL_RESOLVER)))
884 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
885 _("Failed to initialize DANE: %s\n"),
887 gnutls_x509_crt_deinit (x509_cert);
888 return GNUNET_SYSERR;
890 if (0 != (rc = dane_raw_tlsa (dane_state,
897 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
898 _("Failed to parse DANE record: %s\n"),
900 dane_state_deinit (dane_state);
901 gnutls_x509_crt_deinit (x509_cert);
902 return GNUNET_SYSERR;
904 if (0 != (rc = dane_verify_crt_raw (dane_state,
907 gnutls_certificate_type_get (tlsinfo.internals),
912 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
913 _("Failed to verify TLS connection using DANE: %s\n"),
915 dane_query_deinit (dane_query);
916 dane_state_deinit (dane_state);
917 gnutls_x509_crt_deinit (x509_cert);
918 return GNUNET_SYSERR;
922 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
923 _("Failed DANE verification failed with GnuTLS verify status code: %u\n"),
925 dane_query_deinit (dane_query);
926 dane_state_deinit (dane_state);
927 gnutls_x509_crt_deinit (x509_cert);
928 return GNUNET_SYSERR;
930 dane_query_deinit (dane_query);
931 dane_state_deinit (dane_state);
937 /* try LEHO or ordinary domain name X509 verification */
939 if (NULL != s5r->leho)
943 if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert,
946 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
947 _("SSL certificate subject name (%s) does not match `%s'\n"),
950 gnutls_x509_crt_deinit (x509_cert);
951 return GNUNET_SYSERR;
956 /* we did not even have the domain name!? */
958 return GNUNET_SYSERR;
961 gnutls_x509_crt_deinit (x509_cert);
967 * We're getting an HTTP response header from cURL. Convert it to the
968 * MHD response headers. Mostly copies the headers, but makes special
969 * adjustments to "Set-Cookie" and "Location" headers as those may need
970 * to be changed from the LEHO to the domain the browser expects.
972 * @param buffer curl buffer with a single line of header data; not 0-terminated!
973 * @param size curl blocksize
974 * @param nmemb curl blocknumber
975 * @param cls our `struct Socks5Request *`
976 * @return size of processed bytes
979 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
981 struct Socks5Request *s5r = cls;
982 size_t bytes = size * nmemb;
984 const char *hdr_type;
985 const char *cookie_domain;
988 char *new_cookie_hdr;
991 size_t delta_cdomain;
995 if (NULL == s5r->response)
997 /* first, check SSL certificate */
998 if ( (HTTPS_PORT == s5r->port) &&
999 (GNUNET_OK != check_ssl_certificate (s5r)) )
1002 GNUNET_break (CURLE_OK ==
1003 curl_easy_getinfo (s5r->curl,
1004 CURLINFO_RESPONSE_CODE,
1006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1007 "Creating MHD response with code %d\n",
1009 s5r->response_code = resp_code;
1010 s5r->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
1015 if (NULL != s5r->leho)
1019 GNUNET_asprintf (&cors_hdr,
1020 (HTTPS_PORT == s5r->port)
1025 GNUNET_break (MHD_YES ==
1026 MHD_add_response_header (s5r->response,
1027 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
1029 GNUNET_free (cors_hdr);
1031 /* force connection to be closed after each request, as we
1032 do not support HTTP pipelining */
1033 GNUNET_break (MHD_YES ==
1034 MHD_add_response_header (s5r->response,
1035 MHD_HTTP_HEADER_CONNECTION,
1039 ndup = GNUNET_strndup (buffer, bytes);
1040 hdr_type = strtok (ndup, ":");
1041 if (NULL == hdr_type)
1046 hdr_val = strtok (NULL, "");
1047 if (NULL == hdr_val)
1052 if (' ' == *hdr_val)
1055 /* custom logic for certain header types */
1056 new_cookie_hdr = NULL;
1057 if ( (NULL != s5r->leho) &&
1058 (0 == strcasecmp (hdr_type,
1059 MHD_HTTP_HEADER_SET_COOKIE)) )
1062 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
1063 strlen (s5r->domain) + 1);
1065 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
1066 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
1068 if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
1069 (GNUNET_NO == domain_matched) )
1071 domain_matched = GNUNET_YES;
1072 cookie_domain = tok + strlen (" domain") + 1;
1073 if (strlen (cookie_domain) < strlen (s5r->leho))
1075 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
1076 if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
1078 offset += sprintf (new_cookie_hdr + offset,
1084 else if (0 == strcmp (cookie_domain, s5r->leho))
1086 offset += sprintf (new_cookie_hdr + offset,
1091 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1092 _("Cookie domain `%s' supplied by server is invalid\n"),
1095 memcpy (new_cookie_hdr + offset, tok, strlen (tok));
1096 offset += strlen (tok);
1097 new_cookie_hdr[offset++] = ';';
1099 hdr_val = new_cookie_hdr;
1102 new_location = NULL;
1103 if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
1107 GNUNET_asprintf (&leho_host,
1108 (HTTPS_PORT != s5r->port)
1112 if (0 == strncmp (leho_host,
1114 strlen (leho_host)))
1116 GNUNET_asprintf (&new_location,
1118 (HTTPS_PORT != s5r->port)
1122 hdr_val + strlen (leho_host));
1123 hdr_val = new_location;
1125 GNUNET_free (leho_host);
1127 /* MHD does not allow certain characters in values, remove those */
1128 if (NULL != (tok = strchr (hdr_val, '\n')))
1130 if (NULL != (tok = strchr (hdr_val, '\r')))
1132 if (NULL != (tok = strchr (hdr_val, '\t')))
1134 if (0 != strlen (hdr_val))
1136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1137 "Adding header %s: %s to MHD response\n",
1140 GNUNET_break (MHD_YES ==
1141 MHD_add_response_header (s5r->response,
1146 GNUNET_free_non_null (new_cookie_hdr);
1147 GNUNET_free_non_null (new_location);
1153 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1154 * it available to MHD.
1156 * @param ptr pointer to the data
1157 * @param size number of blocks of data
1158 * @param nmemb blocksize
1159 * @param ctx our `struct Socks5Request *`
1160 * @return number of bytes handled
1163 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1165 struct Socks5Request *s5r = ctx;
1166 size_t total = size * nmemb;
1168 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1169 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1171 /* we're still not done with the upload, do not yet
1172 start the download, the IO buffer is still full
1173 with upload data. */
1174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1175 "Pausing CURL download, waiting for UPLOAD to finish\n");
1176 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1178 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1181 "Pausing CURL download, not enough space\n");
1182 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1184 memcpy (&s5r->io_buf[s5r->io_len],
1187 s5r->io_len += total;
1188 if (s5r->io_len == total)
1189 run_mhd_now (s5r->hd);
1195 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1196 * to make it available to MHD.
1198 * @param buf where to write the data
1199 * @param size number of bytes per member
1200 * @param nmemb number of members available in @a buf
1201 * @param cls our `struct Socks5Request` that generated the data
1202 * @return number of bytes copied to @a buf
1205 curl_upload_cb (void *buf, size_t size, size_t nmemb, void *cls)
1207 struct Socks5Request *s5r = cls;
1208 size_t len = size * nmemb;
1211 if ( (0 == s5r->io_len) &&
1212 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1215 "Pausing CURL UPLOAD, need more data\n");
1216 return CURL_READFUNC_PAUSE;
1218 if ( (0 == s5r->io_len) &&
1219 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1221 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1223 "Completed CURL UPLOAD\n");
1224 return 0; /* upload finished, can now download */
1226 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) ||
1227 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1230 return CURL_READFUNC_ABORT;
1232 to_copy = GNUNET_MIN (s5r->io_len,
1234 memcpy (buf, s5r->io_buf, to_copy);
1235 memmove (s5r->io_buf,
1236 &s5r->io_buf[to_copy],
1237 s5r->io_len - to_copy);
1238 s5r->io_len -= to_copy;
1239 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1240 run_mhd_now (s5r->hd); /* got more space for upload now */
1245 /* ************************** main loop of cURL interaction ****************** */
1249 * Task that is run when we are ready to receive more data
1252 * @param cls closure
1253 * @param tc task context
1256 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1260 * Ask cURL for the select() sets and schedule cURL operations.
1263 curl_download_prepare ()
1270 struct GNUNET_NETWORK_FDSet *grs;
1271 struct GNUNET_NETWORK_FDSet *gws;
1273 struct GNUNET_TIME_Relative rtime;
1275 if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
1277 GNUNET_SCHEDULER_cancel (curl_download_task);
1278 curl_download_task = GNUNET_SCHEDULER_NO_TASK;
1284 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max)))
1286 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1287 "%s failed at %s:%d: `%s'\n",
1288 "curl_multi_fdset", __FILE__, __LINE__,
1289 curl_multi_strerror (mret));
1293 GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
1295 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1297 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1300 grs = GNUNET_NETWORK_fdset_create ();
1301 gws = GNUNET_NETWORK_fdset_create ();
1302 GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1303 GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1304 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1307 &curl_task_download, curl_multi);
1308 GNUNET_NETWORK_fdset_destroy (gws);
1309 GNUNET_NETWORK_fdset_destroy (grs);
1313 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1314 &curl_task_download,
1321 * Task that is run when we are ready to receive more data from curl.
1323 * @param cls closure, NULL
1324 * @param tc task context
1327 curl_task_download (void *cls,
1328 const struct GNUNET_SCHEDULER_TaskContext *tc)
1332 struct CURLMsg *msg;
1334 struct Socks5Request *s5r;
1336 curl_download_task = GNUNET_SCHEDULER_NO_TASK;
1340 mret = curl_multi_perform (curl_multi, &running);
1341 while (NULL != (msg = curl_multi_info_read (curl_multi, &msgnum)))
1343 GNUNET_break (CURLE_OK ==
1344 curl_easy_getinfo (msg->easy_handle,
1355 /* documentation says this is not used */
1359 switch (msg->data.result)
1362 case CURLE_GOT_NOTHING:
1363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1364 "CURL download completed.\n");
1365 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1366 run_mhd_now (s5r->hd);
1369 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1370 "Download curl failed: %s\n",
1371 curl_easy_strerror (msg->data.result));
1372 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1373 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1374 run_mhd_now (s5r->hd);
1377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1378 "Cleaning up cURL handle\n");
1379 curl_multi_remove_handle (curl_multi, s5r->curl);
1380 curl_easy_cleanup (s5r->curl);
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_CONNECTION, 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;
1490 char ipstring[INET6_ADDRSTRLEN];
1491 char ipaddr[INET6_ADDRSTRLEN + 2];
1492 const struct sockaddr *sa;
1493 const struct sockaddr_in *s4;
1494 const struct sockaddr_in6 *s6;
1503 if ( (NULL == s5r->curl) &&
1504 (SOCKS5_SOCKET_WITH_MHD == s5r->state) )
1506 /* first time here, initialize curl handle */
1507 sa = (const struct sockaddr *) &s5r->destination_address;
1508 switch (sa->sa_family)
1511 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1512 if (NULL == inet_ntop (AF_INET,
1520 GNUNET_snprintf (ipaddr,
1524 port = ntohs (s4->sin_port);
1527 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1528 if (NULL == inet_ntop (AF_INET6,
1536 GNUNET_snprintf (ipaddr,
1540 port = ntohs (s6->sin6_port);
1546 s5r->curl = curl_easy_init ();
1547 if (NULL == s5r->curl)
1548 return MHD_queue_response (con,
1549 MHD_HTTP_INTERNAL_SERVER_ERROR,
1550 curl_failure_response);
1551 curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1552 curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1553 curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1554 curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1555 curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1556 curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1557 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1558 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1559 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1560 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1561 curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1562 curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0);
1563 GNUNET_asprintf (&curlurl,
1564 (HTTPS_PORT != s5r->port)
1566 : "https://%s:%d%s",
1570 curl_easy_setopt (s5r->curl,
1573 GNUNET_free (curlurl);
1575 if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1577 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1578 curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
1579 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1580 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1581 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1582 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1584 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1586 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1587 curl_easy_setopt (s5r->curl, CURLOPT_POST, 1);
1588 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1589 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1590 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1591 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1593 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1595 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1596 curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
1598 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1600 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1601 curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
1602 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1603 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1607 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1608 _("Unsupported HTTP method `%s'\n"),
1610 curl_easy_cleanup (s5r->curl);
1615 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1617 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1619 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1621 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1625 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1628 if (HTTPS_PORT == s5r->port)
1630 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1631 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1632 /* Disable cURL checking the hostname, as we will check ourselves
1633 as only we have the domain name or the LEHO or the DANE record */
1634 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
1638 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
1641 if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
1644 curl_easy_cleanup (s5r->curl);
1648 MHD_get_connection_values (con,
1650 &con_val_iter, s5r);
1651 curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
1652 curl_download_prepare ();
1656 /* continuing to process request */
1657 if (0 != *upload_data_size)
1659 left = GNUNET_MIN (*upload_data_size,
1660 sizeof (s5r->io_buf) - s5r->io_len);
1661 memcpy (&s5r->io_buf[s5r->io_len],
1664 s5r->io_len += left;
1665 *upload_data_size -= left;
1666 GNUNET_assert (NULL != s5r->curl);
1667 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
1668 curl_download_prepare ();
1671 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
1673 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1674 "Finished processing UPLOAD\n");
1675 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1677 if (NULL == s5r->response)
1678 return MHD_YES; /* too early to queue response, did not yet get headers from cURL */
1679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1680 "Queueing response with MHD\n");
1681 return MHD_queue_response (con,
1687 /* ******************** MHD HTTP setup and event loop ******************** */
1691 * Function called when MHD decides that we are done with a connection.
1694 * @param connection connection handle
1695 * @param con_cls value as set by the last call to
1696 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request`
1697 * @param toe reason for request termination (ignored)
1700 mhd_completed_cb (void *cls,
1701 struct MHD_Connection *connection,
1703 enum MHD_RequestTerminationCode toe)
1705 struct Socks5Request *s5r = *con_cls;
1709 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
1710 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1711 "MHD encountered error handling request: %d\n",
1719 * Function called when MHD first processes an incoming connection.
1720 * Gives us the respective URI information.
1722 * We use this to associate the `struct MHD_Connection` with our
1723 * internal `struct Socks5Request` data structure (by checking
1724 * for matching sockets).
1726 * @param cls the HTTP server handle (a `struct MhdHttpList`)
1727 * @param url the URL that is being requested
1728 * @param connection MHD connection object for the request
1729 * @return the `struct Socks5Request` that this @a connection is for
1732 mhd_log_callback (void *cls,
1734 struct MHD_Connection *connection)
1736 struct Socks5Request *s5r;
1737 const union MHD_ConnectionInfo *ci;
1740 ci = MHD_get_connection_info (connection,
1741 MHD_CONNECTION_INFO_CONNECTION_FD);
1747 sock = ci->connect_fd;
1748 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1750 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1752 if (NULL != s5r->url)
1757 s5r->url = GNUNET_strdup (url);
1758 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
1759 s5r->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1769 * Kill the given MHD daemon.
1771 * @param hd daemon to stop
1774 kill_httpd (struct MhdHttpList *hd)
1776 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1779 GNUNET_free_non_null (hd->domain);
1780 MHD_stop_daemon (hd->daemon);
1781 if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1783 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1784 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
1786 GNUNET_free_non_null (hd->proxy_cert);
1794 * Task run whenever HTTP server is idle for too long. Kill it.
1796 * @param cls the `struct MhdHttpList *`
1797 * @param tc sched context
1800 kill_httpd_task (void *cls,
1801 const struct GNUNET_SCHEDULER_TaskContext *tc)
1803 struct MhdHttpList *hd = cls;
1805 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
1811 * Task run whenever HTTP server operations are pending.
1813 * @param cls the `struct MhdHttpList *` of the daemon that is being run
1814 * @param tc sched context
1817 do_httpd (void *cls,
1818 const struct GNUNET_SCHEDULER_TaskContext *tc);
1822 * Schedule MHD. This function should be called initially when an
1823 * MHD is first getting its client socket, and will then automatically
1824 * always be called later whenever there is work to be done.
1826 * @param hd the daemon to schedule
1829 schedule_httpd (struct MhdHttpList *hd)
1834 struct GNUNET_NETWORK_FDSet *wrs;
1835 struct GNUNET_NETWORK_FDSet *wws;
1838 MHD_UNSIGNED_LONG_LONG timeout;
1839 struct GNUNET_TIME_Relative tv;
1845 if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1850 haveto = MHD_get_timeout (hd->daemon, &timeout);
1851 if (MHD_YES == haveto)
1852 tv.rel_value_us = (uint64_t) timeout * 1000LL;
1854 tv = GNUNET_TIME_UNIT_FOREVER_REL;
1857 wrs = GNUNET_NETWORK_fdset_create ();
1858 wws = GNUNET_NETWORK_fdset_create ();
1859 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1860 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1867 if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1868 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1869 if ( (MHD_YES != haveto) &&
1873 /* daemon is idle, kill after timeout */
1874 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
1881 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1886 GNUNET_NETWORK_fdset_destroy (wrs);
1888 GNUNET_NETWORK_fdset_destroy (wws);
1893 * Task run whenever HTTP server operations are pending.
1895 * @param cls the `struct MhdHttpList` of the daemon that is being run
1896 * @param tc scheduler context
1899 do_httpd (void *cls,
1900 const struct GNUNET_SCHEDULER_TaskContext *tc)
1902 struct MhdHttpList *hd = cls;
1904 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
1905 MHD_run (hd->daemon);
1906 schedule_httpd (hd);
1911 * Run MHD now, we have extra data ready for the callback.
1913 * @param hd the daemon to run now.
1916 run_mhd_now (struct MhdHttpList *hd)
1918 if (GNUNET_SCHEDULER_NO_TASK !=
1920 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1921 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
1927 * Read file in filename
1929 * @param filename file to read
1930 * @param size pointer where filesize is stored
1931 * @return NULL on error
1934 load_file (const char* filename,
1941 GNUNET_DISK_file_size (filename, &fsize,
1942 GNUNET_YES, GNUNET_YES))
1944 if (fsize > MAX_PEM_SIZE)
1946 *size = (unsigned int) fsize;
1947 buffer = GNUNET_malloc (*size);
1948 if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
1950 GNUNET_free (buffer);
1958 * Load PEM key from file
1960 * @param key where to store the data
1961 * @param keyfile path to the PEM file
1962 * @return #GNUNET_OK on success
1965 load_key_from_file (gnutls_x509_privkey_t key,
1966 const char* keyfile)
1968 gnutls_datum_t key_data;
1971 key_data.data = load_file (keyfile, &key_data.size);
1972 if (NULL == key_data.data)
1973 return GNUNET_SYSERR;
1974 ret = gnutls_x509_privkey_import (key, &key_data,
1975 GNUTLS_X509_FMT_PEM);
1976 if (GNUTLS_E_SUCCESS != ret)
1978 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1979 _("Unable to import private key from file `%s'\n"),
1982 GNUNET_free_non_null (key_data.data);
1983 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
1988 * Load cert from file
1990 * @param crt struct to store data in
1991 * @param certfile path to pem file
1992 * @return #GNUNET_OK on success
1995 load_cert_from_file (gnutls_x509_crt_t crt,
1996 const char* certfile)
1998 gnutls_datum_t cert_data;
2001 cert_data.data = load_file (certfile, &cert_data.size);
2002 if (NULL == cert_data.data)
2003 return GNUNET_SYSERR;
2004 ret = gnutls_x509_crt_import (crt, &cert_data,
2005 GNUTLS_X509_FMT_PEM);
2006 if (GNUTLS_E_SUCCESS != ret)
2008 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2009 _("Unable to import certificate %s\n"), certfile);
2011 GNUNET_free_non_null (cert_data.data);
2012 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2017 * Generate new certificate for specific name
2019 * @param name the subject name to generate a cert for
2020 * @return a struct holding the PEM data, NULL on error
2022 static struct ProxyGNSCertificate *
2023 generate_gns_certificate (const char *name)
2025 unsigned int serial;
2026 size_t key_buf_size;
2027 size_t cert_buf_size;
2028 gnutls_x509_crt_t request;
2031 struct ProxyGNSCertificate *pgc;
2033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2034 "Generating TLS/SSL certificate for `%s'\n",
2036 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
2037 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
2038 pgc = GNUNET_new (struct ProxyGNSCertificate);
2039 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2041 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2042 0, "GNU Name System", 4);
2043 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2044 0, name, strlen (name));
2045 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
2046 gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2047 gnutls_x509_crt_set_serial (request,
2050 etime = time (NULL);
2051 tm_data = localtime (&etime);
2052 gnutls_x509_crt_set_activation_time (request,
2055 etime = mktime (tm_data);
2056 gnutls_x509_crt_set_expiration_time (request,
2058 gnutls_x509_crt_sign (request,
2061 key_buf_size = sizeof (pgc->key);
2062 cert_buf_size = sizeof (pgc->cert);
2063 gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2064 pgc->cert, &cert_buf_size);
2065 gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2066 pgc->key, &key_buf_size);
2067 gnutls_x509_crt_deinit (request);
2073 * Function called by MHD with errors, suppresses them all.
2075 * @param cls closure
2076 * @param fm format string (`printf()`-style)
2077 * @param ap arguments to @a fm
2080 mhd_error_log_callback (void *cls,
2089 * Lookup (or create) an SSL MHD instance for a particular domain.
2091 * @param domain the domain the SSL daemon has to serve
2092 * @return NULL on error
2094 static struct MhdHttpList *
2095 lookup_ssl_httpd (const char* domain)
2097 struct MhdHttpList *hd;
2098 struct ProxyGNSCertificate *pgc;
2105 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2106 if ( (NULL != hd->domain) &&
2107 (0 == strcmp (hd->domain, domain)) )
2109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2110 "Starting fresh MHD HTTPS instance for domain `%s'\n",
2112 pgc = generate_gns_certificate (domain);
2113 hd = GNUNET_new (struct MhdHttpList);
2114 hd->is_ssl = GNUNET_YES;
2115 hd->domain = GNUNET_strdup (domain);
2116 hd->proxy_cert = pgc;
2117 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
2120 &create_response, hd,
2121 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2122 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2123 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2124 MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL,
2125 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2126 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2128 if (NULL == hd->daemon)
2134 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2142 * Task run when a Socks5Request somehow fails to be associated with
2143 * an MHD connection (i.e. because the client never speaks HTTP after
2144 * the SOCKS5 handshake). Clean up.
2146 * @param cls the `struct Socks5Request *`
2147 * @param tc sched context
2150 timeout_s5r_handshake (void *cls,
2151 const struct GNUNET_SCHEDULER_TaskContext *tc)
2153 struct Socks5Request *s5r = cls;
2155 s5r->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2161 * We're done with the Socks5 protocol, now we need to pass the
2162 * connection data through to the final destination, either
2163 * direct (if the protocol might not be HTTP), or via MHD
2164 * (if the port looks like it should be HTTP).
2166 * @param s5r socks request that has reached the final stage
2169 setup_data_transfer (struct Socks5Request *s5r)
2171 struct MhdHttpList *hd;
2173 const struct sockaddr *addr;
2179 hd = lookup_ssl_httpd (s5r->domain);
2182 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2183 _("Failed to start HTTPS server for `%s'\n"),
2191 GNUNET_assert (NULL != httpd);
2195 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2196 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2197 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2198 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2199 if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
2201 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2202 _("Failed to pass client to MHD\n"));
2207 schedule_httpd (hd);
2208 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2209 &timeout_s5r_handshake,
2214 /* ********************* SOCKS handling ************************* */
2218 * Write data from buffer to socks5 client, then continue with state machine.
2220 * @param cls the closure with the `struct Socks5Request`
2221 * @param tc scheduler context
2224 do_write (void *cls,
2225 const struct GNUNET_SCHEDULER_TaskContext *tc)
2227 struct Socks5Request *s5r = cls;
2230 s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
2231 len = GNUNET_NETWORK_socket_send (s5r->sock,
2236 /* write error: connection closed, shutdown, etc.; just clean up */
2242 s5r->wbuf_len - len);
2243 s5r->wbuf_len -= len;
2244 if (s5r->wbuf_len > 0)
2246 /* not done writing */
2248 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2254 /* we're done writing, continue with state machine! */
2261 case SOCKS5_REQUEST:
2262 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s5r->rtask);
2264 case SOCKS5_DATA_TRANSFER:
2265 setup_data_transfer (s5r);
2267 case SOCKS5_WRITE_THEN_CLEANUP:
2278 * Return a server response message indicating a failure to the client.
2280 * @param s5r request to return failure code for
2281 * @param sc status code to return
2284 signal_socks_failure (struct Socks5Request *s5r,
2285 enum Socks5StatusCode sc)
2287 struct Socks5ServerResponseMessage *s_resp;
2289 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2290 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2291 s_resp->version = SOCKS_VERSION_5;
2293 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2294 if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
2296 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2303 * Return a server response message indicating success.
2305 * @param s5r request to return success status message for
2308 signal_socks_success (struct Socks5Request *s5r)
2310 struct Socks5ServerResponseMessage *s_resp;
2312 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2313 s_resp->version = SOCKS_VERSION_5;
2314 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2315 s_resp->reserved = 0;
2316 s_resp->addr_type = SOCKS5_AT_IPV4;
2317 /* zero out IPv4 address and port */
2320 sizeof (struct in_addr) + sizeof (uint16_t));
2321 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2322 sizeof (struct in_addr) + sizeof (uint16_t);
2323 if (GNUNET_SCHEDULER_NO_TASK == s5r->wtask)
2325 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2332 * Process GNS results for target domain.
2334 * @param cls the `struct Socks5Request`
2335 * @param rd_count number of records returned
2336 * @param rd record data
2339 handle_gns_result (void *cls,
2341 const struct GNUNET_GNSRECORD_Data *rd)
2343 struct Socks5Request *s5r = cls;
2345 const struct GNUNET_GNSRECORD_Data *r;
2348 s5r->gns_lookup = NULL;
2350 for (i=0;i<rd_count;i++)
2353 switch (r->record_type)
2355 case GNUNET_DNSPARSER_TYPE_A:
2357 struct sockaddr_in *in;
2359 if (sizeof (struct in_addr) != r->data_size)
2361 GNUNET_break_op (0);
2364 if (GNUNET_YES == got_ip)
2367 GNUNET_NETWORK_test_pf (PF_INET))
2369 got_ip = GNUNET_YES;
2370 in = (struct sockaddr_in *) &s5r->destination_address;
2371 in->sin_family = AF_INET;
2372 memcpy (&in->sin_addr,
2375 in->sin_port = htons (s5r->port);
2376 #if HAVE_SOCKADDR_IN_SIN_LEN
2377 in->sin_len = sizeof (*in);
2381 case GNUNET_DNSPARSER_TYPE_AAAA:
2383 struct sockaddr_in6 *in;
2385 if (sizeof (struct in6_addr) != r->data_size)
2387 GNUNET_break_op (0);
2390 if (GNUNET_YES == got_ip)
2393 GNUNET_NETWORK_test_pf (PF_INET))
2395 /* FIXME: allow user to disable IPv6 per configuration option... */
2396 got_ip = GNUNET_YES;
2397 in = (struct sockaddr_in6 *) &s5r->destination_address;
2398 in->sin6_family = AF_INET6;
2399 memcpy (&in->sin6_addr,
2402 in->sin6_port = htons (s5r->port);
2403 #if HAVE_SOCKADDR_IN_SIN_LEN
2404 in->sin6_len = sizeof (*in);
2408 case GNUNET_GNSRECORD_TYPE_VPN:
2409 GNUNET_break (0); /* should have been translated within GNS */
2411 case GNUNET_GNSRECORD_TYPE_LEHO:
2412 GNUNET_free_non_null (s5r->leho);
2413 s5r->leho = GNUNET_strndup (r->data,
2416 case GNUNET_DNSPARSER_TYPE_TLSA:
2417 GNUNET_free_non_null (s5r->dane_data);
2418 s5r->dane_data_len = r->data_size;
2419 s5r->dane_data = GNUNET_malloc (r->data_size);
2420 memcpy (s5r->dane_data,
2429 if (GNUNET_YES != got_ip)
2431 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2432 "Name resolution failed to yield useful IP address.\n");
2433 signal_socks_failure (s5r,
2434 SOCKS5_STATUS_GENERAL_FAILURE);
2437 s5r->state = SOCKS5_DATA_TRANSFER;
2438 signal_socks_success (s5r);
2443 * Remove the first @a len bytes from the beginning of the read buffer.
2445 * @param s5r the handle clear the read buffer for
2446 * @param len number of bytes in read buffer to advance
2449 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2452 GNUNET_assert (len <= s5r->rbuf_len);
2455 s5r->rbuf_len - len);
2456 s5r->rbuf_len -= len;
2461 * Read data from incoming Socks5 connection
2463 * @param cls the closure with the `struct Socks5Request`
2464 * @param tc the scheduler context
2467 do_s5r_read (void *cls,
2468 const struct GNUNET_SCHEDULER_TaskContext *tc)
2470 struct Socks5Request *s5r = cls;
2471 const struct Socks5ClientHelloMessage *c_hello;
2472 struct Socks5ServerHelloMessage *s_hello;
2473 const struct Socks5ClientRequestMessage *c_req;
2477 s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2478 if ( (NULL != tc->read_ready) &&
2479 (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2481 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2482 &s5r->rbuf[s5r->rbuf_len],
2483 sizeof (s5r->rbuf) - s5r->rbuf_len);
2486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2487 "socks5 client disconnected.\n");
2491 s5r->rbuf_len += rlen;
2493 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2497 "Processing %u bytes of socks data in state %d\n",
2503 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2504 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2505 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2506 return; /* need more data */
2507 if (SOCKS_VERSION_5 != c_hello->version)
2509 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2510 _("Unsupported socks version %d\n"),
2511 (int) c_hello->version);
2515 clear_from_s5r_rbuf (s5r,
2516 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2517 GNUNET_assert (0 == s5r->wbuf_len);
2518 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2519 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2520 s_hello->version = SOCKS_VERSION_5;
2521 s_hello->auth_method = SOCKS_AUTH_NONE;
2522 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s5r->wtask);
2523 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2526 s5r->state = SOCKS5_REQUEST;
2528 case SOCKS5_REQUEST:
2529 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2530 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2532 switch (c_req->command)
2534 case SOCKS5_CMD_TCP_STREAM:
2538 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2539 _("Unsupported socks command %d\n"),
2540 (int) c_req->command);
2541 signal_socks_failure (s5r,
2542 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2545 switch (c_req->addr_type)
2547 case SOCKS5_AT_IPV4:
2549 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2550 const uint16_t *port = (const uint16_t *) &v4[1];
2551 struct sockaddr_in *in;
2553 s5r->port = ntohs (*port);
2554 if (HTTPS_PORT == s5r->port)
2556 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2557 _("SSL connection to plain IPv4 address requested\n"));
2558 signal_socks_failure (s5r,
2559 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2562 alen = sizeof (struct in_addr);
2563 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2564 alen + sizeof (uint16_t))
2565 return; /* need more data */
2566 in = (struct sockaddr_in *) &s5r->destination_address;
2567 in->sin_family = AF_INET;
2569 in->sin_port = *port;
2570 #if HAVE_SOCKADDR_IN_SIN_LEN
2571 in->sin_len = sizeof (*in);
2573 s5r->state = SOCKS5_DATA_TRANSFER;
2576 case SOCKS5_AT_IPV6:
2578 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2579 const uint16_t *port = (const uint16_t *) &v6[1];
2580 struct sockaddr_in6 *in;
2582 s5r->port = ntohs (*port);
2583 if (HTTPS_PORT == s5r->port)
2585 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2586 _("SSL connection to plain IPv4 address requested\n"));
2587 signal_socks_failure (s5r,
2588 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE);
2591 alen = sizeof (struct in6_addr);
2592 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2593 alen + sizeof (uint16_t))
2594 return; /* need more data */
2595 in = (struct sockaddr_in6 *) &s5r->destination_address;
2596 in->sin6_family = AF_INET6;
2597 in->sin6_addr = *v6;
2598 in->sin6_port = *port;
2599 #if HAVE_SOCKADDR_IN_SIN_LEN
2600 in->sin6_len = sizeof (*in);
2602 s5r->state = SOCKS5_DATA_TRANSFER;
2605 case SOCKS5_AT_DOMAINNAME:
2607 const uint8_t *dom_len;
2608 const char *dom_name;
2609 const uint16_t *port;
2611 dom_len = (const uint8_t *) &c_req[1];
2612 alen = *dom_len + 1;
2613 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2614 alen + sizeof (uint16_t))
2615 return; /* need more data */
2616 dom_name = (const char *) &dom_len[1];
2617 port = (const uint16_t*) &dom_name[*dom_len];
2618 s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2619 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2620 "Requested connection is to %s:%d\n",
2623 s5r->state = SOCKS5_RESOLVING;
2624 s5r->port = ntohs (*port);
2625 s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2628 GNUNET_DNSPARSER_TYPE_A,
2629 GNUNET_NO /* only cached */,
2630 (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2636 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2637 _("Unsupported socks address type %d\n"),
2638 (int) c_req->addr_type);
2639 signal_socks_failure (s5r,
2640 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2643 clear_from_s5r_rbuf (s5r,
2644 sizeof (struct Socks5ClientRequestMessage) +
2645 alen + sizeof (uint16_t));
2646 if (0 != s5r->rbuf_len)
2648 /* read more bytes than healthy, why did the client send more!? */
2649 GNUNET_break_op (0);
2650 signal_socks_failure (s5r,
2651 SOCKS5_STATUS_GENERAL_FAILURE);
2654 if (SOCKS5_DATA_TRANSFER == s5r->state)
2656 /* if we are not waiting for GNS resolution, signal success */
2657 signal_socks_success (s5r);
2659 /* We are done reading right now */
2660 GNUNET_SCHEDULER_cancel (s5r->rtask);
2661 s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2663 case SOCKS5_RESOLVING:
2666 case SOCKS5_DATA_TRANSFER:
2677 * Accept new incoming connections
2679 * @param cls the closure with the lsock4 or lsock6
2680 * @param tc the scheduler context
2683 do_accept (void *cls,
2684 const struct GNUNET_SCHEDULER_TaskContext *tc)
2686 struct GNUNET_NETWORK_Handle *lsock = cls;
2687 struct GNUNET_NETWORK_Handle *s;
2688 struct Socks5Request *s5r;
2690 if (lsock == lsock4)
2691 ltask4 = GNUNET_SCHEDULER_NO_TASK;
2693 ltask6 = GNUNET_SCHEDULER_NO_TASK;
2694 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2696 if (lsock == lsock4)
2697 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2701 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2704 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2707 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2711 "Got an inbound connection, waiting for data\n");
2712 s5r = GNUNET_new (struct Socks5Request);
2713 GNUNET_CONTAINER_DLL_insert (s5r_head,
2717 s5r->state = SOCKS5_INIT;
2718 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2724 /* ******************* General / main code ********************* */
2728 * Task run on shutdown
2730 * @param cls closure
2731 * @param tc task context
2734 do_shutdown (void *cls,
2735 const struct GNUNET_SCHEDULER_TaskContext *tc)
2737 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2738 "Shutting down...\n");
2739 while (NULL != mhd_httpd_head)
2740 kill_httpd (mhd_httpd_head);
2741 while (NULL != s5r_head)
2742 cleanup_s5r (s5r_head);
2745 GNUNET_NETWORK_socket_close (lsock4);
2750 GNUNET_NETWORK_socket_close (lsock6);
2755 GNUNET_IDENTITY_cancel (id_op);
2758 if (NULL != identity)
2760 GNUNET_IDENTITY_disconnect (identity);
2763 if (NULL != curl_multi)
2765 curl_multi_cleanup (curl_multi);
2768 if (NULL != gns_handle)
2770 GNUNET_GNS_disconnect (gns_handle);
2773 if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
2775 GNUNET_SCHEDULER_cancel (curl_download_task);
2776 curl_download_task = GNUNET_SCHEDULER_NO_TASK;
2778 if (GNUNET_SCHEDULER_NO_TASK != ltask4)
2780 GNUNET_SCHEDULER_cancel (ltask4);
2781 ltask4 = GNUNET_SCHEDULER_NO_TASK;
2783 if (GNUNET_SCHEDULER_NO_TASK != ltask6)
2785 GNUNET_SCHEDULER_cancel (ltask6);
2786 ltask6 = GNUNET_SCHEDULER_NO_TASK;
2788 gnutls_x509_crt_deinit (proxy_ca.cert);
2789 gnutls_x509_privkey_deinit (proxy_ca.key);
2790 gnutls_global_deinit ();
2795 * Create an IPv4 listen socket bound to our port.
2797 * @return NULL on error
2799 static struct GNUNET_NETWORK_Handle *
2802 struct GNUNET_NETWORK_Handle *ls;
2803 struct sockaddr_in sa4;
2806 memset (&sa4, 0, sizeof (sa4));
2807 sa4.sin_family = AF_INET;
2808 sa4.sin_port = htons (port);
2809 #if HAVE_SOCKADDR_IN_SIN_LEN
2810 sa4.sin_len = sizeof (sa4);
2812 ls = GNUNET_NETWORK_socket_create (AF_INET,
2818 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
2822 GNUNET_NETWORK_socket_close (ls);
2831 * Create an IPv6 listen socket bound to our port.
2833 * @return NULL on error
2835 static struct GNUNET_NETWORK_Handle *
2838 struct GNUNET_NETWORK_Handle *ls;
2839 struct sockaddr_in6 sa6;
2842 memset (&sa6, 0, sizeof (sa6));
2843 sa6.sin6_family = AF_INET6;
2844 sa6.sin6_port = htons (port);
2845 #if HAVE_SOCKADDR_IN_SIN_LEN
2846 sa6.sin6_len = sizeof (sa6);
2848 ls = GNUNET_NETWORK_socket_create (AF_INET6,
2854 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
2858 GNUNET_NETWORK_socket_close (ls);
2867 * Continue initialization after we have our zone information.
2872 struct MhdHttpList *hd;
2874 /* Open listen socket for socks proxy */
2875 lsock6 = bind_v6 ();
2877 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2880 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
2882 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2883 GNUNET_NETWORK_socket_close (lsock6);
2888 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2889 lsock6, &do_accept, lsock6);
2892 lsock4 = bind_v4 ();
2894 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2897 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
2899 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2900 GNUNET_NETWORK_socket_close (lsock4);
2905 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2906 lsock4, &do_accept, lsock4);
2909 if ( (NULL == lsock4) &&
2912 GNUNET_SCHEDULER_shutdown ();
2915 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
2917 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2918 "cURL global init failed!\n");
2919 GNUNET_SCHEDULER_shutdown ();
2922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2923 "Proxy listens on port %u\n",
2926 /* start MHD daemon for HTTP */
2927 hd = GNUNET_new (struct MhdHttpList);
2928 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
2931 &create_response, hd,
2932 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2933 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2934 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2936 if (NULL == hd->daemon)
2939 GNUNET_SCHEDULER_shutdown ();
2943 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2948 * Method called to inform about the egos of the shorten zone of this peer.
2950 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2951 * this function is only called ONCE, and 'NULL' being passed in
2952 * @a ego does indicate an error (i.e. name is taken or no default
2953 * value is known). If @a ego is non-NULL and if '*ctx'
2954 * is set in those callbacks, the value WILL be passed to a subsequent
2955 * call to the identity callback of #GNUNET_IDENTITY_connect (if
2956 * that one was not NULL).
2958 * @param cls closure, NULL
2959 * @param ego ego handle
2960 * @param ctx context for application to store data for this ego
2961 * (during the lifetime of this process, initially NULL)
2962 * @param name name assigned by the user for this ego,
2963 * NULL if the user just deleted the ego and it
2964 * must thus no longer be used
2967 identity_shorten_cb (void *cls,
2968 struct GNUNET_IDENTITY_Ego *ego,
2975 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2976 _("No ego configured for `shorten-zone`\n"));
2980 local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
2981 do_shorten = GNUNET_YES;
2988 * Method called to inform about the egos of the master zone of this peer.
2990 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2991 * this function is only called ONCE, and 'NULL' being passed in
2992 * @a ego does indicate an error (i.e. name is taken or no default
2993 * value is known). If @a ego is non-NULL and if '*ctx'
2994 * is set in those callbacks, the value WILL be passed to a subsequent
2995 * call to the identity callback of #GNUNET_IDENTITY_connect (if
2996 * that one was not NULL).
2998 * @param cls closure, NULL
2999 * @param ego ego handle
3000 * @param ctx context for application to store data for this ego
3001 * (during the lifetime of this process, initially NULL)
3002 * @param name name assigned by the user for this ego,
3003 * NULL if the user just deleted the ego and it
3004 * must thus no longer be used
3007 identity_master_cb (void *cls,
3008 struct GNUNET_IDENTITY_Ego *ego,
3015 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3016 _("No ego configured for `%s`\n"),
3018 GNUNET_SCHEDULER_shutdown ();
3021 GNUNET_IDENTITY_ego_get_public_key (ego,
3023 id_op = GNUNET_IDENTITY_get (identity,
3025 &identity_shorten_cb,
3031 * Main function that will be run
3033 * @param cls closure
3034 * @param args remaining command-line arguments
3035 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3036 * @param c configuration
3039 run (void *cls, char *const *args, const char *cfgfile,
3040 const struct GNUNET_CONFIGURATION_Handle *c)
3042 char* cafile_cfg = NULL;
3047 if (NULL == (curl_multi = curl_multi_init ()))
3049 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3050 "Failed to create cURL multi handle!\n");
3053 cafile = cafile_opt;
3056 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3060 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3065 cafile = cafile_cfg;
3067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3068 "Using %s as CA\n", cafile);
3070 gnutls_global_init ();
3071 gnutls_x509_crt_init (&proxy_ca.cert);
3072 gnutls_x509_privkey_init (&proxy_ca.key);
3074 if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
3075 (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
3077 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3078 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
3080 gnutls_x509_crt_deinit (proxy_ca.cert);
3081 gnutls_x509_privkey_deinit (proxy_ca.key);
3082 gnutls_global_deinit ();
3083 GNUNET_free_non_null (cafile_cfg);
3086 GNUNET_free_non_null (cafile_cfg);
3087 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
3089 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3090 "Unable to connect to GNS!\n");
3091 gnutls_x509_crt_deinit (proxy_ca.cert);
3092 gnutls_x509_privkey_deinit (proxy_ca.key);
3093 gnutls_global_deinit ();
3096 identity = GNUNET_IDENTITY_connect (cfg,
3098 id_op = GNUNET_IDENTITY_get (identity,
3100 &identity_master_cb,
3102 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
3103 &do_shutdown, NULL);
3108 * The main function for gnunet-gns-proxy.
3110 * @param argc number of arguments from the command line
3111 * @param argv command line arguments
3112 * @return 0 ok, 1 on error
3115 main (int argc, char *const *argv)
3117 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3119 gettext_noop ("listen on specified port (default: 7777)"), 1,
3120 &GNUNET_GETOPT_set_ulong, &port},
3121 {'a', "authority", NULL,
3122 gettext_noop ("pem file to use as CA"), 1,
3123 &GNUNET_GETOPT_set_string, &cafile_opt},
3124 GNUNET_GETOPT_OPTION_END
3126 static const char* page =
3127 "<html><head><title>gnunet-gns-proxy</title>"
3128 "</head><body>cURL fail</body></html>";
3131 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3133 GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3134 curl_failure_response = MHD_create_response_from_buffer (strlen (page),
3136 MHD_RESPMEM_PERSISTENT);
3140 GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3141 _("GNUnet GNS proxy"),
3143 &run, NULL)) ? 0 : 1;
3144 MHD_destroy_response (curl_failure_response);
3145 GNUNET_free_non_null ((char *) argv);
3146 GNUNET_CRYPTO_ecdsa_key_clear (&local_shorten_zone);
3150 /* end of gnunet-gns-proxy.c */