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