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