7cf743c64e0c954abc2f47c059acac27eed63d38
[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  * Our primary task for IPv4.
62  */
63 static GNUNET_SCHEDULER_TaskIdentifier hostlist_task_v4;
64
65 /**
66  * Our primary task for IPv6.
67  */
68 static GNUNET_SCHEDULER_TaskIdentifier hostlist_task_v6;
69
70 /**
71  * Task that updates our HTTP response.
72  */
73 static GNUNET_SCHEDULER_TaskIdentifier response_task;
74
75 /**
76  * Our canonical response.
77  */
78 static struct MHD_Response *response;
79
80 /**
81  * NULL if we are not currenlty iterating over peer information.
82  */
83 static struct GNUNET_PEERINFO_IteratorContext *pitr;
84
85 /**
86  * Context for host processor.
87  */
88 struct HostSet
89 {
90   unsigned int size;
91
92   char *data;
93 };
94
95
96 /**
97  * Task that will produce a new response object.
98  */
99 static void
100 update_response (void *cls,
101                  const struct GNUNET_SCHEDULER_TaskContext *tc);
102
103
104 /**
105  * Function that assembles our response.
106  */
107 static void
108 finish_response (struct HostSet *results)
109 {
110   struct GNUNET_TIME_Relative freq;
111   
112   if (response != NULL)
113     MHD_destroy_response (response);
114 #if DEBUG_HOSTLIST_SERVER
115   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
116               "Creating hostlist response with %u bytes\n",
117               (unsigned int) results->size);
118 #endif
119   response = MHD_create_response_from_data (results->size,
120                                             results->data, MHD_YES, MHD_NO);
121   if ( (daemon_handle_v4 != NULL) ||
122        (daemon_handle_v6 != NULL) )    
123     {
124       freq = RESPONSE_UPDATE_FREQUENCY;
125       if (results->size == 0)
126         freq = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 50);
127       /* schedule next update of the response */  
128       response_task = GNUNET_SCHEDULER_add_delayed (sched,
129                                                     freq,
130                                                     &update_response,
131                                                     NULL);
132     }
133   else
134     {
135       /* already past shutdown */
136       MHD_destroy_response (response);
137       response = NULL;
138     }
139   GNUNET_free (results);
140 }
141
142
143 /**
144  * Callback that processes each of the known HELLOs for the
145  * hostlist response construction.
146  */
147 static void
148 host_processor (void *cls,
149                 const struct GNUNET_PeerIdentity * peer,
150                 const struct GNUNET_HELLO_Message *hello,
151                 uint32_t trust)
152 {
153   struct HostSet *results = cls;
154   size_t old;
155   size_t s;
156   
157   if (peer == NULL)
158     {
159       pitr = NULL;
160       finish_response (results);
161       return;
162     }
163   old = results->size;
164   s = GNUNET_HELLO_size(hello);
165 #if DEBUG_HOSTLIST_SERVER
166   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
167               "Received %u bytes of `%s' from peer `%s' for hostlist.\n",
168               (unsigned int) s,
169               "HELLO",
170               GNUNET_i2s (peer));
171 #endif
172   if (old + s >= GNUNET_MAX_MALLOC_CHECKED)
173     return; /* too large, skip! */
174   GNUNET_array_grow (results->data,
175                      results->size,
176                      old + s);
177   memcpy (&results->data[old], hello, s);
178 }
179
180
181 /**
182  * Task that will produce a new response object.
183  */
184 static void
185 update_response (void *cls,
186                  const struct GNUNET_SCHEDULER_TaskContext *tc)
187 {
188   struct HostSet *results;
189
190   response_task = GNUNET_SCHEDULER_NO_TASK;
191   results = GNUNET_malloc(sizeof(struct HostSet));
192   pitr = GNUNET_PEERINFO_iterate (cfg, sched, 
193                                   NULL,
194                                   0, 
195                                   GNUNET_TIME_UNIT_MINUTES,
196                                   &host_processor,
197                                   results);
198 }
199
200
201 /**
202  * Hostlist access policy (very permissive, allows everything).
203  */
204 static int
205 accept_policy_callback (void *cls,
206                         const struct sockaddr *addr, socklen_t addrlen)
207 {
208   if (NULL == response)
209     {
210 #if DEBUG_HOSTLIST_SERVER
211       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
212                   "Received request for hostlist, but I am not yet ready; rejecting!\n");
213 #endif
214       return MHD_NO;
215     }
216   return MHD_YES;               /* accept all */
217 }
218
219
220 /**
221  * Main request handler.
222  */
223 static int
224 access_handler_callback (void *cls,
225                          struct MHD_Connection *connection,
226                          const char *url,
227                          const char *method,
228                          const char *version,
229                          const char *upload_data,
230                          size_t*upload_data_size, void **con_cls)
231 {
232   static int dummy;
233   
234   if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
235     {
236       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
237                   _("Refusing `%s' request to hostlist server\n"),
238                   method);
239       return MHD_NO;
240     }
241   if (NULL == *con_cls)
242     {
243       (*con_cls) = &dummy;
244 #if DEBUG_HOSTLIST_SERVER
245       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
246                   _("Sending 100 CONTINUE reply\n"));
247 #endif
248       return MHD_YES;           /* send 100 continue */
249     }
250   if (*upload_data_size != 0)
251     {
252       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
253                   _("Refusing `%s' request with %llu bytes of upload data\n"),
254                   method,
255                   (unsigned long long) *upload_data_size);
256       return MHD_NO;              /* do not support upload data */
257     }
258   if (response == NULL)
259     {
260       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
261                   _("Could not handle hostlist request since I do not have a response yet\n"));
262       return MHD_NO;              /* internal error, no response yet */
263     }
264   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
265               _("Received request for our hostlist\n"));
266   return MHD_queue_response (connection, MHD_HTTP_OK, response);
267 }
268
269
270 /**
271  * Function that queries MHD's select sets and
272  * starts the task waiting for them.
273  */
274 static GNUNET_SCHEDULER_TaskIdentifier
275 prepare_daemon (struct MHD_Daemon *daemon_handle);
276
277 /**
278  * Call MHD to process pending requests and then go back
279  * and schedule the next run.
280  */
281 static void
282 run_daemon (void *cls,
283             const struct GNUNET_SCHEDULER_TaskContext *tc)
284 {
285   struct MHD_Daemon *daemon_handle = cls;
286
287   if (daemon_handle == daemon_handle_v4)
288     hostlist_task_v4 = GNUNET_SCHEDULER_NO_TASK;
289   else
290     hostlist_task_v6 = GNUNET_SCHEDULER_NO_TASK;
291
292   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
293     return;    
294   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
295   if (daemon_handle == daemon_handle_v4)
296     hostlist_task_v4 = prepare_daemon (daemon_handle);
297   else
298     hostlist_task_v6 = prepare_daemon (daemon_handle);
299 }
300
301
302 /**
303  * Function that queries MHD's select sets and
304  * starts the task waiting for them.
305  */
306 static GNUNET_SCHEDULER_TaskIdentifier
307 prepare_daemon (struct MHD_Daemon *daemon_handle)
308 {
309   GNUNET_SCHEDULER_TaskIdentifier ret;
310   fd_set rs;
311   fd_set ws;
312   fd_set es;
313   struct GNUNET_NETWORK_FDSet *wrs;
314   struct GNUNET_NETWORK_FDSet *wws;
315   struct GNUNET_NETWORK_FDSet *wes;
316   int max;
317   unsigned long long timeout;
318   int haveto;
319   struct GNUNET_TIME_Relative tv;
320   
321   FD_ZERO(&rs);
322   FD_ZERO(&ws);
323   FD_ZERO(&es);
324   wrs = GNUNET_NETWORK_fdset_create ();
325   wes = GNUNET_NETWORK_fdset_create ();
326   wws = GNUNET_NETWORK_fdset_create ();
327   max = -1;
328   GNUNET_assert (MHD_YES ==
329                  MHD_get_fdset (daemon_handle,
330                                 &rs,
331                                 &ws,
332                                 &es,
333                                 &max));
334   haveto = MHD_get_timeout (daemon_handle, &timeout);
335   if (haveto == MHD_YES)
336     tv.value = (uint64_t) timeout;
337   else
338     tv = GNUNET_TIME_UNIT_FOREVER_REL;
339   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
340   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
341   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
342   ret = GNUNET_SCHEDULER_add_select (sched,
343                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
344                                      GNUNET_SCHEDULER_NO_TASK,
345                                      tv,
346                                      wrs,
347                                      wws,
348                                      &run_daemon,
349                                      daemon_handle);
350   GNUNET_NETWORK_fdset_destroy (wrs);
351   GNUNET_NETWORK_fdset_destroy (wws);
352   GNUNET_NETWORK_fdset_destroy (wes);
353   return ret;
354 }
355
356
357
358 /**
359  * Start server offering our hostlist.
360  *
361  * @return GNUNET_OK on success
362  */
363 int
364 GNUNET_HOSTLIST_server_start (const struct GNUNET_CONFIGURATION_Handle *c,
365                               struct GNUNET_SCHEDULER_Handle *s,
366                               struct GNUNET_STATISTICS_Handle *st)
367 {
368   unsigned long long port;
369
370   sched = s;
371   cfg = c;
372   if (-1 == GNUNET_CONFIGURATION_get_value_number (cfg,
373                                                    "HOSTLIST",
374                                                    "HTTPPORT", 
375                                                    &port))
376     return GNUNET_SYSERR;
377   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
378               _("Hostlist service starts on port %llu\n"),
379               port);
380   daemon_handle_v6 = MHD_start_daemon (MHD_USE_IPv6 
381 #if DEBUG_HOSTLIST_SERVER
382                                        | MHD_USE_DEBUG
383 #endif
384                                        ,
385                                        (unsigned short) port,
386                                        &accept_policy_callback,
387                                        NULL,
388                                        &access_handler_callback,
389                                        NULL,
390                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
391                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
392                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
393                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
394                                        MHD_OPTION_END);
395   daemon_handle_v4 = MHD_start_daemon (MHD_NO_FLAG
396 #if DEBUG_HOSTLIST_SERVER
397                                        | MHD_USE_DEBUG
398 #endif
399                                        ,
400                                        (unsigned short) port,
401                                        &accept_policy_callback,
402                                        NULL,
403                                        &access_handler_callback,
404                                        NULL,
405                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
406                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
407                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
408                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
409                                        MHD_OPTION_END);
410
411   if ( (daemon_handle_v6 == NULL) &&
412        (daemon_handle_v4 == NULL) )
413     {
414       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
415                   _("Could not start hostlist HTTP server on port %u\n"),
416                   (unsigned short) port);
417       return GNUNET_SYSERR;    
418     }
419   if (daemon_handle_v4 != NULL)
420     hostlist_task_v4 = prepare_daemon (daemon_handle_v4);
421   if (daemon_handle_v6 != NULL)
422     hostlist_task_v6 = prepare_daemon (daemon_handle_v6);
423   response_task = GNUNET_SCHEDULER_add_now (sched,
424                                             &update_response,
425                                             NULL);
426   return GNUNET_OK;
427 }
428
429 /**
430  * Stop server offering our hostlist.
431  */
432 void
433 GNUNET_HOSTLIST_server_stop ()
434 {
435 #if DEBUG_HOSTLIST_SERVER
436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
437               "Hostlist server shutdown\n");
438 #endif
439   if (GNUNET_SCHEDULER_NO_TASK != hostlist_task_v6)
440     {
441       GNUNET_SCHEDULER_cancel (sched, hostlist_task_v6);
442       hostlist_task_v6 = GNUNET_SCHEDULER_NO_TASK;
443     }
444   if (GNUNET_SCHEDULER_NO_TASK != hostlist_task_v4)
445     {
446       GNUNET_SCHEDULER_cancel (sched, hostlist_task_v4);
447       hostlist_task_v4 = GNUNET_SCHEDULER_NO_TASK;
448     }
449   if (pitr != NULL)
450     {
451       GNUNET_PEERINFO_iterate_cancel (pitr);
452       pitr = NULL;
453     }
454   if (GNUNET_SCHEDULER_NO_TASK != response_task)
455     {
456       GNUNET_SCHEDULER_cancel (sched, response_task);
457       response_task = GNUNET_SCHEDULER_NO_TASK;
458     }
459   if (NULL != daemon_handle_v4)
460     {
461       MHD_stop_daemon (daemon_handle_v4);
462       daemon_handle_v4 = NULL;
463     }
464   if (NULL != daemon_handle_v6)
465     {
466       MHD_stop_daemon (daemon_handle_v6);
467       daemon_handle_v6 = NULL;
468     }
469   if (response != NULL)
470     {
471       MHD_destroy_response (response);
472       response = NULL;
473     }
474 }
475
476 /* end of hostlist-server.c */