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