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