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