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