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