reading alpha, beta from .conf
[oweals/gnunet.git] / src / hostlist / gnunet-daemon-hostlist_server.c
1 /*
2      This file is part of GNUnet.
3      (C) 2008, 2009, 2010, 2014 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 3, 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/gnunet-daemon-hostlist_server.c
23  * @author Christian Grothoff
24  * @author Matthias Wachs
25  * @author David Barksdale
26  * @brief application to provide an integrated hostlist HTTP server
27  */
28 #include "platform.h"
29 #include <microhttpd.h>
30 #include "gnunet-daemon-hostlist_server.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_peerinfo_service.h"
33 #include "gnunet-daemon-hostlist.h"
34 #include "gnunet_resolver_service.h"
35
36
37 /**
38  * How long until our hostlist advertisment transmission via CORE should
39  * time out?
40  */
41 #define GNUNET_ADV_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
42
43
44 /**
45  * Handle to the HTTP server as provided by libmicrohttpd for IPv6.
46  */
47 static struct MHD_Daemon *daemon_handle_v6;
48
49 /**
50  * Handle to the HTTP server as provided by libmicrohttpd for IPv4.
51  */
52 static struct MHD_Daemon *daemon_handle_v4;
53
54 /**
55  * Our configuration.
56  */
57 static const struct GNUNET_CONFIGURATION_Handle *cfg;
58
59 /**
60  * For keeping statistics.
61  */
62 static struct GNUNET_STATISTICS_Handle *stats;
63
64 /**
65  * Handle to the core service (NULL until we've connected to it).
66  */
67 static struct GNUNET_CORE_Handle *core;
68
69 /**
70  * Handle to the peerinfo notify service (NULL until we've connected to it).
71  */
72 static struct GNUNET_PEERINFO_NotifyContext *notify;
73
74 /**
75  * Our primary task for IPv4.
76  */
77 static struct GNUNET_SCHEDULER_Task * hostlist_task_v4;
78
79 /**
80  * Our primary task for IPv6.
81  */
82 static struct GNUNET_SCHEDULER_Task * hostlist_task_v6;
83
84 /**
85  * Our canonical response.
86  */
87 static struct MHD_Response *response;
88
89 /**
90  * Handle for accessing peerinfo service.
91  */
92 static struct GNUNET_PEERINFO_Handle *peerinfo;
93
94 /**
95  * Set if we are allowed to advertise our hostlist to others.
96  */
97 static int advertising;
98
99 /**
100  * Buffer for the hostlist address
101  */
102 static char *hostlist_uri;
103
104 /**
105  * Map of peer identities to `struct GNUNET_CORE_TransmitHandle *` for
106  * pending hostlist server advertisements.
107  */
108 static struct GNUNET_CONTAINER_MultiPeerMap *advertisements;
109
110
111 /**
112  * Context for #host_processor().
113  */
114 struct HostSet
115 {
116   /**
117    * Iterator used to build @e data (NULL when done).
118    */
119   struct GNUNET_PEERINFO_IteratorContext *pitr;
120
121   /**
122    * Place where we accumulate all of the HELLO messages.
123    */
124   char *data;
125
126   /**
127    * Number of bytes in @e data.
128    */
129   unsigned int size;
130
131 };
132
133
134 /**
135  * NULL if we are not currenlty iterating over peer information.
136  */
137 static struct HostSet *builder;
138
139
140 /**
141  * Add headers to a request indicating that we allow Cross-Origin Resource
142  * Sharing.
143  *
144  * @param response response to add headers to
145  */
146 static void
147 add_cors_headers (struct MHD_Response *response)
148 {
149   MHD_add_response_header (response,
150                            "Access-Control-Allow-Origin",
151                            "*");
152   MHD_add_response_header (response,
153                            "Access-Control-Allow-Methods",
154                            "GET, OPTIONS");
155   MHD_add_response_header (response,
156                            "Access-Control-Max-Age",
157                            "86400");
158 }
159
160
161 /**
162  * Function that assembles our response.
163  */
164 static void
165 finish_response ()
166 {
167   if (NULL != response)
168     MHD_destroy_response (response);
169   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
170               "Creating hostlist response with %u bytes\n",
171               (unsigned int) builder->size);
172   response =
173       MHD_create_response_from_data (builder->size, builder->data, MHD_YES,
174                                      MHD_NO);
175   add_cors_headers (response);
176   if ((NULL == daemon_handle_v4) && (NULL == daemon_handle_v6))
177   {
178     MHD_destroy_response (response);
179     response = NULL;
180   }
181   GNUNET_STATISTICS_set (stats, gettext_noop ("bytes in hostlist"),
182                          builder->size, GNUNET_YES);
183   GNUNET_free (builder);
184   builder = NULL;
185 }
186
187
188 /**
189  * Set @a cls to #GNUNET_YES (we have an address!).
190  *
191  * @param cls closure, an `int *`
192  * @param address the address (ignored)
193  * @param expiration expiration time (call is ignored if this is in the past)
194  * @return  #GNUNET_SYSERR to stop iterating (unless expiration has occured)
195  */
196 static int
197 check_has_addr (void *cls,
198                 const struct GNUNET_HELLO_Address *address,
199                 struct GNUNET_TIME_Absolute expiration)
200 {
201   int *arg = cls;
202
203   if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us)
204   {
205     GNUNET_STATISTICS_update (stats,
206                               gettext_noop ("expired addresses encountered"), 1,
207                               GNUNET_YES);
208     return GNUNET_YES;          /* ignore this address */
209   }
210   *arg = GNUNET_YES;
211   return GNUNET_SYSERR;
212 }
213
214
215 /**
216  * Callback that processes each of the known HELLOs for the
217  * hostlist response construction.
218  *
219  * @param cls closure, NULL
220  * @param peer id of the peer, NULL for last call
221  * @param hello hello message for the peer (can be NULL)
222  * @param err_msg message
223  */
224 static void
225 host_processor (void *cls,
226                 const struct GNUNET_PeerIdentity *peer,
227                 const struct GNUNET_HELLO_Message *hello,
228                 const char *err_msg)
229 {
230   size_t old;
231   size_t s;
232   int has_addr;
233
234   if (NULL != err_msg)
235   {
236     GNUNET_assert (NULL == peer);
237     builder->pitr = NULL;
238     GNUNET_free_non_null (builder->data);
239     GNUNET_free (builder);
240     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
241                 _("Error in communication with PEERINFO service: %s\n"),
242                 err_msg);
243     return;
244   }
245   if (NULL == peer)
246   {
247     builder->pitr = NULL;
248     finish_response ();
249     return;
250   }
251   if (NULL == hello)
252     return;
253   has_addr = GNUNET_NO;
254   GNUNET_HELLO_iterate_addresses (hello,
255                                   GNUNET_NO,
256                                   &check_has_addr,
257                                   &has_addr);
258   if (GNUNET_NO == has_addr)
259   {
260     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
261                 "HELLO for peer `%4s' has no address, not suitable for hostlist!\n",
262                 GNUNET_i2s (peer));
263     GNUNET_STATISTICS_update (stats,
264                               gettext_noop
265                               ("HELLOs without addresses encountered (ignored)"),
266                               1, GNUNET_NO);
267     return;
268   }
269   old = builder->size;
270   s = GNUNET_HELLO_size (hello);
271   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
272               "Received %u bytes of `%s' from peer `%s' for hostlist.\n",
273               (unsigned int) s,
274               "HELLO",
275               GNUNET_i2s (peer));
276   if ( (old + s >= GNUNET_MAX_MALLOC_CHECKED) ||
277        (old + s >= MAX_BYTES_PER_HOSTLISTS) )
278   {
279     /* too large, skip! */
280     GNUNET_STATISTICS_update (stats,
281                               gettext_noop
282                               ("bytes not included in hostlist (size limit)"),
283                               s, GNUNET_NO);
284     return;
285   }
286   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
287               "Adding peer `%s' to hostlist (%u bytes)\n",
288               GNUNET_i2s (peer),
289               (unsigned int) s);
290   GNUNET_array_grow (builder->data,
291                      builder->size,
292                      old + s);
293   memcpy (&builder->data[old],
294           hello,
295           s);
296 }
297
298
299 /**
300  * Hostlist access policy (very permissive, allows everything).
301  * Returns #MHD_NO only if we are not yet ready to serve.
302  *
303  * @param cls closure
304  * @param addr address information from the client
305  * @param addrlen length of @a addr
306  * @return #MHD_YES if connection is allowed, #MHD_NO if not (we are not ready)
307  */
308 static int
309 accept_policy_callback (void *cls,
310                         const struct sockaddr *addr,
311                         socklen_t addrlen)
312 {
313   if (NULL == response)
314   {
315     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
316                 "Received request for hostlist, but I am not yet ready; rejecting!\n");
317     return MHD_NO;
318   }
319   return MHD_YES;               /* accept all */
320 }
321
322
323 /**
324  * Main request handler.
325  *
326  * @param cls argument given together with the function
327  *        pointer when the handler was registered with MHD
328  * @param connection
329  * @param url the requested url
330  * @param method the HTTP method used (#MHD_HTTP_METHOD_GET,
331  *        #MHD_HTTP_METHOD_PUT, etc.)
332  * @param version the HTTP version string (i.e.
333  *        #MHD_HTTP_VERSION_1_1)
334  * @param upload_data the data being uploaded (excluding HEADERS,
335  *        for a POST that fits into memory and that is encoded
336  *        with a supported encoding, the POST data will NOT be
337  *        given in upload_data and is instead available as
338  *        part of #MHD_get_connection_values; very large POST
339  *        data *will* be made available incrementally in
340  *        @a upload_data)
341  * @param upload_data_size set initially to the size of the
342  *        @a upload_data provided; the method must update this
343  *        value to the number of bytes NOT processed;
344  * @param con_cls pointer that the callback can set to some
345  *        address and that will be preserved by MHD for future
346  *        calls for this request; since the access handler may
347  *        be called many times (i.e., for a PUT/POST operation
348  *        with plenty of upload data) this allows the application
349  *        to easily associate some request-specific state.
350  *        If necessary, this state can be cleaned up in the
351  *        global #MHD_RequestCompletedCallback (which
352  *        can be set with the #MHD_OPTION_NOTIFY_COMPLETED).
353  *        Initially, `*con_cls` will be NULL.
354  * @return #MHD_YES if the connection was handled successfully,
355  *         #MHD_NO if the socket must be closed due to a serios
356  *         error while handling the request
357  */
358 static int
359 access_handler_callback (void *cls,
360                          struct MHD_Connection *connection,
361                          const char *url,
362                          const char *method,
363                          const char *version,
364                          const char *upload_data,
365                          size_t *upload_data_size,
366                          void **con_cls)
367 {
368   static int dummy;
369
370   /* CORS pre-flight request */
371   if (0 == strcmp (MHD_HTTP_METHOD_OPTIONS, method))
372   {
373     struct MHD_Response *options_response;
374     int rc;
375
376     options_response = MHD_create_response_from_buffer (0, NULL,
377                                                         MHD_RESPMEM_PERSISTENT);
378     add_cors_headers(options_response);
379     rc = MHD_queue_response (connection, MHD_HTTP_OK, options_response);
380     MHD_destroy_response (options_response);
381     return rc;
382   }
383   if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
384   {
385     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
386                 _("Refusing `%s' request to hostlist server\n"), method);
387     GNUNET_STATISTICS_update (stats,
388                               gettext_noop
389                               ("hostlist requests refused (not HTTP GET)"), 1,
390                               GNUNET_YES);
391     return MHD_NO;
392   }
393   if (NULL == *con_cls)
394   {
395     (*con_cls) = &dummy;
396     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
397                 "Sending 100 CONTINUE reply\n");
398     return MHD_YES;             /* send 100 continue */
399   }
400   if (0 != *upload_data_size)
401   {
402     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
403                 _("Refusing `%s' request with %llu bytes of upload data\n"),
404                 method, (unsigned long long) *upload_data_size);
405     GNUNET_STATISTICS_update (stats,
406                               gettext_noop
407                               ("hostlist requests refused (upload data)"), 1,
408                               GNUNET_YES);
409     return MHD_NO;              /* do not support upload data */
410   }
411   if (NULL == response)
412   {
413     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
414                 _("Could not handle hostlist request since I do not have a response yet\n"));
415     GNUNET_STATISTICS_update (stats,
416                               gettext_noop
417                               ("hostlist requests refused (not ready)"), 1,
418                               GNUNET_YES);
419     return MHD_NO;              /* internal error, no response yet */
420   }
421   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
422               _("Received request for our hostlist\n"));
423   GNUNET_STATISTICS_update (stats,
424                             gettext_noop ("hostlist requests processed"),
425                             1, GNUNET_YES);
426   return MHD_queue_response (connection, MHD_HTTP_OK, response);
427 }
428
429
430 /**
431  * Handler called by CORE when CORE is ready to transmit message
432  *
433  * @param cls closure with the `const struct GNUNET_PeerIdentity *` of
434  *            the peer we are sending to
435  * @param size size of buffer to copy message to
436  * @param buf buffer to copy message to
437  * @return number of bytes copied to @a buf
438  */
439 static size_t
440 adv_transmit_ready (void *cls,
441                     size_t size,
442                     void *buf)
443 {
444   const struct GNUNET_PeerIdentity *peer = cls;
445   static uint64_t hostlist_adv_count;
446   size_t transmission_size;
447   size_t uri_size;              /* Including \0 termination! */
448   struct GNUNET_MessageHeader header;
449   char *cbuf;
450   struct GNUNET_CORE_TransmitHandle *th;
451
452   th = GNUNET_CONTAINER_multipeermap_get (advertisements,
453                                           peer);
454   GNUNET_assert (NULL != th);
455   GNUNET_assert (GNUNET_YES ==
456                  GNUNET_CONTAINER_multipeermap_remove (advertisements,
457                                                        peer,
458                                                        th));
459   if (NULL == buf)
460   {
461     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
462                 "Transmission failed, buffer invalid!\n");
463     return 0;
464   }
465   uri_size = strlen (hostlist_uri) + 1;
466   transmission_size = sizeof (struct GNUNET_MessageHeader) + uri_size;
467   header.type = htons (GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT);
468   header.size = htons (transmission_size);
469   GNUNET_assert (size >= transmission_size);
470   memcpy (buf,
471           &header,
472           sizeof (struct GNUNET_MessageHeader));
473   cbuf = buf;
474   memcpy (&cbuf[sizeof (struct GNUNET_MessageHeader)],
475           hostlist_uri,
476           uri_size);
477   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
478               "Sent advertisement message: Copied %u bytes into buffer!\n",
479               (unsigned int) transmission_size);
480   hostlist_adv_count++;
481   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
482               " # Sent advertisement message: %u\n",
483               hostlist_adv_count);
484   GNUNET_STATISTICS_update (stats,
485                             gettext_noop ("# hostlist advertisements send"), 1,
486                             GNUNET_NO);
487   return transmission_size;
488 }
489
490
491 /**
492  * Method called whenever a given peer connects.
493  *
494  * @param cls closure
495  * @param peer peer identity this notification is about
496  */
497 static void
498 connect_handler (void *cls,
499                  const struct GNUNET_PeerIdentity *peer)
500 {
501   size_t size;
502   struct GNUNET_CORE_TransmitHandle *th;
503
504   if (! advertising)
505     return;
506   if (NULL == hostlist_uri)
507     return;
508   size = strlen (hostlist_uri) + 1;
509   if (size + sizeof (struct GNUNET_MessageHeader) >=
510       GNUNET_SERVER_MAX_MESSAGE_SIZE)
511   {
512     GNUNET_break (0);
513     return;
514   }
515   size += sizeof (struct GNUNET_MessageHeader);
516   if (NULL == core)
517   {
518     GNUNET_break (0);
519     return;
520   }
521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
522               "Asked CORE to transmit advertisement message with a size of %u bytes to peer `%s'\n",
523               size,
524               GNUNET_i2s (peer));
525   if (NULL ==
526       (th = GNUNET_CORE_notify_transmit_ready (core, GNUNET_YES,
527                                                GNUNET_CORE_PRIO_BEST_EFFORT,
528                                                GNUNET_ADV_TIMEOUT,
529                                                peer,
530                                                size,
531                                                &adv_transmit_ready,
532                                                (void *) peer)) )
533   {
534     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
535                 _("Advertisement message could not be queued by core\n"));
536   }
537   GNUNET_assert (GNUNET_YES ==
538                  GNUNET_CONTAINER_multipeermap_put (advertisements,
539                                                     peer,
540                                                     th,
541                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
542 }
543
544
545 /**
546  * Method called whenever a given peer disconnects.
547  *
548  * @param cls closure
549  * @param peer peer identity this notification is about
550  */
551 static void
552 disconnect_handler (void *cls,
553                     const struct GNUNET_PeerIdentity *peer)
554 {
555   struct GNUNET_CORE_TransmitHandle *th;
556
557   if (! advertising)
558     return;
559   th = GNUNET_CONTAINER_multipeermap_get (advertisements,
560                                           peer);
561   if (NULL == th)
562     return;
563   GNUNET_assert (GNUNET_YES ==
564                  GNUNET_CONTAINER_multipeermap_remove (advertisements,
565                                                        peer,
566                                                        th));
567   GNUNET_CORE_notify_transmit_ready_cancel (th);
568 }
569
570
571 /**
572  * PEERINFO calls this function to let us know about a possible peer
573  * that we might want to connect to.
574  *
575  * @param cls closure (not used)
576  * @param peer potential peer to connect to
577  * @param hello HELLO for this peer (or NULL)
578  * @param err_msg NULL if successful, otherwise contains error message
579  */
580 static void
581 process_notify (void *cls,
582                 const struct GNUNET_PeerIdentity *peer,
583                 const struct GNUNET_HELLO_Message *hello,
584                 const char *err_msg)
585 {
586   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
587               "Peerinfo is notifying us to rebuild our hostlist\n");
588   if (NULL != err_msg)
589     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
590                 _("Error in communication with PEERINFO service: %s\n"),
591                 err_msg);
592   if (NULL != builder)
593   {
594     /* restart re-build already in progress ... */
595     if (NULL != builder->pitr)
596     {
597       GNUNET_PEERINFO_iterate_cancel (builder->pitr);
598       builder->pitr = NULL;
599     }
600     GNUNET_free_non_null (builder->data);
601     builder->size = 0;
602     builder->data = NULL;
603   }
604   else
605   {
606     builder = GNUNET_new (struct HostSet);
607   }
608   GNUNET_assert (NULL != peerinfo);
609   builder->pitr
610     = GNUNET_PEERINFO_iterate (peerinfo,
611                                GNUNET_NO, NULL,
612                                GNUNET_TIME_UNIT_MINUTES,
613                                &host_processor, NULL);
614 }
615
616
617 /**
618  * Function that queries MHD's select sets and
619  * starts the task waiting for them.
620  */
621 static struct GNUNET_SCHEDULER_Task *
622 prepare_daemon (struct MHD_Daemon *daemon_handle);
623
624
625 /**
626  * Call MHD to process pending requests and then go back
627  * and schedule the next run.
628  *
629  * @param cls the `struct MHD_Daemon` of the HTTP server to run
630  * @param tc scheduler context
631  */
632 static void
633 run_daemon (void *cls,
634             const struct GNUNET_SCHEDULER_TaskContext *tc)
635 {
636   struct MHD_Daemon *daemon_handle = cls;
637
638   if (daemon_handle == daemon_handle_v4)
639     hostlist_task_v4 = NULL;
640   else
641     hostlist_task_v6 = NULL;
642
643   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
644     return;
645   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
646   if (daemon_handle == daemon_handle_v4)
647     hostlist_task_v4 = prepare_daemon (daemon_handle);
648   else
649     hostlist_task_v6 = prepare_daemon (daemon_handle);
650 }
651
652
653 /**
654  * Function that queries MHD's select sets and
655  * starts the task waiting for them.
656  *
657  * @param daemon_handle HTTP server to prepare to run
658  */
659 static struct GNUNET_SCHEDULER_Task *
660 prepare_daemon (struct MHD_Daemon *daemon_handle)
661 {
662   struct GNUNET_SCHEDULER_Task * ret;
663   fd_set rs;
664   fd_set ws;
665   fd_set es;
666   struct GNUNET_NETWORK_FDSet *wrs;
667   struct GNUNET_NETWORK_FDSet *wws;
668   int max;
669   MHD_UNSIGNED_LONG_LONG timeout;
670   int haveto;
671   struct GNUNET_TIME_Relative tv;
672
673   FD_ZERO (&rs);
674   FD_ZERO (&ws);
675   FD_ZERO (&es);
676   wrs = GNUNET_NETWORK_fdset_create ();
677   wws = GNUNET_NETWORK_fdset_create ();
678   max = -1;
679   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
680   haveto = MHD_get_timeout (daemon_handle, &timeout);
681   if (haveto == MHD_YES)
682     tv.rel_value_us = (uint64_t) timeout * 1000LL;
683   else
684     tv = GNUNET_TIME_UNIT_FOREVER_REL;
685   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
686   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
687   ret =
688       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
689                                    tv, wrs, wws,
690                                    &run_daemon, daemon_handle);
691   GNUNET_NETWORK_fdset_destroy (wrs);
692   GNUNET_NETWORK_fdset_destroy (wws);
693   return ret;
694 }
695
696
697 /**
698  * Start server offering our hostlist.
699  *
700  * @param c configuration to use
701  * @param st statistics handle to use
702  * @param co core handle to use
703  * @param[out] server_ch set to handler for CORE connect events
704  * @param[out] server_dh set to handler for CORE disconnect events
705  * @param advertise #GNUNET_YES if we should advertise our hostlist
706  * @return #GNUNET_OK on success
707  */
708 int
709 GNUNET_HOSTLIST_server_start (const struct GNUNET_CONFIGURATION_Handle *c,
710                               struct GNUNET_STATISTICS_Handle *st,
711                               struct GNUNET_CORE_Handle *co,
712                               GNUNET_CORE_ConnectEventHandler *server_ch,
713                               GNUNET_CORE_DisconnectEventHandler *server_dh,
714                               int advertise)
715 {
716   unsigned long long port;
717   char *hostname;
718   char *ipv4;
719   char *ipv6;
720   size_t size;
721   struct in_addr i4;
722   struct in6_addr i6;
723   struct sockaddr_in v4;
724   struct sockaddr_in6 v6;
725   const struct sockaddr *sa4;
726   const struct sockaddr *sa6;
727
728   advertising = advertise;
729   if (! advertising)
730   {
731     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
732                 "Advertising not enabled on this hostlist server\n");
733   }
734   else
735   {
736     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
737                 "Advertising enabled on this hostlist server\n");
738     advertisements = GNUNET_CONTAINER_multipeermap_create (8,
739                                                            GNUNET_NO);
740   }
741   cfg = c;
742   stats = st;
743   peerinfo = GNUNET_PEERINFO_connect (cfg);
744   if (NULL == peerinfo)
745   {
746     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
747                 _("Could not access PEERINFO service.  Exiting.\n"));
748     return GNUNET_SYSERR;
749   }
750   if (GNUNET_OK !=
751       GNUNET_CONFIGURATION_get_value_number (cfg,
752                                              "HOSTLIST",
753                                              "HTTPPORT",
754                                              &port))
755     return GNUNET_SYSERR;
756   if ((0 == port) || (port > UINT16_MAX))
757   {
758     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
759                 _("Invalid port number %llu.  Exiting.\n"),
760                 port);
761     return GNUNET_SYSERR;
762   }
763
764   if (GNUNET_SYSERR ==
765       GNUNET_CONFIGURATION_get_value_string (cfg,
766                                              "HOSTLIST",
767                                              "EXTERNAL_DNS_NAME",
768                                              &hostname))
769     hostname = GNUNET_RESOLVER_local_fqdn_get ();
770   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
771               _("Hostlist service starts on %s:%llu\n"),
772               hostname, port);
773   if (NULL != hostname)
774   {
775     size = strlen (hostname);
776     if (size + 15 > MAX_URL_LEN)
777     {
778       GNUNET_break (0);
779     }
780     else
781     {
782       GNUNET_asprintf (&hostlist_uri,
783                        "http://%s:%u/", hostname,
784                        (unsigned int) port);
785       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
786                   _("Address to obtain hostlist: `%s'\n"),
787                   hostlist_uri);
788     }
789     GNUNET_free (hostname);
790   }
791
792   if (GNUNET_CONFIGURATION_have_value (cfg, "HOSTLIST", "BINDTOIPV4"))
793   {
794     if (GNUNET_OK !=
795         GNUNET_CONFIGURATION_get_value_string (cfg, "HOSTLIST",
796                                                "BINDTOIP", &ipv4))
797     {
798       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
799                   _("BINDTOIP does not a valid IPv4 address! Ignoring BINDTOIPV4.\n"));
800     }
801
802   }
803   else
804     ipv4 = NULL;
805   if (GNUNET_CONFIGURATION_have_value (cfg, "HOSTLIST", "BINDTOIPV6"))
806   {
807     if (GNUNET_OK !=
808         GNUNET_CONFIGURATION_get_value_string (cfg, "HOSTLIST",
809                                                "BINDTOIP", &ipv6))
810       {
811       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
812           _("BINDTOIP does not a valid IPv4 address! Ignoring BINDTOIPV6.\n"));
813     }
814   }
815   else
816     ipv6 = NULL;
817   sa4 = NULL;
818   if (NULL != ipv4)
819   {
820     if (1 == inet_pton (AF_INET, ipv4, &i4))
821     {
822       memset (&v4, 0, sizeof (v4));
823       v4.sin_family = AF_INET;
824       v4.sin_addr = i4;
825       v4.sin_port = htons (port);
826 #if HAVE_SOCKADDR_IN_SIN_LEN
827       v4.sin_len = sizeof (v4);
828 #endif
829       sa4 = (const struct sockaddr *) &v4;
830     }
831     else
832       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
833                   _("`%s' is not a valid IPv4 address! Ignoring BINDTOIPV4.\n"),
834                   ipv4);
835     GNUNET_free (ipv4);
836   }
837   sa6 = NULL;
838   if (NULL != ipv6)
839   {
840     if (1 == inet_pton (AF_INET6, ipv6, &i6))
841     {
842       memset (&v6, 0, sizeof (v6));
843       v6.sin6_family = AF_INET6;
844       v6.sin6_addr = i6;
845       v6.sin6_port = htons (port);
846 #if HAVE_SOCKADDR_IN_SIN_LEN
847       v6.sin6_len = sizeof (v6);
848 #endif
849       sa6 = (const struct sockaddr *) &v6;
850     }
851     else
852       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
853                   _("`%s' is not a valid IPv6 address! Ignoring BINDTOIPV6.\n"),
854                   ipv6);
855     GNUNET_free (ipv6);
856   }
857
858   daemon_handle_v6 = MHD_start_daemon (MHD_USE_IPv6 | MHD_USE_DEBUG,
859                                        (uint16_t) port,
860                                        &accept_policy_callback, NULL,
861                                        &access_handler_callback, NULL,
862                                        MHD_OPTION_CONNECTION_LIMIT,
863                                        (unsigned int) 16,
864                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT,
865                                        (unsigned int) 1,
866                                        MHD_OPTION_CONNECTION_TIMEOUT,
867                                        (unsigned int) 16,
868                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
869                                        (size_t) (16 * 1024),
870                                        MHD_OPTION_SOCK_ADDR,
871                                        sa6,
872                                        MHD_OPTION_END);
873   daemon_handle_v4 = MHD_start_daemon (MHD_NO_FLAG | MHD_USE_DEBUG,
874                                        (uint16_t) port,
875                                        &accept_policy_callback, NULL,
876                                        &access_handler_callback, NULL,
877                                        MHD_OPTION_CONNECTION_LIMIT,
878                                        (unsigned int) 16,
879                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT,
880                                        (unsigned int) 1,
881                                        MHD_OPTION_CONNECTION_TIMEOUT,
882                                        (unsigned int) 16,
883                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
884                                        (size_t) (16 * 1024),
885                                        MHD_OPTION_SOCK_ADDR,
886                                        sa4,
887                                        MHD_OPTION_END);
888
889   if ( (NULL == daemon_handle_v6) &&
890        (NULL == daemon_handle_v4) )
891   {
892     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
893                 _("Could not start hostlist HTTP server on port %u\n"),
894                 (unsigned short) port);
895     return GNUNET_SYSERR;
896   }
897
898   core = co;
899   *server_ch = &connect_handler;
900   *server_dh = &disconnect_handler;
901   if (NULL != daemon_handle_v4)
902     hostlist_task_v4 = prepare_daemon (daemon_handle_v4);
903   if (NULL != daemon_handle_v6)
904     hostlist_task_v6 = prepare_daemon (daemon_handle_v6);
905   notify = GNUNET_PEERINFO_notify (cfg,
906                                    GNUNET_NO,
907                                    &process_notify, NULL);
908   return GNUNET_OK;
909 }
910
911
912 /**
913  * Stop server offering our hostlist.
914  */
915 void
916 GNUNET_HOSTLIST_server_stop ()
917 {
918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
919               "Hostlist server shutdown\n");
920   if (NULL != hostlist_task_v6)
921   {
922     GNUNET_SCHEDULER_cancel (hostlist_task_v6);
923     hostlist_task_v6 = NULL;
924   }
925   if (NULL != hostlist_task_v4)
926   {
927     GNUNET_SCHEDULER_cancel (hostlist_task_v4);
928     hostlist_task_v4 = NULL;
929   }
930   if (NULL != daemon_handle_v4)
931   {
932     MHD_stop_daemon (daemon_handle_v4);
933     daemon_handle_v4 = NULL;
934   }
935   if (NULL != daemon_handle_v6)
936   {
937     MHD_stop_daemon (daemon_handle_v6);
938     daemon_handle_v6 = NULL;
939   }
940   if (NULL != response)
941   {
942     MHD_destroy_response (response);
943     response = NULL;
944   }
945   if (NULL != notify)
946   {
947     GNUNET_PEERINFO_notify_cancel (notify);
948     notify = NULL;
949   }
950   if (NULL != builder)
951   {
952     if (NULL != builder->pitr)
953     {
954       GNUNET_PEERINFO_iterate_cancel (builder->pitr);
955       builder->pitr = NULL;
956     }
957     GNUNET_free_non_null (builder->data);
958     GNUNET_free (builder);
959   }
960   if (NULL != peerinfo)
961   {
962     GNUNET_PEERINFO_disconnect (peerinfo);
963     peerinfo = NULL;
964   }
965   if (NULL != advertisements)
966   {
967     GNUNET_break (0 ==
968                   GNUNET_CONTAINER_multipeermap_size (advertisements));
969     GNUNET_CONTAINER_multipeermap_destroy (advertisements);
970     advertisements = NULL;
971   }
972   cfg = NULL;
973   stats = NULL;
974   core = NULL;
975 }
976
977 /* end of gnunet-daemon-hostlist_server.c */