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