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