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