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