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