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
29 * - actually check SSL certificates (#3038)
32 #include <microhttpd.h>
33 #include <curl/curl.h>
34 #include <gnutls/gnutls.h>
35 #include <gnutls/x509.h>
36 #include <gnutls/abstract.h>
37 #include <gnutls/crypto.h>
39 #include "gnunet_util_lib.h"
40 #include "gnunet_gns_service.h"
41 #include "gnunet_identity_service.h"
46 * Default Socks5 listen port.
48 #define GNUNET_GNS_PROXY_PORT 7777
51 * Maximum supported length for a URI.
52 * Should die. @deprecated
54 #define MAX_HTTP_URI_LENGTH 2048
57 * Size of the buffer for the data upload / download. Must be
58 * enough for curl, thus CURL_MAX_WRITE_SIZE is needed here (16k).
60 #define IO_BUFFERSIZE CURL_MAX_WRITE_SIZE
63 * Size of the read/write buffers for Socks. Uses
64 * 256 bytes for the hostname (at most), plus a few
65 * bytes overhead for the messages.
67 #define SOCKS_BUFFERSIZE (256 + 32)
70 * Port for plaintext HTTP.
77 #define HTTPS_PORT 443
80 * Largest allowed size for a PEM certificate.
82 #define MAX_PEM_SIZE (10 * 1024)
85 * After how long do we clean up unused MHD SSL/TLS instances?
87 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
90 * After how long do we clean up Socks5 handles that failed to show any activity
91 * with their respective MHD instance?
93 #define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
99 * @param level log level
100 * @param fun name of curl_easy-function that gave the error
101 * @param rc return code from curl
103 #define LOG_CURL_EASY(level,fun,rc) GNUNET_log(level, _("%s failed at %s:%d: `%s'\n"), fun, __FILE__, __LINE__, curl_easy_strerror (rc))
106 /* *************** Socks protocol definitions (move to TUN?) ****************** */
109 * Which SOCKS version do we speak?
111 #define SOCKS_VERSION_5 0x05
114 * Flag to set for 'no authentication'.
116 #define SOCKS_AUTH_NONE 0
120 * Commands in Socks5.
125 * Establish TCP/IP stream.
127 SOCKS5_CMD_TCP_STREAM = 1,
130 * Establish TCP port binding.
132 SOCKS5_CMD_TCP_PORT = 2,
135 * Establish UDP port binding.
137 SOCKS5_CMD_UDP_PORT = 3
142 * Address types in Socks5.
144 enum Socks5AddressType
154 SOCKS5_AT_DOMAINNAME = 3,
165 * Status codes in Socks5 response.
167 enum Socks5StatusCode
169 SOCKS5_STATUS_REQUEST_GRANTED = 0,
170 SOCKS5_STATUS_GENERAL_FAILURE = 1,
171 SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2,
172 SOCKS5_STATUS_NETWORK_UNREACHABLE = 3,
173 SOCKS5_STATUS_HOST_UNREACHABLE = 4,
174 SOCKS5_STATUS_CONNECTION_REFUSED_BY_HOST = 5,
175 SOCKS5_STATUS_TTL_EXPIRED = 6,
176 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED = 7,
177 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED = 8
182 * Client hello in Socks5 protocol.
184 struct Socks5ClientHelloMessage
187 * Should be #SOCKS_VERSION_5.
192 * How many authentication methods does the client support.
194 uint8_t num_auth_methods;
196 /* followed by supported authentication methods, 1 byte per method */
202 * Server hello in Socks5 protocol.
204 struct Socks5ServerHelloMessage
207 * Should be #SOCKS_VERSION_5.
212 * Chosen authentication method, for us always #SOCKS_AUTH_NONE,
213 * which skips the authentication step.
220 * Client socks request in Socks5 protocol.
222 struct Socks5ClientRequestMessage
225 * Should be #SOCKS_VERSION_5.
230 * Command code, we only uspport #SOCKS5_CMD_TCP_STREAM.
235 * Reserved, always zero.
240 * Address type, an `enum Socks5AddressType`.
245 * Followed by either an ip4/ipv6 address or a domain name with a
246 * length field (uint8_t) in front (depending on @e addr_type).
247 * followed by port number in network byte order (uint16_t).
253 * Server response to client requests in Socks5 protocol.
255 struct Socks5ServerResponseMessage
258 * Should be #SOCKS_VERSION_5.
263 * Status code, an `enum Socks5StatusCode`
273 * Address type, an `enum Socks5AddressType`.
278 * Followed by either an ip4/ipv6 address or a domain name with a
279 * length field (uint8_t) in front (depending on @e addr_type).
280 * followed by port number in network byte order (uint16_t).
287 /* *********************** Datastructures for HTTP handling ****************** */
290 * A structure for CA cert/key
297 gnutls_x509_crt_t cert;
302 gnutls_x509_privkey_t key;
307 * Structure for GNS certificates
309 struct ProxyGNSCertificate
312 * The certificate as PEM
314 char cert[MAX_PEM_SIZE];
317 * The private key as PEM
319 char key[MAX_PEM_SIZE];
325 * A structure for all running Httpds
332 struct MhdHttpList *prev;
337 struct MhdHttpList *next;
340 * the domain name to server (only important for SSL)
347 struct MHD_Daemon *daemon;
350 * Optional proxy certificate used
352 struct ProxyGNSCertificate *proxy_cert;
357 GNUNET_SCHEDULER_TaskIdentifier httpd_task;
360 * is this an ssl daemon?
367 /* ***************** Datastructures for Socks handling **************** */
376 * We're waiting to get the client hello.
381 * We're waiting to get the initial request.
386 * We are currently resolving the destination.
391 * We're in transfer mode.
393 SOCKS5_DATA_TRANSFER,
396 * Finish writing the write buffer, then clean up.
398 SOCKS5_WRITE_THEN_CLEANUP,
401 * Socket has been passed to MHD, do not close it anymore.
403 SOCKS5_SOCKET_WITH_MHD,
406 * We've finished receiving upload data from MHD.
408 SOCKS5_SOCKET_UPLOAD_STARTED,
411 * We've finished receiving upload data from MHD.
413 SOCKS5_SOCKET_UPLOAD_DONE,
416 * We've finished uploading data via CURL and can now download.
418 SOCKS5_SOCKET_DOWNLOAD_STARTED,
421 * We've finished receiving download data from cURL.
423 SOCKS5_SOCKET_DOWNLOAD_DONE
429 * A structure for socks requests
437 struct Socks5Request *next;
442 struct Socks5Request *prev;
447 struct GNUNET_NETWORK_Handle *sock;
450 * Handle to GNS lookup, during #SOCKS5_RESOLVING phase.
452 struct GNUNET_GNS_LookupRequest *gns_lookup;
455 * Client socket read task
457 GNUNET_SCHEDULER_TaskIdentifier rtask;
460 * Client socket write task
462 GNUNET_SCHEDULER_TaskIdentifier wtask;
467 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
472 char rbuf[SOCKS_BUFFERSIZE];
477 char wbuf[SOCKS_BUFFERSIZE];
480 * Buffer we use for moving data between MHD and curl (in both directions).
482 char io_buf[IO_BUFFERSIZE];
485 * MHD HTTP instance handling this request, NULL for none.
487 struct MhdHttpList *hd;
490 * MHD response object for this request.
492 struct MHD_Response *response;
495 * the domain name to server (only important for SSL)
500 * DNS Legacy Host Name as given by GNS, NULL if not given.
515 * HTTP request headers for the curl request.
517 struct curl_slist *headers;
520 * HTTP response code to give to MHD for the response.
522 unsigned int response_code;
525 * Number of bytes already in read buffer
530 * Number of bytes already in write buffer
535 * Number of bytes already in the IO buffer.
540 * Once known, what's the target address for the connection?
542 struct sockaddr_storage destination_address;
547 enum SocksPhase state;
550 * Desired destination port.
558 /* *********************** Globals **************************** */
562 * The port the proxy is running on (default 7777)
564 static unsigned long port = GNUNET_GNS_PROXY_PORT;
567 * The CA file (pem) to use for the proxy CA
569 static char *cafile_opt;
572 * The listen socket of the proxy for IPv4
574 static struct GNUNET_NETWORK_Handle *lsock4;
577 * The listen socket of the proxy for IPv6
579 static struct GNUNET_NETWORK_Handle *lsock6;
582 * The listen task ID for IPv4
584 static GNUNET_SCHEDULER_TaskIdentifier ltask4;
587 * The listen task ID for IPv6
589 static GNUNET_SCHEDULER_TaskIdentifier ltask6;
592 * The cURL download task (curl multi API).
594 static GNUNET_SCHEDULER_TaskIdentifier curl_download_task;
597 * The cURL multi handle
599 static CURLM *curl_multi;
602 * Handle to the GNS service
604 static struct GNUNET_GNS_Handle *gns_handle;
607 * DLL for http/https daemons
609 static struct MhdHttpList *mhd_httpd_head;
612 * DLL for http/https daemons
614 static struct MhdHttpList *mhd_httpd_tail;
617 * Daemon for HTTP (we have one per SSL certificate, and then one for
618 * all HTTP connections; this is the one for HTTP, not HTTPS).
620 static struct MhdHttpList *httpd;
623 * DLL of active socks requests.
625 static struct Socks5Request *s5r_head;
628 * DLL of active socks requests.
630 static struct Socks5Request *s5r_tail;
633 * The users local GNS master zone
635 static struct GNUNET_CRYPTO_EcdsaPublicKey local_gns_zone;
638 * The users local shorten zone
640 static struct GNUNET_CRYPTO_EcdsaPrivateKey local_shorten_zone;
643 * Is shortening enabled?
645 static int do_shorten;
648 * The CA for SSL certificate generation
650 static struct ProxyCA proxy_ca;
653 * Response we return on cURL failures.
655 static struct MHD_Response *curl_failure_response;
658 * Connection to identity service.
660 static struct GNUNET_IDENTITY_Handle *identity;
663 * Request for our ego.
665 static struct GNUNET_IDENTITY_Operation *id_op;
670 static const struct GNUNET_CONFIGURATION_Handle *cfg;
673 /* ************************* Global helpers ********************* */
677 * Run MHD now, we have extra data ready for the callback.
679 * @param hd the daemon to run now.
682 run_mhd_now (struct MhdHttpList *hd);
686 * Clean up s5r handles.
688 * @param s5r the handle to destroy
691 cleanup_s5r (struct Socks5Request *s5r)
693 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
694 "Cleaning up socks request\n");
695 if (NULL != s5r->curl)
697 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
698 "Cleaning up cURL handle\n");
699 curl_multi_remove_handle (curl_multi, s5r->curl);
700 curl_easy_cleanup (s5r->curl);
703 curl_slist_free_all (s5r->headers);
704 if ( (NULL != s5r->response) &&
705 (curl_failure_response != s5r->response) )
706 MHD_destroy_response (s5r->response);
707 if (GNUNET_SCHEDULER_NO_TASK != s5r->rtask)
708 GNUNET_SCHEDULER_cancel (s5r->rtask);
709 if (GNUNET_SCHEDULER_NO_TASK != s5r->timeout_task)
710 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
711 if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
712 GNUNET_SCHEDULER_cancel (s5r->wtask);
713 if (NULL != s5r->gns_lookup)
714 GNUNET_GNS_lookup_cancel (s5r->gns_lookup);
715 if (NULL != s5r->sock)
717 if (SOCKS5_SOCKET_WITH_MHD <= s5r->state)
718 GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock);
720 GNUNET_NETWORK_socket_close (s5r->sock);
722 GNUNET_CONTAINER_DLL_remove (s5r_head,
725 GNUNET_free_non_null (s5r->domain);
726 GNUNET_free_non_null (s5r->leho);
727 GNUNET_free_non_null (s5r->url);
732 /* ************************* HTTP handling with cURL *********************** */
736 * Callback for MHD response generation. This function is called from
737 * MHD whenever MHD expects to get data back. Copies data from the
738 * io_buf, if available.
740 * @param cls closure with our `struct Socks5Request`
741 * @param pos in buffer
742 * @param buf where to copy data
743 * @param max available space in @a buf
744 * @return number of bytes written to @a buf
747 mhd_content_cb (void *cls,
752 struct Socks5Request *s5r = cls;
753 size_t bytes_to_copy;
755 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
756 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
758 /* we're still not done with the upload, do not yet
759 start the download, the IO buffer is still full
761 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
762 "Pausing MHD download, not yet ready for download\n");
763 return 0; /* not yet ready for data download */
765 bytes_to_copy = GNUNET_MIN (max,
767 if ( (0 == bytes_to_copy) &&
768 (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) )
770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
771 "Pausing MHD download, no data available\n");
772 return 0; /* more data later */
774 if ( (0 == bytes_to_copy) &&
775 (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) )
777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
778 "Completed MHD download\n");
779 return MHD_CONTENT_READER_END_OF_STREAM;
781 memcpy (buf, s5r->io_buf, bytes_to_copy);
782 memmove (s5r->io_buf,
783 &s5r->io_buf[bytes_to_copy],
784 s5r->io_len - bytes_to_copy);
785 s5r->io_len -= bytes_to_copy;
786 if (NULL != s5r->curl)
787 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
788 return bytes_to_copy;
793 * Check that the website has presented us with a valid SSL certificate.
794 * The certificate must either match the domain name or the LEHO name
795 * (or, if available, the TLSA record).
797 * @param s5r request to check for.
798 * @return #GNUNET_OK if the certificate is valid
801 check_ssl_certificate (struct Socks5Request *s5r)
804 struct curl_tlsinfo tlsinfo;
805 unsigned int cert_list_size;
806 const gnutls_datum_t *chainp;
808 struct curl_tlsinfo *tlsinfo;
809 struct curl_slist *to_slist;
812 memset (&tlsinfo, 0, sizeof (tlsinfo));
813 gptr.tlsinfo = &tlsinfo;
815 curl_easy_getinfo (s5r->curl,
816 CURLINFO_TLS_SESSION,
818 return GNUNET_SYSERR;
819 if (CURLSSLBACKEND_GNUTLS != tlsinfo.ssl_backend)
821 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
822 _("Unsupported CURL SSL backend %d\n"),
823 tlsinfo.ssl_backend);
824 return GNUNET_SYSERR;
826 chainp = gnutls_certificate_get_peers (tlsinfo.internals, &cert_list_size);
828 return GNUNET_SYSERR;
830 for(i=0;i<cert_list_size;i++)
832 gnutls_x509_crt_t cert;
835 if (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&cert))
837 if (GNUTLS_E_SUCCESS ==
838 gnutls_x509_crt_import (cert, &chainp[i],
839 GNUTLS_X509_FMT_DER))
841 if (GNUTLS_E_SUCCESS ==
842 gnutls_x509_crt_print (cert,
843 GNUTLS_CRT_PRINT_FULL,
846 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
847 "Certificate #%d: %.*s", i, dn.size, dn.data);
848 gnutls_free (dn.data);
851 gnutls_x509_crt_deinit (cert);
859 * We're getting an HTTP response header from cURL. Convert it to the
860 * MHD response headers. Mostly copies the headers, but makes special
861 * adjustments to "Set-Cookie" and "Location" headers as those may need
862 * to be changed from the LEHO to the domain the browser expects.
864 * @param buffer curl buffer with a single line of header data; not 0-terminated!
865 * @param size curl blocksize
866 * @param nmemb curl blocknumber
867 * @param cls our `struct Socks5Request *`
868 * @return size of processed bytes
871 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
873 struct Socks5Request *s5r = cls;
874 size_t bytes = size * nmemb;
876 const char *hdr_type;
877 const char *cookie_domain;
880 char *new_cookie_hdr;
883 size_t delta_cdomain;
887 if (NULL == s5r->response)
889 /* first, check SSL certificate */
890 if ( (HTTPS_PORT == s5r->port) &&
891 (GNUNET_OK != check_ssl_certificate (s5r)) )
894 GNUNET_break (CURLE_OK ==
895 curl_easy_getinfo (s5r->curl,
896 CURLINFO_RESPONSE_CODE,
898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
899 "Creating MHD response with code %d\n",
901 s5r->response_code = resp_code;
902 s5r->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
907 if (NULL != s5r->leho)
911 GNUNET_asprintf (&cors_hdr,
912 (HTTPS_PORT == s5r->port)
917 GNUNET_break (MHD_YES ==
918 MHD_add_response_header (s5r->response,
919 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
921 GNUNET_free (cors_hdr);
923 /* force connection to be closed after each request, as we
924 do not support HTTP pipelining */
925 GNUNET_break (MHD_YES ==
926 MHD_add_response_header (s5r->response,
927 MHD_HTTP_HEADER_CONNECTION,
931 ndup = GNUNET_strndup (buffer, bytes);
932 hdr_type = strtok (ndup, ":");
933 if (NULL == hdr_type)
938 hdr_val = strtok (NULL, "");
947 /* custom logic for certain header types */
948 new_cookie_hdr = NULL;
949 if ( (NULL != s5r->leho) &&
950 (0 == strcasecmp (hdr_type,
951 MHD_HTTP_HEADER_SET_COOKIE)) )
954 new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) +
955 strlen (s5r->domain) + 1);
957 domain_matched = GNUNET_NO; /* make sure we match domain at most once */
958 for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";"))
960 if ( (0 == strncasecmp (tok, " domain", strlen (" domain"))) &&
961 (GNUNET_NO == domain_matched) )
963 domain_matched = GNUNET_YES;
964 cookie_domain = tok + strlen (" domain") + 1;
965 if (strlen (cookie_domain) < strlen (s5r->leho))
967 delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain);
968 if (0 == strcasecmp (cookie_domain, s5r->leho + delta_cdomain))
970 offset += sprintf (new_cookie_hdr + offset,
976 else if (0 == strcmp (cookie_domain, s5r->leho))
978 offset += sprintf (new_cookie_hdr + offset,
983 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
984 _("Cookie domain `%s' supplied by server is invalid\n"),
987 memcpy (new_cookie_hdr + offset, tok, strlen (tok));
988 offset += strlen (tok);
989 new_cookie_hdr[offset++] = ';';
991 hdr_val = new_cookie_hdr;
995 if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
999 GNUNET_asprintf (&leho_host,
1000 (HTTPS_PORT != s5r->port)
1004 if (0 == strncmp (leho_host,
1006 strlen (leho_host)))
1008 GNUNET_asprintf (&new_location,
1010 (HTTPS_PORT != s5r->port)
1014 hdr_val + strlen (leho_host));
1015 hdr_val = new_location;
1017 GNUNET_free (leho_host);
1019 /* MHD does not allow certain characters in values, remove those */
1020 if (NULL != (tok = strchr (hdr_val, '\n')))
1022 if (NULL != (tok = strchr (hdr_val, '\r')))
1024 if (NULL != (tok = strchr (hdr_val, '\t')))
1026 if (0 != strlen (hdr_val))
1028 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1029 "Adding header %s: %s to MHD response\n",
1032 GNUNET_break (MHD_YES ==
1033 MHD_add_response_header (s5r->response,
1038 GNUNET_free_non_null (new_cookie_hdr);
1039 GNUNET_free_non_null (new_location);
1045 * Handle response payload data from cURL. Copies it into our `io_buf` to make
1046 * it available to MHD.
1048 * @param ptr pointer to the data
1049 * @param size number of blocks of data
1050 * @param nmemb blocksize
1051 * @param ctx our `struct Socks5Request *`
1052 * @return number of bytes handled
1055 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1057 struct Socks5Request *s5r = ctx;
1058 size_t total = size * nmemb;
1060 if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) ||
1061 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1063 /* we're still not done with the upload, do not yet
1064 start the download, the IO buffer is still full
1065 with upload data. */
1066 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1067 "Pausing CURL download, waiting for UPLOAD to finish\n");
1068 return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */
1070 if (sizeof (s5r->io_buf) - s5r->io_len < total)
1072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1073 "Pausing CURL download, not enough space\n");
1074 return CURL_WRITEFUNC_PAUSE; /* not enough space */
1076 memcpy (&s5r->io_buf[s5r->io_len],
1079 s5r->io_len += total;
1080 if (s5r->io_len == total)
1081 run_mhd_now (s5r->hd);
1087 * cURL callback for uploaded (PUT/POST) data. Copies it into our `io_buf`
1088 * to make it available to MHD.
1090 * @param buf where to write the data
1091 * @param size number of bytes per member
1092 * @param nmemb number of members available in @a buf
1093 * @param cls our `struct Socks5Request` that generated the data
1094 * @return number of bytes copied to @a buf
1097 curl_upload_cb (void *buf, size_t size, size_t nmemb, void *cls)
1099 struct Socks5Request *s5r = cls;
1100 size_t len = size * nmemb;
1103 if ( (0 == s5r->io_len) &&
1104 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1106 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1107 "Pausing CURL UPLOAD, need more data\n");
1108 return CURL_READFUNC_PAUSE;
1110 if ( (0 == s5r->io_len) &&
1111 (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) )
1113 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1115 "Completed CURL UPLOAD\n");
1116 return 0; /* upload finished, can now download */
1118 if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) ||
1119 (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) )
1122 return CURL_READFUNC_ABORT;
1124 to_copy = GNUNET_MIN (s5r->io_len,
1126 memcpy (buf, s5r->io_buf, to_copy);
1127 memmove (s5r->io_buf,
1128 &s5r->io_buf[to_copy],
1129 s5r->io_len - to_copy);
1130 s5r->io_len -= to_copy;
1131 if (s5r->io_len + to_copy == sizeof (s5r->io_buf))
1132 run_mhd_now (s5r->hd); /* got more space for upload now */
1137 /* ************************** main loop of cURL interaction ****************** */
1141 * Task that is run when we are ready to receive more data
1144 * @param cls closure
1145 * @param tc task context
1148 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1152 * Ask cURL for the select() sets and schedule cURL operations.
1155 curl_download_prepare ()
1162 struct GNUNET_NETWORK_FDSet *grs;
1163 struct GNUNET_NETWORK_FDSet *gws;
1165 struct GNUNET_TIME_Relative rtime;
1167 if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
1169 GNUNET_SCHEDULER_cancel (curl_download_task);
1170 curl_download_task = GNUNET_SCHEDULER_NO_TASK;
1176 if (CURLM_OK != (mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max)))
1178 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1179 "%s failed at %s:%d: `%s'\n",
1180 "curl_multi_fdset", __FILE__, __LINE__,
1181 curl_multi_strerror (mret));
1185 GNUNET_break (CURLM_OK == curl_multi_timeout (curl_multi, &to));
1187 rtime = GNUNET_TIME_UNIT_FOREVER_REL;
1189 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1192 grs = GNUNET_NETWORK_fdset_create ();
1193 gws = GNUNET_NETWORK_fdset_create ();
1194 GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1195 GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1196 curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1199 &curl_task_download, curl_multi);
1200 GNUNET_NETWORK_fdset_destroy (gws);
1201 GNUNET_NETWORK_fdset_destroy (grs);
1205 curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime,
1206 &curl_task_download,
1213 * Task that is run when we are ready to receive more data from curl.
1215 * @param cls closure, NULL
1216 * @param tc task context
1219 curl_task_download (void *cls,
1220 const struct GNUNET_SCHEDULER_TaskContext *tc)
1224 struct CURLMsg *msg;
1226 struct Socks5Request *s5r;
1228 curl_download_task = GNUNET_SCHEDULER_NO_TASK;
1232 mret = curl_multi_perform (curl_multi, &running);
1233 while (NULL != (msg = curl_multi_info_read (curl_multi, &msgnum)))
1235 GNUNET_break (CURLE_OK ==
1236 curl_easy_getinfo (msg->easy_handle,
1247 /* documentation says this is not used */
1251 switch (msg->data.result)
1254 case CURLE_GOT_NOTHING:
1255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1256 "CURL download completed.\n");
1257 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1258 run_mhd_now (s5r->hd);
1261 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1262 "Download curl failed: %s\n",
1263 curl_easy_strerror (msg->data.result));
1264 /* FIXME: indicate error somehow? close MHD connection badly as well? */
1265 s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE;
1266 run_mhd_now (s5r->hd);
1269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1270 "Cleaning up cURL handle\n");
1271 curl_multi_remove_handle (curl_multi, s5r->curl);
1272 curl_easy_cleanup (s5r->curl);
1274 if (NULL == s5r->response)
1275 s5r->response = curl_failure_response;
1278 /* documentation says this is not used */
1282 /* unexpected status code */
1287 } while (mret == CURLM_CALL_MULTI_PERFORM);
1288 if (CURLM_OK != mret)
1289 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1290 "%s failed at %s:%d: `%s'\n",
1291 "curl_multi_perform", __FILE__, __LINE__,
1292 curl_multi_strerror (mret));
1295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1296 "Suspending cURL multi loop, no more events pending\n");
1297 return; /* nothing more in progress */
1299 curl_download_prepare ();
1303 /* ********************************* MHD response generation ******************* */
1307 * Read HTTP request header field from the request. Copies the fields
1308 * over to the 'headers' that will be given to curl. However, 'Host'
1309 * is substituted with the LEHO if present. We also change the
1310 * 'Connection' header value to "close" as the proxy does not support
1313 * @param cls our `struct Socks5Request`
1314 * @param kind value kind
1315 * @param key field key
1316 * @param value field value
1317 * @return MHD_YES to continue to iterate
1320 con_val_iter (void *cls,
1321 enum MHD_ValueKind kind,
1325 struct Socks5Request *s5r = cls;
1328 if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, key)) &&
1329 (NULL != s5r->leho) )
1331 if (0 == strcasecmp (MHD_HTTP_HEADER_CONNECTION, key))
1333 GNUNET_asprintf (&hdr,
1337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1338 "Adding HEADER `%s' to HTTP request\n",
1340 s5r->headers = curl_slist_append (s5r->headers,
1348 * Main MHD callback for handling requests.
1351 * @param con MHD connection handle
1352 * @param url the url in the request
1353 * @param meth the HTTP method used ("GET", "PUT", etc.)
1354 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1355 * @param upload_data the data being uploaded (excluding HEADERS,
1356 * for a POST that fits into memory and that is encoded
1357 * with a supported encoding, the POST data will NOT be
1358 * given in upload_data and is instead available as
1359 * part of MHD_get_connection_values; very large POST
1360 * data *will* be made available incrementally in
1362 * @param upload_data_size set initially to the size of the
1363 * @a upload_data provided; the method must update this
1364 * value to the number of bytes NOT processed;
1365 * @param con_cls pointer to location where we store the 'struct Request'
1366 * @return MHD_YES if the connection was handled successfully,
1367 * MHD_NO if the socket must be closed due to a serious
1368 * error while handling the request
1371 create_response (void *cls,
1372 struct MHD_Connection *con,
1376 const char *upload_data,
1377 size_t *upload_data_size,
1380 /* struct MhdHttpList* hd = cls; */
1381 struct Socks5Request *s5r = *con_cls;
1383 char ipstring[INET6_ADDRSTRLEN];
1384 char ipaddr[INET6_ADDRSTRLEN + 2];
1385 const struct sockaddr *sa;
1386 const struct sockaddr_in *s4;
1387 const struct sockaddr_in6 *s6;
1396 if ( (NULL == s5r->curl) &&
1397 (SOCKS5_SOCKET_WITH_MHD == s5r->state) )
1399 /* first time here, initialize curl handle */
1400 sa = (const struct sockaddr *) &s5r->destination_address;
1401 switch (sa->sa_family)
1404 s4 = (const struct sockaddr_in *) &s5r->destination_address;
1405 if (NULL == inet_ntop (AF_INET,
1413 GNUNET_snprintf (ipaddr,
1417 port = ntohs (s4->sin_port);
1420 s6 = (const struct sockaddr_in6 *) &s5r->destination_address;
1421 if (NULL == inet_ntop (AF_INET6,
1429 GNUNET_snprintf (ipaddr,
1433 port = ntohs (s6->sin6_port);
1439 s5r->curl = curl_easy_init ();
1440 if (NULL == s5r->curl)
1441 return MHD_queue_response (con,
1442 MHD_HTTP_INTERNAL_SERVER_ERROR,
1443 curl_failure_response);
1444 curl_easy_setopt (s5r->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1445 curl_easy_setopt (s5r->curl, CURLOPT_HEADERDATA, s5r);
1446 curl_easy_setopt (s5r->curl, CURLOPT_FOLLOWLOCATION, 0);
1447 curl_easy_setopt (s5r->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1448 curl_easy_setopt (s5r->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1449 curl_easy_setopt (s5r->curl, CURLOPT_TIMEOUT, 600L);
1450 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1451 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_CONTENT_DECODING, 0);
1452 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_TRANSFER_DECODING, 0);
1453 curl_easy_setopt (s5r->curl, CURLOPT_NOSIGNAL, 1L);
1454 curl_easy_setopt (s5r->curl, CURLOPT_PRIVATE, s5r);
1455 curl_easy_setopt (s5r->curl, CURLOPT_VERBOSE, 0); // FIXME: remove later
1456 GNUNET_asprintf (&curlurl,
1457 (HTTPS_PORT != s5r->port)
1459 : "https://%s:%d%s",
1463 curl_easy_setopt (s5r->curl,
1466 GNUNET_free (curlurl);
1468 if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1470 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1471 curl_easy_setopt (s5r->curl, CURLOPT_UPLOAD, 1);
1472 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1473 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1474 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1475 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1477 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1479 s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED;
1480 curl_easy_setopt (s5r->curl, CURLOPT_POST, 1);
1481 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1482 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1483 curl_easy_setopt (s5r->curl, CURLOPT_READFUNCTION, &curl_upload_cb);
1484 curl_easy_setopt (s5r->curl, CURLOPT_READDATA, s5r);
1486 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_HEAD))
1488 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1489 curl_easy_setopt (s5r->curl, CURLOPT_NOBODY, 1);
1491 else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_GET))
1493 s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED;
1494 curl_easy_setopt (s5r->curl, CURLOPT_HTTPGET, 1);
1495 curl_easy_setopt (s5r->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1496 curl_easy_setopt (s5r->curl, CURLOPT_WRITEDATA, s5r);
1500 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1501 _("Unsupported HTTP method `%s'\n"),
1503 curl_easy_cleanup (s5r->curl);
1508 if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0))
1510 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1512 else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1))
1514 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1518 curl_easy_setopt (s5r->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE);
1521 if (HTTPS_PORT == s5r->port)
1523 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1524 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYPEER, 1L);
1525 /* Disable cURL checking the hostname, as we will check ourselves
1526 as only we have the domain name or the LEHO or the DANE record */
1527 curl_easy_setopt (s5r->curl, CURLOPT_SSL_VERIFYHOST, 0L);
1531 curl_easy_setopt (s5r->curl, CURLOPT_USE_SSL, CURLUSESSL_NONE);
1534 if (CURLM_OK != curl_multi_add_handle (curl_multi, s5r->curl))
1537 curl_easy_cleanup (s5r->curl);
1541 MHD_get_connection_values (con,
1543 &con_val_iter, s5r);
1544 curl_easy_setopt (s5r->curl, CURLOPT_HTTPHEADER, s5r->headers);
1545 curl_download_prepare ();
1549 /* continuing to process request */
1550 if (0 != *upload_data_size)
1552 left = GNUNET_MIN (*upload_data_size,
1553 sizeof (s5r->io_buf) - s5r->io_len);
1554 memcpy (&s5r->io_buf[s5r->io_len],
1557 s5r->io_len += left;
1558 *upload_data_size -= left;
1559 GNUNET_assert (NULL != s5r->curl);
1560 curl_easy_pause (s5r->curl, CURLPAUSE_CONT);
1561 curl_download_prepare ();
1564 if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state)
1566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1567 "Finished processing UPLOAD\n");
1568 s5r->state = SOCKS5_SOCKET_UPLOAD_DONE;
1570 if (NULL == s5r->response)
1571 return MHD_YES; /* too early to queue response, did not yet get headers from cURL */
1572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1573 "Queueing response with MHD\n");
1574 return MHD_queue_response (con,
1580 /* ******************** MHD HTTP setup and event loop ******************** */
1584 * Function called when MHD decides that we are done with a connection.
1587 * @param connection connection handle
1588 * @param con_cls value as set by the last call to
1589 * the MHD_AccessHandlerCallback, should be our `struct Socks5Request`
1590 * @param toe reason for request termination (ignored)
1593 mhd_completed_cb (void *cls,
1594 struct MHD_Connection *connection,
1596 enum MHD_RequestTerminationCode toe)
1598 struct Socks5Request *s5r = *con_cls;
1602 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
1603 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1604 "MHD encountered error handling request: %d\n",
1612 * Function called when MHD first processes an incoming connection.
1613 * Gives us the respective URI information.
1615 * We use this to associate the `struct MHD_Connection` with our
1616 * internal `struct Socks5Request` data structure (by checking
1617 * for matching sockets).
1619 * @param cls the HTTP server handle (a `struct MhdHttpList`)
1620 * @param url the URL that is being requested
1621 * @param connection MHD connection object for the request
1622 * @return the `struct Socks5Request` that this @a connection is for
1625 mhd_log_callback (void *cls,
1627 struct MHD_Connection *connection)
1629 struct Socks5Request *s5r;
1630 const union MHD_ConnectionInfo *ci;
1633 ci = MHD_get_connection_info (connection,
1634 MHD_CONNECTION_INFO_CONNECTION_FD);
1640 sock = ci->connect_fd;
1641 for (s5r = s5r_head; NULL != s5r; s5r = s5r->next)
1643 if (GNUNET_NETWORK_get_fd (s5r->sock) == sock)
1645 if (NULL != s5r->url)
1650 s5r->url = GNUNET_strdup (url);
1651 GNUNET_SCHEDULER_cancel (s5r->timeout_task);
1652 s5r->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1661 * Kill the given MHD daemon.
1663 * @param hd daemon to stop
1666 kill_httpd (struct MhdHttpList *hd)
1668 GNUNET_CONTAINER_DLL_remove (mhd_httpd_head,
1671 GNUNET_free_non_null (hd->domain);
1672 MHD_stop_daemon (hd->daemon);
1673 if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1675 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1676 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
1678 GNUNET_free_non_null (hd->proxy_cert);
1686 * Task run whenever HTTP server is idle for too long. Kill it.
1688 * @param cls the `struct MhdHttpList *`
1689 * @param tc sched context
1692 kill_httpd_task (void *cls,
1693 const struct GNUNET_SCHEDULER_TaskContext *tc)
1695 struct MhdHttpList *hd = cls;
1697 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
1703 * Task run whenever HTTP server operations are pending.
1705 * @param cls the `struct MhdHttpList *` of the daemon that is being run
1706 * @param tc sched context
1709 do_httpd (void *cls,
1710 const struct GNUNET_SCHEDULER_TaskContext *tc);
1714 * Schedule MHD. This function should be called initially when an
1715 * MHD is first getting its client socket, and will then automatically
1716 * always be called later whenever there is work to be done.
1718 * @param hd the daemon to schedule
1721 schedule_httpd (struct MhdHttpList *hd)
1726 struct GNUNET_NETWORK_FDSet *wrs;
1727 struct GNUNET_NETWORK_FDSet *wws;
1730 MHD_UNSIGNED_LONG_LONG timeout;
1731 struct GNUNET_TIME_Relative tv;
1737 if (MHD_YES != MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max))
1742 haveto = MHD_get_timeout (hd->daemon, &timeout);
1743 if (MHD_YES == haveto)
1744 tv.rel_value_us = (uint64_t) timeout * 1000LL;
1746 tv = GNUNET_TIME_UNIT_FOREVER_REL;
1749 wrs = GNUNET_NETWORK_fdset_create ();
1750 wws = GNUNET_NETWORK_fdset_create ();
1751 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1752 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1759 if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1760 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1761 if ( (MHD_YES != haveto) &&
1765 /* daemon is idle, kill after timeout */
1766 hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT,
1773 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1778 GNUNET_NETWORK_fdset_destroy (wrs);
1780 GNUNET_NETWORK_fdset_destroy (wws);
1785 * Task run whenever HTTP server operations are pending.
1787 * @param cls the `struct MhdHttpList` of the daemon that is being run
1788 * @param tc scheduler context
1791 do_httpd (void *cls,
1792 const struct GNUNET_SCHEDULER_TaskContext *tc)
1794 struct MhdHttpList *hd = cls;
1796 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
1797 MHD_run (hd->daemon);
1798 schedule_httpd (hd);
1803 * Run MHD now, we have extra data ready for the callback.
1805 * @param hd the daemon to run now.
1808 run_mhd_now (struct MhdHttpList *hd)
1810 if (GNUNET_SCHEDULER_NO_TASK !=
1812 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1813 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
1819 * Read file in filename
1821 * @param filename file to read
1822 * @param size pointer where filesize is stored
1823 * @return NULL on error
1826 load_file (const char* filename,
1833 GNUNET_DISK_file_size (filename, &fsize,
1834 GNUNET_YES, GNUNET_YES))
1836 if (fsize > MAX_PEM_SIZE)
1838 *size = (unsigned int) fsize;
1839 buffer = GNUNET_malloc (*size);
1840 if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
1842 GNUNET_free (buffer);
1850 * Load PEM key from file
1852 * @param key where to store the data
1853 * @param keyfile path to the PEM file
1854 * @return #GNUNET_OK on success
1857 load_key_from_file (gnutls_x509_privkey_t key,
1858 const char* keyfile)
1860 gnutls_datum_t key_data;
1863 key_data.data = load_file (keyfile, &key_data.size);
1864 if (NULL == key_data.data)
1865 return GNUNET_SYSERR;
1866 ret = gnutls_x509_privkey_import (key, &key_data,
1867 GNUTLS_X509_FMT_PEM);
1868 if (GNUTLS_E_SUCCESS != ret)
1870 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1871 _("Unable to import private key from file `%s'\n"),
1874 GNUNET_free_non_null (key_data.data);
1875 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
1880 * Load cert from file
1882 * @param crt struct to store data in
1883 * @param certfile path to pem file
1884 * @return #GNUNET_OK on success
1887 load_cert_from_file (gnutls_x509_crt_t crt,
1888 const char* certfile)
1890 gnutls_datum_t cert_data;
1893 cert_data.data = load_file (certfile, &cert_data.size);
1894 if (NULL == cert_data.data)
1895 return GNUNET_SYSERR;
1896 ret = gnutls_x509_crt_import (crt, &cert_data,
1897 GNUTLS_X509_FMT_PEM);
1898 if (GNUTLS_E_SUCCESS != ret)
1900 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1901 _("Unable to import certificate %s\n"), certfile);
1903 GNUNET_free_non_null (cert_data.data);
1904 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
1909 * Generate new certificate for specific name
1911 * @param name the subject name to generate a cert for
1912 * @return a struct holding the PEM data, NULL on error
1914 static struct ProxyGNSCertificate *
1915 generate_gns_certificate (const char *name)
1917 unsigned int serial;
1918 size_t key_buf_size;
1919 size_t cert_buf_size;
1920 gnutls_x509_crt_t request;
1923 struct ProxyGNSCertificate *pgc;
1925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1926 "Generating TLS/SSL certificate for `%s'\n",
1928 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request));
1929 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key));
1930 pgc = GNUNET_new (struct ProxyGNSCertificate);
1931 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
1933 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
1934 0, "GNU Name System", 4);
1935 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
1936 0, name, strlen (name));
1937 GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_version (request, 3));
1938 gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
1939 gnutls_x509_crt_set_serial (request,
1942 etime = time (NULL);
1943 tm_data = localtime (&etime);
1944 gnutls_x509_crt_set_activation_time (request,
1947 etime = mktime (tm_data);
1948 gnutls_x509_crt_set_expiration_time (request,
1950 gnutls_x509_crt_sign (request,
1953 key_buf_size = sizeof (pgc->key);
1954 cert_buf_size = sizeof (pgc->cert);
1955 gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
1956 pgc->cert, &cert_buf_size);
1957 gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
1958 pgc->key, &key_buf_size);
1959 gnutls_x509_crt_deinit (request);
1965 * Lookup (or create) an SSL MHD instance for a particular domain.
1967 * @param domain the domain the SSL daemon has to serve
1968 * @return NULL on errro
1970 static struct MhdHttpList *
1971 lookup_ssl_httpd (const char* domain)
1973 struct MhdHttpList *hd;
1974 struct ProxyGNSCertificate *pgc;
1976 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
1977 if ( (NULL != hd->domain) &&
1978 (0 == strcmp (hd->domain, domain)) )
1980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1981 "Starting fresh MHD HTTPS instance for domain `%s'\n",
1983 pgc = generate_gns_certificate (domain);
1984 hd = GNUNET_new (struct MhdHttpList);
1985 hd->is_ssl = GNUNET_YES;
1986 hd->domain = GNUNET_strdup (domain);
1987 hd->proxy_cert = pgc;
1988 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET,
1991 &create_response, hd,
1992 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
1993 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
1994 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
1995 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
1996 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
1998 if (NULL == hd->daemon)
2004 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head,
2012 * Task run when a Socks5Request somehow fails to be associated with
2013 * an MHD connection (i.e. because the client never speaks HTTP after
2014 * the SOCKS5 handshake). Clean up.
2016 * @param cls the `struct Socks5Request *`
2017 * @param tc sched context
2020 timeout_s5r_handshake (void *cls,
2021 const struct GNUNET_SCHEDULER_TaskContext *tc)
2023 struct Socks5Request *s5r = cls;
2025 s5r->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2031 * We're done with the Socks5 protocol, now we need to pass the
2032 * connection data through to the final destination, either
2033 * direct (if the protocol might not be HTTP), or via MHD
2034 * (if the port looks like it should be HTTP).
2036 * @param s5r socks request that has reached the final stage
2039 setup_data_transfer (struct Socks5Request *s5r)
2041 struct MhdHttpList *hd;
2043 const struct sockaddr *addr;
2049 hd = lookup_ssl_httpd (s5r->domain);
2052 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2053 _("Failed to start HTTPS server for `%s'\n"),
2061 GNUNET_assert (NULL != httpd);
2065 fd = GNUNET_NETWORK_get_fd (s5r->sock);
2066 addr = GNUNET_NETWORK_get_addr (s5r->sock);
2067 len = GNUNET_NETWORK_get_addrlen (s5r->sock);
2068 s5r->state = SOCKS5_SOCKET_WITH_MHD;
2069 if (MHD_YES != MHD_add_connection (hd->daemon, fd, addr, len))
2071 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2072 _("Failed to pass client to MHD\n"));
2077 schedule_httpd (hd);
2078 s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT,
2079 &timeout_s5r_handshake,
2084 /* ********************* SOCKS handling ************************* */
2088 * Write data from buffer to socks5 client, then continue with state machine.
2090 * @param cls the closure with the `struct Socks5Request`
2091 * @param tc scheduler context
2094 do_write (void *cls,
2095 const struct GNUNET_SCHEDULER_TaskContext *tc)
2097 struct Socks5Request *s5r = cls;
2100 s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
2101 len = GNUNET_NETWORK_socket_send (s5r->sock,
2106 /* write error: connection closed, shutdown, etc.; just clean up */
2112 s5r->wbuf_len - len);
2113 s5r->wbuf_len -= len;
2114 if (s5r->wbuf_len > 0)
2116 /* not done writing */
2118 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2124 /* we're done writing, continue with state machine! */
2131 case SOCKS5_REQUEST:
2132 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s5r->rtask);
2134 case SOCKS5_DATA_TRANSFER:
2135 setup_data_transfer (s5r);
2137 case SOCKS5_WRITE_THEN_CLEANUP:
2148 * Return a server response message indicating a failure to the client.
2150 * @param s5r request to return failure code for
2151 * @param sc status code to return
2154 signal_socks_failure (struct Socks5Request *s5r,
2155 enum Socks5StatusCode sc)
2157 struct Socks5ServerResponseMessage *s_resp;
2159 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2160 memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage));
2161 s_resp->version = SOCKS_VERSION_5;
2163 s5r->state = SOCKS5_WRITE_THEN_CLEANUP;
2164 if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
2166 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2173 * Return a server response message indicating success.
2175 * @param s5r request to return success status message for
2178 signal_socks_success (struct Socks5Request *s5r)
2180 struct Socks5ServerResponseMessage *s_resp;
2182 s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len];
2183 s_resp->version = SOCKS_VERSION_5;
2184 s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED;
2185 s_resp->reserved = 0;
2186 s_resp->addr_type = SOCKS5_AT_IPV4;
2187 /* zero out IPv4 address and port */
2190 sizeof (struct in_addr) + sizeof (uint16_t));
2191 s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) +
2192 sizeof (struct in_addr) + sizeof (uint16_t);
2193 if (GNUNET_SCHEDULER_NO_TASK == s5r->wtask)
2195 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2202 * Process GNS results for target domain.
2204 * @param cls the `struct Socks5Request`
2205 * @param rd_count number of records returned
2206 * @param rd record data
2209 handle_gns_result (void *cls,
2211 const struct GNUNET_GNSRECORD_Data *rd)
2213 struct Socks5Request *s5r = cls;
2215 const struct GNUNET_GNSRECORD_Data *r;
2218 s5r->gns_lookup = NULL;
2220 for (i=0;i<rd_count;i++)
2223 switch (r->record_type)
2225 case GNUNET_DNSPARSER_TYPE_A:
2227 struct sockaddr_in *in;
2229 if (sizeof (struct in_addr) != r->data_size)
2231 GNUNET_break_op (0);
2234 if (GNUNET_YES == got_ip)
2237 GNUNET_NETWORK_test_pf (PF_INET))
2239 got_ip = GNUNET_YES;
2240 in = (struct sockaddr_in *) &s5r->destination_address;
2241 in->sin_family = AF_INET;
2242 memcpy (&in->sin_addr,
2245 in->sin_port = htons (s5r->port);
2246 #if HAVE_SOCKADDR_IN_SIN_LEN
2247 in->sin_len = sizeof (*in);
2251 case GNUNET_DNSPARSER_TYPE_AAAA:
2253 struct sockaddr_in6 *in;
2255 if (sizeof (struct in6_addr) != r->data_size)
2257 GNUNET_break_op (0);
2260 if (GNUNET_YES == got_ip)
2263 GNUNET_NETWORK_test_pf (PF_INET))
2265 /* FIXME: allow user to disable IPv6 per configuration option... */
2266 got_ip = GNUNET_YES;
2267 in = (struct sockaddr_in6 *) &s5r->destination_address;
2268 in->sin6_family = AF_INET6;
2269 memcpy (&in->sin6_addr,
2272 in->sin6_port = htons (s5r->port);
2273 #if HAVE_SOCKADDR_IN_SIN_LEN
2274 in->sin6_len = sizeof (*in);
2278 case GNUNET_GNSRECORD_TYPE_VPN:
2279 GNUNET_break (0); /* should have been translated within GNS */
2281 case GNUNET_GNSRECORD_TYPE_LEHO:
2282 GNUNET_free_non_null (s5r->leho);
2283 s5r->leho = GNUNET_strndup (r->data,
2291 if (GNUNET_YES != got_ip)
2293 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2294 "Name resolution failed to yield useful IP address.\n");
2295 signal_socks_failure (s5r,
2296 SOCKS5_STATUS_GENERAL_FAILURE);
2299 s5r->state = SOCKS5_DATA_TRANSFER;
2300 signal_socks_success (s5r);
2305 * Remove the first @a len bytes from the beginning of the read buffer.
2307 * @param s5r the handle clear the read buffer for
2308 * @param len number of bytes in read buffer to advance
2311 clear_from_s5r_rbuf (struct Socks5Request *s5r,
2314 GNUNET_assert (len <= s5r->rbuf_len);
2317 s5r->rbuf_len - len);
2318 s5r->rbuf_len -= len;
2323 * Read data from incoming Socks5 connection
2325 * @param cls the closure with the `struct Socks5Request`
2326 * @param tc the scheduler context
2329 do_s5r_read (void *cls,
2330 const struct GNUNET_SCHEDULER_TaskContext *tc)
2332 struct Socks5Request *s5r = cls;
2333 const struct Socks5ClientHelloMessage *c_hello;
2334 struct Socks5ServerHelloMessage *s_hello;
2335 const struct Socks5ClientRequestMessage *c_req;
2339 s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2340 if ( (NULL != tc->read_ready) &&
2341 (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) )
2343 rlen = GNUNET_NETWORK_socket_recv (s5r->sock,
2344 &s5r->rbuf[s5r->rbuf_len],
2345 sizeof (s5r->rbuf) - s5r->rbuf_len);
2348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2349 "socks5 client disconnected.\n");
2353 s5r->rbuf_len += rlen;
2355 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2359 "Processing %u bytes of socks data in state %d\n",
2365 c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf;
2366 if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) ||
2367 (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) )
2368 return; /* need more data */
2369 if (SOCKS_VERSION_5 != c_hello->version)
2371 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2372 _("Unsupported socks version %d\n"),
2373 (int) c_hello->version);
2377 clear_from_s5r_rbuf (s5r,
2378 sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods);
2379 GNUNET_assert (0 == s5r->wbuf_len);
2380 s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf;
2381 s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage);
2382 s_hello->version = SOCKS_VERSION_5;
2383 s_hello->auth_method = SOCKS_AUTH_NONE;
2384 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s5r->wtask);
2385 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2388 s5r->state = SOCKS5_REQUEST;
2390 case SOCKS5_REQUEST:
2391 c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf;
2392 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage))
2394 switch (c_req->command)
2396 case SOCKS5_CMD_TCP_STREAM:
2400 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2401 _("Unsupported socks command %d\n"),
2402 (int) c_req->command);
2403 signal_socks_failure (s5r,
2404 SOCKS5_STATUS_COMMAND_NOT_SUPPORTED);
2407 switch (c_req->addr_type)
2409 case SOCKS5_AT_IPV4:
2411 const struct in_addr *v4 = (const struct in_addr *) &c_req[1];
2412 const uint16_t *port = (const uint16_t *) &v4[1];
2413 struct sockaddr_in *in;
2415 s5r->port = ntohs (*port);
2416 alen = sizeof (struct in_addr);
2417 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2418 alen + sizeof (uint16_t))
2419 return; /* need more data */
2420 in = (struct sockaddr_in *) &s5r->destination_address;
2421 in->sin_family = AF_INET;
2423 in->sin_port = *port;
2424 #if HAVE_SOCKADDR_IN_SIN_LEN
2425 in->sin_len = sizeof (*in);
2427 s5r->state = SOCKS5_DATA_TRANSFER;
2430 case SOCKS5_AT_IPV6:
2432 const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1];
2433 const uint16_t *port = (const uint16_t *) &v6[1];
2434 struct sockaddr_in6 *in;
2436 s5r->port = ntohs (*port);
2437 alen = sizeof (struct in6_addr);
2438 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2439 alen + sizeof (uint16_t))
2440 return; /* need more data */
2441 in = (struct sockaddr_in6 *) &s5r->destination_address;
2442 in->sin6_family = AF_INET6;
2443 in->sin6_addr = *v6;
2444 in->sin6_port = *port;
2445 #if HAVE_SOCKADDR_IN_SIN_LEN
2446 in->sin6_len = sizeof (*in);
2448 s5r->state = SOCKS5_DATA_TRANSFER;
2451 case SOCKS5_AT_DOMAINNAME:
2453 const uint8_t *dom_len;
2454 const char *dom_name;
2455 const uint16_t *port;
2457 dom_len = (const uint8_t *) &c_req[1];
2458 alen = *dom_len + 1;
2459 if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) +
2460 alen + sizeof (uint16_t))
2461 return; /* need more data */
2462 dom_name = (const char *) &dom_len[1];
2463 port = (const uint16_t*) &dom_name[*dom_len];
2464 s5r->domain = GNUNET_strndup (dom_name, *dom_len);
2465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2466 "Requested connection is to %s:%d\n",
2469 s5r->state = SOCKS5_RESOLVING;
2470 s5r->port = ntohs (*port);
2471 s5r->gns_lookup = GNUNET_GNS_lookup (gns_handle,
2474 GNUNET_DNSPARSER_TYPE_A,
2475 GNUNET_NO /* only cached */,
2476 (GNUNET_YES == do_shorten) ? &local_shorten_zone : NULL,
2482 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2483 _("Unsupported socks address type %d\n"),
2484 (int) c_req->addr_type);
2485 signal_socks_failure (s5r,
2486 SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED);
2489 clear_from_s5r_rbuf (s5r,
2490 sizeof (struct Socks5ClientRequestMessage) +
2491 alen + sizeof (uint16_t));
2492 if (0 != s5r->rbuf_len)
2494 /* read more bytes than healthy, why did the client send more!? */
2495 GNUNET_break_op (0);
2496 signal_socks_failure (s5r,
2497 SOCKS5_STATUS_GENERAL_FAILURE);
2500 if (SOCKS5_DATA_TRANSFER == s5r->state)
2502 /* if we are not waiting for GNS resolution, signal success */
2503 signal_socks_success (s5r);
2505 /* We are done reading right now */
2506 GNUNET_SCHEDULER_cancel (s5r->rtask);
2507 s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2509 case SOCKS5_RESOLVING:
2512 case SOCKS5_DATA_TRANSFER:
2523 * Accept new incoming connections
2525 * @param cls the closure with the lsock4 or lsock6
2526 * @param tc the scheduler context
2529 do_accept (void *cls,
2530 const struct GNUNET_SCHEDULER_TaskContext *tc)
2532 struct GNUNET_NETWORK_Handle *lsock = cls;
2533 struct GNUNET_NETWORK_Handle *s;
2534 struct Socks5Request *s5r;
2536 if (lsock == lsock4)
2537 ltask4 = GNUNET_SCHEDULER_NO_TASK;
2539 ltask6 = GNUNET_SCHEDULER_NO_TASK;
2540 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2542 if (lsock == lsock4)
2543 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2547 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2550 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2553 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2556 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2557 "Got an inbound connection, waiting for data\n");
2558 s5r = GNUNET_new (struct Socks5Request);
2559 GNUNET_CONTAINER_DLL_insert (s5r_head,
2563 s5r->state = SOCKS5_INIT;
2564 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2570 /* ******************* General / main code ********************* */
2574 * Task run on shutdown
2576 * @param cls closure
2577 * @param tc task context
2580 do_shutdown (void *cls,
2581 const struct GNUNET_SCHEDULER_TaskContext *tc)
2583 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2584 "Shutting down...\n");
2585 while (NULL != mhd_httpd_head)
2586 kill_httpd (mhd_httpd_head);
2587 while (NULL != s5r_head)
2588 cleanup_s5r (s5r_head);
2591 GNUNET_NETWORK_socket_close (lsock4);
2596 GNUNET_NETWORK_socket_close (lsock6);
2601 GNUNET_IDENTITY_cancel (id_op);
2604 if (NULL != identity)
2606 GNUNET_IDENTITY_disconnect (identity);
2609 if (NULL != curl_multi)
2611 curl_multi_cleanup (curl_multi);
2614 if (NULL != gns_handle)
2616 GNUNET_GNS_disconnect (gns_handle);
2619 if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
2621 GNUNET_SCHEDULER_cancel (curl_download_task);
2622 curl_download_task = GNUNET_SCHEDULER_NO_TASK;
2624 if (GNUNET_SCHEDULER_NO_TASK != ltask4)
2626 GNUNET_SCHEDULER_cancel (ltask4);
2627 ltask4 = GNUNET_SCHEDULER_NO_TASK;
2629 if (GNUNET_SCHEDULER_NO_TASK != ltask6)
2631 GNUNET_SCHEDULER_cancel (ltask6);
2632 ltask6 = GNUNET_SCHEDULER_NO_TASK;
2634 gnutls_x509_crt_deinit (proxy_ca.cert);
2635 gnutls_x509_privkey_deinit (proxy_ca.key);
2636 gnutls_global_deinit ();
2641 * Create an IPv4 listen socket bound to our port.
2643 * @return NULL on error
2645 static struct GNUNET_NETWORK_Handle *
2648 struct GNUNET_NETWORK_Handle *ls;
2649 struct sockaddr_in sa4;
2652 memset (&sa4, 0, sizeof (sa4));
2653 sa4.sin_family = AF_INET;
2654 sa4.sin_port = htons (port);
2655 #if HAVE_SOCKADDR_IN_SIN_LEN
2656 sa4.sin_len = sizeof (sa4);
2658 ls = GNUNET_NETWORK_socket_create (AF_INET,
2664 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
2668 GNUNET_NETWORK_socket_close (ls);
2677 * Create an IPv6 listen socket bound to our port.
2679 * @return NULL on error
2681 static struct GNUNET_NETWORK_Handle *
2684 struct GNUNET_NETWORK_Handle *ls;
2685 struct sockaddr_in6 sa6;
2688 memset (&sa6, 0, sizeof (sa6));
2689 sa6.sin6_family = AF_INET6;
2690 sa6.sin6_port = htons (port);
2691 #if HAVE_SOCKADDR_IN_SIN_LEN
2692 sa6.sin6_len = sizeof (sa6);
2694 ls = GNUNET_NETWORK_socket_create (AF_INET6,
2700 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
2704 GNUNET_NETWORK_socket_close (ls);
2713 * Continue initialization after we have our zone information.
2718 struct MhdHttpList *hd;
2720 /* Open listen socket for socks proxy */
2721 lsock6 = bind_v6 ();
2723 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2726 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
2728 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2729 GNUNET_NETWORK_socket_close (lsock6);
2734 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2735 lsock6, &do_accept, lsock6);
2738 lsock4 = bind_v4 ();
2740 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
2743 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
2745 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
2746 GNUNET_NETWORK_socket_close (lsock4);
2751 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2752 lsock4, &do_accept, lsock4);
2755 if ( (NULL == lsock4) &&
2758 GNUNET_SCHEDULER_shutdown ();
2761 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
2763 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2764 "cURL global init failed!\n");
2765 GNUNET_SCHEDULER_shutdown ();
2768 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2769 "Proxy listens on port %u\n",
2772 /* start MHD daemon for HTTP */
2773 hd = GNUNET_new (struct MhdHttpList);
2774 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
2777 &create_response, hd,
2778 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2779 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
2780 MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL,
2782 if (NULL == hd->daemon)
2785 GNUNET_SCHEDULER_shutdown ();
2789 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2794 * Method called to inform about the egos of the shorten zone of this peer.
2796 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2797 * this function is only called ONCE, and 'NULL' being passed in
2798 * @a ego does indicate an error (i.e. name is taken or no default
2799 * value is known). If @a ego is non-NULL and if '*ctx'
2800 * is set in those callbacks, the value WILL be passed to a subsequent
2801 * call to the identity callback of #GNUNET_IDENTITY_connect (if
2802 * that one was not NULL).
2804 * @param cls closure, NULL
2805 * @param ego ego handle
2806 * @param ctx context for application to store data for this ego
2807 * (during the lifetime of this process, initially NULL)
2808 * @param name name assigned by the user for this ego,
2809 * NULL if the user just deleted the ego and it
2810 * must thus no longer be used
2813 identity_shorten_cb (void *cls,
2814 struct GNUNET_IDENTITY_Ego *ego,
2821 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2822 _("No ego configured for `shorten-zone`\n"));
2826 local_shorten_zone = *GNUNET_IDENTITY_ego_get_private_key (ego);
2827 do_shorten = GNUNET_YES;
2834 * Method called to inform about the egos of the master zone of this peer.
2836 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
2837 * this function is only called ONCE, and 'NULL' being passed in
2838 * @a ego does indicate an error (i.e. name is taken or no default
2839 * value is known). If @a ego is non-NULL and if '*ctx'
2840 * is set in those callbacks, the value WILL be passed to a subsequent
2841 * call to the identity callback of #GNUNET_IDENTITY_connect (if
2842 * that one was not NULL).
2844 * @param cls closure, NULL
2845 * @param ego ego handle
2846 * @param ctx context for application to store data for this ego
2847 * (during the lifetime of this process, initially NULL)
2848 * @param name name assigned by the user for this ego,
2849 * NULL if the user just deleted the ego and it
2850 * must thus no longer be used
2853 identity_master_cb (void *cls,
2854 struct GNUNET_IDENTITY_Ego *ego,
2861 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2862 _("No ego configured for `%s`\n"),
2864 GNUNET_SCHEDULER_shutdown ();
2867 GNUNET_IDENTITY_ego_get_public_key (ego,
2869 id_op = GNUNET_IDENTITY_get (identity,
2871 &identity_shorten_cb,
2877 * Main function that will be run
2879 * @param cls closure
2880 * @param args remaining command-line arguments
2881 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2882 * @param c configuration
2885 run (void *cls, char *const *args, const char *cfgfile,
2886 const struct GNUNET_CONFIGURATION_Handle *c)
2888 char* cafile_cfg = NULL;
2892 if (NULL == (curl_multi = curl_multi_init ()))
2894 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2895 "Failed to create cURL multi handle!\n");
2898 cafile = cafile_opt;
2901 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
2905 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2910 cafile = cafile_cfg;
2912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2913 "Using %s as CA\n", cafile);
2915 gnutls_global_init ();
2916 gnutls_x509_crt_init (&proxy_ca.cert);
2917 gnutls_x509_privkey_init (&proxy_ca.key);
2919 if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
2920 (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
2922 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2923 _("Failed to load SSL/TLS key and certificate from `%s'\n"),
2925 gnutls_x509_crt_deinit (proxy_ca.cert);
2926 gnutls_x509_privkey_deinit (proxy_ca.key);
2927 gnutls_global_deinit ();
2928 GNUNET_free_non_null (cafile_cfg);
2931 GNUNET_free_non_null (cafile_cfg);
2932 if (NULL == (gns_handle = GNUNET_GNS_connect (cfg)))
2934 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2935 "Unable to connect to GNS!\n");
2936 gnutls_x509_crt_deinit (proxy_ca.cert);
2937 gnutls_x509_privkey_deinit (proxy_ca.key);
2938 gnutls_global_deinit ();
2941 identity = GNUNET_IDENTITY_connect (cfg,
2943 id_op = GNUNET_IDENTITY_get (identity,
2945 &identity_master_cb,
2947 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2948 &do_shutdown, NULL);
2953 * The main function for gnunet-gns-proxy.
2955 * @param argc number of arguments from the command line
2956 * @param argv command line arguments
2957 * @return 0 ok, 1 on error
2960 main (int argc, char *const *argv)
2962 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2964 gettext_noop ("listen on specified port (default: 7777)"), 1,
2965 &GNUNET_GETOPT_set_ulong, &port},
2966 {'a', "authority", NULL,
2967 gettext_noop ("pem file to use as CA"), 1,
2968 &GNUNET_GETOPT_set_string, &cafile_opt},
2969 GNUNET_GETOPT_OPTION_END
2971 static const char* page =
2972 "<html><head><title>gnunet-gns-proxy</title>"
2973 "</head><body>cURL fail</body></html>";
2976 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
2978 GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
2979 curl_failure_response = MHD_create_response_from_buffer (strlen (page),
2981 MHD_RESPMEM_PERSISTENT);
2985 GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
2986 _("GNUnet GNS proxy"),
2988 &run, NULL)) ? 0 : 1;
2989 MHD_destroy_response (curl_failure_response);
2990 GNUNET_free_non_null ((char *) argv);
2991 GNUNET_CRYPTO_ecdsa_key_clear (&local_shorten_zone);
2995 /* end of gnunet-gns-proxy.c */