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