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