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