fix
[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_init (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   GNUNET_assert (GNUNET_YES == pl->is_connected);    
619   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
620     return; /* we're out of here */
621   if (pl->hello_req != NULL)
622     return; /* did not finish sending the previous one */
623   /* find applicable HELLOs */
624   fah.peer = pl;
625   fah.result = NULL;
626   fah.max_size = GNUNET_SERVER_MAX_MESSAGE_SIZE - 1;
627   fah.next_adv = GNUNET_TIME_UNIT_FOREVER_REL;
628   GNUNET_CONTAINER_multihashmap_iterate (peers,
629                                          &find_advertisable_hello,
630                                          &fah);
631   pl->hello_delay_task 
632     = GNUNET_SCHEDULER_add_delayed (fah.next_adv,
633                                     &schedule_next_hello,
634                                     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 = GNUNET_CORE_notify_transmit_ready (handle, 
643                                                          GNUNET_YES,
644                                                          0,
645                                                          GNUNET_CONSTANTS_SERVICE_TIMEOUT,
646                                                          &pl->pid,
647                                                          next_want,
648                                                          &hello_advertising_ready,
649                                                          pl);
650     }
651 }
652
653
654 /**
655  * Cancel existing requests for sending HELLOs to this peer
656  * and recalculate when we should send HELLOs to it based
657  * on our current state (something changed!).
658  *
659  * @param cls closure, 'struct Peer' to skip, or NULL
660  * @param pid identity of a peer
661  * @param value 'struct Peer*' for the peer
662  * @return GNUNET_YES (always)
663  */
664 static int
665 reschedule_hellos (void *cls,
666                    const GNUNET_HashCode *pid,
667                    void *value)
668 {
669   struct Peer *peer = value;
670   struct Peer *skip = cls;
671
672   if (skip == peer)
673     return GNUNET_YES;
674   if (! peer->is_connected) 
675     return GNUNET_YES;
676   if (peer->hello_req != NULL)
677     {
678       GNUNET_CORE_notify_transmit_ready_cancel (peer->hello_req);
679       peer->hello_req = NULL;
680     }
681   if (peer->hello_delay_task != GNUNET_SCHEDULER_NO_TASK)
682     {
683       GNUNET_SCHEDULER_cancel (peer->hello_delay_task);
684       peer->hello_delay_task = GNUNET_SCHEDULER_NO_TASK;
685     }
686   peer->hello_delay_task 
687     = GNUNET_SCHEDULER_add_now (&schedule_next_hello,
688                                 peer);
689   return GNUNET_YES;
690 }
691
692
693 /**
694  * Method called whenever a peer connects.
695  *
696  * @param cls closure
697  * @param peer peer identity this notification is about
698  * @param atsi performance data
699  */
700 static void 
701 connect_notify (void *cls,
702                 const struct
703                 GNUNET_PeerIdentity * peer,
704                 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
705 {
706   struct Peer *pos;
707
708 #if DEBUG_TOPOLOGY
709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
710               "Core told us that we are connecting to `%s'\n",
711               GNUNET_i2s (peer));
712 #endif
713   if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
714     return;
715
716   connection_count++;
717   GNUNET_STATISTICS_set (stats,
718                          gettext_noop ("# peers connected"),
719                          connection_count,
720                          GNUNET_NO);
721   pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
722   if (pos == NULL)    
723     {
724       pos = make_peer (peer, NULL, GNUNET_NO);
725       GNUNET_break (GNUNET_OK == is_connection_allowed (pos));
726     }
727   else
728     {
729       GNUNET_assert (GNUNET_NO == pos->is_connected);
730       pos->greylisted_until.abs_value = 0; /* remove greylisting */
731     }
732   pos->is_connected = GNUNET_YES;
733   pos->connect_attempts = 0; /* re-set back-off factor */
734   if (pos->is_friend)
735     {
736       if ( (friend_count == minimum_friend_count - 1) &&
737            (GNUNET_YES != friends_only) )       
738         whitelist_peers ();       
739       friend_count++;
740       GNUNET_STATISTICS_set (stats,
741                              gettext_noop ("# friends connected"),
742                              friend_count,
743                              GNUNET_NO);
744     }
745   reschedule_hellos (NULL, &peer->hashPubKey, pos);
746 }
747
748
749 /**
750  * Try to add more peers to our connection set.
751  *
752  * @param cls closure, not used
753  * @param pid identity of a peer
754  * @param value 'struct Peer*' for the peer
755  * @return GNUNET_YES (continue to iterate)
756  */
757 static int
758 try_add_peers (void *cls,
759                const GNUNET_HashCode *pid,
760                void *value)
761 {
762   struct Peer *pos = value;
763
764   attempt_connect (pos);
765   return GNUNET_YES;
766 }
767
768
769 /**
770  * Last task run during shutdown.  Disconnects us from
771  * the transport and core.
772  *
773  * @param cls unused, NULL
774  * @param tc scheduler context
775  */
776 static void
777 add_peer_task (void *cls, 
778                const struct GNUNET_SCHEDULER_TaskContext *tc)
779 {
780   add_task = GNUNET_SCHEDULER_NO_TASK;
781
782   GNUNET_CONTAINER_multihashmap_iterate (peers,
783                                          &try_add_peers,
784                                          NULL);
785 }
786
787 /**
788  * Method called whenever a peer disconnects.
789  *
790  * @param cls closure
791  * @param peer peer identity this notification is about
792  */
793 static void 
794 disconnect_notify (void *cls,
795                    const struct
796                    GNUNET_PeerIdentity * peer)
797 {
798   struct Peer *pos;
799
800   if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
801     return;
802 #if DEBUG_TOPOLOGY
803   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
804               "Core told us that we disconnected from `%s'\n",
805               GNUNET_i2s (peer));
806 #endif       
807   pos = GNUNET_CONTAINER_multihashmap_get (peers,
808                                            &peer->hashPubKey);
809   if (pos == NULL)
810     {
811       GNUNET_break (0);
812       return;
813     }
814   if (pos->is_connected != GNUNET_YES)
815     {
816       GNUNET_break (0);
817       return;
818     }
819   pos->is_connected = GNUNET_NO;
820   connection_count--;
821   if (NULL != pos->hello_req)
822     {
823       GNUNET_CORE_notify_transmit_ready_cancel (pos->hello_req);
824       pos->hello_req = NULL;
825     }
826   if (GNUNET_SCHEDULER_NO_TASK != pos->hello_delay_task)
827     {
828       GNUNET_SCHEDULER_cancel (pos->hello_delay_task);
829       pos->hello_delay_task = GNUNET_SCHEDULER_NO_TASK;
830     }
831   GNUNET_STATISTICS_set (stats,
832                          gettext_noop ("# peers connected"),
833                          connection_count,
834                          GNUNET_NO);
835   if (pos->is_friend)
836     {
837       friend_count--; 
838       GNUNET_STATISTICS_set (stats,
839                              gettext_noop ("# friends connected"),
840                              friend_count,
841                              GNUNET_NO);
842     }
843   if ( ( (connection_count < target_connection_count) ||
844          (friend_count < minimum_friend_count) ) &&
845        (GNUNET_SCHEDULER_NO_TASK == add_task) )
846     add_task = GNUNET_SCHEDULER_add_now (&add_peer_task, NULL);
847   if ( (friend_count < minimum_friend_count) &&
848        (blacklist == NULL) )
849     blacklist = GNUNET_TRANSPORT_blacklist (cfg,
850                                             &blacklist_check, NULL);
851 }
852
853
854 /**
855  * Iterator called on each address.
856  *
857  * @param cls flag that we will set if we see any addresses
858  * @param tname name of the transport
859  * @param expiration when will the given address expire
860  * @param addr the address of the peer
861  * @param addrlen number of bytes in addr
862  * @return GNUNET_SYSERR always, to terminate iteration
863  */
864 static int
865 address_iterator (void *cls,
866                   const char *tname,
867                   struct GNUNET_TIME_Absolute expiration,
868                   const void *addr, 
869                   uint16_t addrlen)
870 {
871   int *flag = cls;
872   *flag = GNUNET_YES;
873   return GNUNET_SYSERR;
874 }
875
876
877 /**
878  * We've gotten a HELLO from another peer.  Consider it for
879  * advertising.
880  *
881  * @param hello the HELLO we got
882  */
883 static void
884 consider_for_advertising (const struct GNUNET_HELLO_Message *hello)
885 {
886   int have_address;
887   struct GNUNET_PeerIdentity pid;
888   struct GNUNET_TIME_Absolute dt;
889   struct GNUNET_HELLO_Message *nh;
890   struct Peer *peer;
891   uint16_t size;
892
893   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
894     {
895         GNUNET_break (0);
896         return;
897     }
898   if (0 == memcmp (&pid,
899                    &my_identity,
900                    sizeof (struct GNUNET_PeerIdentity)))
901     return; /* that's me! */
902   have_address = GNUNET_NO;
903   GNUNET_HELLO_iterate_addresses (hello,
904                                   GNUNET_NO,
905                                   &address_iterator,
906                                   &have_address);
907   if (GNUNET_NO == have_address)
908     return; /* no point in advertising this one... */
909   peer = GNUNET_CONTAINER_multihashmap_get (peers,
910                                             &pid.hashPubKey);
911   if (peer == NULL)
912     {
913       peer = make_peer (&pid, hello, GNUNET_NO);
914     }
915   else if (peer->hello != NULL)
916     {
917       dt = GNUNET_HELLO_equals (peer->hello,
918                                 hello,
919                                 GNUNET_TIME_absolute_get());
920       if (dt.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
921         return; /* nothing new here */
922     }
923 #if DEBUG_TOPOLOGY
924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
925               "Found `%s' from peer `%s' for advertising\n",
926               "HELLO",
927               GNUNET_i2s (&pid));
928 #endif 
929   if (peer->hello != NULL)
930     {
931       nh = GNUNET_HELLO_merge (peer->hello,
932                                hello);
933       GNUNET_free (peer->hello);
934       peer->hello = nh;
935     }
936   else
937     {
938       size = GNUNET_HELLO_size (hello);
939       peer->hello = GNUNET_malloc (size);
940       memcpy (peer->hello, hello, size);
941     }
942   if (peer->filter != NULL)
943     GNUNET_CONTAINER_bloomfilter_free (peer->filter);
944   setup_filter (peer);
945   /* since we have a new HELLO to pick from, re-schedule all
946      HELLO requests that are not bound by the HELLO send rate! */
947   GNUNET_CONTAINER_multihashmap_iterate (peers,
948                                          &reschedule_hellos,
949                                          peer);
950 }
951
952
953 /**
954  * PEERINFO calls this function to let us know about a possible peer
955  * that we might want to connect to.
956  *
957  * @param cls closure (not used)
958  * @param peer potential peer to connect to
959  * @param hello HELLO for this peer (or NULL)
960  * @param err_msg NULL if successful, otherwise contains error message
961  */
962 static void
963 process_peer (void *cls,
964               const struct GNUNET_PeerIdentity *peer,
965               const struct GNUNET_HELLO_Message *hello,
966               const char *err_msg)
967 {
968   struct Peer *pos;
969
970   if (err_msg != NULL)
971     {
972       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
973                   _("Error in communication with PEERINFO service: %s\n"),
974                   err_msg);
975       GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
976       peerinfo_notify = GNUNET_PEERINFO_notify (cfg, &process_peer,
977                                                 NULL);
978       return;
979     }
980   GNUNET_assert (peer != NULL);
981   if (0 == memcmp (&my_identity,
982                    peer, sizeof (struct GNUNET_PeerIdentity)))
983     return;  /* that's me! */
984   if (hello == NULL)
985     {
986       /* free existing HELLO, if any */
987       pos = GNUNET_CONTAINER_multihashmap_get (peers,
988                                                &peer->hashPubKey);
989       if (NULL != pos)
990         {
991           GNUNET_free_non_null (pos->hello);
992           pos->hello = NULL;
993           if (pos->filter != NULL)
994             {
995               GNUNET_CONTAINER_bloomfilter_free (pos->filter);
996               pos->filter = NULL;
997             }
998           if ( (! pos->is_connected) &&
999                (! pos->is_friend) &&
1000                (0 == GNUNET_TIME_absolute_get_remaining (pos->greylisted_until).rel_value) )
1001             free_peer (NULL, &pos->pid.hashPubKey, pos);
1002         }
1003       return;
1004     }
1005   consider_for_advertising (hello);
1006   pos = GNUNET_CONTAINER_multihashmap_get (peers,
1007                                            &peer->hashPubKey);
1008   if (pos == NULL)
1009     pos = make_peer (peer, hello, GNUNET_NO);
1010   GNUNET_assert (NULL != pos);
1011   if (GNUNET_YES == pos->is_connected)
1012     {
1013 #if DEBUG_TOPOLOGY
1014       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1015                   "Already connected to peer `%s'\n",
1016                   GNUNET_i2s (peer));
1017 #endif 
1018       return;
1019     }
1020   if (GNUNET_TIME_absolute_get_remaining (pos->greylisted_until).rel_value > 0)
1021     {
1022 #if DEBUG_TOPOLOGY
1023       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1024                   "Already tried peer `%s' recently\n",
1025                   GNUNET_i2s (peer));
1026 #endif 
1027       return; /* peer still greylisted */
1028     }
1029 #if DEBUG_TOPOLOGY
1030   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1031               "Considering connecting to peer `%s'\n",
1032               GNUNET_i2s (peer));
1033 #endif 
1034   attempt_connect (pos);
1035 }
1036
1037
1038 /**
1039  * Function called after GNUNET_CORE_connect has succeeded
1040  * (or failed for good).
1041  *
1042  * @param cls closure
1043  * @param server handle to the server, NULL if we failed
1044  * @param my_id ID of this peer, NULL if we failed
1045  * @param publicKey public key of this peer, NULL if we failed
1046  */
1047 static void
1048 core_init (void *cls,
1049            struct GNUNET_CORE_Handle * server,
1050            const struct GNUNET_PeerIdentity *
1051            my_id,
1052            const struct
1053            GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
1054            publicKey)
1055 {
1056   if (server == NULL)
1057     {
1058       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1059                   _("Failed to connect to core service, can not manage topology!\n"));
1060       GNUNET_SCHEDULER_shutdown ();
1061       return;
1062     }
1063   handle = server;
1064   my_identity = *my_id;
1065 #if DEBUG_TOPOLOGY
1066   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1067               "I am peer `%s'\n",
1068               GNUNET_i2s (my_id));
1069 #endif  
1070   peerinfo_notify = GNUNET_PEERINFO_notify (cfg, &process_peer,
1071                                             NULL);
1072 }
1073
1074
1075 /**
1076  * Read the friends file.
1077  */
1078 static void
1079 read_friends_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1080 {
1081   char *fn;
1082   char *data;
1083   size_t pos;
1084   struct GNUNET_PeerIdentity pid;
1085   struct stat frstat;
1086   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1087   unsigned int entries_found;
1088   struct Peer *fl;
1089
1090   if (GNUNET_OK !=
1091       GNUNET_CONFIGURATION_get_value_filename (cfg,
1092                                                "TOPOLOGY",
1093                                                "FRIENDS",
1094                                                &fn))
1095     {
1096       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1097                   _("Option `%s' in section `%s' not specified!\n"),
1098                   "FRIENDS",
1099                   "TOPOLOGY");
1100       return;
1101     }
1102   if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1103     GNUNET_DISK_fn_write (fn, NULL, 0, 
1104                           GNUNET_DISK_PERM_USER_READ
1105                           | GNUNET_DISK_PERM_USER_WRITE);
1106   if (0 != STAT (fn, &frstat))
1107     {
1108       if ((friends_only) || (minimum_friend_count > 0))
1109         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1110                     _("Could not read friends list `%s'\n"), fn);
1111       GNUNET_free (fn);
1112       return;
1113     }
1114   if (frstat.st_size == 0)
1115     {
1116       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1117                   _("Friends file `%s' is empty.\n"),
1118                   fn);
1119       GNUNET_free (fn);
1120       return;
1121     }
1122   data = GNUNET_malloc_large (frstat.st_size);
1123   if (data == NULL)
1124     {
1125       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1126                   _("Failed to read friends list from `%s': out of memory\n"), fn);
1127       GNUNET_free (fn);
1128       return;
1129     }
1130   if (frstat.st_size !=
1131       GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1132     {
1133       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1134                   _("Failed to read friends list from `%s'\n"), fn);
1135       GNUNET_free (fn);
1136       GNUNET_free (data);
1137       return;
1138     }
1139   entries_found = 0;
1140   pos = 0;
1141   while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1142     pos++;
1143   while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1144          (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1145     {
1146       memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1147       if (!isspace ( (unsigned char) enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1148         {
1149           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1150                       _("Syntax error in topology specification at offset %llu, skipping bytes.\n"),
1151                       (unsigned long long) pos);
1152           pos++;
1153           while ((pos < frstat.st_size) && (!isspace ( (unsigned char) data[pos])))
1154             pos++;
1155           continue;
1156         }
1157       enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1158       if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1159         {
1160           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1161                       _("Syntax error in topology specification at offset %llu, skipping bytes `%s'.\n"),
1162                       (unsigned long long) pos,
1163                       &enc);
1164         }
1165       else
1166         {
1167           if (0 != memcmp (&pid,
1168                            &my_identity,
1169                            sizeof (struct GNUNET_PeerIdentity)))
1170             {
1171               entries_found++;
1172               fl = make_peer (&pid,
1173                               NULL,
1174                               GNUNET_YES);
1175               GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1176                           _("Found friend `%s' in configuration\n"),
1177                           GNUNET_i2s (&fl->pid));
1178             }
1179           else
1180             {
1181               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1182                           _("Found myself `%s' in friend list (useless, ignored)\n"),
1183                           GNUNET_i2s (&pid));
1184             }
1185         }
1186       pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1187       while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1188         pos++;
1189     }
1190   GNUNET_free (data);
1191   GNUNET_free (fn);
1192   GNUNET_STATISTICS_update (stats,
1193                             gettext_noop ("# friends in configuration"),
1194                             entries_found,
1195                             GNUNET_NO);
1196   if ( (minimum_friend_count > entries_found) &&
1197        (friends_only == GNUNET_NO) )
1198     {
1199       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1200                   _("Fewer friends specified than required by minimum friend count. Will only connect to friends.\n"));
1201     }
1202   if ( (minimum_friend_count > target_connection_count) &&
1203        (friends_only == GNUNET_NO) )
1204     {
1205       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1206                   _("More friendly connections required than target total number of connections.\n"));
1207     }
1208 }
1209
1210
1211 /**
1212  * This function is called whenever an encrypted HELLO message is
1213  * received.
1214  *
1215  * @param cls closure
1216  * @param other the other peer involved (sender or receiver, NULL
1217  *        for loopback messages where we are both sender and receiver)
1218  * @param message the actual HELLO message
1219  * @param atsi performance data
1220  * @return GNUNET_OK to keep the connection open,
1221  *         GNUNET_SYSERR to close it (signal serious error)
1222  */
1223 static int
1224 handle_encrypted_hello (void *cls,
1225                         const struct GNUNET_PeerIdentity * other,
1226                         const struct GNUNET_MessageHeader *
1227                         message,
1228                         const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1229 {
1230   struct Peer *peer;
1231   struct GNUNET_PeerIdentity pid;
1232
1233 #if DEBUG_TOPOLOGY
1234   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1235               "Received encrypted `%s' from peer `%s'",
1236               "HELLO",
1237               GNUNET_i2s (other));
1238 #endif  
1239   if (GNUNET_OK !=
1240       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) message,
1241                            &pid))
1242     {
1243       GNUNET_break_op (0);
1244       return GNUNET_SYSERR;
1245     }
1246   GNUNET_STATISTICS_update (stats,
1247                             gettext_noop ("# HELLO messages received"),
1248                             1,
1249                             GNUNET_NO);
1250   peer = GNUNET_CONTAINER_multihashmap_get (peers,
1251                                             &pid.hashPubKey);
1252   if (peer == NULL)
1253     {
1254       if ( (GNUNET_YES == friends_only) ||
1255            (friend_count < minimum_friend_count) )
1256         return GNUNET_OK;      
1257     }
1258   else
1259     {
1260       if ( (GNUNET_YES != peer->is_friend) &&
1261            (GNUNET_YES == friends_only) )
1262         return GNUNET_OK;
1263       if ( (GNUNET_YES != peer->is_friend) &&
1264            (friend_count < minimum_friend_count) )
1265         return GNUNET_OK;      
1266     }
1267   if (transport != NULL)
1268     GNUNET_TRANSPORT_offer_hello (transport,
1269                                   message, NULL, NULL);
1270   return GNUNET_OK;
1271 }
1272
1273
1274 /**
1275  * Function to fill send buffer with HELLO.
1276  *
1277  * @param cls 'struct Peer' of the target peer
1278  * @param size number of bytes available in buf
1279  * @param buf where the callee should write the message
1280  * @return number of bytes written to buf
1281  */
1282 static size_t
1283 hello_advertising_ready (void *cls,
1284                          size_t size,
1285                          void *buf)
1286 {
1287   struct Peer *pl = cls;
1288   struct FindAdvHelloContext fah;
1289   size_t want;
1290
1291   pl->hello_req = NULL;
1292   GNUNET_assert (GNUNET_YES == pl->is_connected);    
1293   /* find applicable HELLOs */
1294   fah.peer = pl;
1295   fah.result = NULL;
1296   fah.max_size = size;
1297   fah.next_adv = GNUNET_TIME_UNIT_FOREVER_REL;
1298   GNUNET_CONTAINER_multihashmap_iterate (peers,
1299                                          &find_advertisable_hello,
1300                                          &fah);
1301   want = 0;
1302   if (fah.result != NULL)
1303     {
1304       want = GNUNET_HELLO_size (fah.result->hello);
1305       GNUNET_assert (want <= size);
1306       memcpy (buf, fah.result->hello, want);
1307       GNUNET_CONTAINER_bloomfilter_add (fah.result->filter,
1308                                         &pl->pid.hashPubKey);
1309 #if DEBUG_TOPOLOGY
1310       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1311                   "Sending `%s' with %u bytes",
1312                   "HELLO",
1313                   (unsigned int) want);
1314 #endif  
1315       GNUNET_STATISTICS_update (stats,
1316                                 gettext_noop ("# HELLO messages gossipped"),
1317                                 1,
1318                                 GNUNET_NO);    
1319     }
1320
1321   if (pl->hello_delay_task != GNUNET_SCHEDULER_NO_TASK)
1322     GNUNET_SCHEDULER_cancel(pl->hello_delay_task);
1323   pl->next_hello_allowed = GNUNET_TIME_relative_to_absolute (HELLO_ADVERTISEMENT_MIN_FREQUENCY);
1324   pl->hello_delay_task
1325     = GNUNET_SCHEDULER_add_now (&schedule_next_hello,
1326                                 pl);
1327   return want;
1328 }
1329
1330
1331 /**
1332  * Last task run during shutdown.  Disconnects us from
1333  * the transport and core.
1334  *
1335  * @param cls unused, NULL
1336  * @param tc scheduler context
1337  */
1338 static void
1339 cleaning_task (void *cls, 
1340                const struct GNUNET_SCHEDULER_TaskContext *tc)
1341 {
1342   if (NULL != peerinfo_notify)
1343     {
1344       GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
1345       peerinfo_notify = NULL;
1346     }
1347   if (GNUNET_SCHEDULER_NO_TASK != add_task)
1348     {
1349       GNUNET_SCHEDULER_cancel (add_task);
1350       add_task = GNUNET_SCHEDULER_NO_TASK;
1351     }
1352   GNUNET_TRANSPORT_disconnect (transport);
1353   transport = NULL;
1354   GNUNET_CONTAINER_multihashmap_iterate (peers,
1355                                          &free_peer,
1356                                          NULL);
1357   GNUNET_CONTAINER_multihashmap_destroy (peers);
1358   if (handle != NULL)
1359     {
1360       GNUNET_CORE_disconnect (handle);
1361       handle = NULL;
1362     }
1363   whitelist_peers ();
1364   if (stats != NULL)
1365     {
1366       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1367       stats = NULL;
1368     }
1369 }
1370
1371
1372 /**
1373  * Main function that will be run.
1374  *
1375  * @param cls closure
1376  * @param args remaining command-line arguments
1377  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1378  * @param c configuration
1379  */
1380 static void
1381 run (void *cls,
1382      char *const *args,
1383      const char *cfgfile,
1384      const struct GNUNET_CONFIGURATION_Handle * c)
1385 {
1386   static struct GNUNET_CORE_MessageHandler handlers[] =
1387     {
1388       { &handle_encrypted_hello, GNUNET_MESSAGE_TYPE_HELLO, 0},
1389       { NULL, 0, 0 }
1390     };
1391   unsigned long long opt;
1392
1393   cfg = c;
1394   stats = GNUNET_STATISTICS_create ("topology", cfg);
1395   autoconnect = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1396                                                       "TOPOLOGY",
1397                                                       "AUTOCONNECT");
1398   friends_only = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1399                                                        "TOPOLOGY",
1400                                                        "FRIENDS-ONLY");
1401   if (GNUNET_OK !=
1402       GNUNET_CONFIGURATION_get_value_number (cfg,
1403                                              "TOPOLOGY",
1404                                              "MINIMUM-FRIENDS",
1405                                              &opt))
1406     opt = 0;
1407   minimum_friend_count = (unsigned int) opt;
1408   if (GNUNET_OK !=
1409       GNUNET_CONFIGURATION_get_value_number (cfg,
1410                                              "TOPOLOGY",
1411                                              "TARGET-CONNECTION-COUNT",
1412                                              &opt))
1413     opt = 16;
1414   target_connection_count = (unsigned int) opt;
1415   peers = GNUNET_CONTAINER_multihashmap_create (target_connection_count * 2);
1416
1417   if ( (friends_only == GNUNET_YES) ||
1418        (minimum_friend_count > 0) )
1419     read_friends_file (cfg);
1420 #if DEBUG_TOPOLOGY
1421   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1422               "Topology would like %u connections with at least %u friends (%s)\n",
1423               target_connection_count,
1424               minimum_friend_count,
1425               autoconnect ? "autoconnect enabled" : "autoconnect disabled");
1426 #endif       
1427   if ( (friend_count < minimum_friend_count) &&
1428        (blacklist == NULL) )
1429     blacklist = GNUNET_TRANSPORT_blacklist (cfg,
1430                                             &blacklist_check, NULL);
1431   transport = GNUNET_TRANSPORT_connect (cfg,
1432                                         NULL,
1433                                         NULL,
1434                                         NULL,
1435                                         NULL,
1436                                         NULL);
1437   handle = GNUNET_CORE_connect (cfg,
1438                                 1,
1439                                 NULL,
1440                                 &core_init,
1441                                 &connect_notify,
1442                                 &disconnect_notify, 
1443                                 NULL,
1444                                 NULL, GNUNET_NO,
1445                                 NULL, GNUNET_NO,
1446                                 handlers);
1447   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1448                                 &cleaning_task, NULL);
1449   if (NULL == transport)
1450     {
1451       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1452                   _("Failed to connect to `%s' service.\n"),
1453                   "transport");
1454       GNUNET_SCHEDULER_shutdown ();
1455       return;
1456     }
1457   if (NULL == handle)
1458     {
1459       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1460                   _("Failed to connect to `%s' service.\n"),
1461                   "core");
1462       GNUNET_SCHEDULER_shutdown ();
1463       return;
1464     }
1465 }
1466
1467
1468 /**
1469  * The main function for the topology daemon.
1470  *
1471  * @param argc number of arguments from the command line
1472  * @param argv command line arguments
1473  * @return 0 ok, 1 on error
1474  */
1475 int
1476 main (int argc, char *const *argv)
1477 {
1478   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1479     GNUNET_GETOPT_OPTION_END
1480   };
1481   int ret;
1482
1483   ret = (GNUNET_OK ==
1484          GNUNET_PROGRAM_run (argc,
1485                              argv,
1486                              "gnunet-daemon-topology",
1487                              _("GNUnet topology control (maintaining P2P mesh and F2F constraints)"),
1488                              options,
1489                              &run, NULL)) ? 0 : 1;
1490   return ret;
1491 }
1492
1493 /* end of gnunet-daemon-topology.c */