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