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