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