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