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