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