02f7e0e9bee1de1154808ad13ba75362f4fb3792
[oweals/gnunet.git] / src / gns / gnunet-gns-proxy.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 #include "platform.h"
22 #include <gnunet_util_lib.h>
23 #include <gnunet_gns_service.h>
24 #include <microhttpd.h>
25 #include <curl/curl.h>
26 #include <regex.h>
27 #include "gns_proxy_proto.h"
28 #include "gns.h"
29
30 /** SSL **/
31 #include <gnutls/gnutls.h>
32 #include <gnutls/x509.h>
33 #include <gnutls/abstract.h>
34 #include <gnutls/crypto.h>
35 #include <time.h>
36
37 #define GNUNET_GNS_PROXY_PORT 7777
38 #define MHD_MAX_CONNECTIONS 300
39 #define MAX_HTTP_URI_LENGTH 2048
40 #define POSTBUFFERSIZE 4096
41
42 /* MHD/cURL defines */
43 #define BUF_WAIT_FOR_CURL 0
44 #define BUF_WAIT_FOR_MHD 1
45 #define BUF_WAIT_FOR_PP 2
46 #define HTML_HDR_CONTENT "Content-Type: text/html"
47
48 /* buffer padding for proper RE matching */
49 #define CURL_BUF_PADDING 1000
50
51 /* regexp */
52 //#define RE_DOTPLUS "<a href=\"http://(([A-Za-z]+[.])+)([+])"
53 #define RE_A_HREF  "href=\"https?://(([A-Za-z0-9]+[.])+)([+]|[a-z]+)"
54 #define RE_N_MATCHES 4
55
56 /* The usual suspects */
57 #define HTTP_PORT 80
58 #define HTTPS_PORT 443
59
60
61 /**
62  * A structure for CA cert/key
63  */
64 struct ProxyCA
65 {
66   /* The certificate */
67   gnutls_x509_crt_t cert;
68
69   /* The private key */
70   gnutls_x509_privkey_t key;
71 };
72
73 #define MAX_PEM_SIZE (10 * 1024)
74
75 /**
76  * Structure for GNS certificates
77  */
78 struct ProxyGNSCertificate
79 {
80   /* The certificate as PEM */
81   char cert[MAX_PEM_SIZE];
82
83   /* The private key as PEM */
84   char key[MAX_PEM_SIZE];
85 };
86
87
88 /**
89  * A structure for socks requests
90  */
91 struct Socks5Request
92 {
93   /* The client socket */
94   struct GNUNET_NETWORK_Handle *sock;
95
96   /* The server socket */
97   struct GNUNET_NETWORK_Handle *remote_sock;
98   
99   /* The socks state */
100   int state;
101   
102   /* Client socket read task */
103   GNUNET_SCHEDULER_TaskIdentifier rtask;
104
105   /* Server socket read task */
106   GNUNET_SCHEDULER_TaskIdentifier fwdrtask;
107
108   /* Client socket write task */
109   GNUNET_SCHEDULER_TaskIdentifier wtask;
110
111   /* Server socket write task */
112   GNUNET_SCHEDULER_TaskIdentifier fwdwtask;
113
114   /* Read buffer */
115   char rbuf[2048];
116
117   /* Write buffer */
118   char wbuf[2048];
119
120   /* Length of data in read buffer */
121   unsigned int rbuf_len;
122
123   /* Length of data in write buffer */
124   unsigned int wbuf_len;
125
126   /* This handle is scheduled for cleanup? */
127   int cleanup;
128
129   /* Shall we close the client socket on cleanup? */
130   int cleanup_sock;
131 };
132
133 /**
134  * DLL for Network Handles
135  */
136 struct NetworkHandleList
137 {
138   /*DLL*/
139   struct NetworkHandleList *next;
140
141   /*DLL*/
142   struct NetworkHandleList *prev;
143
144   /* The handle */
145   struct GNUNET_NETWORK_Handle *h;
146 };
147
148 /**
149  * A structure for all running Httpds
150  */
151 struct MhdHttpList
152 {
153   /* DLL for httpds */
154   struct MhdHttpList *prev;
155
156   /* DLL for httpds */
157   struct MhdHttpList *next;
158
159   /* is this an ssl daemon? */
160   int is_ssl;
161
162   /* the domain name to server (only important for SSL) */
163   char domain[256];
164
165   /* The daemon handle */
166   struct MHD_Daemon *daemon;
167
168   /* Optional proxy certificate used */
169   struct ProxyGNSCertificate *proxy_cert;
170
171   /* The task ID */
172   GNUNET_SCHEDULER_TaskIdentifier httpd_task;
173
174   /* Handles associated with this daemon */
175   struct NetworkHandleList *socket_handles_head;
176   
177   /* Handles associated with this daemon */
178   struct NetworkHandleList *socket_handles_tail;
179 };
180
181 /**
182  * A structure for MHD<->cURL streams
183  */
184 struct ProxyCurlTask
185 {
186   /* DLL for tasks */
187   struct ProxyCurlTask *prev;
188
189   /* DLL for tasks */
190   struct ProxyCurlTask *next;
191
192   /* Handle to cURL */
193   CURL *curl;
194
195   /* Optional header replacements for curl (LEHO) */
196   struct curl_slist *headers;
197
198   /* Optional resolver replacements for curl (LEHO) */
199   struct curl_slist *resolver;
200
201   /* curl response code */
202   long curl_response_code;
203
204   /* The URL to fetch */
205   char url[MAX_HTTP_URI_LENGTH];
206
207   /* The cURL write buffer / MHD read buffer */
208   char buffer[CURL_MAX_WRITE_SIZE + CURL_BUF_PADDING];
209
210   /* Read pos of the data in the buffer */
211   char *buffer_read_ptr;
212
213   /* Write pos in the buffer */
214   char *buffer_write_ptr;
215
216   /* The buffer status (BUF_WAIT_FOR_CURL or BUF_WAIT_FOR_MHD) */
217   int buf_status;
218
219   /* Number of bytes in buffer */
220   unsigned int bytes_in_buffer;
221
222   /* Indicates wheather the download is in progress */
223   int download_in_progress;
224
225   /* Indicates wheather the download was successful */
226   int download_is_finished;
227
228   /* Indicates wheather the download failed */
229   int download_error;
230
231   /* Indicates wheather we need to parse HTML */
232   int parse_content;
233
234   /* Indicates wheather we are postprocessing the HTML right now */
235   int is_postprocessing;
236
237   /* Indicates wheather postprocessing has finished */
238   int pp_finished;
239
240   /* PP task */
241   GNUNET_SCHEDULER_TaskIdentifier pp_task;
242
243   /* PP match list */
244   struct ProxyREMatch *pp_match_head;
245
246   /* PP match list */
247   struct ProxyREMatch *pp_match_tail;
248
249   /* The authority of the corresponding host (site of origin) */
250   char authority[256];
251
252   /* The hostname (Host header field) */
253   char host[256];
254
255   /* The LEgacy HOstname (can be empty) */
256   char leho[256];
257
258   /* The associated daemon list entry */
259   struct MhdHttpList *mhd;
260
261   /* The associated response */
262   struct MHD_Response *response;
263
264   /* Cookies to set */
265   struct ProxySetCookieHeader *set_cookies_head;
266
267   /* Cookies to set */
268   struct ProxySetCookieHeader *set_cookies_tail;
269
270   /* connection status */
271   int ready_to_queue;
272   
273   /* are we done */
274   int fin;
275
276   /* connection */
277   struct MHD_Connection *connection;
278
279   /*put*/
280   size_t put_read_offset;
281   size_t put_read_size;
282
283   /*post*/
284   struct MHD_PostProcessor *post_handler;
285
286   /* post data */
287   struct ProxyPostData *post_data_head;
288   struct ProxyPostData *post_data_tail;
289
290   int post_done;
291
292   /* the type of POST encoding */
293   char* post_type;
294   
295 };
296
297 /**
298  * Struct for RE matches in postprocessing of HTML
299  */
300 struct ProxyREMatch
301 {
302   /* DLL */
303   struct ProxyREMatch *next;
304
305   /* DLL */
306   struct ProxyREMatch *prev;
307
308   /* hostname found */
309   char hostname[255];
310
311   /* PP result */
312   char result[255];
313
314   /* shorten task */
315   struct GNUNET_GNS_ShortenRequest *shorten_task;
316
317   /* are we done */
318   int done;
319
320   /* start of match in buffer */
321   char* start;
322
323   /* end of match in buffer */
324   char* end;
325
326   /* associated proxycurltask */
327   struct ProxyCurlTask *ctask;
328 };
329
330 /**
331  * Struct for set-cookies
332  */
333 struct ProxySetCookieHeader
334 {
335   /* DLL */
336   struct ProxySetCookieHeader *next;
337
338   /* DLL */
339   struct ProxySetCookieHeader *prev;
340
341   /* the cookie */
342   char *cookie;
343 };
344
345 /**
346  * Post data structure
347  */
348 struct ProxyPostData
349 {
350   /* DLL */
351   struct ProxyPostData *next;
352
353   /* DLL */
354   struct ProxyPostData *prev;
355   
356   /* value */
357   char *value;
358
359   /* to copy */
360   size_t bytes_left;
361
362   /* size */
363   size_t total_bytes;
364 };
365
366
367 /* The port the proxy is running on (default 7777) */
368 static unsigned long port = GNUNET_GNS_PROXY_PORT;
369
370 /* The CA file (pem) to use for the proxy CA */
371 static char* cafile_opt;
372
373 /* The listen socket of the proxy */
374 static struct GNUNET_NETWORK_Handle *lsock;
375
376 /* The listen task ID */
377 GNUNET_SCHEDULER_TaskIdentifier ltask;
378
379 /* The cURL download task */
380 GNUNET_SCHEDULER_TaskIdentifier curl_download_task;
381
382 /* The non SSL httpd daemon handle */
383 static struct MHD_Daemon *httpd;
384
385 /* Number of current mhd connections */
386 static unsigned int total_mhd_connections;
387
388 /* The cURL multi handle */
389 static CURLM *curl_multi;
390
391 /* Handle to the GNS service */
392 static struct GNUNET_GNS_Handle *gns_handle;
393
394 /* DLL for ProxyCurlTasks */
395 static struct ProxyCurlTask *ctasks_head;
396
397 /* DLL for ProxyCurlTasks */
398 static struct ProxyCurlTask *ctasks_tail;
399
400 /* DLL for http daemons */
401 static struct MhdHttpList *mhd_httpd_head;
402
403 /* DLL for http daemons */
404 static struct MhdHttpList *mhd_httpd_tail;
405
406 /* Handle to the regex for dotplus (.+) replacement in HTML */
407 static regex_t re_dotplus;
408
409 /* The users local GNS zone hash */
410 static struct GNUNET_CRYPTO_ShortHashCode local_gns_zone;
411
412 /* The users local private zone */
413 static struct GNUNET_CRYPTO_ShortHashCode local_private_zone;
414
415 /* The users local shorten zone */
416 static struct GNUNET_CRYPTO_ShortHashCode local_shorten_zone;
417
418 /* The CA for SSL certificate generation */
419 static struct ProxyCA proxy_ca;
420
421 /* UNIX domain socket for mhd */
422 struct GNUNET_NETWORK_Handle *mhd_unix_socket;
423
424 /* Shorten zone private key */
425 struct GNUNET_CRYPTO_RsaPrivateKey *shorten_zonekey;
426
427 /**
428  * Checks if name is in tld
429  *
430  * @param name the name to check
431  * @param tld the TLD to check for
432  * @return GNUNET_YES or GNUNET_NO
433  */
434 int
435 is_tld(const char* name, const char* tld)
436 {
437   size_t offset;
438
439   if (strlen(name) <= strlen(tld))  
440     return GNUNET_NO;  
441
442   offset = strlen(name) - strlen(tld);
443   if (0 != strcmp (name+offset, tld))
444   {
445     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
446                "%s is not in .%s TLD\n", name, tld);
447     return GNUNET_NO;
448   }
449
450   return GNUNET_YES;
451 }
452
453 /**
454  * convert integer to string representation
455  *
456  * @param i integer
457  * @return the character
458  */
459 char i_to_hexchar (char i)
460 {
461   static char hexmap[] = "0123456789abcdef";
462   GNUNET_assert (sizeof (hexmap) > (i & 15));
463   return hexmap[i & 15];
464 }
465
466 /**
467  * Escape giben 0-terminated string
468  *
469  * @param to_esc string to escapse
470  * @return allocated new escaped string (MUST free!)
471  */
472 static char*
473 escape_to_urlenc (const char *to_esc)
474 {
475   char *pos = (char*)to_esc;
476   char *res = GNUNET_malloc (strlen (to_esc) * 3 + 1);
477   char *rpos = res;
478
479   while ('\0' != *pos)
480   {
481     if (isalnum (*pos) ||
482         ('-' == *pos) || ('_' == *pos) ||
483         ('.' == *pos) || ('~' == *pos))
484         *rpos++ = *pos;
485     else if (' ' == *pos)
486       *rpos++ = '+';
487     else
488     {
489       *rpos++ = '%';
490       *rpos++ = i_to_hexchar (*pos >> 4);
491       *rpos++ = i_to_hexchar (*pos >> 15);
492     }
493     pos++;
494   }
495   *rpos = '\0';
496   return res;
497 }
498
499 static int
500 con_post_data_iter (void *cls,
501                   enum MHD_ValueKind kind,
502                   const char *key,
503                   const char *filename,
504                   const char *content_type,
505                   const char *transfer_encoding,
506                   const char *data,
507                   uint64_t off,
508                   size_t size)
509 {
510   struct ProxyCurlTask* ctask = cls;
511   struct ProxyPostData* pdata;
512   char* enc;
513   
514   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
515               "Got POST data: '%s : %s' at offset %llu size %lld\n",
516               key, data, off, size);
517
518   if (0 != strcasecmp (MHD_HTTP_POST_ENCODING_FORM_URLENCODED,
519                        ctask->post_type))
520   {
521     return MHD_NO;
522   }
523
524   if (0 == off)
525   {
526     /* a key */
527     pdata = GNUNET_malloc (sizeof (struct ProxyPostData));
528     enc = escape_to_urlenc (key);
529     pdata->value = GNUNET_malloc (strlen (enc) + 3);
530     if (NULL != ctask->post_data_head)
531     {
532       pdata->value[0] = '&';
533       memcpy (pdata->value+1, enc, strlen (enc));
534     }
535     else
536       memcpy (pdata->value, enc, strlen (enc));
537     pdata->value[strlen (pdata->value)] = '=';
538     pdata->bytes_left = strlen (pdata->value);
539     pdata->total_bytes = pdata->bytes_left;
540     GNUNET_free (enc);
541
542     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
543                 "Escaped POST key: '%s'\n",
544                 pdata->value);
545
546     GNUNET_CONTAINER_DLL_insert_tail (ctask->post_data_head,
547                                       ctask->post_data_tail,
548                                       pdata);
549   }
550
551   /* a value */
552   pdata = GNUNET_malloc (sizeof (struct ProxyPostData));
553   enc = escape_to_urlenc (data);
554   pdata->value = GNUNET_malloc (strlen (enc) + 1);
555   memcpy (pdata->value, enc, strlen (enc));
556   pdata->bytes_left = strlen (pdata->value);
557   pdata->total_bytes = pdata->bytes_left;
558   GNUNET_free (enc);
559
560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
561               "Escaped POST value: '%s'\n",
562               pdata->value);
563
564   GNUNET_CONTAINER_DLL_insert_tail (ctask->post_data_head,
565                                     ctask->post_data_tail,
566                                     pdata);
567   return MHD_YES;
568 }
569
570
571 static int
572 get_uri_val_iter (void *cls,
573                   enum MHD_ValueKind kind,
574                   const char *key,
575                   const char *value)
576 {
577   char* buf = cls;
578   
579   if (strlen (buf) + strlen (value) + 3 > MAX_HTTP_URI_LENGTH)
580     return MHD_NO;
581   sprintf (buf+strlen (buf), "?%s=%s", key, value);
582
583   return MHD_YES;
584 }
585
586 /**
587  * Read HTTP request header field 'Host'
588  *
589  * @param cls buffer to write to
590  * @param kind value kind
591  * @param key field key
592  * @param value field value
593  * @return MHD_NO when Host found
594  */
595 static int
596 con_val_iter (void *cls,
597               enum MHD_ValueKind kind,
598               const char *key,
599               const char *value)
600 {
601   struct ProxyCurlTask *ctask = cls;
602   char* buf = ctask->host;
603   char* cstr;
604   const char* hdr_val;
605
606   if (0 == strcmp ("Host", key))
607   {
608     strcpy (buf, value);
609     return MHD_YES;
610   }
611
612   if (0 == strcmp ("Accept-Encoding", key))
613     hdr_val = "";
614   else
615     hdr_val = value;
616
617   if (0 == strcmp (MHD_HTTP_HEADER_CONTENT_TYPE,
618                    key))
619   {
620     if (0 == strcmp (value,
621                      MHD_HTTP_POST_ENCODING_FORM_URLENCODED))
622       ctask->post_type = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
623     else if (0 == strcmp (value,
624                           MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA))
625       ctask->post_type = MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA;
626     else
627       ctask->post_type = NULL;
628
629   }
630
631   cstr = GNUNET_malloc (strlen (key) + strlen (hdr_val) + 3);
632   GNUNET_snprintf (cstr, strlen (key) + strlen (hdr_val) + 3,
633                    "%s: %s", key, hdr_val);
634
635   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
636               "Client Header: %s\n", cstr);
637
638   ctask->headers = curl_slist_append (ctask->headers, cstr);
639   GNUNET_free (cstr);
640
641   return MHD_YES;
642 }
643
644
645 /**
646  * Callback for MHD response
647  *
648  * @param cls closure
649  * @param pos in buffer
650  * @param buf buffer
651  * @param max space in buffer
652  * @return number of bytes written
653  */
654 static ssize_t
655 mhd_content_cb (void *cls,
656                 uint64_t pos,
657                 char* buf,
658                 size_t max);
659
660 /**
661  * Check HTTP response header for mime
662  *
663  * @param buffer curl buffer
664  * @param size curl blocksize
665  * @param nmemb curl blocknumber
666  * @param cls handle
667  * @return size of read bytes
668  */
669 static size_t
670 curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
671 {
672   size_t bytes = size * nmemb;
673   struct ProxyCurlTask *ctask = cls;
674   int html_mime_len = strlen (HTML_HDR_CONTENT);
675   int cookie_hdr_len = strlen (MHD_HTTP_HEADER_SET_COOKIE);
676   char hdr_mime[html_mime_len+1];
677   char hdr_generic[bytes+1];
678   char new_cookie_hdr[bytes+strlen (ctask->leho)+1];
679   char new_location[MAX_HTTP_URI_LENGTH+500];
680   char real_host[264];
681   char leho_host[264];
682   char* ndup;
683   char* tok;
684   char* cookie_domain;
685   char* hdr_type;
686   char* hdr_val;
687   int delta_cdomain;
688   size_t offset = 0;
689   
690   if (NULL == ctask->response)
691   {
692     /* FIXME: get total size from curl (if available) */
693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
694                 "Creating response for %s\n", ctask->url);
695     ctask->response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
696                                                          sizeof (ctask->buffer),
697                                                          &mhd_content_cb,
698                                                          ctask,
699                                                          NULL);
700     ctask->ready_to_queue = GNUNET_YES;
701     
702   }
703   
704   if (html_mime_len <= bytes)
705   {
706     memcpy (hdr_mime, buffer, html_mime_len);
707     hdr_mime[html_mime_len] = '\0';
708
709     if (0 == strcmp (hdr_mime, HTML_HDR_CONTENT))
710     {
711       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
712                   "Got HTML HTTP response header\n");
713       ctask->parse_content = GNUNET_YES;
714     }
715   }
716
717   if (cookie_hdr_len > bytes)
718     return bytes;
719
720   memcpy (hdr_generic, buffer, bytes);
721   hdr_generic[bytes] = '\0';
722   /* remove crlf */
723   if ('\n' == hdr_generic[bytes-1])
724     hdr_generic[bytes-1] = '\0';
725
726   if (hdr_generic[bytes-2] == '\r')
727     hdr_generic[bytes-2] = '\0';
728   
729   if (0 == memcmp (hdr_generic,
730                    MHD_HTTP_HEADER_SET_COOKIE,
731                    cookie_hdr_len))
732   {
733     ndup = GNUNET_strdup (hdr_generic+cookie_hdr_len+1);
734     memset (new_cookie_hdr, 0, sizeof (new_cookie_hdr));
735     tok = strtok (ndup, ";");
736
737     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
738                 "Looking for cookie in : %s\n", hdr_generic);
739     
740     for (; tok != NULL; tok = strtok (NULL, ";"))
741     {
742       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
743                   "Got Cookie token: %s\n", tok);
744       //memcpy (new_cookie_hdr+offset, tok, strlen (tok));
745       if (0 == memcmp (tok, " domain", strlen (" domain")))
746       {
747         cookie_domain = tok + strlen (" domain") + 1;
748
749         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
750                     "Got Set-Cookie Domain: %s\n", cookie_domain);
751
752         if (strlen (cookie_domain) < strlen (ctask->leho))
753         {
754           delta_cdomain = strlen (ctask->leho) - strlen (cookie_domain);
755           if (0 == strcmp (cookie_domain, ctask->leho + (delta_cdomain)))
756           {
757             GNUNET_snprintf (new_cookie_hdr+offset,
758                              sizeof (new_cookie_hdr),
759                              " domain=%s", ctask->authority);
760             offset += strlen (" domain=") + strlen (ctask->authority);
761             new_cookie_hdr[offset] = ';';
762             offset++;
763             continue;
764           }
765         }
766         else if (strlen (cookie_domain) == strlen (ctask->leho))
767         {
768           if (0 == strcmp (cookie_domain, ctask->leho))
769           {
770             GNUNET_snprintf (new_cookie_hdr+offset,
771                              sizeof (new_cookie_hdr),
772                              " domain=%s", ctask->host);
773             offset += strlen (" domain=") + strlen (ctask->host);
774             new_cookie_hdr[offset] = ';';
775             offset++;
776             continue;
777           }
778         }
779         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
780                     "Cookie domain invalid\n");
781
782         
783       }
784       memcpy (new_cookie_hdr+offset, tok, strlen (tok));
785       offset += strlen (tok);
786       new_cookie_hdr[offset] = ';';
787       offset++;
788     }
789     
790     GNUNET_free (ndup);
791
792     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
793                 "Got Set-Cookie HTTP header %s\n", new_cookie_hdr);
794
795     if (GNUNET_NO == MHD_add_response_header (ctask->response,
796                                               MHD_HTTP_HEADER_SET_COOKIE,
797                                               new_cookie_hdr))
798     {
799       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
800                   "MHD: Error adding set-cookie header field %s\n",
801                   hdr_generic+cookie_hdr_len+1);
802     }
803     return bytes;
804   }
805
806   ndup = GNUNET_strdup (hdr_generic);
807   hdr_type = strtok (ndup, ":");
808
809   if (NULL == hdr_type)
810   {
811     GNUNET_free (ndup);
812     return bytes;
813   }
814
815   hdr_val = strtok (NULL, "");
816
817   if (NULL == hdr_val)
818   {
819     GNUNET_free (ndup);
820     return bytes;
821   }
822
823   hdr_val++;
824
825   if (0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, hdr_type))
826   {
827     if (ctask->mhd->is_ssl)
828     {
829       sprintf (leho_host, "https://%s", ctask->leho);
830       sprintf (real_host, "https://%s", ctask->host);
831     }
832     else
833     {
834       sprintf (leho_host, "http://%s", ctask->leho);
835       sprintf (real_host, "http://%s", ctask->host);
836     }
837
838     if (0 == memcmp (leho_host, hdr_val, strlen (leho_host)))
839     {
840       sprintf (new_location, "%s%s", real_host, hdr_val+strlen (leho_host));
841       hdr_val = new_location;
842     }
843   }
844
845   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
846               "Trying to set %s: %s\n",
847               hdr_type,
848               hdr_val);
849   if (GNUNET_NO == MHD_add_response_header (ctask->response,
850                                             hdr_type,
851                                             hdr_val))
852   {
853     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
854                 "MHD: Error adding %s header field %s\n",
855                 hdr_type,
856                 hdr_val);
857   }
858   GNUNET_free (ndup);
859   return bytes;
860 }
861
862 /**
863  * schedule mhd
864  *
865  * @param hd a http daemon list entry
866  */
867 static void
868 run_httpd (struct MhdHttpList *hd);
869
870
871 /**
872  * schedule all mhds
873  *
874  */
875 static void
876 run_httpds (void);
877
878 /**
879  * Task run whenever HTTP server operations are pending.
880  *
881  * @param cls unused
882  * @param tc sched context
883  */
884 static void
885 do_httpd (void *cls,
886           const struct GNUNET_SCHEDULER_TaskContext *tc);
887
888 static void
889 run_mhd_now (struct MhdHttpList *hd)
890 {
891   if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
892   {
893     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
894                 "MHD: killing old task\n");
895     GNUNET_SCHEDULER_cancel (hd->httpd_task);
896   }
897   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898               "MHD: Scheduling MHD now\n");
899   hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd, hd);
900 }
901
902 /**
903  * Ask cURL for the select sets and schedule download
904  */
905 static void
906 curl_download_prepare ();
907
908 /**
909  * Callback to free content
910  *
911  * @param cls content to free
912  * @param tc task context
913  */
914 static void
915 mhd_content_free (void *cls,
916                   const struct GNUNET_SCHEDULER_TaskContext *tc)
917 {
918   struct ProxyCurlTask *ctask = cls;
919   GNUNET_assert (NULL == ctask->pp_match_head);
920
921   if (NULL != ctask->headers)
922     curl_slist_free_all (ctask->headers);
923
924   if (NULL != ctask->headers)
925     curl_slist_free_all (ctask->resolver);
926
927   if (NULL != ctask->response)
928     MHD_destroy_response (ctask->response);
929
930   if (NULL != ctask->post_handler)
931     MHD_destroy_post_processor (ctask->post_handler);
932
933
934   GNUNET_free (ctask);
935 }
936
937
938 /**
939  * Callback for MHD response
940  *
941  * @param cls closure
942  * @param pos in buffer
943  * @param buf buffer
944  * @param max space in buffer
945  * @return number of bytes written
946  */
947 static ssize_t
948 mhd_content_cb (void *cls,
949                 uint64_t pos,
950                 char* buf,
951                 size_t max)
952 {
953   struct ProxyCurlTask *ctask = cls;
954   struct ProxyREMatch *re_match = ctask->pp_match_head;
955   ssize_t copied = 0;
956   long long int bytes_to_copy = ctask->buffer_write_ptr - ctask->buffer_read_ptr;
957
958   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
959               "MHD: content cb for %s. To copy: %lld\n",
960               ctask->url, bytes_to_copy);
961   GNUNET_assert (bytes_to_copy >= 0);
962
963   if ((GNUNET_YES == ctask->download_is_finished) &&
964       (GNUNET_NO == ctask->download_error) &&
965       (0 == bytes_to_copy)) /* &&
966       (BUF_WAIT_FOR_CURL == ctask->buf_status))*/
967   {
968     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
969                 "MHD: sending response for %s\n", ctask->url);
970     ctask->download_in_progress = GNUNET_NO;
971     run_mhd_now (ctask->mhd);
972     GNUNET_SCHEDULER_add_now (&mhd_content_free, ctask);
973     total_mhd_connections--;
974     return MHD_CONTENT_READER_END_OF_STREAM;
975   }
976   
977   if ((GNUNET_YES == ctask->download_error) &&
978       (GNUNET_YES == ctask->download_is_finished) &&
979       (0 == bytes_to_copy)) /* &&
980       (BUF_WAIT_FOR_CURL == ctask->buf_status))*/
981   {
982     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
983                 "MHD: sending error response\n");
984     ctask->download_in_progress = GNUNET_NO;
985     run_mhd_now (ctask->mhd);
986     GNUNET_SCHEDULER_add_now (&mhd_content_free, ctask);
987     total_mhd_connections--;
988     return MHD_CONTENT_READER_END_WITH_ERROR;
989   }
990
991   if ( ctask->buf_status == BUF_WAIT_FOR_CURL )
992     return 0;
993   
994   copied = 0;
995   for (; NULL != re_match; re_match = ctask->pp_match_head)
996   {
997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
998                 "MHD: Processing PP %s\n",
999                 re_match->hostname);
1000     bytes_to_copy = re_match->start - ctask->buffer_read_ptr;
1001     GNUNET_assert (bytes_to_copy >= 0);
1002
1003     if (bytes_to_copy+copied > max)
1004     {
1005       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1006              "MHD: buffer in response too small for %d. Using available space (%d). (%s)\n",
1007              bytes_to_copy,
1008              max,
1009              ctask->url);
1010       memcpy (buf+copied, ctask->buffer_read_ptr, max-copied);
1011       ctask->buffer_read_ptr += max-copied;
1012       copied = max;
1013       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014               "MHD: copied %d bytes\n", copied);
1015       return copied;
1016     }
1017
1018     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1019                 "MHD: copying %d bytes to mhd response at offset %d\n",
1020                 bytes_to_copy, ctask->buffer_read_ptr);
1021     memcpy (buf+copied, ctask->buffer_read_ptr, bytes_to_copy);
1022     copied += bytes_to_copy;
1023
1024     if (GNUNET_NO == re_match->done)
1025     {
1026       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1027                   "MHD: Waiting for PP of %s\n", re_match->hostname);
1028       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1029               "MHD: copied %d bytes\n", copied);
1030       ctask->buffer_read_ptr += bytes_to_copy;
1031       return copied;
1032     }
1033     
1034     if (strlen (re_match->result) > (max - copied))
1035     {
1036       //FIXME partially copy domain here
1037       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1038                   "MHD: buffer in response too small for %s! (%s)\n",
1039                   re_match->result,
1040                   ctask->url);
1041       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1042               "MHD: copied %d bytes\n", copied);
1043       ctask->buffer_read_ptr += bytes_to_copy;
1044       return copied;
1045     }
1046     
1047     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1048                 "MHD: Adding PP result %s to buffer\n",
1049                 re_match->result);
1050     memcpy (buf+copied, re_match->result, strlen (re_match->result));
1051     copied += strlen (re_match->result);
1052     ctask->buffer_read_ptr = re_match->end;
1053     GNUNET_CONTAINER_DLL_remove (ctask->pp_match_head,
1054                                  ctask->pp_match_tail,
1055                                  re_match);
1056     GNUNET_free (re_match);
1057   }
1058
1059   bytes_to_copy = ctask->buffer_write_ptr - ctask->buffer_read_ptr;
1060
1061   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1062               "MHD: copied: %d left: %d, space left in buf: %d\n",
1063               copied,
1064               bytes_to_copy, max-copied);
1065   
1066   GNUNET_assert (0 <= bytes_to_copy);
1067
1068   if (GNUNET_NO == ctask->download_is_finished)
1069   {
1070     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1071                 "MHD: Purging buffer\n");
1072     memmove (ctask->buffer, ctask->buffer_read_ptr, bytes_to_copy);
1073     ctask->buffer_read_ptr = ctask->buffer;
1074     ctask->buffer_write_ptr = ctask->buffer + bytes_to_copy;
1075     ctask->buffer[bytes_to_copy] = '\0';
1076   }
1077   
1078   if (bytes_to_copy+copied > max)
1079     bytes_to_copy = max-copied;
1080
1081   if (0 > bytes_to_copy)
1082     bytes_to_copy = 0;
1083   
1084   memcpy (buf+copied, ctask->buffer_read_ptr, bytes_to_copy);
1085   ctask->buffer_read_ptr += bytes_to_copy;
1086   copied += bytes_to_copy;
1087   ctask->buf_status = BUF_WAIT_FOR_CURL;
1088   
1089   if (NULL != ctask->curl)
1090     curl_easy_pause (ctask->curl, CURLPAUSE_CONT);
1091
1092   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1093               "MHD: copied %d bytes\n", copied);
1094   run_mhd_now (ctask->mhd);
1095   return copied;
1096 }
1097
1098 /**
1099  * Shorten result callback
1100  *
1101  * @param cls the proxycurltask
1102  * @param short_name the shortened name (NULL on error)
1103  */
1104 static void
1105 process_shorten (void* cls, const char* short_name)
1106 {
1107   struct ProxyREMatch *re_match = cls;
1108   char result[sizeof (re_match->result)];
1109   
1110   if (NULL == short_name)
1111   {
1112     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1113                 "PP: Unable to shorten %s\n",
1114                 re_match->hostname);
1115     GNUNET_CONTAINER_DLL_remove (re_match->ctask->pp_match_head,
1116                                  re_match->ctask->pp_match_tail,
1117                                  re_match);
1118     GNUNET_free (re_match);
1119     return;
1120   }
1121
1122   if (0 == strcmp (short_name, re_match->ctask->leho))
1123     strcpy (result, re_match->ctask->host);
1124   else
1125     strcpy (result, short_name);
1126
1127   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1128               "PP: Shorten %s -> %s\n",
1129               re_match->hostname,
1130               result);
1131   
1132   if (re_match->ctask->mhd->is_ssl)
1133     sprintf (re_match->result, "href=\"https://%s", result);
1134   else
1135     sprintf (re_match->result, "href=\"http://%s", result);
1136
1137   re_match->done = GNUNET_YES;
1138   run_mhd_now (re_match->ctask->mhd);
1139 }
1140
1141
1142 /**
1143  * Postprocess data in buffer. From read ptr to write ptr
1144  *
1145  * @param cls the curlproxytask
1146  * @param tc task context
1147  */
1148 static void
1149 postprocess_buffer (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1150 {
1151   struct ProxyCurlTask *ctask = cls;
1152   struct ProxyREMatch *re_match;
1153   char* re_ptr = ctask->buffer_read_ptr;
1154   char re_hostname[255];
1155   regmatch_t m[RE_N_MATCHES];
1156
1157   ctask->pp_task = GNUNET_SCHEDULER_NO_TASK;
1158
1159   if (GNUNET_YES != ctask->parse_content)
1160   {
1161     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1162                 "PP: Not parsing content\n");
1163     ctask->buf_status = BUF_WAIT_FOR_MHD;
1164     run_mhd_now (ctask->mhd);
1165     return;
1166   }
1167
1168   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1169               "PP: We need to parse the HTML\n");
1170
1171   /* 0 means match found */
1172   while (0 == regexec (&re_dotplus, re_ptr, RE_N_MATCHES, m, 0))
1173   {
1174     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1175                 "PP: regex match\n");
1176
1177     GNUNET_assert (m[1].rm_so != -1);
1178
1179     memset (re_hostname, 0, sizeof (re_hostname));
1180     memcpy (re_hostname, re_ptr+m[1].rm_so, (m[3].rm_eo-m[1].rm_so));
1181
1182     re_match = GNUNET_malloc (sizeof (struct ProxyREMatch));
1183     re_match->start = re_ptr + m[0].rm_so;
1184     re_match->end = re_ptr + m[3].rm_eo;
1185     re_match->done = GNUNET_NO;
1186     re_match->ctask = ctask;
1187     strcpy (re_match->hostname, re_hostname);
1188     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1189                 "PP: Got hostname %s\n", re_hostname);
1190     re_ptr += m[3].rm_eo;
1191
1192     if (GNUNET_YES == is_tld (re_match->hostname, GNUNET_GNS_TLD_PLUS))
1193     {
1194       re_match->hostname[strlen(re_match->hostname)-1] = '\0';
1195       strcpy (re_match->hostname+strlen(re_match->hostname),
1196               ctask->authority);
1197     }
1198
1199     re_match->shorten_task = GNUNET_GNS_shorten_zone (gns_handle,
1200                              re_match->hostname,
1201                              &local_private_zone,
1202                              &local_shorten_zone,
1203                              &local_gns_zone,
1204                              &process_shorten,
1205                              re_match); //FIXME cancel appropriately
1206
1207     GNUNET_CONTAINER_DLL_insert_tail (ctask->pp_match_head,
1208                                       ctask->pp_match_tail,
1209                                       re_match);
1210   }
1211   
1212   ctask->buf_status = BUF_WAIT_FOR_MHD;
1213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1214               "PP: No more matches\n");
1215   run_mhd_now (ctask->mhd);
1216 }
1217
1218 /**
1219  * Handle data from cURL
1220  *
1221  * @param ptr pointer to the data
1222  * @param size number of blocks of data
1223  * @param nmemb blocksize
1224  * @param ctx the curlproxytask
1225  * @return number of bytes handled
1226  */
1227 static size_t
1228 curl_download_cb (void *ptr, size_t size, size_t nmemb, void* ctx)
1229 {
1230   const char *cbuf = ptr;
1231   size_t total = size * nmemb;
1232   struct ProxyCurlTask *ctask = ctx;
1233   size_t buf_space = sizeof (ctask->buffer) -
1234     (ctask->buffer_write_ptr-ctask->buffer);
1235
1236   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1237               "CURL: Got %d. %d free in buffer\n",
1238               total, buf_space);
1239
1240   if (total > (buf_space - CURL_BUF_PADDING))
1241   {
1242     if (ctask->buf_status == BUF_WAIT_FOR_CURL)
1243     {
1244       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1245                   "CURL: Buffer full starting postprocessing\n");
1246       ctask->buf_status = BUF_WAIT_FOR_PP;
1247       ctask->pp_task = GNUNET_SCHEDULER_add_now (&postprocess_buffer,
1248                                                  ctask);
1249       return CURL_WRITEFUNC_PAUSE;
1250     }
1251
1252     /* we should not get called in that case */
1253     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1254                 "CURL: called out of context and no space in buffer!\n");
1255     return CURL_WRITEFUNC_PAUSE;
1256   }
1257
1258   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1259               "CURL: Copying %d bytes to buffer (%s)\n", total, ctask->url);
1260   memcpy (ctask->buffer_write_ptr, cbuf, total);
1261   ctask->bytes_in_buffer += total;
1262   ctask->buffer_write_ptr += total;
1263   ctask->buffer_write_ptr[0] = '\0';
1264
1265   return total;
1266 }
1267
1268 /**
1269  * cURL callback for post data
1270  */
1271 static size_t
1272 read_callback (void *buf, size_t size, size_t nmemb, void *cls)
1273 {
1274   struct ProxyCurlTask *ctask = cls;
1275   struct ProxyPostData *pdata = ctask->post_data_head;
1276   size_t len = size * nmemb;
1277   size_t to_copy;
1278   char* pos;
1279
1280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1281               "CURL: read callback\n");
1282
1283   if (NULL == pdata)
1284     return 0;
1285   
1286   //fin
1287   if (NULL == pdata->value)
1288   {
1289     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1290                 "CURL: Terminating POST data\n");
1291
1292     GNUNET_CONTAINER_DLL_remove (ctask->post_data_head,
1293                                  ctask->post_data_tail,
1294                                  pdata);
1295     GNUNET_free (pdata);
1296     return 0;
1297   }
1298  
1299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1300               "CURL: read callback value %s\n", pdata->value); 
1301   
1302   to_copy = pdata->bytes_left;
1303   if (to_copy > len)
1304     to_copy = len;
1305   
1306   pos = pdata->value + (pdata->total_bytes - pdata->bytes_left);
1307   memcpy (buf, pos, to_copy);
1308   pdata->bytes_left -= to_copy;
1309   if (pdata->bytes_left <= 0)
1310   {
1311     GNUNET_free (pdata->value);
1312     GNUNET_CONTAINER_DLL_remove (ctask->post_data_head,
1313                                  ctask->post_data_tail,
1314                                  pdata);
1315     GNUNET_free (pdata);
1316   }
1317   return to_copy;
1318 }
1319
1320 /**
1321  * Task that is run when we are ready to receive more data
1322  * from curl
1323  *
1324  * @param cls closure
1325  * @param tc task context
1326  */
1327 static void
1328 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1329
1330 /**
1331  * Ask cURL for the select sets and schedule download
1332  */
1333 static void
1334 curl_download_prepare ()
1335 {
1336   CURLMcode mret;
1337   fd_set rs;
1338   fd_set ws;
1339   fd_set es;
1340   int max;
1341   struct GNUNET_NETWORK_FDSet *grs;
1342   struct GNUNET_NETWORK_FDSet *gws;
1343   long to;
1344   struct GNUNET_TIME_Relative rtime;
1345
1346   max = -1;
1347   FD_ZERO (&rs);
1348   FD_ZERO (&ws);
1349   FD_ZERO (&es);
1350   mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max);
1351
1352   if (mret != CURLM_OK)
1353   {
1354     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1355                 "%s failed at %s:%d: `%s'\n",
1356                 "curl_multi_fdset", __FILE__, __LINE__,
1357                 curl_multi_strerror (mret));
1358     //TODO cleanup here?
1359     return;
1360   }
1361
1362   mret = curl_multi_timeout (curl_multi, &to);
1363   rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
1364
1365   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1366               "cURL multi fds: max=%d timeout=%llu\n", max, to);
1367
1368   grs = GNUNET_NETWORK_fdset_create ();
1369   gws = GNUNET_NETWORK_fdset_create ();
1370   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1371   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1372   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1373               "Scheduling task cURL\n");
1374
1375   if (curl_download_task != GNUNET_SCHEDULER_NO_TASK)
1376     GNUNET_SCHEDULER_cancel (curl_download_task);
1377   
1378   if (-1 != max)
1379   {
1380     curl_download_task =
1381       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1382                                    rtime,
1383                                    grs, gws,
1384                                    &curl_task_download, curl_multi);
1385   }
1386   else if (NULL != ctasks_head)
1387   {
1388     /* as specified in curl docs */
1389     curl_download_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1390                                                        &curl_task_download,
1391                                                        curl_multi);
1392   }
1393   GNUNET_NETWORK_fdset_destroy (gws);
1394   GNUNET_NETWORK_fdset_destroy (grs);
1395
1396 }
1397
1398
1399 /**
1400  * Task that is run when we are ready to receive more data
1401  * from curl
1402  *
1403  * @param cls closure
1404  * @param tc task context
1405  */
1406 static void
1407 curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1408 {
1409   int running;
1410   int msgnum;
1411   struct CURLMsg *msg;
1412   CURLMcode mret;
1413   struct ProxyCurlTask *ctask;
1414   int num_ctasks;
1415   long resp_code;
1416
1417   struct ProxyCurlTask *clean_head = NULL;
1418   struct ProxyCurlTask *clean_tail = NULL;
1419
1420   curl_download_task = GNUNET_SCHEDULER_NO_TASK;
1421
1422   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1423   {
1424     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1425                 "Shutdown requested while trying to download\n");
1426     //TODO cleanup
1427     return;
1428   }
1429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1430               "Ready to dl\n");
1431
1432   do
1433   {
1434     running = 0;
1435     num_ctasks = 0;
1436     
1437     mret = curl_multi_perform (curl_multi, &running);
1438
1439     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1440                 "Running curl tasks: %d\n", running);
1441
1442     ctask = ctasks_head;
1443     for (; ctask != NULL; ctask = ctask->next)
1444     {
1445       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1446                   "CTask: %s\n", ctask->url);
1447       num_ctasks++;
1448     }
1449
1450     if (num_ctasks != running)
1451     {
1452       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1453                   "%d ctasks, %d curl running\n", num_ctasks, running);
1454     }
1455     
1456     do
1457     {
1458       ctask = ctasks_head;
1459       msg = curl_multi_info_read (curl_multi, &msgnum);
1460       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1461                   "Messages left: %d\n", msgnum);
1462       
1463       if (msg == NULL)
1464         break;
1465       switch (msg->msg)
1466       {
1467        case CURLMSG_DONE:
1468          if ((msg->data.result != CURLE_OK) &&
1469              (msg->data.result != CURLE_GOT_NOTHING))
1470          {
1471            GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1472                        "Download curl failed");
1473             
1474            for (; ctask != NULL; ctask = ctask->next)
1475            {
1476              if (NULL == ctask->curl)
1477                continue;
1478
1479              if (memcmp (msg->easy_handle, ctask->curl, sizeof (CURL)) != 0)
1480                continue;
1481              
1482              GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1483                          "CURL: Download failed for task %s: %s.\n",
1484                          ctask->url,
1485                          curl_easy_strerror (msg->data.result));
1486              ctask->download_is_finished = GNUNET_YES;
1487              ctask->download_error = GNUNET_YES;
1488              if (CURLE_OK == curl_easy_getinfo (ctask->curl,
1489                                                 CURLINFO_RESPONSE_CODE,
1490                                                 &resp_code))
1491                ctask->curl_response_code = resp_code;
1492              ctask->ready_to_queue = MHD_YES;
1493              ctask->buf_status = BUF_WAIT_FOR_MHD;
1494              run_mhd_now (ctask->mhd);
1495              
1496              GNUNET_CONTAINER_DLL_remove (ctasks_head, ctasks_tail,
1497                                           ctask);
1498              GNUNET_CONTAINER_DLL_insert (clean_head, clean_tail, ctask);
1499              break;
1500            }
1501            GNUNET_assert (ctask != NULL);
1502          }
1503          else
1504          {
1505            GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1506                        "CURL: download completed.\n");
1507
1508            for (; ctask != NULL; ctask = ctask->next)
1509            {
1510              if (NULL == ctask->curl)
1511                continue;
1512
1513              if (memcmp (msg->easy_handle, ctask->curl, sizeof (CURL)) != 0)
1514                continue;
1515              
1516              if (ctask->buf_status != BUF_WAIT_FOR_CURL)
1517                continue;
1518              
1519              GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1520                          "CURL: completed task %s found.\n", ctask->url);
1521              if (CURLE_OK == curl_easy_getinfo (ctask->curl,
1522                                                 CURLINFO_RESPONSE_CODE,
1523                                                 &resp_code))
1524                ctask->curl_response_code = resp_code;
1525
1526
1527              GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1528                          "CURL: Completed ctask!\n");
1529              if (GNUNET_SCHEDULER_NO_TASK == ctask->pp_task)
1530              {
1531               ctask->buf_status = BUF_WAIT_FOR_PP;
1532               ctask->pp_task = GNUNET_SCHEDULER_add_now (&postprocess_buffer,
1533                                                           ctask);
1534              }
1535
1536              ctask->ready_to_queue = MHD_YES;
1537              ctask->download_is_finished = GNUNET_YES;
1538
1539              /* We MUST not modify the multi handle else we loose messages */
1540              GNUNET_CONTAINER_DLL_remove (ctasks_head, ctasks_tail,
1541                                           ctask);
1542              GNUNET_CONTAINER_DLL_insert (clean_head, clean_tail, ctask);
1543
1544              break;
1545            }
1546            GNUNET_assert (ctask != NULL);
1547          }
1548          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1549                      "CURL: %s\n", curl_easy_strerror(msg->data.result));
1550          break;
1551        default:
1552          GNUNET_assert (0);
1553          break;
1554       }
1555     } while (msgnum > 0);
1556
1557     for (ctask=clean_head; ctask != NULL; ctask = ctask->next)
1558     {
1559       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1560                   "CURL: Removing task %s.\n", ctask->url);
1561       curl_multi_remove_handle (curl_multi, ctask->curl);
1562       curl_easy_cleanup (ctask->curl);
1563       ctask->curl = NULL;
1564     }
1565     
1566     num_ctasks=0;
1567     for (ctask=ctasks_head; ctask != NULL; ctask = ctask->next)
1568     {
1569       num_ctasks++;
1570     }
1571     
1572     if (num_ctasks != running)
1573     {
1574       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1575                   "CURL: %d tasks, %d running\n", num_ctasks, running);
1576     }
1577
1578     GNUNET_assert ( num_ctasks == running );
1579
1580   } while (mret == CURLM_CALL_MULTI_PERFORM);
1581   
1582   if (mret != CURLM_OK)
1583   {
1584     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "CURL: %s failed at %s:%d: `%s'\n",
1585                 "curl_multi_perform", __FILE__, __LINE__,
1586                 curl_multi_strerror (mret));
1587   }
1588   curl_download_prepare();
1589 }
1590
1591 /**
1592  * Process LEHO lookup
1593  *
1594  * @param cls the ctask
1595  * @param rd_count number of records returned
1596  * @param rd record data
1597  */
1598 static void
1599 process_leho_lookup (void *cls,
1600                      uint32_t rd_count,
1601                      const struct GNUNET_NAMESTORE_RecordData *rd)
1602 {
1603   struct ProxyCurlTask *ctask = cls;
1604   char hosthdr[262]; //256 + "Host: "
1605   int i;
1606   CURLcode ret;
1607   CURLMcode mret;
1608   struct hostent *phost;
1609   char *ssl_ip;
1610   char resolvename[512];
1611   char curlurl[512];
1612
1613   strcpy (ctask->leho, "");
1614
1615   if (rd_count == 0)
1616     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1617                 "No LEHO present!\n");
1618
1619   for (i=0; i<rd_count; i++)
1620   {
1621     if (rd[i].record_type != GNUNET_GNS_RECORD_LEHO)
1622       continue;
1623
1624     memcpy (ctask->leho, rd[i].data, rd[i].data_size);
1625
1626     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1627                 "Found LEHO %s for %s\n", ctask->leho, ctask->url);
1628   }
1629
1630   if (0 != strcmp (ctask->leho, ""))
1631   {
1632     sprintf (hosthdr, "%s%s", "Host: ", ctask->leho);
1633     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1634                 "New HTTP header value: %s\n", hosthdr);
1635     ctask->headers = curl_slist_append (ctask->headers, hosthdr);
1636     GNUNET_assert (NULL != ctask->headers);
1637     ret = curl_easy_setopt (ctask->curl, CURLOPT_HTTPHEADER, ctask->headers);
1638     if (CURLE_OK != ret)
1639     {
1640       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s failed at %s:%d: `%s'\n",
1641                            "curl_easy_setopt", __FILE__, __LINE__, curl_easy_strerror(ret));
1642     }
1643
1644   }
1645
1646   if (ctask->mhd->is_ssl)
1647   {
1648     phost = (struct hostent*)gethostbyname (ctask->host);
1649
1650     if (phost!=NULL)
1651     {
1652       ssl_ip = inet_ntoa(*((struct in_addr*)(phost->h_addr)));
1653       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1654                   "SSL target server: %s\n", ssl_ip);
1655       sprintf (resolvename, "%s:%d:%s", ctask->leho, HTTPS_PORT, ssl_ip);
1656       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1657                   "Curl resolve: %s\n", resolvename);
1658       ctask->resolver = curl_slist_append ( ctask->resolver, resolvename);
1659       curl_easy_setopt (ctask->curl, CURLOPT_RESOLVE, ctask->resolver);
1660       sprintf (curlurl, "https://%s%s", ctask->leho, ctask->url);
1661       curl_easy_setopt (ctask->curl, CURLOPT_URL, curlurl);
1662     }
1663     else
1664     {
1665       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1666                   "gethostbyname failed for %s!\n", ctask->host);
1667       ctask->download_is_finished = GNUNET_YES;
1668       ctask->download_error = GNUNET_YES;
1669       return;
1670     }
1671   }
1672
1673   if (CURLM_OK != (mret=curl_multi_add_handle (curl_multi, ctask->curl)))
1674   {
1675     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1676                 "%s failed at %s:%d: `%s'\n",
1677                 "curl_multi_add_handle", __FILE__, __LINE__,
1678                 curl_multi_strerror (mret));
1679     ctask->download_is_finished = GNUNET_YES;
1680     ctask->download_error = GNUNET_YES;
1681     return;
1682   }
1683   GNUNET_CONTAINER_DLL_insert (ctasks_head, ctasks_tail, ctask);
1684
1685   curl_download_prepare ();
1686
1687 }
1688
1689 /**
1690  * Initialize download and trigger curl
1691  *
1692  * @param cls the proxycurltask
1693  * @param auth_name the name of the authority (site of origin) of ctask->host
1694  *
1695  */
1696 static void
1697 process_get_authority (void *cls,
1698                        const char* auth_name)
1699 {
1700   struct ProxyCurlTask *ctask = cls;
1701
1702   if (NULL == auth_name)
1703   {
1704     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1705                 "Get authority failed!\n");
1706     strcpy (ctask->authority, "");
1707   }
1708   else
1709   {
1710     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1711                 "Get authority yielded %s\n", auth_name);
1712     strcpy (ctask->authority, auth_name);
1713   }
1714
1715   GNUNET_GNS_lookup_zone (gns_handle,
1716                           ctask->host,
1717                           &local_gns_zone,
1718                           GNUNET_GNS_RECORD_LEHO,
1719                           GNUNET_YES, //Only cached for performance
1720                           shorten_zonekey,
1721                           &process_leho_lookup,
1722                           ctask);
1723 }
1724
1725
1726 /**
1727  * Main MHD callback for handling requests.
1728  *
1729  * @param cls unused
1730  * @param con MHD connection handle
1731  * @param url the url in the request
1732  * @param meth the HTTP method used ("GET", "PUT", etc.)
1733  * @param ver the HTTP version string (i.e. "HTTP/1.1")
1734  * @param upload_data the data being uploaded (excluding HEADERS,
1735  *        for a POST that fits into memory and that is encoded
1736  *        with a supported encoding, the POST data will NOT be
1737  *        given in upload_data and is instead available as
1738  *        part of MHD_get_connection_values; very large POST
1739  *        data *will* be made available incrementally in
1740  *        upload_data)
1741  * @param upload_data_size set initially to the size of the
1742  *        upload_data provided; the method must update this
1743  *        value to the number of bytes NOT processed;
1744  * @param con_cls pointer to location where we store the 'struct Request'
1745  * @return MHD_YES if the connection was handled successfully,
1746  *         MHD_NO if the socket must be closed due to a serious
1747  *         error while handling the request
1748  */
1749 static int
1750 create_response (void *cls,
1751                  struct MHD_Connection *con,
1752                  const char *url,
1753                  const char *meth,
1754                  const char *ver,
1755                  const char *upload_data,
1756                  size_t *upload_data_size,
1757                  void **con_cls)
1758 {
1759   struct MhdHttpList* hd = cls;
1760   const char* page = "<html><head><title>gnoxy</title>"\
1761                       "</head><body>cURL fail</body></html>";
1762   
1763   char curlurl[MAX_HTTP_URI_LENGTH]; // buffer overflow!
1764   int ret = MHD_YES;
1765
1766   struct ProxyCurlTask *ctask;
1767   struct ProxyPostData *fin_post;
1768   
1769   //FIXME handle
1770   if ((0 != strcasecmp (meth, MHD_HTTP_METHOD_GET)) &&
1771       (0 != strcasecmp (meth, MHD_HTTP_METHOD_PUT)) &&
1772       (0 != strcasecmp (meth, MHD_HTTP_METHOD_POST)))
1773   {
1774     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1775                 "MHD: %s NOT IMPLEMENTED!\n", meth);
1776     return MHD_NO;
1777   }
1778
1779
1780   if (NULL == *con_cls)
1781   {
1782
1783     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1784                 "Got %s request for %s\n", meth, url);
1785     ctask = GNUNET_malloc (sizeof (struct ProxyCurlTask));
1786     ctask->mhd = hd;
1787     *con_cls = ctask;
1788     
1789     ctask->curl = curl_easy_init();
1790     if (NULL == ctask->curl)
1791     {
1792       ctask->response = MHD_create_response_from_buffer (strlen (page),
1793                                                 (void*)page,
1794                                                 MHD_RESPMEM_PERSISTENT);
1795       ret = MHD_queue_response (con,
1796                                 MHD_HTTP_OK,
1797                                 ctask->response);
1798       MHD_destroy_response (ctask->response);
1799       GNUNET_free (ctask);
1800       return ret;
1801     }
1802   
1803     ctask->download_in_progress = GNUNET_YES;
1804     ctask->buf_status = BUF_WAIT_FOR_CURL;
1805     ctask->connection = con;
1806     ctask->curl_response_code = MHD_HTTP_OK;
1807     ctask->buffer_read_ptr = ctask->buffer;
1808     ctask->buffer_write_ptr = ctask->buffer;
1809     ctask->pp_task = GNUNET_SCHEDULER_NO_TASK;
1810
1811     MHD_get_connection_values (con,
1812                                MHD_HEADER_KIND,
1813                                &con_val_iter, ctask);
1814
1815     if (0 == strcasecmp (meth, MHD_HTTP_METHOD_PUT))
1816     {
1817       if (0 == *upload_data_size)
1818       {
1819         curl_easy_cleanup (ctask->curl);
1820         GNUNET_free (ctask);
1821         return MHD_NO;
1822       }
1823       ctask->put_read_offset = 0;
1824       ctask->put_read_size = *upload_data_size;
1825       curl_easy_setopt (ctask->curl, CURLOPT_UPLOAD, 1);
1826       curl_easy_setopt (ctask->curl, CURLOPT_READDATA, upload_data);
1827       //curl_easy_setopt (ctask->curl, CURLOPT_READFUNCTION, &curl_read_cb);
1828       
1829       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1830                   "Got PUT data: %s\n", upload_data);
1831       curl_easy_cleanup (ctask->curl);
1832       GNUNET_free (ctask);
1833       return MHD_NO;
1834     }
1835
1836     if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1837     {
1838       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1839                   "Setting up POST processor\n");
1840       ctask->post_handler = MHD_create_post_processor (con,
1841                                  POSTBUFFERSIZE,
1842                                  &con_post_data_iter,
1843                                  ctask);
1844       curl_easy_setopt (ctask->curl, CURLOPT_POST, 1);
1845       curl_easy_setopt (ctask->curl, CURLOPT_READFUNCTION,
1846                         &read_callback);
1847       curl_easy_setopt (ctask->curl, CURLOPT_READDATA, ctask);
1848       ctask->headers = curl_slist_append (ctask->headers,
1849                                           "Transfer-Encoding: chunked");
1850       /*curl_easy_setopt (ctask->curl, CURLOPT_POST, 1);
1851       curl_easy_setopt (ctask->curl, CURLOPT_POSTFIELDSIZE, *upload_data_size);
1852       curl_easy_setopt (ctask->curl, CURLOPT_COPYPOSTFIELDS, upload_data);
1853       
1854       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1855                   "Got POST data: %s\n", upload_data);
1856       curl_easy_cleanup (ctask->curl);
1857       GNUNET_free (ctask);
1858       return MHD_NO;*/
1859     }
1860
1861     curl_easy_setopt (ctask->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
1862     curl_easy_setopt (ctask->curl, CURLOPT_HEADERDATA, ctask);
1863     curl_easy_setopt (ctask->curl, CURLOPT_WRITEFUNCTION, &curl_download_cb);
1864     curl_easy_setopt (ctask->curl, CURLOPT_WRITEDATA, ctask);
1865     curl_easy_setopt (ctask->curl, CURLOPT_FOLLOWLOCATION, 0);
1866     curl_easy_setopt (ctask->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1867     
1868     if (GNUNET_NO == ctask->mhd->is_ssl)
1869     {
1870       sprintf (curlurl, "http://%s%s", ctask->host, url);
1871       MHD_get_connection_values (con,
1872                                  MHD_GET_ARGUMENT_KIND,
1873                                  &get_uri_val_iter, curlurl);
1874       curl_easy_setopt (ctask->curl, CURLOPT_URL, curlurl);
1875     }
1876     strcpy (ctask->url, url);
1877     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1878                   "MHD: Adding new curl task for %s%s\n", ctask->host, url);
1879     MHD_get_connection_values (con,
1880                                MHD_GET_ARGUMENT_KIND,
1881                                &get_uri_val_iter, ctask->url);
1882   
1883     curl_easy_setopt (ctask->curl, CURLOPT_FAILONERROR, 1);
1884     curl_easy_setopt (ctask->curl, CURLOPT_CONNECTTIMEOUT, 600L);
1885     curl_easy_setopt (ctask->curl, CURLOPT_TIMEOUT, 600L);
1886
1887     GNUNET_GNS_get_authority (gns_handle,
1888                               ctask->host,
1889                               &process_get_authority,
1890                               ctask);
1891     ctask->ready_to_queue = GNUNET_NO;
1892     ctask->fin = GNUNET_NO;
1893     return MHD_YES;
1894   }
1895
1896   ctask = (struct ProxyCurlTask *) *con_cls;
1897   if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST))
1898   {
1899     if (0 != *upload_data_size)
1900     {
1901       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1902                   "Invoking POST processor\n");
1903       MHD_post_process (ctask->post_handler,
1904                         upload_data, *upload_data_size);
1905       *upload_data_size = 0;
1906       return MHD_YES;
1907     }
1908     else if (GNUNET_NO == ctask->post_done)
1909     {
1910       fin_post = GNUNET_malloc (sizeof (struct ProxyPostData));
1911       GNUNET_CONTAINER_DLL_insert_tail (ctask->post_data_head,
1912                                         ctask->post_data_tail,
1913                                         fin_post);
1914       ctask->post_done = GNUNET_YES;
1915       return MHD_YES;
1916     }
1917   }
1918   
1919   if (GNUNET_YES != ctask->ready_to_queue)
1920     return MHD_YES; /* wait longer */
1921   
1922   if (GNUNET_YES == ctask->fin)
1923     return MHD_YES;
1924
1925   ctask->fin = GNUNET_YES;
1926   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1927               "MHD: Queueing response for %s\n", ctask->url);
1928   ret = MHD_queue_response (con, ctask->curl_response_code, ctask->response);
1929   run_mhd_now (ctask->mhd);
1930   return ret;
1931 }
1932
1933
1934 /**
1935  * run all httpd
1936  */
1937 static void
1938 run_httpds ()
1939 {
1940   struct MhdHttpList *hd;
1941
1942   for (hd=mhd_httpd_head; NULL != hd; hd = hd->next)
1943     run_httpd (hd);
1944
1945 }
1946
1947 /**
1948  * schedule mhd
1949  *
1950  * @param hd the daemon to run
1951  */
1952 static void
1953 run_httpd (struct MhdHttpList *hd)
1954 {
1955   fd_set rs;
1956   fd_set ws;
1957   fd_set es;
1958   struct GNUNET_NETWORK_FDSet *wrs;
1959   struct GNUNET_NETWORK_FDSet *wws;
1960   struct GNUNET_NETWORK_FDSet *wes;
1961   int max;
1962   int haveto;
1963   unsigned MHD_LONG_LONG timeout;
1964   struct GNUNET_TIME_Relative tv;
1965
1966   FD_ZERO (&rs);
1967   FD_ZERO (&ws);
1968   FD_ZERO (&es);
1969   wrs = GNUNET_NETWORK_fdset_create ();
1970   wes = GNUNET_NETWORK_fdset_create ();
1971   wws = GNUNET_NETWORK_fdset_create ();
1972   max = -1;
1973   GNUNET_assert (MHD_YES == MHD_get_fdset (hd->daemon, &rs, &ws, &es, &max));
1974   
1975   
1976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1977               "MHD fds: max=%d\n", max);
1978   
1979   haveto = MHD_get_timeout (hd->daemon, &timeout);
1980
1981   if (MHD_YES == haveto)
1982     tv.rel_value = (uint64_t) timeout;
1983   else
1984     tv = GNUNET_TIME_UNIT_FOREVER_REL;
1985   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1986   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1987   GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
1988   
1989   if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
1990     GNUNET_SCHEDULER_cancel (hd->httpd_task);
1991   hd->httpd_task =
1992     GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
1993                                  tv, wrs, wws,
1994                                  &do_httpd, hd);
1995   GNUNET_NETWORK_fdset_destroy (wrs);
1996   GNUNET_NETWORK_fdset_destroy (wws);
1997   GNUNET_NETWORK_fdset_destroy (wes);
1998 }
1999
2000
2001 /**
2002  * Task run whenever HTTP server operations are pending.
2003  *
2004  * @param cls unused
2005  * @param tc sched context
2006  */
2007 static void
2008 do_httpd (void *cls,
2009           const struct GNUNET_SCHEDULER_TaskContext *tc)
2010 {
2011   struct MhdHttpList *hd = cls;
2012   
2013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2014               "MHD: Main loop\n");
2015   hd->httpd_task = GNUNET_SCHEDULER_NO_TASK; 
2016   MHD_run (hd->daemon);
2017   run_httpd (hd);
2018 }
2019
2020
2021
2022 /**
2023  * Read data from socket
2024  *
2025  * @param cls the closure
2026  * @param tc scheduler context
2027  */
2028 static void
2029 do_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2030
2031 /**
2032  * Read from remote end
2033  *
2034  * @param cls closure
2035  * @param tc scheduler context
2036  */
2037 static void
2038 do_read_remote (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2039
2040 /**
2041  * Write data to remote socket
2042  *
2043  * @param cls the closure
2044  * @param tc scheduler context
2045  */
2046 static void
2047 do_write_remote (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2048 {
2049   struct Socks5Request *s5r = cls;
2050   unsigned int len;
2051
2052   s5r->fwdwtask = GNUNET_SCHEDULER_NO_TASK;
2053
2054   if ((NULL != tc->read_ready) &&
2055       (GNUNET_NETWORK_fdset_isset (tc->write_ready, s5r->remote_sock)) &&
2056       ((len = GNUNET_NETWORK_socket_send (s5r->remote_sock, s5r->rbuf,
2057                                          s5r->rbuf_len)>0)))
2058   {
2059     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2060                 "Successfully sent %d bytes to remote socket\n",
2061                 len);
2062   }
2063   else
2064   {
2065     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write remote");
2066     if (GNUNET_SCHEDULER_NO_TASK != s5r->rtask)
2067       GNUNET_SCHEDULER_cancel (s5r->rtask);
2068     if (GNUNET_SCHEDULER_NO_TASK != s5r->wtask)
2069       GNUNET_SCHEDULER_cancel (s5r->wtask);
2070     if (GNUNET_SCHEDULER_NO_TASK != s5r->fwdrtask)
2071       GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2072     GNUNET_NETWORK_socket_close (s5r->remote_sock);
2073     GNUNET_NETWORK_socket_close (s5r->sock);
2074     GNUNET_free(s5r);
2075     return;
2076   }
2077
2078   s5r->rtask =
2079     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2080                                    s5r->sock,
2081                                    &do_read, s5r);
2082 }
2083
2084
2085 /**
2086  * Clean up s5r handles
2087  *
2088  * @param s5r the handle to destroy
2089  */
2090 static void
2091 cleanup_s5r (struct Socks5Request *s5r)
2092 {
2093   if (GNUNET_SCHEDULER_NO_TASK != s5r->rtask)
2094     GNUNET_SCHEDULER_cancel (s5r->rtask);
2095   if (GNUNET_SCHEDULER_NO_TASK != s5r->fwdwtask)
2096     GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2097   if (GNUNET_SCHEDULER_NO_TASK != s5r->fwdrtask)
2098     GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2099   
2100   if (NULL != s5r->remote_sock)
2101     GNUNET_NETWORK_socket_close (s5r->remote_sock);
2102   if ((NULL != s5r->sock) && (s5r->cleanup_sock == GNUNET_YES))
2103     GNUNET_NETWORK_socket_close (s5r->sock);
2104   
2105   GNUNET_free(s5r);
2106 }
2107
2108 /**
2109  * Write data to socket
2110  *
2111  * @param cls the closure
2112  * @param tc scheduler context
2113  */
2114 static void
2115 do_write (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2116 {
2117   struct Socks5Request *s5r = cls;
2118   unsigned int len;
2119
2120   s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
2121
2122   if ((NULL != tc->read_ready) &&
2123       (GNUNET_NETWORK_fdset_isset (tc->write_ready, s5r->sock)) &&
2124       ((len = GNUNET_NETWORK_socket_send (s5r->sock, s5r->wbuf,
2125                                          s5r->wbuf_len)>0)))
2126   {
2127     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2128                 "Successfully sent %d bytes to socket\n",
2129                 len);
2130   }
2131   else
2132   {
2133     
2134     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
2135     s5r->cleanup = GNUNET_YES;
2136     s5r->cleanup_sock = GNUNET_YES;
2137     cleanup_s5r (s5r);
2138     
2139     return;
2140   }
2141
2142   if (GNUNET_YES == s5r->cleanup)
2143   {
2144     cleanup_s5r (s5r);
2145     return;
2146   }
2147
2148   if ((s5r->state == SOCKS5_DATA_TRANSFER) &&
2149       (s5r->fwdrtask == GNUNET_SCHEDULER_NO_TASK))
2150     s5r->fwdrtask =
2151       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2152                                      s5r->remote_sock,
2153                                      &do_read_remote, s5r);
2154 }
2155
2156 /**
2157  * Read from remote end
2158  *
2159  * @param cls closure
2160  * @param tc scheduler context
2161  */
2162 static void
2163 do_read_remote (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2164 {
2165   struct Socks5Request *s5r = cls;
2166   
2167   s5r->fwdrtask = GNUNET_SCHEDULER_NO_TASK;
2168
2169
2170   if ((NULL != tc->write_ready) &&
2171       (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->remote_sock)) &&
2172       (s5r->wbuf_len = GNUNET_NETWORK_socket_recv (s5r->remote_sock, s5r->wbuf,
2173                                          sizeof (s5r->wbuf))))
2174   {
2175     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2176                 "Successfully read %d bytes from remote socket\n",
2177                 s5r->wbuf_len);
2178   }
2179   else
2180   {
2181     if (s5r->wbuf_len == 0)
2182       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2183                   "0 bytes received from remote... graceful shutdown!\n");
2184     if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
2185       GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2186     if (s5r->rtask != GNUNET_SCHEDULER_NO_TASK)
2187       GNUNET_SCHEDULER_cancel (s5r->rtask);
2188     
2189     GNUNET_NETWORK_socket_close (s5r->remote_sock);
2190     s5r->remote_sock = NULL;
2191     GNUNET_NETWORK_socket_close (s5r->sock);
2192     GNUNET_free(s5r);
2193
2194     return;
2195   }
2196   
2197   s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2198                                                s5r->sock,
2199                                                &do_write, s5r);
2200   
2201 }
2202
2203
2204 /**
2205  * Adds a socket to MHD
2206  *
2207  * @param h the handle to the socket to add
2208  * @param daemon the daemon to add the fd to
2209  * @return whatever MHD_add_connection returns
2210  */
2211 static int
2212 add_handle_to_mhd (struct GNUNET_NETWORK_Handle *h, struct MHD_Daemon *daemon)
2213 {
2214   int fd;
2215   struct sockaddr *addr;
2216   socklen_t len;
2217
2218   fd = dup (GNUNET_NETWORK_get_fd (h));
2219   addr = GNUNET_NETWORK_get_addr (h);
2220   len = GNUNET_NETWORK_get_addrlen (h);
2221
2222   return MHD_add_connection (daemon, fd, addr, len);
2223 }
2224
2225 /**
2226  * Read file in filename
2227  *
2228  * @param filename file to read
2229  * @param size pointer where filesize is stored
2230  * @return data
2231  */
2232 static char*
2233 load_file (const char* filename, 
2234            unsigned int* size)
2235 {
2236   char *buffer;
2237   uint64_t fsize;
2238
2239   if (GNUNET_OK !=
2240       GNUNET_DISK_file_size (filename, &fsize,
2241                              GNUNET_YES, GNUNET_YES))
2242     return NULL;
2243   if (fsize > MAX_PEM_SIZE)
2244     return NULL;
2245   *size = (unsigned int) fsize;
2246   buffer = GNUNET_malloc (*size);
2247   if (fsize != GNUNET_DISK_fn_read (filename, buffer, (size_t) fsize))
2248   {
2249     GNUNET_free (buffer);
2250     return NULL;
2251   }
2252   return buffer;
2253 }
2254
2255
2256 /**
2257  * Load PEM key from file
2258  *
2259  * @param key where to store the data
2260  * @param keyfile path to the PEM file
2261  * @return GNUNET_OK on success
2262  */
2263 static int
2264 load_key_from_file (gnutls_x509_privkey_t key, const char* keyfile)
2265 {
2266   gnutls_datum_t key_data;
2267   int ret;
2268
2269   key_data.data = (unsigned char*) load_file (keyfile, &key_data.size);
2270   ret = gnutls_x509_privkey_import (key, &key_data,
2271                                     GNUTLS_X509_FMT_PEM);
2272   if (GNUTLS_E_SUCCESS != ret)
2273   {
2274     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2275                 _("Unable to import private key from file `%s'\n"),
2276                 keyfile);
2277     GNUNET_break (0);
2278   }
2279   GNUNET_free (key_data.data);
2280   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2281 }
2282
2283
2284 /**
2285  * Load cert from file
2286  *
2287  * @param crt struct to store data in
2288  * @param certfile path to pem file
2289  * @return GNUNET_OK on success
2290  */
2291 static int
2292 load_cert_from_file (gnutls_x509_crt_t crt, char* certfile)
2293 {
2294   gnutls_datum_t cert_data;
2295   cert_data.data = NULL;
2296   int ret;
2297
2298   cert_data.data = (unsigned char*) load_file (certfile, &cert_data.size);
2299   ret = gnutls_x509_crt_import (crt, &cert_data,
2300                                 GNUTLS_X509_FMT_PEM);
2301   if (GNUTLS_E_SUCCESS != ret)
2302   {
2303     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2304                _("Unable to import certificate %s\n"), certfile);
2305     GNUNET_break (0);
2306   }
2307   GNUNET_free (cert_data.data);
2308   return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK;
2309 }
2310
2311
2312 /**
2313  * Generate new certificate for specific name
2314  *
2315  * @param name the subject name to generate a cert for
2316  * @return a struct holding the PEM data
2317  */
2318 static struct ProxyGNSCertificate *
2319 generate_gns_certificate (const char *name)
2320 {
2321
2322   int ret;
2323   unsigned int serial;
2324   size_t key_buf_size;
2325   size_t cert_buf_size;
2326   gnutls_x509_crt_t request;
2327   time_t etime;
2328   struct tm *tm_data;
2329
2330   ret = gnutls_x509_crt_init (&request);
2331
2332   if (GNUTLS_E_SUCCESS != ret)
2333   {
2334     GNUNET_break (0);
2335   }
2336
2337   ret = gnutls_x509_crt_set_key (request, proxy_ca.key);
2338
2339   if (GNUTLS_E_SUCCESS != ret)
2340   {
2341     GNUNET_break (0);
2342   }
2343
2344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Generating cert\n");
2345
2346   struct ProxyGNSCertificate *pgc =
2347     GNUNET_malloc (sizeof (struct ProxyGNSCertificate));
2348
2349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding DNs\n");
2350   
2351   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COUNTRY_NAME,
2352                                  0, "DE", 2);
2353
2354   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_ORGANIZATION_NAME,
2355                                  0, "GNUnet", 6);
2356
2357   gnutls_x509_crt_set_dn_by_oid (request, GNUTLS_OID_X520_COMMON_NAME,
2358                                  0, name, strlen (name));
2359
2360   ret = gnutls_x509_crt_set_version (request, 3);
2361
2362   ret = gnutls_rnd (GNUTLS_RND_NONCE, &serial, sizeof (serial));
2363
2364   etime = time (NULL);
2365   tm_data = localtime (&etime);
2366   
2367
2368   ret = gnutls_x509_crt_set_serial (request,
2369                                     &serial,
2370                                     sizeof (serial));
2371
2372   ret = gnutls_x509_crt_set_activation_time (request,
2373                                              etime);
2374   tm_data->tm_year++;
2375   etime = mktime (tm_data);
2376
2377   if (-1 == etime)
2378   {
2379     GNUNET_break (0);
2380   }
2381
2382   ret = gnutls_x509_crt_set_expiration_time (request,
2383                                              etime);
2384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Signing...\n");
2385
2386   ret = gnutls_x509_crt_sign (request, proxy_ca.cert, proxy_ca.key);
2387
2388   key_buf_size = sizeof (pgc->key);
2389   cert_buf_size = sizeof (pgc->cert);
2390
2391   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Exporting certificate...\n");
2392   
2393   gnutls_x509_crt_export (request, GNUTLS_X509_FMT_PEM,
2394                           pgc->cert, &cert_buf_size);
2395
2396   gnutls_x509_privkey_export (proxy_ca.key, GNUTLS_X509_FMT_PEM,
2397                           pgc->key, &key_buf_size);
2398
2399
2400   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n");
2401   gnutls_x509_crt_deinit (request);
2402
2403   return pgc;
2404
2405 }
2406
2407
2408 /*
2409  * Accept policy for mhdaemons
2410  *
2411  * @param cls NULL
2412  * @param addr the sockaddr
2413  * @param addrlen the sockaddr length
2414  * @return MHD_NO if sockaddr is wrong or #conns too high
2415  */
2416 static int
2417 accept_cb (void* cls, const struct sockaddr *addr, socklen_t addrlen)
2418 {
2419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2420               "In MHD accept policy cb\n");
2421
2422   if (addr != NULL)
2423   {
2424     if (addr->sa_family == AF_UNIX)
2425       return MHD_NO;
2426   }
2427
2428   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2429               "Connection accepted\n");
2430
2431   return MHD_YES;
2432 }
2433
2434
2435 /**
2436  * Adds a socket to an SSL MHD instance
2437  * It is important the the domain name is
2438  * correct. In most cases we need to start a new daemon
2439  *
2440  * @param h the handle to add to a daemon
2441  * @param domain the domain the ssl daemon has to serve
2442  * @return MHD_YES on success
2443  */
2444 static int
2445 add_handle_to_ssl_mhd (struct GNUNET_NETWORK_Handle *h, const char* domain)
2446 {
2447   struct MhdHttpList *hd = NULL;
2448   struct ProxyGNSCertificate *pgc;
2449   struct NetworkHandleList *nh;
2450
2451   for (hd = mhd_httpd_head; NULL != hd; hd = hd->next)
2452     if (0 == strcmp (hd->domain, domain))
2453       break;
2454
2455   if (NULL == hd)
2456   {    
2457     pgc = generate_gns_certificate (domain);
2458     
2459     hd = GNUNET_malloc (sizeof (struct MhdHttpList));
2460     hd->is_ssl = GNUNET_YES;
2461     strcpy (hd->domain, domain);
2462     hd->proxy_cert = pgc;
2463
2464     /* Start new MHD */
2465     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2466                 "No previous SSL instance found... starting new one for %s\n",
2467                 domain);
2468
2469     hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL, 4444,
2470             &accept_cb, NULL,
2471             &create_response, hd,
2472             MHD_OPTION_LISTEN_SOCKET, GNUNET_NETWORK_get_fd (mhd_unix_socket),
2473             MHD_OPTION_CONNECTION_LIMIT, MHD_MAX_CONNECTIONS,
2474             MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2475             MHD_OPTION_NOTIFY_COMPLETED,
2476             NULL, NULL,
2477             MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2478             MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2479             MHD_OPTION_END);
2480
2481     GNUNET_assert (hd->daemon != NULL);
2482     hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2483     
2484     GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2485   }
2486
2487   nh = GNUNET_malloc (sizeof (struct NetworkHandleList));
2488   nh->h = h;
2489
2490   GNUNET_CONTAINER_DLL_insert (hd->socket_handles_head,
2491                                hd->socket_handles_tail,
2492                                nh);
2493   
2494   return add_handle_to_mhd (h, hd->daemon);
2495 }
2496
2497
2498
2499 /**
2500  * Read data from incoming connection
2501  *
2502  * @param cls the closure
2503  * @param tc the scheduler context
2504  */
2505 static void
2506 do_read (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2507 {
2508   struct Socks5Request *s5r = cls;
2509   struct socks5_client_hello *c_hello;
2510   struct socks5_server_hello *s_hello;
2511   struct socks5_client_request *c_req;
2512   struct socks5_server_response *s_resp;
2513
2514   int ret;
2515   char domain[256];
2516   uint8_t dom_len;
2517   uint16_t req_port;
2518   struct hostent *phost;
2519   uint32_t remote_ip;
2520   struct sockaddr_in remote_addr;
2521   struct in_addr *r_sin_addr;
2522
2523   struct NetworkHandleList *nh;
2524
2525   s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2526
2527   if ((NULL != tc->write_ready) &&
2528       (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) &&
2529       (s5r->rbuf_len = GNUNET_NETWORK_socket_recv (s5r->sock, s5r->rbuf,
2530                                          sizeof (s5r->rbuf))))
2531   {
2532     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2533                 "Successfully read %d bytes from socket\n",
2534                 s5r->rbuf_len);
2535   }
2536   else
2537   {
2538     if (s5r->rbuf_len != 0)
2539       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
2540     else
2541       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disco!\n");
2542
2543     if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2544       GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2545     if (s5r->wtask != GNUNET_SCHEDULER_NO_TASK)
2546       GNUNET_SCHEDULER_cancel (s5r->wtask);
2547     if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
2548       GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2549     GNUNET_NETWORK_socket_close (s5r->remote_sock);
2550     GNUNET_NETWORK_socket_close (s5r->sock);
2551     GNUNET_free(s5r);
2552     return;
2553   }
2554
2555   if (s5r->state == SOCKS5_INIT)
2556   {
2557     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2558                 "SOCKS5 init\n");
2559     c_hello = (struct socks5_client_hello*)&s5r->rbuf;
2560
2561     GNUNET_assert (c_hello->version == SOCKS_VERSION_5);
2562
2563     s_hello = (struct socks5_server_hello*)&s5r->wbuf;
2564     s5r->wbuf_len = sizeof( struct socks5_server_hello );
2565
2566     s_hello->version = c_hello->version;
2567     s_hello->auth_method = SOCKS_AUTH_NONE;
2568
2569     /* Write response to client */
2570     s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2571                                                 s5r->sock,
2572                                                 &do_write, s5r);
2573
2574     s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2575                                                 s5r->sock,
2576                                                 &do_read, s5r);
2577
2578     s5r->state = SOCKS5_REQUEST;
2579     return;
2580   }
2581
2582   if (s5r->state == SOCKS5_REQUEST)
2583   {
2584     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2585                 "Processing SOCKS5 request\n");
2586     c_req = (struct socks5_client_request*)&s5r->rbuf;
2587     s_resp = (struct socks5_server_response*)&s5r->wbuf;
2588     //Only 10byte for ipv4 response!
2589     s5r->wbuf_len = 10;//sizeof (struct socks5_server_response);
2590
2591     GNUNET_assert (c_req->addr_type == 3);
2592
2593     dom_len = *((uint8_t*)(&(c_req->addr_type) + 1));
2594     memset(domain, 0, sizeof(domain));
2595     strncpy(domain, (char*)(&(c_req->addr_type) + 2), dom_len);
2596     req_port = *((uint16_t*)(&(c_req->addr_type) + 2 + dom_len));
2597
2598     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2599                 "Requested connection is %s:%d\n",
2600                 domain,
2601                 ntohs(req_port));
2602
2603     if (is_tld (domain, GNUNET_GNS_TLD) ||
2604         is_tld (domain, GNUNET_GNS_TLD_ZKEY))
2605     {
2606       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2607                   "Requested connection is gnunet tld\n",
2608                   domain);
2609       
2610       ret = MHD_NO;
2611       if (ntohs(req_port) == HTTPS_PORT)
2612       {
2613         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2614                     "Requested connection is HTTPS\n");
2615         ret = add_handle_to_ssl_mhd ( s5r->sock, domain );
2616       }
2617       else if (NULL != httpd)
2618       {
2619         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2620                     "Requested connection is HTTP\n");
2621         nh = GNUNET_malloc (sizeof (struct NetworkHandleList));
2622         nh->h = s5r->sock;
2623
2624         GNUNET_CONTAINER_DLL_insert (mhd_httpd_head->socket_handles_head,
2625                                mhd_httpd_head->socket_handles_tail,
2626                                nh);
2627
2628         ret = add_handle_to_mhd ( s5r->sock, httpd );
2629       }
2630
2631       if (ret != MHD_YES)
2632       {
2633         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2634                     _("Failed to start HTTP server\n"));
2635         s_resp->version = 0x05;
2636         s_resp->reply = 0x01;
2637         s5r->cleanup = GNUNET_YES;
2638         s5r->cleanup_sock = GNUNET_YES;
2639         s5r->wtask = 
2640           GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2641                                         s5r->sock,
2642                                         &do_write, s5r);
2643         return;
2644       }
2645       
2646       /* Signal success */
2647       s_resp->version = 0x05;
2648       s_resp->reply = 0x00;
2649       s_resp->reserved = 0x00;
2650       s_resp->addr_type = 0x01;
2651       
2652       s5r->cleanup = GNUNET_YES;
2653       s5r->cleanup_sock = GNUNET_NO;
2654       s5r->wtask =
2655         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2656                                         s5r->sock,
2657                                         &do_write, s5r);
2658       run_httpds ();
2659       return;
2660     }
2661     else
2662     {
2663       phost = (struct hostent*)gethostbyname (domain);
2664       if (phost == NULL)
2665       {
2666         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2667                     "Resolve %s error!\n", domain );
2668         s_resp->version = 0x05;
2669         s_resp->reply = 0x01;
2670         s5r->cleanup = GNUNET_YES;
2671         s5r->cleanup_sock = GNUNET_YES;
2672         s5r->wtask = 
2673           GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2674                                           s5r->sock,
2675                                           &do_write, s5r);
2676         return;
2677       }
2678
2679       s5r->remote_sock = GNUNET_NETWORK_socket_create (AF_INET,
2680                                                        SOCK_STREAM,
2681                                                        0);
2682       r_sin_addr = (struct in_addr*)(phost->h_addr);
2683       remote_ip = r_sin_addr->s_addr;
2684       memset(&remote_addr, 0, sizeof(remote_addr));
2685       remote_addr.sin_family = AF_INET;
2686 #if HAVE_SOCKADDR_IN_SIN_LEN
2687       remote_addr.sin_len = sizeof (remote_addr);
2688 #endif
2689       remote_addr.sin_addr.s_addr = remote_ip;
2690       remote_addr.sin_port = req_port;
2691       
2692       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2693                   "target server: %s:%u\n", inet_ntoa(remote_addr.sin_addr),
2694                   ntohs(req_port));
2695
2696       if ((GNUNET_OK !=
2697           GNUNET_NETWORK_socket_connect ( s5r->remote_sock,
2698                                           (const struct sockaddr*)&remote_addr,
2699                                           sizeof (remote_addr)))
2700           && (errno != EINPROGRESS))
2701       {
2702         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "connect");
2703         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2704                     "socket request error...\n");
2705         s_resp->version = 0x05;
2706         s_resp->reply = 0x01;
2707         s5r->wtask =
2708           GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2709                                           s5r->sock,
2710                                           &do_write, s5r);
2711         //TODO see above
2712         return;
2713       }
2714
2715       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2716                   "new remote connection\n");
2717
2718       s_resp->version = 0x05;
2719       s_resp->reply = 0x00;
2720       s_resp->reserved = 0x00;
2721       s_resp->addr_type = 0x01;
2722
2723       s5r->state = SOCKS5_DATA_TRANSFER;
2724
2725       s5r->wtask =
2726         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2727                                         s5r->sock,
2728                                         &do_write, s5r);
2729       s5r->rtask =
2730         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2731                                        s5r->sock,
2732                                        &do_read, s5r);
2733
2734     }
2735     return;
2736   }
2737
2738   if (s5r->state == SOCKS5_DATA_TRANSFER)
2739   {
2740     if ((s5r->remote_sock == NULL) || (s5r->rbuf_len == 0))
2741     {
2742       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2743                   "Closing connection to client\n");
2744       if (s5r->rtask != GNUNET_SCHEDULER_NO_TASK)
2745         GNUNET_SCHEDULER_cancel (s5r->rtask);
2746       if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
2747         GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2748       if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2749         GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2750       if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2751         GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2752       
2753       if (s5r->remote_sock != NULL)
2754         GNUNET_NETWORK_socket_close (s5r->remote_sock);
2755       GNUNET_NETWORK_socket_close (s5r->sock);
2756       GNUNET_free(s5r);
2757       return;
2758     }
2759
2760     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2761                 "forwarding %d bytes from client\n", s5r->rbuf_len);
2762
2763     s5r->fwdwtask =
2764       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2765                                       s5r->remote_sock,
2766                                       &do_write_remote, s5r);
2767
2768     if (s5r->fwdrtask == GNUNET_SCHEDULER_NO_TASK)
2769     {
2770       s5r->fwdrtask =
2771         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2772                                        s5r->remote_sock,
2773                                        &do_read_remote, s5r);
2774     }
2775
2776
2777   }
2778
2779 }
2780
2781
2782 /**
2783  * Accept new incoming connections
2784  *
2785  * @param cls the closure
2786  * @param tc the scheduler context
2787  */
2788 static void
2789 do_accept (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2790 {
2791   struct GNUNET_NETWORK_Handle *s;
2792   struct Socks5Request *s5r;
2793
2794   ltask = GNUNET_SCHEDULER_NO_TASK;
2795   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2796     return;
2797
2798   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2799                                          lsock,
2800                                          &do_accept, NULL);
2801
2802   s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2803
2804   if (NULL == s)
2805   {
2806     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2807     return;
2808   }
2809
2810   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2811               "Got an inbound connection, waiting for data\n");
2812
2813   s5r = GNUNET_malloc (sizeof (struct Socks5Request));
2814   s5r->sock = s;
2815   s5r->state = SOCKS5_INIT;
2816   s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
2817   s5r->fwdwtask = GNUNET_SCHEDULER_NO_TASK;
2818   s5r->fwdrtask = GNUNET_SCHEDULER_NO_TASK;
2819   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2820                                               s5r->sock,
2821                                               &do_read, s5r);
2822 }
2823
2824
2825 /**
2826  * Task run on shutdown
2827  *
2828  * @param cls closure
2829  * @param tc task context
2830  */
2831 static void
2832 do_shutdown (void *cls,
2833              const struct GNUNET_SCHEDULER_TaskContext *tc)
2834 {
2835
2836   struct MhdHttpList *hd;
2837   struct MhdHttpList *tmp_hd;
2838   struct NetworkHandleList *nh;
2839   struct NetworkHandleList *tmp_nh;
2840   struct ProxyCurlTask *ctask;
2841   struct ProxyCurlTask *ctask_tmp;
2842   
2843   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2844               "Shutting down...\n");
2845
2846   gnutls_global_deinit ();
2847
2848   if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
2849   {
2850     GNUNET_SCHEDULER_cancel (curl_download_task);
2851     curl_download_task = GNUNET_SCHEDULER_NO_TASK;
2852   }
2853
2854   for (hd = mhd_httpd_head; hd != NULL; hd = tmp_hd)
2855   {
2856     tmp_hd = hd->next;
2857
2858     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2859                 "Stopping daemon\n");
2860
2861     if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
2862     {
2863       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2864                   "Stopping select task %d\n",
2865                   hd->httpd_task);
2866       GNUNET_SCHEDULER_cancel (hd->httpd_task);
2867       hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2868     }
2869
2870     if (NULL != hd->daemon)
2871     {
2872       MHD_stop_daemon (hd->daemon);
2873       hd->daemon = NULL;
2874     }
2875
2876     for (nh = hd->socket_handles_head; nh != NULL; nh = tmp_nh)
2877     {
2878       tmp_nh = nh->next;
2879
2880       GNUNET_NETWORK_socket_close (nh->h);
2881
2882       GNUNET_free (nh);
2883     }
2884
2885     if (NULL != hd->proxy_cert)
2886     {
2887       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2888                   "Free certificate\n");
2889       GNUNET_free (hd->proxy_cert);
2890     }
2891
2892     GNUNET_free (hd);
2893   }
2894
2895   for (ctask=ctasks_head; ctask != NULL; ctask=ctask_tmp)
2896   {
2897     ctask_tmp = ctask->next;
2898
2899     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2900                 "Cleaning up cURL task\n");
2901
2902     if (ctask->curl != NULL)
2903       curl_easy_cleanup (ctask->curl);
2904     ctask->curl = NULL;
2905     if (NULL != ctask->headers)
2906       curl_slist_free_all (ctask->headers);
2907     if (NULL != ctask->resolver)
2908       curl_slist_free_all (ctask->resolver);
2909
2910     if (NULL != ctask->response)
2911       MHD_destroy_response (ctask->response);
2912
2913
2914     GNUNET_free (ctask);
2915   }
2916   curl_multi_cleanup (curl_multi);
2917
2918   GNUNET_GNS_disconnect (gns_handle);
2919 }
2920
2921
2922 /**
2923  * Compiles a regex for us
2924  *
2925  * @param re ptr to re struct
2926  * @param rt the expression to compile
2927  * @return 0 on success
2928  */
2929 static int
2930 compile_regex (regex_t *re, const char* rt)
2931 {
2932   int status;
2933   char err[1024];
2934
2935   status = regcomp (re, rt, REG_EXTENDED|REG_NEWLINE);
2936   if (status)
2937   {
2938     regerror (status, re, err, 1024);
2939     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2940                 "Regex error compiling '%s': %s\n", rt, err);
2941     return 1;
2942   }
2943   return 0;
2944 }
2945
2946
2947 /**
2948  * Loads the users local zone key
2949  *
2950  * @return GNUNET_YES on success
2951  */
2952 static int
2953 load_local_zone_key (const struct GNUNET_CONFIGURATION_Handle *cfg)
2954 {
2955   char *keyfile;
2956   struct GNUNET_CRYPTO_RsaPrivateKey *key = NULL;
2957   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
2958   struct GNUNET_CRYPTO_ShortHashCode *zone = NULL;
2959   struct GNUNET_CRYPTO_ShortHashAsciiEncoded zonename;
2960
2961   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
2962                                                             "ZONEKEY", &keyfile))
2963   {
2964     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2965                 "Unable to load zone key config value!\n");
2966     return GNUNET_NO;
2967   }
2968
2969   if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
2970   {
2971     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2972                 "Unable to load zone key %s!\n", keyfile);
2973     GNUNET_free(keyfile);
2974     return GNUNET_NO;
2975   }
2976
2977   key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2978   GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
2979   GNUNET_CRYPTO_short_hash(&pkey,
2980                            sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2981                            &local_gns_zone);
2982   zone = &local_gns_zone;
2983   GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
2984   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2985               "Using zone: %s!\n", &zonename);
2986   GNUNET_CRYPTO_rsa_key_free(key);
2987   GNUNET_free(keyfile);
2988   
2989   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
2990                                                    "PRIVATE_ZONEKEY", &keyfile))
2991   {
2992     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2993                 "Unable to load private zone key config value!\n");
2994     return GNUNET_NO;
2995   }
2996
2997   if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
2998   {
2999     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3000                 "Unable to load private zone key %s!\n", keyfile);
3001     GNUNET_free(keyfile);
3002     return GNUNET_NO;
3003   }
3004
3005   key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3006   GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
3007   GNUNET_CRYPTO_short_hash(&pkey,
3008                            sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3009                            &local_private_zone);
3010   GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
3011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3012               "Using private zone: %s!\n", &zonename);
3013   GNUNET_CRYPTO_rsa_key_free(key);
3014   GNUNET_free(keyfile);
3015
3016   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
3017                                                    "SHORTEN_ZONEKEY", &keyfile))
3018   {
3019     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3020                 "Unable to load shorten zone key config value!\n");
3021     return GNUNET_NO;
3022   }
3023
3024   if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
3025   {
3026     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3027                 "Unable to load shorten zone key %s!\n", keyfile);
3028     GNUNET_free(keyfile);
3029     return GNUNET_NO;
3030   }
3031
3032   key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3033   GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
3034   GNUNET_CRYPTO_short_hash(&pkey,
3035                            sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3036                            &local_shorten_zone);
3037   GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
3038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3039               "Using shorten zone: %s!\n", &zonename);
3040   GNUNET_CRYPTO_rsa_key_free(key);
3041   GNUNET_free(keyfile);
3042
3043   return GNUNET_YES;
3044 }
3045
3046 /**
3047  * Main function that will be run
3048  *
3049  * @param cls closure
3050  * @param args remaining command-line arguments
3051  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3052  * @param cfg configuration
3053  */
3054 static void
3055 run (void *cls, char *const *args, const char *cfgfile,
3056      const struct GNUNET_CONFIGURATION_Handle *cfg)
3057 {
3058   struct sockaddr_in sa;
3059   struct MhdHttpList *hd;
3060   struct sockaddr_un mhd_unix_sock_addr;
3061   size_t len;
3062   char* proxy_sockfile;
3063   char* cafile_cfg = NULL;
3064   char* cafile;
3065
3066   curl_multi = curl_multi_init ();
3067
3068   if (NULL == curl_multi)
3069   {
3070     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3071                 "Failed to create cURL multo handle!\n");
3072     return;
3073   }
3074   
3075   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3076               "Loading CA\n");
3077   cafile = cafile_opt;
3078   if (NULL == cafile)
3079   {
3080     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3081                                                           "PROXY_CACERT",
3082                                                           &cafile_cfg))
3083     {
3084       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3085                   "Unable to load proxy CA config value!\n");
3086       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3087                   "No proxy CA provided!\n");
3088       return;
3089     }
3090     cafile = cafile_cfg;
3091   }
3092   
3093   gnutls_global_init ();
3094   gnutls_x509_crt_init (&proxy_ca.cert);
3095   gnutls_x509_privkey_init (&proxy_ca.key);
3096   
3097   if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
3098        (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
3099   {
3100     // FIXME: release resources...
3101     return;
3102   }
3103
3104   GNUNET_free_non_null (cafile_cfg);
3105   
3106   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3107               "Loading Template\n");
3108   
3109   compile_regex (&re_dotplus, (char*) RE_A_HREF);
3110
3111   gns_handle = GNUNET_GNS_connect (cfg);
3112
3113   if (GNUNET_NO == load_local_zone_key (cfg))
3114   {
3115     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3116                 "Unable to load zone!\n");
3117     return;
3118   }
3119
3120   if (NULL == gns_handle)
3121   {
3122     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3123                 "Unable to connect to GNS!\n");
3124     return;
3125   }
3126
3127   memset (&sa, 0, sizeof (sa));
3128   sa.sin_family = AF_INET;
3129   sa.sin_port = htons (port);
3130 #if HAVE_SOCKADDR_IN_SIN_LEN
3131   sa.sin_len = sizeof (sa);
3132 #endif
3133
3134   lsock = GNUNET_NETWORK_socket_create (AF_INET,
3135                                         SOCK_STREAM,
3136                                         0);
3137
3138   if ((NULL == lsock) ||
3139       (GNUNET_OK !=
3140        GNUNET_NETWORK_socket_bind (lsock, (const struct sockaddr *) &sa,
3141                                    sizeof (sa))))
3142   {
3143     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3144                 "Failed to create listen socket bound to `%s'",
3145                 GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)));
3146     if (NULL != lsock)
3147       GNUNET_NETWORK_socket_close (lsock);
3148     return;
3149   }
3150
3151   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock, 5))
3152   {
3153     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3154                 "Failed to listen on socket bound to `%s'",
3155                 GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)));
3156     return;
3157   }
3158
3159   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3160                                          lsock, &do_accept, NULL);
3161
3162   ctasks_head = NULL;
3163   ctasks_tail = NULL;
3164
3165   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3166   {
3167     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3168                 "cURL global init failed!\n");
3169     return;
3170   }
3171
3172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3173               "Proxy listens on port %u\n",
3174               port);
3175
3176   mhd_httpd_head = NULL;
3177   mhd_httpd_tail = NULL;
3178   total_mhd_connections = 0;
3179
3180   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3181                                                             "PROXY_UNIXPATH",
3182                                                             &proxy_sockfile))
3183   {
3184     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3185                 "Specify PROXY_UNIXPATH in gns-proxy config section!\n");
3186     return;
3187   }
3188   
3189   mhd_unix_socket = GNUNET_NETWORK_socket_create (AF_UNIX,
3190                                                 SOCK_STREAM,
3191                                                 0);
3192
3193   if (NULL == mhd_unix_socket)
3194   {
3195     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3196                 "Unable to create unix domain socket!\n");
3197     return;
3198   }
3199
3200   mhd_unix_sock_addr.sun_family = AF_UNIX;
3201   strcpy (mhd_unix_sock_addr.sun_path, proxy_sockfile);
3202
3203 #if LINUX
3204   mhd_unix_sock_addr.sun_path[0] = '\0';
3205 #endif
3206 #if HAVE_SOCKADDR_IN_SIN_LEN
3207   mhd_unix_sock_addr.sun_len = (u_char) sizeof (struct sockaddr_un);
3208 #endif
3209
3210   len = strlen (proxy_sockfile) + sizeof(AF_UNIX);
3211
3212   GNUNET_free (proxy_sockfile);
3213
3214   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (mhd_unix_socket,
3215                                (struct sockaddr*)&mhd_unix_sock_addr,
3216                                len))
3217   {
3218     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3219                 "Unable to bind unix domain socket!\n");
3220     return;
3221   }
3222
3223   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (mhd_unix_socket,
3224                                                  1))
3225   {
3226     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3227                 "Unable to listen on unix domain socket!\n");
3228     return;
3229   }
3230
3231   hd = GNUNET_malloc (sizeof (struct MhdHttpList));
3232   hd->is_ssl = GNUNET_NO;
3233   strcpy (hd->domain, "");
3234   httpd = MHD_start_daemon (MHD_USE_DEBUG, 4444, //Dummy port
3235             &accept_cb, NULL,
3236             &create_response, hd,
3237             MHD_OPTION_LISTEN_SOCKET, GNUNET_NETWORK_get_fd (mhd_unix_socket),
3238             MHD_OPTION_CONNECTION_LIMIT, MHD_MAX_CONNECTIONS,
3239             MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3240             MHD_OPTION_NOTIFY_COMPLETED,
3241             NULL, NULL,
3242             MHD_OPTION_END);
3243
3244   GNUNET_assert (httpd != NULL);
3245   hd->daemon = httpd;
3246   hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
3247
3248   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
3249
3250   run_httpds ();
3251
3252   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
3253                                 &do_shutdown, NULL);
3254
3255 }
3256
3257
3258 /**
3259  * The main function for gnunet-gns-proxy.
3260  *
3261  * @param argc number of arguments from the command line
3262  * @param argv command line arguments
3263  * @return 0 ok, 1 on error
3264  */
3265 int
3266 main (int argc, char *const *argv)
3267 {
3268   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3269     {'p', "port", NULL,
3270      gettext_noop ("listen on specified port"), 1,
3271      &GNUNET_GETOPT_set_string, &port},
3272     {'a', "authority", NULL,
3273       gettext_noop ("pem file to use as CA"), 1,
3274       &GNUNET_GETOPT_set_string, &cafile_opt},
3275     GNUNET_GETOPT_OPTION_END
3276   };
3277
3278   int ret;
3279
3280   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3281     return 2;
3282
3283
3284   GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3285   ret =
3286       (GNUNET_OK ==
3287        GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3288                            _("GNUnet GNS proxy"),
3289                            options,
3290                            &run, NULL)) ? 0 : 1;
3291   GNUNET_free_non_null ((char*)argv);
3292
3293   return ret;
3294 }
3295
3296
3297
3298