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