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