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