6c7c5a8f148c89c14717f7d41146f9807a62abc4
[oweals/gnunet.git] / src / hostlist / hostlist-server.c
1 /*
2      This file is part of GNUnet.
3      (C) 2008, 2009, 2010 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 2, 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 hostlist/hostlist-server.c
23  * @author Christian Grothoff
24  * @brief application to provide an integrated hostlist HTTP server
25  */
26
27 #include "platform.h"
28 #include <microhttpd.h>
29 #include "hostlist-server.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_peerinfo_service.h"
32
33 #define DEBUG_HOSTLIST_SERVER GNUNET_NO
34
35 /**
36  * How often should we recalculate our response to hostlist requests?
37  */
38 #define RESPONSE_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
39
40 /**
41  * Handle to the HTTP server as provided by libmicrohttpd for IPv6.
42  */
43 static struct MHD_Daemon *daemon_handle_v6;
44
45 /**
46  * Handle to the HTTP server as provided by libmicrohttpd for IPv4.
47  */
48 static struct MHD_Daemon *daemon_handle_v4;
49
50 /**
51  * Our configuration.
52  */
53 static const struct GNUNET_CONFIGURATION_Handle *cfg;
54
55 /**
56  * Our scheduler.
57  */
58 static struct GNUNET_SCHEDULER_Handle *sched;
59
60 /**
61  * For keeping statistics.
62  */ 
63 static struct GNUNET_STATISTICS_Handle *stats;
64
65 /**
66  * Our primary task for IPv4.
67  */
68 static GNUNET_SCHEDULER_TaskIdentifier hostlist_task_v4;
69
70 /**
71  * Our primary task for IPv6.
72  */
73 static GNUNET_SCHEDULER_TaskIdentifier hostlist_task_v6;
74
75 /**
76  * Task that updates our HTTP response.
77  */
78 static GNUNET_SCHEDULER_TaskIdentifier response_task;
79
80 /**
81  * Our canonical response.
82  */
83 static struct MHD_Response *response;
84
85 /**
86  * NULL if we are not currenlty iterating over peer information.
87  */
88 static struct GNUNET_PEERINFO_IteratorContext *pitr;
89
90 /**
91  * Context for host processor.
92  */
93 struct HostSet
94 {
95   unsigned int size;
96
97   char *data;
98 };
99
100
101 /**
102  * Task that will produce a new response object.
103  */
104 static void
105 update_response (void *cls,
106                  const struct GNUNET_SCHEDULER_TaskContext *tc);
107
108
109 /**
110  * Function that assembles our response.
111  */
112 static void
113 finish_response (struct HostSet *results)
114 {
115   struct GNUNET_TIME_Relative freq;
116   
117   if (response != NULL)
118     MHD_destroy_response (response);
119 #if DEBUG_HOSTLIST_SERVER
120   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
121               "Creating hostlist response with %u bytes\n",
122               (unsigned int) results->size);
123 #endif
124   response = MHD_create_response_from_data (results->size,
125                                             results->data, MHD_YES, MHD_NO);
126   if ( (daemon_handle_v4 != NULL) ||
127        (daemon_handle_v6 != NULL) )    
128     {
129       freq = RESPONSE_UPDATE_FREQUENCY;
130       if (results->size == 0)
131         freq = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250);
132       /* schedule next update of the response */  
133       response_task = GNUNET_SCHEDULER_add_delayed (sched,
134                                                     freq,
135                                                     &update_response,
136                                                     NULL);
137     }
138   else
139     {
140       /* already past shutdown */
141       MHD_destroy_response (response);
142       response = NULL;
143     }
144   GNUNET_STATISTICS_set (stats,
145                          gettext_noop("bytes in hostlist"),
146                          results->size,
147                          GNUNET_YES);
148   GNUNET_free (results);
149 }
150
151
152 /**
153  * Set 'cls' to GNUNET_YES (we have an address!).
154  *
155  * @param cls closure, an 'int*'
156  * @param tname name of the transport (ignored)
157  * @param expiration expiration time (call is ignored if this is in the past)
158  * @param addr the address (ignored)
159  * @param addrlen length of the address (ignored)
160  * @return  GNUNET_SYSERR to stop iterating (unless expiration has occured)
161  */
162 static int
163 check_has_addr (void *cls,
164                 const char *tname,
165                 struct GNUNET_TIME_Absolute expiration,
166                 const void *addr, size_t addrlen)
167 {
168   int *arg = cls;
169
170   if (GNUNET_TIME_absolute_get_remaining (expiration).value == 0)
171     {
172       GNUNET_STATISTICS_update (stats,
173                                 gettext_noop("expired addresses encountered"),
174                                 1,
175                                 GNUNET_YES);
176       return GNUNET_YES; /* ignore this address */
177     }
178   *arg = GNUNET_YES;
179   return GNUNET_SYSERR;
180 }
181
182
183 /**
184  * Callback that processes each of the known HELLOs for the
185  * hostlist response construction.
186  */
187 static void
188 host_processor (void *cls,
189                 const struct GNUNET_PeerIdentity * peer,
190                 const struct GNUNET_HELLO_Message *hello,
191                 uint32_t trust)
192 {
193   struct HostSet *results = cls;
194   size_t old;
195   size_t s;
196   int has_addr;
197   
198   if (peer == NULL)
199     {
200       pitr = NULL;
201       finish_response (results);
202       return;
203     }
204   has_addr = GNUNET_NO;
205   GNUNET_HELLO_iterate_addresses (hello,
206                                   GNUNET_NO,
207                                   &check_has_addr,
208                                   &has_addr);
209   if (GNUNET_NO == has_addr)
210     {
211       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
212                   "HELLO for peer `%4s' has no address, not suitable for hostlist!\n",
213                   GNUNET_i2s (peer));
214       GNUNET_STATISTICS_update (stats,
215                                 gettext_noop("HELLOs without addresses encountered (ignored)"),
216                                 1,
217                                 GNUNET_NO);
218       return; 
219     }
220   old = results->size;
221   s = GNUNET_HELLO_size(hello);
222 #if DEBUG_HOSTLIST_SERVER
223   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
224               "Received %u bytes of `%s' from peer `%s' for hostlist.\n",
225               (unsigned int) s,
226               "HELLO",
227               GNUNET_i2s (peer));
228 #endif
229   if (old + s >= GNUNET_MAX_MALLOC_CHECKED)
230     {
231       GNUNET_STATISTICS_update (stats,
232                                 gettext_noop("bytes not included in hostlist (size limit)"),
233                                 s,
234                                 GNUNET_NO);
235       return; /* too large, skip! */
236     }
237   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
238               "Adding peer `%s' to hostlist (%u bytes)\n",
239               GNUNET_i2s (peer),
240               (unsigned int) s);
241   GNUNET_array_grow (results->data,
242                      results->size,
243                      old + s);
244   memcpy (&results->data[old], hello, s);
245 }
246
247
248 /**
249  * Task that will produce a new response object.
250  */
251 static void
252 update_response (void *cls,
253                  const struct GNUNET_SCHEDULER_TaskContext *tc)
254 {
255   struct HostSet *results;
256
257   response_task = GNUNET_SCHEDULER_NO_TASK;
258   results = GNUNET_malloc(sizeof(struct HostSet));
259   pitr = GNUNET_PEERINFO_iterate (cfg, sched, 
260                                   NULL,
261                                   0, 
262                                   GNUNET_TIME_UNIT_MINUTES,
263                                   &host_processor,
264                                   results);
265 }
266
267
268 /**
269  * Hostlist access policy (very permissive, allows everything).
270  */
271 static int
272 accept_policy_callback (void *cls,
273                         const struct sockaddr *addr, socklen_t addrlen)
274 {
275   if (NULL == response)
276     {
277 #if DEBUG_HOSTLIST_SERVER
278       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
279                   "Received request for hostlist, but I am not yet ready; rejecting!\n");
280 #endif
281       return MHD_NO;
282     }
283   return MHD_YES;               /* accept all */
284 }
285
286
287 /**
288  * Main request handler.
289  */
290 static int
291 access_handler_callback (void *cls,
292                          struct MHD_Connection *connection,
293                          const char *url,
294                          const char *method,
295                          const char *version,
296                          const char *upload_data,
297                          size_t*upload_data_size, void **con_cls)
298 {
299   static int dummy;
300   
301   if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
302     {
303       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
304                   _("Refusing `%s' request to hostlist server\n"),
305                   method);
306       GNUNET_STATISTICS_update (stats,
307                                 gettext_noop("hostlist requests refused (not HTTP GET)"),
308                                 1,
309                                 GNUNET_YES);
310       return MHD_NO;
311     }
312   if (NULL == *con_cls)
313     {
314       (*con_cls) = &dummy;
315 #if DEBUG_HOSTLIST_SERVER
316       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
317                   _("Sending 100 CONTINUE reply\n"));
318 #endif
319       return MHD_YES;           /* send 100 continue */
320     }
321   if (*upload_data_size != 0)
322     {
323       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
324                   _("Refusing `%s' request with %llu bytes of upload data\n"),
325                   method,
326                   (unsigned long long) *upload_data_size);
327       GNUNET_STATISTICS_update (stats,
328                                 gettext_noop("hostlist requests refused (upload data)"),
329                                 1,
330                                 GNUNET_YES);
331       return MHD_NO;              /* do not support upload data */
332     }
333   if (response == NULL)
334     {
335       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
336                   _("Could not handle hostlist request since I do not have a response yet\n"));
337       GNUNET_STATISTICS_update (stats,
338                                 gettext_noop("hostlist requests refused (not ready)"),
339                                 1,
340                                 GNUNET_YES);
341       return MHD_NO;              /* internal error, no response yet */
342     }
343   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
344               _("Received request for our hostlist\n"));
345   GNUNET_STATISTICS_update (stats,
346                             gettext_noop("hostlist requests processed"),
347                             1,
348                             GNUNET_YES);
349   return MHD_queue_response (connection, MHD_HTTP_OK, response);
350 }
351
352 /**
353  * Method called whenever a given peer connects.
354  *
355  * @param cls closure
356  * @param peer peer identity this notification is about
357  * @param latency reported latency of the connection with 'other'
358  * @param distance reported distance (DV) to 'other'
359  */
360 static void
361 connect_handler (void *cls,
362                  const struct
363                  GNUNET_PeerIdentity * peer,
364                  struct GNUNET_TIME_Relative latency,
365                  uint32_t distance)
366 {
367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
368               "A new peer connected to the server, preparing to send hostlist advertisement\n");
369 }
370
371
372 /**
373  * Method called whenever a given peer disconnects.
374  *
375  * @param cls closure
376  * @param peer peer identity this notification is about
377  */
378 static void
379 disconnect_handler (void *cls,
380                     const struct
381                     GNUNET_PeerIdentity * peer)
382 {
383
384 }
385
386
387 /**
388  * Function that queries MHD's select sets and
389  * starts the task waiting for them.
390  */
391 static GNUNET_SCHEDULER_TaskIdentifier
392 prepare_daemon (struct MHD_Daemon *daemon_handle);
393
394 /**
395  * Call MHD to process pending requests and then go back
396  * and schedule the next run.
397  */
398 static void
399 run_daemon (void *cls,
400             const struct GNUNET_SCHEDULER_TaskContext *tc)
401 {
402   struct MHD_Daemon *daemon_handle = cls;
403
404   if (daemon_handle == daemon_handle_v4)
405     hostlist_task_v4 = GNUNET_SCHEDULER_NO_TASK;
406   else
407     hostlist_task_v6 = GNUNET_SCHEDULER_NO_TASK;
408
409   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
410     return;    
411   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
412   if (daemon_handle == daemon_handle_v4)
413     hostlist_task_v4 = prepare_daemon (daemon_handle);
414   else
415     hostlist_task_v6 = prepare_daemon (daemon_handle);
416 }
417
418
419 /**
420  * Function that queries MHD's select sets and
421  * starts the task waiting for them.
422  */
423 static GNUNET_SCHEDULER_TaskIdentifier
424 prepare_daemon (struct MHD_Daemon *daemon_handle)
425 {
426   GNUNET_SCHEDULER_TaskIdentifier ret;
427   fd_set rs;
428   fd_set ws;
429   fd_set es;
430   struct GNUNET_NETWORK_FDSet *wrs;
431   struct GNUNET_NETWORK_FDSet *wws;
432   struct GNUNET_NETWORK_FDSet *wes;
433   int max;
434   unsigned long long timeout;
435   int haveto;
436   struct GNUNET_TIME_Relative tv;
437   
438   FD_ZERO(&rs);
439   FD_ZERO(&ws);
440   FD_ZERO(&es);
441   wrs = GNUNET_NETWORK_fdset_create ();
442   wes = GNUNET_NETWORK_fdset_create ();
443   wws = GNUNET_NETWORK_fdset_create ();
444   max = -1;
445   GNUNET_assert (MHD_YES ==
446                  MHD_get_fdset (daemon_handle,
447                                 &rs,
448                                 &ws,
449                                 &es,
450                                 &max));
451   haveto = MHD_get_timeout (daemon_handle, &timeout);
452   if (haveto == MHD_YES)
453     tv.value = (uint64_t) timeout;
454   else
455     tv = GNUNET_TIME_UNIT_FOREVER_REL;
456   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
457   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
458   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
459   ret = GNUNET_SCHEDULER_add_select (sched,
460                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
461                                      GNUNET_SCHEDULER_NO_TASK,
462                                      tv,
463                                      wrs,
464                                      wws,
465                                      &run_daemon,
466                                      daemon_handle);
467   GNUNET_NETWORK_fdset_destroy (wrs);
468   GNUNET_NETWORK_fdset_destroy (wws);
469   GNUNET_NETWORK_fdset_destroy (wes);
470   return ret;
471 }
472
473
474
475 /**
476  * Start server offering our hostlist.
477  *
478  * @return GNUNET_OK on success
479  */
480 int
481 GNUNET_HOSTLIST_server_start (const struct GNUNET_CONFIGURATION_Handle *c,
482                               struct GNUNET_SCHEDULER_Handle *s,
483                               struct GNUNET_STATISTICS_Handle *st,
484                               GNUNET_CORE_ConnectEventHandler *server_ch,
485                               GNUNET_CORE_DisconnectEventHandler *server_dh)
486 {
487   unsigned long long port;
488
489   sched = s;
490   cfg = c;
491   stats = st;
492   if (-1 == GNUNET_CONFIGURATION_get_value_number (cfg,
493                                                    "HOSTLIST",
494                                                    "HTTPPORT", 
495                                                    &port))
496     return GNUNET_SYSERR;
497   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
498               _("Hostlist service starts on port %llu\n"),
499               port);
500   daemon_handle_v6 = MHD_start_daemon (MHD_USE_IPv6 
501 #if DEBUG_HOSTLIST_SERVER
502                                        | MHD_USE_DEBUG
503 #endif
504                                        ,
505                                        (unsigned short) port,
506                                        &accept_policy_callback,
507                                        NULL,
508                                        &access_handler_callback,
509                                        NULL,
510                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
511                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
512                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
513                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
514                                        MHD_OPTION_END);
515   daemon_handle_v4 = MHD_start_daemon (MHD_NO_FLAG
516 #if DEBUG_HOSTLIST_SERVER
517                                        | MHD_USE_DEBUG
518 #endif
519                                        ,
520                                        (unsigned short) port,
521                                        &accept_policy_callback,
522                                        NULL,
523                                        &access_handler_callback,
524                                        NULL,
525                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
526                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
527                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
528                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
529                                        MHD_OPTION_END);
530
531   if ( (daemon_handle_v6 == NULL) &&
532        (daemon_handle_v4 == NULL) )
533     {
534       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
535                   _("Could not start hostlist HTTP server on port %u\n"),
536                   (unsigned short) port);
537       return GNUNET_SYSERR;    
538     }
539
540   *server_ch = &connect_handler;
541   *server_dh = &disconnect_handler;
542
543   if (daemon_handle_v4 != NULL)
544     hostlist_task_v4 = prepare_daemon (daemon_handle_v4);
545   if (daemon_handle_v6 != NULL)
546     hostlist_task_v6 = prepare_daemon (daemon_handle_v6);
547   response_task = GNUNET_SCHEDULER_add_now (sched,
548                                             &update_response,
549                                             NULL);
550   return GNUNET_OK;
551 }
552
553 /**
554  * Stop server offering our hostlist.
555  */
556 void
557 GNUNET_HOSTLIST_server_stop ()
558 {
559 #if DEBUG_HOSTLIST_SERVER
560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
561               "Hostlist server shutdown\n");
562 #endif
563   if (GNUNET_SCHEDULER_NO_TASK != hostlist_task_v6)
564     {
565       GNUNET_SCHEDULER_cancel (sched, hostlist_task_v6);
566       hostlist_task_v6 = GNUNET_SCHEDULER_NO_TASK;
567     }
568   if (GNUNET_SCHEDULER_NO_TASK != hostlist_task_v4)
569     {
570       GNUNET_SCHEDULER_cancel (sched, hostlist_task_v4);
571       hostlist_task_v4 = GNUNET_SCHEDULER_NO_TASK;
572     }
573   if (pitr != NULL)
574     {
575       GNUNET_PEERINFO_iterate_cancel (pitr);
576       pitr = NULL;
577     }
578   if (GNUNET_SCHEDULER_NO_TASK != response_task)
579     {
580       GNUNET_SCHEDULER_cancel (sched, response_task);
581       response_task = GNUNET_SCHEDULER_NO_TASK;
582     }
583   if (NULL != daemon_handle_v4)
584     {
585       MHD_stop_daemon (daemon_handle_v4);
586       daemon_handle_v4 = NULL;
587     }
588   if (NULL != daemon_handle_v6)
589     {
590       MHD_stop_daemon (daemon_handle_v6);
591       daemon_handle_v6 = NULL;
592     }
593   if (response != NULL)
594     {
595       MHD_destroy_response (response);
596       response = NULL;
597     }
598 }
599
600 /* end of hostlist-server.c */