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