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