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