2 This file is part of GNUnet.
3 (C) 2012 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.
22 #include <gnunet_util_lib.h>
23 #include <gnunet_gns_service.h>
24 #include <microhttpd.h>
25 #include <curl/curl.h>
27 #include "gns_proxy_proto.h"
31 #include <gnutls/gnutls.h>
32 #include <gnutls/x509.h>
33 #include <gnutls/abstract.h>
34 #include <gnutls/crypto.h>
37 #define GNUNET_GNS_PROXY_PORT 7777
38 #define MHD_MAX_CONNECTIONS 300
40 /* MHD/cURL defines */
41 #define BUF_WAIT_FOR_CURL 0
42 #define BUF_WAIT_FOR_MHD 1
43 #define BUF_WAIT_FOR_PP 2
44 #define HTML_HDR_CONTENT "Content-Type: text/html"
46 /* buffer padding for proper RE matching */
47 #define CURL_BUF_PADDING 1000
50 //#define RE_DOTPLUS "<a href=\"http://(([A-Za-z]+[.])+)([+])"
51 #define RE_A_HREF "href=\"https?://(([A-Za-z0-9]+[.])+)([+]|[a-z]+)"
52 #define RE_N_MATCHES 4
54 /* The usual suspects */
56 #define HTTPS_PORT 443
60 * A structure for CA cert/key
65 gnutls_x509_crt_t cert;
68 gnutls_x509_privkey_t key;
71 #define MAX_PEM_SIZE (10 * 1024)
74 * Structure for GNS certificates
76 struct ProxyGNSCertificate
78 /* The certificate as PEM */
79 char cert[MAX_PEM_SIZE];
81 /* The private key as PEM */
82 char key[MAX_PEM_SIZE];
87 * A structure for socks requests
91 /* The client socket */
92 struct GNUNET_NETWORK_Handle *sock;
94 /* The server socket */
95 struct GNUNET_NETWORK_Handle *remote_sock;
100 /* Client socket read task */
101 GNUNET_SCHEDULER_TaskIdentifier rtask;
103 /* Server socket read task */
104 GNUNET_SCHEDULER_TaskIdentifier fwdrtask;
106 /* Client socket write task */
107 GNUNET_SCHEDULER_TaskIdentifier wtask;
109 /* Server socket write task */
110 GNUNET_SCHEDULER_TaskIdentifier fwdwtask;
118 /* Length of data in read buffer */
119 unsigned int rbuf_len;
121 /* Length of data in write buffer */
122 unsigned int wbuf_len;
124 /* This handle is scheduled for cleanup? */
127 /* Shall we close the client socket on cleanup? */
132 * DLL for Network Handles
134 struct NetworkHandleList
137 struct NetworkHandleList *next;
140 struct NetworkHandleList *prev;
143 struct GNUNET_NETWORK_Handle *h;
147 * A structure for all running Httpds
152 struct MhdHttpList *prev;
155 struct MhdHttpList *next;
157 /* is this an ssl daemon? */
160 /* the domain name to server (only important for SSL) */
163 /* The daemon handle */
164 struct MHD_Daemon *daemon;
166 /* Optional proxy certificate used */
167 struct ProxyGNSCertificate *proxy_cert;
170 GNUNET_SCHEDULER_TaskIdentifier httpd_task;
172 /* Handles associated with this daemon */
173 struct NetworkHandleList *socket_handles_head;
175 /* Handles associated with this daemon */
176 struct NetworkHandleList *socket_handles_tail;
180 * A structure for MHD<->cURL streams
185 struct ProxyCurlTask *prev;
188 struct ProxyCurlTask *next;
193 /* Optional header replacements for curl (LEHO) */
194 struct curl_slist *headers;
196 /* Optional resolver replacements for curl (LEHO) */
197 struct curl_slist *resolver;
199 /* curl response code */
200 long curl_response_code;
202 /* The URL to fetch */
205 /* The cURL write buffer / MHD read buffer */
206 char buffer[CURL_MAX_WRITE_SIZE + CURL_BUF_PADDING];
208 /* Read pos of the data in the buffer */
209 char *buffer_read_ptr;
211 /* Write pos in the buffer */
212 char *buffer_write_ptr;
214 /* The buffer status (BUF_WAIT_FOR_CURL or BUF_WAIT_FOR_MHD) */
217 /* Number of bytes in buffer */
218 unsigned int bytes_in_buffer;
220 /* Indicates wheather the download is in progress */
221 int download_in_progress;
223 /* Indicates wheather the download was successful */
224 int download_is_finished;
226 /* Indicates wheather the download failed */
229 /* Indicates wheather we need to parse HTML */
232 /* Indicates wheather we are postprocessing the HTML right now */
233 int is_postprocessing;
235 /* Indicates wheather postprocessing has finished */
239 GNUNET_SCHEDULER_TaskIdentifier pp_task;
242 struct ProxyREMatch *pp_match_head;
245 struct ProxyREMatch *pp_match_tail;
247 /* The authority of the corresponding host (site of origin) */
250 /* The hostname (Host header field) */
253 /* The LEgacy HOstname (can be empty) */
256 /* The associated daemon list entry */
257 struct MhdHttpList *mhd;
259 /* The associated response */
260 struct MHD_Response *response;
263 struct ProxySetCookieHeader *set_cookies_head;
266 struct ProxySetCookieHeader *set_cookies_tail;
268 /* connection status */
275 struct MHD_Connection *connection;
278 size_t put_read_offset;
279 size_t put_read_size;
284 * Struct for RE matches in postprocessing of HTML
289 struct ProxyREMatch *next;
292 struct ProxyREMatch *prev;
301 struct GNUNET_GNS_ShortenRequest *shorten_task;
306 /* start of match in buffer */
309 /* end of match in buffer */
312 /* associated proxycurltask */
313 struct ProxyCurlTask *ctask;
317 * Struct for set-cookies
319 struct ProxySetCookieHeader
322 struct ProxySetCookieHeader *next;
325 struct ProxySetCookieHeader *prev;
331 /* The port the proxy is running on (default 7777) */
332 static unsigned long port = GNUNET_GNS_PROXY_PORT;
334 /* The CA file (pem) to use for the proxy CA */
335 static char* cafile_opt;
337 /* The listen socket of the proxy */
338 static struct GNUNET_NETWORK_Handle *lsock;
340 /* The listen task ID */
341 GNUNET_SCHEDULER_TaskIdentifier ltask;
343 /* The cURL download task */
344 GNUNET_SCHEDULER_TaskIdentifier curl_download_task;
346 /* The non SSL httpd daemon handle */
347 static struct MHD_Daemon *httpd;
349 /* Number of current mhd connections */
350 static unsigned int total_mhd_connections;
352 /* The cURL multi handle */
353 static CURLM *curl_multi;
355 /* Handle to the GNS service */
356 static struct GNUNET_GNS_Handle *gns_handle;
358 /* DLL for ProxyCurlTasks */
359 static struct ProxyCurlTask *ctasks_head;
361 /* DLL for ProxyCurlTasks */
362 static struct ProxyCurlTask *ctasks_tail;
364 /* DLL for http daemons */
365 static struct MhdHttpList *mhd_httpd_head;
367 /* DLL for http daemons */
368 static struct MhdHttpList *mhd_httpd_tail;
370 /* Handle to the regex for dotplus (.+) replacement in HTML */
371 static regex_t re_dotplus;
373 /* The users local GNS zone hash */
374 static struct GNUNET_CRYPTO_ShortHashCode local_gns_zone;
376 /* The users local private zone */
377 static struct GNUNET_CRYPTO_ShortHashCode local_private_zone;
379 /* The users local shorten zone */
380 static struct GNUNET_CRYPTO_ShortHashCode local_shorten_zone;
382 /* The CA for SSL certificate generation */
383 static struct ProxyCA proxy_ca;
385 /* UNIX domain socket for mhd */
386 struct GNUNET_NETWORK_Handle *mhd_unix_socket;
388 /* Shorten zone private key */
389 struct GNUNET_CRYPTO_RsaPrivateKey *shorten_zonekey;
392 * Checks if name is in tld
394 * @param name the name to check
395 * @param tld the TLD to check for
396 * @return GNUNET_YES or GNUNET_NO
399 is_tld(const char* name, const char* tld)
403 if (strlen(name) <= strlen(tld))
406 offset = strlen(name) - strlen(tld);
407 if (0 != strcmp (name+offset, tld))
409 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
410 "%s is not in .%s TLD\n", name, tld);
418 get_uri_val_iter (void *cls,
419 enum MHD_ValueKind kind,
425 sprintf (buf+strlen (buf), "?%s=%s", key, value);
431 * Read HTTP request header field 'Host'
433 * @param cls buffer to write to
434 * @param kind value kind
435 * @param key field key
436 * @param value field value
437 * @return MHD_NO when Host found
440 con_val_iter (void *cls,
441 enum MHD_ValueKind kind,
445 struct ProxyCurlTask *ctask = cls;
446 char* buf = ctask->host;
450 if (0 == strcmp ("Host", key))
456 if (0 == strcmp ("Accept-Encoding", key))
461 cstr = GNUNET_malloc (strlen (key) + strlen (hdr_val) + 3);
462 GNUNET_snprintf (cstr, strlen (key) + strlen (hdr_val) + 3,
463 "%s: %s", key, hdr_val);
465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
466 "Client Header: %s\n", cstr);
468 ctask->headers = curl_slist_append (ctask->headers, cstr);
476 * Callback for MHD response
479 * @param pos in buffer
481 * @param max space in buffer
482 * @return number of bytes written
485 mhd_content_cb (void *cls,
491 * Check HTTP response header for mime
493 * @param buffer curl buffer
494 * @param size curl blocksize
495 * @param nmemb curl blocknumber
497 * @return size of read bytes
500 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
502 size_t bytes = size * nmemb;
503 struct ProxyCurlTask *ctask = cls;
504 int html_mime_len = strlen (HTML_HDR_CONTENT);
505 int cookie_hdr_len = strlen (MHD_HTTP_HEADER_SET_COOKIE);
506 char hdr_mime[html_mime_len+1];
507 char hdr_generic[bytes+1];
508 char new_cookie_hdr[bytes+strlen (ctask->leho)+1];
517 if (NULL == ctask->response)
519 /* FIXME: get total size from curl (if available) */
520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
521 "Creating response for %s\n", ctask->url);
522 ctask->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
523 sizeof (ctask->buffer),
527 ctask->ready_to_queue = GNUNET_YES;
531 if (html_mime_len <= bytes)
533 memcpy (hdr_mime, buffer, html_mime_len);
534 hdr_mime[html_mime_len] = '\0';
536 if (0 == strcmp (hdr_mime, HTML_HDR_CONTENT))
538 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
539 "Got HTML HTTP response header\n");
540 ctask->parse_content = GNUNET_YES;
544 if (cookie_hdr_len > bytes)
547 memcpy (hdr_generic, buffer, bytes);
548 hdr_generic[bytes] = '\0';
550 if ('\n' == hdr_generic[bytes-1])
551 hdr_generic[bytes-1] = '\0';
553 if (hdr_generic[bytes-2] == '\r')
554 hdr_generic[bytes-2] = '\0';
556 if (0 == memcmp (hdr_generic,
557 MHD_HTTP_HEADER_SET_COOKIE,
560 ndup = GNUNET_strdup (hdr_generic+cookie_hdr_len+1);
561 memset (new_cookie_hdr, 0, sizeof (new_cookie_hdr));
562 tok = strtok (ndup, ";");
564 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
565 "Looking for cookie in : %s\n", hdr_generic);
567 for (; tok != NULL; tok = strtok (NULL, ";"))
569 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
570 "Got Cookie token: %s\n", tok);
571 //memcpy (new_cookie_hdr+offset, tok, strlen (tok));
572 if (0 == memcmp (tok, " domain", strlen (" domain")))
574 cookie_domain = tok + strlen (" domain") + 1;
576 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
577 "Got Set-Cookie Domain: %s\n", cookie_domain);
579 if (strlen (cookie_domain) < strlen (ctask->leho))
581 delta_cdomain = strlen (ctask->leho) - strlen (cookie_domain);
582 if (0 == strcmp (cookie_domain, ctask->leho + (delta_cdomain)))
584 GNUNET_snprintf (new_cookie_hdr+offset,
585 sizeof (new_cookie_hdr),
586 " domain=%s", ctask->authority);
587 offset += strlen (" domain=") + strlen (ctask->authority);
588 new_cookie_hdr[offset] = ';';
593 else if (strlen (cookie_domain) == strlen (ctask->leho))
595 if (0 == strcmp (cookie_domain, ctask->leho))
597 GNUNET_snprintf (new_cookie_hdr+offset,
598 sizeof (new_cookie_hdr),
599 " domain=%s", ctask->host);
600 offset += strlen (" domain=") + strlen (ctask->host);
601 new_cookie_hdr[offset] = ';';
606 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
607 "Cookie domain invalid\n");
611 memcpy (new_cookie_hdr+offset, tok, strlen (tok));
612 offset += strlen (tok);
613 new_cookie_hdr[offset] = ';';
619 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
620 "Got Set-Cookie HTTP header %s\n", new_cookie_hdr);
622 if (GNUNET_NO == MHD_add_response_header (ctask->response,
623 MHD_HTTP_HEADER_SET_COOKIE,
626 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
627 "MHD: Error adding set-cookie header field %s\n",
628 hdr_generic+cookie_hdr_len+1);
633 ndup = GNUNET_strdup (hdr_generic);
634 hdr_type = strtok (ndup, ":");
636 if (NULL == hdr_type)
642 hdr_val = strtok (NULL, "");
650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
651 "Trying to set %s: %s\n",
654 if (GNUNET_NO == MHD_add_response_header (ctask->response,
658 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
659 "MHD: Error adding %s header field %s\n",
670 * @param hd a http daemon list entry
673 run_httpd (struct MhdHttpList *hd);
684 * Task run whenever HTTP server operations are pending.
687 * @param tc sched context
691 const struct GNUNET_SCHEDULER_TaskContext *tc);
694 run_mhd_now (struct MhdHttpList *hd)
696 if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
699 "MHD: killing old task\n");
700 GNUNET_SCHEDULER_cancel (hd->httpd_task);
702 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
703 "MHD: Scheduling MHD now\n");
704 hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd, hd);
708 * Ask cURL for the select sets and schedule download
711 curl_download_prepare ();
714 * Callback to free content
716 * @param cls content to free
717 * @param tc task context
720 mhd_content_free (void *cls,
721 const struct GNUNET_SCHEDULER_TaskContext *tc)
723 struct ProxyCurlTask *ctask = cls;
724 GNUNET_assert (NULL == ctask->pp_match_head);
726 if (NULL != ctask->headers)
727 curl_slist_free_all (ctask->headers);
729 if (NULL != ctask->headers)
730 curl_slist_free_all (ctask->resolver);
732 if (NULL != ctask->response)
733 MHD_destroy_response (ctask->response);
741 * Callback for MHD response
744 * @param pos in buffer
746 * @param max space in buffer
747 * @return number of bytes written
750 mhd_content_cb (void *cls,
755 struct ProxyCurlTask *ctask = cls;
756 struct ProxyREMatch *re_match = ctask->pp_match_head;
758 long long int bytes_to_copy = ctask->buffer_write_ptr - ctask->buffer_read_ptr;
760 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
761 "MHD: content cb for %s. To copy: %lld\n",
762 ctask->url, bytes_to_copy);
763 GNUNET_assert (bytes_to_copy >= 0);
765 if ((GNUNET_YES == ctask->download_is_finished) &&
766 (GNUNET_NO == ctask->download_error) &&
767 (0 == bytes_to_copy) &&
768 (BUF_WAIT_FOR_CURL == ctask->buf_status))
770 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
771 "MHD: sending response for %s\n", ctask->url);
772 ctask->download_in_progress = GNUNET_NO;
773 run_mhd_now (ctask->mhd);
774 GNUNET_SCHEDULER_add_now (&mhd_content_free, ctask);
775 total_mhd_connections--;
776 return MHD_CONTENT_READER_END_OF_STREAM;
779 if ((GNUNET_YES == ctask->download_error) &&
780 (GNUNET_YES == ctask->download_is_finished) &&
781 (0 == bytes_to_copy) &&
782 (BUF_WAIT_FOR_CURL == ctask->buf_status))
784 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
785 "MHD: sending error response\n");
786 ctask->download_in_progress = GNUNET_NO;
787 run_mhd_now (ctask->mhd);
788 GNUNET_SCHEDULER_add_now (&mhd_content_free, ctask);
789 total_mhd_connections--;
790 return MHD_CONTENT_READER_END_WITH_ERROR;
793 if ( ctask->buf_status == BUF_WAIT_FOR_CURL )
797 for (; NULL != re_match; re_match = ctask->pp_match_head)
799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
800 "MHD: Processing PP %s\n",
802 bytes_to_copy = re_match->start - ctask->buffer_read_ptr;
803 GNUNET_assert (bytes_to_copy >= 0);
805 if (bytes_to_copy+copied > max)
807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
808 "MHD: buffer in response too small for %d. Using available space (%d). (%s)\n",
812 memcpy (buf+copied, ctask->buffer_read_ptr, max-copied);
813 ctask->buffer_read_ptr += max-copied;
815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
816 "MHD: copied %d bytes\n", copied);
820 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
821 "MHD: copying %d bytes to mhd response at offset %d\n",
822 bytes_to_copy, ctask->buffer_read_ptr);
823 memcpy (buf+copied, ctask->buffer_read_ptr, bytes_to_copy);
824 copied += bytes_to_copy;
826 if (GNUNET_NO == re_match->done)
828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
829 "MHD: Waiting for PP of %s\n", re_match->hostname);
830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
831 "MHD: copied %d bytes\n", copied);
832 ctask->buffer_read_ptr += bytes_to_copy;
836 if (strlen (re_match->result) > (max - copied))
838 //FIXME partially copy domain here
839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
840 "MHD: buffer in response too small for %s! (%s)\n",
843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
844 "MHD: copied %d bytes\n", copied);
845 ctask->buffer_read_ptr += bytes_to_copy;
849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
850 "MHD: Adding PP result %s to buffer\n",
852 memcpy (buf+copied, re_match->result, strlen (re_match->result));
853 copied += strlen (re_match->result);
854 ctask->buffer_read_ptr = re_match->end;
855 GNUNET_CONTAINER_DLL_remove (ctask->pp_match_head,
856 ctask->pp_match_tail,
858 GNUNET_free (re_match);
861 bytes_to_copy = ctask->buffer_write_ptr - ctask->buffer_read_ptr;
863 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864 "MHD: copied: %d left: %d, space left in buf: %d\n",
866 bytes_to_copy, max-copied);
868 GNUNET_assert (0 <= bytes_to_copy);
870 if (GNUNET_NO == ctask->download_is_finished)
872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
873 "MHD: Purging buffer\n");
874 memmove (ctask->buffer, ctask->buffer_read_ptr, bytes_to_copy);
875 ctask->buffer_read_ptr = ctask->buffer;
876 ctask->buffer_write_ptr = ctask->buffer + bytes_to_copy;
877 ctask->buffer[bytes_to_copy] = '\0';
880 if (bytes_to_copy+copied > max)
881 bytes_to_copy = max-copied;
883 if (0 > bytes_to_copy)
886 memcpy (buf+copied, ctask->buffer_read_ptr, bytes_to_copy);
887 ctask->buffer_read_ptr += bytes_to_copy;
888 copied += bytes_to_copy;
889 ctask->buf_status = BUF_WAIT_FOR_CURL;
891 if (NULL != ctask->curl)
892 curl_easy_pause (ctask->curl, CURLPAUSE_CONT);
894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
895 "MHD: copied %d bytes\n", copied);
896 run_mhd_now (ctask->mhd);
901 * Shorten result callback
903 * @param cls the proxycurltask
904 * @param short_name the shortened name (NULL on error)
907 process_shorten (void* cls, const char* short_name)
909 struct ProxyREMatch *re_match = cls;
910 char result[sizeof (re_match->result)];
912 if (NULL == short_name)
914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
915 "PP: Unable to shorten %s\n",
917 GNUNET_CONTAINER_DLL_remove (re_match->ctask->pp_match_head,
918 re_match->ctask->pp_match_tail,
920 GNUNET_free (re_match);
924 if (0 == strcmp (short_name, re_match->ctask->leho))
925 strcpy (result, re_match->ctask->host);
927 strcpy (result, short_name);
929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930 "PP: Shorten %s -> %s\n",
934 if (re_match->ctask->mhd->is_ssl)
935 sprintf (re_match->result, "href=\"https://%s", result);
937 sprintf (re_match->result, "href=\"http://%s", result);
939 re_match->done = GNUNET_YES;
940 run_mhd_now (re_match->ctask->mhd);
945 * Postprocess data in buffer. From read ptr to write ptr
947 * @param cls the curlproxytask
948 * @param tc task context
951 postprocess_buffer (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
953 struct ProxyCurlTask *ctask = cls;
954 struct ProxyREMatch *re_match;
955 char* re_ptr = ctask->buffer_read_ptr;
956 char re_hostname[255];
957 regmatch_t m[RE_N_MATCHES];
959 ctask->pp_task = GNUNET_SCHEDULER_NO_TASK;
961 if (GNUNET_YES != ctask->parse_content)
963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964 "PP: Not parsing content\n");
965 ctask->buf_status = BUF_WAIT_FOR_MHD;
966 run_mhd_now (ctask->mhd);
970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
971 "PP: We need to parse the HTML\n");
973 /* 0 means match found */
974 while (0 == regexec (&re_dotplus, re_ptr, RE_N_MATCHES, m, 0))
976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
977 "PP: regex match\n");
979 GNUNET_assert (m[1].rm_so != -1);
981 memset (re_hostname, 0, sizeof (re_hostname));
982 memcpy (re_hostname, re_ptr+m[1].rm_so, (m[3].rm_eo-m[1].rm_so));
984 re_match = GNUNET_malloc (sizeof (struct ProxyREMatch));
985 re_match->start = re_ptr + m[0].rm_so;
986 re_match->end = re_ptr + m[3].rm_eo;
987 re_match->done = GNUNET_NO;
988 re_match->ctask = ctask;
989 strcpy (re_match->hostname, re_hostname);
990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
991 "PP: Got hostname %s\n", re_hostname);
992 re_ptr += m[3].rm_eo;
994 if (GNUNET_YES == is_tld (re_match->hostname, GNUNET_GNS_TLD_PLUS))
996 re_match->hostname[strlen(re_match->hostname)-1] = '\0';
997 strcpy (re_match->hostname+strlen(re_match->hostname),
1001 re_match->shorten_task = GNUNET_GNS_shorten_zone (gns_handle,
1003 &local_private_zone,
1004 &local_shorten_zone,
1007 re_match); //FIXME cancel appropriately
1009 GNUNET_CONTAINER_DLL_insert_tail (ctask->pp_match_head,
1010 ctask->pp_match_tail,
1014 ctask->buf_status = BUF_WAIT_FOR_MHD;
1015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1016 "PP: No more matches\n");
1017 run_mhd_now (ctask->mhd);
1021 * Handle data from cURL
1023 * @param ptr pointer to the data
1024 * @param size number of blocks of data
1025 * @param nmemb blocksize
1026 * @param ctx the curlproxytask
1027 * @return number of bytes handled
1030 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1032 const char *cbuf = ptr;
1033 size_t total = size * nmemb;
1034 struct ProxyCurlTask *ctask = ctx;
1035 size_t buf_space = sizeof (ctask->buffer) -
1036 (ctask->buffer_write_ptr-ctask->buffer);
1038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1039 "CURL: Got %d. %d free in buffer\n",
1042 if (total > (buf_space - CURL_BUF_PADDING))
1044 if (ctask->buf_status == BUF_WAIT_FOR_CURL)
1046 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1047 "CURL: Buffer full starting postprocessing\n");
1048 ctask->buf_status = BUF_WAIT_FOR_PP;
1049 ctask->pp_task = GNUNET_SCHEDULER_add_now (&postprocess_buffer,
1051 return CURL_WRITEFUNC_PAUSE;
1054 /* we should not get called in that case */
1055 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1056 "CURL: called out of context and no space in buffer!\n");
1057 return CURL_WRITEFUNC_PAUSE;
1060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1061 "CURL: Copying %d bytes to buffer (%s)\n", total, ctask->url);
1062 memcpy (ctask->buffer_write_ptr, cbuf, total);
1063 ctask->bytes_in_buffer += total;
1064 ctask->buffer_write_ptr += total;
1065 ctask->buffer_write_ptr[0] = '\0';
1071 * Task that is run when we are ready to receive more data
1074 * @param cls closure
1075 * @param tc task context
1078 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1081 * Ask cURL for the select sets and schedule download
1084 curl_download_prepare ()
1091 struct GNUNET_NETWORK_FDSet *grs;
1092 struct GNUNET_NETWORK_FDSet *gws;
1094 struct GNUNET_TIME_Relative rtime;
1100 mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max);
1102 if (mret != CURLM_OK)
1104 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1105 "%s failed at %s:%d: `%s'\n",
1106 "curl_multi_fdset", __FILE__, __LINE__,
1107 curl_multi_strerror (mret));
1108 //TODO cleanup here?
1112 mret = curl_multi_timeout (curl_multi, &to);
1113 rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1116 "cURL multi fds: max=%d timeout=%llu\n", max, to);
1118 grs = GNUNET_NETWORK_fdset_create ();
1119 gws = GNUNET_NETWORK_fdset_create ();
1120 GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1121 GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1122 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123 "Scheduling task cURL\n");
1125 if (curl_download_task != GNUNET_SCHEDULER_NO_TASK)
1126 GNUNET_SCHEDULER_cancel (curl_download_task);
1130 curl_download_task =
1131 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1134 &curl_task_download, curl_multi);
1136 else if (NULL != ctasks_head)
1138 /* as specified in curl docs */
1139 curl_download_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1140 &curl_task_download,
1143 GNUNET_NETWORK_fdset_destroy (gws);
1144 GNUNET_NETWORK_fdset_destroy (grs);
1150 * Task that is run when we are ready to receive more data
1153 * @param cls closure
1154 * @param tc task context
1157 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1161 struct CURLMsg *msg;
1163 struct ProxyCurlTask *ctask;
1167 struct ProxyCurlTask *clean_head = NULL;
1168 struct ProxyCurlTask *clean_tail = NULL;
1170 curl_download_task = GNUNET_SCHEDULER_NO_TASK;
1172 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1174 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1175 "Shutdown requested while trying to download\n");
1179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1187 mret = curl_multi_perform (curl_multi, &running);
1189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1190 "Running curl tasks: %d\n", running);
1192 ctask = ctasks_head;
1193 for (; ctask != NULL; ctask = ctask->next)
1195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1196 "CTask: %s\n", ctask->url);
1200 if (num_ctasks != running)
1202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1203 "%d ctasks, %d curl running\n", num_ctasks, running);
1208 ctask = ctasks_head;
1209 msg = curl_multi_info_read (curl_multi, &msgnum);
1210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1211 "Messages left: %d\n", msgnum);
1218 if ((msg->data.result != CURLE_OK) &&
1219 (msg->data.result != CURLE_GOT_NOTHING))
1221 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1222 "Download curl failed");
1224 for (; ctask != NULL; ctask = ctask->next)
1226 if (NULL == ctask->curl)
1229 if (memcmp (msg->easy_handle, ctask->curl, sizeof (CURL)) != 0)
1232 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1233 "CURL: Download failed for task %s: %s.\n",
1235 curl_easy_strerror (msg->data.result));
1236 ctask->download_is_finished = GNUNET_YES;
1237 ctask->download_error = GNUNET_YES;
1238 if (CURLE_OK == curl_easy_getinfo (ctask->curl,
1239 CURLINFO_RESPONSE_CODE,
1241 ctask->curl_response_code = resp_code;
1242 ctask->ready_to_queue = MHD_YES;
1243 ctask->buf_status = BUF_WAIT_FOR_MHD;
1244 run_mhd_now (ctask->mhd);
1246 GNUNET_CONTAINER_DLL_remove (ctasks_head, ctasks_tail,
1248 GNUNET_CONTAINER_DLL_insert (clean_head, clean_tail, ctask);
1251 GNUNET_assert (ctask != NULL);
1255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1256 "CURL: download completed.\n");
1258 for (; ctask != NULL; ctask = ctask->next)
1260 if (NULL == ctask->curl)
1263 if (memcmp (msg->easy_handle, ctask->curl, sizeof (CURL)) != 0)
1266 if (ctask->buf_status != BUF_WAIT_FOR_CURL)
1269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1270 "CURL: completed task %s found.\n", ctask->url);
1271 if (CURLE_OK == curl_easy_getinfo (ctask->curl,
1272 CURLINFO_RESPONSE_CODE,
1274 ctask->curl_response_code = resp_code;
1277 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1278 "CURL: Completed ctask!\n");
1279 if (GNUNET_SCHEDULER_NO_TASK == ctask->pp_task)
1281 ctask->buf_status = BUF_WAIT_FOR_PP;
1282 ctask->pp_task = GNUNET_SCHEDULER_add_now (&postprocess_buffer,
1286 ctask->ready_to_queue = MHD_YES;
1287 ctask->download_is_finished = GNUNET_YES;
1289 /* We MUST not modify the multi handle else we loose messages */
1290 GNUNET_CONTAINER_DLL_remove (ctasks_head, ctasks_tail,
1292 GNUNET_CONTAINER_DLL_insert (clean_head, clean_tail, ctask);
1296 GNUNET_assert (ctask != NULL);
1298 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1299 "CURL: %s\n", curl_easy_strerror(msg->data.result));
1305 } while (msgnum > 0);
1307 for (ctask=clean_head; ctask != NULL; ctask = ctask->next)
1309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1310 "CURL: Removing task %s.\n", ctask->url);
1311 curl_multi_remove_handle (curl_multi, ctask->curl);
1312 curl_easy_cleanup (ctask->curl);
1317 for (ctask=ctasks_head; ctask != NULL; ctask = ctask->next)
1322 if (num_ctasks != running)
1324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1325 "CURL: %d tasks, %d running\n", num_ctasks, running);
1328 GNUNET_assert ( num_ctasks == running );
1330 } while (mret == CURLM_CALL_MULTI_PERFORM);
1332 if (mret != CURLM_OK)
1334 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "CURL: %s failed at %s:%d: `%s'\n",
1335 "curl_multi_perform", __FILE__, __LINE__,
1336 curl_multi_strerror (mret));
1338 curl_download_prepare();
1342 * Process LEHO lookup
1344 * @param cls the ctask
1345 * @param rd_count number of records returned
1346 * @param rd record data
1349 process_leho_lookup (void *cls,
1351 const struct GNUNET_NAMESTORE_RecordData *rd)
1353 struct ProxyCurlTask *ctask = cls;
1354 char hosthdr[262]; //256 + "Host: "
1358 struct hostent *phost;
1360 char resolvename[512];
1363 strcpy (ctask->leho, "");
1366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1367 "No LEHO present!\n");
1369 for (i=0; i<rd_count; i++)
1371 if (rd[i].record_type != GNUNET_GNS_RECORD_LEHO)
1374 memcpy (ctask->leho, rd[i].data, rd[i].data_size);
1376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1377 "Found LEHO %s for %s\n", ctask->leho, ctask->url);
1380 if (0 != strcmp (ctask->leho, ""))
1382 sprintf (hosthdr, "%s%s", "Host: ", ctask->leho);
1383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1384 "New HTTP header value: %s\n", hosthdr);
1385 ctask->headers = curl_slist_append (ctask->headers, hosthdr);
1386 GNUNET_assert (NULL != ctask->headers);
1387 ret = curl_easy_setopt (ctask->curl, CURLOPT_HTTPHEADER, ctask->headers);
1388 if (CURLE_OK != ret)
1390 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s failed at %s:%d: `%s'\n",
1391 "curl_easy_setopt", __FILE__, __LINE__, curl_easy_strerror(ret));
1396 if (ctask->mhd->is_ssl)
1398 phost = (struct hostent*)gethostbyname (ctask->host);
1402 ssl_ip = inet_ntoa(*((struct in_addr*)(phost->h_addr)));
1403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1404 "SSL target server: %s\n", ssl_ip);
1405 sprintf (resolvename, "%s:%d:%s", ctask->leho, HTTPS_PORT, ssl_ip);
1406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1407 "Curl resolve: %s\n", resolvename);
1408 ctask->resolver = curl_slist_append ( ctask->resolver, resolvename);
1409 curl_easy_setopt (ctask->curl, CURLOPT_RESOLVE, ctask->resolver);
1410 sprintf (curlurl, "https://%s%s", ctask->leho, ctask->url);
1411 curl_easy_setopt (ctask->curl, CURLOPT_URL, curlurl);
1415 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1416 "gethostbyname failed for %s!\n", ctask->host);
1417 ctask->download_is_finished = GNUNET_YES;
1418 ctask->download_error = GNUNET_YES;
1423 if (CURLM_OK != (mret=curl_multi_add_handle (curl_multi, ctask->curl)))
1425 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1426 "%s failed at %s:%d: `%s'\n",
1427 "curl_multi_add_handle", __FILE__, __LINE__,
1428 curl_multi_strerror (mret));
1429 ctask->download_is_finished = GNUNET_YES;
1430 ctask->download_error = GNUNET_YES;
1433 GNUNET_CONTAINER_DLL_insert (ctasks_head, ctasks_tail, ctask);
1435 curl_download_prepare ();
1440 * Initialize download and trigger curl
1442 * @param cls the proxycurltask
1443 * @param auth_name the name of the authority (site of origin) of ctask->host
1447 process_get_authority (void *cls,
1448 const char* auth_name)
1450 struct ProxyCurlTask *ctask = cls;
1452 if (NULL == auth_name)
1454 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1455 "Get authority failed!\n");
1456 strcpy (ctask->authority, "");
1460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1461 "Get authority yielded %s\n", auth_name);
1462 strcpy (ctask->authority, auth_name);
1465 GNUNET_GNS_lookup_zone (gns_handle,
1468 GNUNET_GNS_RECORD_LEHO,
1469 GNUNET_YES, //Only cached for performance
1471 &process_leho_lookup,
1477 * Main MHD callback for handling requests.
1480 * @param con MHD connection handle
1481 * @param url the url in the request
1482 * @param meth the HTTP method used ("GET", "PUT", etc.)
1483 * @param ver the HTTP version string (i.e. "HTTP/1.1")
1484 * @param upload_data the data being uploaded (excluding HEADERS,
1485 * for a POST that fits into memory and that is encoded
1486 * with a supported encoding, the POST data will NOT be
1487 * given in upload_data and is instead available as
1488 * part of MHD_get_connection_values; very large POST
1489 * data *will* be made available incrementally in
1491 * @param upload_data_size set initially to the size of the
1492 * upload_data provided; the method must update this
1493 * value to the number of bytes NOT processed;
1494 * @param con_cls pointer to location where we store the 'struct Request'
1495 * @return MHD_YES if the connection was handled successfully,
1496 * MHD_NO if the socket must be closed due to a serious
1497 * error while handling the request
1500 create_response (void *cls,
1501 struct MHD_Connection *con,
1505 const char *upload_data,
1506 size_t *upload_data_size,
1509 struct MhdHttpList* hd = cls;
1510 const char* page = "<html><head><title>gnoxy</title>"\
1511 "</head><body>cURL fail</body></html>";
1513 char curlurl[512]; // buffer overflow!
1516 struct ProxyCurlTask *ctask;
1519 if ((0 != strcasecmp (meth, MHD_HTTP_METHOD_GET)) &&
1520 (0 != strcasecmp (meth, MHD_HTTP_METHOD_PUT)) &&
1521 (0 != strcasecmp (meth, MHD_HTTP_METHOD_POST)))
1523 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1524 "MHD: %s NOT IMPLEMENTED!\n", meth);
1529 if (NULL == *con_cls)
1532 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1533 "Got %s request for %s\n", meth, url);
1534 ctask = GNUNET_malloc (sizeof (struct ProxyCurlTask));
1538 ctask->curl = curl_easy_init();
1539 if (NULL == ctask->curl)
1541 ctask->response = MHD_create_response_from_buffer (strlen (page),
1543 MHD_RESPMEM_PERSISTENT);
1544 ret = MHD_queue_response (con,
1547 MHD_destroy_response (ctask->response);
1548 GNUNET_free (ctask);
1552 ctask->download_in_progress = GNUNET_YES;
1553 ctask->buf_status = BUF_WAIT_FOR_CURL;
1554 ctask->connection = con;
1555 ctask->curl_response_code = MHD_HTTP_OK;
1556 ctask->buffer_read_ptr = ctask->buffer;
1557 ctask->buffer_write_ptr = ctask->buffer;
1558 ctask->pp_task = GNUNET_SCHEDULER_NO_TASK;
1560 MHD_get_connection_values (con,
1562 &con_val_iter, ctask);
1564 if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1566 if (0 == *upload_data_size)
1568 curl_easy_cleanup (ctask->curl);
1569 GNUNET_free (ctask);
1572 ctask->put_read_offset = 0;
1573 ctask->put_read_size = *upload_data_size;
1574 curl_easy_setopt (ctask->curl, CURLOPT_UPLOAD, 1);
1575 curl_easy_setopt (ctask->curl, CURLOPT_READDATA, upload_data);
1576 //curl_easy_setopt (ctask->curl, CURLOPT_READFUNCTION, &curl_read_cb);
1578 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1579 "Got PUT data: %s\n", upload_data);
1580 curl_easy_cleanup (ctask->curl);
1581 GNUNET_free (ctask);
1585 if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1587 if (0 == *upload_data_size)
1589 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1590 "NO data for post!\n");
1591 curl_easy_cleanup (ctask->curl);
1592 GNUNET_free (ctask);
1595 curl_easy_setopt (ctask->curl, CURLOPT_POST, 1);
1596 curl_easy_setopt (ctask->curl, CURLOPT_POSTFIELDSIZE, *upload_data_size);
1597 curl_easy_setopt (ctask->curl, CURLOPT_COPYPOSTFIELDS, upload_data);
1599 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1600 "Got POST data: %s\n", upload_data);
1601 curl_easy_cleanup (ctask->curl);
1602 GNUNET_free (ctask);
1606 curl_easy_setopt (ctask->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1607 curl_easy_setopt (ctask->curl, CURLOPT_HEADERDATA, ctask);
1608 curl_easy_setopt (ctask->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1609 curl_easy_setopt (ctask->curl, CURLOPT_WRITEDATA, ctask);
1610 curl_easy_setopt (ctask->curl, CURLOPT_FOLLOWLOCATION, 0);
1611 curl_easy_setopt (ctask->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1613 if (GNUNET_NO == ctask->mhd->is_ssl)
1615 sprintf (curlurl, "http://%s%s", ctask->host, url);
1616 MHD_get_connection_values (con,
1617 MHD_GET_ARGUMENT_KIND,
1618 &get_uri_val_iter, curlurl);
1619 curl_easy_setopt (ctask->curl, CURLOPT_URL, curlurl);
1621 strcpy (ctask->url, url);
1622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1623 "MHD: Adding new curl task for %s%s\n", ctask->host, url);
1624 MHD_get_connection_values (con,
1625 MHD_GET_ARGUMENT_KIND,
1626 &get_uri_val_iter, ctask->url);
1628 curl_easy_setopt (ctask->curl, CURLOPT_FAILONERROR, 1);
1629 curl_easy_setopt (ctask->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1630 curl_easy_setopt (ctask->curl, CURLOPT_TIMEOUT, 600L);
1632 GNUNET_GNS_get_authority (gns_handle,
1634 &process_get_authority,
1636 ctask->ready_to_queue = GNUNET_NO;
1637 ctask->fin = GNUNET_NO;
1641 ctask = (struct ProxyCurlTask *) *con_cls;
1643 if (GNUNET_YES != ctask->ready_to_queue)
1644 return MHD_YES; /* wait longer */
1646 if (GNUNET_YES == ctask->fin)
1649 ctask->fin = GNUNET_YES;
1650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1651 "MHD: Queueing response for %s\n", ctask->url);
1652 ret = MHD_queue_response (con, ctask->curl_response_code, ctask->response);
1653 run_mhd_now (ctask->mhd);
1664 struct MhdHttpList *hd;
1666 for (hd=mhd_httpd_head; NULL != hd; hd = hd->next)
1674 * @param hd the daemon to run
1677 run_httpd (struct MhdHttpList *hd)
1682 struct GNUNET_NETWORK_FDSet *wrs;
1683 struct GNUNET_NETWORK_FDSet *wws;
1684 struct GNUNET_NETWORK_FDSet *wes;
1687 unsigned MHD_LONG_LONG timeout;
1688 struct GNUNET_TIME_Relative tv;
1693 wrs = GNUNET_NETWORK_fdset_create ();
1694 wes = GNUNET_NETWORK_fdset_create ();
1695 wws = GNUNET_NETWORK_fdset_create ();
1697 GNUNET_assert (MHD_YES == MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max));
1700 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1701 "MHD fds: max=%d\n", max);
1703 haveto = MHD_get_timeout (hd->daemon, &timeout);
1705 if (MHD_YES == haveto)
1706 tv.rel_value = (uint64_t) timeout;
1708 tv = GNUNET_TIME_UNIT_FOREVER_REL;
1709 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1710 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1711 GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
1713 if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1714 GNUNET_SCHEDULER_cancel (hd->httpd_task);
1716 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
1719 GNUNET_NETWORK_fdset_destroy (wrs);
1720 GNUNET_NETWORK_fdset_destroy (wws);
1721 GNUNET_NETWORK_fdset_destroy (wes);
1726 * Task run whenever HTTP server operations are pending.
1729 * @param tc sched context
1732 do_httpd (void *cls,
1733 const struct GNUNET_SCHEDULER_TaskContext *tc)
1735 struct MhdHttpList *hd = cls;
1737 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1738 "MHD: Main loop\n");
1739 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
1740 MHD_run (hd->daemon);
1747 * Read data from socket
1749 * @param cls the closure
1750 * @param tc scheduler context
1753 do_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1756 * Read from remote end
1758 * @param cls closure
1759 * @param tc scheduler context
1762 do_read_remote (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1765 * Write data to remote socket
1767 * @param cls the closure
1768 * @param tc scheduler context
1771 do_write_remote (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1773 struct Socks5Request *s5r = cls;
1776 s5r->fwdwtask = GNUNET_SCHEDULER_NO_TASK;
1778 if ((NULL != tc->read_ready) &&
1779 (GNUNET_NETWORK_fdset_isset (tc->write_ready, s5r->remote_sock)) &&
1780 ((len = GNUNET_NETWORK_socket_send (s5r->remote_sock, s5r->rbuf,
1783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1784 "Successfully sent %d bytes to remote socket\n",
1789 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write remote");
1790 if (GNUNET_SCHEDULER_NO_TASK != s5r->rtask)
1791 GNUNET_SCHEDULER_cancel (s5r->rtask);
1792 if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
1793 GNUNET_SCHEDULER_cancel (s5r->wtask);
1794 if (GNUNET_SCHEDULER_NO_TASK != s5r->fwdrtask)
1795 GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
1796 GNUNET_NETWORK_socket_close (s5r->remote_sock);
1797 GNUNET_NETWORK_socket_close (s5r->sock);
1803 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1810 * Clean up s5r handles
1812 * @param s5r the handle to destroy
1815 cleanup_s5r (struct Socks5Request *s5r)
1817 if (GNUNET_SCHEDULER_NO_TASK != s5r->rtask)
1818 GNUNET_SCHEDULER_cancel (s5r->rtask);
1819 if (GNUNET_SCHEDULER_NO_TASK != s5r->fwdwtask)
1820 GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
1821 if (GNUNET_SCHEDULER_NO_TASK != s5r->fwdrtask)
1822 GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
1824 if (NULL != s5r->remote_sock)
1825 GNUNET_NETWORK_socket_close (s5r->remote_sock);
1826 if ((NULL != s5r->sock) && (s5r->cleanup_sock == GNUNET_YES))
1827 GNUNET_NETWORK_socket_close (s5r->sock);
1833 * Write data to socket
1835 * @param cls the closure
1836 * @param tc scheduler context
1839 do_write (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1841 struct Socks5Request *s5r = cls;
1844 s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
1846 if ((NULL != tc->read_ready) &&
1847 (GNUNET_NETWORK_fdset_isset (tc->write_ready, s5r->sock)) &&
1848 ((len = GNUNET_NETWORK_socket_send (s5r->sock, s5r->wbuf,
1851 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1852 "Successfully sent %d bytes to socket\n",
1858 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1859 s5r->cleanup = GNUNET_YES;
1860 s5r->cleanup_sock = GNUNET_YES;
1866 if (GNUNET_YES == s5r->cleanup)
1872 if ((s5r->state == SOCKS5_DATA_TRANSFER) &&
1873 (s5r->fwdrtask == GNUNET_SCHEDULER_NO_TASK))
1875 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1877 &do_read_remote, s5r);
1881 * Read from remote end
1883 * @param cls closure
1884 * @param tc scheduler context
1887 do_read_remote (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1889 struct Socks5Request *s5r = cls;
1891 s5r->fwdrtask = GNUNET_SCHEDULER_NO_TASK;
1894 if ((NULL != tc->write_ready) &&
1895 (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->remote_sock)) &&
1896 (s5r->wbuf_len = GNUNET_NETWORK_socket_recv (s5r->remote_sock, s5r->wbuf,
1897 sizeof (s5r->wbuf))))
1899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1900 "Successfully read %d bytes from remote socket\n",
1905 if (s5r->wbuf_len == 0)
1906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1907 "0 bytes received from remote... graceful shutdown!\n");
1908 if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
1909 GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
1910 if (s5r->rtask != GNUNET_SCHEDULER_NO_TASK)
1911 GNUNET_SCHEDULER_cancel (s5r->rtask);
1913 GNUNET_NETWORK_socket_close (s5r->remote_sock);
1914 s5r->remote_sock = NULL;
1915 GNUNET_NETWORK_socket_close (s5r->sock);
1921 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1929 * Adds a socket to MHD
1931 * @param h the handle to the socket to add
1932 * @param daemon the daemon to add the fd to
1933 * @return whatever MHD_add_connection returns
1936 add_handle_to_mhd (struct GNUNET_NETWORK_Handle *h, struct MHD_Daemon *daemon)
1939 struct sockaddr *addr;
1942 fd = dup (GNUNET_NETWORK_get_fd (h));
1943 addr = GNUNET_NETWORK_get_addr (h);
1944 len = GNUNET_NETWORK_get_addrlen (h);
1946 return MHD_add_connection (daemon, fd, addr, len);
1950 * Read file in filename
1952 * @param filename file to read
1953 * @param size pointer where filesize is stored
1957 load_file (const char* filename,
1964 GNUNET_DISK_file_size (filename, &fsize,
1965 GNUNET_YES, GNUNET_YES))
1967 if (fsize > MAX_PEM_SIZE)
1969 *size = (unsigned int) fsize;
1970 buffer = GNUNET_malloc (*size);
1971 if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
1973 GNUNET_free (buffer);
1981 * Load PEM key from file
1983 * @param key where to store the data
1984 * @param keyfile path to the PEM file
1985 * @return GNUNET_OK on success
1988 load_key_from_file (gnutls_x509_privkey_t key, const char* keyfile)
1990 gnutls_datum_t key_data;
1993 key_data.data = (unsigned char*) load_file (keyfile, &key_data.size);
1994 ret = gnutls_x509_privkey_import (key, &key_data,
1995 GNUTLS_X509_FMT_PEM);
1996 if (GNUTLS_E_SUCCESS != ret)
1998 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1999 _("Unable to import private key from file `%s'\n"),
2003 GNUNET_free (key_data.data);
2004 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2009 * Load cert from file
2011 * @param crt struct to store data in
2012 * @param certfile path to pem file
2013 * @return GNUNET_OK on success
2016 load_cert_from_file (gnutls_x509_crt_t crt, char* certfile)
2018 gnutls_datum_t cert_data;
2019 cert_data.data = NULL;
2022 cert_data.data = (unsigned char*) load_file (certfile, &cert_data.size);
2023 ret = gnutls_x509_crt_import (crt, &cert_data,
2024 GNUTLS_X509_FMT_PEM);
2025 if (GNUTLS_E_SUCCESS != ret)
2027 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2028 _("Unable to import certificate %s\n"), certfile);
2031 GNUNET_free (cert_data.data);
2032 return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2037 * Generate new certificate for specific name
2039 * @param name the subject name to generate a cert for
2040 * @return a struct holding the PEM data
2042 static struct ProxyGNSCertificate *
2043 generate_gns_certificate (const char *name)
2047 unsigned int serial;
2048 size_t key_buf_size;
2049 size_t cert_buf_size;
2050 gnutls_x509_crt_t request;
2054 ret = gnutls_x509_crt_init (&request);
2056 if (GNUTLS_E_SUCCESS != ret)
2061 ret = gnutls_x509_crt_set_key (request, proxy_ca.key);
2063 if (GNUTLS_E_SUCCESS != ret)
2068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Generating cert\n");
2070 struct ProxyGNSCertificate *pgc =
2071 GNUNET_malloc (sizeof (struct ProxyGNSCertificate));
2073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding DNs\n");
2075 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2078 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2081 gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2082 0, name, strlen (name));
2084 ret = gnutls_x509_crt_set_version (request, 3);
2086 ret = gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2088 etime = time (NULL);
2089 tm_data = localtime (&etime);
2092 ret = gnutls_x509_crt_set_serial (request,
2096 ret = gnutls_x509_crt_set_activation_time (request,
2099 etime = mktime (tm_data);
2106 ret = gnutls_x509_crt_set_expiration_time (request,
2108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Signing...\n");
2110 ret = gnutls_x509_crt_sign (request, proxy_ca.cert, proxy_ca.key);
2112 key_buf_size = sizeof (pgc->key);
2113 cert_buf_size = sizeof (pgc->cert);
2115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Exporting certificate...\n");
2117 gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2118 pgc->cert, &cert_buf_size);
2120 gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2121 pgc->key, &key_buf_size);
2124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n");
2125 gnutls_x509_crt_deinit (request);
2133 * Accept policy for mhdaemons
2136 * @param addr the sockaddr
2137 * @param addrlen the sockaddr length
2138 * @return MHD_NO if sockaddr is wrong or #conns too high
2141 accept_cb (void* cls, const struct sockaddr *addr, socklen_t addrlen)
2143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2144 "In MHD accept policy cb\n");
2148 if (addr->sa_family == AF_UNIX)
2152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2153 "Connection accepted\n");
2160 * Adds a socket to an SSL MHD instance
2161 * It is important the the domain name is
2162 * correct. In most cases we need to start a new daemon
2164 * @param h the handle to add to a daemon
2165 * @param domain the domain the ssl daemon has to serve
2166 * @return MHD_YES on success
2169 add_handle_to_ssl_mhd (struct GNUNET_NETWORK_Handle *h, const char* domain)
2171 struct MhdHttpList *hd = NULL;
2172 struct ProxyGNSCertificate *pgc;
2173 struct NetworkHandleList *nh;
2175 for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2176 if (0 == strcmp (hd->domain, domain))
2181 pgc = generate_gns_certificate (domain);
2183 hd = GNUNET_malloc (sizeof (struct MhdHttpList));
2184 hd->is_ssl = GNUNET_YES;
2185 strcpy (hd->domain, domain);
2186 hd->proxy_cert = pgc;
2189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2190 "No previous SSL instance found... starting new one for %s\n",
2193 hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL, 4444,
2195 &create_response, hd,
2196 MHD_OPTION_LISTEN_SOCKET, GNUNET_NETWORK_get_fd (mhd_unix_socket),
2197 MHD_OPTION_CONNECTION_LIMIT, MHD_MAX_CONNECTIONS,
2198 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2199 MHD_OPTION_NOTIFY_COMPLETED,
2201 MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2202 MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2205 GNUNET_assert (hd->daemon != NULL);
2206 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2208 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2211 nh = GNUNET_malloc (sizeof (struct NetworkHandleList));
2214 GNUNET_CONTAINER_DLL_insert (hd->socket_handles_head,
2215 hd->socket_handles_tail,
2218 return add_handle_to_mhd (h, hd->daemon);
2224 * Read data from incoming connection
2226 * @param cls the closure
2227 * @param tc the scheduler context
2230 do_read (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2232 struct Socks5Request *s5r = cls;
2233 struct socks5_client_hello *c_hello;
2234 struct socks5_server_hello *s_hello;
2235 struct socks5_client_request *c_req;
2236 struct socks5_server_response *s_resp;
2242 struct hostent *phost;
2244 struct sockaddr_in remote_addr;
2245 struct in_addr *r_sin_addr;
2247 struct NetworkHandleList *nh;
2249 s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2251 if ((NULL != tc->write_ready) &&
2252 (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) &&
2253 (s5r->rbuf_len = GNUNET_NETWORK_socket_recv (s5r->sock, s5r->rbuf,
2254 sizeof (s5r->rbuf))))
2256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2257 "Successfully read %d bytes from socket\n",
2262 if (s5r->rbuf_len != 0)
2263 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
2265 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disco!\n");
2267 if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2268 GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2269 if (s5r->wtask != GNUNET_SCHEDULER_NO_TASK)
2270 GNUNET_SCHEDULER_cancel (s5r->wtask);
2271 if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
2272 GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2273 GNUNET_NETWORK_socket_close (s5r->remote_sock);
2274 GNUNET_NETWORK_socket_close (s5r->sock);
2279 if (s5r->state == SOCKS5_INIT)
2281 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2283 c_hello = (struct socks5_client_hello*)&s5r->rbuf;
2285 GNUNET_assert (c_hello->version == SOCKS_VERSION_5);
2287 s_hello = (struct socks5_server_hello*)&s5r->wbuf;
2288 s5r->wbuf_len = sizeof( struct socks5_server_hello );
2290 s_hello->version = c_hello->version;
2291 s_hello->auth_method = SOCKS_AUTH_NONE;
2293 /* Write response to client */
2294 s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2298 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2302 s5r->state = SOCKS5_REQUEST;
2306 if (s5r->state == SOCKS5_REQUEST)
2308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2309 "Processing SOCKS5 request\n");
2310 c_req = (struct socks5_client_request*)&s5r->rbuf;
2311 s_resp = (struct socks5_server_response*)&s5r->wbuf;
2312 //Only 10byte for ipv4 response!
2313 s5r->wbuf_len = 10;//sizeof (struct socks5_server_response);
2315 GNUNET_assert (c_req->addr_type == 3);
2317 dom_len = *((uint8_t*)(&(c_req->addr_type) + 1));
2318 memset(domain, 0, sizeof(domain));
2319 strncpy(domain, (char*)(&(c_req->addr_type) + 2), dom_len);
2320 req_port = *((uint16_t*)(&(c_req->addr_type) + 2 + dom_len));
2322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2323 "Requested connection is %s:%d\n",
2327 if (is_tld (domain, GNUNET_GNS_TLD) ||
2328 is_tld (domain, GNUNET_GNS_TLD_ZKEY))
2330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2331 "Requested connection is gnunet tld\n",
2335 if (ntohs(req_port) == HTTPS_PORT)
2337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2338 "Requested connection is HTTPS\n");
2339 ret = add_handle_to_ssl_mhd ( s5r->sock, domain );
2341 else if (NULL != httpd)
2343 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2344 "Requested connection is HTTP\n");
2345 nh = GNUNET_malloc (sizeof (struct NetworkHandleList));
2348 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head->socket_handles_head,
2349 mhd_httpd_head->socket_handles_tail,
2352 ret = add_handle_to_mhd ( s5r->sock, httpd );
2357 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2358 _("Failed to start HTTP server\n"));
2359 s_resp->version = 0x05;
2360 s_resp->reply = 0x01;
2361 s5r->cleanup = GNUNET_YES;
2362 s5r->cleanup_sock = GNUNET_YES;
2364 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2370 /* Signal success */
2371 s_resp->version = 0x05;
2372 s_resp->reply = 0x00;
2373 s_resp->reserved = 0x00;
2374 s_resp->addr_type = 0x01;
2376 s5r->cleanup = GNUNET_YES;
2377 s5r->cleanup_sock = GNUNET_NO;
2379 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2387 phost = (struct hostent*)gethostbyname (domain);
2390 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2391 "Resolve %s error!\n", domain );
2392 s_resp->version = 0x05;
2393 s_resp->reply = 0x01;
2394 s5r->cleanup = GNUNET_YES;
2395 s5r->cleanup_sock = GNUNET_YES;
2397 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2403 s5r->remote_sock = GNUNET_NETWORK_socket_create (AF_INET,
2406 r_sin_addr = (struct in_addr*)(phost->h_addr);
2407 remote_ip = r_sin_addr->s_addr;
2408 memset(&remote_addr, 0, sizeof(remote_addr));
2409 remote_addr.sin_family = AF_INET;
2410 #if HAVE_SOCKADDR_IN_SIN_LEN
2411 remote_addr.sin_len = sizeof (remote_addr);
2413 remote_addr.sin_addr.s_addr = remote_ip;
2414 remote_addr.sin_port = req_port;
2416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2417 "target server: %s:%u\n", inet_ntoa(remote_addr.sin_addr),
2421 GNUNET_NETWORK_socket_connect ( s5r->remote_sock,
2422 (const struct sockaddr*)&remote_addr,
2423 sizeof (remote_addr)))
2424 && (errno != EINPROGRESS))
2426 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "connect");
2427 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2428 "socket request error...\n");
2429 s_resp->version = 0x05;
2430 s_resp->reply = 0x01;
2432 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2440 "new remote connection\n");
2442 s_resp->version = 0x05;
2443 s_resp->reply = 0x00;
2444 s_resp->reserved = 0x00;
2445 s_resp->addr_type = 0x01;
2447 s5r->state = SOCKS5_DATA_TRANSFER;
2450 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2454 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2462 if (s5r->state == SOCKS5_DATA_TRANSFER)
2464 if ((s5r->remote_sock == NULL) || (s5r->rbuf_len == 0))
2466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2467 "Closing connection to client\n");
2468 if (s5r->rtask != GNUNET_SCHEDULER_NO_TASK)
2469 GNUNET_SCHEDULER_cancel (s5r->rtask);
2470 if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
2471 GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2472 if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2473 GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2474 if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2475 GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2477 if (s5r->remote_sock != NULL)
2478 GNUNET_NETWORK_socket_close (s5r->remote_sock);
2479 GNUNET_NETWORK_socket_close (s5r->sock);
2484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2485 "forwarding %d bytes from client\n", s5r->rbuf_len);
2488 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2490 &do_write_remote, s5r);
2492 if (s5r->fwdrtask == GNUNET_SCHEDULER_NO_TASK)
2495 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2497 &do_read_remote, s5r);
2507 * Accept new incoming connections
2509 * @param cls the closure
2510 * @param tc the scheduler context
2513 do_accept (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2515 struct GNUNET_NETWORK_Handle *s;
2516 struct Socks5Request *s5r;
2518 ltask = GNUNET_SCHEDULER_NO_TASK;
2519 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2522 ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2526 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2530 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2534 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2535 "Got an inbound connection, waiting for data\n");
2537 s5r = GNUNET_malloc (sizeof (struct Socks5Request));
2539 s5r->state = SOCKS5_INIT;
2540 s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
2541 s5r->fwdwtask = GNUNET_SCHEDULER_NO_TASK;
2542 s5r->fwdrtask = GNUNET_SCHEDULER_NO_TASK;
2543 s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2550 * Task run on shutdown
2552 * @param cls closure
2553 * @param tc task context
2556 do_shutdown (void *cls,
2557 const struct GNUNET_SCHEDULER_TaskContext *tc)
2560 struct MhdHttpList *hd;
2561 struct MhdHttpList *tmp_hd;
2562 struct NetworkHandleList *nh;
2563 struct NetworkHandleList *tmp_nh;
2564 struct ProxyCurlTask *ctask;
2565 struct ProxyCurlTask *ctask_tmp;
2567 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2568 "Shutting down...\n");
2570 gnutls_global_deinit ();
2572 if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
2574 GNUNET_SCHEDULER_cancel (curl_download_task);
2575 curl_download_task = GNUNET_SCHEDULER_NO_TASK;
2578 for (hd = mhd_httpd_head; hd != NULL; hd = tmp_hd)
2582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2583 "Stopping daemon\n");
2585 if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
2587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2588 "Stopping select task %d\n",
2590 GNUNET_SCHEDULER_cancel (hd->httpd_task);
2591 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2594 if (NULL != hd->daemon)
2596 MHD_stop_daemon (hd->daemon);
2600 for (nh = hd->socket_handles_head; nh != NULL; nh = tmp_nh)
2604 GNUNET_NETWORK_socket_close (nh->h);
2609 if (NULL != hd->proxy_cert)
2611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2612 "Free certificate\n");
2613 GNUNET_free (hd->proxy_cert);
2619 for (ctask=ctasks_head; ctask != NULL; ctask=ctask_tmp)
2621 ctask_tmp = ctask->next;
2623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2624 "Cleaning up cURL task\n");
2626 if (ctask->curl != NULL)
2627 curl_easy_cleanup (ctask->curl);
2629 if (NULL != ctask->headers)
2630 curl_slist_free_all (ctask->headers);
2631 if (NULL != ctask->resolver)
2632 curl_slist_free_all (ctask->resolver);
2634 if (NULL != ctask->response)
2635 MHD_destroy_response (ctask->response);
2638 GNUNET_free (ctask);
2640 curl_multi_cleanup (curl_multi);
2642 GNUNET_GNS_disconnect (gns_handle);
2647 * Compiles a regex for us
2649 * @param re ptr to re struct
2650 * @param rt the expression to compile
2651 * @return 0 on success
2654 compile_regex (regex_t *re, const char* rt)
2659 status = regcomp (re, rt, REG_EXTENDED|REG_NEWLINE);
2662 regerror (status, re, err, 1024);
2663 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2664 "Regex error compiling '%s': %s\n", rt, err);
2672 * Loads the users local zone key
2674 * @return GNUNET_YES on success
2677 load_local_zone_key (const struct GNUNET_CONFIGURATION_Handle *cfg)
2680 struct GNUNET_CRYPTO_RsaPrivateKey *key = NULL;
2681 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
2682 struct GNUNET_CRYPTO_ShortHashCode *zone = NULL;
2683 struct GNUNET_CRYPTO_ShortHashAsciiEncoded zonename;
2685 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
2686 "ZONEKEY", &keyfile))
2688 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2689 "Unable to load zone key config value!\n");
2693 if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
2695 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2696 "Unable to load zone key %s!\n", keyfile);
2697 GNUNET_free(keyfile);
2701 key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2702 GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
2703 GNUNET_CRYPTO_short_hash(&pkey,
2704 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2706 zone = &local_gns_zone;
2707 GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
2708 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2709 "Using zone: %s!\n", &zonename);
2710 GNUNET_CRYPTO_rsa_key_free(key);
2711 GNUNET_free(keyfile);
2713 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
2714 "PRIVATE_ZONEKEY", &keyfile))
2716 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2717 "Unable to load private zone key config value!\n");
2721 if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
2723 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2724 "Unable to load private zone key %s!\n", keyfile);
2725 GNUNET_free(keyfile);
2729 key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2730 GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
2731 GNUNET_CRYPTO_short_hash(&pkey,
2732 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2733 &local_private_zone);
2734 GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
2735 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2736 "Using private zone: %s!\n", &zonename);
2737 GNUNET_CRYPTO_rsa_key_free(key);
2738 GNUNET_free(keyfile);
2740 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
2741 "SHORTEN_ZONEKEY", &keyfile))
2743 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2744 "Unable to load shorten zone key config value!\n");
2748 if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
2750 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2751 "Unable to load shorten zone key %s!\n", keyfile);
2752 GNUNET_free(keyfile);
2756 key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2757 GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
2758 GNUNET_CRYPTO_short_hash(&pkey,
2759 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2760 &local_shorten_zone);
2761 GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
2762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2763 "Using shorten zone: %s!\n", &zonename);
2764 GNUNET_CRYPTO_rsa_key_free(key);
2765 GNUNET_free(keyfile);
2771 * Main function that will be run
2773 * @param cls closure
2774 * @param args remaining command-line arguments
2775 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2776 * @param cfg configuration
2779 run (void *cls, char *const *args, const char *cfgfile,
2780 const struct GNUNET_CONFIGURATION_Handle *cfg)
2782 struct sockaddr_in sa;
2783 struct MhdHttpList *hd;
2784 struct sockaddr_un mhd_unix_sock_addr;
2786 char* proxy_sockfile;
2787 char* cafile_cfg = NULL;
2790 curl_multi = curl_multi_init ();
2792 if (NULL == curl_multi)
2794 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2795 "Failed to create cURL multo handle!\n");
2799 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2801 cafile = cafile_opt;
2804 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
2808 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2809 "Unable to load proxy CA config value!\n");
2810 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2811 "No proxy CA provided!\n");
2814 cafile = cafile_cfg;
2817 gnutls_global_init ();
2818 gnutls_x509_crt_init (&proxy_ca.cert);
2819 gnutls_x509_privkey_init (&proxy_ca.key);
2821 if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
2822 (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
2824 // FIXME: release resources...
2828 GNUNET_free_non_null (cafile_cfg);
2830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2831 "Loading Template\n");
2833 compile_regex (&re_dotplus, (char*) RE_A_HREF);
2835 gns_handle = GNUNET_GNS_connect (cfg);
2837 if (GNUNET_NO == load_local_zone_key (cfg))
2839 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2840 "Unable to load zone!\n");
2844 if (NULL == gns_handle)
2846 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2847 "Unable to connect to GNS!\n");
2851 memset (&sa, 0, sizeof (sa));
2852 sa.sin_family = AF_INET;
2853 sa.sin_port = htons (port);
2854 #if HAVE_SOCKADDR_IN_SIN_LEN
2855 sa.sin_len = sizeof (sa);
2858 lsock = GNUNET_NETWORK_socket_create (AF_INET,
2862 if ((NULL == lsock) ||
2864 GNUNET_NETWORK_socket_bind (lsock, (const struct sockaddr *) &sa,
2867 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2868 "Failed to create listen socket bound to `%s'",
2869 GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)));
2871 GNUNET_NETWORK_socket_close (lsock);
2875 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock, 5))
2877 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2878 "Failed to listen on socket bound to `%s'",
2879 GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)));
2883 ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2884 lsock, &do_accept, NULL);
2889 if (0 != curl_global_init (CURL_GLOBAL_WIN32))
2891 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2892 "cURL global init failed!\n");
2896 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2897 "Proxy listens on port %u\n",
2900 mhd_httpd_head = NULL;
2901 mhd_httpd_tail = NULL;
2902 total_mhd_connections = 0;
2904 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
2908 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2909 "Specify PROXY_UNIXPATH in gns-proxy config section!\n");
2913 mhd_unix_socket = GNUNET_NETWORK_socket_create (AF_UNIX,
2917 if (NULL == mhd_unix_socket)
2919 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2920 "Unable to create unix domain socket!\n");
2924 mhd_unix_sock_addr.sun_family = AF_UNIX;
2925 strcpy (mhd_unix_sock_addr.sun_path, proxy_sockfile);
2928 mhd_unix_sock_addr.sun_path[0] = '\0';
2930 #if HAVE_SOCKADDR_IN_SIN_LEN
2931 mhd_unix_sock_addr.sun_len = (u_char) sizeof (struct sockaddr_un);
2934 len = strlen (proxy_sockfile) + sizeof(AF_UNIX);
2936 GNUNET_free (proxy_sockfile);
2938 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (mhd_unix_socket,
2939 (struct sockaddr*)&mhd_unix_sock_addr,
2942 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2943 "Unable to bind unix domain socket!\n");
2947 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (mhd_unix_socket,
2950 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2951 "Unable to listen on unix domain socket!\n");
2955 hd = GNUNET_malloc (sizeof (struct MhdHttpList));
2956 hd->is_ssl = GNUNET_NO;
2957 strcpy (hd->domain, "");
2958 httpd = MHD_start_daemon (MHD_USE_DEBUG, 4444, //Dummy port
2960 &create_response, hd,
2961 MHD_OPTION_LISTEN_SOCKET, GNUNET_NETWORK_get_fd (mhd_unix_socket),
2962 MHD_OPTION_CONNECTION_LIMIT, MHD_MAX_CONNECTIONS,
2963 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2964 MHD_OPTION_NOTIFY_COMPLETED,
2968 GNUNET_assert (httpd != NULL);
2970 hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2972 GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2976 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2977 &do_shutdown, NULL);
2983 * The main function for gnunet-gns-proxy.
2985 * @param argc number of arguments from the command line
2986 * @param argv command line arguments
2987 * @return 0 ok, 1 on error
2990 main (int argc, char *const *argv)
2992 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2994 gettext_noop ("listen on specified port"), 1,
2995 &GNUNET_GETOPT_set_string, &port},
2996 {'a', "authority", NULL,
2997 gettext_noop ("pem file to use as CA"), 1,
2998 &GNUNET_GETOPT_set_string, &cafile_opt},
2999 GNUNET_GETOPT_OPTION_END
3004 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3008 GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3011 GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3012 _("GNUnet GNS proxy"),
3014 &run, NULL)) ? 0 : 1;
3015 GNUNET_free_non_null ((char*)argv);