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