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