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