-fix time assertion introduce in last patch
[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  * 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,
645                                            GNUNET_CORE_PRIO_BEST_EFFORT,
646                                            GNUNET_CONSTANTS_SERVICE_TIMEOUT,
647                                            &pl->pid, next_want,
648                                            &hello_advertising_ready, pl);
649   }
650 }
651
652
653 /**
654  * Cancel existing requests for sending HELLOs to this peer
655  * and recalculate when we should send HELLOs to it based
656  * on our current state (something changed!).
657  *
658  * @param cls closure, 'struct Peer' to skip, or NULL
659  * @param pid identity of a peer
660  * @param value 'struct Peer*' for the peer
661  * @return GNUNET_YES (always)
662  */
663 static int
664 reschedule_hellos (void *cls, const struct GNUNET_PeerIdentity * pid, void *value)
665 {
666   struct Peer *peer = value;
667   struct Peer *skip = cls;
668
669   if (skip == peer)
670     return GNUNET_YES;
671   if (!peer->is_connected)
672     return GNUNET_YES;
673   if (peer->hello_req != NULL)
674   {
675     GNUNET_CORE_notify_transmit_ready_cancel (peer->hello_req);
676     peer->hello_req = NULL;
677   }
678   if (peer->hello_delay_task != GNUNET_SCHEDULER_NO_TASK)
679   {
680     GNUNET_SCHEDULER_cancel (peer->hello_delay_task);
681     peer->hello_delay_task = GNUNET_SCHEDULER_NO_TASK;
682   }
683   peer->hello_delay_task =
684       GNUNET_SCHEDULER_add_now (&schedule_next_hello, peer);
685   return GNUNET_YES;
686 }
687
688
689 /**
690  * Method called whenever a peer connects.
691  *
692  * @param cls closure
693  * @param peer peer identity this notification is about
694  */
695 static void
696 connect_notify (void *cls, const struct GNUNET_PeerIdentity *peer)
697 {
698   struct Peer *pos;
699
700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
701               "Core told us that we are connecting to `%s'\n",
702               GNUNET_i2s (peer));
703   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
704     return;
705
706   connection_count++;
707   GNUNET_STATISTICS_set (stats, gettext_noop ("# peers connected"),
708                          connection_count, GNUNET_NO);
709   pos = GNUNET_CONTAINER_multipeermap_get (peers, peer);
710   if (NULL == pos)
711   {
712     pos = make_peer (peer, NULL, GNUNET_NO);
713     GNUNET_break (GNUNET_OK == is_connection_allowed (pos));
714   }
715   else
716   {
717     GNUNET_assert (GNUNET_NO == pos->is_connected);
718     pos->greylisted_until.abs_value_us = 0;        /* remove greylisting */
719   }
720   pos->is_connected = GNUNET_YES;
721   pos->connect_attempts = 0;    /* re-set back-off factor */
722   if (pos->is_friend)
723   {
724     if ((friend_count == minimum_friend_count - 1) &&
725         (GNUNET_YES != friends_only))
726       whitelist_peers ();
727     friend_count++;
728     GNUNET_STATISTICS_set (stats, gettext_noop ("# friends connected"),
729                            friend_count, GNUNET_NO);
730   }
731   reschedule_hellos (NULL, peer, pos);
732 }
733
734
735 /**
736  * Try to add more peers to our connection set.
737  *
738  * @param cls closure, not used
739  * @param pid identity of a peer
740  * @param value 'struct Peer*' for the peer
741  * @return GNUNET_YES (continue to iterate)
742  */
743 static int
744 try_add_peers (void *cls, const struct GNUNET_PeerIdentity * pid, void *value)
745 {
746   struct Peer *pos = value;
747
748   schedule_attempt_connect (pos);
749   return GNUNET_YES;
750 }
751
752
753 /**
754  * Last task run during shutdown.  Disconnects us from
755  * the transport and core.
756  *
757  * @param cls unused, NULL
758  * @param tc scheduler context
759  */
760 static void
761 add_peer_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
762 {
763   add_task = GNUNET_SCHEDULER_NO_TASK;
764
765   GNUNET_CONTAINER_multipeermap_iterate (peers, &try_add_peers, NULL);
766 }
767
768
769 /**
770  * Method called whenever a peer disconnects.
771  *
772  * @param cls closure
773  * @param peer peer identity this notification is about
774  */
775 static void
776 disconnect_notify (void *cls, const struct GNUNET_PeerIdentity *peer)
777 {
778   struct Peer *pos;
779
780   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
781     return;
782   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
783               "Core told us that we disconnected from `%s'\n",
784               GNUNET_i2s (peer));
785   pos = GNUNET_CONTAINER_multipeermap_get (peers, peer);
786   if (NULL == pos)
787   {
788     GNUNET_break (0);
789     return;
790   }
791   if (pos->is_connected != GNUNET_YES)
792   {
793     GNUNET_break (0);
794     return;
795   }
796   pos->is_connected = GNUNET_NO;
797   connection_count--;
798   if (NULL != pos->hello_req)
799   {
800     GNUNET_CORE_notify_transmit_ready_cancel (pos->hello_req);
801     pos->hello_req = NULL;
802   }
803   if (GNUNET_SCHEDULER_NO_TASK != pos->hello_delay_task)
804   {
805     GNUNET_SCHEDULER_cancel (pos->hello_delay_task);
806     pos->hello_delay_task = GNUNET_SCHEDULER_NO_TASK;
807   }
808   GNUNET_STATISTICS_set (stats, gettext_noop ("# peers connected"),
809                          connection_count, GNUNET_NO);
810   if (pos->is_friend)
811   {
812     friend_count--;
813     GNUNET_STATISTICS_set (stats, gettext_noop ("# friends connected"),
814                            friend_count, GNUNET_NO);
815   }
816   if (((connection_count < target_connection_count) ||
817        (friend_count < minimum_friend_count)) &&
818       (GNUNET_SCHEDULER_NO_TASK == add_task))
819     add_task = GNUNET_SCHEDULER_add_now (&add_peer_task, NULL);
820   if ((friend_count < minimum_friend_count) && (blacklist == NULL))
821     blacklist = GNUNET_TRANSPORT_blacklist (cfg, &blacklist_check, NULL);
822 }
823
824
825 /**
826  * Iterator called on each address.
827  *
828  * @param cls flag that we will set if we see any addresses
829  * @param address the address of the peer
830  * @param expiration when will the given address expire
831  * @return GNUNET_SYSERR always, to terminate iteration
832  */
833 static int
834 address_iterator (void *cls, const struct GNUNET_HELLO_Address *address,
835                   struct GNUNET_TIME_Absolute expiration)
836 {
837   int *flag = cls;
838
839   *flag = GNUNET_YES;
840   return GNUNET_SYSERR;
841 }
842
843
844 /**
845  * We've gotten a HELLO from another peer.  Consider it for
846  * advertising.
847  *
848  * @param hello the HELLO we got
849  */
850 static void
851 consider_for_advertising (const struct GNUNET_HELLO_Message *hello)
852 {
853   int have_address;
854   struct GNUNET_PeerIdentity pid;
855   struct GNUNET_TIME_Absolute dt;
856   struct GNUNET_HELLO_Message *nh;
857   struct Peer *peer;
858   uint16_t size;
859
860   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
861   {
862     GNUNET_break (0);
863     return;
864   }
865   if (0 == memcmp (&pid, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
866     return;                     /* that's me! */
867   have_address = GNUNET_NO;
868   GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &address_iterator,
869                                   &have_address);
870   if (GNUNET_NO == have_address)
871     return;                     /* no point in advertising this one... */
872   peer = GNUNET_CONTAINER_multipeermap_get (peers, &pid);
873   if (NULL == peer)
874   {
875     peer = make_peer (&pid, hello, GNUNET_NO);
876   }
877   else if (peer->hello != NULL)
878   {
879     dt = GNUNET_HELLO_equals (peer->hello, hello, GNUNET_TIME_absolute_get ());
880     if (dt.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
881       return;                   /* nothing new here */
882   }
883   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
884               "Found `%s' from peer `%s' for advertising\n", "HELLO",
885               GNUNET_i2s (&pid));
886   if (peer->hello != NULL)
887   {
888     nh = GNUNET_HELLO_merge (peer->hello, hello);
889     GNUNET_free (peer->hello);
890     peer->hello = nh;
891   }
892   else
893   {
894     size = GNUNET_HELLO_size (hello);
895     peer->hello = GNUNET_malloc (size);
896     memcpy (peer->hello, hello, size);
897   }
898   if (peer->filter != NULL)
899     GNUNET_CONTAINER_bloomfilter_free (peer->filter);
900   setup_filter (peer);
901   /* since we have a new HELLO to pick from, re-schedule all
902    * HELLO requests that are not bound by the HELLO send rate! */
903   GNUNET_CONTAINER_multipeermap_iterate (peers, &reschedule_hellos, peer);
904 }
905
906
907 /**
908  * PEERINFO calls this function to let us know about a possible peer
909  * that we might want to connect to.
910  *
911  * @param cls closure (not used)
912  * @param peer potential peer to connect to
913  * @param hello HELLO for this peer (or NULL)
914  * @param err_msg NULL if successful, otherwise contains error message
915  */
916 static void
917 process_peer (void *cls, const struct GNUNET_PeerIdentity *peer,
918               const struct GNUNET_HELLO_Message *hello, const char *err_msg)
919 {
920   struct Peer *pos;
921
922   if (err_msg != NULL)
923   {
924     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
925                 _("Error in communication with PEERINFO service: %s\n"),
926                 err_msg);
927     GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
928     peerinfo_notify = GNUNET_PEERINFO_notify (cfg, GNUNET_NO, &process_peer, NULL);
929     return;
930   }
931   GNUNET_assert (peer != NULL);
932   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
933     return;                     /* that's me! */
934   if (hello == NULL)
935   {
936     /* free existing HELLO, if any */
937     pos = GNUNET_CONTAINER_multipeermap_get (peers, peer);
938     if (NULL != pos)
939     {
940       GNUNET_free_non_null (pos->hello);
941       pos->hello = NULL;
942       if (pos->filter != NULL)
943       {
944         GNUNET_CONTAINER_bloomfilter_free (pos->filter);
945         pos->filter = NULL;
946       }
947       if ((GNUNET_NO == pos->is_connected) && (GNUNET_NO == pos->is_friend) &&
948           (0 ==
949            GNUNET_TIME_absolute_get_remaining (pos->
950                                                greylisted_until).rel_value_us))
951         free_peer (NULL, &pos->pid, pos);
952     }
953     return;
954   }
955   consider_for_advertising (hello);
956   pos = GNUNET_CONTAINER_multipeermap_get (peers, peer);
957   if (pos == NULL)
958     pos = make_peer (peer, hello, GNUNET_NO);
959   GNUNET_assert (NULL != pos);
960   if (GNUNET_YES == pos->is_connected)
961   {
962     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Already connected to peer `%s'\n",
963                 GNUNET_i2s (peer));
964     return;
965   }
966   if (GNUNET_TIME_absolute_get_remaining (pos->greylisted_until).rel_value_us > 0)
967   {
968     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Already tried peer `%s' recently\n",
969                 GNUNET_i2s (peer));
970     return;                     /* peer still greylisted */
971   }
972   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Considering connecting to peer `%s'\n",
973               GNUNET_i2s (peer));
974   schedule_attempt_connect (pos);
975 }
976
977
978 /**
979  * Function called after #GNUNET_CORE_connect has succeeded
980  * (or failed for good).
981  *
982  * @param cls closure
983  * @param my_id ID of this peer, NULL if we failed
984  */
985 static void
986 core_init (void *cls,
987            const struct GNUNET_PeerIdentity *my_id)
988 {
989   if (NULL == my_id)
990   {
991     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
992                 _
993                 ("Failed to connect to core service, can not manage topology!\n"));
994     GNUNET_SCHEDULER_shutdown ();
995     return;
996   }
997   my_identity = *my_id;
998   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
999               "I am peer `%s'\n",
1000               GNUNET_i2s (my_id));
1001   peerinfo_notify = GNUNET_PEERINFO_notify (cfg, GNUNET_NO,
1002                                             &process_peer, NULL);
1003 }
1004
1005
1006 /**
1007  * Process friend found in FRIENDS file.
1008  *
1009  * @param cls pointer to an `unsigned int` to be incremented per friend found
1010  * @param pid identity of the friend
1011  */
1012 static void
1013 handle_friend (void *cls,
1014                const struct GNUNET_PeerIdentity *pid)
1015 {
1016   unsigned int *entries_found = cls;
1017   struct Peer *fl;
1018
1019   if (0 == memcmp (pid, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
1020   {
1021     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1022                 _("Found myself `%s' in friend list (useless, ignored)\n"),
1023                 GNUNET_i2s (pid));
1024     return;
1025   }
1026   (*entries_found)++;
1027   fl = make_peer (pid, NULL, GNUNET_YES);
1028   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1029               _("Found friend `%s' in configuration\n"),
1030               GNUNET_i2s (&fl->pid));
1031 }
1032
1033
1034 /**
1035  * Read the friends file.
1036  */
1037 static void
1038 read_friends_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1039 {
1040   unsigned int entries_found;
1041
1042   entries_found = 0;
1043   if (GNUNET_OK !=
1044       GNUNET_FRIENDS_parse (cfg,
1045                             &handle_friend,
1046                             &entries_found))
1047   {
1048     if ((friends_only) || (minimum_friend_count > 0))
1049       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1050                   _("Encountered errors parsing friends list!\n"));
1051   }
1052   GNUNET_STATISTICS_update (stats, gettext_noop ("# friends in configuration"),
1053                             entries_found, GNUNET_NO);
1054   if ((minimum_friend_count > entries_found) && (friends_only == GNUNET_NO))
1055   {
1056     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1057                 _("Fewer friends specified than required by minimum friend count. Will only connect to friends.\n"));
1058   }
1059   if ((minimum_friend_count > target_connection_count) &&
1060       (friends_only == GNUNET_NO))
1061   {
1062     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1063                 _("More friendly connections required than target total number of connections.\n"));
1064   }
1065 }
1066
1067
1068 /**
1069  * This function is called whenever an encrypted HELLO message is
1070  * received.
1071  *
1072  * @param cls closure
1073  * @param other the other peer involved (sender or receiver, NULL
1074  *        for loopback messages where we are both sender and receiver)
1075  * @param message the actual HELLO message
1076  * @return GNUNET_OK to keep the connection open,
1077  *         GNUNET_SYSERR to close it (signal serious error)
1078  */
1079 static int
1080 handle_encrypted_hello (void *cls, const struct GNUNET_PeerIdentity *other,
1081                         const struct GNUNET_MessageHeader *message)
1082 {
1083   struct Peer *peer;
1084   struct GNUNET_PeerIdentity pid;
1085
1086   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received encrypted `%s' from peer `%s'",
1087               "HELLO", GNUNET_i2s (other));
1088   if (GNUNET_OK !=
1089       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) message, &pid))
1090   {
1091     GNUNET_break_op (0);
1092     return GNUNET_SYSERR;
1093   }
1094   GNUNET_STATISTICS_update (stats, gettext_noop ("# HELLO messages received"),
1095                             1, GNUNET_NO);
1096   peer = GNUNET_CONTAINER_multipeermap_get (peers, &pid);
1097   if (NULL == peer)
1098   {
1099     if ((GNUNET_YES == friends_only) || (friend_count < minimum_friend_count))
1100       return GNUNET_OK;
1101   }
1102   else
1103   {
1104     if ((GNUNET_YES != peer->is_friend) && (GNUNET_YES == friends_only))
1105       return GNUNET_OK;
1106     if ((GNUNET_YES != peer->is_friend) &&
1107         (friend_count < minimum_friend_count))
1108       return GNUNET_OK;
1109   }
1110   if (transport != NULL)
1111     GNUNET_TRANSPORT_offer_hello (transport, message, NULL, NULL);
1112   return GNUNET_OK;
1113 }
1114
1115
1116 /**
1117  * Function to fill send buffer with HELLO.
1118  *
1119  * @param cls 'struct Peer' of the target peer
1120  * @param size number of bytes available in buf
1121  * @param buf where the callee should write the message
1122  * @return number of bytes written to buf
1123  */
1124 static size_t
1125 hello_advertising_ready (void *cls, size_t size, void *buf)
1126 {
1127   struct Peer *pl = cls;
1128   struct FindAdvHelloContext fah;
1129   size_t want;
1130   struct GNUNET_HashCode hc;
1131
1132   pl->hello_req = NULL;
1133   GNUNET_assert (GNUNET_YES == pl->is_connected);
1134   /* find applicable HELLOs */
1135   fah.peer = pl;
1136   fah.result = NULL;
1137   fah.max_size = size;
1138   fah.next_adv = GNUNET_TIME_UNIT_FOREVER_REL;
1139   GNUNET_CONTAINER_multipeermap_iterate (peers, &find_advertisable_hello, &fah);
1140   want = 0;
1141   if (fah.result != NULL)
1142   {
1143     want = GNUNET_HELLO_size (fah.result->hello);
1144     GNUNET_assert (want <= size);
1145     memcpy (buf, fah.result->hello, want);
1146     GNUNET_CRYPTO_hash (&pl->pid, sizeof (struct GNUNET_PeerIdentity), &hc);
1147     GNUNET_CONTAINER_bloomfilter_add (fah.result->filter, &hc);
1148     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' with %u bytes", "HELLO",
1149                 (unsigned int) want);
1150     GNUNET_STATISTICS_update (stats,
1151                               gettext_noop ("# HELLO messages gossipped"), 1,
1152                               GNUNET_NO);
1153   }
1154
1155   if (pl->hello_delay_task != GNUNET_SCHEDULER_NO_TASK)
1156     GNUNET_SCHEDULER_cancel (pl->hello_delay_task);
1157   pl->next_hello_allowed =
1158       GNUNET_TIME_relative_to_absolute (HELLO_ADVERTISEMENT_MIN_FREQUENCY);
1159   pl->hello_delay_task = GNUNET_SCHEDULER_add_now (&schedule_next_hello, pl);
1160   return want;
1161 }
1162
1163
1164 /**
1165  * Last task run during shutdown.  Disconnects us from
1166  * the transport and core.
1167  *
1168  * @param cls unused, NULL
1169  * @param tc scheduler context
1170  */
1171 static void
1172 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1173 {
1174   if (NULL != peerinfo_notify)
1175   {
1176     GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
1177     peerinfo_notify = NULL;
1178   }
1179   GNUNET_TRANSPORT_disconnect (transport);
1180   transport = NULL;
1181   if (handle != NULL)
1182   {
1183     GNUNET_CORE_disconnect (handle);
1184     handle = NULL;
1185   }
1186   whitelist_peers ();
1187   if (GNUNET_SCHEDULER_NO_TASK != add_task)
1188   {
1189     GNUNET_SCHEDULER_cancel (add_task);
1190     add_task = GNUNET_SCHEDULER_NO_TASK;
1191   }
1192   GNUNET_CONTAINER_multipeermap_iterate (peers, &free_peer, NULL);
1193   GNUNET_CONTAINER_multipeermap_destroy (peers);
1194   peers = NULL;
1195   if (stats != NULL)
1196   {
1197     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1198     stats = NULL;
1199   }
1200 }
1201
1202
1203 /**
1204  * Main function that will be run.
1205  *
1206  * @param cls closure
1207  * @param args remaining command-line arguments
1208  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1209  * @param c configuration
1210  */
1211 static void
1212 run (void *cls,
1213      char *const *args,
1214      const char *cfgfile,
1215      const struct GNUNET_CONFIGURATION_Handle *c)
1216 {
1217   static struct GNUNET_CORE_MessageHandler handlers[] = {
1218     {&handle_encrypted_hello, GNUNET_MESSAGE_TYPE_HELLO, 0},
1219     {NULL, 0, 0}
1220   };
1221   unsigned long long opt;
1222
1223   cfg = c;
1224   stats = GNUNET_STATISTICS_create ("topology", cfg);
1225   friends_only =
1226       GNUNET_CONFIGURATION_get_value_yesno (cfg, "TOPOLOGY", "FRIENDS-ONLY");
1227   if (GNUNET_OK !=
1228       GNUNET_CONFIGURATION_get_value_number (cfg, "TOPOLOGY", "MINIMUM-FRIENDS",
1229                                              &opt))
1230     opt = 0;
1231   minimum_friend_count = (unsigned int) opt;
1232   if (GNUNET_OK !=
1233       GNUNET_CONFIGURATION_get_value_number (cfg, "TOPOLOGY",
1234                                              "TARGET-CONNECTION-COUNT", &opt))
1235     opt = 16;
1236   target_connection_count = (unsigned int) opt;
1237   peers = GNUNET_CONTAINER_multipeermap_create (target_connection_count * 2, GNUNET_NO);
1238
1239   if ((friends_only == GNUNET_YES) || (minimum_friend_count > 0))
1240     read_friends_file (cfg);
1241   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1242               "Topology would like %u connections with at least %u friends\n",
1243               target_connection_count, minimum_friend_count);
1244   if ((friend_count < minimum_friend_count) && (blacklist == NULL))
1245     blacklist = GNUNET_TRANSPORT_blacklist (cfg, &blacklist_check, NULL);
1246   transport = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL, NULL, NULL);
1247   handle =
1248       GNUNET_CORE_connect (cfg, NULL,
1249                            &core_init,
1250                            &connect_notify,
1251                            &disconnect_notify,
1252                            NULL, GNUNET_NO,
1253                            NULL, GNUNET_NO,
1254                            handlers);
1255   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleaning_task,
1256                                 NULL);
1257   if (NULL == transport)
1258   {
1259     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1260                 _("Failed to connect to `%s' service.\n"), "transport");
1261     GNUNET_SCHEDULER_shutdown ();
1262     return;
1263   }
1264   if (NULL == handle)
1265   {
1266     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1267                 _("Failed to connect to `%s' service.\n"), "core");
1268     GNUNET_SCHEDULER_shutdown ();
1269     return;
1270   }
1271 }
1272
1273
1274 /**
1275  * The main function for the topology daemon.
1276  *
1277  * @param argc number of arguments from the command line
1278  * @param argv command line arguments
1279  * @return 0 ok, 1 on error
1280  */
1281 int
1282 main (int argc, char *const *argv)
1283 {
1284   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1285     GNUNET_GETOPT_OPTION_END
1286   };
1287   int ret;
1288
1289   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1290     return 2;
1291
1292   ret =
1293       (GNUNET_OK ==
1294        GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-topology",
1295                            _
1296                            ("GNUnet topology control (maintaining P2P cadet and F2F constraints)"),
1297                            options, &run, NULL)) ? 0 : 1;
1298   GNUNET_free ((void*) argv);
1299   return ret;
1300 }
1301
1302
1303 #ifdef LINUX
1304 #include <malloc.h>
1305
1306 /**
1307  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1308  */
1309 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
1310 {
1311   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
1312   mallopt (M_TOP_PAD, 1 * 1024);
1313   malloc_trim (0);
1314 }
1315 #endif
1316
1317 /* end of gnunet-daemon-topology.c */