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