- implementation for mantis 0002485
[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 struct 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 cls peer to connect to
402  * @param tc scheduler context
403  */
404 static void
405 do_attempt_connect (void *cls,
406                     const struct GNUNET_SCHEDULER_TaskContext *tc)
407 {
408   struct Peer *pos = cls;
409   struct GNUNET_TIME_Relative delay;
410
411   pos->attempt_connect_task = GNUNET_SCHEDULER_NO_TASK;
412   if (GNUNET_YES == pos->is_connected)
413     return;
414   delay = GNUNET_TIME_absolute_get_remaining (next_connect_attempt);
415   if (delay.rel_value > 0)
416   {
417     pos->attempt_connect_task = GNUNET_SCHEDULER_add_delayed (delay,
418                                                               &do_attempt_connect,
419                                                               pos);
420     return;
421   }
422   next_connect_attempt = GNUNET_TIME_relative_to_absolute (MAX_CONNECT_FREQUENCY_DELAY);
423   attempt_connect (pos);
424 }
425
426
427 /**
428  * Schedule a task to try to connect to the specified peer.
429  *
430  * @param pos peer to connect to
431  */
432 static void
433 schedule_attempt_connect (struct Peer *pos)
434 {
435   if (GNUNET_SCHEDULER_NO_TASK != pos->attempt_connect_task)
436     return;
437   pos->attempt_connect_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_connect_attempt),
438                                                             &do_attempt_connect,
439                                                             pos);
440 }
441
442
443 /**
444  * Discard peer entries for greylisted peers
445  * where the greylisting has expired.
446  *
447  * @param cls 'struct Peer' to greylist
448  * @param tc scheduler context
449  */
450 static void
451 remove_from_greylist (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
452 {
453   struct Peer *pos = cls;
454   struct GNUNET_TIME_Relative rem;
455
456   pos->greylist_clean_task = GNUNET_SCHEDULER_NO_TASK;
457   rem = GNUNET_TIME_absolute_get_remaining (pos->greylisted_until);
458   if (rem.rel_value == 0)
459   {
460     schedule_attempt_connect (pos);
461   }
462   else
463   {
464     pos->greylist_clean_task =
465         GNUNET_SCHEDULER_add_delayed (rem, &remove_from_greylist, pos);
466   }
467   if ((GNUNET_NO == pos->is_friend) && (GNUNET_NO == pos->is_connected) &&
468       (NULL == pos->hello))
469   {
470     free_peer (NULL, &pos->pid.hashPubKey, pos);
471     return;
472   }
473 }
474
475
476 /**
477  * Create a new entry in the peer list.
478  *
479  * @param peer identity of the new entry
480  * @param hello hello message, can be NULL
481  * @param is_friend is the new entry for a friend?
482  * @return the new entry
483  */
484 static struct Peer *
485 make_peer (const struct GNUNET_PeerIdentity *peer,
486            const struct GNUNET_HELLO_Message *hello, int is_friend)
487 {
488   struct Peer *ret;
489
490   ret = GNUNET_malloc (sizeof (struct Peer));
491   ret->pid = *peer;
492   ret->is_friend = is_friend;
493   if (hello != NULL)
494   {
495     ret->hello = GNUNET_malloc (GNUNET_HELLO_size (hello));
496     memcpy (ret->hello, hello, GNUNET_HELLO_size (hello));
497   }
498   GNUNET_break (GNUNET_OK ==
499                 GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey,
500                                                    ret,
501                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
502   return ret;
503 }
504
505
506 /**
507  * Setup bloom filter for the given peer entry.
508  *
509  * @param peer entry to initialize
510  */
511 static void
512 setup_filter (struct Peer *peer)
513 {
514   /* 2^{-5} chance of not sending a HELLO to a peer is
515    * acceptably small (if the filter is 50% full);
516    * 64 bytes of memory are small compared to the rest
517    * of the data structure and would only really become
518    * "useless" once a HELLO has been passed on to ~100
519    * other peers, which is likely more than enough in
520    * any case; hence 64, 5 as bloomfilter parameters. */
521   peer->filter = GNUNET_CONTAINER_bloomfilter_init (NULL, 64, 5);
522   peer->filter_expiration =
523       GNUNET_TIME_relative_to_absolute
524       (HELLO_ADVERTISEMENT_MIN_REPEAT_FREQUENCY);
525   /* never send a peer its own HELLO */
526   GNUNET_CONTAINER_bloomfilter_add (peer->filter, &peer->pid.hashPubKey);
527 }
528
529
530 /**
531  * Function to fill send buffer with HELLO.
532  *
533  * @param cls 'struct Peer' of the target peer
534  * @param size number of bytes available in buf
535  * @param buf where the callee should write the message
536  * @return number of bytes written to buf
537  */
538 static size_t
539 hello_advertising_ready (void *cls, size_t size, void *buf);
540
541
542 /**
543  * Closure for 'find_advertisable_hello'.
544  */
545 struct FindAdvHelloContext
546 {
547
548   /**
549    * Peer we want to advertise to.
550    */
551   struct Peer *peer;
552
553   /**
554    * Where to store the result (peer selected for advertising).
555    */
556   struct Peer *result;
557
558   /**
559    * Maximum HELLO size we can use right now.
560    */
561   size_t max_size;
562
563   struct GNUNET_TIME_Relative next_adv;
564 };
565
566
567 /**
568  * Find a peer that would be reasonable for advertising.
569  *
570  * @param cls closure
571  * @param pid identity of a peer
572  * @param value 'struct Peer*' for the peer we are considering
573  * @return GNUNET_YES (continue iteration)
574  */
575 static int
576 find_advertisable_hello (void *cls, const struct GNUNET_HashCode * pid, void *value)
577 {
578   struct FindAdvHelloContext *fah = cls;
579   struct Peer *pos = value;
580   struct GNUNET_TIME_Relative rst_time;
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)
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   if (GNUNET_NO ==
599       GNUNET_CONTAINER_bloomfilter_test (pos->filter,
600                                          &fah->peer->pid.hashPubKey))
601     fah->result = pos;
602   return GNUNET_YES;
603 }
604
605
606 /**
607  * Calculate when we would like to send the next HELLO to this
608  * peer and ask for it.
609  *
610  * @param cls for which peer to schedule the HELLO
611  * @param tc task context
612  */
613 static void
614 schedule_next_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
615 {
616   struct Peer *pl = cls;
617   struct FindAdvHelloContext fah;
618   size_t next_want;
619   struct GNUNET_TIME_Relative delay;
620
621   pl->hello_delay_task = GNUNET_SCHEDULER_NO_TASK;
622   GNUNET_assert (GNUNET_YES == pl->is_connected);
623   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
624     return;                     /* we're out of here */
625   if (pl->hello_req != NULL)
626     return;                     /* did not finish sending the previous one */
627   /* find applicable HELLOs */
628   fah.peer = pl;
629   fah.result = NULL;
630   fah.max_size = GNUNET_SERVER_MAX_MESSAGE_SIZE - 1;
631   fah.next_adv = GNUNET_TIME_UNIT_FOREVER_REL;
632   GNUNET_CONTAINER_multihashmap_iterate (peers, &find_advertisable_hello, &fah);
633   pl->hello_delay_task =
634       GNUNET_SCHEDULER_add_delayed (fah.next_adv, &schedule_next_hello, pl);
635   if (fah.result == NULL)
636     return;
637   next_want = GNUNET_HELLO_size (fah.result->hello);
638   delay = GNUNET_TIME_absolute_get_remaining (pl->next_hello_allowed);
639   if (delay.rel_value == 0)
640   {
641     /* now! */
642     pl->hello_req =
643         GNUNET_CORE_notify_transmit_ready (handle, GNUNET_YES, 0,
644                                            GNUNET_CONSTANTS_SERVICE_TIMEOUT,
645                                            &pl->pid, next_want,
646                                            &hello_advertising_ready, pl);
647   }
648 }
649
650
651 /**
652  * Cancel existing requests for sending HELLOs to this peer
653  * and recalculate when we should send HELLOs to it based
654  * on our current state (something changed!).
655  *
656  * @param cls closure, 'struct Peer' to skip, or NULL
657  * @param pid identity of a peer
658  * @param value 'struct Peer*' for the peer
659  * @return GNUNET_YES (always)
660  */
661 static int
662 reschedule_hellos (void *cls, const struct GNUNET_HashCode * pid, void *value)
663 {
664   struct Peer *peer = value;
665   struct Peer *skip = cls;
666
667   if (skip == peer)
668     return GNUNET_YES;
669   if (!peer->is_connected)
670     return GNUNET_YES;
671   if (peer->hello_req != NULL)
672   {
673     GNUNET_CORE_notify_transmit_ready_cancel (peer->hello_req);
674     peer->hello_req = NULL;
675   }
676   if (peer->hello_delay_task != GNUNET_SCHEDULER_NO_TASK)
677   {
678     GNUNET_SCHEDULER_cancel (peer->hello_delay_task);
679     peer->hello_delay_task = GNUNET_SCHEDULER_NO_TASK;
680   }
681   peer->hello_delay_task =
682       GNUNET_SCHEDULER_add_now (&schedule_next_hello, peer);
683   return GNUNET_YES;
684 }
685
686
687 /**
688  * Method called whenever a peer connects.
689  *
690  * @param cls closure
691  * @param peer peer identity this notification is about
692  * @param atsi performance data
693  * @param atsi_count number of records in 'atsi'
694  */
695 static void
696 connect_notify (void *cls, const struct GNUNET_PeerIdentity *peer,
697                 const struct GNUNET_ATS_Information *atsi,
698                 unsigned int atsi_count)
699 {
700   struct Peer *pos;
701
702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
703               "Core told us that we are connecting to `%s'\n",
704               GNUNET_i2s (peer));
705   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
706     return;
707
708   connection_count++;
709   GNUNET_STATISTICS_set (stats, gettext_noop ("# peers connected"),
710                          connection_count, GNUNET_NO);
711   pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
712   if (NULL == pos)
713   {
714     pos = make_peer (peer, NULL, GNUNET_NO);
715     GNUNET_break (GNUNET_OK == is_connection_allowed (pos));
716   }
717   else
718   {
719     GNUNET_assert (GNUNET_NO == pos->is_connected);
720     pos->greylisted_until.abs_value = 0;        /* remove greylisting */
721   }
722   pos->is_connected = GNUNET_YES;
723   pos->connect_attempts = 0;    /* re-set back-off factor */
724   if (pos->is_friend)
725   {
726     if ((friend_count == minimum_friend_count - 1) &&
727         (GNUNET_YES != friends_only))
728       whitelist_peers ();
729     friend_count++;
730     GNUNET_STATISTICS_set (stats, gettext_noop ("# friends connected"),
731                            friend_count, GNUNET_NO);
732   }
733   reschedule_hellos (NULL, &peer->hashPubKey, pos);
734 }
735
736
737 /**
738  * Try to add more peers to our connection set.
739  *
740  * @param cls closure, not used
741  * @param pid identity of a peer
742  * @param value 'struct Peer*' for the peer
743  * @return GNUNET_YES (continue to iterate)
744  */
745 static int
746 try_add_peers (void *cls, const struct GNUNET_HashCode * pid, void *value)
747 {
748   struct Peer *pos = value;
749
750   schedule_attempt_connect (pos);
751   return GNUNET_YES;
752 }
753
754
755 /**
756  * Last task run during shutdown.  Disconnects us from
757  * the transport and core.
758  *
759  * @param cls unused, NULL
760  * @param tc scheduler context
761  */
762 static void
763 add_peer_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
764 {
765   add_task = GNUNET_SCHEDULER_NO_TASK;
766
767   GNUNET_CONTAINER_multihashmap_iterate (peers, &try_add_peers, NULL);
768 }
769
770
771 /**
772  * Method called whenever a peer disconnects.
773  *
774  * @param cls closure
775  * @param peer peer identity this notification is about
776  */
777 static void
778 disconnect_notify (void *cls, const struct GNUNET_PeerIdentity *peer)
779 {
780   struct Peer *pos;
781
782   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
783     return;
784   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
785               "Core told us that we disconnected from `%s'\n",
786               GNUNET_i2s (peer));
787   pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
788   if (NULL == pos)
789   {
790     GNUNET_break (0);
791     return;
792   }
793   if (pos->is_connected != GNUNET_YES)
794   {
795     GNUNET_break (0);
796     return;
797   }
798   pos->is_connected = GNUNET_NO;
799   connection_count--;
800   if (NULL != pos->hello_req)
801   {
802     GNUNET_CORE_notify_transmit_ready_cancel (pos->hello_req);
803     pos->hello_req = NULL;
804   }
805   if (GNUNET_SCHEDULER_NO_TASK != pos->hello_delay_task)
806   {
807     GNUNET_SCHEDULER_cancel (pos->hello_delay_task);
808     pos->hello_delay_task = GNUNET_SCHEDULER_NO_TASK;
809   }
810   GNUNET_STATISTICS_set (stats, gettext_noop ("# peers connected"),
811                          connection_count, GNUNET_NO);
812   if (pos->is_friend)
813   {
814     friend_count--;
815     GNUNET_STATISTICS_set (stats, gettext_noop ("# friends connected"),
816                            friend_count, GNUNET_NO);
817   }
818   if (((connection_count < target_connection_count) ||
819        (friend_count < minimum_friend_count)) &&
820       (GNUNET_SCHEDULER_NO_TASK == add_task))
821     add_task = GNUNET_SCHEDULER_add_now (&add_peer_task, NULL);
822   if ((friend_count < minimum_friend_count) && (blacklist == NULL))
823     blacklist = GNUNET_TRANSPORT_blacklist (cfg, &blacklist_check, NULL);
824 }
825
826
827 /**
828  * Iterator called on each address.
829  *
830  * @param cls flag that we will set if we see any addresses
831  * @param address the address of the peer
832  * @param expiration when will the given address expire
833  * @return GNUNET_SYSERR always, to terminate iteration
834  */
835 static int
836 address_iterator (void *cls, const struct GNUNET_HELLO_Address *address,
837                   struct GNUNET_TIME_Absolute expiration)
838 {
839   int *flag = cls;
840
841   *flag = GNUNET_YES;
842   return GNUNET_SYSERR;
843 }
844
845
846 /**
847  * We've gotten a HELLO from another peer.  Consider it for
848  * advertising.
849  *
850  * @param hello the HELLO we got
851  */
852 static void
853 consider_for_advertising (const struct GNUNET_HELLO_Message *hello)
854 {
855   int have_address;
856   struct GNUNET_PeerIdentity pid;
857   struct GNUNET_TIME_Absolute dt;
858   struct GNUNET_HELLO_Message *nh;
859   struct Peer *peer;
860   uint16_t size;
861
862   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
863   {
864     GNUNET_break (0);
865     return;
866   }
867   if (0 == memcmp (&pid, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
868     return;                     /* that's me! */
869   have_address = GNUNET_NO;
870   GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &address_iterator,
871                                   &have_address);
872   if (GNUNET_NO == have_address)
873     return;                     /* no point in advertising this one... */
874   peer = GNUNET_CONTAINER_multihashmap_get (peers, &pid.hashPubKey);
875   if (NULL == peer)
876   {
877     peer = make_peer (&pid, hello, GNUNET_NO);
878   }
879   else if (peer->hello != NULL)
880   {
881     dt = GNUNET_HELLO_equals (peer->hello, hello, GNUNET_TIME_absolute_get ());
882     if (dt.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
883       return;                   /* nothing new here */
884   }
885   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
886               "Found `%s' from peer `%s' for advertising\n", "HELLO",
887               GNUNET_i2s (&pid));
888   if (peer->hello != NULL)
889   {
890     nh = GNUNET_HELLO_merge (peer->hello, hello);
891     GNUNET_free (peer->hello);
892     peer->hello = nh;
893   }
894   else
895   {
896     size = GNUNET_HELLO_size (hello);
897     peer->hello = GNUNET_malloc (size);
898     memcpy (peer->hello, hello, size);
899   }
900   if (peer->filter != NULL)
901     GNUNET_CONTAINER_bloomfilter_free (peer->filter);
902   setup_filter (peer);
903   /* since we have a new HELLO to pick from, re-schedule all
904    * HELLO requests that are not bound by the HELLO send rate! */
905   GNUNET_CONTAINER_multihashmap_iterate (peers, &reschedule_hellos, peer);
906 }
907
908
909 /**
910  * PEERINFO calls this function to let us know about a possible peer
911  * that we might want to connect to.
912  *
913  * @param cls closure (not used)
914  * @param peer potential peer to connect to
915  * @param hello HELLO for this peer (or NULL)
916  * @param err_msg NULL if successful, otherwise contains error message
917  */
918 static void
919 process_peer (void *cls, const struct GNUNET_PeerIdentity *peer,
920               const struct GNUNET_HELLO_Message *hello, const char *err_msg)
921 {
922   struct Peer *pos;
923
924   if (err_msg != NULL)
925   {
926     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
927                 _("Error in communication with PEERINFO service: %s\n"),
928                 err_msg);
929     GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
930     peerinfo_notify = GNUNET_PEERINFO_notify (cfg, &process_peer, NULL);
931     return;
932   }
933   GNUNET_assert (peer != NULL);
934   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
935     return;                     /* that's me! */
936   if (hello == NULL)
937   {
938     /* free existing HELLO, if any */
939     pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
940     if (NULL != pos)
941     {
942       GNUNET_free_non_null (pos->hello);
943       pos->hello = NULL;
944       if (pos->filter != NULL)
945       {
946         GNUNET_CONTAINER_bloomfilter_free (pos->filter);
947         pos->filter = NULL;
948       }
949       if ((GNUNET_NO == pos->is_connected) && (GNUNET_NO == pos->is_friend) &&
950           (0 ==
951            GNUNET_TIME_absolute_get_remaining (pos->
952                                                greylisted_until).rel_value))
953         free_peer (NULL, &pos->pid.hashPubKey, pos);
954     }
955     return;
956   }
957   consider_for_advertising (hello);
958   pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
959   if (pos == NULL)
960     pos = make_peer (peer, hello, GNUNET_NO);
961   GNUNET_assert (NULL != pos);
962   if (GNUNET_YES == pos->is_connected)
963   {
964     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Already connected to peer `%s'\n",
965                 GNUNET_i2s (peer));
966     return;
967   }
968   if (GNUNET_TIME_absolute_get_remaining (pos->greylisted_until).rel_value > 0)
969   {
970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Already tried peer `%s' recently\n",
971                 GNUNET_i2s (peer));
972     return;                     /* peer still greylisted */
973   }
974   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Considering connecting to peer `%s'\n",
975               GNUNET_i2s (peer));
976   schedule_attempt_connect (pos);
977 }
978
979
980 /**
981  * Function called after GNUNET_CORE_connect has succeeded
982  * (or failed for good).
983  *
984  * @param cls closure
985  * @param server handle to the server, NULL if we failed
986  * @param my_id ID of this peer, NULL if we failed
987  */
988 static void
989 core_init (void *cls, struct GNUNET_CORE_Handle *server,
990            const struct GNUNET_PeerIdentity *my_id)
991 {
992   if (server == NULL)
993   {
994     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
995                 _
996                 ("Failed to connect to core service, can not manage topology!\n"));
997     GNUNET_SCHEDULER_shutdown ();
998     return;
999   }
1000   handle = server;
1001   my_identity = *my_id;
1002   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "I am peer `%s'\n", GNUNET_i2s (my_id));
1003   peerinfo_notify = GNUNET_PEERINFO_notify (cfg, &process_peer, NULL);
1004 }
1005
1006
1007 /**
1008  * Read the friends file.
1009  */
1010 static void
1011 read_friends_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1012 {
1013   char *fn;
1014   char *data;
1015   size_t pos;
1016   struct GNUNET_PeerIdentity pid;
1017   uint64_t fsize;
1018   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1019   unsigned int entries_found;
1020   struct Peer *fl;
1021
1022   if (GNUNET_OK !=
1023       GNUNET_CONFIGURATION_get_value_filename (cfg, "TOPOLOGY", "FRIENDS", &fn))
1024   {
1025     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1026                 _("Option `%s' in section `%s' not specified!\n"), "FRIENDS",
1027                 "TOPOLOGY");
1028     return;
1029   }
1030   if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1031     GNUNET_DISK_fn_write (fn, NULL, 0,
1032                           GNUNET_DISK_PERM_USER_READ |
1033                           GNUNET_DISK_PERM_USER_WRITE);
1034   if (GNUNET_OK != GNUNET_DISK_file_size (fn,
1035       &fsize, GNUNET_NO, GNUNET_YES))
1036   {
1037     if ((friends_only) || (minimum_friend_count > 0))
1038       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1039                   _("Could not read friends list `%s'\n"), fn);
1040     GNUNET_free (fn);
1041     return;
1042   }
1043   if (fsize == 0)
1044   {
1045     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Friends file `%s' is empty.\n"),
1046                 fn);
1047     GNUNET_free (fn);
1048     return;
1049   }
1050   data = GNUNET_malloc_large (fsize);
1051   if (data == NULL)
1052   {
1053     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1054                 _("Failed to read friends list from `%s': out of memory\n"),
1055                 fn);
1056     GNUNET_free (fn);
1057     return;
1058   }
1059   if (fsize != GNUNET_DISK_fn_read (fn, data, fsize))
1060   {
1061     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1062                 _("Failed to read friends list from `%s'\n"), fn);
1063     GNUNET_free (fn);
1064     GNUNET_free (data);
1065     return;
1066   }
1067   entries_found = 0;
1068   pos = 0;
1069   while ((pos < fsize) && isspace ((unsigned char) data[pos]))
1070     pos++;
1071   while ((fsize >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1072          (pos <=
1073           fsize - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1074   {
1075     memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1076     if (!isspace
1077         ((unsigned char)
1078          enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1079     {
1080       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1081                   _
1082                   ("Syntax error in topology specification at offset %llu, skipping bytes.\n"),
1083                   (unsigned long long) pos);
1084       pos++;
1085       while ((pos < fsize) && (!isspace ((unsigned char) data[pos])))
1086         pos++;
1087       continue;
1088     }
1089     enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1090     if (GNUNET_OK !=
1091         GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1092     {
1093       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1094                   _
1095                   ("Syntax error in topology specification at offset %llu, skipping bytes `%s'.\n"),
1096                   (unsigned long long) pos, &enc);
1097     }
1098     else
1099     {
1100       if (0 != memcmp (&pid, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
1101       {
1102         entries_found++;
1103         fl = make_peer (&pid, NULL, GNUNET_YES);
1104         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1105                     _("Found friend `%s' in configuration\n"),
1106                     GNUNET_i2s (&fl->pid));
1107       }
1108       else
1109       {
1110         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1111                     _("Found myself `%s' in friend list (useless, ignored)\n"),
1112                     GNUNET_i2s (&pid));
1113       }
1114     }
1115     pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1116     while ((pos < fsize) && isspace ((unsigned char) data[pos]))
1117       pos++;
1118   }
1119   GNUNET_free (data);
1120   GNUNET_free (fn);
1121   GNUNET_STATISTICS_update (stats, gettext_noop ("# friends in configuration"),
1122                             entries_found, GNUNET_NO);
1123   if ((minimum_friend_count > entries_found) && (friends_only == GNUNET_NO))
1124   {
1125     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1126                 _
1127                 ("Fewer friends specified than required by minimum friend count. Will only connect to friends.\n"));
1128   }
1129   if ((minimum_friend_count > target_connection_count) &&
1130       (friends_only == GNUNET_NO))
1131   {
1132     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1133                 _
1134                 ("More friendly connections required than target total number of connections.\n"));
1135   }
1136 }
1137
1138
1139 /**
1140  * This function is called whenever an encrypted HELLO message is
1141  * received.
1142  *
1143  * @param cls closure
1144  * @param other the other peer involved (sender or receiver, NULL
1145  *        for loopback messages where we are both sender and receiver)
1146  * @param message the actual HELLO message
1147  * @param atsi performance data
1148  * @param atsi_count number of records in 'atsi'
1149  * @return GNUNET_OK to keep the connection open,
1150  *         GNUNET_SYSERR to close it (signal serious error)
1151  */
1152 static int
1153 handle_encrypted_hello (void *cls, const struct GNUNET_PeerIdentity *other,
1154                         const struct GNUNET_MessageHeader *message,
1155                         const struct GNUNET_ATS_Information *atsi,
1156                         unsigned int atsi_count)
1157 {
1158   struct Peer *peer;
1159   struct GNUNET_PeerIdentity pid;
1160
1161   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received encrypted `%s' from peer `%s'",
1162               "HELLO", GNUNET_i2s (other));
1163   if (GNUNET_OK !=
1164       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) message, &pid))
1165   {
1166     GNUNET_break_op (0);
1167     return GNUNET_SYSERR;
1168   }
1169   GNUNET_STATISTICS_update (stats, gettext_noop ("# HELLO messages received"),
1170                             1, GNUNET_NO);
1171   peer = GNUNET_CONTAINER_multihashmap_get (peers, &pid.hashPubKey);
1172   if (NULL == peer)
1173   {
1174     if ((GNUNET_YES == friends_only) || (friend_count < minimum_friend_count))
1175       return GNUNET_OK;
1176   }
1177   else
1178   {
1179     if ((GNUNET_YES != peer->is_friend) && (GNUNET_YES == friends_only))
1180       return GNUNET_OK;
1181     if ((GNUNET_YES != peer->is_friend) &&
1182         (friend_count < minimum_friend_count))
1183       return GNUNET_OK;
1184   }
1185   if (transport != NULL)
1186     GNUNET_TRANSPORT_offer_hello (transport, message, NULL, NULL);
1187   return GNUNET_OK;
1188 }
1189
1190
1191 /**
1192  * Function to fill send buffer with HELLO.
1193  *
1194  * @param cls 'struct Peer' of the target peer
1195  * @param size number of bytes available in buf
1196  * @param buf where the callee should write the message
1197  * @return number of bytes written to buf
1198  */
1199 static size_t
1200 hello_advertising_ready (void *cls, size_t size, void *buf)
1201 {
1202   struct Peer *pl = cls;
1203   struct FindAdvHelloContext fah;
1204   size_t want;
1205
1206   pl->hello_req = NULL;
1207   GNUNET_assert (GNUNET_YES == pl->is_connected);
1208   /* find applicable HELLOs */
1209   fah.peer = pl;
1210   fah.result = NULL;
1211   fah.max_size = size;
1212   fah.next_adv = GNUNET_TIME_UNIT_FOREVER_REL;
1213   GNUNET_CONTAINER_multihashmap_iterate (peers, &find_advertisable_hello, &fah);
1214   want = 0;
1215   if (fah.result != NULL)
1216   {
1217     want = GNUNET_HELLO_size (fah.result->hello);
1218     GNUNET_assert (want <= size);
1219     memcpy (buf, fah.result->hello, want);
1220     GNUNET_CONTAINER_bloomfilter_add (fah.result->filter, &pl->pid.hashPubKey);
1221     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' with %u bytes", "HELLO",
1222                 (unsigned int) want);
1223     GNUNET_STATISTICS_update (stats,
1224                               gettext_noop ("# HELLO messages gossipped"), 1,
1225                               GNUNET_NO);
1226   }
1227
1228   if (pl->hello_delay_task != GNUNET_SCHEDULER_NO_TASK)
1229     GNUNET_SCHEDULER_cancel (pl->hello_delay_task);
1230   pl->next_hello_allowed =
1231       GNUNET_TIME_relative_to_absolute (HELLO_ADVERTISEMENT_MIN_FREQUENCY);
1232   pl->hello_delay_task = GNUNET_SCHEDULER_add_now (&schedule_next_hello, pl);
1233   return want;
1234 }
1235
1236
1237 /**
1238  * Last task run during shutdown.  Disconnects us from
1239  * the transport and core.
1240  *
1241  * @param cls unused, NULL
1242  * @param tc scheduler context
1243  */
1244 static void
1245 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1246 {
1247   if (NULL != peerinfo_notify)
1248   {
1249     GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
1250     peerinfo_notify = NULL;
1251   }
1252   GNUNET_TRANSPORT_disconnect (transport);
1253   transport = NULL;
1254   if (handle != NULL)
1255   {
1256     GNUNET_CORE_disconnect (handle);
1257     handle = NULL;
1258   }
1259   whitelist_peers ();
1260   if (GNUNET_SCHEDULER_NO_TASK != add_task)
1261   {
1262     GNUNET_SCHEDULER_cancel (add_task);
1263     add_task = GNUNET_SCHEDULER_NO_TASK;
1264   }
1265   GNUNET_CONTAINER_multihashmap_iterate (peers, &free_peer, NULL);
1266   GNUNET_CONTAINER_multihashmap_destroy (peers);
1267   peers = NULL;
1268   if (stats != NULL)
1269   {
1270     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1271     stats = NULL;
1272   }
1273 }
1274
1275
1276 /**
1277  * Main function that will be run.
1278  *
1279  * @param cls closure
1280  * @param args remaining command-line arguments
1281  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1282  * @param c configuration
1283  */
1284 static void
1285 run (void *cls, char *const *args, const char *cfgfile,
1286      const struct GNUNET_CONFIGURATION_Handle *c)
1287 {
1288   static struct GNUNET_CORE_MessageHandler handlers[] = {
1289     {&handle_encrypted_hello, GNUNET_MESSAGE_TYPE_HELLO, 0},
1290     {NULL, 0, 0}
1291   };
1292   unsigned long long opt;
1293
1294   cfg = c;
1295   stats = GNUNET_STATISTICS_create ("topology", cfg);
1296   autoconnect =
1297       GNUNET_CONFIGURATION_get_value_yesno (cfg, "TOPOLOGY", "AUTOCONNECT");
1298   friends_only =
1299       GNUNET_CONFIGURATION_get_value_yesno (cfg, "TOPOLOGY", "FRIENDS-ONLY");
1300   if (GNUNET_OK !=
1301       GNUNET_CONFIGURATION_get_value_number (cfg, "TOPOLOGY", "MINIMUM-FRIENDS",
1302                                              &opt))
1303     opt = 0;
1304   minimum_friend_count = (unsigned int) opt;
1305   if (GNUNET_OK !=
1306       GNUNET_CONFIGURATION_get_value_number (cfg, "TOPOLOGY",
1307                                              "TARGET-CONNECTION-COUNT", &opt))
1308     opt = 16;
1309   target_connection_count = (unsigned int) opt;
1310   peers = GNUNET_CONTAINER_multihashmap_create (target_connection_count * 2);
1311
1312   if ((friends_only == GNUNET_YES) || (minimum_friend_count > 0))
1313     read_friends_file (cfg);
1314   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1315               "Topology would like %u connections with at least %u friends (%s)\n",
1316               target_connection_count, minimum_friend_count,
1317               autoconnect ? "autoconnect enabled" : "autoconnect disabled");
1318   if ((friend_count < minimum_friend_count) && (blacklist == NULL))
1319     blacklist = GNUNET_TRANSPORT_blacklist (cfg, &blacklist_check, NULL);
1320   transport = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL, NULL, NULL);
1321   handle =
1322       GNUNET_CORE_connect (cfg, NULL, &core_init, &connect_notify,
1323                            &disconnect_notify, NULL, GNUNET_NO, NULL, GNUNET_NO,
1324                            handlers);
1325   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleaning_task,
1326                                 NULL);
1327   if (NULL == transport)
1328   {
1329     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1330                 _("Failed to connect to `%s' service.\n"), "transport");
1331     GNUNET_SCHEDULER_shutdown ();
1332     return;
1333   }
1334   if (NULL == handle)
1335   {
1336     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1337                 _("Failed to connect to `%s' service.\n"), "core");
1338     GNUNET_SCHEDULER_shutdown ();
1339     return;
1340   }
1341 }
1342
1343
1344 /**
1345  * The main function for the topology daemon.
1346  *
1347  * @param argc number of arguments from the command line
1348  * @param argv command line arguments
1349  * @return 0 ok, 1 on error
1350  */
1351 int
1352 main (int argc, char *const *argv)
1353 {
1354   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1355     GNUNET_GETOPT_OPTION_END
1356   };
1357   int ret;
1358
1359   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1360     return 2;
1361
1362   ret =
1363       (GNUNET_OK ==
1364        GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-topology",
1365                            _
1366                            ("GNUnet topology control (maintaining P2P mesh and F2F constraints)"),
1367                            options, &run, NULL)) ? 0 : 1;
1368   return ret;
1369 }
1370
1371 /* end of gnunet-daemon-topology.c */