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