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