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