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