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