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