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