all tests use generated configs and pass on my system
[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 IPv4HttpAddress a4;
356   struct IPv6HttpAddress a6;
357   struct sockaddr_in * s4;
358   struct sockaddr_in6 * s6;
359   void * a;
360   size_t a_len;
361   struct GNUNET_PeerIdentity target;
362   size_t addrlen;
363   int check = GNUNET_NO;
364   uint32_t tag = 0;
365   int direction;
366
367   conn_info = MHD_get_connection_info (mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS);
368   if (conn_info->client_addr->sa_family == AF_INET)
369     addrlen = sizeof (struct sockaddr_in);
370   else if (conn_info->client_addr->sa_family == AF_INET6)
371     addrlen = sizeof (struct sockaddr_in6);
372   else
373     return MHD_NO;
374
375   if ((strlen(&url[1]) >= 105)  && (url[104] == ';'))
376   {
377     char hash[104];
378     char * tagc = (char *) &url[105];
379     memcpy(&hash, &url[1], 103);
380     hash [103] = '\0';
381     if (GNUNET_OK == GNUNET_CRYPTO_hash_from_string ((const char *) &hash,
382           &(target.hashPubKey)))
383     {
384       tag = strtoul (tagc, NULL, 10);
385       if (tagc > 0)
386         check = GNUNET_YES;
387     }
388   }
389
390   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
391     direction = _RECEIVE;
392   if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
393     direction = _SEND;
394
395   if (check == GNUNET_NO)
396     goto error;
397
398   plugin->cur_connections++;
399
400 #if VERBOSE_SERVER
401   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
402                    "Server: New inbound connection from %s with tag %u\n", GNUNET_i2s(&target), tag);
403 #endif
404   /* find duplicate session */
405
406   t = plugin->head;
407
408   while (t != NULL)
409   {
410     if ((t->inbound) && (0 == memcmp (&t->target, &target, sizeof (struct GNUNET_PeerIdentity))) &&
411         /* FIXME add source address comparison */
412         (t->tag == tag))
413     break;
414     t = t->next;
415   }
416   if (t != NULL)
417   {
418 #if VERBOSE_SERVER
419     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
420                      "Server: Duplicate session, dismissing new connection from peer `%s'\n", GNUNET_i2s (&target));
421 #endif
422     goto error;
423   }
424
425   /* find semi-session */
426   t = plugin->server_semi_head;
427
428   while (t != NULL)
429   {
430     /* FIXME add source address comparison */
431     if ((0 == memcmp (&t->target, &target, sizeof (struct GNUNET_PeerIdentity))) &&
432         (t->tag == tag))
433     {
434       break;
435     }
436     t = t->next;
437   }
438
439   if (t == NULL)
440     goto create;
441
442 #if VERBOSE_SERVER
443   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
444                    "Server: Found existing semi-session for `%s'\n", GNUNET_i2s (&target));
445 #endif
446
447   if ((direction == _SEND) && (t->server_send != NULL))
448   {
449 #if VERBOSE_SERVER
450     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
451                      "Server: Duplicate GET session, dismissing new connection from peer `%s'\n", GNUNET_i2s (&target));
452 #endif
453     goto error;
454   }
455   else
456   {
457     s = t;
458     GNUNET_CONTAINER_DLL_remove(plugin->server_semi_head, plugin->server_semi_tail, s);
459     GNUNET_CONTAINER_DLL_insert(plugin->head, plugin->tail, s);
460 #if VERBOSE_SERVER
461     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
462                      "Server: Found matching semi-session, merging session for peer `%s'\n", GNUNET_i2s (&target));
463 #endif
464
465     goto found;
466   }
467   if ((direction == _RECEIVE) && (t->server_recv != NULL))
468   {
469 #if VERBOSE_SERVER
470     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
471                      "Server: Duplicate PUT session, dismissing new connection from peer `%s'\n", GNUNET_i2s (&target));
472 #endif
473     goto error;
474   }
475   else
476   {
477     s = t;
478     GNUNET_CONTAINER_DLL_remove(plugin->server_semi_head, 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", GNUNET_i2s (&target));
483 #endif
484     goto found;
485   }
486
487 create:
488 /* create new session */
489 #if VERBOSE_SERVER
490   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
491                "Server: Creating new session for peer `%s' \n", GNUNET_i2s (&target));
492 #endif
493
494   switch (conn_info->client_addr->sa_family)
495   {
496   case (AF_INET):
497       s4 = ((struct sockaddr_in * ) conn_info->client_addr);
498       a4.u4_port = s4->sin_port;
499       memcpy (&a4.ipv4_addr, &s4->sin_addr,
500               sizeof (struct in_addr));
501       a = &a4;
502       a_len = sizeof (struct IPv4HttpAddress);
503       break;
504   case (AF_INET6):
505       s6 = ((struct sockaddr_in6 * ) conn_info->client_addr);
506       a6.u6_port = s6->sin6_port;
507       memcpy (&a6.ipv6_addr, &s6->sin6_addr,
508               sizeof (struct in6_addr));
509       a = &a6;
510       a_len = sizeof (struct IPv6HttpAddress);
511       break;
512   default:
513     GNUNET_break (0);
514   }
515
516   s = create_session (plugin,
517                       &target,
518                       a,
519                       a_len,
520                       NULL,
521                       NULL);
522
523   s->inbound = GNUNET_YES;
524   s->next_receive = GNUNET_TIME_absolute_get_zero();
525   s->tag= tag;
526   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
527     s->server_recv = s;
528   if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
529     s->server_send = s;
530   GNUNET_CONTAINER_DLL_insert (plugin->server_semi_head, plugin->server_semi_tail, s);
531   goto found;
532
533 error:
534 #if VERBOSE_SERVER
535   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
536                "Server: Invalid connection request\n");
537 #endif
538   return NULL;
539
540 found:
541   sc = GNUNET_malloc (sizeof (struct ServerConnection));
542   sc->mhd_conn = mhd_connection;
543   sc->direction = direction;
544   sc->session = s;
545   if (direction == _SEND)
546     s->server_send = sc;
547   if (direction == _RECEIVE)
548     s->server_recv = sc;
549
550 #if MHD_VERSION >= 0x00090E00
551   int to = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000);
552 #if VERBOSE_SERVER
553   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
554                    "Server: Setting timeout for %X to %u sec.\n", sc, to);
555 #endif
556   MHD_set_connection_option (mhd_connection, MHD_CONNECTION_OPTION_TIMEOUT, to);
557   server_reschedule (plugin, GNUNET_NO);
558 #endif
559   return sc;
560 }
561
562 /**
563  * Process GET or PUT request received via MHD.  For
564  * GET, queue response that will send back our pending
565  * messages.  For PUT, process incoming data and send
566  * to GNUnet core.  In either case, check if a session
567  * already exists and create a new one if not.
568  */
569 static int
570 server_access_cb (void *cls, struct MHD_Connection *mhd_connection,
571                   const char *url, const char *method, const char *version,
572                   const char *upload_data, size_t * upload_data_size,
573                   void **httpSessionCache)
574 {
575
576   struct Plugin *plugin = cls;
577   struct ServerConnection *sc = *httpSessionCache;
578   struct Session *s = NULL;
579
580   int res = MHD_YES;
581   struct MHD_Response *response;
582
583   GNUNET_assert (cls != NULL);
584   /* new connection */
585   if (sc == NULL)
586   {
587     sc = server_lookup_session(plugin, mhd_connection, url, method);
588     if (sc != NULL)
589       (*httpSessionCache) = sc;
590     else
591     {
592       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
593       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
594       MHD_destroy_response (response);
595       return res;
596     }
597   }
598
599   /* existing connection */
600   sc = (*httpSessionCache);
601   s = sc->session;
602
603   /* connection is to be disconnected*/
604   if (sc->disconnect == GNUNET_YES)
605   {
606     response = MHD_create_response_from_data (strlen ("Thank you!"), "Thank you!", MHD_NO, MHD_NO);
607     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
608 #if VERBOSE_SERVER
609     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
610                 "Sent HTTP/1.1: 200 OK as PUT Response\n");
611 #endif
612     MHD_destroy_response (response);
613     return MHD_YES;
614   }
615
616   GNUNET_assert (s != NULL);
617   if (sc->direction == _SEND)
618   {
619     response = MHD_create_response_from_callback (-1, 32 * 1024, &server_send_callback,
620                                            s, NULL);
621     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
622     MHD_destroy_response (response);
623     return MHD_YES;
624   }
625   if (sc->direction == _RECEIVE)
626   {
627     if (*upload_data_size == 0)
628     {
629 #if VERBOSE_SERVER
630   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
631                    "Server: Peer `%s' PUT on address `%s' connected\n",
632                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen));
633 #endif
634       return MHD_YES;
635     }
636
637     /* Recieving data */
638     if ((*upload_data_size > 0))
639     {
640 #if VERBOSE_SERVER
641   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
642                    "Server: peer `%s' PUT on address `%s' received %Zu bytes\n",
643                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen), *upload_data_size);
644 #endif
645       struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
646       if (( s->next_receive.abs_value <= now.abs_value))
647       {
648 #if VERBOSE_SERVER
649         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
650                     "Server: %X: PUT with %u bytes forwarded to MST\n", s,
651                     *upload_data_size);
652 #endif
653         if (s->msg_tk == NULL)
654         {
655           s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
656         }
657         res = GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data, *upload_data_size, GNUNET_NO, GNUNET_NO);
658
659 #if MHD_VERSION >= 0x00090E00
660         int to = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000);
661         struct ServerConnection *t = NULL;
662
663 #if VERBOSE_SERVER
664         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
665                          "Server: Received %Zu bytes\n", *upload_data_size);
666 #endif
667
668         /* Setting timeouts for other connections */
669         if (s->server_recv != NULL)
670         {
671           t = s->server_recv;
672 #if VERBOSE_SERVER
673           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
674                      "Server: Setting timeout for %X to %u sec.\n", t, to);
675 #endif
676           MHD_set_connection_option (t->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT, to);
677         }
678         if (s->server_send != NULL)
679         {
680           t = s->server_send;
681 #if VERBOSE_SERVER
682           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
683                      "Server: Setting timeout for %X to %u sec.\n", t, to);
684 #endif
685           MHD_set_connection_option (t->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT, to);
686         }
687         server_reschedule (plugin, GNUNET_NO);
688 #endif
689         (*upload_data_size) = 0;
690       }
691       else
692       {
693 #if DEBUG_HTTP
694        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
695                   "Server: %X no inbound bandwidth available! Next read was delayed by %llu ms\n", s, now.abs_value - s->next_receive.abs_value);
696 #endif
697       }
698       return MHD_YES;
699     }
700     else
701       return MHD_NO;
702   }
703   return res;
704 }
705
706 static void
707 server_disconnect_cb (void *cls, struct MHD_Connection *connection,
708                       void **httpSessionCache)
709 {
710   struct ServerConnection *sc = *httpSessionCache;
711   struct ServerConnection *tc = *httpSessionCache;
712   struct Session * s = NULL;
713   struct Session * t = NULL;
714   struct Plugin * plugin = NULL;
715
716   if (sc == NULL)
717     return;
718
719   s = sc->session;
720   plugin = s-> plugin;
721   if (sc->direction == _SEND)
722   {
723 #if VERBOSE_SERVER
724   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
725                    "Server: %X peer `%s' GET on address `%s' disconnected\n",
726                    s->server_send,
727                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen));
728 #endif
729     s->server_send = NULL;
730
731     if (s->server_recv != NULL)
732     {
733       tc = s->server_recv;
734       tc->disconnect = GNUNET_YES;
735 #if MHD_VERSION >= 0x00090E00
736       MHD_set_connection_option (sc->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT, 1);
737 #endif
738     }
739   }
740   if (sc->direction == _RECEIVE)
741   {
742 #if VERBOSE_SERVER
743   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
744                    "Server: %X peer `%s' PUT on address `%s' disconnected\n",
745                    s->server_recv,
746                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen));
747 #endif
748     s->server_recv = NULL;
749     if (s->server_send != NULL)
750     {
751       tc = s->server_send;
752       tc->disconnect = GNUNET_YES;
753 #if MHD_VERSION >= 0x00090E00
754       MHD_set_connection_option (sc->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT, 1);
755 #endif
756     }
757     if (s->msg_tk != NULL)
758     {
759        GNUNET_SERVER_mst_destroy(s->msg_tk);
760        s->msg_tk = NULL;
761     }
762   }
763   GNUNET_free (sc);
764
765   t = plugin->server_semi_head;
766   while (t != NULL)
767   {
768     if (t == s)
769     {
770       GNUNET_CONTAINER_DLL_remove(plugin->server_semi_head, plugin->server_semi_tail, s);
771       GNUNET_CONTAINER_DLL_insert(plugin->head, plugin->tail, s);
772       break;
773     }
774     t = t->next;
775   }
776   plugin->cur_connections--;
777
778   server_reschedule (plugin, GNUNET_NO);
779
780   if ((s->server_send == NULL) && (s->server_recv == NULL))
781   {
782 #if VERBOSE_SERVER
783   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
784                    "Server: peer `%s' on address `%s' disconnected\n",
785                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen));
786 #endif
787     if (s->msg_tk != NULL)
788     {
789        GNUNET_SERVER_mst_destroy(s->msg_tk);
790        s->msg_tk = NULL;
791     }
792
793     notify_session_end(s->plugin, &s->target, s);
794   }
795 }
796
797 int
798 server_disconnect (struct Session *s)
799 {
800   struct Plugin *plugin = s->plugin;
801   struct Session *t = plugin->head;
802
803   while (t != NULL)
804   {
805     if (t->inbound == GNUNET_YES)
806     {
807       if (t->server_send != NULL)
808       {
809         ((struct ServerConnection *) t->server_send)->disconnect = GNUNET_YES;
810       }
811       if (t->server_send != NULL)
812       {
813         ((struct ServerConnection *) t->server_send)->disconnect = GNUNET_YES;
814       }
815     }
816     t = t->next;
817   }
818
819
820   return GNUNET_OK;
821 }
822
823 int
824 server_send (struct Session *s, struct HTTP_Message * msg)
825 {
826   GNUNET_CONTAINER_DLL_insert (s->msg_head, s->msg_tail, msg);
827   server_reschedule (s->plugin, GNUNET_YES);
828   return GNUNET_OK;
829 }
830
831
832
833 /**
834  * Call MHD IPv4 to process pending requests and then go back
835  * and schedule the next run.
836  * @param cls plugin as closure
837  * @param tc task context
838  */
839 static void
840 server_v4_run (void *cls,
841                            const struct GNUNET_SCHEDULER_TaskContext *tc)
842 {
843   struct Plugin *plugin = cls;
844   GNUNET_assert (cls != NULL);
845
846   plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
847
848   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
849     return;
850
851   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
852   if (plugin->server_v4 != NULL)
853     plugin->server_v4_task = server_schedule (plugin, plugin->server_v4, GNUNET_NO);
854 }
855
856
857 /**
858  * Call MHD IPv6 to process pending requests and then go back
859  * and schedule the next run.
860  * @param cls plugin as closure
861  * @param tc task context
862  */
863 static void
864 server_v6_run (void *cls,
865                            const struct GNUNET_SCHEDULER_TaskContext *tc)
866 {
867   struct Plugin *plugin = cls;
868   GNUNET_assert (cls != NULL);
869
870   plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
871
872   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
873     return;
874
875   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
876   if (plugin->server_v6 != NULL)
877     plugin->server_v6_task = server_schedule (plugin, plugin->server_v6, GNUNET_NO);
878 }
879
880 /**
881  * Function that queries MHD's select sets and
882  * starts the task waiting for them.
883  * @param plugin plugin
884  * @param daemon_handle the MHD daemon handle
885  * @return gnunet task identifier
886  */
887 static GNUNET_SCHEDULER_TaskIdentifier
888 server_schedule (struct Plugin *plugin, struct MHD_Daemon *daemon_handle, int now)
889 {
890   GNUNET_SCHEDULER_TaskIdentifier ret;
891   fd_set rs;
892   fd_set ws;
893   fd_set es;
894   struct GNUNET_NETWORK_FDSet *wrs;
895   struct GNUNET_NETWORK_FDSet *wws;
896   struct GNUNET_NETWORK_FDSet *wes;
897   int max;
898   unsigned long long timeout;
899   static unsigned long long last_timeout = 0;
900   int haveto;
901
902   struct GNUNET_TIME_Relative tv;
903
904   ret = GNUNET_SCHEDULER_NO_TASK;
905   FD_ZERO (&rs);
906   FD_ZERO (&ws);
907   FD_ZERO (&es);
908   wrs = GNUNET_NETWORK_fdset_create ();
909   wes = GNUNET_NETWORK_fdset_create ();
910   wws = GNUNET_NETWORK_fdset_create ();
911   max = -1;
912   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
913   haveto = MHD_get_timeout (daemon_handle, &timeout);
914   if (haveto == MHD_YES)
915     {
916     if (timeout != last_timeout)
917     {
918 #if VERBOSE_SERVER
919       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
920                        "SELECT Timeout changed from %llu to %llu\n",
921                        last_timeout, timeout);
922 #endif
923       last_timeout = timeout;
924     }
925     tv.rel_value = (uint64_t) timeout;
926     }
927   else
928     tv = GNUNET_TIME_UNIT_SECONDS;
929   /* Force immediate run, since we have outbound data to send */
930   if (now == GNUNET_YES)
931     tv = GNUNET_TIME_UNIT_MILLISECONDS;
932   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
933   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
934   GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
935   if (daemon_handle == plugin->server_v4)
936   {
937     if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
938     {
939       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
940       plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
941     }
942
943     ret =
944         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
945                                      GNUNET_SCHEDULER_NO_TASK, tv, wrs, wws,
946                                      &server_v4_run, plugin);
947   }
948   if (daemon_handle == plugin->server_v6)
949   {
950     if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
951     {
952       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
953       plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
954     }
955
956     ret =
957         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
958                                      GNUNET_SCHEDULER_NO_TASK, tv, wrs, wws,
959                                      &server_v6_run, plugin);
960   }
961   GNUNET_NETWORK_fdset_destroy (wrs);
962   GNUNET_NETWORK_fdset_destroy (wws);
963   GNUNET_NETWORK_fdset_destroy (wes);
964   return ret;
965 }
966
967 int
968 server_start (struct Plugin *plugin)
969 {
970   int res = GNUNET_OK;
971   unsigned int timeout;
972
973 #if BUILD_HTTPS
974   res = server_load_certificate (plugin);
975   if (res == GNUNET_SYSERR)
976   {
977     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
978         "Could not load or create server certificate! Loading plugin failed!\n");
979     return res;
980   }
981 #endif
982
983
984 #if MHD_VERSION >= 0x00090E00
985   timeout = GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT.rel_value / 1000;
986   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
987       "MHD can set timeout per connection! Default time out %u sec.\n", timeout);
988 #else
989   timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000;
990   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
991       "MHD cannot set timeout per connection! Default time out %u sec.\n", timeout);
992 #endif
993   plugin->server_v4 = NULL;
994   if (plugin->ipv4 == GNUNET_YES)
995   {
996     plugin->server_v4 = MHD_start_daemon (
997 #if VERBOSE_SERVER
998                                            MHD_USE_DEBUG |
999 #endif
1000 #if BUILD_HTTPS
1001                                            MHD_USE_SSL |
1002 #endif
1003                                            MHD_NO_FLAG, plugin->port,
1004                                            &server_accept_cb, plugin,
1005                                            &server_access_cb, plugin,
1006                                            MHD_OPTION_SOCK_ADDR,
1007                                            (struct sockaddr_in *)
1008                                            plugin->server_addr_v4,
1009                                            MHD_OPTION_CONNECTION_LIMIT,
1010                                            (unsigned int)
1011                                            plugin->max_connections,
1012 #if BUILD_HTTPS
1013                                            MHD_OPTION_HTTPS_PRIORITIES,
1014                                            plugin->crypto_init,
1015                                            MHD_OPTION_HTTPS_MEM_KEY,
1016                                            plugin->key,
1017                                            MHD_OPTION_HTTPS_MEM_CERT,
1018                                            plugin->cert,
1019 #endif
1020                                            MHD_OPTION_CONNECTION_TIMEOUT,
1021                                            timeout ,
1022                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
1023                                            (size_t) (2 *
1024                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
1025                                            MHD_OPTION_NOTIFY_COMPLETED,
1026                                            &server_disconnect_cb, plugin,
1027                                            MHD_OPTION_EXTERNAL_LOGGER,
1028                                            server_log, NULL, MHD_OPTION_END);
1029   }
1030   plugin->server_v6 = NULL;
1031   if (plugin->ipv6 == GNUNET_YES)
1032   {
1033     plugin->server_v6 = MHD_start_daemon (
1034 #if VERBOSE_SERVER
1035                                            MHD_USE_DEBUG |
1036 #endif
1037 #if BUILD_HTTPS
1038                                            MHD_USE_SSL |
1039 #endif
1040                                            MHD_USE_IPv6, plugin->port,
1041                                            &server_accept_cb, plugin,
1042                                            &server_access_cb, plugin,
1043                                            MHD_OPTION_SOCK_ADDR,
1044                                            (struct sockaddr_in6 *)
1045                                            plugin->server_addr_v6,
1046                                            MHD_OPTION_CONNECTION_LIMIT,
1047                                            (unsigned int)
1048                                            plugin->max_connections,
1049 #if BUILD_HTTPS
1050                                            MHD_OPTION_HTTPS_PRIORITIES,
1051                                            plugin->crypto_init,
1052                                            MHD_OPTION_HTTPS_MEM_KEY,
1053                                            plugin->key,
1054                                            MHD_OPTION_HTTPS_MEM_CERT,
1055                                            plugin->cert,
1056 #endif
1057                                            MHD_OPTION_CONNECTION_TIMEOUT,
1058                                            timeout,
1059                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
1060                                            (size_t) (2 *
1061                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
1062                                            MHD_OPTION_NOTIFY_COMPLETED,
1063                                            &server_disconnect_cb, plugin,
1064                                            MHD_OPTION_EXTERNAL_LOGGER,
1065                                            server_log, NULL, MHD_OPTION_END);
1066
1067   }
1068
1069   if ((plugin->ipv4 == GNUNET_YES) && (plugin->server_v4 == NULL))
1070   {
1071     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1072                      "Failed to start %s IPv4 server component on port %u\n", plugin->name,
1073                      plugin->port);
1074     return GNUNET_SYSERR;
1075   }
1076   if ((plugin->ipv6 == GNUNET_YES) && (plugin->server_v6 == NULL))
1077   {
1078     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1079                      "Failed to start %s IPv6 server component on port %u\n", plugin->name,
1080                      plugin->port);
1081     return GNUNET_SYSERR;
1082   }
1083
1084   server_reschedule (plugin, GNUNET_NO);
1085
1086 #if DEBUG_HTTP
1087   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1088                    "%s server component started on port %u\n", plugin->name,
1089                    plugin->port);
1090 #endif
1091   return res;
1092 }
1093
1094 void
1095 server_stop (struct Plugin *plugin)
1096 {
1097   struct Session *s = NULL;
1098   struct Session *t = NULL;
1099
1100   struct MHD_Daemon *server_v4_tmp = plugin->server_v4;
1101   plugin->server_v4 = NULL;
1102   struct MHD_Daemon *server_v6_tmp = plugin->server_v6;
1103   plugin->server_v6 = NULL;
1104
1105   if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1106   {
1107     GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1108     plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1109   }
1110
1111   if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1112   {
1113     GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1114     plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1115   }
1116
1117   if (server_v6_tmp != NULL)
1118   {
1119     MHD_stop_daemon (server_v4_tmp);
1120   }
1121   if (server_v6_tmp != NULL)
1122   {
1123     MHD_stop_daemon (server_v6_tmp);
1124   }
1125
1126   /* cleaning up semi-sessions never propagated */
1127   s = plugin->server_semi_head;
1128   while (s != NULL)
1129   {
1130     t = s->next;
1131     delete_session (s);
1132     s = t;
1133   }
1134
1135 #if BUILD_HTTPS
1136   GNUNET_free_non_null (plugin->crypto_init);
1137   GNUNET_free_non_null (plugin->cert);
1138   GNUNET_free_non_null (plugin->key);
1139 #endif
1140
1141 #if DEBUG_HTTP
1142   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1143                    "%s server component stopped\n", plugin->name);
1144 #endif
1145 }
1146
1147
1148
1149 /* end of plugin_transport_http.c */