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