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