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