310416f6f123c332e74383e4d0cdf66e6cfa212e
[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
2489     hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL, 4444,
2490             &accept_cb, NULL,
2491             &create_response, hd,
2492             MHD_OPTION_LISTEN_SOCKET, GNUNET_NETWORK_get_fd (mhd_unix_socket),
2493             MHD_OPTION_CONNECTION_LIMIT, MHD_MAX_CONNECTIONS,
2494             MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
2495             MHD_OPTION_NOTIFY_COMPLETED,
2496             NULL, NULL,
2497             MHD_OPTION_HTTPS_MEM_KEY, pgc->key,
2498             MHD_OPTION_HTTPS_MEM_CERT, pgc->cert,
2499             MHD_OPTION_END);
2500
2501     GNUNET_assert (hd->daemon != NULL);
2502     hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2503     
2504     GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
2505   }
2506
2507   nh = GNUNET_malloc (sizeof (struct NetworkHandleList));
2508   nh->h = h;
2509
2510   GNUNET_CONTAINER_DLL_insert (hd->socket_handles_head,
2511                                hd->socket_handles_tail,
2512                                nh);
2513   
2514   return add_handle_to_mhd (h, hd->daemon);
2515 }
2516
2517
2518
2519 /**
2520  * Read data from incoming connection
2521  *
2522  * @param cls the closure
2523  * @param tc the scheduler context
2524  */
2525 static void
2526 do_read (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2527 {
2528   struct Socks5Request *s5r = cls;
2529   struct socks5_client_hello *c_hello;
2530   struct socks5_server_hello *s_hello;
2531   struct socks5_client_request *c_req;
2532   struct socks5_server_response *s_resp;
2533
2534   int ret;
2535   char domain[256];
2536   uint8_t dom_len;
2537   uint16_t req_port;
2538   struct hostent *phost;
2539   uint32_t remote_ip;
2540   struct sockaddr_in remote_addr;
2541   struct in_addr *r_sin_addr;
2542
2543   struct NetworkHandleList *nh;
2544
2545   s5r->rtask = GNUNET_SCHEDULER_NO_TASK;
2546
2547   if ((NULL != tc->write_ready) &&
2548       (GNUNET_NETWORK_fdset_isset (tc->read_ready, s5r->sock)) &&
2549       (s5r->rbuf_len = GNUNET_NETWORK_socket_recv (s5r->sock, s5r->rbuf,
2550                                          sizeof (s5r->rbuf))))
2551   {
2552     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2553                 "Successfully read %d bytes from socket\n",
2554                 s5r->rbuf_len);
2555   }
2556   else
2557   {
2558     if (s5r->rbuf_len != 0)
2559       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
2560     else
2561       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disco!\n");
2562
2563     if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2564       GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2565     if (s5r->wtask != GNUNET_SCHEDULER_NO_TASK)
2566       GNUNET_SCHEDULER_cancel (s5r->wtask);
2567     if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
2568       GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2569     GNUNET_NETWORK_socket_close (s5r->remote_sock);
2570     GNUNET_NETWORK_socket_close (s5r->sock);
2571     GNUNET_free(s5r);
2572     return;
2573   }
2574
2575   if (s5r->state == SOCKS5_INIT)
2576   {
2577     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2578                 "SOCKS5 init\n");
2579     c_hello = (struct socks5_client_hello*)&s5r->rbuf;
2580
2581     GNUNET_assert (c_hello->version == SOCKS_VERSION_5);
2582
2583     s_hello = (struct socks5_server_hello*)&s5r->wbuf;
2584     s5r->wbuf_len = sizeof( struct socks5_server_hello );
2585
2586     s_hello->version = c_hello->version;
2587     s_hello->auth_method = SOCKS_AUTH_NONE;
2588
2589     /* Write response to client */
2590     s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2591                                                 s5r->sock,
2592                                                 &do_write, s5r);
2593
2594     s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2595                                                 s5r->sock,
2596                                                 &do_read, s5r);
2597
2598     s5r->state = SOCKS5_REQUEST;
2599     return;
2600   }
2601
2602   if (s5r->state == SOCKS5_REQUEST)
2603   {
2604     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2605                 "Processing SOCKS5 request\n");
2606     c_req = (struct socks5_client_request*)&s5r->rbuf;
2607     s_resp = (struct socks5_server_response*)&s5r->wbuf;
2608     //Only 10byte for ipv4 response!
2609     s5r->wbuf_len = 10;//sizeof (struct socks5_server_response);
2610
2611     GNUNET_assert (c_req->addr_type == 3);
2612
2613     dom_len = *((uint8_t*)(&(c_req->addr_type) + 1));
2614     memset(domain, 0, sizeof(domain));
2615     strncpy(domain, (char*)(&(c_req->addr_type) + 2), dom_len);
2616     req_port = *((uint16_t*)(&(c_req->addr_type) + 2 + dom_len));
2617
2618     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2619                 "Requested connection is %s:%d\n",
2620                 domain,
2621                 ntohs(req_port));
2622
2623     if (is_tld (domain, GNUNET_GNS_TLD) ||
2624         is_tld (domain, GNUNET_GNS_TLD_ZKEY))
2625     {
2626       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2627                   "Requested connection is gnunet tld\n",
2628                   domain);
2629       
2630       ret = MHD_NO;
2631       if (ntohs(req_port) == HTTPS_PORT)
2632       {
2633         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2634                     "Requested connection is HTTPS\n");
2635         ret = add_handle_to_ssl_mhd ( s5r->sock, domain );
2636       }
2637       else if (NULL != httpd)
2638       {
2639         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2640                     "Requested connection is HTTP\n");
2641         nh = GNUNET_malloc (sizeof (struct NetworkHandleList));
2642         nh->h = s5r->sock;
2643
2644         GNUNET_CONTAINER_DLL_insert (mhd_httpd_head->socket_handles_head,
2645                                mhd_httpd_head->socket_handles_tail,
2646                                nh);
2647
2648         ret = add_handle_to_mhd ( s5r->sock, httpd );
2649       }
2650
2651       if (ret != MHD_YES)
2652       {
2653         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2654                     _("Failed to start HTTP server\n"));
2655         s_resp->version = 0x05;
2656         s_resp->reply = 0x01;
2657         s5r->cleanup = GNUNET_YES;
2658         s5r->cleanup_sock = GNUNET_YES;
2659         s5r->wtask = 
2660           GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2661                                         s5r->sock,
2662                                         &do_write, s5r);
2663         return;
2664       }
2665       
2666       /* Signal success */
2667       s_resp->version = 0x05;
2668       s_resp->reply = 0x00;
2669       s_resp->reserved = 0x00;
2670       s_resp->addr_type = 0x01;
2671       
2672       s5r->cleanup = GNUNET_YES;
2673       s5r->cleanup_sock = GNUNET_NO;
2674       s5r->wtask =
2675         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2676                                         s5r->sock,
2677                                         &do_write, s5r);
2678       run_httpds ();
2679       return;
2680     }
2681     else
2682     {
2683       phost = (struct hostent*)gethostbyname (domain);
2684       if (phost == NULL)
2685       {
2686         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2687                     "Resolve %s error!\n", domain );
2688         s_resp->version = 0x05;
2689         s_resp->reply = 0x01;
2690         s5r->cleanup = GNUNET_YES;
2691         s5r->cleanup_sock = GNUNET_YES;
2692         s5r->wtask = 
2693           GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2694                                           s5r->sock,
2695                                           &do_write, s5r);
2696         return;
2697       }
2698
2699       s5r->remote_sock = GNUNET_NETWORK_socket_create (AF_INET,
2700                                                        SOCK_STREAM,
2701                                                        0);
2702       r_sin_addr = (struct in_addr*)(phost->h_addr);
2703       remote_ip = r_sin_addr->s_addr;
2704       memset(&remote_addr, 0, sizeof(remote_addr));
2705       remote_addr.sin_family = AF_INET;
2706 #if HAVE_SOCKADDR_IN_SIN_LEN
2707       remote_addr.sin_len = sizeof (remote_addr);
2708 #endif
2709       remote_addr.sin_addr.s_addr = remote_ip;
2710       remote_addr.sin_port = req_port;
2711       
2712       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2713                   "target server: %s:%u\n", inet_ntoa(remote_addr.sin_addr),
2714                   ntohs(req_port));
2715
2716       if ((GNUNET_OK !=
2717           GNUNET_NETWORK_socket_connect ( s5r->remote_sock,
2718                                           (const struct sockaddr*)&remote_addr,
2719                                           sizeof (remote_addr)))
2720           && (errno != EINPROGRESS))
2721       {
2722         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "connect");
2723         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2724                     "socket request error...\n");
2725         s_resp->version = 0x05;
2726         s_resp->reply = 0x01;
2727         s5r->wtask =
2728           GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2729                                           s5r->sock,
2730                                           &do_write, s5r);
2731         //TODO see above
2732         return;
2733       }
2734
2735       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2736                   "new remote connection\n");
2737
2738       s_resp->version = 0x05;
2739       s_resp->reply = 0x00;
2740       s_resp->reserved = 0x00;
2741       s_resp->addr_type = 0x01;
2742
2743       s5r->state = SOCKS5_DATA_TRANSFER;
2744
2745       s5r->wtask =
2746         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2747                                         s5r->sock,
2748                                         &do_write, s5r);
2749       s5r->rtask =
2750         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2751                                        s5r->sock,
2752                                        &do_read, s5r);
2753
2754     }
2755     return;
2756   }
2757
2758   if (s5r->state == SOCKS5_DATA_TRANSFER)
2759   {
2760     if ((s5r->remote_sock == NULL) || (s5r->rbuf_len == 0))
2761     {
2762       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2763                   "Closing connection to client\n");
2764       if (s5r->rtask != GNUNET_SCHEDULER_NO_TASK)
2765         GNUNET_SCHEDULER_cancel (s5r->rtask);
2766       if (s5r->fwdwtask != GNUNET_SCHEDULER_NO_TASK)
2767         GNUNET_SCHEDULER_cancel (s5r->fwdwtask);
2768       if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2769         GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2770       if (s5r->fwdrtask != GNUNET_SCHEDULER_NO_TASK)
2771         GNUNET_SCHEDULER_cancel (s5r->fwdrtask);
2772       
2773       if (s5r->remote_sock != NULL)
2774         GNUNET_NETWORK_socket_close (s5r->remote_sock);
2775       GNUNET_NETWORK_socket_close (s5r->sock);
2776       GNUNET_free(s5r);
2777       return;
2778     }
2779
2780     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2781                 "forwarding %d bytes from client\n", s5r->rbuf_len);
2782
2783     s5r->fwdwtask =
2784       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2785                                       s5r->remote_sock,
2786                                       &do_write_remote, s5r);
2787
2788     if (s5r->fwdrtask == GNUNET_SCHEDULER_NO_TASK)
2789     {
2790       s5r->fwdrtask =
2791         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2792                                        s5r->remote_sock,
2793                                        &do_read_remote, s5r);
2794     }
2795
2796
2797   }
2798
2799 }
2800
2801
2802 /**
2803  * Accept new incoming connections
2804  *
2805  * @param cls the closure
2806  * @param tc the scheduler context
2807  */
2808 static void
2809 do_accept (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2810 {
2811   struct GNUNET_NETWORK_Handle *s;
2812   struct Socks5Request *s5r;
2813
2814   ltask = GNUNET_SCHEDULER_NO_TASK;
2815   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2816     return;
2817
2818   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2819                                          lsock,
2820                                          &do_accept, NULL);
2821
2822   s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
2823
2824   if (NULL == s)
2825   {
2826     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
2827     return;
2828   }
2829
2830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2831               "Got an inbound connection, waiting for data\n");
2832
2833   s5r = GNUNET_malloc (sizeof (struct Socks5Request));
2834   s5r->sock = s;
2835   s5r->state = SOCKS5_INIT;
2836   s5r->wtask = GNUNET_SCHEDULER_NO_TASK;
2837   s5r->fwdwtask = GNUNET_SCHEDULER_NO_TASK;
2838   s5r->fwdrtask = GNUNET_SCHEDULER_NO_TASK;
2839   s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2840                                               s5r->sock,
2841                                               &do_read, s5r);
2842 }
2843
2844
2845 /**
2846  * Task run on shutdown
2847  *
2848  * @param cls closure
2849  * @param tc task context
2850  */
2851 static void
2852 do_shutdown (void *cls,
2853              const struct GNUNET_SCHEDULER_TaskContext *tc)
2854 {
2855
2856   struct MhdHttpList *hd;
2857   struct MhdHttpList *tmp_hd;
2858   struct NetworkHandleList *nh;
2859   struct NetworkHandleList *tmp_nh;
2860   struct ProxyCurlTask *ctask;
2861   struct ProxyCurlTask *ctask_tmp;
2862   
2863   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2864               "Shutting down...\n");
2865
2866   gnutls_global_deinit ();
2867  
2868   if (NULL != local_gns_zone)
2869     GNUNET_free (local_gns_zone); 
2870   if (NULL != local_private_zone)
2871     GNUNET_free (local_private_zone);
2872   if (NULL != local_shorten_zone)
2873     GNUNET_free (local_shorten_zone);
2874
2875   if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
2876   {
2877     GNUNET_SCHEDULER_cancel (curl_download_task);
2878     curl_download_task = GNUNET_SCHEDULER_NO_TASK;
2879   }
2880
2881   for (hd = mhd_httpd_head; hd != NULL; hd = tmp_hd)
2882   {
2883     tmp_hd = hd->next;
2884
2885     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2886                 "Stopping daemon\n");
2887
2888     if (GNUNET_SCHEDULER_NO_TASK != hd->httpd_task)
2889     {
2890       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2891                   "Stopping select task %d\n",
2892                   hd->httpd_task);
2893       GNUNET_SCHEDULER_cancel (hd->httpd_task);
2894       hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
2895     }
2896
2897     if (NULL != hd->daemon)
2898     {
2899       MHD_stop_daemon (hd->daemon);
2900       hd->daemon = NULL;
2901     }
2902
2903     for (nh = hd->socket_handles_head; nh != NULL; nh = tmp_nh)
2904     {
2905       tmp_nh = nh->next;
2906
2907       GNUNET_NETWORK_socket_close (nh->h);
2908
2909       GNUNET_free (nh);
2910     }
2911
2912     if (NULL != hd->proxy_cert)
2913     {
2914       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2915                   "Free certificate\n");
2916       GNUNET_free (hd->proxy_cert);
2917     }
2918
2919     GNUNET_free (hd);
2920   }
2921
2922   for (ctask=ctasks_head; ctask != NULL; ctask=ctask_tmp)
2923   {
2924     ctask_tmp = ctask->next;
2925
2926     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2927                 "Cleaning up cURL task\n");
2928
2929     if (ctask->curl != NULL)
2930       curl_easy_cleanup (ctask->curl);
2931     ctask->curl = NULL;
2932     if (NULL != ctask->headers)
2933       curl_slist_free_all (ctask->headers);
2934     if (NULL != ctask->resolver)
2935       curl_slist_free_all (ctask->resolver);
2936
2937     if (NULL != ctask->response)
2938       MHD_destroy_response (ctask->response);
2939
2940
2941     GNUNET_free (ctask);
2942   }
2943   curl_multi_cleanup (curl_multi);
2944
2945   GNUNET_GNS_disconnect (gns_handle);
2946 }
2947
2948
2949 /**
2950  * Compiles a regex for us
2951  *
2952  * @param re ptr to re struct
2953  * @param rt the expression to compile
2954  * @return 0 on success
2955  */
2956 static int
2957 compile_regex (regex_t *re, const char* rt)
2958 {
2959   int status;
2960   char err[1024];
2961
2962   status = regcomp (re, rt, REG_EXTENDED|REG_NEWLINE);
2963   if (status)
2964   {
2965     regerror (status, re, err, 1024);
2966     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2967                 "Regex error compiling '%s': %s\n", rt, err);
2968     return 1;
2969   }
2970   return 0;
2971 }
2972
2973
2974 /**
2975  * Loads the users local zone key
2976  *
2977  * @return GNUNET_YES on success
2978  */
2979 static int
2980 load_local_zone_key (const struct GNUNET_CONFIGURATION_Handle *cfg)
2981 {
2982   char *keyfile;
2983   struct GNUNET_CRYPTO_RsaPrivateKey *key = NULL;
2984   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
2985   struct GNUNET_CRYPTO_ShortHashCode *zone = NULL;
2986   struct GNUNET_CRYPTO_ShortHashAsciiEncoded zonename;
2987
2988   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
2989                                                             "ZONEKEY", &keyfile))
2990   {
2991     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2992                 "Unable to load zone key config value!\n");
2993     return GNUNET_NO;
2994   }
2995
2996   if (GNUNET_NO == GNUNET_DISK_file_test (keyfile))
2997   {
2998     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2999                 "Unable to load zone key %s!\n", keyfile);
3000     GNUNET_free(keyfile);
3001     return GNUNET_NO;
3002   }
3003
3004   key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3005   GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
3006   local_gns_zone = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_ShortHashCode));
3007   GNUNET_CRYPTO_short_hash(&pkey,
3008                            sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3009                            local_gns_zone);
3010   zone = local_gns_zone;
3011   GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
3012   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3013               "Using zone: %s!\n", &zonename);
3014   GNUNET_CRYPTO_rsa_key_free(key);
3015   GNUNET_free(keyfile);
3016   keyfile = NULL;
3017
3018   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
3019                                                    "PRIVATE_ZONEKEY", &keyfile))
3020   {
3021     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3022                 "Unable to load private zone key config value!\n");
3023   }
3024
3025   if ((NULL != keyfile) && (GNUNET_NO == GNUNET_DISK_file_test (keyfile)))
3026   {
3027     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3028                 "Unable to load private zone key %s!\n", keyfile);
3029     GNUNET_free(keyfile);
3030   }
3031   else
3032   {
3033     key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3034     GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
3035     local_private_zone = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_ShortHashCode));
3036     GNUNET_CRYPTO_short_hash(&pkey,
3037                              sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3038                              local_private_zone);
3039     GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
3040     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3041                 "Using private zone: %s!\n", &zonename);
3042     GNUNET_CRYPTO_rsa_key_free(key);
3043     GNUNET_free(keyfile);
3044   }
3045   keyfile = NULL;
3046
3047   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
3048                                                    "SHORTEN_ZONEKEY", &keyfile))
3049   {
3050     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3051                 "Unable to load shorten zone key config value!\n");
3052   }
3053
3054   if ((NULL != keyfile) && (GNUNET_NO == GNUNET_DISK_file_test (keyfile)))
3055   {
3056     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3057                 "Unable to load shorten zone key %s!\n", keyfile);
3058     GNUNET_free(keyfile);
3059   }
3060   else
3061   {
3062     key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3063     GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
3064     local_shorten_zone = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_ShortHashCode));
3065     GNUNET_CRYPTO_short_hash(&pkey,
3066                              sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3067                              local_shorten_zone);
3068     GNUNET_CRYPTO_short_hash_to_enc (zone, &zonename);
3069     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3070                 "Using shorten zone: %s!\n", &zonename);
3071     GNUNET_CRYPTO_rsa_key_free(key);
3072     GNUNET_free(keyfile);
3073   }
3074
3075   return GNUNET_YES;
3076 }
3077
3078 /**
3079  * Main function that will be run
3080  *
3081  * @param cls closure
3082  * @param args remaining command-line arguments
3083  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
3084  * @param cfg configuration
3085  */
3086 static void
3087 run (void *cls, char *const *args, const char *cfgfile,
3088      const struct GNUNET_CONFIGURATION_Handle *cfg)
3089 {
3090   struct sockaddr_in sa;
3091   struct MhdHttpList *hd;
3092   struct sockaddr_un mhd_unix_sock_addr;
3093   size_t len;
3094   char* proxy_sockfile;
3095   char* cafile_cfg = NULL;
3096   char* cafile;
3097
3098   curl_multi = curl_multi_init ();
3099
3100   if (NULL == curl_multi)
3101   {
3102     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3103                 "Failed to create cURL multo handle!\n");
3104     return;
3105   }
3106   
3107   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3108               "Loading CA\n");
3109   cafile = cafile_opt;
3110   if (NULL == cafile)
3111   {
3112     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3113                                                           "PROXY_CACERT",
3114                                                           &cafile_cfg))
3115     {
3116       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3117                   "Unable to load proxy CA config value!\n");
3118       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3119                   "No proxy CA provided!\n");
3120       return;
3121     }
3122     cafile = cafile_cfg;
3123   }
3124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3125               "Using %s as CA\n", cafile);
3126   
3127   gnutls_global_init ();
3128   gnutls_x509_crt_init (&proxy_ca.cert);
3129   gnutls_x509_privkey_init (&proxy_ca.key);
3130   
3131   if ( (GNUNET_OK != load_cert_from_file (proxy_ca.cert, cafile)) ||
3132        (GNUNET_OK != load_key_from_file (proxy_ca.key, cafile)) )
3133   {
3134     // FIXME: release resources...
3135     return;
3136   }
3137
3138   GNUNET_free_non_null (cafile_cfg);
3139   
3140   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3141               "Loading Template\n");
3142   
3143   compile_regex (&re_dotplus, (char*) RE_A_HREF);
3144
3145   gns_handle = GNUNET_GNS_connect (cfg);
3146
3147   if (GNUNET_NO == load_local_zone_key (cfg))
3148   {
3149     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3150                 "Unable to load zone!\n");
3151     return;
3152   }
3153
3154   if (NULL == gns_handle)
3155   {
3156     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3157                 "Unable to connect to GNS!\n");
3158     return;
3159   }
3160
3161   memset (&sa, 0, sizeof (sa));
3162   sa.sin_family = AF_INET;
3163   sa.sin_port = htons (port);
3164 #if HAVE_SOCKADDR_IN_SIN_LEN
3165   sa.sin_len = sizeof (sa);
3166 #endif
3167
3168   lsock = GNUNET_NETWORK_socket_create (AF_INET,
3169                                         SOCK_STREAM,
3170                                         0);
3171
3172   if ((NULL == lsock) ||
3173       (GNUNET_OK !=
3174        GNUNET_NETWORK_socket_bind (lsock, (const struct sockaddr *) &sa,
3175                                    sizeof (sa))))
3176   {
3177     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3178                 "Failed to create listen socket bound to `%s'",
3179                 GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)));
3180     if (NULL != lsock)
3181       GNUNET_NETWORK_socket_close (lsock);
3182     return;
3183   }
3184
3185   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock, 5))
3186   {
3187     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3188                 "Failed to listen on socket bound to `%s'",
3189                 GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)));
3190     return;
3191   }
3192
3193   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3194                                          lsock, &do_accept, NULL);
3195
3196   ctasks_head = NULL;
3197   ctasks_tail = NULL;
3198
3199   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
3200   {
3201     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3202                 "cURL global init failed!\n");
3203     return;
3204   }
3205
3206   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3207               "Proxy listens on port %u\n",
3208               port);
3209
3210   mhd_httpd_head = NULL;
3211   mhd_httpd_tail = NULL;
3212   total_mhd_connections = 0;
3213
3214   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns-proxy",
3215                                                             "PROXY_UNIXPATH",
3216                                                             &proxy_sockfile))
3217   {
3218     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3219                 "Specify PROXY_UNIXPATH in gns-proxy config section!\n");
3220     return;
3221   }
3222   
3223   mhd_unix_socket = GNUNET_NETWORK_socket_create (AF_UNIX,
3224                                                 SOCK_STREAM,
3225                                                 0);
3226
3227   if (NULL == mhd_unix_socket)
3228   {
3229     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3230                 "Unable to create unix domain socket!\n");
3231     return;
3232   }
3233
3234   mhd_unix_sock_addr.sun_family = AF_UNIX;
3235   strcpy (mhd_unix_sock_addr.sun_path, proxy_sockfile);
3236
3237 #if LINUX
3238   mhd_unix_sock_addr.sun_path[0] = '\0';
3239 #endif
3240 #if HAVE_SOCKADDR_IN_SIN_LEN
3241   mhd_unix_sock_addr.sun_len = (u_char) sizeof (struct sockaddr_un);
3242 #endif
3243
3244   len = strlen (proxy_sockfile) + sizeof(AF_UNIX);
3245
3246   GNUNET_free (proxy_sockfile);
3247
3248   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (mhd_unix_socket,
3249                                (struct sockaddr*)&mhd_unix_sock_addr,
3250                                len))
3251   {
3252     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3253                 "Unable to bind unix domain socket!\n");
3254     return;
3255   }
3256
3257   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (mhd_unix_socket,
3258                                                  1))
3259   {
3260     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3261                 "Unable to listen on unix domain socket!\n");
3262     return;
3263   }
3264
3265   hd = GNUNET_malloc (sizeof (struct MhdHttpList));
3266   hd->is_ssl = GNUNET_NO;
3267   strcpy (hd->domain, "");
3268   httpd = MHD_start_daemon (MHD_USE_DEBUG, 4444, //Dummy port
3269             &accept_cb, NULL,
3270             &create_response, hd,
3271             MHD_OPTION_LISTEN_SOCKET, GNUNET_NETWORK_get_fd (mhd_unix_socket),
3272             MHD_OPTION_CONNECTION_LIMIT, MHD_MAX_CONNECTIONS,
3273             MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
3274             MHD_OPTION_NOTIFY_COMPLETED,
3275             NULL, NULL,
3276             MHD_OPTION_END);
3277
3278   GNUNET_assert (httpd != NULL);
3279   hd->daemon = httpd;
3280   hd->httpd_task = GNUNET_SCHEDULER_NO_TASK;
3281
3282   GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, mhd_httpd_tail, hd);
3283
3284   run_httpds ();
3285
3286   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
3287                                 &do_shutdown, NULL);
3288
3289 }
3290
3291
3292 /**
3293  * The main function for gnunet-gns-proxy.
3294  *
3295  * @param argc number of arguments from the command line
3296  * @param argv command line arguments
3297  * @return 0 ok, 1 on error
3298  */
3299 int
3300 main (int argc, char *const *argv)
3301 {
3302   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3303     {'p', "port", NULL,
3304      gettext_noop ("listen on specified port"), 1,
3305      &GNUNET_GETOPT_set_string, &port},
3306     {'a', "authority", NULL,
3307       gettext_noop ("pem file to use as CA"), 1,
3308       &GNUNET_GETOPT_set_string, &cafile_opt},
3309     GNUNET_GETOPT_OPTION_END
3310   };
3311
3312   int ret;
3313
3314   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
3315     return 2;
3316
3317
3318   GNUNET_log_setup ("gnunet-gns-proxy", "WARNING", NULL);
3319   ret =
3320       (GNUNET_OK ==
3321        GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-proxy",
3322                            _("GNUnet GNS proxy"),
3323                            options,
3324                            &run, NULL)) ? 0 : 1;
3325   GNUNET_free_non_null ((char*)argv);
3326
3327   return ret;
3328 }
3329
3330
3331
3332