596ac4925fe2e45d184dc7c879f1b87795b84444
[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   struct Plugin *plugin = s->plugin;
246   struct GNUNET_TIME_Relative delay;
247
248   delay = http_plugin_receive (s, &s->target, message, s, s->addr, s->addrlen);
249
250   s->delay = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), delay);
251   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name, "Server: SERVER DELAY %llu ms\n",
252               delay.rel_value);
253
254   if (GNUNET_TIME_absolute_get().abs_value < s->delay.abs_value)
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   struct Plugin *plugin = s->plugin;
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   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
308                    "Server: %X: sent %u bytes\n",
309                    s, bytes_read);
310 #endif
311   return bytes_read;
312 }
313
314 /**
315  * Process GET or PUT request received via MHD.  For
316  * GET, queue response that will send back our pending
317  * messages.  For PUT, process incoming data and send
318  * to GNUnet core.  In either case, check if a session
319  * already exists and create a new one if not.
320  */
321 static int
322 server_access_cb (void *cls, struct MHD_Connection *mhd_connection,
323                   const char *url, const char *method, const char *version,
324                   const char *upload_data, size_t * upload_data_size,
325                   void **httpSessionCache)
326 {
327   struct Plugin *plugin = cls;
328   struct ServerConnection *sc = *httpSessionCache;
329   struct Session *s = NULL;
330
331   int res = MHD_YES;
332   struct MHD_Response *response;
333
334   GNUNET_assert (cls != NULL);
335   /* new connection */
336   if (sc == NULL)
337     {
338     uint32_t tag = 0;
339     const union MHD_ConnectionInfo *conn_info;
340     size_t addrlen;
341     struct GNUNET_PeerIdentity target;
342     int check = GNUNET_NO;
343     struct Session * t;
344     int direction;
345
346     conn_info = MHD_get_connection_info (mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS);
347     if (conn_info->client_addr->sa_family == AF_INET)
348       addrlen = sizeof (struct sockaddr_in);
349     else if (conn_info->client_addr->sa_family == AF_INET6)
350       addrlen = sizeof (struct sockaddr_in6);
351     else
352       return MHD_NO;
353
354     if ((strlen(&url[1]) >= 105)  && (url[104] == ';'))
355     {
356       char hash[104];
357       char * tagc = (char *) &url[105];
358       memcpy(&hash, &url[1], 103);
359       hash [103] = '\0';
360       if (GNUNET_OK == GNUNET_CRYPTO_hash_from_string ((const char *) &hash, &(target.hashPubKey)))
361       {
362         tag = strtoul (tagc, NULL, 10);
363         if (tagc > 0)
364           check = GNUNET_YES;
365       }
366     }
367
368     if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
369       direction = _RECEIVE;
370     if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
371       direction = _SEND;
372
373     if (check == GNUNET_NO)
374       goto error;
375
376     plugin->cur_connections++;
377
378 #if VERBOSE_SERVER
379     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
380                      "Server: New inbound connection from %s with tag %u\n", GNUNET_i2s(&target), tag);
381 #endif
382     /* find duplicate session */
383
384     t = plugin->head;
385
386     while (t != NULL)
387     {
388       if ((t->inbound) && (0 == memcmp (&t->target, &target, sizeof (struct GNUNET_PeerIdentity))) &&
389           /* FIXME add source address comparison */
390           (t->tag == tag))
391       break;
392       t = t->next;
393     }
394     if (t != NULL)
395     {
396 #if VERBOSE_SERVER
397       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
398                        "Server: Duplicate session, dismissing new connection from peer `%s'\n", GNUNET_i2s (&target));
399 #endif
400       goto error;
401     }
402
403     /* find semi-session */
404     t = plugin->server_semi_head;
405
406     while (t != NULL)
407     {
408       /* FIXME add source address comparison */
409       if ((0 == memcmp (&t->target, &target, sizeof (struct GNUNET_PeerIdentity))) &&
410           (t->tag == tag))
411       {
412         break;
413       }
414       t = t->next;
415     }
416
417     if (t == NULL)
418       goto create;
419
420 #if VERBOSE_SERVER
421     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
422                      "Server: Found existing semi-session for `%s'\n", GNUNET_i2s (&target));
423 #endif
424
425     if ((direction == _SEND) && (t->server_send != NULL))
426     {
427 #if VERBOSE_SERVER
428       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
429                        "Server: Duplicate GET session, dismissing new connection from peer `%s'\n", GNUNET_i2s (&target));
430 #endif
431       goto error;
432     }
433     else
434     {
435       s = t;
436       GNUNET_CONTAINER_DLL_remove(plugin->server_semi_head, plugin->server_semi_tail, s);
437       GNUNET_CONTAINER_DLL_insert(plugin->head, plugin->tail, s);
438 #if VERBOSE_SERVER
439       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
440                        "Server: Found matching semi-session, merging session for peer `%s'\n", GNUNET_i2s (&target));
441 #endif
442
443       goto found;
444     }
445     if ((direction == _RECEIVE) && (t->server_recv != NULL))
446     {
447 #if VERBOSE_SERVER
448       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
449                        "Server: Duplicate PUT session, dismissing new connection from peer `%s'\n", GNUNET_i2s (&target));
450 #endif
451       goto error;
452     }
453     else
454     {
455       s = t;
456       GNUNET_CONTAINER_DLL_remove(plugin->server_semi_head, plugin->server_semi_tail, s);
457       GNUNET_CONTAINER_DLL_insert(plugin->head, plugin->tail, s);
458 #if VERBOSE_SERVER
459       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
460                        "Server: Found matching semi-session, merging session for peer `%s'\n", GNUNET_i2s (&target));
461 #endif
462       goto found;
463     }
464
465 create:
466 /* create new session */
467 #if VERBOSE_SERVER
468     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
469                  "Server: Creating new session for peer `%s' \n", GNUNET_i2s (&target));
470 #endif
471
472     s = create_session (plugin,
473                         &target,
474                         conn_info->client_addr,
475                         addrlen,
476                         NULL,
477                         NULL);
478
479     s->inbound = GNUNET_YES;
480     s->delay = GNUNET_TIME_absolute_get_zero();
481     s->tag= tag;
482     if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
483       s->server_recv = s;
484     if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
485       s->server_send = s;
486     GNUNET_CONTAINER_DLL_insert (plugin->server_semi_head, plugin->server_semi_tail, s);
487
488     goto found;
489 error:
490 #if VERBOSE_SERVER
491     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
492                  "Server: Invalid connection request\n");
493 #endif
494         response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
495         res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
496         MHD_destroy_response (response);
497         return res;
498 found:
499     sc = GNUNET_malloc (sizeof (struct ServerConnection));
500     sc->mhd_conn = mhd_connection;
501     sc->direction = direction;
502     sc->session = s;
503     if (direction == _SEND)
504       s->server_send = sc;
505     if (direction == _RECEIVE)
506       s->server_recv = sc;
507
508     int to = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000);
509 #if VERBOSE_SERVER
510     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
511                      "Server: Setting Timeout to %u\n", to);
512 #endif
513     MHD_set_connection_option (mhd_connection, MHD_CONNECTION_OPTION_TIMEOUT, to);
514
515     (*httpSessionCache) = sc;
516   }
517
518
519   /* existing connection */
520   sc = (*httpSessionCache);
521   s = sc->session;
522
523   /* connection is to be disconnected*/
524   if (sc->disconnect == GNUNET_YES)
525   {
526     response = MHD_create_response_from_data (strlen ("Thank you!"), "Thank you!", MHD_NO, MHD_NO);
527     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
528 #if VERBOSE_SERVER
529     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
530                 "Sent HTTP/1.1: 200 OK as PUT Response\n");
531 #endif
532     MHD_destroy_response (response);
533     return MHD_YES;
534   }
535
536   GNUNET_assert (s != NULL);
537   if (sc->direction == _SEND)
538   {
539     response = MHD_create_response_from_callback (-1, 32 * 1024, &server_send_callback,
540                                            s, NULL);
541     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
542     MHD_destroy_response (response);
543     return MHD_YES;
544   }
545   if (sc->direction == _RECEIVE)
546   {
547     if (*upload_data_size == 0)
548     {
549 #if VERBOSE_SERVER
550   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
551                    "Server: Peer `%s' PUT on address `%s' connected\n",
552                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen));
553 #endif
554       return MHD_YES;
555     }
556
557     /* Recieving data */
558     if ((*upload_data_size > 0))
559     {
560 #if VERBOSE_SERVER
561   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
562                    "Server: peer `%s' PUT on address `%s' received %Zu bytes\n",
563                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen), *upload_data_size);
564 #endif
565       struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
566       if (( s->delay.abs_value < now.abs_value))
567       {
568 #if VERBOSE_SERVER
569         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
570                     "Server: %X: PUT with %u bytes forwarded to MST\n", s,
571                     *upload_data_size);
572 #endif
573         if (s->msg_tk == NULL)
574         {
575           s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
576         }
577         res = GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data, *upload_data_size, GNUNET_NO, GNUNET_NO);
578         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
579                          "Server: Received %Zu bytes\n",
580                     *upload_data_size);
581         (*upload_data_size) = 0;
582       }
583       else
584       {
585
586 #if DEBUG_HTTP
587        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
588                   "Connection %X: no inbound bandwidth available! Next read was delayed by %llu ms\n", s, now.abs_value - s->delay.abs_value);
589 #endif
590
591       }
592       return MHD_YES;
593     }
594     else
595       return MHD_NO;
596   }
597   return res;
598 }
599
600 /**
601  * Function that queries MHD's select sets and
602  * starts the task waiting for them.
603  * @param plugin plugin
604  * @param daemon_handle the MHD daemon handle
605  * @return gnunet task identifier
606  */
607 static GNUNET_SCHEDULER_TaskIdentifier
608 server_schedule (struct Plugin *plugin, struct MHD_Daemon *daemon_handle);
609
610 static void
611 server_disconnect_cb (void *cls, struct MHD_Connection *connection,
612                       void **httpSessionCache)
613 {
614   struct ServerConnection *sc = *httpSessionCache;
615   struct ServerConnection *tc = *httpSessionCache;
616   struct Session * s = NULL;
617   struct Session * t = NULL;
618   struct Plugin * plugin = NULL;
619
620   if (sc == NULL)
621     return;
622
623   s = sc->session;
624   plugin = s-> plugin;
625   if (sc->direction == _SEND)
626   {
627 #if VERBOSE_SERVER
628   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
629                    "Server: peer `%s' GET on address `%s' disconnected\n",
630                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen));
631 #endif
632     s->server_send = NULL;
633
634     if (s->server_recv != NULL)
635     {
636       tc = s->server_recv;
637       tc->disconnect = GNUNET_YES;
638       MHD_set_connection_option (sc->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT, 1);
639     }
640   }
641   if (sc->direction == _RECEIVE)
642   {
643 #if VERBOSE_SERVER
644   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
645                    "Server: peer `%s' PUT on address `%s' disconnected\n",
646                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen));
647 #endif
648     s->server_recv = NULL;
649     if (s->server_send != NULL)
650     {
651       tc = s->server_send;
652       tc->disconnect = GNUNET_YES;
653       MHD_set_connection_option (sc->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT, 1);
654     }
655     if (s->msg_tk != NULL)
656     {
657        GNUNET_SERVER_mst_destroy(s->msg_tk);
658        s->msg_tk = NULL;
659     }
660   }
661   GNUNET_free (sc);
662
663   t = plugin->server_semi_head;
664   while (t != NULL)
665   {
666     if (t == s)
667     {
668       GNUNET_CONTAINER_DLL_remove(plugin->server_semi_head, plugin->server_semi_tail, s);
669       GNUNET_CONTAINER_DLL_insert(plugin->head, plugin->tail, s);
670       break;
671     }
672     t = t->next;
673   }
674   plugin->cur_connections--;
675 /*
676   if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
677   {
678     GNUNET_SCHEDULER_cancel(plugin->server_v4_task);
679     plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
680   }
681   plugin->server_v4_task = server_schedule (plugin, plugin->server_v4);
682
683   if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
684    {
685      GNUNET_SCHEDULER_cancel(plugin->server_v6_task);
686      plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
687    }
688    plugin->server_v6_task = server_schedule (plugin, plugin->server_v6);
689 */
690   if ((s->server_send == NULL) && (s->server_recv == NULL))
691   {
692 #if VERBOSE_SERVER
693   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
694                    "Server: peer `%s' on address `%s' disconnected\n",
695                    GNUNET_i2s (&s->target), GNUNET_a2s (s->addr, s->addrlen));
696 #endif
697     if (s->msg_tk != NULL)
698     {
699        GNUNET_SERVER_mst_destroy(s->msg_tk);
700        s->msg_tk = NULL;
701     }
702
703     notify_session_end(s->plugin, &s->target, s);
704   }
705 }
706
707 int
708 server_disconnect (struct Session *s)
709 {
710   struct Plugin *plugin = s->plugin;
711   struct Session *t = plugin->head;
712
713   while (t != NULL)
714   {
715     if (t->inbound == GNUNET_YES)
716     {
717       if (t->server_send != NULL)
718       {
719         ((struct ServerConnection *) t->server_send)->disconnect = GNUNET_YES;
720       }
721       if (t->server_send != NULL)
722       {
723         ((struct ServerConnection *) t->server_send)->disconnect = GNUNET_YES;
724       }
725     }
726     t = t->next;
727   }
728
729
730   return GNUNET_OK;
731 }
732
733 int
734 server_send (struct Session *s, struct HTTP_Message * msg)
735 {
736   GNUNET_CONTAINER_DLL_insert (s->msg_head, s->msg_tail, msg);
737   return GNUNET_OK;
738 }
739
740
741
742 /**
743  * Call MHD IPv4 to process pending requests and then go back
744  * and schedule the next run.
745  * @param cls plugin as closure
746  * @param tc task context
747  */
748 static void
749 server_v4_run (void *cls,
750                            const struct GNUNET_SCHEDULER_TaskContext *tc)
751 {
752   struct Plugin *plugin = cls;
753   GNUNET_assert (cls != NULL);
754
755   plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
756
757   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
758     return;
759
760   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
761   plugin->server_v4_task = server_schedule (plugin, plugin->server_v4);
762 }
763
764
765 /**
766  * Call MHD IPv6 to process pending requests and then go back
767  * and schedule the next run.
768  * @param cls plugin as closure
769  * @param tc task context
770  */
771 static void
772 server_v6_run (void *cls,
773                            const struct GNUNET_SCHEDULER_TaskContext *tc)
774 {
775   struct Plugin *plugin = cls;
776   GNUNET_assert (cls != NULL);
777
778   plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
779
780   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
781     return;
782
783   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
784   plugin->server_v6_task = server_schedule (plugin, plugin->server_v6);
785 }
786
787 /**
788  * Function that queries MHD's select sets and
789  * starts the task waiting for them.
790  * @param plugin plugin
791  * @param daemon_handle the MHD daemon handle
792  * @return gnunet task identifier
793  */
794 static GNUNET_SCHEDULER_TaskIdentifier
795 server_schedule (struct Plugin *plugin, struct MHD_Daemon *daemon_handle)
796 {
797   GNUNET_SCHEDULER_TaskIdentifier ret;
798   fd_set rs;
799   fd_set ws;
800   fd_set es;
801   struct GNUNET_NETWORK_FDSet *wrs;
802   struct GNUNET_NETWORK_FDSet *wws;
803   struct GNUNET_NETWORK_FDSet *wes;
804   int max;
805   unsigned long long timeout;
806   int haveto;
807   struct GNUNET_TIME_Relative tv;
808
809   ret = GNUNET_SCHEDULER_NO_TASK;
810   FD_ZERO (&rs);
811   FD_ZERO (&ws);
812   FD_ZERO (&es);
813   wrs = GNUNET_NETWORK_fdset_create ();
814   wes = GNUNET_NETWORK_fdset_create ();
815   wws = GNUNET_NETWORK_fdset_create ();
816   max = -1;
817   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
818   haveto = MHD_get_timeout (daemon_handle, &timeout);
819   if (haveto == MHD_YES)
820     tv.rel_value = (uint64_t) timeout;
821   else
822     tv = GNUNET_TIME_UNIT_SECONDS;
823   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
824   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
825   GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
826   if (daemon_handle == plugin->server_v4)
827   {
828     if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
829     {
830       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
831       plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
832     }
833
834     ret =
835         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
836                                      GNUNET_SCHEDULER_NO_TASK, tv, wrs, wws,
837                                      &server_v4_run, plugin);
838   }
839   if (daemon_handle == plugin->server_v6)
840   {
841     if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
842     {
843       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
844       plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
845     }
846
847     ret =
848         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
849                                      GNUNET_SCHEDULER_NO_TASK, tv, wrs, wws,
850                                      &server_v6_run, plugin);
851   }
852   GNUNET_NETWORK_fdset_destroy (wrs);
853   GNUNET_NETWORK_fdset_destroy (wws);
854   GNUNET_NETWORK_fdset_destroy (wes);
855   return ret;
856 }
857
858 int
859 server_start (struct Plugin *plugin)
860 {
861   int res = GNUNET_OK;
862
863 #if BUILD_HTTPS
864   res = server_load_certificate (plugin);
865   if (res == GNUNET_SYSERR)
866   {
867     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TABORT\n");
868     return res;
869   }
870 #endif
871
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                                            (unsigned int) 3,
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                                            (unsigned int) 3,
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 */