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