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