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