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