d14e8f8724b759f209d43e50a43ecbef404783f9
[oweals/gnunet.git] / src / gns / gnunet-gns-proxy.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012 Christian Grothoff (and other contributing authors)
4
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.
9
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.
14
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.
19 */
20
21 #include "platform.h"
22 #include <gnunet_util_lib.h>
23 #include <gnunet_gns_service.h>
24 #include <microhttpd.h>
25 #include <curl/curl.h>
26 #include <regex.h>
27 #include "gns_proxy_proto.h"
28 #include "gns.h"
29
30 /** SSL **/
31 #include <gnutls/gnutls.h>
32 #include <gnutls/x509.h>
33 #include <gnutls/abstract.h>
34 #include <gnutls/crypto.h>
35 #include <time.h>
36
37 #define GNUNET_GNS_PROXY_PORT 7777
38 #define MHD_MAX_CONNECTIONS 300
39 #define MAX_HTTP_URI_LENGTH 2048
40
41 /* MHD/cURL defines */
42 #define BUF_WAIT_FOR_CURL 0
43 #define BUF_WAIT_FOR_MHD 1
44 #define BUF_WAIT_FOR_PP 2
45 #define HTML_HDR_CONTENT "Content-Type: text/html"
46
47 /* buffer padding for proper RE matching */
48 #define CURL_BUF_PADDING 1000
49
50 /* regexp */
51 //#define RE_DOTPLUS "<a href=\"http://(([A-Za-z]+[.])+)([+])"
52 #define RE_A_HREF  "href=\"https?://(([A-Za-z0-9]+[.])+)([+]|[a-z]+)"
53 #define RE_N_MATCHES 4
54
55 /* The usual suspects */
56 #define HTTP_PORT 80
57 #define HTTPS_PORT 443
58
59
60 /**
61  * A structure for CA cert/key
62  */
63 struct ProxyCA
64 {
65   /* The certificate */
66   gnutls_x509_crt_t cert;
67
68   /* The private key */
69   gnutls_x509_privkey_t key;
70 };
71
72 #define MAX_PEM_SIZE (10 * 1024)
73
74 /**
75  * Structure for GNS certificates
76  */
77 struct ProxyGNSCertificate
78 {
79   /* The certificate as PEM */
80   char cert[MAX_PEM_SIZE];
81
82   /* The private key as PEM */
83   char key[MAX_PEM_SIZE];
84 };
85
86
87 /**
88  * A structure for socks requests
89  */
90 struct Socks5Request
91 {
92   /* The client socket */
93   struct GNUNET_NETWORK_Handle *sock;
94
95   /* The server socket */
96   struct GNUNET_NETWORK_Handle *remote_sock;
97   
98   /* The socks state */
99   int state;
100   
101   /* Client socket read task */
102   GNUNET_SCHEDULER_TaskIdentifier rtask;
103
104   /* Server socket read task */
105   GNUNET_SCHEDULER_TaskIdentifier fwdrtask;
106
107   /* Client socket write task */
108   GNUNET_SCHEDULER_TaskIdentifier wtask;
109
110   /* Server socket write task */
111   GNUNET_SCHEDULER_TaskIdentifier fwdwtask;
112
113   /* Read buffer */
114   char rbuf[2048];
115
116   /* Write buffer */
117   char wbuf[2048];
118
119   /* Length of data in read buffer */
120   unsigned int rbuf_len;
121
122   /* Length of data in write buffer */
123   unsigned int wbuf_len;
124
125   /* This handle is scheduled for cleanup? */
126   int cleanup;
127
128   /* Shall we close the client socket on cleanup? */
129   int cleanup_sock;
130 };
131
132 /**
133  * DLL for Network Handles
134  */
135 struct NetworkHandleList
136 {
137   /*DLL*/
138   struct NetworkHandleList *next;
139
140   /*DLL*/
141   struct NetworkHandleList *prev;
142
143   /* The handle */
144   struct GNUNET_NETWORK_Handle *h;
145 };
146
147 /**
148  * A structure for all running Httpds
149  */
150 struct MhdHttpList
151 {
152   /* DLL for httpds */
153   struct MhdHttpList *prev;
154
155   /* DLL for httpds */
156   struct MhdHttpList *next;
157
158   /* is this an ssl daemon? */
159   int is_ssl;
160
161   /* the domain name to server (only important for SSL) */
162   char domain[256];
163
164   /* The daemon handle */
165   struct MHD_Daemon *daemon;
166
167   /* Optional proxy certificate used */
168   struct ProxyGNSCertificate *proxy_cert;
169
170   /* The task ID */
171   GNUNET_SCHEDULER_TaskIdentifier httpd_task;
172
173   /* Handles associated with this daemon */
174   struct NetworkHandleList *socket_handles_head;
175   
176   /* Handles associated with this daemon */
177   struct NetworkHandleList *socket_handles_tail;
178 };
179
180 /**
181  * A structure for MHD<->cURL streams
182  */
183 struct ProxyCurlTask
184 {
185   /* DLL for tasks */
186   struct ProxyCurlTask *prev;
187
188   /* DLL for tasks */
189   struct ProxyCurlTask *next;
190
191   /* Handle to cURL */
192   CURL *curl;
193
194   /* Optional header replacements for curl (LEHO) */
195   struct curl_slist *headers;
196
197   /* Optional resolver replacements for curl (LEHO) */
198   struct curl_slist *resolver;
199
200   /* curl response code */
201   long curl_response_code;
202
203   /* The URL to fetch */
204   char url[MAX_HTTP_URI_LENGTH];
205
206   /* The cURL write buffer / MHD read buffer */
207   char buffer[CURL_MAX_WRITE_SIZE + CURL_BUF_PADDING];
208
209   /* Read pos of the data in the buffer */
210   char *buffer_read_ptr;
211
212   /* Write pos in the buffer */
213   char *buffer_write_ptr;
214
215   /* The buffer status (BUF_WAIT_FOR_CURL or BUF_WAIT_FOR_MHD) */
216   int buf_status;
217
218   /* Number of bytes in buffer */
219   unsigned int bytes_in_buffer;
220
221   /* Indicates wheather the download is in progress */
222   int download_in_progress;
223
224   /* Indicates wheather the download was successful */
225   int download_is_finished;
226
227   /* Indicates wheather the download failed */
228   int download_error;
229
230   /* Indicates wheather we need to parse HTML */
231   int parse_content;
232
233   /* Indicates wheather we are postprocessing the HTML right now */
234   int is_postprocessing;
235
236   /* Indicates wheather postprocessing has finished */
237   int pp_finished;
238
239   /* PP task */
240   GNUNET_SCHEDULER_TaskIdentifier pp_task;
241
242   /* PP match list */
243   struct ProxyREMatch *pp_match_head;
244
245   /* PP match list */
246   struct ProxyREMatch *pp_match_tail;
247
248   /* The authority of the corresponding host (site of origin) */
249   char authority[256];
250
251   /* The hostname (Host header field) */
252   char host[256];
253
254   /* The LEgacy HOstname (can be empty) */
255   char leho[256];
256
257   /* The associated daemon list entry */
258   struct MhdHttpList *mhd;
259
260   /* The associated response */
261   struct MHD_Response *response;
262
263   /* Cookies to set */
264   struct ProxySetCookieHeader *set_cookies_head;
265
266   /* Cookies to set */
267   struct ProxySetCookieHeader *set_cookies_tail;
268
269   /* connection status */
270   int ready_to_queue;
271   
272   /* are we done */
273   int fin;
274
275   /* connection */
276   struct MHD_Connection *connection;
277
278   /*put*/
279   size_t put_read_offset;
280   size_t put_read_size;
281   
282 };
283
284 /**
285  * Struct for RE matches in postprocessing of HTML
286  */
287 struct ProxyREMatch
288 {
289   /* DLL */
290   struct ProxyREMatch *next;
291
292   /* DLL */
293   struct ProxyREMatch *prev;
294
295   /* hostname found */
296   char hostname[255];
297
298   /* PP result */
299   char result[255];
300
301   /* shorten task */
302   struct GNUNET_GNS_ShortenRequest *shorten_task;
303
304   /* are we done */
305   int done;
306
307   /* start of match in buffer */
308   char* start;
309
310   /* end of match in buffer */
311   char* end;
312
313   /* associated proxycurltask */
314   struct ProxyCurlTask *ctask;
315 };
316
317 /**
318  * Struct for set-cookies
319  */
320 struct ProxySetCookieHeader
321 {
322   /* DLL */
323   struct ProxySetCookieHeader *next;
324
325   /* DLL */
326   struct ProxySetCookieHeader *prev;
327
328   /* the cookie */
329   char *cookie;
330 };
331
332 /* The port the proxy is running on (default 7777) */
333 static unsigned long port = GNUNET_GNS_PROXY_PORT;
334
335 /* The CA file (pem) to use for the proxy CA */
336 static char* cafile_opt;
337
338 /* The listen socket of the proxy */
339 static struct GNUNET_NETWORK_Handle *lsock;
340
341 /* The listen task ID */
342 GNUNET_SCHEDULER_TaskIdentifier ltask;
343
344 /* The cURL download task */
345 GNUNET_SCHEDULER_TaskIdentifier curl_download_task;
346
347 /* The non SSL httpd daemon handle */
348 static struct MHD_Daemon *httpd;
349
350 /* Number of current mhd connections */
351 static unsigned int total_mhd_connections;
352
353 /* The cURL multi handle */
354 static CURLM *curl_multi;
355
356 /* Handle to the GNS service */
357 static struct GNUNET_GNS_Handle *gns_handle;
358
359 /* DLL for ProxyCurlTasks */
360 static struct ProxyCurlTask *ctasks_head;
361
362 /* DLL for ProxyCurlTasks */
363 static struct ProxyCurlTask *ctasks_tail;
364
365 /* DLL for http daemons */
366 static struct MhdHttpList *mhd_httpd_head;
367
368 /* DLL for http daemons */
369 static struct MhdHttpList *mhd_httpd_tail;
370
371 /* Handle to the regex for dotplus (.+) replacement in HTML */
372 static regex_t re_dotplus;
373
374 /* The users local GNS zone hash */
375 static struct GNUNET_CRYPTO_ShortHashCode local_gns_zone;
376
377 /* The users local private zone */
378 static struct GNUNET_CRYPTO_ShortHashCode local_private_zone;
379
380 /* The users local shorten zone */
381 static struct GNUNET_CRYPTO_ShortHashCode local_shorten_zone;
382
383 /* The CA for SSL certificate generation */
384 static struct ProxyCA proxy_ca;
385
386 /* UNIX domain socket for mhd */
387 struct GNUNET_NETWORK_Handle *mhd_unix_socket;
388
389 /* Shorten zone private key */
390 struct GNUNET_CRYPTO_RsaPrivateKey *shorten_zonekey;
391
392 /**
393  * Checks if name is in tld
394  *
395  * @param name the name to check
396  * @param tld the TLD to check for
397  * @return GNUNET_YES or GNUNET_NO
398  */
399 int
400 is_tld(const char* name, const char* tld)
401 {
402   size_t offset;
403
404   if (strlen(name) <= strlen(tld))  
405     return GNUNET_NO;  
406
407   offset = strlen(name) - strlen(tld);
408   if (0 != strcmp (name+offset, tld))
409   {
410     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
411                "%s is not in .%s TLD\n", name, tld);
412     return GNUNET_NO;
413   }
414
415   return GNUNET_YES;
416 }
417
418 static int
419 get_uri_val_iter (void *cls,
420                   enum MHD_ValueKind kind,
421                   const char *key,
422                   const char *value)
423 {
424   char* buf = cls;
425   
426   if (strlen (buf) + strlen (value) + 3 > MAX_HTTP_URI_LENGTH)
427     return MHD_NO;
428   sprintf (buf+strlen (buf), "?%s=%s", key, value);
429
430   return MHD_YES;
431 }
432
433 /**
434  * Read HTTP request header field 'Host'
435  *
436  * @param cls buffer to write to
437  * @param kind value kind
438  * @param key field key
439  * @param value field value
440  * @return MHD_NO when Host found
441  */
442 static int
443 con_val_iter (void *cls,
444               enum MHD_ValueKind kind,
445               const char *key,
446               const char *value)
447 {
448   struct ProxyCurlTask *ctask = cls;
449   char* buf = ctask->host;
450   char* cstr;
451   const char* hdr_val;
452
453   if (0 == strcmp ("Host", key))
454   {
455     strcpy (buf, value);
456     return MHD_YES;
457   }
458
459   if (0 == strcmp ("Accept-Encoding", key))
460     hdr_val = "";
461   else
462     hdr_val = value;
463
464   cstr = GNUNET_malloc (strlen (key) + strlen (hdr_val) + 3);
465   GNUNET_snprintf (cstr, strlen (key) + strlen (hdr_val) + 3,
466                    "%s: %s", key, hdr_val);
467
468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
469               "Client Header: %s\n", cstr);
470
471   ctask->headers = curl_slist_append (ctask->headers, cstr);
472   GNUNET_free (cstr);
473
474   return MHD_YES;
475 }
476
477
478 /**
479  * Callback for MHD response
480  *
481  * @param cls closure
482  * @param pos in buffer
483  * @param buf buffer
484  * @param max space in buffer
485  * @return number of bytes written
486  */
487 static ssize_t
488 mhd_content_cb (void *cls,
489                 uint64_t pos,
490                 char* buf,
491                 size_t max);
492
493 /**
494  * Check HTTP response header for mime
495  *
496  * @param buffer curl buffer
497  * @param size curl blocksize
498  * @param nmemb curl blocknumber
499  * @param cls handle
500  * @return size of read bytes
501  */
502 static size_t
503 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
504 {
505   size_t bytes = size * nmemb;
506   struct ProxyCurlTask *ctask = cls;
507   int html_mime_len = strlen (HTML_HDR_CONTENT);
508   int cookie_hdr_len = strlen (MHD_HTTP_HEADER_SET_COOKIE);
509   char hdr_mime[html_mime_len+1];
510   char hdr_generic[bytes+1];
511   char new_cookie_hdr[bytes+strlen (ctask->leho)+1];
512   char* ndup;
513   char* tok;
514   char* cookie_domain;
515   char* hdr_type;
516   char* hdr_val;
517   int delta_cdomain;
518   size_t offset = 0;
519   
520   if (NULL == ctask->response)
521   {
522     /* FIXME: get total size from curl (if available) */
523     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
524                 "Creating response for %s\n", ctask->url);
525     ctask->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
526                                                          sizeof (ctask->buffer),
527                                                          &mhd_content_cb,
528                                                          ctask,
529                                                          NULL);
530     ctask->ready_to_queue = GNUNET_YES;
531     
532   }
533   
534   if (html_mime_len <= bytes)
535   {
536     memcpy (hdr_mime, buffer, html_mime_len);
537     hdr_mime[html_mime_len] = '\0';
538
539     if (0 == strcmp (hdr_mime, HTML_HDR_CONTENT))
540     {
541       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
542                   "Got HTML HTTP response header\n");
543       ctask->parse_content = GNUNET_YES;
544     }
545   }
546
547   if (cookie_hdr_len > bytes)
548     return bytes;
549
550   memcpy (hdr_generic, buffer, bytes);
551   hdr_generic[bytes] = '\0';
552   /* remove crlf */
553   if ('\n' == hdr_generic[bytes-1])
554     hdr_generic[bytes-1] = '\0';
555
556   if (hdr_generic[bytes-2] == '\r')
557     hdr_generic[bytes-2] = '\0';
558   
559   if (0 == memcmp (hdr_generic,
560                    MHD_HTTP_HEADER_SET_COOKIE,
561                    cookie_hdr_len))
562   {
563     ndup = GNUNET_strdup (hdr_generic+cookie_hdr_len+1);
564     memset (new_cookie_hdr, 0, sizeof (new_cookie_hdr));
565     tok = strtok (ndup, ";");
566
567     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
568                 "Looking for cookie in : %s\n", hdr_generic);
569     
570     for (; tok != NULL; tok = strtok (NULL, ";"))
571     {
572       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
573                   "Got Cookie token: %s\n", tok);
574       //memcpy (new_cookie_hdr+offset, tok, strlen (tok));
575       if (0 == memcmp (tok, " domain", strlen (" domain")))
576       {
577         cookie_domain = tok + strlen (" domain") + 1;
578
579         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
580                     "Got Set-Cookie Domain: %s\n", cookie_domain);
581
582         if (strlen (cookie_domain) < strlen (ctask->leho))
583         {
584           delta_cdomain = strlen (ctask->leho) - strlen (cookie_domain);
585           if (0 == strcmp (cookie_domain, ctask->leho + (delta_cdomain)))
586           {
587             GNUNET_snprintf (new_cookie_hdr+offset,
588                              sizeof (new_cookie_hdr),
589                              " domain=%s", ctask->authority);
590             offset += strlen (" domain=") + strlen (ctask->authority);
591             new_cookie_hdr[offset] = ';';
592             offset++;
593             continue;
594           }
595         }
596         else if (strlen (cookie_domain) == strlen (ctask->leho))
597         {
598           if (0 == strcmp (cookie_domain, ctask->leho))
599           {
600             GNUNET_snprintf (new_cookie_hdr+offset,
601                              sizeof (new_cookie_hdr),
602                              " domain=%s", ctask->host);
603             offset += strlen (" domain=") + strlen (ctask->host);
604             new_cookie_hdr[offset] = ';';
605             offset++;
606             continue;
607           }
608         }
609         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
610                     "Cookie domain invalid\n");
611
612         
613       }
614       memcpy (new_cookie_hdr+offset, tok, strlen (tok));
615       offset += strlen (tok);
616       new_cookie_hdr[offset] = ';';
617       offset++;
618     }
619     
620     GNUNET_free (ndup);
621
622     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
623                 "Got Set-Cookie HTTP header %s\n", new_cookie_hdr);
624
625     if (GNUNET_NO == MHD_add_response_header (ctask->response,
626                                               MHD_HTTP_HEADER_SET_COOKIE,
627                                               new_cookie_hdr))
628     {
629       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
630                   "MHD: Error adding set-cookie header field %s\n",
631                   hdr_generic+cookie_hdr_len+1);
632     }
633     return bytes;
634   }
635
636   ndup = GNUNET_strdup (hdr_generic);
637   hdr_type = strtok (ndup, ":");
638
639   if (NULL == hdr_type)
640   {
641     GNUNET_free (ndup);
642     return bytes;
643   }
644
645   hdr_val = strtok (NULL, "");
646
647   if (NULL == hdr_val)
648   {
649     GNUNET_free (ndup);
650     return bytes;
651   }
652
653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
654               "Trying to set %s: %s\n",
655               hdr_type,
656               hdr_val+1);
657   if (GNUNET_NO == MHD_add_response_header (ctask->response,
658                                             hdr_type,
659                                             hdr_val+1))
660   {
661     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
662                 "MHD: Error adding %s header field %s\n",
663                 hdr_type,
664                 hdr_val+1);
665   }
666   GNUNET_free (ndup);
667   return bytes;
668 }
669
670 /**
671  * schedule mhd
672  *
673  * @param hd a http daemon list entry
674  */
675 static void
676 run_httpd (struct MhdHttpList *hd);
677
678
679 /**
680  * schedule all mhds
681  *
682  */
683 static void
684 run_httpds (void);
685
686 /**
687  * Task run whenever HTTP server operations are pending.
688  *
689  * @param cls unused
690  * @param tc sched context
691  */
692 static void
693 do_httpd (void *cls,
694           const struct GNUNET_SCHEDULER_TaskContext *tc);
695
696 static void
697 run_mhd_now (struct MhdHttpList *hd)
698 {
699   if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
700   {
701     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
702                 "MHD: killing old task\n");
703     GNUNET_SCHEDULER_cancel (hd->httpd_task);
704   }
705   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
706               "MHD: Scheduling MHD now\n");
707   hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd, hd);
708 }
709
710 /**
711  * Ask cURL for the select sets and schedule download
712  */
713 static void
714 curl_download_prepare ();
715
716 /**
717  * Callback to free content
718  *
719  * @param cls content to free
720  * @param tc task context
721  */
722 static void
723 mhd_content_free (void *cls,
724                   const struct GNUNET_SCHEDULER_TaskContext *tc)
725 {
726   struct ProxyCurlTask *ctask = cls;
727   GNUNET_assert (NULL == ctask->pp_match_head);
728
729   if (NULL != ctask->headers)
730     curl_slist_free_all (ctask->headers);
731
732   if (NULL != ctask->headers)
733     curl_slist_free_all (ctask->resolver);
734
735   if (NULL != ctask->response)
736     MHD_destroy_response (ctask->response);
737
738
739   GNUNET_free (ctask);
740 }
741
742
743 /**
744  * Callback for MHD response
745  *
746  * @param cls closure
747  * @param pos in buffer
748  * @param buf buffer
749  * @param max space in buffer
750  * @return number of bytes written
751  */
752 static ssize_t
753 mhd_content_cb (void *cls,
754                 uint64_t pos,
755                 char* buf,
756                 size_t max)
757 {
758   struct ProxyCurlTask *ctask = cls;
759   struct ProxyREMatch *re_match = ctask->pp_match_head;
760   ssize_t copied = 0;
761   long long int bytes_to_copy = ctask->buffer_write_ptr - ctask->buffer_read_ptr;
762
763   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
764               "MHD: content cb for %s. To copy: %lld\n",
765               ctask->url, bytes_to_copy);
766   GNUNET_assert (bytes_to_copy >= 0);
767
768   if ((GNUNET_YES == ctask->download_is_finished) &&
769       (GNUNET_NO == ctask->download_error) &&
770       (0 == bytes_to_copy) &&
771       (BUF_WAIT_FOR_CURL == ctask->buf_status))
772   {
773     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
774                 "MHD: sending response for %s\n", ctask->url);
775     ctask->download_in_progress = GNUNET_NO;
776     run_mhd_now (ctask->mhd);
777     GNUNET_SCHEDULER_add_now (&mhd_content_free, ctask);
778     total_mhd_connections--;
779     return MHD_CONTENT_READER_END_OF_STREAM;
780   }
781   
782   if ((GNUNET_YES == ctask->download_error) &&
783       (GNUNET_YES == ctask->download_is_finished) &&
784       (0 == bytes_to_copy) &&
785       (BUF_WAIT_FOR_CURL == ctask->buf_status))
786   {
787     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
788                 "MHD: sending error response\n");
789     ctask->download_in_progress = GNUNET_NO;
790     run_mhd_now (ctask->mhd);
791     GNUNET_SCHEDULER_add_now (&mhd_content_free, ctask);
792     total_mhd_connections--;
793     return MHD_CONTENT_READER_END_WITH_ERROR;
794   }
795
796   if ( ctask->buf_status == BUF_WAIT_FOR_CURL )
797     return 0;
798   
799   copied = 0;
800   for (; NULL != re_match; re_match = ctask->pp_match_head)
801   {
802     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
803                 "MHD: Processing PP %s\n",
804                 re_match->hostname);
805     bytes_to_copy = re_match->start - ctask->buffer_read_ptr;
806     GNUNET_assert (bytes_to_copy >= 0);
807
808     if (bytes_to_copy+copied > max)
809     {
810       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
811              "MHD: buffer in response too small for %d. Using available space (%d). (%s)\n",
812              bytes_to_copy,
813              max,
814              ctask->url);
815       memcpy (buf+copied, ctask->buffer_read_ptr, max-copied);
816       ctask->buffer_read_ptr += max-copied;
817       copied = max;
818       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
819               "MHD: copied %d bytes\n", copied);
820       return copied;
821     }
822
823     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
824                 "MHD: copying %d bytes to mhd response at offset %d\n",
825                 bytes_to_copy, ctask->buffer_read_ptr);
826     memcpy (buf+copied, ctask->buffer_read_ptr, bytes_to_copy);
827     copied += bytes_to_copy;
828
829     if (GNUNET_NO == re_match->done)
830     {
831       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
832                   "MHD: Waiting for PP of %s\n", re_match->hostname);
833       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
834               "MHD: copied %d bytes\n", copied);
835       ctask->buffer_read_ptr += bytes_to_copy;
836       return copied;
837     }
838     
839     if (strlen (re_match->result) > (max - copied))
840     {
841       //FIXME partially copy domain here
842       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
843                   "MHD: buffer in response too small for %s! (%s)\n",
844                   re_match->result,
845                   ctask->url);
846       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847               "MHD: copied %d bytes\n", copied);
848       ctask->buffer_read_ptr += bytes_to_copy;
849       return copied;
850     }
851     
852     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853                 "MHD: Adding PP result %s to buffer\n",
854                 re_match->result);
855     memcpy (buf+copied, re_match->result, strlen (re_match->result));
856     copied += strlen (re_match->result);
857     ctask->buffer_read_ptr = re_match->end;
858     GNUNET_CONTAINER_DLL_remove (ctask->pp_match_head,
859                                  ctask->pp_match_tail,
860                                  re_match);
861     GNUNET_free (re_match);
862   }
863
864   bytes_to_copy = ctask->buffer_write_ptr - ctask->buffer_read_ptr;
865
866   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
867               "MHD: copied: %d left: %d, space left in buf: %d\n",
868               copied,
869               bytes_to_copy, max-copied);
870   
871   GNUNET_assert (0 <= bytes_to_copy);
872
873   if (GNUNET_NO == ctask->download_is_finished)
874   {
875     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
876                 "MHD: Purging buffer\n");
877     memmove (ctask->buffer, ctask->buffer_read_ptr, bytes_to_copy);
878     ctask->buffer_read_ptr = ctask->buffer;
879     ctask->buffer_write_ptr = ctask->buffer + bytes_to_copy;
880     ctask->buffer[bytes_to_copy] = '\0';
881   }
882   
883   if (bytes_to_copy+copied > max)
884     bytes_to_copy = max-copied;
885
886   if (0 > bytes_to_copy)
887     bytes_to_copy = 0;
888   
889   memcpy (buf+copied, ctask->buffer_read_ptr, bytes_to_copy);
890   ctask->buffer_read_ptr += bytes_to_copy;
891   copied += bytes_to_copy;
892   ctask->buf_status = BUF_WAIT_FOR_CURL;
893   
894   if (NULL != ctask->curl)
895     curl_easy_pause (ctask->curl, CURLPAUSE_CONT);
896
897   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898               "MHD: copied %d bytes\n", copied);
899   run_mhd_now (ctask->mhd);
900   return copied;
901 }
902
903 /**
904  * Shorten result callback
905  *
906  * @param cls the proxycurltask
907  * @param short_name the shortened name (NULL on error)
908  */
909 static void
910 process_shorten (void* cls, const char* short_name)
911 {
912   struct ProxyREMatch *re_match = cls;
913   char result[sizeof (re_match->result)];
914   
915   if (NULL == short_name)
916   {
917     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
918                 "PP: Unable to shorten %s\n",
919                 re_match->hostname);
920     GNUNET_CONTAINER_DLL_remove (re_match->ctask->pp_match_head,
921                                  re_match->ctask->pp_match_tail,
922                                  re_match);
923     GNUNET_free (re_match);
924     return;
925   }
926
927   if (0 == strcmp (short_name, re_match->ctask->leho))
928     strcpy (result, re_match->ctask->host);
929   else
930     strcpy (result, short_name);
931
932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
933               "PP: Shorten %s -> %s\n",
934               re_match->hostname,
935               result);
936   
937   if (re_match->ctask->mhd->is_ssl)
938     sprintf (re_match->result, "href=\"https://%s", result);
939   else
940     sprintf (re_match->result, "href=\"http://%s", result);
941
942   re_match->done = GNUNET_YES;
943   run_mhd_now (re_match->ctask->mhd);
944 }
945
946
947 /**
948  * Postprocess data in buffer. From read ptr to write ptr
949  *
950  * @param cls the curlproxytask
951  * @param tc task context
952  */
953 static void
954 postprocess_buffer (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
955 {
956   struct ProxyCurlTask *ctask = cls;
957   struct ProxyREMatch *re_match;
958   char* re_ptr = ctask->buffer_read_ptr;
959   char re_hostname[255];
960   regmatch_t m[RE_N_MATCHES];
961
962   ctask->pp_task = GNUNET_SCHEDULER_NO_TASK;
963
964   if (GNUNET_YES != ctask->parse_content)
965   {
966     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
967                 "PP: Not parsing content\n");
968     ctask->buf_status = BUF_WAIT_FOR_MHD;
969     run_mhd_now (ctask->mhd);
970     return;
971   }
972
973   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
974               "PP: We need to parse the HTML\n");
975
976   /* 0 means match found */
977   while (0 == regexec (&re_dotplus, re_ptr, RE_N_MATCHES, m, 0))
978   {
979     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
980                 "PP: regex match\n");
981
982     GNUNET_assert (m[1].rm_so != -1);
983
984     memset (re_hostname, 0, sizeof (re_hostname));
985     memcpy (re_hostname, re_ptr+m[1].rm_so, (m[3].rm_eo-m[1].rm_so));
986
987     re_match = GNUNET_malloc (sizeof (struct ProxyREMatch));
988     re_match->start = re_ptr + m[0].rm_so;
989     re_match->end = re_ptr + m[3].rm_eo;
990     re_match->done = GNUNET_NO;
991     re_match->ctask = ctask;
992     strcpy (re_match->hostname, re_hostname);
993     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
994                 "PP: Got hostname %s\n", re_hostname);
995     re_ptr += m[3].rm_eo;
996
997     if (GNUNET_YES == is_tld (re_match->hostname, GNUNET_GNS_TLD_PLUS))
998     {
999       re_match->hostname[strlen(re_match->hostname)-1] = '\0';
1000       strcpy (re_match->hostname+strlen(re_match->hostname),
1001               ctask->authority);
1002     }
1003
1004     re_match->shorten_task = GNUNET_GNS_shorten_zone (gns_handle,
1005                              re_match->hostname,
1006                              &local_private_zone,
1007                              &local_shorten_zone,
1008                              &local_gns_zone,
1009                              &process_shorten,
1010                              re_match); //FIXME cancel appropriately
1011
1012     GNUNET_CONTAINER_DLL_insert_tail (ctask->pp_match_head,
1013                                       ctask->pp_match_tail,
1014                                       re_match);
1015   }
1016   
1017   ctask->buf_status = BUF_WAIT_FOR_MHD;
1018   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1019               "PP: No more matches\n");
1020   run_mhd_now (ctask->mhd);
1021 }
1022
1023 /**
1024  * Handle data from cURL
1025  *
1026  * @param ptr pointer to the data
1027  * @param size number of blocks of data
1028  * @param nmemb blocksize
1029  * @param ctx the curlproxytask
1030  * @return number of bytes handled
1031  */
1032 static size_t
1033 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1034 {
1035   const char *cbuf = ptr;
1036   size_t total = size * nmemb;
1037   struct ProxyCurlTask *ctask = ctx;
1038   size_t buf_space = sizeof (ctask->buffer) -
1039     (ctask->buffer_write_ptr-ctask->buffer);
1040
1041   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1042               "CURL: Got %d. %d free in buffer\n",
1043               total, buf_space);
1044
1045   if (total > (buf_space - CURL_BUF_PADDING))
1046   {
1047     if (ctask->buf_status == BUF_WAIT_FOR_CURL)
1048     {
1049       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1050                   "CURL: Buffer full starting postprocessing\n");
1051       ctask->buf_status = BUF_WAIT_FOR_PP;
1052       ctask->pp_task = GNUNET_SCHEDULER_add_now (&postprocess_buffer,
1053                                                  ctask);
1054       return CURL_WRITEFUNC_PAUSE;
1055     }
1056
1057     /* we should not get called in that case */
1058     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1059                 "CURL: called out of context and no space in buffer!\n");
1060     return CURL_WRITEFUNC_PAUSE;
1061   }
1062
1063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1064               "CURL: Copying %d bytes to buffer (%s)\n", total, ctask->url);
1065   memcpy (ctask->buffer_write_ptr, cbuf, total);
1066   ctask->bytes_in_buffer += total;
1067   ctask->buffer_write_ptr += total;
1068   ctask->buffer_write_ptr[0] = '\0';
1069
1070   return total;
1071 }
1072
1073 /**
1074  * Task that is run when we are ready to receive more data
1075  * from curl
1076  *
1077  * @param cls closure
1078  * @param tc task context
1079  */
1080 static void
1081 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1082
1083 /**
1084  * Ask cURL for the select sets and schedule download
1085  */
1086 static void
1087 curl_download_prepare ()
1088 {
1089   CURLMcode mret;
1090   fd_set rs;
1091   fd_set ws;
1092   fd_set es;
1093   int max;
1094   struct GNUNET_NETWORK_FDSet *grs;
1095   struct GNUNET_NETWORK_FDSet *gws;
1096   long to;
1097   struct GNUNET_TIME_Relative rtime;
1098
1099   max = -1;
1100   FD_ZERO (&rs);
1101   FD_ZERO (&ws);
1102   FD_ZERO (&es);
1103   mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max);
1104
1105   if (mret != CURLM_OK)
1106   {
1107     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1108                 "%s failed at %s:%d: `%s'\n",
1109                 "curl_multi_fdset", __FILE__, __LINE__,
1110                 curl_multi_strerror (mret));
1111     //TODO cleanup here?
1112     return;
1113   }
1114
1115   mret = curl_multi_timeout (curl_multi, &to);
1116   rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1117
1118   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1119               "cURL multi fds: max=%d timeout=%llu\n", max, to);
1120
1121   grs = GNUNET_NETWORK_fdset_create ();
1122   gws = GNUNET_NETWORK_fdset_create ();
1123   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1124   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1125   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1126               "Scheduling task cURL\n");
1127
1128   if (curl_download_task != GNUNET_SCHEDULER_NO_TASK)
1129     GNUNET_SCHEDULER_cancel (curl_download_task);
1130   
1131   if (-1 != max)
1132   {
1133     curl_download_task =
1134       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1135                                    rtime,
1136                                    grs, gws,
1137                                    &curl_task_download, curl_multi);
1138   }
1139   else if (NULL != ctasks_head)
1140   {
1141     /* as specified in curl docs */
1142     curl_download_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1143                                                        &curl_task_download,
1144                                                        curl_multi);
1145   }
1146   GNUNET_NETWORK_fdset_destroy (gws);
1147   GNUNET_NETWORK_fdset_destroy (grs);
1148
1149 }
1150
1151
1152 /**
1153  * Task that is run when we are ready to receive more data
1154  * from curl
1155  *
1156  * @param cls closure
1157  * @param tc task context
1158  */
1159 static void
1160 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1161 {
1162   int running;
1163   int msgnum;
1164   struct CURLMsg *msg;
1165   CURLMcode mret;
1166   struct ProxyCurlTask *ctask;
1167   int num_ctasks;
1168   long resp_code;
1169
1170   struct ProxyCurlTask *clean_head = NULL;
1171   struct ProxyCurlTask *clean_tail = NULL;
1172
1173   curl_download_task = GNUNET_SCHEDULER_NO_TASK;
1174
1175   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1176   {
1177     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1178                 "Shutdown requested while trying to download\n");
1179     //TODO cleanup
1180     return;
1181   }
1182   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1183               "Ready to dl\n");
1184
1185   do
1186   {
1187     running = 0;
1188     num_ctasks = 0;
1189     
1190     mret = curl_multi_perform (curl_multi, &running);
1191
1192     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1193                 "Running curl tasks: %d\n", running);
1194
1195     ctask = ctasks_head;
1196     for (; ctask != NULL; ctask = ctask->next)
1197     {
1198       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1199                   "CTask: %s\n", ctask->url);
1200       num_ctasks++;
1201     }
1202
1203     if (num_ctasks != running)
1204     {
1205       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1206                   "%d ctasks, %d curl running\n", num_ctasks, running);
1207     }
1208     
1209     do
1210     {
1211       ctask = ctasks_head;
1212       msg = curl_multi_info_read (curl_multi, &msgnum);
1213       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1214                   "Messages left: %d\n", msgnum);
1215       
1216       if (msg == NULL)
1217         break;
1218       switch (msg->msg)
1219       {
1220        case CURLMSG_DONE:
1221          if ((msg->data.result != CURLE_OK) &&
1222              (msg->data.result != CURLE_GOT_NOTHING))
1223          {
1224            GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1225                        "Download curl failed");
1226             
1227            for (; ctask != NULL; ctask = ctask->next)
1228            {
1229              if (NULL == ctask->curl)
1230                continue;
1231
1232              if (memcmp (msg->easy_handle, ctask->curl, sizeof (CURL)) != 0)
1233                continue;
1234              
1235              GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1236                          "CURL: Download failed for task %s: %s.\n",
1237                          ctask->url,
1238                          curl_easy_strerror (msg->data.result));
1239              ctask->download_is_finished = GNUNET_YES;
1240              ctask->download_error = GNUNET_YES;
1241              if (CURLE_OK == curl_easy_getinfo (ctask->curl,
1242                                                 CURLINFO_RESPONSE_CODE,
1243                                                 &resp_code))
1244                ctask->curl_response_code = resp_code;
1245              ctask->ready_to_queue = MHD_YES;
1246              ctask->buf_status = BUF_WAIT_FOR_MHD;
1247              run_mhd_now (ctask->mhd);
1248              
1249              GNUNET_CONTAINER_DLL_remove (ctasks_head, ctasks_tail,
1250                                           ctask);
1251              GNUNET_CONTAINER_DLL_insert (clean_head, clean_tail, ctask);
1252              break;
1253            }
1254            GNUNET_assert (ctask != NULL);
1255          }
1256          else
1257          {
1258            GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1259                        "CURL: download completed.\n");
1260
1261            for (; ctask != NULL; ctask = ctask->next)
1262            {
1263              if (NULL == ctask->curl)
1264                continue;
1265
1266              if (memcmp (msg->easy_handle, ctask->curl, sizeof (CURL)) != 0)
1267                continue;
1268              
1269              if (ctask->buf_status != BUF_WAIT_FOR_CURL)
1270                continue;
1271              
1272              GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1273                          "CURL: completed task %s found.\n", ctask->url);
1274              if (CURLE_OK == curl_easy_getinfo (ctask->curl,
1275                                                 CURLINFO_RESPONSE_CODE,
1276                                                 &resp_code))
1277                ctask->curl_response_code = resp_code;
1278
1279
1280              GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1281                          "CURL: Completed ctask!\n");
1282              if (GNUNET_SCHEDULER_NO_TASK == ctask->pp_task)
1283              {
1284               ctask->buf_status = BUF_WAIT_FOR_PP;
1285               ctask->pp_task = GNUNET_SCHEDULER_add_now (&postprocess_buffer,
1286                                                           ctask);
1287              }
1288
1289              ctask->ready_to_queue = MHD_YES;
1290              ctask->download_is_finished = GNUNET_YES;
1291
1292              /* We MUST not modify the multi handle else we loose messages */
1293              GNUNET_CONTAINER_DLL_remove (ctasks_head, ctasks_tail,
1294                                           ctask);
1295              GNUNET_CONTAINER_DLL_insert (clean_head, clean_tail, ctask);
1296
1297              break;
1298            }
1299            GNUNET_assert (ctask != NULL);
1300          }
1301          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1302                      "CURL: %s\n", curl_easy_strerror(msg->data.result));
1303          break;
1304        default:
1305          GNUNET_assert (0);
1306          break;
1307       }
1308     } while (msgnum > 0);
1309
1310     for (ctask=clean_head; ctask != NULL; ctask = ctask->next)
1311     {
1312       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1313                   "CURL: Removing task %s.\n", ctask->url);
1314       curl_multi_remove_handle (curl_multi, ctask->curl);
1315       curl_easy_cleanup (ctask->curl);
1316       ctask->curl = NULL;
1317     }
1318     
1319     num_ctasks=0;
1320     for (ctask=ctasks_head; ctask != NULL; ctask = ctask->next)
1321     {
1322       num_ctasks++;
1323     }
1324     
1325     if (num_ctasks != running)
1326     {
1327       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328                   "CURL: %d tasks, %d running\n", num_ctasks, running);
1329     }
1330
1331     GNUNET_assert ( num_ctasks == running );
1332
1333   } while (mret == CURLM_CALL_MULTI_PERFORM);
1334   
1335   if (mret != CURLM_OK)
1336   {
1337     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "CURL: %s failed at %s:%d: `%s'\n",
1338                 "curl_multi_perform", __FILE__, __LINE__,
1339                 curl_multi_strerror (mret));
1340   }
1341   curl_download_prepare();
1342 }
1343
1344 /**
1345  * Process LEHO lookup
1346  *
1347  * @param cls the ctask
1348  * @param rd_count number of records returned
1349  * @param rd record data
1350  */
1351 static void
1352 process_leho_lookup (void *cls,
1353                      uint32_t rd_count,
1354                      const struct GNUNET_NAMESTORE_RecordData *rd)
1355 {
1356   struct ProxyCurlTask *ctask = cls;
1357   char hosthdr[262]; //256 + "Host: "
1358   int i;
1359   CURLcode ret;
1360   CURLMcode mret;
1361   struct hostent *phost;
1362   char *ssl_ip;
1363   char resolvename[512];
1364   char curlurl[512];
1365
1366   strcpy (ctask->leho, "");
1367
1368   if (rd_count == 0)
1369     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1370                 "No LEHO present!\n");
1371
1372   for (i=0; i<rd_count; i++)
1373   {
1374     if (rd[i].record_type != GNUNET_GNS_RECORD_LEHO)
1375       continue;
1376
1377     memcpy (ctask->leho, rd[i].data, rd[i].data_size);
1378
1379     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1380                 "Found LEHO %s for %s\n", ctask->leho, ctask->url);
1381   }
1382
1383   if (0 != strcmp (ctask->leho, ""))
1384   {
1385     sprintf (hosthdr, "%s%s", "Host: ", ctask->leho);
1386     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1387                 "New HTTP header value: %s\n", hosthdr);
1388     ctask->headers = curl_slist_append (ctask->headers, hosthdr);
1389     GNUNET_assert (NULL != ctask->headers);
1390     ret = curl_easy_setopt (ctask->curl, CURLOPT_HTTPHEADER, ctask->headers);
1391     if (CURLE_OK != ret)
1392     {
1393       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s failed at %s:%d: `%s'\n",
1394                            "curl_easy_setopt", __FILE__, __LINE__, curl_easy_strerror(ret));
1395     }
1396
1397   }
1398
1399   if (ctask->mhd->is_ssl)
1400   {
1401     phost = (struct hostent*)gethostbyname (ctask->host);
1402
1403     if (phost!=NULL)
1404     {
1405       ssl_ip = inet_ntoa(*((struct in_addr*)(phost->h_addr)));
1406       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1407                   "SSL target server: %s\n", ssl_ip);
1408       sprintf (resolvename, "%s:%d:%s", ctask->leho, HTTPS_PORT, ssl_ip);
1409       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1410                   "Curl resolve: %s\n", resolvename);
1411       ctask->resolver = curl_slist_append ( ctask->resolver, resolvename);
1412       curl_easy_setopt (ctask->curl, CURLOPT_RESOLVE, ctask->resolver);
1413       sprintf (curlurl, "https://%s%s", ctask->leho, ctask->url);
1414       curl_easy_setopt (ctask->curl, CURLOPT_URL, curlurl);
1415     }
1416     else
1417     {
1418       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1419                   "gethostbyname failed for %s!\n", ctask->host);
1420       ctask->download_is_finished = GNUNET_YES;
1421       ctask->download_error = GNUNET_YES;
1422       return;
1423     }
1424   }
1425
1426   if (CURLM_OK != (mret=curl_multi_add_handle (curl_multi, ctask->curl)))
1427   {
1428     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1429                 "%s failed at %s:%d: `%s'\n",
1430                 "curl_multi_add_handle", __FILE__, __LINE__,
1431                 curl_multi_strerror (mret));
1432     ctask->download_is_finished = GNUNET_YES;
1433     ctask->download_error = GNUNET_YES;
1434     return;
1435   }
1436   GNUNET_CONTAINER_DLL_insert (ctasks_head, ctasks_tail, ctask);
1437
1438   curl_download_prepare ();
1439
1440 }
1441
1442 /**
1443  * Initialize download and trigger curl
1444  *
1445  * @param cls the proxycurltask
1446  * @param auth_name the name of the authority (site of origin) of ctask->host
1447  *
1448  */
1449 static void
1450 process_get_authority (void *cls,
1451                        const char* auth_name)
1452 {
1453   struct ProxyCurlTask *ctask = cls;
1454
1455   if (NULL == auth_name)
1456   {
1457     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1458                 "Get authority failed!\n");
1459     strcpy (ctask->authority, "");
1460   }
1461   else
1462   {
1463     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1464                 "Get authority yielded %s\n", auth_name);
1465     strcpy (ctask->authority, auth_name);
1466   }
1467
1468   GNUNET_GNS_lookup_zone (gns_handle,
1469                           ctask->host,
1470                           &local_gns_zone,
1471                           GNUNET_GNS_RECORD_LEHO,
1472                           GNUNET_YES, //Only cached for performance
1473                           shorten_zonekey,
1474                           &process_leho_lookup,
1475                           ctask);
1476 }
1477
1478
1479 /**
1480  * Main MHD callback for handling requests.
1481  *
1482  * @param cls unused
1483  * @param con MHD connection handle
1484  * @param url the url in the request
1485  * @param meth the HTTP method used ("GET", "PUT", etc.)
1486  * @param ver the HTTP version string (i.e. "HTTP/1.1")
1487  * @param upload_data the data being uploaded (excluding HEADERS,
1488  *        for a POST that fits into memory and that is encoded
1489  *        with a supported encoding, the POST data will NOT be
1490  *        given in upload_data and is instead available as
1491  *        part of MHD_get_connection_values; very large POST
1492  *        data *will* be made available incrementally in
1493  *        upload_data)
1494  * @param upload_data_size set initially to the size of the
1495  *        upload_data provided; the method must update this
1496  *        value to the number of bytes NOT processed;
1497  * @param con_cls pointer to location where we store the 'struct Request'
1498  * @return MHD_YES if the connection was handled successfully,
1499  *         MHD_NO if the socket must be closed due to a serious
1500  *         error while handling the request
1501  */
1502 static int
1503 create_response (void *cls,
1504                  struct MHD_Connection *con,
1505                  const char *url,
1506                  const char *meth,
1507                  const char *ver,
1508                  const char *upload_data,
1509                  size_t *upload_data_size,
1510                  void **con_cls)
1511 {
1512   struct MhdHttpList* hd = cls;
1513   const char* page = "<html><head><title>gnoxy</title>"\
1514                       "</head><body>cURL fail</body></html>";
1515   
1516   char curlurl[MAX_HTTP_URI_LENGTH]; // buffer overflow!
1517   int ret = MHD_YES;
1518
1519   struct ProxyCurlTask *ctask;
1520   
1521   //FIXME handle
1522   if ((0 != strcasecmp (meth, MHD_HTTP_METHOD_GET)) &&
1523       (0 != strcasecmp (meth, MHD_HTTP_METHOD_PUT)) &&
1524       (0 != strcasecmp (meth, MHD_HTTP_METHOD_POST)))
1525   {
1526     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1527                 "MHD: %s NOT IMPLEMENTED!\n", meth);
1528     return MHD_NO;
1529   }
1530
1531
1532   if (NULL == *con_cls)
1533   {
1534
1535     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1536                 "Got %s request for %s\n", meth, url);
1537     ctask = GNUNET_malloc (sizeof (struct ProxyCurlTask));
1538     ctask->mhd = hd;
1539     *con_cls = ctask;
1540     
1541     ctask->curl = curl_easy_init();
1542     if (NULL == ctask->curl)
1543     {
1544       ctask->response = MHD_create_response_from_buffer (strlen (page),
1545                                                 (void*)page,
1546                                                 MHD_RESPMEM_PERSISTENT);
1547       ret = MHD_queue_response (con,
1548                                 MHD_HTTP_OK,
1549                                 ctask->response);
1550       MHD_destroy_response (ctask->response);
1551       GNUNET_free (ctask);
1552       return ret;
1553     }
1554   
1555     ctask->download_in_progress = GNUNET_YES;
1556     ctask->buf_status = BUF_WAIT_FOR_CURL;
1557     ctask->connection = con;
1558     ctask->curl_response_code = MHD_HTTP_OK;
1559     ctask->buffer_read_ptr = ctask->buffer;
1560     ctask->buffer_write_ptr = ctask->buffer;
1561     ctask->pp_task = GNUNET_SCHEDULER_NO_TASK;
1562
1563     MHD_get_connection_values (con,
1564                                MHD_HEADER_KIND,
1565                                &con_val_iter, ctask);
1566
1567     if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1568     {
1569       if (0 == *upload_data_size)
1570       {
1571         curl_easy_cleanup (ctask->curl);
1572         GNUNET_free (ctask);
1573         return MHD_NO;
1574       }
1575       ctask->put_read_offset = 0;
1576       ctask->put_read_size = *upload_data_size;
1577       curl_easy_setopt (ctask->curl, CURLOPT_UPLOAD, 1);
1578       curl_easy_setopt (ctask->curl, CURLOPT_READDATA, upload_data);
1579       //curl_easy_setopt (ctask->curl, CURLOPT_READFUNCTION, &curl_read_cb);
1580       
1581       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1582                   "Got PUT data: %s\n", upload_data);
1583       curl_easy_cleanup (ctask->curl);
1584       GNUNET_free (ctask);
1585       return MHD_NO;
1586     }
1587
1588     if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1589     {
1590       if (0 == *upload_data_size)
1591       {
1592         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1593                     "NO data for post!\n");
1594         curl_easy_cleanup (ctask->curl);
1595         GNUNET_free (ctask);
1596         return MHD_NO;
1597       }
1598       curl_easy_setopt (ctask->curl, CURLOPT_POST, 1);
1599       curl_easy_setopt (ctask->curl, CURLOPT_POSTFIELDSIZE, *upload_data_size);
1600       curl_easy_setopt (ctask->curl, CURLOPT_COPYPOSTFIELDS, upload_data);
1601       
1602       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1603                   "Got POST data: %s\n", upload_data);
1604       curl_easy_cleanup (ctask->curl);
1605       GNUNET_free (ctask);
1606       return MHD_NO;
1607     }
1608
1609     curl_easy_setopt (ctask->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1610     curl_easy_setopt (ctask->curl, CURLOPT_HEADERDATA, ctask);
1611     curl_easy_setopt (ctask->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1612     curl_easy_setopt (ctask->curl, CURLOPT_WRITEDATA, ctask);
1613     curl_easy_setopt (ctask->curl, CURLOPT_FOLLOWLOCATION, 0);
1614     curl_easy_setopt (ctask->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1615     
1616     if (GNUNET_NO == ctask->mhd->is_ssl)
1617     {
1618       sprintf (curlurl, "http://%s%s", ctask->host, url);
1619       MHD_get_connection_values (con,
1620                                  MHD_GET_ARGUMENT_KIND,
1621                                  &get_uri_val_iter, curlurl);
1622       curl_easy_setopt (ctask->curl, CURLOPT_URL, curlurl);
1623     }
1624     strcpy (ctask->url, url);
1625     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1626                   "MHD: Adding new curl task for %s%s\n", ctask->host, url);
1627     MHD_get_connection_values (con,
1628                                MHD_GET_ARGUMENT_KIND,
1629                                &get_uri_val_iter, ctask->url);
1630   
1631     curl_easy_setopt (ctask->curl, CURLOPT_FAILONERROR, 1);
1632     curl_easy_setopt (ctask->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1633     curl_easy_setopt (ctask->curl, CURLOPT_TIMEOUT, 600L);
1634
1635     GNUNET_GNS_get_authority (gns_handle,
1636                               ctask->host,
1637                               &process_get_authority,
1638                               ctask);
1639     ctask->ready_to_queue = GNUNET_NO;
1640     ctask->fin = GNUNET_NO;
1641     return MHD_YES;
1642   }
1643
1644   ctask = (struct ProxyCurlTask *) *con_cls;
1645   
1646   if (GNUNET_YES != ctask->ready_to_queue)
1647     return MHD_YES; /* wait longer */
1648   
1649   if (GNUNET_YES == ctask->fin)
1650     return MHD_YES;
1651
1652   ctask->fin = GNUNET_YES;
1653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1654               "MHD: Queueing response for %s\n", ctask->url);
1655   ret = MHD_queue_response (con, ctask->curl_response_code, ctask->response);
1656   run_mhd_now (ctask->mhd);
1657   return ret;
1658 }
1659
1660
1661 /**
1662  * run all httpd
1663  */
1664 static void
1665 run_httpds ()
1666 {
1667   struct MhdHttpList *hd;
1668
1669   for (hd=mhd_httpd_head; NULL != hd; hd = hd->next)
1670     run_httpd (hd);
1671
1672 }
1673
1674 /**
1675  * schedule mhd
1676  *
1677  * @param hd the daemon to run
1678  */
1679 static void
1680 run_httpd (struct MhdHttpList *hd)
1681 {
1682   fd_set rs;
1683   fd_set ws;
1684   fd_set es;
1685   struct GNUNET_NETWORK_FDSet *wrs;
1686   struct GNUNET_NETWORK_FDSet *wws;
1687   struct GNUNET_NETWORK_FDSet *wes;
1688   int max;
1689   int haveto;
1690   unsigned MHD_LONG_LONG timeout;
1691   struct GNUNET_TIME_Relative tv;
1692
1693   FD_ZERO (&rs);
1694   FD_ZERO (&ws);
1695   FD_ZERO (&es);
1696   wrs = GNUNET_NETWORK_fdset_create ();
1697   wes = GNUNET_NETWORK_fdset_create ();
1698   wws = GNUNET_NETWORK_fdset_create ();
1699   max = -1;
1700   GNUNET_assert (MHD_YES == MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max));
1701   
1702   
1703   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1704               "MHD fds: max=%d\n", max);
1705   
1706   haveto = MHD_get_timeout (hd->daemon, &timeout);
1707
1708   if (MHD_YES == haveto)
1709     tv.rel_value = (uint64_t) timeout;
1710   else
1711     tv = GNUNET_TIME_UNIT_FOREVER_REL;
1712   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1713   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1714   GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
1715   
1716   if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1717     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1718   hd->httpd_task =
1719     GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
1720                                  tv, wrs, wws,
1721                                  &do_httpd, hd);
1722   GNUNET_NETWORK_fdset_destroy (wrs);
1723   GNUNET_NETWORK_fdset_destroy (wws);
1724   GNUNET_NETWORK_fdset_destroy (wes);
1725 }
1726
1727
1728 /**
1729  * Task run whenever HTTP server operations are pending.
1730  *
1731  * @param cls unused
1732  * @param tc sched context
1733  */
1734 static void
1735 do_httpd (void *cls,
1736           const struct GNUNET_SCHEDULER_TaskContext *tc)
1737 {
1738   struct MhdHttpList *hd = cls;
1739   
1740   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1741               "MHD: Main loop\n");
1742   hd->httpd_task = GNUNET_SCHEDULER_NO_TASK; 
1743   MHD_run (hd->daemon);
1744   run_httpd (hd);
1745 }
1746
1747
1748
1749 /**
1750  * Read data from socket
1751  *
1752  * @param cls the closure
1753  * @param tc scheduler context
1754  */
1755 static void
1756 do_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1757
1758 /**
1759  * Read from remote end
1760  *
1761  * @param cls closure
1762  * @param tc scheduler context
1763  */
1764 static void
1765 do_read_remote (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1766
1767 /**
1768  * Write data to remote socket
1769  *
1770  * @param cls the closure
1771  * @param tc scheduler context
1772  */
1773 static void
1774 do_write_remote (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1775 {
1776   struct Socks5Request *s5r = cls;
1777   unsigned int len;
1778
1779   s5r->fwdwtask = GNUNET_SCHEDULER_NO_TASK;
1780
1781   if ((NULL != tc->read_ready) &&
1782       (GNUNET_NETWORK_fdset_isset (tc->write_ready, s5r->remote_sock)) &&
1783       ((len = GNUNET_NETWORK_socket_send (s5r->remote_sock, s5r->rbuf,
1784                                          s5r->rbuf_len)>0)))
1785   {
1786     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1787                 "Successfully sent %d bytes to remote socket\n",
1788                 len);
1789   }
1790   else
1791   {
1792     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write remote");
1793     if (GNUNET_SCHEDULER_NO_TASK != s5r->rtask)
1794       GNUNET_SCHEDULER_cancel (s5r->rtask);
1795     if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
1796       GNUNET_SCHEDULER_cancel (s5r->wtask);
1797     if (GNUNET_SCHEDULER_NO_TASK != s5r->fwdrtask)
1798       GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
1799     GNUNET_NETWORK_socket_close (s5r->remote_sock);
1800     GNUNET_NETWORK_socket_close (s5r->sock);
1801     GNUNET_free(s5r);
1802     return;
1803   }
1804
1805   s5r->rtask =
1806     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1807                                    s5r->sock,
1808                                    &do_read, s5r);
1809 }
1810
1811
1812 /**
1813  * Clean up s5r handles
1814  *
1815  * @param s5r the handle to destroy
1816  */
1817 static void
1818 cleanup_s5r (struct Socks5Request *s5r)
1819 {
1820   if (GNUNET_SCHEDULER_NO_TASK != s5r->rtask)
1821     GNUNET_SCHEDULER_cancel (s5r->rtask);
1822   if (GNUNET_SCHEDULER_NO_TASK != s5r->fwdwtask)
1823     GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
1824   if (GNUNET_SCHEDULER_NO_TASK != s5r->fwdrtask)
1825     GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
1826   
1827   if (NULL != s5r->remote_sock)
1828     GNUNET_NETWORK_socket_close (s5r->remote_sock);
1829   if ((NULL != s5r->sock) && (s5r->cleanup_sock == GNUNET_YES))
1830     GNUNET_NETWORK_socket_close (s5r->sock);
1831   
1832   GNUNET_free(s5r);
1833 }
1834
1835 /**
1836  * Write data to socket
1837  *
1838  * @param cls the closure
1839  * @param tc scheduler context
1840  */
1841 static void
1842 do_write (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1843 {
1844   struct Socks5Request *s5r = cls;
1845   unsigned int len;
1846
1847   s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
1848
1849   if ((NULL != tc->read_ready) &&
1850       (GNUNET_NETWORK_fdset_isset (tc->write_ready, s5r->sock)) &&
1851       ((len = GNUNET_NETWORK_socket_send (s5r->sock, s5r->wbuf,
1852                                          s5r->wbuf_len)>0)))
1853   {
1854     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1855                 "Successfully sent %d bytes to socket\n",
1856                 len);
1857   }
1858   else
1859   {
1860     
1861     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1862     s5r->cleanup = GNUNET_YES;
1863     s5r->cleanup_sock = GNUNET_YES;
1864     cleanup_s5r (s5r);
1865     
1866     return;
1867   }
1868
1869   if (GNUNET_YES == s5r->cleanup)
1870   {
1871     cleanup_s5r (s5r);
1872     return;
1873   }
1874
1875   if ((s5r->state == SOCKS5_DATA_TRANSFER) &&
1876       (s5r->fwdrtask == GNUNET_SCHEDULER_NO_TASK))
1877     s5r->fwdrtask =
1878       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1879                                      s5r->remote_sock,
1880                                      &do_read_remote, s5r);
1881 }
1882
1883 /**
1884  * Read from remote end
1885  *
1886  * @param cls closure
1887  * @param tc scheduler context
1888  */
1889 static void
1890 do_read_remote (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1891 {
1892   struct Socks5Request *s5r = cls;
1893   
1894   s5r->fwdrtask = GNUNET_SCHEDULER_NO_TASK;
1895
1896
1897   if ((NULL != tc->write_ready) &&
1898       (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->remote_sock)) &&
1899       (s5r->wbuf_len = GNUNET_NETWORK_socket_recv (s5r->remote_sock, s5r->wbuf,
1900                                          sizeof (s5r->wbuf))))
1901   {
1902     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1903                 "Successfully read %d bytes from remote socket\n",
1904                 s5r->wbuf_len);
1905   }
1906   else
1907   {
1908     if (s5r->wbuf_len == 0)
1909       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1910                   "0 bytes received from remote... graceful shutdown!\n");
1911     if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
1912       GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
1913     if (s5r->rtask != GNUNET_SCHEDULER_NO_TASK)
1914       GNUNET_SCHEDULER_cancel (s5r->rtask);
1915     
1916     GNUNET_NETWORK_socket_close (s5r->remote_sock);
1917     s5r->remote_sock = NULL;
1918     GNUNET_NETWORK_socket_close (s5r->sock);
1919     GNUNET_free(s5r);
1920
1921     return;
1922   }
1923   
1924   s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1925                                                s5r->sock,
1926                                                &do_write, s5r);
1927   
1928 }
1929
1930
1931 /**
1932  * Adds a socket to MHD
1933  *
1934  * @param h the handle to the socket to add
1935  * @param daemon the daemon to add the fd to
1936  * @return whatever MHD_add_connection returns
1937  */
1938 static int
1939 add_handle_to_mhd (struct GNUNET_NETWORK_Handle *h, struct MHD_Daemon *daemon)
1940 {
1941   int fd;
1942   struct sockaddr *addr;
1943   socklen_t len;
1944
1945   fd = dup (GNUNET_NETWORK_get_fd (h));
1946   addr = GNUNET_NETWORK_get_addr (h);
1947   len = GNUNET_NETWORK_get_addrlen (h);
1948
1949   return MHD_add_connection (daemon, fd, addr, len);
1950 }
1951
1952 /**
1953  * Read file in filename
1954  *
1955  * @param filename file to read
1956  * @param size pointer where filesize is stored
1957  * @return data
1958  */
1959 static char*
1960 load_file (const char* filename, 
1961            unsigned int* size)
1962 {
1963   char *buffer;
1964   uint64_t fsize;
1965
1966   if (GNUNET_OK !=
1967       GNUNET_DISK_file_size (filename, &fsize,
1968                              GNUNET_YES, GNUNET_YES))
1969     return NULL;
1970   if (fsize > MAX_PEM_SIZE)
1971     return NULL;
1972   *size = (unsigned int) fsize;
1973   buffer = GNUNET_malloc (*size);
1974   if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
1975   {
1976     GNUNET_free (buffer);
1977     return NULL;
1978   }
1979   return buffer;
1980 }
1981
1982
1983 /**
1984  * Load PEM key from file
1985  *
1986  * @param key where to store the data
1987  * @param keyfile path to the PEM file
1988  * @return GNUNET_OK on success
1989  */
1990 static int
1991 load_key_from_file (gnutls_x509_privkey_t key, const char* keyfile)
1992 {
1993   gnutls_datum_t key_data;
1994   int ret;
1995
1996   key_data.data = (unsigned char*) load_file (keyfile, &key_data.size);
1997   ret = gnutls_x509_privkey_import (key, &key_data,
1998                                     GNUTLS_X509_FMT_PEM);
1999   if (GNUTLS_E_SUCCESS != ret)
2000   {
2001     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2002                 _("Unable to import private key from file `%s'\n"),
2003                 keyfile);
2004     GNUNET_break (0);
2005   }
2006   GNUNET_free (key_data.data);
2007   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2008 }
2009
2010
2011 /**
2012  * Load cert from file
2013  *
2014  * @param crt struct to store data in
2015  * @param certfile path to pem file
2016  * @return GNUNET_OK on success
2017  */
2018 static int
2019 load_cert_from_file (gnutls_x509_crt_t crt, char* certfile)
2020 {
2021   gnutls_datum_t cert_data;
2022   cert_data.data = NULL;
2023   int ret;
2024
2025   cert_data.data = (unsigned char*) load_file (certfile, &cert_data.size);
2026   ret = gnutls_x509_crt_import (crt, &cert_data,
2027                                 GNUTLS_X509_FMT_PEM);
2028   if (GNUTLS_E_SUCCESS != ret)
2029   {
2030     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2031                _("Unable to import certificate %s\n"), certfile);
2032     GNUNET_break (0);
2033   }
2034   GNUNET_free (cert_data.data);
2035   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2036 }
2037
2038
2039 /**
2040  * Generate new certificate for specific name
2041  *
2042  * @param name the subject name to generate a cert for
2043  * @return a struct holding the PEM data
2044  */
2045 static struct ProxyGNSCertificate *
2046 generate_gns_certificate (const char *name)
2047 {
2048
2049   int ret;
2050   unsigned int serial;
2051   size_t key_buf_size;
2052   size_t cert_buf_size;
2053   gnutls_x509_crt_t request;
2054   time_t etime;
2055   struct tm *tm_data;
2056
2057   ret = gnutls_x509_crt_init (&request);
2058
2059   if (GNUTLS_E_SUCCESS != ret)
2060   {
2061     GNUNET_break (0);
2062   }
2063
2064   ret = gnutls_x509_crt_set_key (request, proxy_ca.key);
2065
2066   if (GNUTLS_E_SUCCESS != ret)
2067   {
2068     GNUNET_break (0);
2069   }
2070
2071   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Generating cert\n");
2072
2073   struct ProxyGNSCertificate *pgc =
2074     GNUNET_malloc (sizeof (struct ProxyGNSCertificate));
2075
2076   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding DNs\n");
2077   
2078   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2079                                  0, "DE", 2);
2080
2081   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2082                                  0, "GNUnet", 6);
2083
2084   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2085                                  0, name, strlen (name));
2086
2087   ret = gnutls_x509_crt_set_version (request, 3);
2088
2089   ret = gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2090
2091   etime = time (NULL);
2092   tm_data = localtime (&etime);
2093   
2094
2095   ret = gnutls_x509_crt_set_serial (request,
2096                                     &serial,
2097                                     sizeof (serial));
2098
2099   ret = gnutls_x509_crt_set_activation_time (request,
2100                                              etime);
2101   tm_data->tm_year++;
2102   etime = mktime (tm_data);
2103
2104   if (-1 == etime)
2105   {
2106     GNUNET_break (0);
2107   }
2108
2109   ret = gnutls_x509_crt_set_expiration_time (request,
2110                                              etime);
2111   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Signing...\n");
2112
2113   ret = gnutls_x509_crt_sign (request, proxy_ca.cert, proxy_ca.key);
2114
2115   key_buf_size = sizeof (pgc->key);
2116   cert_buf_size = sizeof (pgc->cert);
2117
2118   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Exporting certificate...\n");
2119   
2120   gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2121                           pgc->cert, &cert_buf_size);
2122
2123   gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2124                           pgc->key, &key_buf_size);
2125
2126
2127   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n");
2128   gnutls_x509_crt_deinit (request);
2129
2130   return pgc;
2131
2132 }
2133
2134
2135 /*
2136  * Accept policy for mhdaemons
2137  *
2138  * @param cls NULL
2139  * @param addr the sockaddr
2140  * @param addrlen the sockaddr length
2141  * @return MHD_NO if sockaddr is wrong or #conns too high
2142  */
2143 static int
2144 accept_cb (void* cls, const struct sockaddr *addr, socklen_t addrlen)
2145 {
2146   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2147               "In MHD accept policy cb\n");
2148
2149   if (addr != NULL)
2150   {
2151     if (addr->sa_family == AF_UNIX)
2152       return MHD_NO;
2153   }
2154
2155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2156               "Connection accepted\n");
2157
2158   return MHD_YES;
2159 }
2160
2161
2162 /**
2163  * Adds a socket to an SSL MHD instance
2164  * It is important the the domain name is
2165  * correct. In most cases we need to start a new daemon
2166  *
2167  * @param h the handle to add to a daemon
2168  * @param domain the domain the ssl daemon has to serve
2169  * @return MHD_YES on success
2170  */
2171 static int
2172 add_handle_to_ssl_mhd (struct GNUNET_NETWORK_Handle *h, const char* domain)
2173 {
2174   struct MhdHttpList *hd = NULL;
2175   struct ProxyGNSCertificate *pgc;
2176   struct NetworkHandleList *nh;
2177
2178   for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2179     if (0 == strcmp (hd->domain, domain))
2180       break;
2181
2182   if (NULL == hd)
2183   {    
2184     pgc = generate_gns_certificate (domain);
2185     
2186     hd = GNUNET_malloc (sizeof (struct MhdHttpList));
2187     hd->is_ssl = GNUNET_YES;
2188     strcpy (hd->domain, domain);
2189     hd->proxy_cert = pgc;
2190
2191     /* Start new MHD */
2192     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193                 "No previous SSL instance found... starting new one for %s\n",
2194                 domain);
2195
2196     hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL, 4444,
2197             &accept_cb, NULL,
2198             &create_response, hd,
2199             MHD_OPTION_LISTEN_SOCKET, GNUNET_NETWORK_get_fd (mhd_unix_socket),
2200             MHD_OPTION_CONNECTION_LIMIT, MHD_MAX_CONNECTIONS,
2201             MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2202             MHD_OPTION_NOTIFY_COMPLETED,
2203             NULL, NULL,
2204             MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2205             MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2206             MHD_OPTION_END);
2207
2208     GNUNET_assert (hd->daemon != NULL);
2209     hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2210     
2211     GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2212   }
2213
2214   nh = GNUNET_malloc (sizeof (struct NetworkHandleList));
2215   nh->h = h;
2216
2217   GNUNET_CONTAINER_DLL_insert (hd->socket_handles_head,
2218                                hd->socket_handles_tail,
2219                                nh);
2220   
2221   return add_handle_to_mhd (h, hd->daemon);
2222 }
2223
2224
2225
2226 /**
2227  * Read data from incoming connection
2228  *
2229  * @param cls the closure
2230  * @param tc the scheduler context
2231  */
2232 static void
2233 do_read (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2234 {
2235   struct Socks5Request *s5r = cls;
2236   struct socks5_client_hello *c_hello;
2237   struct socks5_server_hello *s_hello;
2238   struct socks5_client_request *c_req;
2239   struct socks5_server_response *s_resp;
2240
2241   int ret;
2242   char domain[256];
2243   uint8_t dom_len;
2244   uint16_t req_port;
2245   struct hostent *phost;
2246   uint32_t remote_ip;
2247   struct sockaddr_in remote_addr;
2248   struct in_addr *r_sin_addr;
2249
2250   struct NetworkHandleList *nh;
2251
2252   s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2253
2254   if ((NULL != tc->write_ready) &&
2255       (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) &&
2256       (s5r->rbuf_len = GNUNET_NETWORK_socket_recv (s5r->sock, s5r->rbuf,
2257                                          sizeof (s5r->rbuf))))
2258   {
2259     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2260                 "Successfully read %d bytes from socket\n",
2261                 s5r->rbuf_len);
2262   }
2263   else
2264   {
2265     if (s5r->rbuf_len != 0)
2266       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
2267     else
2268       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disco!\n");
2269
2270     if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2271       GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2272     if (s5r->wtask != GNUNET_SCHEDULER_NO_TASK)
2273       GNUNET_SCHEDULER_cancel (s5r->wtask);
2274     if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
2275       GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2276     GNUNET_NETWORK_socket_close (s5r->remote_sock);
2277     GNUNET_NETWORK_socket_close (s5r->sock);
2278     GNUNET_free(s5r);
2279     return;
2280   }
2281
2282   if (s5r->state == SOCKS5_INIT)
2283   {
2284     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2285                 "SOCKS5 init\n");
2286     c_hello = (struct socks5_client_hello*)&s5r->rbuf;
2287
2288     GNUNET_assert (c_hello->version == SOCKS_VERSION_5);
2289
2290     s_hello = (struct socks5_server_hello*)&s5r->wbuf;
2291     s5r->wbuf_len = sizeof( struct socks5_server_hello );
2292
2293     s_hello->version = c_hello->version;
2294     s_hello->auth_method = SOCKS_AUTH_NONE;
2295
2296     /* Write response to client */
2297     s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2298                                                 s5r->sock,
2299                                                 &do_write, s5r);
2300
2301     s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2302                                                 s5r->sock,
2303                                                 &do_read, s5r);
2304
2305     s5r->state = SOCKS5_REQUEST;
2306     return;
2307   }
2308
2309   if (s5r->state == SOCKS5_REQUEST)
2310   {
2311     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312                 "Processing SOCKS5 request\n");
2313     c_req = (struct socks5_client_request*)&s5r->rbuf;
2314     s_resp = (struct socks5_server_response*)&s5r->wbuf;
2315     //Only 10byte for ipv4 response!
2316     s5r->wbuf_len = 10;//sizeof (struct socks5_server_response);
2317
2318     GNUNET_assert (c_req->addr_type == 3);
2319
2320     dom_len = *((uint8_t*)(&(c_req->addr_type) + 1));
2321     memset(domain, 0, sizeof(domain));
2322     strncpy(domain, (char*)(&(c_req->addr_type) + 2), dom_len);
2323     req_port = *((uint16_t*)(&(c_req->addr_type) + 2 + dom_len));
2324
2325     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2326                 "Requested connection is %s:%d\n",
2327                 domain,
2328                 ntohs(req_port));
2329
2330     if (is_tld (domain, GNUNET_GNS_TLD) ||
2331         is_tld (domain, GNUNET_GNS_TLD_ZKEY))
2332     {
2333       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2334                   "Requested connection is gnunet tld\n",
2335                   domain);
2336       
2337       ret = MHD_NO;
2338       if (ntohs(req_port) == HTTPS_PORT)
2339       {
2340         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2341                     "Requested connection is HTTPS\n");
2342         ret = add_handle_to_ssl_mhd ( s5r->sock, domain );
2343       }
2344       else if (NULL != httpd)
2345       {
2346         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347                     "Requested connection is HTTP\n");
2348         nh = GNUNET_malloc (sizeof (struct NetworkHandleList));
2349         nh->h = s5r->sock;
2350
2351         GNUNET_CONTAINER_DLL_insert (mhd_httpd_head->socket_handles_head,
2352                                mhd_httpd_head->socket_handles_tail,
2353                                nh);
2354
2355         ret = add_handle_to_mhd ( s5r->sock, httpd );
2356       }
2357
2358       if (ret != MHD_YES)
2359       {
2360         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2361                     _("Failed to start HTTP server\n"));
2362         s_resp->version = 0x05;
2363         s_resp->reply = 0x01;
2364         s5r->cleanup = GNUNET_YES;
2365         s5r->cleanup_sock = GNUNET_YES;
2366         s5r->wtask = 
2367           GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2368                                         s5r->sock,
2369                                         &do_write, s5r);
2370         return;
2371       }
2372       
2373       /* Signal success */
2374       s_resp->version = 0x05;
2375       s_resp->reply = 0x00;
2376       s_resp->reserved = 0x00;
2377       s_resp->addr_type = 0x01;
2378       
2379       s5r->cleanup = GNUNET_YES;
2380       s5r->cleanup_sock = GNUNET_NO;
2381       s5r->wtask =
2382         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2383                                         s5r->sock,
2384                                         &do_write, s5r);
2385       run_httpds ();
2386       return;
2387     }
2388     else
2389     {
2390       phost = (struct hostent*)gethostbyname (domain);
2391       if (phost == NULL)
2392       {
2393         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2394                     "Resolve %s error!\n", domain );
2395         s_resp->version = 0x05;
2396         s_resp->reply = 0x01;
2397         s5r->cleanup = GNUNET_YES;
2398         s5r->cleanup_sock = GNUNET_YES;
2399         s5r->wtask = 
2400           GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2401                                           s5r->sock,
2402                                           &do_write, s5r);
2403         return;
2404       }
2405
2406       s5r->remote_sock = GNUNET_NETWORK_socket_create (AF_INET,
2407                                                        SOCK_STREAM,
2408                                                        0);
2409       r_sin_addr = (struct in_addr*)(phost->h_addr);
2410       remote_ip = r_sin_addr->s_addr;
2411       memset(&remote_addr, 0, sizeof(remote_addr));
2412       remote_addr.sin_family = AF_INET;
2413 #if HAVE_SOCKADDR_IN_SIN_LEN
2414       remote_addr.sin_len = sizeof (remote_addr);
2415 #endif
2416       remote_addr.sin_addr.s_addr = remote_ip;
2417       remote_addr.sin_port = req_port;
2418       
2419       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2420                   "target server: %s:%u\n", inet_ntoa(remote_addr.sin_addr),
2421                   ntohs(req_port));
2422
2423       if ((GNUNET_OK !=
2424           GNUNET_NETWORK_socket_connect ( s5r->remote_sock,
2425                                           (const struct sockaddr*)&remote_addr,
2426                                           sizeof (remote_addr)))
2427           && (errno != EINPROGRESS))
2428       {
2429         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "connect");
2430         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2431                     "socket request error...\n");
2432         s_resp->version = 0x05;
2433         s_resp->reply = 0x01;
2434         s5r->wtask =
2435           GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2436                                           s5r->sock,
2437                                           &do_write, s5r);
2438         //TODO see above
2439         return;
2440       }
2441
2442       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2443                   "new remote connection\n");
2444
2445       s_resp->version = 0x05;
2446       s_resp->reply = 0x00;
2447       s_resp->reserved = 0x00;
2448       s_resp->addr_type = 0x01;
2449
2450       s5r->state = SOCKS5_DATA_TRANSFER;
2451
2452       s5r->wtask =
2453         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2454                                         s5r->sock,
2455                                         &do_write, s5r);
2456       s5r->rtask =
2457         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2458                                        s5r->sock,
2459                                        &do_read, s5r);
2460
2461     }
2462     return;
2463   }
2464
2465   if (s5r->state == SOCKS5_DATA_TRANSFER)
2466   {
2467     if ((s5r->remote_sock == NULL) || (s5r->rbuf_len == 0))
2468     {
2469       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2470                   "Closing connection to client\n");
2471       if (s5r->rtask != GNUNET_SCHEDULER_NO_TASK)
2472         GNUNET_SCHEDULER_cancel (s5r->rtask);
2473       if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
2474         GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2475       if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2476         GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2477       if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2478         GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2479       
2480       if (s5r->remote_sock != NULL)
2481         GNUNET_NETWORK_socket_close (s5r->remote_sock);
2482       GNUNET_NETWORK_socket_close (s5r->sock);
2483       GNUNET_free(s5r);
2484       return;
2485     }
2486
2487     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488                 "forwarding %d bytes from client\n", s5r->rbuf_len);
2489
2490     s5r->fwdwtask =
2491       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2492                                       s5r->remote_sock,
2493                                       &do_write_remote, s5r);
2494
2495     if (s5r->fwdrtask == GNUNET_SCHEDULER_NO_TASK)
2496     {
2497       s5r->fwdrtask =
2498         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2499                                        s5r->remote_sock,
2500                                        &do_read_remote, s5r);
2501     }
2502
2503
2504   }
2505
2506 }
2507
2508
2509 /**
2510  * Accept new incoming connections
2511  *
2512  * @param cls the closure
2513  * @param tc the scheduler context
2514  */
2515 static void
2516 do_accept (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2517 {
2518   struct GNUNET_NETWORK_Handle *s;
2519   struct Socks5Request *s5r;
2520
2521   ltask = GNUNET_SCHEDULER_NO_TASK;
2522   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2523     return;
2524
2525   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2526                                          lsock,
2527                                          &do_accept, NULL);
2528
2529   s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2530
2531   if (NULL == s)
2532   {
2533     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2534     return;
2535   }
2536
2537   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2538               "Got an inbound connection, waiting for data\n");
2539
2540   s5r = GNUNET_malloc (sizeof (struct Socks5Request));
2541   s5r->sock = s;
2542   s5r->state = SOCKS5_INIT;
2543   s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
2544   s5r->fwdwtask = GNUNET_SCHEDULER_NO_TASK;
2545   s5r->fwdrtask = GNUNET_SCHEDULER_NO_TASK;
2546   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2547                                               s5r->sock,
2548                                               &do_read, s5r);
2549 }
2550
2551
2552 /**
2553  * Task run on shutdown
2554  *
2555  * @param cls closure
2556  * @param tc task context
2557  */
2558 static void
2559 do_shutdown (void *cls,
2560              const struct GNUNET_SCHEDULER_TaskContext *tc)
2561 {
2562
2563   struct MhdHttpList *hd;
2564   struct MhdHttpList *tmp_hd;
2565   struct NetworkHandleList *nh;
2566   struct NetworkHandleList *tmp_nh;
2567   struct ProxyCurlTask *ctask;
2568   struct ProxyCurlTask *ctask_tmp;
2569   
2570   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2571               "Shutting down...\n");
2572
2573   gnutls_global_deinit ();
2574
2575   if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
2576   {
2577     GNUNET_SCHEDULER_cancel (curl_download_task);
2578     curl_download_task = GNUNET_SCHEDULER_NO_TASK;
2579   }
2580
2581   for (hd = mhd_httpd_head; hd != NULL; hd = tmp_hd)
2582   {
2583     tmp_hd = hd->next;
2584
2585     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2586                 "Stopping daemon\n");
2587
2588     if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
2589     {
2590       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2591                   "Stopping select task %d\n",
2592                   hd->httpd_task);
2593       GNUNET_SCHEDULER_cancel (hd->httpd_task);
2594       hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2595     }
2596
2597     if (NULL != hd->daemon)
2598     {
2599       MHD_stop_daemon (hd->daemon);
2600       hd->daemon = NULL;
2601     }
2602
2603     for (nh = hd->socket_handles_head; nh != NULL; nh = tmp_nh)
2604     {
2605       tmp_nh = nh->next;
2606
2607       GNUNET_NETWORK_socket_close (nh->h);
2608
2609       GNUNET_free (nh);
2610     }
2611
2612     if (NULL != hd->proxy_cert)
2613     {
2614       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2615                   "Free certificate\n");
2616       GNUNET_free (hd->proxy_cert);
2617     }
2618
2619     GNUNET_free (hd);
2620   }
2621
2622   for (ctask=ctasks_head; ctask != NULL; ctask=ctask_tmp)
2623   {
2624     ctask_tmp = ctask->next;
2625
2626     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2627                 "Cleaning up cURL task\n");
2628
2629     if (ctask->curl != NULL)
2630       curl_easy_cleanup (ctask->curl);
2631     ctask->curl = NULL;
2632     if (NULL != ctask->headers)
2633       curl_slist_free_all (ctask->headers);
2634     if (NULL != ctask->resolver)
2635       curl_slist_free_all (ctask->resolver);
2636
2637     if (NULL != ctask->response)
2638       MHD_destroy_response (ctask->response);
2639
2640
2641     GNUNET_free (ctask);
2642   }
2643   curl_multi_cleanup (curl_multi);
2644
2645   GNUNET_GNS_disconnect (gns_handle);
2646 }
2647
2648
2649 /**
2650  * Compiles a regex for us
2651  *
2652  * @param re ptr to re struct
2653  * @param rt the expression to compile
2654  * @return 0 on success
2655  */
2656 static int
2657 compile_regex (regex_t *re, const char* rt)
2658 {
2659   int status;
2660   char err[1024];
2661
2662   status = regcomp (re, rt, REG_EXTENDED|REG_NEWLINE);
2663   if (status)
2664   {
2665     regerror (status, re, err, 1024);
2666     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2667                 "Regex error compiling '%s': %s\n", rt, err);
2668     return 1;
2669   }
2670   return 0;
2671 }
2672
2673
2674 /**
2675  * Loads the users local zone key
2676  *
2677  * @return GNUNET_YES on success
2678  */
2679 static int
2680 load_local_zone_key (const struct GNUNET_CONFIGURATION_Handle *cfg)
2681 {
2682   char *keyfile;
2683   struct GNUNET_CRYPTO_RsaPrivateKey *key = NULL;
2684   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
2685   struct GNUNET_CRYPTO_ShortHashCode *zone = NULL;
2686   struct GNUNET_CRYPTO_ShortHashAsciiEncoded zonename;
2687
2688   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
2689                                                             "ZONEKEY", &keyfile))
2690   {
2691     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2692                 "Unable to load zone key config value!\n");
2693     return GNUNET_NO;
2694   }
2695
2696   if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
2697   {
2698     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2699                 "Unable to load zone key %s!\n", keyfile);
2700     GNUNET_free(keyfile);
2701     return GNUNET_NO;
2702   }
2703
2704   key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2705   GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
2706   GNUNET_CRYPTO_short_hash(&pkey,
2707                            sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2708                            &local_gns_zone);
2709   zone = &local_gns_zone;
2710   GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
2711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2712               "Using zone: %s!\n", &zonename);
2713   GNUNET_CRYPTO_rsa_key_free(key);
2714   GNUNET_free(keyfile);
2715   
2716   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
2717                                                    "PRIVATE_ZONEKEY", &keyfile))
2718   {
2719     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2720                 "Unable to load private zone key config value!\n");
2721     return GNUNET_NO;
2722   }
2723
2724   if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
2725   {
2726     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2727                 "Unable to load private zone key %s!\n", keyfile);
2728     GNUNET_free(keyfile);
2729     return GNUNET_NO;
2730   }
2731
2732   key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2733   GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
2734   GNUNET_CRYPTO_short_hash(&pkey,
2735                            sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2736                            &local_private_zone);
2737   GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
2738   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2739               "Using private zone: %s!\n", &zonename);
2740   GNUNET_CRYPTO_rsa_key_free(key);
2741   GNUNET_free(keyfile);
2742
2743   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
2744                                                    "SHORTEN_ZONEKEY", &keyfile))
2745   {
2746     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2747                 "Unable to load shorten zone key config value!\n");
2748     return GNUNET_NO;
2749   }
2750
2751   if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
2752   {
2753     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2754                 "Unable to load shorten zone key %s!\n", keyfile);
2755     GNUNET_free(keyfile);
2756     return GNUNET_NO;
2757   }
2758
2759   key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2760   GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
2761   GNUNET_CRYPTO_short_hash(&pkey,
2762                            sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2763                            &local_shorten_zone);
2764   GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
2765   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2766               "Using shorten zone: %s!\n", &zonename);
2767   GNUNET_CRYPTO_rsa_key_free(key);
2768   GNUNET_free(keyfile);
2769
2770   return GNUNET_YES;
2771 }
2772
2773 /**
2774  * Main function that will be run
2775  *
2776  * @param cls closure
2777  * @param args remaining command-line arguments
2778  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2779  * @param cfg configuration
2780  */
2781 static void
2782 run (void *cls, char *const *args, const char *cfgfile,
2783      const struct GNUNET_CONFIGURATION_Handle *cfg)
2784 {
2785   struct sockaddr_in sa;
2786   struct MhdHttpList *hd;
2787   struct sockaddr_un mhd_unix_sock_addr;
2788   size_t len;
2789   char* proxy_sockfile;
2790   char* cafile_cfg = NULL;
2791   char* cafile;
2792
2793   curl_multi = curl_multi_init ();
2794
2795   if (NULL == curl_multi)
2796   {
2797     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2798                 "Failed to create cURL multo handle!\n");
2799     return;
2800   }
2801   
2802   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2803               "Loading CA\n");
2804   cafile = cafile_opt;
2805   if (NULL == cafile)
2806   {
2807     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
2808                                                           "PROXY_CACERT",
2809                                                           &cafile_cfg))
2810     {
2811       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2812                   "Unable to load proxy CA config value!\n");
2813       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2814                   "No proxy CA provided!\n");
2815       return;
2816     }
2817     cafile = cafile_cfg;
2818   }
2819   
2820   gnutls_global_init ();
2821   gnutls_x509_crt_init (&proxy_ca.cert);
2822   gnutls_x509_privkey_init (&proxy_ca.key);
2823   
2824   if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
2825        (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
2826   {
2827     // FIXME: release resources...
2828     return;
2829   }
2830
2831   GNUNET_free_non_null (cafile_cfg);
2832   
2833   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2834               "Loading Template\n");
2835   
2836   compile_regex (&re_dotplus, (char*) RE_A_HREF);
2837
2838   gns_handle = GNUNET_GNS_connect (cfg);
2839
2840   if (GNUNET_NO == load_local_zone_key (cfg))
2841   {
2842     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2843                 "Unable to load zone!\n");
2844     return;
2845   }
2846
2847   if (NULL == gns_handle)
2848   {
2849     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2850                 "Unable to connect to GNS!\n");
2851     return;
2852   }
2853
2854   memset (&sa, 0, sizeof (sa));
2855   sa.sin_family = AF_INET;
2856   sa.sin_port = htons (port);
2857 #if HAVE_SOCKADDR_IN_SIN_LEN
2858   sa.sin_len = sizeof (sa);
2859 #endif
2860
2861   lsock = GNUNET_NETWORK_socket_create (AF_INET,
2862                                         SOCK_STREAM,
2863                                         0);
2864
2865   if ((NULL == lsock) ||
2866       (GNUNET_OK !=
2867        GNUNET_NETWORK_socket_bind (lsock, (const struct sockaddr *) &sa,
2868                                    sizeof (sa))))
2869   {
2870     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2871                 "Failed to create listen socket bound to `%s'",
2872                 GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)));
2873     if (NULL != lsock)
2874       GNUNET_NETWORK_socket_close (lsock);
2875     return;
2876   }
2877
2878   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock, 5))
2879   {
2880     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2881                 "Failed to listen on socket bound to `%s'",
2882                 GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)));
2883     return;
2884   }
2885
2886   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2887                                          lsock, &do_accept, NULL);
2888
2889   ctasks_head = NULL;
2890   ctasks_tail = NULL;
2891
2892   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
2893   {
2894     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2895                 "cURL global init failed!\n");
2896     return;
2897   }
2898
2899   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2900               "Proxy listens on port %u\n",
2901               port);
2902
2903   mhd_httpd_head = NULL;
2904   mhd_httpd_tail = NULL;
2905   total_mhd_connections = 0;
2906
2907   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
2908                                                             "PROXY_UNIXPATH",
2909                                                             &proxy_sockfile))
2910   {
2911     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2912                 "Specify PROXY_UNIXPATH in gns-proxy config section!\n");
2913     return;
2914   }
2915   
2916   mhd_unix_socket = GNUNET_NETWORK_socket_create (AF_UNIX,
2917                                                 SOCK_STREAM,
2918                                                 0);
2919
2920   if (NULL == mhd_unix_socket)
2921   {
2922     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2923                 "Unable to create unix domain socket!\n");
2924     return;
2925   }
2926
2927   mhd_unix_sock_addr.sun_family = AF_UNIX;
2928   strcpy (mhd_unix_sock_addr.sun_path, proxy_sockfile);
2929
2930 #if LINUX
2931   mhd_unix_sock_addr.sun_path[0] = '\0';
2932 #endif
2933 #if HAVE_SOCKADDR_IN_SIN_LEN
2934   mhd_unix_sock_addr.sun_len = (u_char) sizeof (struct sockaddr_un);
2935 #endif
2936
2937   len = strlen (proxy_sockfile) + sizeof(AF_UNIX);
2938
2939   GNUNET_free (proxy_sockfile);
2940
2941   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (mhd_unix_socket,
2942                                (struct sockaddr*)&mhd_unix_sock_addr,
2943                                len))
2944   {
2945     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2946                 "Unable to bind unix domain socket!\n");
2947     return;
2948   }
2949
2950   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (mhd_unix_socket,
2951                                                  1))
2952   {
2953     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2954                 "Unable to listen on unix domain socket!\n");
2955     return;
2956   }
2957
2958   hd = GNUNET_malloc (sizeof (struct MhdHttpList));
2959   hd->is_ssl = GNUNET_NO;
2960   strcpy (hd->domain, "");
2961   httpd = MHD_start_daemon (MHD_USE_DEBUG, 4444, //Dummy port
2962             &accept_cb, NULL,
2963             &create_response, hd,
2964             MHD_OPTION_LISTEN_SOCKET, GNUNET_NETWORK_get_fd (mhd_unix_socket),
2965             MHD_OPTION_CONNECTION_LIMIT, MHD_MAX_CONNECTIONS,
2966             MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2967             MHD_OPTION_NOTIFY_COMPLETED,
2968             NULL, NULL,
2969             MHD_OPTION_END);
2970
2971   GNUNET_assert (httpd != NULL);
2972   hd->daemon = httpd;
2973   hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2974
2975   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2976
2977   run_httpds ();
2978
2979   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2980                                 &do_shutdown, NULL);
2981
2982 }
2983
2984
2985 /**
2986  * The main function for gnunet-gns-proxy.
2987  *
2988  * @param argc number of arguments from the command line
2989  * @param argv command line arguments
2990  * @return 0 ok, 1 on error
2991  */
2992 int
2993 main (int argc, char *const *argv)
2994 {
2995   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2996     {'p', "port", NULL,
2997      gettext_noop ("listen on specified port"), 1,
2998      &GNUNET_GETOPT_set_string, &port},
2999     {'a', "authority", NULL,
3000       gettext_noop ("pem file to use as CA"), 1,
3001       &GNUNET_GETOPT_set_string, &cafile_opt},
3002     GNUNET_GETOPT_OPTION_END
3003   };
3004
3005   int ret;
3006
3007   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3008     return 2;
3009
3010
3011   GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3012   ret =
3013       (GNUNET_OK ==
3014        GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3015                            _("GNUnet GNS proxy"),
3016                            options,
3017                            &run, NULL)) ? 0 : 1;
3018   GNUNET_free_non_null ((char*)argv);
3019
3020   return ret;
3021 }
3022
3023
3024
3025