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