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