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