simplify MQ logic to always carry the same kinds of flags, and extend transport API...
[oweals/gnunet.git] / src / topology / gnunet-daemon-topology.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2007-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      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20
21 /**
22  * @file topology/gnunet-daemon-topology.c
23  * @brief code for maintaining the overlay topology
24  * @author Christian Grothoff
25  *
26  * This daemon combines three functions:
27  * - suggesting to ATS which peers we might want to connect to
28  * - enforcing the F2F restrictions (by blacklisting)
29  * - gossping HELLOs
30  *
31  * All three require similar information (who are our friends
32  * impacts connectivity suggestions; connectivity suggestions
33  * should consider blacklisting; connectivity suggestions
34  * should consider available/known HELLOs; gossip requires
35  * connectivity data; connectivity suggestions require
36  * connectivity data), which is why they are combined in this
37  * program.
38  */
39 #include "platform.h"
40 #include "gnunet_util_lib.h"
41 #include "gnunet_friends_lib.h"
42 #include "gnunet_constants.h"
43 #include "gnunet_core_service.h"
44 #include "gnunet_protocols.h"
45 #include "gnunet_peerinfo_service.h"
46 #include "gnunet_statistics_service.h"
47 #include "gnunet_transport_service.h"
48 #include "gnunet_ats_service.h"
49
50
51 /**
52  * At what frequency do we sent HELLOs to a peer?
53  */
54 #define HELLO_ADVERTISEMENT_MIN_FREQUENCY \
55   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
56
57 /**
58  * After what time period do we expire the HELLO Bloom filter?
59  */
60 #define HELLO_ADVERTISEMENT_MIN_REPEAT_FREQUENCY \
61   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 4)
62
63
64 /**
65  * Record for neighbours, friends and blacklisted peers.
66  */
67 struct Peer
68 {
69   /**
70    * Which peer is this entry about?
71    */
72   struct GNUNET_PeerIdentity pid;
73
74   /**
75    * Our handle for transmitting to this peer; NULL
76    * if peer is not connected.
77    */
78   struct GNUNET_MQ_Handle *mq;
79
80   /**
81    * Pointer to the HELLO message of this peer; can be NULL.
82    */
83   struct GNUNET_HELLO_Message *hello;
84
85   /**
86    * Bloom filter used to mark which peers already got the HELLO
87    * from this peer.
88    */
89   struct GNUNET_CONTAINER_BloomFilter *filter;
90
91   /**
92    * Next time we are allowed to transmit a HELLO to this peer?
93    */
94   struct GNUNET_TIME_Absolute next_hello_allowed;
95
96   /**
97    * When should we reset the bloom filter of this entry?
98    */
99   struct GNUNET_TIME_Absolute filter_expiration;
100
101   /**
102    * ID of task we use to wait for the time to send the next HELLO
103    * to this peer.
104    */
105   struct GNUNET_SCHEDULER_Task *hello_delay_task;
106
107   /**
108    * Handle for our connectivity suggestion for this peer.
109    */
110   struct GNUNET_ATS_ConnectivitySuggestHandle *sh;
111
112   /**
113    * How much would we like to connect to this peer?
114    */
115   uint32_t strength;
116
117   /**
118    * Is this peer listed here because it is a friend?
119    */
120   int is_friend;
121 };
122
123
124 /**
125  * Our peerinfo notification context.  We use notification
126  * to instantly learn about new peers as they are discovered.
127  */
128 static struct GNUNET_PEERINFO_NotifyContext *peerinfo_notify;
129
130 /**
131  * Our configuration.
132  */
133 static const struct GNUNET_CONFIGURATION_Handle *cfg;
134
135 /**
136  * Handle to the CORE service.
137  */
138 static struct GNUNET_CORE_Handle *handle;
139
140 /**
141  * Handle to the PEERINFO service.
142  */
143 static struct GNUNET_PEERINFO_Handle *pi;
144
145 /**
146  * Handle to the ATS service.
147  */
148 static struct GNUNET_ATS_ConnectivityHandle *ats;
149
150 /**
151  * Identity of this peer.
152  */
153 static struct GNUNET_PeerIdentity my_identity;
154
155 /**
156  * All of our friends, all of our current neighbours and all peers for
157  * which we have HELLOs.  So pretty much everyone.  Maps peer identities
158  * to `struct Peer *` values.
159  */
160 static struct GNUNET_CONTAINER_MultiPeerMap *peers;
161
162 /**
163  * Handle for reporting statistics.
164  */
165 static struct GNUNET_STATISTICS_Handle *stats;
166
167 /**
168  * Blacklist (NULL if we have none).
169  */
170 static struct GNUNET_TRANSPORT_Blacklist *blacklist;
171
172 /**
173  * Task scheduled to asynchronously reconsider adding/removing
174  * peer connectivity suggestions.
175  */
176 static struct GNUNET_SCHEDULER_Task *add_task;
177
178 /**
179  * Active HELLO offering to transport service.
180  */
181 static struct GNUNET_TRANSPORT_OfferHelloHandle *oh;
182
183 /**
184  * Flag to disallow non-friend connections (pure F2F mode).
185  */
186 static int friends_only;
187
188 /**
189  * Minimum number of friends to have in the
190  * connection set before we allow non-friends.
191  */
192 static unsigned int minimum_friend_count;
193
194 /**
195  * Number of peers (friends and others) that we are currently connected to.
196  */
197 static unsigned int connection_count;
198
199 /**
200  * Target number of connections.
201  */
202 static unsigned int target_connection_count;
203
204 /**
205  * Number of friends that we are currently connected to.
206  */
207 static unsigned int friend_count;
208
209
210 /**
211  * Function that decides if a connection is acceptable or not.
212  * If we have a blacklist, only friends are allowed, so the check
213  * is rather simple.
214  *
215  * @param cls closure
216  * @param pid peer to approve or disapprove
217  * @return #GNUNET_OK if the connection is allowed
218  */
219 static int
220 blacklist_check (void *cls, const struct GNUNET_PeerIdentity *pid)
221 {
222   struct Peer *pos;
223
224   pos = GNUNET_CONTAINER_multipeermap_get (peers, pid);
225   if ((NULL != pos) && (GNUNET_YES == pos->is_friend))
226     return GNUNET_OK;
227   GNUNET_STATISTICS_update (stats,
228                             gettext_noop ("# peers blacklisted"),
229                             1,
230                             GNUNET_NO);
231   return GNUNET_SYSERR;
232 }
233
234
235 /**
236  * Whitelist all peers that we blacklisted; we've passed
237  * the minimum number of friends.
238  */
239 static void
240 whitelist_peers ()
241 {
242   if (NULL != blacklist)
243   {
244     GNUNET_TRANSPORT_blacklist_cancel (blacklist);
245     blacklist = NULL;
246   }
247 }
248
249
250 /**
251  * Free all resources associated with the given peer.
252  *
253  * @param cls closure (not used)
254  * @param pid identity of the peer
255  * @param value peer to free
256  * @return #GNUNET_YES (always: continue to iterate)
257  */
258 static int
259 free_peer (void *cls, const struct GNUNET_PeerIdentity *pid, void *value)
260 {
261   struct Peer *pos = value;
262
263   GNUNET_break (NULL == pos->mq);
264   GNUNET_break (GNUNET_OK ==
265                 GNUNET_CONTAINER_multipeermap_remove (peers, pid, pos));
266   if (NULL != pos->hello_delay_task)
267   {
268     GNUNET_SCHEDULER_cancel (pos->hello_delay_task);
269     pos->hello_delay_task = NULL;
270   }
271   if (NULL != pos->sh)
272   {
273     GNUNET_ATS_connectivity_suggest_cancel (pos->sh);
274     pos->sh = NULL;
275   }
276   if (NULL != pos->hello)
277   {
278     GNUNET_free_non_null (pos->hello);
279     pos->hello = NULL;
280   }
281   if (NULL != pos->filter)
282   {
283     GNUNET_CONTAINER_bloomfilter_free (pos->filter);
284     pos->filter = NULL;
285   }
286   GNUNET_free (pos);
287   return GNUNET_YES;
288 }
289
290
291 /**
292  * Recalculate how much we want to be connected to the specified peer
293  * and let ATS know about the result.
294  *
295  * @param pos peer to consider connecting to
296  */
297 static void
298 attempt_connect (struct Peer *pos)
299 {
300   uint32_t strength;
301
302   if (0 == GNUNET_memcmp (&my_identity, &pos->pid))
303     return; /* This is myself, nothing to do. */
304   if (connection_count < target_connection_count)
305     strength = 1;
306   else
307     strength = 0;
308   if ((friend_count < minimum_friend_count) || (GNUNET_YES == friends_only))
309   {
310     if (pos->is_friend)
311       strength += 10; /* urgently needed */
312     else
313       strength = 0; /* disallowed */
314   }
315   if (pos->is_friend)
316     strength *= 2; /* friends always count more */
317   if (NULL != pos->mq)
318     strength *= 2; /* existing connections preferred */
319   if (strength == pos->strength)
320     return; /* nothing to do */
321   if (NULL != pos->sh)
322   {
323     GNUNET_ATS_connectivity_suggest_cancel (pos->sh);
324     pos->sh = NULL;
325   }
326   pos->strength = strength;
327   if (0 != strength)
328   {
329     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
330                 "Asking to connect to `%s' with strength %u\n",
331                 GNUNET_i2s (&pos->pid),
332                 (unsigned int) strength);
333     GNUNET_STATISTICS_update (stats,
334                               gettext_noop ("# connect requests issued to ATS"),
335                               1,
336                               GNUNET_NO);
337     pos->sh = GNUNET_ATS_connectivity_suggest (ats, &pos->pid, strength);
338   }
339 }
340
341
342 /**
343  * Create a new entry in the peer list.
344  *
345  * @param peer identity of the new entry
346  * @param hello hello message, can be NULL
347  * @param is_friend is the new entry for a friend?
348  * @return the new entry
349  */
350 static struct Peer *
351 make_peer (const struct GNUNET_PeerIdentity *peer,
352            const struct GNUNET_HELLO_Message *hello,
353            int is_friend)
354 {
355   struct Peer *ret;
356
357   ret = GNUNET_new (struct Peer);
358   ret->pid = *peer;
359   ret->is_friend = is_friend;
360   if (NULL != hello)
361   {
362     ret->hello = GNUNET_malloc (GNUNET_HELLO_size (hello));
363     GNUNET_memcpy (ret->hello, hello, GNUNET_HELLO_size (hello));
364   }
365   GNUNET_break (GNUNET_OK ==
366                 GNUNET_CONTAINER_multipeermap_put (
367                   peers,
368                   peer,
369                   ret,
370                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
371   return ret;
372 }
373
374
375 /**
376  * Setup bloom filter for the given peer entry.
377  *
378  * @param peer entry to initialize
379  */
380 static void
381 setup_filter (struct Peer *peer)
382 {
383   struct GNUNET_HashCode hc;
384
385   /* 2^{-5} chance of not sending a HELLO to a peer is
386    * acceptably small (if the filter is 50% full);
387    * 64 bytes of memory are small compared to the rest
388    * of the data structure and would only really become
389    * "useless" once a HELLO has been passed on to ~100
390    * other peers, which is likely more than enough in
391    * any case; hence 64, 5 as bloomfilter parameters. */
392   peer->filter = GNUNET_CONTAINER_bloomfilter_init (NULL, 64, 5);
393   peer->filter_expiration =
394     GNUNET_TIME_relative_to_absolute (HELLO_ADVERTISEMENT_MIN_REPEAT_FREQUENCY);
395   /* never send a peer its own HELLO */
396   GNUNET_CRYPTO_hash (&peer->pid, sizeof (struct GNUNET_PeerIdentity), &hc);
397   GNUNET_CONTAINER_bloomfilter_add (peer->filter, &hc);
398 }
399
400
401 /**
402  * Closure for #find_advertisable_hello().
403  */
404 struct FindAdvHelloContext
405 {
406
407   /**
408    * Peer we want to advertise to.
409    */
410   struct Peer *peer;
411
412   /**
413    * Where to store the result (peer selected for advertising).
414    */
415   struct Peer *result;
416
417   /**
418    * Maximum HELLO size we can use right now.
419    */
420   size_t max_size;
421
422   struct GNUNET_TIME_Relative next_adv;
423 };
424
425
426 /**
427  * Find a peer that would be reasonable for advertising.
428  *
429  * @param cls closure
430  * @param pid identity of a peer
431  * @param value 'struct Peer*' for the peer we are considering
432  * @return #GNUNET_YES (continue iteration)
433  */
434 static int
435 find_advertisable_hello (void *cls,
436                          const struct GNUNET_PeerIdentity *pid,
437                          void *value)
438 {
439   struct FindAdvHelloContext *fah = cls;
440   struct Peer *pos = value;
441   struct GNUNET_TIME_Relative rst_time;
442   struct GNUNET_HashCode hc;
443   size_t hs;
444
445   if (pos == fah->peer)
446     return GNUNET_YES;
447   if (pos->hello == NULL)
448     return GNUNET_YES;
449   rst_time = GNUNET_TIME_absolute_get_remaining (pos->filter_expiration);
450   if (0 == rst_time.rel_value_us)
451   {
452     /* time to discard... */
453     GNUNET_CONTAINER_bloomfilter_free (pos->filter);
454     setup_filter (pos);
455   }
456   fah->next_adv = GNUNET_TIME_relative_min (rst_time, fah->next_adv);
457   hs = GNUNET_HELLO_size (pos->hello);
458   if (hs > fah->max_size)
459     return GNUNET_YES;
460   GNUNET_CRYPTO_hash (&fah->peer->pid,
461                       sizeof (struct GNUNET_PeerIdentity),
462                       &hc);
463   if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (pos->filter, &hc))
464     fah->result = pos;
465   return GNUNET_YES;
466 }
467
468
469 /**
470  * Calculate when we would like to send the next HELLO to this
471  * peer and ask for it.
472  *
473  * @param cls for which peer to schedule the HELLO
474  */
475 static void
476 schedule_next_hello (void *cls)
477 {
478   struct Peer *pl = cls;
479   struct FindAdvHelloContext fah;
480   struct GNUNET_MQ_Envelope *env;
481   size_t want;
482   struct GNUNET_TIME_Relative delay;
483   struct GNUNET_HashCode hc;
484
485   pl->hello_delay_task = NULL;
486   GNUNET_assert (NULL != pl->mq);
487   /* find applicable HELLOs */
488   fah.peer = pl;
489   fah.result = NULL;
490   fah.max_size = GNUNET_MAX_MESSAGE_SIZE - 1;
491   fah.next_adv = GNUNET_TIME_UNIT_FOREVER_REL;
492   GNUNET_CONTAINER_multipeermap_iterate (peers, &find_advertisable_hello, &fah);
493   pl->hello_delay_task =
494     GNUNET_SCHEDULER_add_delayed (fah.next_adv, &schedule_next_hello, pl);
495   if (NULL == fah.result)
496     return;
497   delay = GNUNET_TIME_absolute_get_remaining (pl->next_hello_allowed);
498   if (0 != delay.rel_value_us)
499     return;
500
501   want = GNUNET_HELLO_size (fah.result->hello);
502   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
503               "Sending HELLO with %u bytes",
504               (unsigned int) want);
505   env = GNUNET_MQ_msg_copy (&fah.result->hello->header);
506   GNUNET_MQ_send (pl->mq, env);
507
508   /* avoid sending this one again soon */
509   GNUNET_CRYPTO_hash (&pl->pid, sizeof (struct GNUNET_PeerIdentity), &hc);
510   GNUNET_CONTAINER_bloomfilter_add (fah.result->filter, &hc);
511
512   GNUNET_STATISTICS_update (stats,
513                             gettext_noop ("# HELLO messages gossipped"),
514                             1,
515                             GNUNET_NO);
516   /* prepare to send the next one */
517   pl->next_hello_allowed =
518     GNUNET_TIME_relative_to_absolute (HELLO_ADVERTISEMENT_MIN_FREQUENCY);
519   if (NULL != pl->hello_delay_task)
520     GNUNET_SCHEDULER_cancel (pl->hello_delay_task);
521   pl->hello_delay_task = GNUNET_SCHEDULER_add_now (&schedule_next_hello, pl);
522 }
523
524
525 /**
526  * Cancel existing requests for sending HELLOs to this peer
527  * and recalculate when we should send HELLOs to it based
528  * on our current state (something changed!).
529  *
530  * @param cls closure `struct Peer` to skip, or NULL
531  * @param pid identity of a peer
532  * @param value `struct Peer *` for the peer
533  * @return #GNUNET_YES (always)
534  */
535 static int
536 reschedule_hellos (void *cls,
537                    const struct GNUNET_PeerIdentity *pid,
538                    void *value)
539 {
540   struct Peer *peer = value;
541   struct Peer *skip = cls;
542
543   if (skip == peer)
544     return GNUNET_YES;
545   if (NULL == peer->mq)
546     return GNUNET_YES;
547   if (NULL != peer->hello_delay_task)
548   {
549     GNUNET_SCHEDULER_cancel (peer->hello_delay_task);
550     peer->hello_delay_task = NULL;
551   }
552   peer->hello_delay_task =
553     GNUNET_SCHEDULER_add_now (&schedule_next_hello, peer);
554   return GNUNET_YES;
555 }
556
557
558 /**
559  * Method called whenever a peer connects.
560  *
561  * @param cls closure
562  * @param peer peer identity this notification is about
563  * @param mq message queue for communicating with @a peer
564  * @return our `struct Peer` for @a peer
565  */
566 static void *
567 connect_notify (void *cls,
568                 const struct GNUNET_PeerIdentity *peer,
569                 struct GNUNET_MQ_Handle *mq)
570 {
571   struct Peer *pos;
572
573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
574               "Core told us that we are connecting to `%s'\n",
575               GNUNET_i2s (peer));
576   if (0 == GNUNET_memcmp (&my_identity, peer))
577     return NULL;
578   GNUNET_MQ_set_options (mq, GNUNET_MQ_PRIO_BEST_EFFORT);
579   connection_count++;
580   GNUNET_STATISTICS_set (stats,
581                          gettext_noop ("# peers connected"),
582                          connection_count,
583                          GNUNET_NO);
584   pos = GNUNET_CONTAINER_multipeermap_get (peers, peer);
585   if (NULL == pos)
586   {
587     pos = make_peer (peer, NULL, GNUNET_NO);
588   }
589   else
590   {
591     GNUNET_assert (NULL == pos->mq);
592   }
593   pos->mq = mq;
594   if (pos->is_friend)
595   {
596     friend_count++;
597     if ((friend_count == minimum_friend_count) && (GNUNET_YES != friends_only))
598       whitelist_peers ();
599     GNUNET_STATISTICS_set (stats,
600                            gettext_noop ("# friends connected"),
601                            friend_count,
602                            GNUNET_NO);
603   }
604   reschedule_hellos (NULL, peer, pos);
605   return pos;
606 }
607
608
609 /**
610  * Try to add more peers to our connection set.
611  *
612  * @param cls closure, not used
613  * @param pid identity of a peer
614  * @param value `struct Peer *` for the peer
615  * @return #GNUNET_YES (continue to iterate)
616  */
617 static int
618 try_add_peers (void *cls, const struct GNUNET_PeerIdentity *pid, void *value)
619 {
620   struct Peer *pos = value;
621
622   attempt_connect (pos);
623   return GNUNET_YES;
624 }
625
626
627 /**
628  * Add peers and schedule connection attempt
629  *
630  * @param cls unused, NULL
631  */
632 static void
633 add_peer_task (void *cls)
634 {
635   add_task = NULL;
636
637   GNUNET_CONTAINER_multipeermap_iterate (peers, &try_add_peers, NULL);
638 }
639
640
641 /**
642  * Method called whenever a peer disconnects.
643  *
644  * @param cls closure
645  * @param peer peer identity this notification is about
646  * @param internal_cls the `struct Peer` for this peer
647  */
648 static void
649 disconnect_notify (void *cls,
650                    const struct GNUNET_PeerIdentity *peer,
651                    void *internal_cls)
652 {
653   struct Peer *pos = internal_cls;
654
655   if (NULL == pos)
656     return; /* myself, we're shutting down */
657   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
658               "Core told us that we disconnected from `%s'\n",
659               GNUNET_i2s (peer));
660   if (NULL == pos->mq)
661   {
662     GNUNET_break (0);
663     return;
664   }
665   pos->mq = NULL;
666   connection_count--;
667   if (NULL != pos->hello_delay_task)
668   {
669     GNUNET_SCHEDULER_cancel (pos->hello_delay_task);
670     pos->hello_delay_task = NULL;
671   }
672   GNUNET_STATISTICS_set (stats,
673                          gettext_noop ("# peers connected"),
674                          connection_count,
675                          GNUNET_NO);
676   if (pos->is_friend)
677   {
678     friend_count--;
679     GNUNET_STATISTICS_set (stats,
680                            gettext_noop ("# friends connected"),
681                            friend_count,
682                            GNUNET_NO);
683   }
684   if (((connection_count < target_connection_count) ||
685        (friend_count < minimum_friend_count)) &&
686       (NULL == add_task))
687     add_task = GNUNET_SCHEDULER_add_now (&add_peer_task, NULL);
688   if ((friend_count < minimum_friend_count) && (NULL == blacklist))
689     blacklist = GNUNET_TRANSPORT_blacklist (cfg, &blacklist_check, NULL);
690 }
691
692
693 /**
694  * Iterator called on each address.
695  *
696  * @param cls flag that we will set if we see any addresses
697  * @param address the address of the peer
698  * @param expiration when will the given address expire
699  * @return #GNUNET_SYSERR always, to terminate iteration
700  */
701 static int
702 address_iterator (void *cls,
703                   const struct GNUNET_HELLO_Address *address,
704                   struct GNUNET_TIME_Absolute expiration)
705 {
706   int *flag = cls;
707
708   *flag = GNUNET_YES;
709   return GNUNET_SYSERR;
710 }
711
712
713 /**
714  * We've gotten a HELLO from another peer.  Consider it for
715  * advertising.
716  *
717  * @param hello the HELLO we got
718  */
719 static void
720 consider_for_advertising (const struct GNUNET_HELLO_Message *hello)
721 {
722   int have_address;
723   struct GNUNET_PeerIdentity pid;
724   struct GNUNET_TIME_Absolute dt;
725   struct GNUNET_HELLO_Message *nh;
726   struct Peer *peer;
727   uint16_t size;
728
729   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
730   {
731     GNUNET_break (0);
732     return;
733   }
734   if (0 == GNUNET_memcmp (&pid, &my_identity))
735     return; /* that's me! */
736   have_address = GNUNET_NO;
737   GNUNET_HELLO_iterate_addresses (hello,
738                                   GNUNET_NO,
739                                   &address_iterator,
740                                   &have_address);
741   if (GNUNET_NO == have_address)
742     return; /* no point in advertising this one... */
743   peer = GNUNET_CONTAINER_multipeermap_get (peers, &pid);
744   if (NULL == peer)
745   {
746     peer = make_peer (&pid, hello, GNUNET_NO);
747   }
748   else if (NULL != peer->hello)
749   {
750     dt = GNUNET_HELLO_equals (peer->hello, hello, GNUNET_TIME_absolute_get ());
751     if (dt.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
752       return; /* nothing new here */
753   }
754   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
755               "Found HELLO from peer `%s' for advertising\n",
756               GNUNET_i2s (&pid));
757   if (NULL != peer->hello)
758   {
759     nh = GNUNET_HELLO_merge (peer->hello, hello);
760     GNUNET_free (peer->hello);
761     peer->hello = nh;
762   }
763   else
764   {
765     size = GNUNET_HELLO_size (hello);
766     peer->hello = GNUNET_malloc (size);
767     GNUNET_memcpy (peer->hello, hello, size);
768   }
769   if (NULL != peer->filter)
770   {
771     GNUNET_CONTAINER_bloomfilter_free (peer->filter);
772     peer->filter = NULL;
773   }
774   setup_filter (peer);
775   /* since we have a new HELLO to pick from, re-schedule all
776    * HELLO requests that are not bound by the HELLO send rate! */
777   GNUNET_CONTAINER_multipeermap_iterate (peers, &reschedule_hellos, peer);
778 }
779
780
781 /**
782  * PEERINFO calls this function to let us know about a possible peer
783  * that we might want to connect to.
784  *
785  * @param cls closure (not used)
786  * @param peer potential peer to connect to
787  * @param hello HELLO for this peer (or NULL)
788  * @param err_msg NULL if successful, otherwise contains error message
789  */
790 static void
791 process_peer (void *cls,
792               const struct GNUNET_PeerIdentity *peer,
793               const struct GNUNET_HELLO_Message *hello,
794               const char *err_msg)
795 {
796   struct Peer *pos;
797
798   if (NULL != err_msg)
799   {
800     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
801                 _ ("Error in communication with PEERINFO service: %s\n"),
802                 err_msg);
803     GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
804     peerinfo_notify =
805       GNUNET_PEERINFO_notify (cfg, GNUNET_NO, &process_peer, NULL);
806     return;
807   }
808   GNUNET_assert (NULL != peer);
809   if (0 == GNUNET_memcmp (&my_identity, peer))
810     return; /* that's me! */
811   if (NULL == hello)
812   {
813     /* free existing HELLO, if any */
814     pos = GNUNET_CONTAINER_multipeermap_get (peers, peer);
815     if (NULL != pos)
816     {
817       GNUNET_free_non_null (pos->hello);
818       pos->hello = NULL;
819       if (NULL != pos->filter)
820       {
821         GNUNET_CONTAINER_bloomfilter_free (pos->filter);
822         pos->filter = NULL;
823       }
824       if ((NULL == pos->mq) && (GNUNET_NO == pos->is_friend))
825         free_peer (NULL, &pos->pid, pos);
826     }
827     return;
828   }
829   consider_for_advertising (hello);
830   pos = GNUNET_CONTAINER_multipeermap_get (peers, peer);
831   if (NULL == pos)
832     pos = make_peer (peer, hello, GNUNET_NO);
833   attempt_connect (pos);
834 }
835
836
837 /**
838  * Function called after #GNUNET_CORE_connect has succeeded
839  * (or failed for good).
840  *
841  * @param cls closure
842  * @param my_id ID of this peer, NULL if we failed
843  */
844 static void
845 core_init (void *cls, const struct GNUNET_PeerIdentity *my_id)
846 {
847   if (NULL == my_id)
848   {
849     GNUNET_log (
850       GNUNET_ERROR_TYPE_ERROR,
851       _ ("Failed to connect to core service, can not manage topology!\n"));
852     GNUNET_SCHEDULER_shutdown ();
853     return;
854   }
855   my_identity = *my_id;
856   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "I am peer `%s'\n", GNUNET_i2s (my_id));
857   peerinfo_notify =
858     GNUNET_PEERINFO_notify (cfg, GNUNET_NO, &process_peer, NULL);
859 }
860
861
862 /**
863  * Process friend found in FRIENDS file.
864  *
865  * @param cls pointer to an `unsigned int` to be incremented per friend found
866  * @param pid identity of the friend
867  */
868 static void
869 handle_friend (void *cls, const struct GNUNET_PeerIdentity *pid)
870 {
871   unsigned int *entries_found = cls;
872   struct Peer *fl;
873
874   if (0 == GNUNET_memcmp (pid, &my_identity))
875   {
876     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
877                 _ ("Found myself `%s' in friend list (useless, ignored)\n"),
878                 GNUNET_i2s (pid));
879     return;
880   }
881   (*entries_found)++;
882   fl = make_peer (pid, NULL, GNUNET_YES);
883   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
884               _ ("Found friend `%s' in configuration\n"),
885               GNUNET_i2s (&fl->pid));
886 }
887
888
889 /**
890  * Read the friends file.
891  */
892 static void
893 read_friends_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
894 {
895   unsigned int entries_found;
896
897   entries_found = 0;
898   if (GNUNET_OK != GNUNET_FRIENDS_parse (cfg, &handle_friend, &entries_found))
899   {
900     if ((GNUNET_YES == friends_only) || (minimum_friend_count > 0))
901       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
902                   _ ("Encountered errors parsing friends list!\n"));
903   }
904   GNUNET_STATISTICS_update (stats,
905                             gettext_noop ("# friends in configuration"),
906                             entries_found,
907                             GNUNET_NO);
908   if ((minimum_friend_count > entries_found) && (GNUNET_NO == friends_only))
909   {
910     GNUNET_log (
911       GNUNET_ERROR_TYPE_WARNING,
912       _ (
913         "Fewer friends specified than required by minimum friend count. Will only connect to friends.\n"));
914   }
915   if ((minimum_friend_count > target_connection_count) &&
916       (GNUNET_NO == friends_only))
917   {
918     GNUNET_log (
919       GNUNET_ERROR_TYPE_WARNING,
920       _ (
921         "More friendly connections required than target total number of connections.\n"));
922   }
923 }
924
925
926 /**
927  * This function is called whenever an encrypted HELLO message is
928  * received.
929  *
930  * @param cls closure with the peer identity of the sender
931  * @param message the actual HELLO message
932  * @return #GNUNET_OK if @a message is well-formed
933  *         #GNUNET_SYSERR if @a message is invalid
934  */
935 static int
936 check_hello (void *cls, const struct GNUNET_HELLO_Message *message)
937 {
938   struct GNUNET_PeerIdentity pid;
939
940   if (GNUNET_OK != GNUNET_HELLO_get_id (message, &pid))
941   {
942     GNUNET_break_op (0);
943     return GNUNET_SYSERR;
944   }
945   return GNUNET_OK;
946 }
947
948
949 /**
950  * This function is called whenever an encrypted HELLO message is
951  * received.
952  *
953  * @param cls closure with the peer identity of the sender
954  * @param message the actual HELLO message
955  */
956 static void
957 handle_hello (void *cls, const struct GNUNET_HELLO_Message *message)
958 {
959   const struct GNUNET_PeerIdentity *other = cls;
960   struct Peer *peer;
961   struct GNUNET_PeerIdentity pid;
962
963   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964               "Received encrypted HELLO from peer `%s'",
965               GNUNET_i2s (other));
966   GNUNET_assert (GNUNET_OK == GNUNET_HELLO_get_id (message, &pid));
967   GNUNET_STATISTICS_update (stats,
968                             gettext_noop ("# HELLO messages received"),
969                             1,
970                             GNUNET_NO);
971   peer = GNUNET_CONTAINER_multipeermap_get (peers, &pid);
972   if (NULL == peer)
973   {
974     if ((GNUNET_YES == friends_only) || (friend_count < minimum_friend_count))
975       return;
976   }
977   else
978   {
979     if ((GNUNET_YES != peer->is_friend) && (GNUNET_YES == friends_only))
980       return;
981     if ((GNUNET_YES != peer->is_friend) &&
982         (friend_count < minimum_friend_count))
983       return;
984   }
985   (void) GNUNET_PEERINFO_add_peer (pi, message, NULL, NULL);
986 }
987
988
989 /**
990  * Last task run during shutdown.  Disconnects us from
991  * the transport and core.
992  *
993  * @param cls unused, NULL
994  */
995 static void
996 cleaning_task (void *cls)
997 {
998   if (NULL != peerinfo_notify)
999   {
1000     GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
1001     peerinfo_notify = NULL;
1002   }
1003   if (NULL != handle)
1004   {
1005     GNUNET_CORE_disconnect (handle);
1006     handle = NULL;
1007   }
1008   whitelist_peers ();
1009   if (NULL != add_task)
1010   {
1011     GNUNET_SCHEDULER_cancel (add_task);
1012     add_task = NULL;
1013   }
1014   if (NULL != oh)
1015   {
1016     GNUNET_TRANSPORT_offer_hello_cancel (oh);
1017     oh = NULL;
1018   }
1019   GNUNET_CONTAINER_multipeermap_iterate (peers, &free_peer, NULL);
1020   GNUNET_CONTAINER_multipeermap_destroy (peers);
1021   peers = NULL;
1022   if (NULL != ats)
1023   {
1024     GNUNET_ATS_connectivity_done (ats);
1025     ats = NULL;
1026   }
1027   if (NULL != pi)
1028   {
1029     GNUNET_PEERINFO_disconnect (pi);
1030     pi = NULL;
1031   }
1032   if (NULL != stats)
1033   {
1034     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1035     stats = NULL;
1036   }
1037 }
1038
1039
1040 /**
1041  * Main function that will be run.
1042  *
1043  * @param cls closure
1044  * @param args remaining command-line arguments
1045  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1046  * @param c configuration
1047  */
1048 static void
1049 run (void *cls,
1050      char *const *args,
1051      const char *cfgfile,
1052      const struct GNUNET_CONFIGURATION_Handle *c)
1053 {
1054   struct GNUNET_MQ_MessageHandler handlers[] =
1055     {GNUNET_MQ_hd_var_size (hello,
1056                             GNUNET_MESSAGE_TYPE_HELLO,
1057                             struct GNUNET_HELLO_Message,
1058                             NULL),
1059      GNUNET_MQ_handler_end ()};
1060   unsigned long long opt;
1061
1062   cfg = c;
1063   stats = GNUNET_STATISTICS_create ("topology", cfg);
1064   friends_only =
1065     GNUNET_CONFIGURATION_get_value_yesno (cfg, "TOPOLOGY", "FRIENDS-ONLY");
1066   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg,
1067                                                           "TOPOLOGY",
1068                                                           "MINIMUM-FRIENDS",
1069                                                           &opt))
1070     opt = 0;
1071   minimum_friend_count = (unsigned int) opt;
1072   if (GNUNET_OK !=
1073       GNUNET_CONFIGURATION_get_value_number (cfg,
1074                                              "TOPOLOGY",
1075                                              "TARGET-CONNECTION-COUNT",
1076                                              &opt))
1077     opt = 16;
1078   target_connection_count = (unsigned int) opt;
1079   peers = GNUNET_CONTAINER_multipeermap_create (target_connection_count * 2,
1080                                                 GNUNET_NO);
1081   read_friends_file (cfg);
1082   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1083               "Topology would like %u connections with at least %u friends\n",
1084               target_connection_count,
1085               minimum_friend_count);
1086   if ((GNUNET_YES == friends_only) || (minimum_friend_count > 0))
1087     blacklist = GNUNET_TRANSPORT_blacklist (cfg, &blacklist_check, NULL);
1088   ats = GNUNET_ATS_connectivity_init (cfg);
1089   pi = GNUNET_PEERINFO_connect (cfg);
1090   handle = GNUNET_CORE_connect (cfg,
1091                                 NULL,
1092                                 &core_init,
1093                                 &connect_notify,
1094                                 &disconnect_notify,
1095                                 handlers);
1096   GNUNET_SCHEDULER_add_shutdown (&cleaning_task, NULL);
1097   if (NULL == handle)
1098   {
1099     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1100                 _ ("Failed to connect to `%s' service.\n"),
1101                 "core");
1102     GNUNET_SCHEDULER_shutdown ();
1103     return;
1104   }
1105 }
1106
1107
1108 /**
1109  * The main function for the topology daemon.
1110  *
1111  * @param argc number of arguments from the command line
1112  * @param argv command line arguments
1113  * @return 0 ok, 1 on error
1114  */
1115 int
1116 main (int argc, char *const *argv)
1117 {
1118   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1119     GNUNET_GETOPT_OPTION_END};
1120   int ret;
1121
1122   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1123     return 2;
1124
1125   ret = (GNUNET_OK == GNUNET_PROGRAM_run (argc,
1126                                           argv,
1127                                           "gnunet-daemon-topology",
1128                                           _ ("GNUnet topology control"),
1129                                           options,
1130                                           &run,
1131                                           NULL))
1132           ? 0
1133           : 1;
1134   GNUNET_free ((void *) argv);
1135   return ret;
1136 }
1137
1138
1139 #if defined(LINUX) && defined(__GLIBC__)
1140 #include <malloc.h>
1141
1142 /**
1143  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1144  */
1145 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
1146 {
1147   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
1148   mallopt (M_TOP_PAD, 1 * 1024);
1149   malloc_trim (0);
1150 }
1151 #endif
1152
1153 /* end of gnunet-daemon-topology.c */