raise low limits, as they were they are bound to cause problems with reverse-proxy...
[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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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     return MHD_YES;
398   }
399   if (0 != *upload_data_size)
400   {
401     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
402                 _("Refusing `%s' request with %llu bytes of upload data\n"),
403                 method, (unsigned long long) *upload_data_size);
404     GNUNET_STATISTICS_update (stats,
405                               gettext_noop
406                               ("hostlist requests refused (upload data)"), 1,
407                               GNUNET_YES);
408     return MHD_NO;              /* do not support upload data */
409   }
410   if (NULL == response)
411   {
412     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
413                 _("Could not handle hostlist request since I do not have a response yet\n"));
414     GNUNET_STATISTICS_update (stats,
415                               gettext_noop
416                               ("hostlist requests refused (not ready)"), 1,
417                               GNUNET_YES);
418     return MHD_NO;              /* internal error, no response yet */
419   }
420   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
421               _("Received request for our hostlist\n"));
422   GNUNET_STATISTICS_update (stats,
423                             gettext_noop ("hostlist requests processed"),
424                             1, GNUNET_YES);
425   return MHD_queue_response (connection, MHD_HTTP_OK, response);
426 }
427
428
429 /**
430  * Handler called by CORE when CORE is ready to transmit message
431  *
432  * @param cls closure with the `const struct GNUNET_PeerIdentity *` of
433  *            the peer we are sending to
434  * @param size size of buffer to copy message to
435  * @param buf buffer to copy message to
436  * @return number of bytes copied to @a buf
437  */
438 static size_t
439 adv_transmit_ready (void *cls,
440                     size_t size,
441                     void *buf)
442 {
443   const struct GNUNET_PeerIdentity *peer = cls;
444   static uint64_t hostlist_adv_count;
445   size_t transmission_size;
446   size_t uri_size;              /* Including \0 termination! */
447   struct GNUNET_MessageHeader header;
448   char *cbuf;
449   struct GNUNET_CORE_TransmitHandle *th;
450
451   th = GNUNET_CONTAINER_multipeermap_get (advertisements,
452                                           peer);
453   GNUNET_assert (NULL != th);
454   GNUNET_assert (GNUNET_YES ==
455                  GNUNET_CONTAINER_multipeermap_remove (advertisements,
456                                                        peer,
457                                                        th));
458   if (NULL == buf)
459   {
460     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
461                 "Transmission failed, buffer invalid!\n");
462     return 0;
463   }
464   uri_size = strlen (hostlist_uri) + 1;
465   transmission_size = sizeof (struct GNUNET_MessageHeader) + uri_size;
466   header.type = htons (GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT);
467   header.size = htons (transmission_size);
468   GNUNET_assert (size >= transmission_size);
469   memcpy (buf,
470           &header,
471           sizeof (struct GNUNET_MessageHeader));
472   cbuf = buf;
473   memcpy (&cbuf[sizeof (struct GNUNET_MessageHeader)],
474           hostlist_uri,
475           uri_size);
476   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
477               "Sent advertisement message: Copied %u bytes into buffer!\n",
478               (unsigned int) transmission_size);
479   hostlist_adv_count++;
480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
481               " # Sent advertisement message: %u\n",
482               hostlist_adv_count);
483   GNUNET_STATISTICS_update (stats,
484                             gettext_noop ("# hostlist advertisements send"), 1,
485                             GNUNET_NO);
486   return transmission_size;
487 }
488
489
490 /**
491  * Method called whenever a given peer connects.
492  *
493  * @param cls closure
494  * @param peer peer identity this notification is about
495  */
496 static void
497 connect_handler (void *cls,
498                  const struct GNUNET_PeerIdentity *peer)
499 {
500   size_t size;
501   struct GNUNET_CORE_TransmitHandle *th;
502
503   if (! advertising)
504     return;
505   if (NULL == hostlist_uri)
506     return;
507   size = strlen (hostlist_uri) + 1;
508   if (size + sizeof (struct GNUNET_MessageHeader) >=
509       GNUNET_SERVER_MAX_MESSAGE_SIZE)
510   {
511     GNUNET_break (0);
512     return;
513   }
514   size += sizeof (struct GNUNET_MessageHeader);
515   if (NULL == core)
516   {
517     GNUNET_break (0);
518     return;
519   }
520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
521               "Asked CORE to transmit advertisement message with a size of %u bytes to peer `%s'\n",
522               size,
523               GNUNET_i2s (peer));
524   if (NULL ==
525       (th = GNUNET_CORE_notify_transmit_ready (core, GNUNET_YES,
526                                                GNUNET_CORE_PRIO_BEST_EFFORT,
527                                                GNUNET_ADV_TIMEOUT,
528                                                peer,
529                                                size,
530                                                &adv_transmit_ready,
531                                                (void *) peer)) )
532   {
533     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
534                 _("Advertisement message could not be queued by core\n"));
535   }
536   GNUNET_assert (GNUNET_YES ==
537                  GNUNET_CONTAINER_multipeermap_put (advertisements,
538                                                     peer,
539                                                     th,
540                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
541 }
542
543
544 /**
545  * Method called whenever a given peer disconnects.
546  *
547  * @param cls closure
548  * @param peer peer identity this notification is about
549  */
550 static void
551 disconnect_handler (void *cls,
552                     const struct GNUNET_PeerIdentity *peer)
553 {
554   struct GNUNET_CORE_TransmitHandle *th;
555
556   if (! advertising)
557     return;
558   th = GNUNET_CONTAINER_multipeermap_get (advertisements,
559                                           peer);
560   if (NULL == th)
561     return;
562   GNUNET_assert (GNUNET_YES ==
563                  GNUNET_CONTAINER_multipeermap_remove (advertisements,
564                                                        peer,
565                                                        th));
566   GNUNET_CORE_notify_transmit_ready_cancel (th);
567 }
568
569
570 /**
571  * PEERINFO calls this function to let us know about a possible peer
572  * that we might want to connect to.
573  *
574  * @param cls closure (not used)
575  * @param peer potential peer to connect to
576  * @param hello HELLO for this peer (or NULL)
577  * @param err_msg NULL if successful, otherwise contains error message
578  */
579 static void
580 process_notify (void *cls,
581                 const struct GNUNET_PeerIdentity *peer,
582                 const struct GNUNET_HELLO_Message *hello,
583                 const char *err_msg)
584 {
585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
586               "Peerinfo is notifying us to rebuild our hostlist\n");
587   if (NULL != err_msg)
588     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
589                 _("Error in communication with PEERINFO service: %s\n"),
590                 err_msg);
591   if (NULL != builder)
592   {
593     /* restart re-build already in progress ... */
594     if (NULL != builder->pitr)
595     {
596       GNUNET_PEERINFO_iterate_cancel (builder->pitr);
597       builder->pitr = NULL;
598     }
599     GNUNET_free_non_null (builder->data);
600     builder->size = 0;
601     builder->data = NULL;
602   }
603   else
604   {
605     builder = GNUNET_new (struct HostSet);
606   }
607   GNUNET_assert (NULL != peerinfo);
608   builder->pitr
609     = GNUNET_PEERINFO_iterate (peerinfo,
610                                GNUNET_NO, NULL,
611                                GNUNET_TIME_UNIT_MINUTES,
612                                &host_processor, NULL);
613 }
614
615
616 /**
617  * Function that queries MHD's select sets and
618  * starts the task waiting for them.
619  */
620 static struct GNUNET_SCHEDULER_Task *
621 prepare_daemon (struct MHD_Daemon *daemon_handle);
622
623
624 /**
625  * Call MHD to process pending requests and then go back
626  * and schedule the next run.
627  *
628  * @param cls the `struct MHD_Daemon` of the HTTP server to run
629  * @param tc scheduler context
630  */
631 static void
632 run_daemon (void *cls,
633             const struct GNUNET_SCHEDULER_TaskContext *tc)
634 {
635   struct MHD_Daemon *daemon_handle = cls;
636
637   if (daemon_handle == daemon_handle_v4)
638     hostlist_task_v4 = NULL;
639   else
640     hostlist_task_v6 = NULL;
641
642   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
643     return;
644   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
645   if (daemon_handle == daemon_handle_v4)
646     hostlist_task_v4 = prepare_daemon (daemon_handle);
647   else
648     hostlist_task_v6 = prepare_daemon (daemon_handle);
649 }
650
651
652 /**
653  * Function that queries MHD's select sets and
654  * starts the task waiting for them.
655  *
656  * @param daemon_handle HTTP server to prepare to run
657  */
658 static struct GNUNET_SCHEDULER_Task *
659 prepare_daemon (struct MHD_Daemon *daemon_handle)
660 {
661   struct GNUNET_SCHEDULER_Task * ret;
662   fd_set rs;
663   fd_set ws;
664   fd_set es;
665   struct GNUNET_NETWORK_FDSet *wrs;
666   struct GNUNET_NETWORK_FDSet *wws;
667   int max;
668   MHD_UNSIGNED_LONG_LONG timeout;
669   int haveto;
670   struct GNUNET_TIME_Relative tv;
671
672   FD_ZERO (&rs);
673   FD_ZERO (&ws);
674   FD_ZERO (&es);
675   wrs = GNUNET_NETWORK_fdset_create ();
676   wws = GNUNET_NETWORK_fdset_create ();
677   max = -1;
678   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
679   haveto = MHD_get_timeout (daemon_handle, &timeout);
680   if (haveto == MHD_YES)
681     tv.rel_value_us = (uint64_t) timeout * 1000LL;
682   else
683     tv = GNUNET_TIME_UNIT_FOREVER_REL;
684   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
685   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
686   ret =
687       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
688                                    tv, wrs, wws,
689                                    &run_daemon, daemon_handle);
690   GNUNET_NETWORK_fdset_destroy (wrs);
691   GNUNET_NETWORK_fdset_destroy (wws);
692   return ret;
693 }
694
695
696 /**
697  * Start server offering our hostlist.
698  *
699  * @param c configuration to use
700  * @param st statistics handle to use
701  * @param co core handle to use
702  * @param[out] server_ch set to handler for CORE connect events
703  * @param[out] server_dh set to handler for CORE disconnect events
704  * @param advertise #GNUNET_YES if we should advertise our hostlist
705  * @return #GNUNET_OK on success
706  */
707 int
708 GNUNET_HOSTLIST_server_start (const struct GNUNET_CONFIGURATION_Handle *c,
709                               struct GNUNET_STATISTICS_Handle *st,
710                               struct GNUNET_CORE_Handle *co,
711                               GNUNET_CORE_ConnectEventHandler *server_ch,
712                               GNUNET_CORE_DisconnectEventHandler *server_dh,
713                               int advertise)
714 {
715   unsigned long long port;
716   char *hostname;
717   char *ipv4;
718   char *ipv6;
719   size_t size;
720   struct in_addr i4;
721   struct in6_addr i6;
722   struct sockaddr_in v4;
723   struct sockaddr_in6 v6;
724   const struct sockaddr *sa4;
725   const struct sockaddr *sa6;
726
727   advertising = advertise;
728   if (! advertising)
729   {
730     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
731                 "Advertising not enabled on this hostlist server\n");
732   }
733   else
734   {
735     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
736                 "Advertising enabled on this hostlist server\n");
737     advertisements = GNUNET_CONTAINER_multipeermap_create (8,
738                                                            GNUNET_NO);
739   }
740   cfg = c;
741   stats = st;
742   peerinfo = GNUNET_PEERINFO_connect (cfg);
743   if (NULL == peerinfo)
744   {
745     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
746                 _("Could not access PEERINFO service.  Exiting.\n"));
747     return GNUNET_SYSERR;
748   }
749   if (GNUNET_OK !=
750       GNUNET_CONFIGURATION_get_value_number (cfg,
751                                              "HOSTLIST",
752                                              "HTTPPORT",
753                                              &port))
754     return GNUNET_SYSERR;
755   if ((0 == port) || (port > UINT16_MAX))
756   {
757     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
758                 _("Invalid port number %llu.  Exiting.\n"),
759                 port);
760     return GNUNET_SYSERR;
761   }
762
763   if (GNUNET_SYSERR ==
764       GNUNET_CONFIGURATION_get_value_string (cfg,
765                                              "HOSTLIST",
766                                              "EXTERNAL_DNS_NAME",
767                                              &hostname))
768     hostname = GNUNET_RESOLVER_local_fqdn_get ();
769   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
770               _("Hostlist service starts on %s:%llu\n"),
771               hostname, port);
772   if (NULL != hostname)
773   {
774     size = strlen (hostname);
775     if (size + 15 > MAX_URL_LEN)
776     {
777       GNUNET_break (0);
778     }
779     else
780     {
781       GNUNET_asprintf (&hostlist_uri,
782                        "http://%s:%u/", hostname,
783                        (unsigned int) port);
784       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
785                   _("Address to obtain hostlist: `%s'\n"),
786                   hostlist_uri);
787     }
788     GNUNET_free (hostname);
789   }
790
791   if (GNUNET_CONFIGURATION_have_value (cfg, "HOSTLIST", "BINDTOIPV4"))
792   {
793     if (GNUNET_OK !=
794         GNUNET_CONFIGURATION_get_value_string (cfg, "HOSTLIST",
795                                                "BINDTOIP", &ipv4))
796     {
797       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
798                   _("BINDTOIP does not a valid IPv4 address! Ignoring BINDTOIPV4.\n"));
799     }
800
801   }
802   else
803     ipv4 = NULL;
804   if (GNUNET_CONFIGURATION_have_value (cfg, "HOSTLIST", "BINDTOIPV6"))
805   {
806     if (GNUNET_OK !=
807         GNUNET_CONFIGURATION_get_value_string (cfg, "HOSTLIST",
808                                                "BINDTOIP", &ipv6))
809       {
810       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
811           _("BINDTOIP does not a valid IPv4 address! Ignoring BINDTOIPV6.\n"));
812     }
813   }
814   else
815     ipv6 = NULL;
816   sa4 = NULL;
817   if (NULL != ipv4)
818   {
819     if (1 == inet_pton (AF_INET, ipv4, &i4))
820     {
821       memset (&v4, 0, sizeof (v4));
822       v4.sin_family = AF_INET;
823       v4.sin_addr = i4;
824       v4.sin_port = htons (port);
825 #if HAVE_SOCKADDR_IN_SIN_LEN
826       v4.sin_len = sizeof (v4);
827 #endif
828       sa4 = (const struct sockaddr *) &v4;
829     }
830     else
831       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
832                   _("`%s' is not a valid IPv4 address! Ignoring BINDTOIPV4.\n"),
833                   ipv4);
834     GNUNET_free (ipv4);
835   }
836   sa6 = NULL;
837   if (NULL != ipv6)
838   {
839     if (1 == inet_pton (AF_INET6, ipv6, &i6))
840     {
841       memset (&v6, 0, sizeof (v6));
842       v6.sin6_family = AF_INET6;
843       v6.sin6_addr = i6;
844       v6.sin6_port = htons (port);
845 #if HAVE_SOCKADDR_IN_SIN_LEN
846       v6.sin6_len = sizeof (v6);
847 #endif
848       sa6 = (const struct sockaddr *) &v6;
849     }
850     else
851       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
852                   _("`%s' is not a valid IPv6 address! Ignoring BINDTOIPV6.\n"),
853                   ipv6);
854     GNUNET_free (ipv6);
855   }
856
857   daemon_handle_v6 = MHD_start_daemon (MHD_USE_IPv6 | MHD_USE_DEBUG,
858                                        (uint16_t) port,
859                                        &accept_policy_callback, NULL,
860                                        &access_handler_callback, NULL,
861                                        MHD_OPTION_CONNECTION_LIMIT,
862                                        (unsigned int) 128,
863                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT,
864                                        (unsigned int) 32,
865                                        MHD_OPTION_CONNECTION_TIMEOUT,
866                                        (unsigned int) 16,
867                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
868                                        (size_t) (16 * 1024),
869                                        MHD_OPTION_SOCK_ADDR,
870                                        sa6,
871                                        MHD_OPTION_END);
872   daemon_handle_v4 = MHD_start_daemon (MHD_NO_FLAG | MHD_USE_DEBUG,
873                                        (uint16_t) port,
874                                        &accept_policy_callback, NULL,
875                                        &access_handler_callback, NULL,
876                                        MHD_OPTION_CONNECTION_LIMIT,
877                                        (unsigned int) 128,
878                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT,
879                                        (unsigned int) 32,
880                                        MHD_OPTION_CONNECTION_TIMEOUT,
881                                        (unsigned int) 16,
882                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
883                                        (size_t) (16 * 1024),
884                                        MHD_OPTION_SOCK_ADDR,
885                                        sa4,
886                                        MHD_OPTION_END);
887
888   if ( (NULL == daemon_handle_v6) &&
889        (NULL == daemon_handle_v4) )
890   {
891     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
892                 _("Could not start hostlist HTTP server on port %u\n"),
893                 (unsigned short) port);
894     return GNUNET_SYSERR;
895   }
896
897   core = co;
898   *server_ch = &connect_handler;
899   *server_dh = &disconnect_handler;
900   if (NULL != daemon_handle_v4)
901     hostlist_task_v4 = prepare_daemon (daemon_handle_v4);
902   if (NULL != daemon_handle_v6)
903     hostlist_task_v6 = prepare_daemon (daemon_handle_v6);
904   notify = GNUNET_PEERINFO_notify (cfg,
905                                    GNUNET_NO,
906                                    &process_notify, NULL);
907   return GNUNET_OK;
908 }
909
910
911 /**
912  * Stop server offering our hostlist.
913  */
914 void
915 GNUNET_HOSTLIST_server_stop ()
916 {
917   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
918               "Hostlist server shutdown\n");
919   if (NULL != hostlist_task_v6)
920   {
921     GNUNET_SCHEDULER_cancel (hostlist_task_v6);
922     hostlist_task_v6 = NULL;
923   }
924   if (NULL != hostlist_task_v4)
925   {
926     GNUNET_SCHEDULER_cancel (hostlist_task_v4);
927     hostlist_task_v4 = NULL;
928   }
929   if (NULL != daemon_handle_v4)
930   {
931     MHD_stop_daemon (daemon_handle_v4);
932     daemon_handle_v4 = NULL;
933   }
934   if (NULL != daemon_handle_v6)
935   {
936     MHD_stop_daemon (daemon_handle_v6);
937     daemon_handle_v6 = NULL;
938   }
939   if (NULL != response)
940   {
941     MHD_destroy_response (response);
942     response = NULL;
943   }
944   if (NULL != notify)
945   {
946     GNUNET_PEERINFO_notify_cancel (notify);
947     notify = NULL;
948   }
949   if (NULL != builder)
950   {
951     if (NULL != builder->pitr)
952     {
953       GNUNET_PEERINFO_iterate_cancel (builder->pitr);
954       builder->pitr = NULL;
955     }
956     GNUNET_free_non_null (builder->data);
957     GNUNET_free (builder);
958   }
959   if (NULL != peerinfo)
960   {
961     GNUNET_PEERINFO_disconnect (peerinfo);
962     peerinfo = NULL;
963   }
964   if (NULL != advertisements)
965   {
966     GNUNET_break (0 ==
967                   GNUNET_CONTAINER_multipeermap_size (advertisements));
968     GNUNET_CONTAINER_multipeermap_destroy (advertisements);
969     advertisements = NULL;
970   }
971   cfg = NULL;
972   stats = NULL;
973   core = NULL;
974 }
975
976 /* end of gnunet-daemon-hostlist_server.c */