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