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