9583d6a4f66127f3b6b7b0a1793855a3ba23a768
[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_YES
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  * Callback that processes each of the known HELLOs for the
154  * hostlist response construction.
155  */
156 static void
157 host_processor (void *cls,
158                 const struct GNUNET_PeerIdentity * peer,
159                 const struct GNUNET_HELLO_Message *hello,
160                 uint32_t trust)
161 {
162   struct HostSet *results = cls;
163   size_t old;
164   size_t s;
165   
166   if (peer == NULL)
167     {
168       pitr = NULL;
169       finish_response (results);
170       return;
171     }
172   old = results->size;
173   s = GNUNET_HELLO_size(hello);
174 #if DEBUG_HOSTLIST_SERVER
175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
176               "Received %u bytes of `%s' from peer `%s' for hostlist.\n",
177               (unsigned int) s,
178               "HELLO",
179               GNUNET_i2s (peer));
180 #endif
181   if (old + s >= GNUNET_MAX_MALLOC_CHECKED)
182     {
183       GNUNET_STATISTICS_update (stats,
184                                 gettext_noop("bytes not included in hostlist (size limit)"),
185                                 s,
186                                 GNUNET_NO);
187       return; /* too large, skip! */
188     }
189   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
190               "Adding peer `%s' to hostlist (%u bytes)\n",
191               GNUNET_i2s (peer),
192               (unsigned int) s);
193   GNUNET_array_grow (results->data,
194                      results->size,
195                      old + s);
196   memcpy (&results->data[old], hello, s);
197 }
198
199
200 /**
201  * Task that will produce a new response object.
202  */
203 static void
204 update_response (void *cls,
205                  const struct GNUNET_SCHEDULER_TaskContext *tc)
206 {
207   struct HostSet *results;
208
209   response_task = GNUNET_SCHEDULER_NO_TASK;
210   results = GNUNET_malloc(sizeof(struct HostSet));
211   pitr = GNUNET_PEERINFO_iterate (cfg, sched, 
212                                   NULL,
213                                   0, 
214                                   GNUNET_TIME_UNIT_MINUTES,
215                                   &host_processor,
216                                   results);
217 }
218
219
220 /**
221  * Hostlist access policy (very permissive, allows everything).
222  */
223 static int
224 accept_policy_callback (void *cls,
225                         const struct sockaddr *addr, socklen_t addrlen)
226 {
227   if (NULL == response)
228     {
229 #if DEBUG_HOSTLIST_SERVER
230       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
231                   "Received request for hostlist, but I am not yet ready; rejecting!\n");
232 #endif
233       return MHD_NO;
234     }
235   return MHD_YES;               /* accept all */
236 }
237
238
239 /**
240  * Main request handler.
241  */
242 static int
243 access_handler_callback (void *cls,
244                          struct MHD_Connection *connection,
245                          const char *url,
246                          const char *method,
247                          const char *version,
248                          const char *upload_data,
249                          size_t*upload_data_size, void **con_cls)
250 {
251   static int dummy;
252   
253   if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
254     {
255       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
256                   _("Refusing `%s' request to hostlist server\n"),
257                   method);
258       GNUNET_STATISTICS_update (stats,
259                                 gettext_noop("hostlist requests refused (not HTTP GET)"),
260                                 1,
261                                 GNUNET_YES);
262       return MHD_NO;
263     }
264   if (NULL == *con_cls)
265     {
266       (*con_cls) = &dummy;
267 #if DEBUG_HOSTLIST_SERVER
268       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
269                   _("Sending 100 CONTINUE reply\n"));
270 #endif
271       return MHD_YES;           /* send 100 continue */
272     }
273   if (*upload_data_size != 0)
274     {
275       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
276                   _("Refusing `%s' request with %llu bytes of upload data\n"),
277                   method,
278                   (unsigned long long) *upload_data_size);
279       GNUNET_STATISTICS_update (stats,
280                                 gettext_noop("hostlist requests refused (upload data)"),
281                                 1,
282                                 GNUNET_YES);
283       return MHD_NO;              /* do not support upload data */
284     }
285   if (response == NULL)
286     {
287       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
288                   _("Could not handle hostlist request since I do not have a response yet\n"));
289       GNUNET_STATISTICS_update (stats,
290                                 gettext_noop("hostlist requests refused (not ready)"),
291                                 1,
292                                 GNUNET_YES);
293       return MHD_NO;              /* internal error, no response yet */
294     }
295   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
296               _("Received request for our hostlist\n"));
297   GNUNET_STATISTICS_update (stats,
298                             gettext_noop("hostlist requests processed"),
299                             1,
300                             GNUNET_YES);
301   return MHD_queue_response (connection, MHD_HTTP_OK, response);
302 }
303
304
305 /**
306  * Function that queries MHD's select sets and
307  * starts the task waiting for them.
308  */
309 static GNUNET_SCHEDULER_TaskIdentifier
310 prepare_daemon (struct MHD_Daemon *daemon_handle);
311
312 /**
313  * Call MHD to process pending requests and then go back
314  * and schedule the next run.
315  */
316 static void
317 run_daemon (void *cls,
318             const struct GNUNET_SCHEDULER_TaskContext *tc)
319 {
320   struct MHD_Daemon *daemon_handle = cls;
321
322   if (daemon_handle == daemon_handle_v4)
323     hostlist_task_v4 = GNUNET_SCHEDULER_NO_TASK;
324   else
325     hostlist_task_v6 = GNUNET_SCHEDULER_NO_TASK;
326
327   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
328     return;    
329   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
330   if (daemon_handle == daemon_handle_v4)
331     hostlist_task_v4 = prepare_daemon (daemon_handle);
332   else
333     hostlist_task_v6 = prepare_daemon (daemon_handle);
334 }
335
336
337 /**
338  * Function that queries MHD's select sets and
339  * starts the task waiting for them.
340  */
341 static GNUNET_SCHEDULER_TaskIdentifier
342 prepare_daemon (struct MHD_Daemon *daemon_handle)
343 {
344   GNUNET_SCHEDULER_TaskIdentifier ret;
345   fd_set rs;
346   fd_set ws;
347   fd_set es;
348   struct GNUNET_NETWORK_FDSet *wrs;
349   struct GNUNET_NETWORK_FDSet *wws;
350   struct GNUNET_NETWORK_FDSet *wes;
351   int max;
352   unsigned long long timeout;
353   int haveto;
354   struct GNUNET_TIME_Relative tv;
355   
356   FD_ZERO(&rs);
357   FD_ZERO(&ws);
358   FD_ZERO(&es);
359   wrs = GNUNET_NETWORK_fdset_create ();
360   wes = GNUNET_NETWORK_fdset_create ();
361   wws = GNUNET_NETWORK_fdset_create ();
362   max = -1;
363   GNUNET_assert (MHD_YES ==
364                  MHD_get_fdset (daemon_handle,
365                                 &rs,
366                                 &ws,
367                                 &es,
368                                 &max));
369   haveto = MHD_get_timeout (daemon_handle, &timeout);
370   if (haveto == MHD_YES)
371     tv.value = (uint64_t) timeout;
372   else
373     tv = GNUNET_TIME_UNIT_FOREVER_REL;
374   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
375   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
376   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
377   ret = GNUNET_SCHEDULER_add_select (sched,
378                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
379                                      GNUNET_SCHEDULER_NO_TASK,
380                                      tv,
381                                      wrs,
382                                      wws,
383                                      &run_daemon,
384                                      daemon_handle);
385   GNUNET_NETWORK_fdset_destroy (wrs);
386   GNUNET_NETWORK_fdset_destroy (wws);
387   GNUNET_NETWORK_fdset_destroy (wes);
388   return ret;
389 }
390
391
392
393 /**
394  * Start server offering our hostlist.
395  *
396  * @return GNUNET_OK on success
397  */
398 int
399 GNUNET_HOSTLIST_server_start (const struct GNUNET_CONFIGURATION_Handle *c,
400                               struct GNUNET_SCHEDULER_Handle *s,
401                               struct GNUNET_STATISTICS_Handle *st)
402 {
403   unsigned long long port;
404
405   sched = s;
406   cfg = c;
407   stats = st;
408   if (-1 == GNUNET_CONFIGURATION_get_value_number (cfg,
409                                                    "HOSTLIST",
410                                                    "HTTPPORT", 
411                                                    &port))
412     return GNUNET_SYSERR;
413   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
414               _("Hostlist service starts on port %llu\n"),
415               port);
416   daemon_handle_v6 = MHD_start_daemon (MHD_USE_IPv6 
417 #if DEBUG_HOSTLIST_SERVER
418                                        | MHD_USE_DEBUG
419 #endif
420                                        ,
421                                        (unsigned short) port,
422                                        &accept_policy_callback,
423                                        NULL,
424                                        &access_handler_callback,
425                                        NULL,
426                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
427                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
428                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
429                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
430                                        MHD_OPTION_END);
431   daemon_handle_v4 = MHD_start_daemon (MHD_NO_FLAG
432 #if DEBUG_HOSTLIST_SERVER
433                                        | MHD_USE_DEBUG
434 #endif
435                                        ,
436                                        (unsigned short) port,
437                                        &accept_policy_callback,
438                                        NULL,
439                                        &access_handler_callback,
440                                        NULL,
441                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
442                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
443                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
444                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
445                                        MHD_OPTION_END);
446
447   if ( (daemon_handle_v6 == NULL) &&
448        (daemon_handle_v4 == NULL) )
449     {
450       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
451                   _("Could not start hostlist HTTP server on port %u\n"),
452                   (unsigned short) port);
453       return GNUNET_SYSERR;    
454     }
455   if (daemon_handle_v4 != NULL)
456     hostlist_task_v4 = prepare_daemon (daemon_handle_v4);
457   if (daemon_handle_v6 != NULL)
458     hostlist_task_v6 = prepare_daemon (daemon_handle_v6);
459   response_task = GNUNET_SCHEDULER_add_now (sched,
460                                             &update_response,
461                                             NULL);
462   return GNUNET_OK;
463 }
464
465 /**
466  * Stop server offering our hostlist.
467  */
468 void
469 GNUNET_HOSTLIST_server_stop ()
470 {
471 #if DEBUG_HOSTLIST_SERVER
472   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
473               "Hostlist server shutdown\n");
474 #endif
475   if (GNUNET_SCHEDULER_NO_TASK != hostlist_task_v6)
476     {
477       GNUNET_SCHEDULER_cancel (sched, hostlist_task_v6);
478       hostlist_task_v6 = GNUNET_SCHEDULER_NO_TASK;
479     }
480   if (GNUNET_SCHEDULER_NO_TASK != hostlist_task_v4)
481     {
482       GNUNET_SCHEDULER_cancel (sched, hostlist_task_v4);
483       hostlist_task_v4 = GNUNET_SCHEDULER_NO_TASK;
484     }
485   if (pitr != NULL)
486     {
487       GNUNET_PEERINFO_iterate_cancel (pitr);
488       pitr = NULL;
489     }
490   if (GNUNET_SCHEDULER_NO_TASK != response_task)
491     {
492       GNUNET_SCHEDULER_cancel (sched, response_task);
493       response_task = GNUNET_SCHEDULER_NO_TASK;
494     }
495   if (NULL != daemon_handle_v4)
496     {
497       MHD_stop_daemon (daemon_handle_v4);
498       daemon_handle_v4 = NULL;
499     }
500   if (NULL != daemon_handle_v6)
501     {
502       MHD_stop_daemon (daemon_handle_v6);
503       daemon_handle_v6 = NULL;
504     }
505   if (response != NULL)
506     {
507       MHD_destroy_response (response);
508       response = NULL;
509     }
510 }
511
512 /* end of hostlist-server.c */