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