20d541eb2b277d8179789a9364a2820954dfdb5f
[oweals/gnunet.git] / src / topology / gnunet-daemon-topology.c
1 /*
2      This file is part of GNUnet.
3      (C) 2007, 2008, 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file topology/gnunet-daemon-topology.c
23  * @brief code for bootstrapping via topology servers
24  * @author Christian Grothoff
25  */
26
27 #include <stdlib.h>
28 #include "platform.h"
29 #include "gnunet_core_service.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_peerinfo_service.h"
32 #include "gnunet_transport_service.h"
33 #include "gnunet_util_lib.h"
34
35
36 #define DEBUG_TOPOLOGY GNUNET_NO
37
38 /**
39  * For how long do we blacklist a peer after a failed
40  * connection attempt?
41  */
42 #define BLACKLIST_AFTER_ATTEMPT GNUNET_TIME_UNIT_HOURS
43
44 /**
45  * For how long do we blacklist a friend after a failed
46  * connection attempt?
47  */
48 #define BLACKLIST_AFTER_ATTEMPT_FRIEND GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
49
50 /**
51  * How frequently are we allowed to ask PEERINFO for more
52  * HELLO's to advertise (at most)?
53  */
54 #define MIN_HELLO_GATHER_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 27)
55
56 /**
57  * How often do we at most advertise the same HELLO to the same peer?
58  * Also used to remove HELLOs of peers that PEERINFO no longer lists
59  * from our cache.
60  */
61 #define HELLO_ADVERTISEMENT_MIN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
62
63
64 /**
65  * List of neighbours, friends and blacklisted peers.
66  */
67 struct PeerList
68 {
69
70   /**
71    * This is a linked list.
72    */
73   struct PeerList *next;
74
75   /**
76    * Is this peer listed here because he is a friend?
77    */
78   int is_friend;
79
80   /**
81    * Are we connected to this peer right now?
82    */
83   int is_connected;
84
85   /**
86    * Until what time should we not try to connect again
87    * to this peer?
88    */
89   struct GNUNET_TIME_Absolute blacklisted_until;
90
91   /**
92    * Last time we transmitted a HELLO to this peer?
93    */
94   struct GNUNET_TIME_Absolute last_hello_sent;
95
96   /**
97    * ID of the peer.
98    */
99   struct GNUNET_PeerIdentity id;
100
101 };
102
103
104 /**
105  * List of HELLOs we may consider for advertising.
106  */
107 struct HelloList
108 {
109   /**
110    * This is a linked list.
111    */
112   struct HelloList *next;
113
114   /**
115    * Pointer to the HELLO message.  Memory allocated as part
116    * of the "struct HelloList" --- do not free!
117    */
118   struct GNUNET_HELLO_Message *msg;
119
120   /**
121    * Bloom filter used to mark which peers already got
122    * this HELLO.
123    */
124   struct GNUNET_CONTAINER_BloomFilter *filter;
125
126   /**
127    * What peer is this HELLO for?
128    */
129   struct GNUNET_PeerIdentity id;
130
131   /**
132    * When should we remove this entry from the linked list (either
133    * resetting the filter or possibly eliminating it for good because
134    * we no longer consider the peer to be participating in the
135    * network)?
136    */
137   struct GNUNET_TIME_Absolute expiration;
138 };
139
140
141 /**
142  * Linked list of HELLOs for advertising.
143  */
144 static struct HelloList *hellos;
145
146 /**
147  * Our scheduler.
148  */
149 static struct GNUNET_SCHEDULER_Handle * sched;
150
151 /**
152  * Our configuration.
153  */
154 static struct GNUNET_CONFIGURATION_Handle * cfg;
155
156 /**
157  * Handle to the core API.
158  */
159 static struct GNUNET_CORE_Handle *handle;
160
161 /**
162  * Handle to the transport API.
163  */
164 static struct GNUNET_TRANSPORT_Handle *transport;
165
166 /**
167  * Identity of this peer.
168  */
169 static struct GNUNET_PeerIdentity my_identity;
170
171 /**
172  * Linked list of all of our friends and all of our current
173  * neighbours.
174  */
175 static struct PeerList *friends;
176
177 /**
178  * Timestamp from the last time we tried to gather HELLOs.
179  */
180 static struct GNUNET_TIME_Absolute last_hello_gather_time;
181
182 /**
183  * Flag to disallow non-friend connections (pure F2F mode).
184  */
185 static int friends_only;
186
187 /**
188  * Minimum number of friends to have in the
189  * connection set before we allow non-friends.
190  */
191 static unsigned int minimum_friend_count;
192
193 /**
194  * Number of peers (friends and others) that we are currently connected to.
195  */
196 static unsigned int connection_count;
197
198 /**
199  * Target number of connections.
200  */
201 static unsigned int target_connection_count;
202
203 /**
204  * Number of friends that we are currently connected to.
205  */
206 static unsigned int friend_count;
207
208 /**
209  * Should the topology daemon try to establish connections?
210  */
211 static int autoconnect;
212
213 /**
214  * Are we currently having a request pending with
215  * PEERINFO asking for HELLOs for advertising?
216  */
217 static int hello_gathering_active;
218
219
220
221 /**
222  * Force a disconnect from the specified peer.
223  */
224 static void
225 force_disconnect (const struct GNUNET_PeerIdentity *peer)
226 {
227   GNUNET_CORE_peer_configure (handle,
228                               peer,
229                               GNUNET_TIME_UNIT_FOREVER_REL,
230                               0,
231                               0,
232                               0,
233                               NULL,
234                               NULL);
235 }
236
237
238 /**
239  * Function called by core when our attempt to connect
240  * succeeded.  Does nothing.
241  */
242 static size_t
243 ready_callback (void *cls,
244                 size_t size, void *buf)
245 {
246   return 0;
247 }
248
249
250 /**
251  * Try to connect to the specified peer.
252  *
253  * @param pos NULL if not in friend list yet
254  */
255 static void
256 attempt_connect (const struct GNUNET_PeerIdentity *peer,
257                  struct PeerList *pos)
258 {
259   if (pos == NULL)
260     {
261       pos = friends;
262       while (pos != NULL)
263         {
264           if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
265             break;
266         }
267     }
268   if (pos == NULL)
269     {
270       pos = GNUNET_malloc (sizeof(struct PeerList));
271       pos->id = *peer;
272       pos->next = friends;
273       friends = pos;
274     }
275   if (GNUNET_YES == pos->is_friend)
276     pos->blacklisted_until = GNUNET_TIME_relative_to_absolute (BLACKLIST_AFTER_ATTEMPT_FRIEND);
277   else
278     pos->blacklisted_until = GNUNET_TIME_relative_to_absolute (BLACKLIST_AFTER_ATTEMPT);
279   GNUNET_CORE_notify_transmit_ready (handle,
280                                      0 /* priority */,
281                                      GNUNET_TIME_UNIT_MINUTES,
282                                      peer,
283                                      sizeof(struct GNUNET_MessageHeader),
284                                      &ready_callback,
285                                      NULL);
286 }
287
288
289 /**
290  * Is this peer one of our friends?
291  */
292 static int
293 is_friend (const struct GNUNET_PeerIdentity * peer)
294 {
295   struct PeerList *pos;
296
297   pos = friends;
298   while (pos != NULL)
299     {
300       if ( (GNUNET_YES == pos->is_friend) &&
301            (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity))) )
302         return GNUNET_YES;
303       pos = pos->next;
304     }
305   return GNUNET_NO;
306 }
307
308
309 /**
310  * Check if an additional connection from the given peer is allowed.
311  */
312 static int
313 is_connection_allowed (const struct GNUNET_PeerIdentity * peer)
314 {
315   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
316     return GNUNET_SYSERR;       /* disallow connections to self */
317   if (is_friend (peer))
318     return GNUNET_OK;
319   if (GNUNET_YES == friends_only)
320     return GNUNET_SYSERR;
321   if (friend_count >= minimum_friend_count)
322     return GNUNET_OK;
323   return GNUNET_SYSERR;
324 }
325
326
327 /**
328  * Method called whenever a peer connects.
329  *
330  * @param cls closure
331  * @param peer peer identity this notification is about
332  */
333 static void connect_notify (void *cls,
334                             const struct
335                             GNUNET_PeerIdentity * peer)
336 {
337   struct PeerList *pos;
338
339   connection_count++;
340   pos = friends;
341   while (pos != NULL)
342     {
343       if ( (GNUNET_YES == pos->is_friend) &&
344            (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity))) )
345         {
346           GNUNET_assert (GNUNET_NO == pos->is_connected);
347           pos->is_connected = GNUNET_YES;
348           pos->blacklisted_until.value = 0; /* remove blacklisting */
349           friend_count++;
350           return;
351         }
352       pos = pos->next;
353     }
354   pos = GNUNET_malloc (sizeof(struct PeerList));
355   pos->id = *peer;
356   pos->is_connected = GNUNET_YES;
357   pos->next = friends;
358   friends = pos;
359   if (GNUNET_OK != is_connection_allowed (peer))
360     force_disconnect (peer);
361 }
362
363
364 /**
365  * Disconnect from all non-friends (we're below quota).
366  */
367 static void
368 drop_non_friends ()
369 {
370   struct PeerList *pos;
371
372   pos = friends;
373   while (pos != NULL)
374     {
375       if (GNUNET_NO == pos->is_friend)
376         {
377           GNUNET_assert (GNUNET_YES == pos->is_connected);
378           force_disconnect (&pos->id);
379         }
380       pos = pos->next;
381     }
382 }
383
384
385 /**
386  * Method called whenever a peer disconnects.
387  *
388  * @param cls closure
389  * @param peer peer identity this notification is about
390  */
391 static void disconnect_notify (void *cls,
392                                const struct
393                                GNUNET_PeerIdentity * peer)
394 {
395   struct PeerList *pos;
396   struct PeerList *prev;
397
398   connection_count--;
399   pos = friends;
400   prev = NULL;
401   while (pos != NULL)
402     {
403       if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
404         {
405           GNUNET_assert (GNUNET_YES == pos->is_connected);
406           pos->is_connected = GNUNET_NO;
407           if (GNUNET_YES == pos->is_friend)
408             {
409               friend_count--;
410               if (friend_count < minimum_friend_count)
411                 {
412                   /* disconnect from all non-friends */
413                   drop_non_friends ();
414                   attempt_connect (peer, pos);
415                 }
416             }
417           else
418             {
419               /* free entry */
420               if (prev == NULL)
421                 friends = pos->next;
422               else
423                 prev->next = pos->next;
424               GNUNET_free (pos);
425             }
426           return;
427         }
428       prev = pos;
429       pos = pos->next;
430     }
431   GNUNET_break (0);
432 }
433
434
435 /**
436  * Find more peers that we should connect to and ask the
437  * core to establish connections.
438  */
439 static void
440 find_more_peers (void *cls,
441                  const struct GNUNET_SCHEDULER_TaskContext *tc);
442
443
444 /**
445  * Determine when we should try again to find more peers and
446  * schedule the task.
447  */
448 static void
449 schedule_peer_search ()
450 {
451   struct GNUNET_TIME_Relative delay;
452
453   /* Typically, we try again every 15 minutes; the minimum period is
454      15s; if we are above the connection target, we reduce re-trying
455      by the square of how much we are above; so for example, with 200%
456      of the connection target we would only look for more peers once
457      every hour (after all, we're quite busy processing twice as many
458      connections as we intended to have); similarly, if we are at only
459      25% of our connectivity goal, we will try 16x as hard to connect
460      (so roughly once a minute, plus the 15s minimum delay */
461   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
462                                          15 + 15 * 60 * connection_count * connection_count / target_connection_count / target_connection_count);
463   GNUNET_SCHEDULER_add_delayed (sched,
464                                 GNUNET_NO,
465                                 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
466                                 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
467                                 delay,
468                                 &find_more_peers,
469                                 NULL);
470 }
471
472
473
474
475 /**
476  * Iterator called on each address.
477  *
478  * @param cls flag that we will set if we see any addresses.
479  */
480 static int
481 address_iterator (void *cls,
482                   const char *tname,
483                   struct GNUNET_TIME_Absolute expiration,
484                   const void *addr, size_t addrlen)
485 {
486   int *flag = cls;
487   *flag = GNUNET_YES;
488   return GNUNET_SYSERR;
489 }
490
491
492 /**
493  * We've gotten a HELLO from another peer.
494  * Consider it for advertising.
495  */
496 static void
497 consider_for_advertising (const struct GNUNET_HELLO_Message *hello)
498 {
499   int have_address;
500   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
501   struct GNUNET_PeerIdentity pid;
502   struct HelloList *pos;
503   uint16_t size;
504
505   have_address = GNUNET_NO;
506   GNUNET_HELLO_iterate_addresses (hello,
507                                   GNUNET_NO,
508                                   &address_iterator,
509                                   &have_address);
510   if (GNUNET_NO == have_address)
511     return; /* no point in advertising this one... */
512   GNUNET_HELLO_get_key (hello, &pkey);
513   GNUNET_CRYPTO_hash (&pkey, sizeof (pkey), &pid.hashPubKey);
514   pos = hellos;
515   while (pos != NULL)
516     {
517       if (0 == memcmp (&pos->id,
518                        &pid,
519                        sizeof(struct GNUNET_PeerIdentity)))
520         return; /* duplicate, at least "mostly" */
521       pos = pos->next;
522     }
523   size = GNUNET_HELLO_size (hello);
524   pos = GNUNET_malloc (sizeof(struct HelloList) + size);
525   pos->msg = (struct GNUNET_HELLO_Message*) &pos[1];
526   memcpy (&pos->msg, hello, size);
527   pos->id = pid;
528   pos->expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADVERTISEMENT_MIN_FREQUENCY);
529   /* 2^{-5} chance of not sending a HELLO to a peer is
530      acceptably small (if the filter is 50% full);
531      64 bytes of memory are small compared to the rest
532      of the data structure and would only really become
533      "useless" once a HELLO has been passed on to ~100
534      other peers, which is likely more than enough in
535      any case; hence 64, 5 as bloomfilter parameters. */
536   pos->filter = GNUNET_CONTAINER_bloomfilter_load (NULL, 64, 5);
537   /* never send a peer its own HELLO */
538   GNUNET_CONTAINER_bloomfilter_add (pos->filter, &pos->id.hashPubKey);
539   pos->next = hellos;
540   hellos = pos;
541 }
542
543
544 /**
545  * Peerinfo calls this function to let us know about a
546  * possible peer that we might want to connect to.
547  */
548 static void
549 process_peer (void *cls,
550               const struct GNUNET_PeerIdentity *peer,
551               const struct GNUNET_HELLO_Message *hello,
552               uint32_t trust)
553 {
554   struct PeerList *pos;
555
556   if (peer == NULL)
557     {
558       /* last call, schedule 'find_more_peers' again... */
559       schedule_peer_search ();
560       return;
561     }
562   if (hello == NULL)
563     {
564       /* no HELLO known; can not connect, ignore! */
565       return;
566     }
567   if (0 == memcmp (&my_identity,
568                    peer, sizeof (struct GNUNET_PeerIdentity)))
569     return;  /* that's me! */
570
571   consider_for_advertising (hello);
572   pos = friends;
573   while (pos != NULL)
574     {
575       if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
576         {
577           if (GNUNET_YES == pos->is_connected)
578             return;
579           if (GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value > 0)
580             return; /* peer still blacklisted */
581           if (GNUNET_YES == pos->is_friend)
582             {
583               attempt_connect (peer, pos);
584               return;
585             }
586         }
587       pos = pos->next;
588     }
589   if (GNUNET_YES == friends_only)
590     return;
591   if (friend_count < minimum_friend_count)
592     return;
593   attempt_connect (peer, NULL);
594 }
595
596
597 /**
598  * Try to add more friends to our connection set.
599  */
600 static void
601 try_add_friends ()
602 {
603   struct PeerList *pos;
604
605   pos = friends;
606   while (pos != NULL)
607     {
608       if ( (GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value == 0) &&
609            (GNUNET_YES == pos->is_friend) &&
610            (GNUNET_YES != pos->is_connected) )
611         attempt_connect (&pos->id, pos);
612       pos = pos->next;
613     }
614 }
615
616
617 /**
618  * Discard peer entries for blacklisted peers
619  * where the blacklisting has expired.
620  */
621 static void
622 discard_old_blacklist_entries ()
623 {
624   struct PeerList *pos;
625   struct PeerList *next;
626   struct PeerList *prev;
627
628   next = friends;
629   prev = NULL;
630   while (NULL != (pos = next))
631     {
632       next = pos->next;
633       if ( (GNUNET_NO == pos->is_friend) &&
634            (GNUNET_NO == pos->is_connected) &&
635            (0 == GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value) )
636         {
637           /* delete 'pos' from list */
638           if (prev == NULL)
639             friends = next;
640           else
641             prev->next = next;
642           GNUNET_free (pos);
643         }
644       else
645         {
646           prev = pos;
647         }
648     }
649 }
650
651
652 /**
653  * Find more peers that we should connect to and ask the
654  * core to establish connections.
655  */
656 static void
657 find_more_peers (void *cls,
658                  const struct GNUNET_SCHEDULER_TaskContext *tc)
659 {
660   discard_old_blacklist_entries ();
661   if (target_connection_count <= connection_count)
662     {
663       schedule_peer_search ();
664       return;
665     }
666   if ( (GNUNET_YES == friends_only) ||
667        (friend_count < minimum_friend_count) )
668     {
669       try_add_friends ();
670       schedule_peer_search ();
671       return;
672     }
673   GNUNET_PEERINFO_for_all (cfg,
674                            sched,
675                            NULL,
676                            0, GNUNET_TIME_UNIT_FOREVER_REL,
677                            &process_peer, NULL);
678 }
679
680
681 /**
682  * Function called after GNUNET_CORE_connect has succeeded
683  * (or failed for good).
684  *
685  * @param cls closure
686  * @param server handle to the server, NULL if we failed
687  * @param my_id ID of this peer, NULL if we failed
688  * @param publicKey public key of this peer, NULL if we failed
689  */
690 static void
691 core_init (void *cls,
692            struct GNUNET_CORE_Handle * server,
693            const struct GNUNET_PeerIdentity *
694            my_id,
695            const struct
696            GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
697            publicKey)
698 {
699   if (server == NULL)
700     {
701       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
702                   _("Failed to connect to core service, can not manage topology!\n"));
703       return;
704     }
705   handle = server;
706   my_identity = *my_id;
707   if (autoconnect)
708     GNUNET_SCHEDULER_add_delayed (sched,
709                                   GNUNET_NO,
710                                   GNUNET_SCHEDULER_PRIORITY_DEFAULT,
711                                   GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
712                                   GNUNET_TIME_UNIT_SECONDS /* give core time to tell us about existing connections */,
713                                   &find_more_peers,
714                                   NULL);
715 }
716
717
718 /**
719  * gnunet-daemon-topology command line options.
720  */
721 static struct GNUNET_GETOPT_CommandLineOption options[] = {
722   GNUNET_GETOPT_OPTION_END
723 };
724
725
726 /**
727  * Read the friends file.
728  */
729 static void
730 read_friends_file (struct GNUNET_CONFIGURATION_Handle *cfg)
731 {
732   char *fn;
733   char *data;
734   size_t pos;
735   GNUNET_HashCode hc;
736   struct stat frstat;
737   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
738   unsigned int entries_found;
739   struct PeerList *fl;
740
741   fn = NULL;
742   GNUNET_CONFIGURATION_get_value_filename (cfg,
743                                            "TOPOLOGY",
744                                            "FRIENDS",
745                                            &fn);
746   if (GNUNET_OK != GNUNET_DISK_file_test (fn))
747     GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
748         | GNUNET_DISK_PERM_USER_WRITE);
749   if (0 != STAT (fn, &frstat))
750     {
751       if ((friends_only) || (minimum_friend_count > 0))
752         {
753           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
754                       _("Could not read friends list `%s'\n"), fn);
755           GNUNET_free (fn);
756           return;
757         }
758     }
759   if (frstat.st_size == 0)
760     {
761       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
762                   _("Friends file `%s' is empty.\n"),
763                   fn);
764       GNUNET_free (fn);
765       return;
766     }
767   data = GNUNET_malloc_large (frstat.st_size);
768   if (frstat.st_size !=
769       GNUNET_DISK_fn_read (fn, data, frstat.st_size))
770     {
771       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
772                   _("Failed to read friends list from `%s'\n"), fn);
773       GNUNET_free (fn);
774       GNUNET_free (data);
775       return;
776     }
777   entries_found = 0;
778   pos = 0;
779   while ((pos < frstat.st_size) && isspace (data[pos]))
780     pos++;
781   while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
782          (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
783     {
784       memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
785       if (!isspace (enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
786         {
787           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
788                       _("Syntax error in topology specification at offset %llu, skipping bytes.\n"),
789                       (unsigned long long) pos);
790           pos++;
791           while ((pos < frstat.st_size) && (!isspace (data[pos])))
792             pos++;
793           continue;
794         }
795       enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
796       if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &hc))
797         {
798           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
799                       _("Syntax error in topology specification at offset %llu, skipping bytes `%s'.\n"),
800                       (unsigned long long) pos,
801                       &enc);
802         }
803       else
804         {
805           entries_found++;
806           fl = GNUNET_malloc (sizeof(struct PeerList));
807           fl->is_friend = GNUNET_YES;
808           fl->id.hashPubKey = hc;
809           fl->next = friends;
810           friends = fl;
811         }
812       pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
813       while ((pos < frstat.st_size) && isspace (data[pos]))
814         pos++;
815     }
816   GNUNET_free (data);
817   GNUNET_free (fn);
818   if ( (minimum_friend_count > entries_found) &&
819        (friends_only == GNUNET_NO) )
820     {
821       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
822                   _("Fewer friends specified than required by minimum friend count. Will only connect to friends.\n"));
823     }
824   if ( (minimum_friend_count > target_connection_count) &&
825        (friends_only == GNUNET_NO) )
826     {
827       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
828                   _("More friendly connections required than target total number of connections.\n"));
829     }
830 }
831
832
833 /**
834  * This function is called whenever an encrypted HELLO message is
835  * received.
836  *
837  * @param cls closure
838  * @param peer the other peer involved (sender or receiver, NULL
839  *        for loopback messages where we are both sender and receiver)
840  * @param message the actual HELLO message
841  * @return GNUNET_OK to keep the connection open,
842  *         GNUNET_SYSERR to close it (signal serious error)
843  */
844 static int
845 handle_encrypted_hello (void *cls,
846                         const struct GNUNET_PeerIdentity * other,
847                         const struct GNUNET_MessageHeader *
848                         message)
849 {
850   if (transport != NULL)
851     GNUNET_TRANSPORT_offer_hello (transport,
852                                   message);
853   return GNUNET_OK;
854 }
855
856
857 /**
858  * Peerinfo calls this function to let us know about a
859  * possible peer that we might want to connect to.
860  */
861 static void
862 gather_hello_callback (void *cls,
863                        const struct GNUNET_PeerIdentity *peer,
864                        const struct GNUNET_HELLO_Message *hello,
865                        uint32_t trust)
866 {
867   if (peer == NULL)
868     {
869       hello_gathering_active = GNUNET_NO;
870       return;
871     }
872   if (hello != NULL)
873     consider_for_advertising (hello);
874 }
875
876
877 /**
878  * Function to fill send buffer with HELLO.
879  *
880  * @param receiver the receiver of the message
881  * @param position is the reference to the
882  *        first unused position in the buffer where GNUnet is building
883  *        the message
884  * @param padding is the number of bytes left in that buffer.
885  * @return the number of bytes written to
886  *   that buffer (must be a positive number).
887  */
888 static unsigned int
889 hello_advertising (void *cls,
890                    const struct GNUNET_PeerIdentity *
891                    receiver,
892                    void *position, unsigned int padding)
893 {
894   struct PeerList *pl;
895   struct HelloList *pos;
896   struct HelloList *prev;
897   struct HelloList *next;
898   uint16_t size;
899
900   pl = friends;
901   while (pl != NULL)
902     {
903       if (0 == memcmp (&pl->id, receiver, sizeof (struct GNUNET_PeerIdentity)))
904         break;
905       pl = pl->next;
906     }
907   if (pl == NULL)
908     {
909       GNUNET_break (0);
910       return 0;
911     }
912   /* find applicable HELLOs */
913   prev = NULL;
914   next = hellos;
915   while (NULL != (pos = next))
916     {
917       next = pos->next;
918       if (GNUNET_NO ==
919           GNUNET_CONTAINER_bloomfilter_test (pos->filter,
920                                              &receiver->hashPubKey))
921         break;
922       if (0 == GNUNET_TIME_absolute_get_remaining (pos->expiration).value)
923         {
924           /* time to discard... */
925           if (prev == NULL)
926             prev->next = next;
927           else
928             hellos = next;
929           GNUNET_CONTAINER_bloomfilter_free (pos->filter);
930           GNUNET_free (pos);
931         }
932       else
933         {
934           prev = pos;
935         }
936     }
937   if (pos != NULL)
938     {
939       size = GNUNET_HELLO_size (pos->msg);
940       if (size < padding)
941         {
942           memcpy (position, pos->msg, size);
943           GNUNET_CONTAINER_bloomfilter_add (pos->filter,
944                                             &receiver->hashPubKey);
945         }
946       else
947         {
948           size = 0;
949         }
950       return size;
951     }
952   if ( (GNUNET_NO == hello_gathering_active) &&
953        (GNUNET_TIME_absolute_get_duration (last_hello_gather_time).value >
954         MIN_HELLO_GATHER_DELAY.value) )
955     {
956       hello_gathering_active = GNUNET_YES;
957       last_hello_gather_time = GNUNET_TIME_absolute_get();
958       GNUNET_PEERINFO_for_all (cfg,
959                                sched,
960                                NULL,
961                                0, GNUNET_TIME_UNIT_FOREVER_REL,
962                                &gather_hello_callback, NULL);
963     }
964   return 0;
965 }
966
967
968 /**
969  * Last task run during shutdown.  Disconnects us from
970  * the transport and core.
971  */
972 static void
973 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
974 {
975   struct PeerList *pl;
976
977   GNUNET_TRANSPORT_disconnect (transport);
978   transport = NULL;
979   GNUNET_CORE_disconnect (handle);
980   handle = NULL;
981   while (NULL != (pl = friends))
982     {
983       friends = pl->next;
984       GNUNET_free (pl);
985     }
986 }
987
988
989 /**
990  * Main function that will be run.
991  *
992  * @param cls closure
993  * @param s the scheduler to use
994  * @param args remaining command-line arguments
995  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
996  * @param c configuration
997  */
998 static void
999 run (void *cls,
1000      struct GNUNET_SCHEDULER_Handle * s,
1001      char *const *args,
1002      const char *cfgfile,
1003      struct GNUNET_CONFIGURATION_Handle * c)
1004 {
1005   struct GNUNET_CORE_MessageHandler handlers[] =
1006     {
1007       { &handle_encrypted_hello, GNUNET_MESSAGE_TYPE_HELLO, 0},
1008       { NULL, 0, 0 }
1009     };
1010   unsigned long long opt;
1011
1012   sched = s;
1013   cfg = c;
1014   autoconnect = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1015                                                       "TOPOLOGY",
1016                                                       "AUTOCONNECT");
1017   friends_only = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1018                                                        "TOPOLOGY",
1019                                                        "FRIENDS-ONLY");
1020   opt = 0;
1021   GNUNET_CONFIGURATION_get_value_number (cfg,
1022                                          "TOPOLOGY",
1023                                          "MINIMUM-FRIENDS",
1024                                          &opt);
1025   minimum_friend_count = (unsigned int) opt;
1026   opt = 16;
1027   GNUNET_CONFIGURATION_get_value_number (cfg,
1028                                          "TOPOLOGY",
1029                                          "TARGET-CONNECTION-COUNT",
1030                                          &opt);
1031   target_connection_count = (unsigned int) opt;
1032
1033   if ( (friends_only == GNUNET_YES) ||
1034        (minimum_friend_count > 0) )
1035     read_friends_file (cfg);
1036
1037   transport = GNUNET_TRANSPORT_connect (sched,
1038                                         cfg,
1039                                         NULL,
1040                                         NULL,
1041                                         NULL,
1042                                         NULL);
1043   GNUNET_CORE_connect (sched,
1044                        cfg,
1045                        GNUNET_TIME_UNIT_FOREVER_REL,
1046                        NULL,
1047                        &core_init,
1048                        &connect_notify,
1049                        &disconnect_notify,
1050                        &hello_advertising,
1051                        NULL, GNUNET_NO,
1052                        NULL, GNUNET_NO,
1053                        handlers);
1054
1055   GNUNET_SCHEDULER_add_delayed (sched,
1056                                 GNUNET_YES,
1057                                 GNUNET_SCHEDULER_PRIORITY_IDLE,
1058                                 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1059                                 GNUNET_TIME_UNIT_FOREVER_REL,
1060                                 &cleaning_task, NULL);
1061 }
1062
1063
1064 /**
1065  * The main function for the topology daemon.
1066  *
1067  * @param argc number of arguments from the command line
1068  * @param argv command line arguments
1069  * @return 0 ok, 1 on error
1070  */
1071 int
1072 main (int argc, char *const *argv)
1073 {
1074   int ret;
1075
1076   ret = (GNUNET_OK ==
1077          GNUNET_PROGRAM_run (argc,
1078                              argv,
1079                              "topology",
1080                              _("GNUnet topology control (maintaining P2P mesh and F2F constraints)"),
1081                              options,
1082                              &run, NULL)) ? 0 : 1;
1083   return ret;
1084 }
1085
1086 /* end of gnunet-daemon-topology.c */