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