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