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