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