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