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