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