1ce08435d7206386bed8ef456be2e83c3f1ce89a
[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 %s connection from %s with tag %u\n",
423                    method,
424                    GNUNET_i2s (&target), tag);
425
426   /* find duplicate session */
427   t = plugin->head;
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     GNUNET_break (0);
484     plugin->inbound_sessions ++;
485     GNUNET_STATISTICS_set (plugin->env->stats,
486         "# HTTP inbound sessions",
487         plugin->inbound_sessions,
488         GNUNET_NO);
489
490     goto found;
491   }
492   if ((direction == _RECEIVE) && (t->server_recv != NULL))
493   {
494     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
495                      "Server: Duplicate PUT session, dismissing new connection from peer `%s'\n",
496                      GNUNET_i2s (&target));
497     goto error;
498   }
499   else
500   {
501     s = t;
502     GNUNET_CONTAINER_DLL_remove (plugin->server_semi_head,
503                                  plugin->server_semi_tail, s);
504     GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
505     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
506                      "Server: Found matching semi-session, merging session for peer `%s'\n",
507                      GNUNET_i2s (&target));
508
509     GNUNET_break (0);
510     plugin->inbound_sessions ++;
511     GNUNET_STATISTICS_set (plugin->env->stats,
512         "# HTTP inbound sessions",
513         plugin->inbound_sessions,
514         GNUNET_NO);
515
516     goto found;
517   }
518
519 create:
520 /* create new session */
521   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
522                    "Server: Creating new session for peer `%s' \n",
523                    GNUNET_i2s (&target));
524   switch (conn_info->client_addr->sa_family)
525   {
526   case (AF_INET):
527     s4 = ((struct sockaddr_in *) conn_info->client_addr);
528     a4.u4_port = s4->sin_port;
529     memcpy (&a4.ipv4_addr, &s4->sin_addr, sizeof (struct in_addr));
530     a = &a4;
531     a_len = sizeof (struct IPv4HttpAddress);
532     ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) s4, sizeof (struct sockaddr_in));
533     break;
534   case (AF_INET6):
535     s6 = ((struct sockaddr_in6 *) conn_info->client_addr);
536     a6.u6_port = s6->sin6_port;
537     memcpy (&a6.ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
538     a = &a6;
539     a_len = sizeof (struct IPv6HttpAddress);
540     ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) s6, sizeof (struct sockaddr_in6));
541     break;
542   default:
543     GNUNET_break (0);
544     goto error;
545   }
546   s = create_session (plugin, &target, a, a_len, NULL, NULL);
547   s->ats_address_network_type = ats.value;
548
549   s->inbound = GNUNET_YES;
550   s->next_receive = GNUNET_TIME_absolute_get_zero ();
551   s->tag = tag;
552   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
553     s->server_recv = s;
554   if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
555     s->server_send = s;
556   GNUNET_CONTAINER_DLL_insert (plugin->server_semi_head,
557                                plugin->server_semi_tail, s);
558   goto found;
559
560 error:
561   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
562                    "Server: Invalid connection request\n");
563   return NULL;
564
565 found:
566   sc = GNUNET_malloc (sizeof (struct ServerConnection));
567   sc->mhd_conn = mhd_connection;
568   sc->direction = direction;
569   sc->session = s;
570   if (direction == _SEND)
571     s->server_send = sc;
572   if (direction == _RECEIVE)
573     s->server_recv = sc;
574
575 #if MHD_VERSION >= 0x00090E00
576   int to = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000);
577
578   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
579                    "Server: Setting timeout for %X to %u sec.\n", sc, to);
580   MHD_set_connection_option (mhd_connection, MHD_CONNECTION_OPTION_TIMEOUT, to);
581
582   struct MHD_Daemon *d = NULL;
583
584   if (s->addrlen == sizeof (struct IPv6HttpAddress))
585     d = plugin->server_v6;
586   if (s->addrlen == sizeof (struct IPv4HttpAddress))
587     d = plugin->server_v4;
588
589   server_reschedule (plugin, d, GNUNET_NO);
590 #endif
591   return sc;
592 }
593
594 /**
595  * Process GET or PUT request received via MHD.  For
596  * GET, queue response that will send back our pending
597  * messages.  For PUT, process incoming data and send
598  * to GNUnet core.  In either case, check if a session
599  * already exists and create a new one if not.
600  */
601 static int
602 server_access_cb (void *cls, struct MHD_Connection *mhd_connection,
603                   const char *url, const char *method, const char *version,
604                   const char *upload_data, size_t * upload_data_size,
605                   void **httpSessionCache)
606 {
607
608   struct Plugin *plugin = cls;
609   struct ServerConnection *sc = *httpSessionCache;
610   struct Session *s = NULL;
611
612   int res = MHD_YES;
613   struct MHD_Response *response;
614
615   GNUNET_assert (cls != NULL);
616   /* new connection */
617   if (sc == NULL)
618   {
619     sc = server_lookup_session (plugin, mhd_connection, url, method);
620     if (sc != NULL)
621       (*httpSessionCache) = sc;
622     else
623     {
624       response =
625           MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),
626                                          HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
627       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
628       MHD_destroy_response (response);
629       return res;
630     }
631   }
632
633   /* existing connection */
634   sc = (*httpSessionCache);
635   s = sc->session;
636
637   /* connection is to be disconnected */
638   if (sc->disconnect == GNUNET_YES)
639   {
640     /* Sent HTTP/1.1: 200 OK as PUT Response\ */
641     response =
642         MHD_create_response_from_data (strlen ("Thank you!"), "Thank you!",
643                                        MHD_NO, MHD_NO);
644     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
645     MHD_destroy_response (response);
646     return MHD_YES;
647   }
648
649   GNUNET_assert (s != NULL);
650   /* Check if both directions are connected */
651   if ((sc->session->server_recv == NULL) || (sc->session->server_send == NULL))
652   {
653     /* Delayed read from since not both semi-connections are connected */
654     return MHD_YES;
655   }
656
657   if (sc->direction == _SEND)
658   {
659     response =
660         MHD_create_response_from_callback (-1, 32 * 1024, &server_send_callback,
661                                            s, NULL);
662     MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
663     MHD_destroy_response (response);
664     return MHD_YES;
665   }
666   if (sc->direction == _RECEIVE)
667   {
668     if (*upload_data_size == 0)
669     {
670       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
671                        "Server: Peer `%s' PUT on address `%s' connected\n",
672                        GNUNET_i2s (&s->target),
673                        http_plugin_address_to_string (NULL, s->addr,
674                                                       s->addrlen));
675       return MHD_YES;
676     }
677
678     /* Receiving data */
679     if ((*upload_data_size > 0))
680     {
681       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
682                        "Server: peer `%s' PUT on address `%s' received %u bytes\n",
683                        GNUNET_i2s (&s->target),
684                        http_plugin_address_to_string (NULL, s->addr,
685                                                       s->addrlen),
686                        *upload_data_size);
687       struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
688
689       if ((s->next_receive.abs_value <= now.abs_value))
690       {
691         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
692                          "Server: %X: PUT with %u bytes forwarded to MST\n", s,
693                          *upload_data_size);
694         if (s->msg_tk == NULL)
695         {
696           s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
697         }
698             GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data,
699                                        *upload_data_size, GNUNET_NO, GNUNET_NO);
700
701 #if MHD_VERSION >= 0x00090E00
702         int to = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000);
703         struct ServerConnection *t = NULL;
704
705         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
706                          "Server: Received %u bytes\n", *upload_data_size);
707         /* Setting timeouts for other connections */
708         if (s->server_recv != NULL)
709         {
710           t = s->server_recv;
711           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
712                            "Server: Setting timeout for %X to %u sec.\n", t,
713                            to);
714           MHD_set_connection_option (t->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
715                                      to);
716         }
717         if (s->server_send != NULL)
718         {
719           t = s->server_send;
720           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
721                            "Server: Setting timeout for %X to %u sec.\n", t,
722                            to);
723           MHD_set_connection_option (t->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
724                                      to);
725         }
726         struct MHD_Daemon *d = NULL;
727
728         if (s->addrlen == sizeof (struct IPv6HttpAddress))
729           d = plugin->server_v6;
730         if (s->addrlen == sizeof (struct IPv4HttpAddress))
731           d = plugin->server_v4;
732         server_reschedule (plugin, d, GNUNET_NO);
733 #endif
734         (*upload_data_size) = 0;
735       }
736       else
737       {
738         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
739                     "Server: %X no inbound bandwidth available! Next read was delayed by %llu ms\n",
740                     s, now.abs_value - s->next_receive.abs_value);
741       }
742       return MHD_YES;
743     }
744     else
745       return MHD_NO;
746   }
747   return res;
748 }
749
750 static void
751 server_disconnect_cb (void *cls, struct MHD_Connection *connection,
752                       void **httpSessionCache)
753 {
754   struct ServerConnection *sc = *httpSessionCache;
755   struct ServerConnection *tc = NULL;
756   struct Session *s = NULL;
757   struct Session *t = NULL;
758   struct Plugin *plugin = NULL;
759 GNUNET_break (0);
760   if (sc == NULL)
761     return;
762
763   s = sc->session;
764   GNUNET_assert (NULL != p);
765   if (GNUNET_NO == exist_session(p, s))
766     return;
767
768   plugin = s->plugin;
769   if (sc->direction == _SEND)
770   {
771
772     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
773                      "Server: %X peer `%s' GET on address `%s' disconnected\n",
774                      s->server_send, GNUNET_i2s (&s->target),
775                      http_plugin_address_to_string (NULL, s->addr, s->addrlen));
776
777     s->server_send = NULL;
778
779     if (s->server_recv != NULL)
780     {
781       tc = s->server_recv;
782       tc->disconnect = GNUNET_YES;
783 #if MHD_VERSION >= 0x00090E00
784       MHD_set_connection_option (sc->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
785                                  1);
786 #endif
787     }
788   }
789   if (sc->direction == _RECEIVE)
790   {
791     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
792                      "Server: %X peer `%s' PUT on address `%s' disconnected\n",
793                      s->server_recv, GNUNET_i2s (&s->target),
794                      http_plugin_address_to_string (NULL, s->addr, s->addrlen));
795     s->server_recv = NULL;
796     if (s->server_send != NULL)
797     {
798       tc = s->server_send;
799       tc->disconnect = GNUNET_YES;
800 #if MHD_VERSION >= 0x00090E00
801       MHD_set_connection_option (sc->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
802                                  1);
803 #endif
804     }
805     if (s->msg_tk != NULL)
806     {
807       GNUNET_SERVER_mst_destroy (s->msg_tk);
808       s->msg_tk = NULL;
809     }
810   }
811   GNUNET_free (sc);
812
813   t = plugin->server_semi_head;
814   while (t != NULL)
815   {
816     if (t == s)
817     {
818       GNUNET_CONTAINER_DLL_remove (plugin->server_semi_head,
819                                    plugin->server_semi_tail, s);
820       GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
821       break;
822     }
823     t = t->next;
824   }
825   plugin->cur_connections--;
826
827   struct MHD_Daemon *d = NULL;
828
829   if (s->addrlen == sizeof (struct IPv6HttpAddress))
830     d = plugin->server_v6;
831   if (s->addrlen == sizeof (struct IPv4HttpAddress))
832     d = plugin->server_v4;
833   server_reschedule (plugin, d, GNUNET_NO);
834
835   if ((s->server_send == NULL) && (s->server_recv == NULL))
836   {
837     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
838                      "Server: peer `%s' on address `%s' disconnected\n",
839                      GNUNET_i2s (&s->target),
840                      http_plugin_address_to_string (NULL, s->addr, s->addrlen));
841     if (s->msg_tk != NULL)
842     {
843       GNUNET_SERVER_mst_destroy (s->msg_tk);
844       s->msg_tk = NULL;
845     }
846
847     GNUNET_assert (plugin->inbound_sessions > 0);
848     plugin->inbound_sessions --;
849     GNUNET_STATISTICS_set (plugin->env->stats,
850         "# HTTP inbound sessions",
851         plugin->inbound_sessions, GNUNET_NO);
852
853     notify_session_end (s->plugin, &s->target, s);
854   }
855 }
856
857 int
858 server_disconnect (struct Session *s)
859 {
860   struct Plugin *plugin = s->plugin;
861   struct Session *t = plugin->head;
862
863   while (t != NULL)
864   {
865     if (t->inbound == GNUNET_YES)
866     {
867       if (t->server_send != NULL)
868       {
869         ((struct ServerConnection *) t->server_send)->disconnect = GNUNET_YES;
870       }
871       if (t->server_send != NULL)
872       {
873         ((struct ServerConnection *) t->server_send)->disconnect = GNUNET_YES;
874       }
875     }
876     t = t->next;
877   }
878   return GNUNET_OK;
879 }
880
881 int
882 server_send (struct Session *s, struct HTTP_Message *msg)
883 {
884   GNUNET_CONTAINER_DLL_insert (s->msg_head, s->msg_tail, msg);
885
886   if (s->addrlen == sizeof (struct IPv4HttpAddress))
887   {
888     server_reschedule (s->plugin, s->plugin->server_v4, GNUNET_YES);
889   }
890   else if (s->addrlen == sizeof (struct IPv6HttpAddress))
891   {
892     server_reschedule (s->plugin, s->plugin->server_v6, GNUNET_YES);
893   }
894   else
895     return GNUNET_SYSERR;
896   return GNUNET_OK;
897 }
898
899
900
901 /**
902  * Call MHD IPv4 to process pending requests and then go back
903  * and schedule the next run.
904  * @param cls plugin as closure
905  * @param tc task context
906  */
907 static void
908 server_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
909 {
910   struct Plugin *plugin = cls;
911
912   GNUNET_assert (cls != NULL);
913
914   plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
915
916   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
917     return;
918 #if 0
919   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
920                    "Running IPv4 server\n");
921 #endif
922   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
923   if (plugin->server_v4 != NULL)
924     plugin->server_v4_task =
925         server_schedule (plugin, plugin->server_v4, GNUNET_NO);
926 }
927
928
929 /**
930  * Call MHD IPv6 to process pending requests and then go back
931  * and schedule the next run.
932  * @param cls plugin as closure
933  * @param tc task context
934  */
935 static void
936 server_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
937 {
938   struct Plugin *plugin = cls;
939
940   GNUNET_assert (cls != NULL);
941
942   plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
943
944   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
945     return;
946 #if 0
947   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
948                    "Running IPv6 server\n");
949 #endif
950   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
951   if (plugin->server_v6 != NULL)
952     plugin->server_v6_task =
953         server_schedule (plugin, plugin->server_v6, GNUNET_NO);
954 }
955
956 /**
957  * Function that queries MHD's select sets and
958  * starts the task waiting for them.
959  * @param plugin plugin
960  * @param daemon_handle the MHD daemon handle
961  * @return gnunet task identifier
962  */
963 static GNUNET_SCHEDULER_TaskIdentifier
964 server_schedule (struct Plugin *plugin, struct MHD_Daemon *daemon_handle,
965                  int now)
966 {
967   GNUNET_SCHEDULER_TaskIdentifier ret;
968   fd_set rs;
969   fd_set ws;
970   fd_set es;
971   struct GNUNET_NETWORK_FDSet *wrs;
972   struct GNUNET_NETWORK_FDSet *wws;
973   struct GNUNET_NETWORK_FDSet *wes;
974   int max;
975   unsigned long long timeout;
976   static unsigned long long last_timeout = 0;
977   int haveto;
978
979   struct GNUNET_TIME_Relative tv;
980
981   ret = GNUNET_SCHEDULER_NO_TASK;
982   FD_ZERO (&rs);
983   FD_ZERO (&ws);
984   FD_ZERO (&es);
985   wrs = GNUNET_NETWORK_fdset_create ();
986   wes = GNUNET_NETWORK_fdset_create ();
987   wws = GNUNET_NETWORK_fdset_create ();
988   max = -1;
989   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
990   haveto = MHD_get_timeout (daemon_handle, &timeout);
991   if (haveto == MHD_YES)
992   {
993     if (timeout != last_timeout)
994     {
995 #if VERBOSE_SERVER
996       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
997                        "SELECT Timeout changed from %llu to %llu\n",
998                        last_timeout, timeout);
999 #endif
1000       last_timeout = timeout;
1001     }
1002     tv.rel_value = (uint64_t) timeout;
1003   }
1004   else
1005     tv = GNUNET_TIME_UNIT_SECONDS;
1006   /* Force immediate run, since we have outbound data to send */
1007   if (now == GNUNET_YES)
1008     tv = GNUNET_TIME_UNIT_MILLISECONDS;
1009   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1010   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1011   GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
1012
1013   if (daemon_handle == plugin->server_v4)
1014   {
1015     if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1016     {
1017       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1018       plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1019     }
1020 #if 0
1021     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1022                      "Scheduling IPv4 server task in %llu ms\n", tv);
1023 #endif
1024     ret =
1025         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1026                                      tv, wrs, wws,
1027                                      &server_v4_run, plugin);
1028   }
1029   if (daemon_handle == plugin->server_v6)
1030   {
1031     if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1032     {
1033       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1034       plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1035     }
1036 #if 0
1037     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1038                      "Scheduling IPv6 server task in %llu ms\n", tv);
1039 #endif
1040     ret =
1041         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1042                                      tv, wrs, wws,
1043                                      &server_v6_run, plugin);
1044   }
1045   GNUNET_NETWORK_fdset_destroy (wrs);
1046   GNUNET_NETWORK_fdset_destroy (wws);
1047   GNUNET_NETWORK_fdset_destroy (wes);
1048   return ret;
1049 }
1050
1051 int
1052 server_start (struct Plugin *plugin)
1053 {
1054   int res = GNUNET_OK;
1055   unsigned int timeout;
1056   p = plugin;
1057   GNUNET_assert (NULL != plugin);
1058
1059 #if BUILD_HTTPS
1060   res = server_load_certificate (plugin);
1061   if (res == GNUNET_SYSERR)
1062   {
1063     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1064                      "Could not load or create server certificate! Loading plugin failed!\n");
1065     return res;
1066   }
1067 #endif
1068
1069
1070 #if MHD_VERSION >= 0x00090E00
1071   timeout = HTTP_NOT_VALIDATED_TIMEOUT.rel_value / 1000;
1072   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1073                    "MHD can set timeout per connection! Default time out %u sec.\n",
1074                    timeout);
1075 #else
1076   timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000;
1077   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1078                    "MHD cannot set timeout per connection! Default time out %u sec.\n",
1079                    timeout);
1080 #endif
1081   plugin->server_v4 = NULL;
1082   if (plugin->ipv4 == GNUNET_YES)
1083   {
1084     plugin->server_v4 = MHD_start_daemon (
1085 #if VERBOSE_SERVER
1086                                            MHD_USE_DEBUG |
1087 #endif
1088 #if BUILD_HTTPS
1089                                            MHD_USE_SSL |
1090 #endif
1091                                            MHD_NO_FLAG, plugin->port,
1092                                            &server_accept_cb, plugin,
1093                                            &server_access_cb, plugin,
1094                                            MHD_OPTION_SOCK_ADDR,
1095                                            (struct sockaddr_in *)
1096                                            plugin->server_addr_v4,
1097                                            MHD_OPTION_CONNECTION_LIMIT,
1098                                            (unsigned int)
1099                                            plugin->max_connections,
1100 #if BUILD_HTTPS
1101                                            MHD_OPTION_HTTPS_PRIORITIES,
1102                                            plugin->crypto_init,
1103                                            MHD_OPTION_HTTPS_MEM_KEY,
1104                                            plugin->key,
1105                                            MHD_OPTION_HTTPS_MEM_CERT,
1106                                            plugin->cert,
1107 #endif
1108                                            MHD_OPTION_CONNECTION_TIMEOUT,
1109                                            timeout,
1110                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
1111                                            (size_t) (2 *
1112                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
1113                                            MHD_OPTION_NOTIFY_COMPLETED,
1114                                            &server_disconnect_cb, plugin,
1115                                            MHD_OPTION_EXTERNAL_LOGGER,
1116                                            server_log, NULL, MHD_OPTION_END);
1117   }
1118   plugin->server_v6 = NULL;
1119   if (plugin->ipv6 == GNUNET_YES)
1120   {
1121     plugin->server_v6 = MHD_start_daemon (
1122 #if VERBOSE_SERVER
1123                                            MHD_USE_DEBUG |
1124 #endif
1125 #if BUILD_HTTPS
1126                                            MHD_USE_SSL |
1127 #endif
1128                                            MHD_USE_IPv6, plugin->port,
1129                                            &server_accept_cb, plugin,
1130                                            &server_access_cb, plugin,
1131                                            MHD_OPTION_SOCK_ADDR,
1132                                            (struct sockaddr_in6 *)
1133                                            plugin->server_addr_v6,
1134                                            MHD_OPTION_CONNECTION_LIMIT,
1135                                            (unsigned int)
1136                                            plugin->max_connections,
1137 #if BUILD_HTTPS
1138                                            MHD_OPTION_HTTPS_PRIORITIES,
1139                                            plugin->crypto_init,
1140                                            MHD_OPTION_HTTPS_MEM_KEY,
1141                                            plugin->key,
1142                                            MHD_OPTION_HTTPS_MEM_CERT,
1143                                            plugin->cert,
1144 #endif
1145                                            MHD_OPTION_CONNECTION_TIMEOUT,
1146                                            timeout,
1147                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
1148                                            (size_t) (2 *
1149                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
1150                                            MHD_OPTION_NOTIFY_COMPLETED,
1151                                            &server_disconnect_cb, plugin,
1152                                            MHD_OPTION_EXTERNAL_LOGGER,
1153                                            server_log, NULL, MHD_OPTION_END);
1154
1155   }
1156
1157   if ((plugin->ipv4 == GNUNET_YES) && (plugin->server_v4 == NULL))
1158   {
1159     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1160                      "Failed to start %s IPv4 server component on port %u\n",
1161                      plugin->name, plugin->port);
1162     return GNUNET_SYSERR;
1163   }
1164   server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
1165
1166   if ((plugin->ipv6 == GNUNET_YES) && (plugin->server_v6 == NULL))
1167   {
1168     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1169                      "Failed to start %s IPv6 server component on port %u\n",
1170                      plugin->name, plugin->port);
1171     return GNUNET_SYSERR;
1172   }
1173   server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
1174
1175
1176 #if DEBUG_HTTP
1177   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1178                    "%s server component started on port %u\n", plugin->name,
1179                    plugin->port);
1180 #endif
1181   return res;
1182 }
1183
1184 void
1185 server_stop (struct Plugin *plugin)
1186 {
1187   struct Session *s = NULL;
1188   struct Session *t = NULL;
1189
1190   p = NULL;
1191
1192   struct MHD_Daemon *server_v4_tmp = plugin->server_v4;
1193
1194   plugin->server_v4 = NULL;
1195   struct MHD_Daemon *server_v6_tmp = plugin->server_v6;
1196
1197   plugin->server_v6 = NULL;
1198
1199   if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1200   {
1201     GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1202     plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1203   }
1204
1205   if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1206   {
1207     GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1208     plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1209   }
1210
1211   if (server_v6_tmp != NULL)
1212   {
1213     MHD_stop_daemon (server_v4_tmp);
1214   }
1215   if (server_v6_tmp != NULL)
1216   {
1217     MHD_stop_daemon (server_v6_tmp);
1218   }
1219
1220   /* cleaning up semi-sessions never propagated */
1221   s = plugin->server_semi_head;
1222   while (s != NULL)
1223   {
1224 #if VERBOSE_SERVER
1225     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1226                      "Deleting semi-sessions %p\n", s);
1227 #endif
1228     t = s->next;
1229     struct HTTP_Message *msg = s->msg_head;
1230     struct HTTP_Message *tmp = NULL;
1231
1232     while (msg != NULL)
1233     {
1234       tmp = msg->next;
1235
1236       GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
1237       if (msg->transmit_cont != NULL)
1238       {
1239         msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_SYSERR);
1240       }
1241       GNUNET_free (msg);
1242       msg = tmp;
1243     }
1244
1245     delete_session (s);
1246     s = t;
1247   }
1248
1249 #if BUILD_HTTPS
1250   GNUNET_free_non_null (plugin->crypto_init);
1251   GNUNET_free_non_null (plugin->cert);
1252   GNUNET_free_non_null (plugin->key);
1253 #endif
1254
1255 #if DEBUG_HTTP
1256   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1257                    "%s server component stopped\n", plugin->name);
1258 #endif
1259 }
1260
1261
1262
1263 /* end of plugin_transport_http.c */