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