159b0853f6500753b481ae06e2ccb182c43dd5a3
[oweals/gnunet.git] / src / transport / plugin_transport_http_server.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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 /**
22  * @file transport/plugin_transport_http.c
23  * @brief http transport service plugin
24  * @author Matthias Wachs
25  */
26
27 #include "plugin_transport_http.h"
28
29 #define HTTP_ERROR_RESPONSE "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"><HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>Not Found</H1>The requested URL was not found on this server.<P><HR><ADDRESS></ADDRESS></BODY></HTML>"
30 #define _RECEIVE 0
31 #define _SEND 1
32
33 struct ServerConnection
34 {
35   /* _RECV or _SEND */
36   int direction;
37
38   /* should this connection get disconnected? GNUNET_YES/NO  */
39   int disconnect;
40
41   struct Session *session;
42   struct MHD_Connection *mhd_conn;
43 };
44
45 /**
46  * Function that queries MHD's select sets and
47  * starts the task waiting for them.
48  * @param plugin plugin
49  * @param daemon_handle the MHD daemon handle
50  * @return gnunet task identifier
51  */
52 static GNUNET_SCHEDULER_TaskIdentifier
53 server_schedule (struct Plugin *plugin, struct MHD_Daemon *daemon_handle,
54                  int now);
55
56 static void
57 server_log (void *arg, const char *fmt, va_list ap)
58 {
59   char text[1024];
60
61   vsnprintf (text, sizeof (text), fmt, ap);
62   va_end (ap);
63   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Server: %s\n", text);
64 }
65
66 /**
67  * Check if incoming connection is accepted.
68  * NOTE: Here every connection is accepted
69  * @param cls plugin as closure
70  * @param addr address of incoming connection
71  * @param addr_len address length of incoming connection
72  * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
73  *
74  */
75 static int
76 server_accept_cb (void *cls, const struct sockaddr *addr, socklen_t addr_len)
77 {
78   struct Plugin *plugin = cls;
79
80   if (plugin->cur_connections <= plugin->max_connections)
81     return MHD_YES;
82   else
83   {
84     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
85                 "Server: Cannot accept new connections\n");
86     return MHD_NO;
87   }
88 }
89
90
91 #if BUILD_HTTPS
92 static char *
93 server_load_file (const char *file)
94 {
95   struct GNUNET_DISK_FileHandle *gn_file;
96   struct stat fstat;
97   char *text = NULL;
98
99   if (0 != STAT (file, &fstat))
100     return NULL;
101   text = GNUNET_malloc (fstat.st_size + 1);
102   gn_file =
103       GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
104                              GNUNET_DISK_PERM_USER_READ);
105   if (gn_file == NULL)
106   {
107     GNUNET_free (text);
108     return NULL;
109   }
110   if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fstat.st_size))
111   {
112     GNUNET_free (text);
113     GNUNET_DISK_file_close (gn_file);
114     return NULL;
115   }
116   text[fstat.st_size] = '\0';
117   GNUNET_DISK_file_close (gn_file);
118   return text;
119 }
120 #endif
121
122
123 #if BUILD_HTTPS
124
125 static int
126 server_load_certificate (struct Plugin *plugin)
127 {
128   int res = GNUNET_OK;
129
130   char *key_file;
131   char *cert_file;
132
133   /* Get crypto init string from config
134    * If not present just use default values */
135
136   GNUNET_assert (GNUNET_OK ==
137                  GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
138                                                         plugin->name,
139                                                         "CRYPTO_INIT",
140                                                         &plugin->crypto_init));
141
142   if (GNUNET_OK !=
143       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg, plugin->name,
144                                                "KEY_FILE", &key_file))
145   {
146     key_file = GNUNET_strdup ("https_key.key");
147   }
148
149   if (GNUNET_OK !=
150       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg, plugin->name,
151                                                "CERT_FILE", &cert_file))
152   {
153     GNUNET_asprintf (&cert_file, "%s", "https_cert.crt");
154   }
155
156   /* read key & certificates from file */
157 #if VERBOSE_SERVER
158   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
159               "Loading TLS certificate from key-file `%s' cert-file`%s'\n",
160               key_file, cert_file);
161 #endif
162
163   plugin->key = server_load_file (key_file);
164   plugin->cert = server_load_file (cert_file);
165
166   if ((plugin->key == NULL) || (plugin->cert == NULL))
167   {
168     struct GNUNET_OS_Process *cert_creation;
169
170     GNUNET_free_non_null (plugin->key);
171     plugin->key = NULL;
172     GNUNET_free_non_null (plugin->cert);
173     plugin->cert = NULL;
174
175 #if VERBOSE_SERVER
176     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
177                 "No usable TLS certificate found, creating certificate\n");
178 #endif
179     errno = 0;
180     cert_creation =
181         GNUNET_OS_start_process (NULL, NULL,
182                                  "gnunet-transport-certificate-creation",
183                                  "gnunet-transport-certificate-creation",
184                                  key_file, cert_file, NULL);
185     if (cert_creation == NULL)
186     {
187       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
188                        _
189                        ("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
190       GNUNET_free (key_file);
191       GNUNET_free (cert_file);
192
193       GNUNET_free_non_null (plugin->key);
194       plugin->key = NULL;
195       GNUNET_free_non_null (plugin->cert);
196       plugin->cert = NULL;
197       GNUNET_free_non_null (plugin->crypto_init);
198       plugin->crypto_init = NULL;
199
200       return GNUNET_SYSERR;
201     }
202     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
203     GNUNET_OS_process_close (cert_creation);
204
205     plugin->key = server_load_file (key_file);
206     plugin->cert = server_load_file (cert_file);
207   }
208
209   if ((plugin->key == NULL) || (plugin->cert == NULL))
210   {
211     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
212                      _
213                      ("No usable TLS certificate found and creating one failed!\n"),
214                      "transport-https");
215     GNUNET_free (key_file);
216     GNUNET_free (cert_file);
217
218     GNUNET_free_non_null (plugin->key);
219     plugin->key = NULL;
220     GNUNET_free_non_null (plugin->cert);
221     plugin->cert = NULL;
222     GNUNET_free_non_null (plugin->crypto_init);
223     plugin->crypto_init = NULL;
224
225     return GNUNET_SYSERR;
226   }
227   GNUNET_free (key_file);
228   GNUNET_free (cert_file);
229 #if DEBUG_HTTP
230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TLS certificate loaded\n");
231 #endif
232
233   return res;
234 }
235 #endif
236
237
238 /**
239  * Reschedule the execution of both IPv4 and IPv6 server
240  * @param plugin the plugin
241  * @param now GNUNET_YES to schedule execution immediately, GNUNET_NO to wait
242  * until timeout
243  */
244
245 static void
246 server_reschedule (struct Plugin *plugin, struct MHD_Daemon *server, int now)
247 {
248   if ((server == plugin->server_v4) && (plugin->server_v4 != NULL))
249   {
250     if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
251     {
252       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
253       plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
254     }
255     plugin->server_v4_task = server_schedule (plugin, plugin->server_v4, now);
256   }
257
258   if ((server == plugin->server_v6) && (plugin->server_v6 != NULL))
259   {
260     if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
261     {
262       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
263       plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
264     }
265     plugin->server_v6_task = server_schedule (plugin, plugin->server_v6, now);
266   }
267 }
268
269 /**
270  * Callback called by MessageStreamTokenizer when a message has arrived
271  * @param cls current session as closure
272  * @param client clien
273  * @param message the message to be forwarded to transport service
274  */
275 static void
276 server_receive_mst_cb (void *cls, void *client,
277                        const struct GNUNET_MessageHeader *message)
278 {
279   struct Session *s = cls;
280
281 #if VERBOSE_SERVER
282   struct Plugin *plugin = s->plugin;
283 #endif
284   struct GNUNET_TIME_Relative delay;
285
286   delay = http_plugin_receive (s, &s->target, message, s, s->addr, s->addrlen);
287
288   s->next_receive =
289       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), delay);
290
291   if (delay.rel_value > 0)
292   {
293 #if VERBOSE_SERVER
294     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
295                      "Server: peer `%s' address `%s' next read delayed for %llu ms\n",
296                      GNUNET_i2s (&s->target),
297                      http_plugin_address_to_string (NULL, s->addr, s->addrlen),
298                      delay);
299 #endif
300   }
301 }
302
303 /**
304  * Callback called by MHD when it needs data to send
305  * @param cls current session
306  * @param pos position in buffer
307  * @param buf the buffer to write data to
308  * @param max max number of bytes available in buffer
309  * @return bytes written to buffer
310  */
311 static ssize_t
312 server_send_callback (void *cls, uint64_t pos, char *buf, size_t max)
313 {
314   struct Session *s = cls;
315 #if VERBOSE_SERVER
316   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, s->plugin->name,
317                    "Server: %X can sent maximum  %u \n", s, max);
318 #endif
319   struct HTTP_Message *msg;
320   int bytes_read = 0;
321
322   //static int c = 0;
323   msg = s->msg_head;
324   if (msg != NULL)
325   {
326     /* sending */
327     if ((msg->size - msg->pos) <= max)
328     {
329       memcpy (buf, &msg->buf[msg->pos], (msg->size - msg->pos));
330       bytes_read = msg->size - msg->pos;
331       msg->pos += (msg->size - msg->pos);
332     }
333     else
334     {
335       memcpy (buf, &msg->buf[msg->pos], max);
336       msg->pos += max;
337       bytes_read = max;
338     }
339
340     /* removing message */
341     if (msg->pos == msg->size)
342     {
343       if (NULL != msg->transmit_cont)
344         msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK);
345       GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
346       GNUNET_free (msg);
347     }
348   }
349
350 #if VERBOSE_SERVER
351   struct Plugin *plugin = s->plugin;
352   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
353                    "Server: %X: sent %u bytes\n", s, bytes_read);
354 #endif
355   return bytes_read;
356 }
357
358 static struct ServerConnection *
359 server_lookup_session (struct Plugin *plugin,
360                        struct MHD_Connection *mhd_connection, const char *url,
361                        const char *method)
362 {
363   struct Session *s = NULL;
364   struct Session *t;
365   struct ServerConnection *sc = NULL;
366   const union MHD_ConnectionInfo *conn_info;
367
368   struct IPv4HttpAddress a4;
369   struct IPv6HttpAddress a6;
370   struct sockaddr_in *s4;
371   struct sockaddr_in6 *s6;
372   void *a;
373   size_t a_len;
374   struct GNUNET_PeerIdentity target;
375   int check = GNUNET_NO;
376   uint32_t tag = 0;
377   int direction;
378
379   conn_info =
380       MHD_get_connection_info (mhd_connection,
381                                MHD_CONNECTION_INFO_CLIENT_ADDRESS);
382   if ((conn_info->client_addr->sa_family != AF_INET) &&
383       (conn_info->client_addr->sa_family != AF_INET6))
384     return MHD_NO;
385
386   if ((strlen (&url[1]) >= 105) && (url[104] == ';'))
387   {
388     char hash[104];
389     char *tagc = (char *) &url[105];
390
391     memcpy (&hash, &url[1], 103);
392     hash[103] = '\0';
393     if (GNUNET_OK ==
394         GNUNET_CRYPTO_hash_from_string ((const char *) &hash,
395                                         &(target.hashPubKey)))
396     {
397       tag = strtoul (tagc, NULL, 10);
398       if (tagc > 0)
399         check = GNUNET_YES;
400     }
401   }
402
403   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
404     direction = _RECEIVE;
405   if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
406     direction = _SEND;
407
408   if (check == GNUNET_NO)
409     goto error;
410
411   plugin->cur_connections++;
412
413 #if VERBOSE_SERVER
414   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
415                    "Server: New inbound connection from %s with tag %u\n",
416                    GNUNET_i2s (&target), tag);
417 #endif
418   /* find duplicate session */
419
420   t = plugin->head;
421
422   while (t != NULL)
423   {
424     if ((t->inbound) &&
425         (0 == memcmp (&t->target, &target, sizeof (struct GNUNET_PeerIdentity)))
426         &&
427         /* FIXME add source address comparison */
428         (t->tag == tag))
429       break;
430     t = t->next;
431   }
432   if (t != NULL)
433   {
434 #if VERBOSE_SERVER
435     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
436                      "Server: Duplicate session, dismissing new connection from peer `%s'\n",
437                      GNUNET_i2s (&target));
438 #endif
439     goto error;
440   }
441
442   /* find semi-session */
443   t = plugin->server_semi_head;
444
445   while (t != NULL)
446   {
447     /* FIXME add source address comparison */
448     if ((0 == memcmp (&t->target, &target, sizeof (struct GNUNET_PeerIdentity)))
449         && (t->tag == tag))
450     {
451       break;
452     }
453     t = t->next;
454   }
455
456   if (t == NULL)
457     goto create;
458
459 #if VERBOSE_SERVER
460   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
461                    "Server: Found existing semi-session for `%s'\n",
462                    GNUNET_i2s (&target));
463 #endif
464
465   if ((direction == _SEND) && (t->server_send != NULL))
466   {
467 #if VERBOSE_SERVER
468     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
469                      "Server: Duplicate GET session, dismissing new connection from peer `%s'\n",
470                      GNUNET_i2s (&target));
471 #endif
472     goto error;
473   }
474   else
475   {
476     s = t;
477     GNUNET_CONTAINER_DLL_remove (plugin->server_semi_head,
478                                  plugin->server_semi_tail, s);
479     GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
480 #if VERBOSE_SERVER
481     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
482                      "Server: Found matching semi-session, merging session for peer `%s'\n",
483                      GNUNET_i2s (&target));
484 #endif
485
486     goto found;
487   }
488   if ((direction == _RECEIVE) && (t->server_recv != NULL))
489   {
490 #if VERBOSE_SERVER
491     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
492                      "Server: Duplicate PUT session, dismissing new connection from peer `%s'\n",
493                      GNUNET_i2s (&target));
494 #endif
495     goto error;
496   }
497   else
498   {
499     s = t;
500     GNUNET_CONTAINER_DLL_remove (plugin->server_semi_head,
501                                  plugin->server_semi_tail, s);
502     GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
503 #if VERBOSE_SERVER
504     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
505                      "Server: Found matching semi-session, merging session for peer `%s'\n",
506                      GNUNET_i2s (&target));
507 #endif
508     goto found;
509   }
510
511 create:
512 /* create new session */
513 #if VERBOSE_SERVER
514   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
515                    "Server: Creating new session for peer `%s' \n",
516                    GNUNET_i2s (&target));
517 #endif
518
519   switch (conn_info->client_addr->sa_family)
520   {
521   case (AF_INET):
522     s4 = ((struct sockaddr_in *) conn_info->client_addr);
523     a4.u4_port = s4->sin_port;
524     memcpy (&a4.ipv4_addr, &s4->sin_addr, sizeof (struct in_addr));
525     a = &a4;
526     a_len = sizeof (struct IPv4HttpAddress);
527     break;
528   case (AF_INET6):
529     s6 = ((struct sockaddr_in6 *) conn_info->client_addr);
530     a6.u6_port = s6->sin6_port;
531     memcpy (&a6.ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
532     a = &a6;
533     a_len = sizeof (struct IPv6HttpAddress);
534     break;
535   default:
536     GNUNET_break (0);
537     goto error;
538   }
539   s = create_session (plugin, &target, a, a_len, NULL, NULL);
540
541   s->inbound = GNUNET_YES;
542   s->next_receive = GNUNET_TIME_absolute_get_zero ();
543   s->tag = tag;
544   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
545     s->server_recv = s;
546   if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
547     s->server_send = s;
548   GNUNET_CONTAINER_DLL_insert (plugin->server_semi_head,
549                                plugin->server_semi_tail, s);
550   goto found;
551
552 error:
553 #if VERBOSE_SERVER
554   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
555                    "Server: Invalid connection request\n");
556 #endif
557   return NULL;
558
559 found:
560   sc = GNUNET_malloc (sizeof (struct ServerConnection));
561   sc->mhd_conn = mhd_connection;
562   sc->direction = direction;
563   sc->session = s;
564   if (direction == _SEND)
565     s->server_send = sc;
566   if (direction == _RECEIVE)
567     s->server_recv = sc;
568
569 #if MHD_VERSION >= 0x00090E00
570   int to = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000);
571
572 #if VERBOSE_SERVER
573   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
574                    "Server: Setting timeout for %X to %u sec.\n", sc, to);
575 #endif
576   MHD_set_connection_option (mhd_connection, MHD_CONNECTION_OPTION_TIMEOUT, to);
577
578   struct MHD_Daemon * d = NULL;
579   if (s->addrlen == sizeof (struct IPv6HttpAddress))
580     d = plugin->server_v6;
581   if (s->addrlen == sizeof (struct IPv4HttpAddress))
582     d = plugin->server_v4;
583
584   server_reschedule (plugin, d, GNUNET_NO);
585 #endif
586   return sc;
587 }
588
589 /**
590  * Process GET or PUT request received via MHD.  For
591  * GET, queue response that will send back our pending
592  * messages.  For PUT, process incoming data and send
593  * to GNUnet core.  In either case, check if a session
594  * already exists and create a new one if not.
595  */
596 static int
597 server_access_cb (void *cls, struct MHD_Connection *mhd_connection,
598                   const char *url, const char *method, const char *version,
599                   const char *upload_data, size_t * upload_data_size,
600                   void **httpSessionCache)
601 {
602
603   struct Plugin *plugin = cls;
604   struct ServerConnection *sc = *httpSessionCache;
605   struct Session *s = NULL;
606
607   int res = MHD_YES;
608   struct MHD_Response *response;
609
610   GNUNET_assert (cls != NULL);
611   /* new connection */
612   if (sc == NULL)
613   {
614     sc = server_lookup_session (plugin, mhd_connection, url, method);
615     if (sc != NULL)
616       (*httpSessionCache) = sc;
617     else
618     {
619       response =
620           MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),
621                                          HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
622       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
623       MHD_destroy_response (response);
624       return res;
625     }
626   }
627
628   /* existing connection */
629   sc = (*httpSessionCache);
630   s = sc->session;
631
632   /* connection is to be disconnected */
633   if (sc->disconnect == GNUNET_YES)
634   {
635     response =
636         MHD_create_response_from_data (strlen ("Thank you!"), "Thank you!",
637                                        MHD_NO, MHD_NO);
638     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
639 #if VERBOSE_SERVER
640     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
641                 "Sent HTTP/1.1: 200 OK as PUT Response\n");
642 #endif
643     MHD_destroy_response (response);
644     return MHD_YES;
645   }
646
647   GNUNET_assert (s != NULL);
648   /* Check if both directions are connected */
649   if ((sc->session->server_recv == NULL) || (sc->session->server_send == NULL))
650   {
651 #if VERBOSE_SERVER
652       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
653                        "Server: Delayed read from `%s' `%s' since not both semi-connections are connected\n",
654                        GNUNET_i2s (&s->target),
655                        http_plugin_address_to_string (NULL, s->addr, s->addrlen));
656 #endif
657     return MHD_YES;
658   }
659
660   if (sc->direction == _SEND)
661   {
662     response =
663         MHD_create_response_from_callback (-1, 32 * 1024, &server_send_callback,
664                                            s, NULL);
665     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
666     MHD_destroy_response (response);
667     return MHD_YES;
668   }
669   if (sc->direction == _RECEIVE)
670   {
671     if (*upload_data_size == 0)
672     {
673 #if VERBOSE_SERVER
674       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
675                        "Server: Peer `%s' PUT on address `%s' connected\n",
676                        GNUNET_i2s (&s->target),
677                        http_plugin_address_to_string (NULL, s->addr, s->addrlen));
678 #endif
679       return MHD_YES;
680     }
681
682     /* Receiving data */
683     if ((*upload_data_size > 0))
684     {
685 #if VERBOSE_SERVER
686       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
687                        "Server: peer `%s' PUT on address `%s' received %u bytes\n",
688                        GNUNET_i2s (&s->target),
689                        http_plugin_address_to_string (NULL,s->addr, s->addrlen),
690                        *upload_data_size);
691 #endif
692       struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
693
694       if ((s->next_receive.abs_value <= now.abs_value))
695       {
696 #if VERBOSE_SERVER
697         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
698                          "Server: %X: PUT with %u bytes forwarded to MST\n", s,
699                          *upload_data_size);
700 #endif
701         if (s->msg_tk == NULL)
702         {
703           s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
704         }
705         res =
706             GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data,
707                                        *upload_data_size, GNUNET_NO, GNUNET_NO);
708
709 #if MHD_VERSION >= 0x00090E00
710         int to = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000);
711         struct ServerConnection *t = NULL;
712
713 #if VERBOSE_SERVER
714         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
715                          "Server: Received %u bytes\n", *upload_data_size);
716 #endif
717
718         /* Setting timeouts for other connections */
719         if (s->server_recv != NULL)
720         {
721           t = s->server_recv;
722 #if VERBOSE_SERVER
723           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
724                            "Server: Setting timeout for %X to %u sec.\n", t,
725                            to);
726 #endif
727           MHD_set_connection_option (t->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
728                                      to);
729         }
730         if (s->server_send != NULL)
731         {
732           t = s->server_send;
733 #if VERBOSE_SERVER
734           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
735                            "Server: Setting timeout for %X to %u sec.\n", t,
736                            to);
737 #endif
738           MHD_set_connection_option (t->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
739                                      to);
740         }
741         struct MHD_Daemon *d = NULL;
742         if (s->addrlen == sizeof (struct IPv6HttpAddress))
743           d = plugin->server_v6;
744         if (s->addrlen == sizeof (struct IPv4HttpAddress))
745           d = plugin->server_v4;
746         server_reschedule (plugin, d, GNUNET_NO);
747 #endif
748         (*upload_data_size) = 0;
749       }
750       else
751       {
752 #if DEBUG_HTTP
753         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
754                     "Server: %X no inbound bandwidth available! Next read was delayed by %llu ms\n",
755                     s, now.abs_value - s->next_receive.abs_value);
756 #endif
757       }
758       return MHD_YES;
759     }
760     else
761       return MHD_NO;
762   }
763   return res;
764 }
765
766 static void
767 server_disconnect_cb (void *cls, struct MHD_Connection *connection,
768                       void **httpSessionCache)
769 {
770   struct ServerConnection *sc = *httpSessionCache;
771   struct ServerConnection *tc = *httpSessionCache;
772   struct Session *s = NULL;
773   struct Session *t = NULL;
774   struct Plugin *plugin = NULL;
775
776   if (sc == NULL)
777     return;
778
779   s = sc->session;
780   plugin = s->plugin;
781   if (sc->direction == _SEND)
782   {
783 #if VERBOSE_SERVER
784     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
785                      "Server: %X peer `%s' GET on address `%s' disconnected\n",
786                      s->server_send, GNUNET_i2s (&s->target),
787                      http_plugin_address_to_string (NULL, s->addr, s->addrlen));
788 #endif
789     s->server_send = NULL;
790
791     if (s->server_recv != NULL)
792     {
793       tc = s->server_recv;
794       tc->disconnect = GNUNET_YES;
795 #if MHD_VERSION >= 0x00090E00
796       MHD_set_connection_option (sc->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
797                                  1);
798 #endif
799     }
800   }
801   if (sc->direction == _RECEIVE)
802   {
803 #if VERBOSE_SERVER
804     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
805                      "Server: %X peer `%s' PUT on address `%s' disconnected\n",
806                      s->server_recv, GNUNET_i2s (&s->target),
807                      http_plugin_address_to_string (NULL, s->addr, s->addrlen));
808 #endif
809     s->server_recv = NULL;
810     if (s->server_send != NULL)
811     {
812       tc = s->server_send;
813       tc->disconnect = GNUNET_YES;
814 #if MHD_VERSION >= 0x00090E00
815       MHD_set_connection_option (sc->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
816                                  1);
817 #endif
818     }
819     if (s->msg_tk != NULL)
820     {
821       GNUNET_SERVER_mst_destroy (s->msg_tk);
822       s->msg_tk = NULL;
823     }
824   }
825   GNUNET_free (sc);
826
827   t = plugin->server_semi_head;
828   while (t != NULL)
829   {
830     if (t == s)
831     {
832       GNUNET_CONTAINER_DLL_remove (plugin->server_semi_head,
833                                    plugin->server_semi_tail, s);
834       GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
835       break;
836     }
837     t = t->next;
838   }
839   plugin->cur_connections--;
840
841   struct MHD_Daemon *d = NULL;
842   if (s->addrlen == sizeof (struct IPv6HttpAddress))
843     d = plugin->server_v6;
844   if (s->addrlen == sizeof (struct IPv4HttpAddress))
845     d = plugin->server_v4;
846   server_reschedule (plugin, d, GNUNET_NO);
847
848   if ((s->server_send == NULL) && (s->server_recv == NULL))
849   {
850 #if VERBOSE_SERVER
851     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
852                      "Server: peer `%s' on address `%s' disconnected\n",
853                      GNUNET_i2s (&s->target),
854                      http_plugin_address_to_string (NULL, s->addr, s->addrlen));
855 #endif
856     if (s->msg_tk != NULL)
857     {
858       GNUNET_SERVER_mst_destroy (s->msg_tk);
859       s->msg_tk = NULL;
860     }
861
862     notify_session_end (s->plugin, &s->target, s);
863   }
864 }
865
866 int
867 server_disconnect (struct Session *s)
868 {
869   struct Plugin *plugin = s->plugin;
870   struct Session *t = plugin->head;
871
872   while (t != NULL)
873   {
874     if (t->inbound == GNUNET_YES)
875     {
876       if (t->server_send != NULL)
877       {
878         ((struct ServerConnection *) t->server_send)->disconnect = GNUNET_YES;
879       }
880       if (t->server_send != NULL)
881       {
882         ((struct ServerConnection *) t->server_send)->disconnect = GNUNET_YES;
883       }
884     }
885     t = t->next;
886   }
887   return GNUNET_OK;
888 }
889
890 int
891 server_send (struct Session *s, struct HTTP_Message *msg)
892 {
893   GNUNET_CONTAINER_DLL_insert (s->msg_head, s->msg_tail, msg);
894
895   if (s->addrlen == sizeof (struct IPv4HttpAddress))
896   {
897     server_reschedule (s->plugin, s->plugin->server_v4 , GNUNET_YES);
898   }
899   else if (s->addrlen == sizeof (struct IPv6HttpAddress))
900   {
901     server_reschedule (s->plugin, s->plugin->server_v6 , GNUNET_YES);
902   }
903   else
904     return GNUNET_SYSERR;
905   return GNUNET_OK;
906 }
907
908
909
910 /**
911  * Call MHD IPv4 to process pending requests and then go back
912  * and schedule the next run.
913  * @param cls plugin as closure
914  * @param tc task context
915  */
916 static void
917 server_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
918 {
919   struct Plugin *plugin = cls;
920
921   GNUNET_assert (cls != NULL);
922
923   plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
924
925   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
926     return;
927 #if VERBOSE_SERVER
928   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
929                        "Running IPv4 server\n");
930 #endif
931   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
932   if (plugin->server_v4 != NULL)
933     plugin->server_v4_task =
934         server_schedule (plugin, plugin->server_v4, GNUNET_NO);
935 }
936
937
938 /**
939  * Call MHD IPv6 to process pending requests and then go back
940  * and schedule the next run.
941  * @param cls plugin as closure
942  * @param tc task context
943  */
944 static void
945 server_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
946 {
947   struct Plugin *plugin = cls;
948
949   GNUNET_assert (cls != NULL);
950
951   plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
952
953   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
954     return;
955 #if VERBOSE_SERVER
956   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
957                        "Running IPv6 server\n");
958 #endif
959   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
960   if (plugin->server_v6 != NULL)
961     plugin->server_v6_task =
962         server_schedule (plugin, plugin->server_v6, GNUNET_NO);
963 }
964
965 /**
966  * Function that queries MHD's select sets and
967  * starts the task waiting for them.
968  * @param plugin plugin
969  * @param daemon_handle the MHD daemon handle
970  * @return gnunet task identifier
971  */
972 static GNUNET_SCHEDULER_TaskIdentifier
973 server_schedule (struct Plugin *plugin, struct MHD_Daemon *daemon_handle,
974                  int now)
975 {
976   GNUNET_SCHEDULER_TaskIdentifier ret;
977   fd_set rs;
978   fd_set ws;
979   fd_set es;
980   struct GNUNET_NETWORK_FDSet *wrs;
981   struct GNUNET_NETWORK_FDSet *wws;
982   struct GNUNET_NETWORK_FDSet *wes;
983   int max;
984   unsigned long long timeout;
985   static unsigned long long last_timeout = 0;
986   int haveto;
987
988   struct GNUNET_TIME_Relative tv;
989
990   ret = GNUNET_SCHEDULER_NO_TASK;
991   FD_ZERO (&rs);
992   FD_ZERO (&ws);
993   FD_ZERO (&es);
994   wrs = GNUNET_NETWORK_fdset_create ();
995   wes = GNUNET_NETWORK_fdset_create ();
996   wws = GNUNET_NETWORK_fdset_create ();
997   max = -1;
998   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
999   haveto = MHD_get_timeout (daemon_handle, &timeout);
1000   if (haveto == MHD_YES)
1001   {
1002     if (timeout != last_timeout)
1003     {
1004 #if VERBOSE_SERVER
1005       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1006                        "SELECT Timeout changed from %llu to %llu\n",
1007                        last_timeout, timeout);
1008 #endif
1009       last_timeout = timeout;
1010     }
1011     tv.rel_value = (uint64_t) timeout;
1012   }
1013   else
1014     tv = GNUNET_TIME_UNIT_SECONDS;
1015   /* Force immediate run, since we have outbound data to send */
1016   if (now == GNUNET_YES)
1017     tv = GNUNET_TIME_UNIT_MILLISECONDS;
1018   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1019   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1020   GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
1021
1022   if (daemon_handle == plugin->server_v4)
1023   {
1024     if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1025     {
1026       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1027       plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1028     }
1029 #if VERBOSE_SERVER
1030   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1031                        "Scheduling IPv4 server task in %llu ms\n", tv);
1032 #endif
1033     ret =
1034         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1035                                      GNUNET_SCHEDULER_NO_TASK, tv, wrs, wws,
1036                                      &server_v4_run, plugin);
1037   }
1038   if (daemon_handle == plugin->server_v6)
1039   {
1040     if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1041     {
1042       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1043       plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1044     }
1045 #if VERBOSE_SERVER
1046   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1047                        "Scheduling IPv6 server task in %llu ms\n", tv);
1048 #endif
1049     ret =
1050         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1051                                      GNUNET_SCHEDULER_NO_TASK, tv, wrs, wws,
1052                                      &server_v6_run, plugin);
1053   }
1054   GNUNET_NETWORK_fdset_destroy (wrs);
1055   GNUNET_NETWORK_fdset_destroy (wws);
1056   GNUNET_NETWORK_fdset_destroy (wes);
1057   return ret;
1058 }
1059
1060 int
1061 server_start (struct Plugin *plugin)
1062 {
1063   int res = GNUNET_OK;
1064   unsigned int timeout;
1065
1066 #if BUILD_HTTPS
1067   res = server_load_certificate (plugin);
1068   if (res == GNUNET_SYSERR)
1069   {
1070     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1071                      "Could not load or create server certificate! Loading plugin failed!\n");
1072     return res;
1073   }
1074 #endif
1075
1076
1077 #if MHD_VERSION >= 0x00090E00
1078   timeout = HTTP_NOT_VALIDATED_TIMEOUT.rel_value / 1000;
1079   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1080                    "MHD can set timeout per connection! Default time out %u sec.\n",
1081                    timeout);
1082 #else
1083   timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000;
1084   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1085                    "MHD cannot set timeout per connection! Default time out %u sec.\n",
1086                    timeout);
1087 #endif
1088   plugin->server_v4 = NULL;
1089   if (plugin->ipv4 == GNUNET_YES)
1090   {
1091     plugin->server_v4 = MHD_start_daemon (
1092 #if VERBOSE_SERVER
1093                                            MHD_USE_DEBUG |
1094 #endif
1095 #if BUILD_HTTPS
1096                                            MHD_USE_SSL |
1097 #endif
1098                                            MHD_NO_FLAG, plugin->port,
1099                                            &server_accept_cb, plugin,
1100                                            &server_access_cb, plugin,
1101                                            MHD_OPTION_SOCK_ADDR,
1102                                            (struct sockaddr_in *)
1103                                            plugin->server_addr_v4,
1104                                            MHD_OPTION_CONNECTION_LIMIT,
1105                                            (unsigned int)
1106                                            plugin->max_connections,
1107 #if BUILD_HTTPS
1108                                            MHD_OPTION_HTTPS_PRIORITIES,
1109                                            plugin->crypto_init,
1110                                            MHD_OPTION_HTTPS_MEM_KEY,
1111                                            plugin->key,
1112                                            MHD_OPTION_HTTPS_MEM_CERT,
1113                                            plugin->cert,
1114 #endif
1115                                            MHD_OPTION_CONNECTION_TIMEOUT,
1116                                            timeout,
1117                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
1118                                            (size_t) (2 *
1119                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
1120                                            MHD_OPTION_NOTIFY_COMPLETED,
1121                                            &server_disconnect_cb, plugin,
1122                                            MHD_OPTION_EXTERNAL_LOGGER,
1123                                            server_log, NULL, MHD_OPTION_END);
1124   }
1125   plugin->server_v6 = NULL;
1126   if (plugin->ipv6 == GNUNET_YES)
1127   {
1128     plugin->server_v6 = MHD_start_daemon (
1129 #if VERBOSE_SERVER
1130                                            MHD_USE_DEBUG |
1131 #endif
1132 #if BUILD_HTTPS
1133                                            MHD_USE_SSL |
1134 #endif
1135                                            MHD_USE_IPv6, plugin->port,
1136                                            &server_accept_cb, plugin,
1137                                            &server_access_cb, plugin,
1138                                            MHD_OPTION_SOCK_ADDR,
1139                                            (struct sockaddr_in6 *)
1140                                            plugin->server_addr_v6,
1141                                            MHD_OPTION_CONNECTION_LIMIT,
1142                                            (unsigned int)
1143                                            plugin->max_connections,
1144 #if BUILD_HTTPS
1145                                            MHD_OPTION_HTTPS_PRIORITIES,
1146                                            plugin->crypto_init,
1147                                            MHD_OPTION_HTTPS_MEM_KEY,
1148                                            plugin->key,
1149                                            MHD_OPTION_HTTPS_MEM_CERT,
1150                                            plugin->cert,
1151 #endif
1152                                            MHD_OPTION_CONNECTION_TIMEOUT,
1153                                            timeout,
1154                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
1155                                            (size_t) (2 *
1156                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
1157                                            MHD_OPTION_NOTIFY_COMPLETED,
1158                                            &server_disconnect_cb, plugin,
1159                                            MHD_OPTION_EXTERNAL_LOGGER,
1160                                            server_log, NULL, MHD_OPTION_END);
1161
1162   }
1163
1164   if ((plugin->ipv4 == GNUNET_YES) && (plugin->server_v4 == NULL))
1165   {
1166     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1167                      "Failed to start %s IPv4 server component on port %u\n",
1168                      plugin->name, plugin->port);
1169     return GNUNET_SYSERR;
1170   }
1171   server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
1172
1173   if ((plugin->ipv6 == GNUNET_YES) && (plugin->server_v6 == NULL))
1174   {
1175     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1176                      "Failed to start %s IPv6 server component on port %u\n",
1177                      plugin->name, plugin->port);
1178     return GNUNET_SYSERR;
1179   }
1180   server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
1181
1182
1183 #if DEBUG_HTTP
1184   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1185                    "%s server component started on port %u\n", plugin->name,
1186                    plugin->port);
1187 #endif
1188   return res;
1189 }
1190
1191 void
1192 server_stop (struct Plugin *plugin)
1193 {
1194   struct Session *s = NULL;
1195   struct Session *t = NULL;
1196
1197 #if VERBOSE_SERVER
1198   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1199                    "server_stop\n");
1200 #endif
1201
1202   struct MHD_Daemon *server_v4_tmp = plugin->server_v4;
1203
1204   plugin->server_v4 = NULL;
1205   struct MHD_Daemon *server_v6_tmp = plugin->server_v6;
1206
1207   plugin->server_v6 = NULL;
1208
1209   if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1210   {
1211     GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1212     plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1213   }
1214
1215   if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1216   {
1217     GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1218     plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1219   }
1220
1221   if (server_v6_tmp != NULL)
1222   {
1223     MHD_stop_daemon (server_v4_tmp);
1224   }
1225   if (server_v6_tmp != NULL)
1226   {
1227     MHD_stop_daemon (server_v6_tmp);
1228   }
1229
1230   /* cleaning up semi-sessions never propagated */
1231   s = plugin->server_semi_head;
1232   while (s != NULL)
1233   {
1234 #if VERBOSE_SERVER
1235     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1236                      "Deleting semi-sessions %p\n", s);
1237 #endif
1238     t = s->next;
1239     struct HTTP_Message * msg = s->msg_head;
1240     struct HTTP_Message * tmp = s->msg_head;
1241     while (msg != NULL)
1242     {
1243       tmp = msg->next;
1244
1245       GNUNET_CONTAINER_DLL_remove(s->msg_head,s->msg_tail, msg);
1246       if (msg->transmit_cont != NULL)
1247       {
1248         msg->transmit_cont(msg->transmit_cont_cls, &s->target, GNUNET_SYSERR);
1249       }
1250       GNUNET_free (msg);
1251       msg = tmp;
1252     }
1253
1254     delete_session (s);
1255     s = t;
1256   }
1257
1258 #if BUILD_HTTPS
1259   GNUNET_free_non_null (plugin->crypto_init);
1260   GNUNET_free_non_null (plugin->cert);
1261   GNUNET_free_non_null (plugin->key);
1262 #endif
1263
1264 #if DEBUG_HTTP
1265   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1266                    "%s server component stopped\n", plugin->name);
1267 #endif
1268 }
1269
1270
1271
1272 /* end of plugin_transport_http.c */