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