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