leaks
[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 != pl->wh)
283     {
284       GNUNET_TRANSPORT_blacklist_cancel (pl->wh);
285       pl->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                                                &pl->id,
348                                                GNUNET_TIME_UNIT_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_non_null (pos->hello);   
511    if (pos->filter != NULL)
512      GNUNET_CONTAINER_bloomfilter_free (peer->filter);
513    GNUNET_free (pos);
514 }
515
516
517 /**
518  * Setup bloom filter for the given peer entry.
519  *
520  * @param peer entry to initialize
521  */
522 static void
523 setup_filter (struct PeerList *peer)
524 {
525   /* 2^{-5} chance of not sending a HELLO to a peer is
526      acceptably small (if the filter is 50% full);
527      64 bytes of memory are small compared to the rest
528      of the data structure and would only really become
529      "useless" once a HELLO has been passed on to ~100
530      other peers, which is likely more than enough in
531      any case; hence 64, 5 as bloomfilter parameters. */
532   peer->filter = GNUNET_CONTAINER_bloomfilter_load (NULL, 64, 5);
533   peer->filter_expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADVERTISEMENT_MIN_REPEAT_FREQUENCY);
534   /* never send a peer its own HELLO */
535   GNUNET_CONTAINER_bloomfilter_add (peer->filter, &peer->id.hashPubKey);
536 }
537
538
539 /**
540  * Function to fill send buffer with HELLO.
541  *
542  * @param cls 'struct PeerList' of the target peer
543  * @param size number of bytes available in buf
544  * @param buf where the callee should write the message
545  * @return number of bytes written to buf
546  */
547 static size_t
548 hello_advertising_ready (void *cls,
549                          size_t size,
550                          void *buf);
551
552
553 /**
554  * Calculate when we would like to send the next HELLO to this
555  * peer and ask for it.
556  *
557  * @param cls for which peer to schedule the HELLO
558  * @param tc task context
559  */
560 static void
561 schedule_next_hello (void *cls,
562                      const struct GNUNET_SCHEDULER_TaskContext *tc)
563 {
564   struct PeerList *pl = cls;
565   struct PeerList *pos;
566   struct PeerList *next;
567   uint16_t next_want;
568   struct GNUNET_TIME_Relative next_adv;
569   struct GNUNET_TIME_Relative rst_time;
570   
571   pl->hello_delay_task = GNUNET_SCHEDULER_NO_TASK;
572   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
573     return; /* we're out of here */
574   next_want = 0;
575   next_adv = GNUNET_TIME_UNIT_FOREVER_REL;
576   /* find applicable HELLOs */
577   next = peers;
578   while (NULL != (pos = next))
579     {
580       next = pos->next;
581       if (pos->hello == NULL)
582         continue;
583       rst_time = GNUNET_TIME_absolute_get_remaining (pos->filter_expiration);
584       if (0 == rst_time.value)
585         {
586           /* time to discard... */
587           GNUNET_CONTAINER_bloomfilter_free (pos->filter);
588           setup_filter (pos);
589         }
590       else
591         {
592           if (rst_time.value < next_adv.value)
593             next_want = GNUNET_HELLO_size (pos->hello);
594           next_adv = GNUNET_TIME_relative_min (rst_time,
595                                                next_adv);         
596         }
597       if (GNUNET_NO ==
598           GNUNET_CONTAINER_bloomfilter_test (pos->filter,
599                                              &pl->id.hashPubKey))
600         break;
601     }
602   if (pos != NULL)  
603     next_adv = GNUNET_TIME_absolute_get_remaining (pl->next_hello_allowed);
604   if (next_adv.value == 0)
605     {
606       /* now! */
607       pl->hello_req = GNUNET_CORE_notify_transmit_ready (handle, 0,
608                                                          next_adv,
609                                                          &pl->id,
610                                                          next_want,
611                                                          &hello_advertising_ready,
612                                                          pl);
613       return;
614     }
615   pl->hello_delay_task 
616     = GNUNET_SCHEDULER_add_delayed (sched,
617                                     next_adv,
618                                     &schedule_next_hello,
619                                     pl);
620 }
621
622
623 /**
624  * Cancel existing requests for sending HELLOs to this peer
625  * and recalculate when we should send HELLOs to it based
626  * on our current state (something changed!).
627  */
628 static void
629 reschedule_hellos (struct PeerList *peer)
630 {
631   if (peer->hello_req != NULL)
632     {
633       GNUNET_CORE_notify_transmit_ready_cancel (peer->hello_req);
634       peer->hello_req = NULL;
635     }
636    if (peer->hello_delay_task != GNUNET_SCHEDULER_NO_TASK)
637      {
638        GNUNET_SCHEDULER_cancel (sched,
639                                 peer->hello_delay_task);
640        peer->hello_delay_task = GNUNET_SCHEDULER_NO_TASK;
641      }
642    peer->hello_delay_task 
643      = GNUNET_SCHEDULER_add_now (sched,
644                                  &schedule_next_hello,
645                                  peer);
646 }
647
648
649 /**
650  * Method called whenever a peer connects.
651  *
652  * @param cls closure
653  * @param peer peer identity this notification is about
654  * @param latency reported latency of the connection with 'other'
655  * @param distance reported distance (DV) to 'other' 
656  */
657 static void 
658 connect_notify (void *cls,
659                 const struct
660                 GNUNET_PeerIdentity * peer,
661                 struct GNUNET_TIME_Relative latency,
662                 uint32_t distance)
663 {
664   struct PeerList *pos;
665
666 #if DEBUG_TOPOLOGY
667   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
668               "Core told us that we are connecting to `%s'\n",
669               GNUNET_i2s (peer));
670 #endif
671   connection_count++;
672   pos = find_peer (peer);
673   if (pos == NULL)    
674     {
675       pos = make_peer (peer, NULL, GNUNET_NO);
676       if (GNUNET_OK != is_connection_allowed (pos))
677         {
678           GNUNET_assert (pos->is_friend == GNUNET_NO);
679           pos->is_connected = GNUNET_YES;
680 #if DEBUG_TOPOLOGY
681           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
682                       "Connection to `%s' is forbidden, forcing disconnect!\n",
683                       GNUNET_i2s (peer));
684 #endif       
685           force_disconnect (pos);
686           return;
687         }
688     }
689   else
690     {
691       GNUNET_assert (GNUNET_NO == pos->is_connected);
692       pos->blacklisted_until.value = 0; /* remove blacklisting */
693     }
694   pos->is_connected = GNUNET_YES;
695   if (pos->is_friend)
696     {
697       if ( (friend_count == minimum_friend_count - 1) &&
698            (GNUNET_YES != friends_only) )       
699         whitelist_peers ();       
700       friend_count++;
701     }
702   reschedule_hellos (pos);
703 }
704
705
706 /**
707  * Disconnect from all non-friends (we're below quota).
708  */
709 static void
710 drop_non_friends ()
711 {
712   struct PeerList *pos;
713
714   pos = peers;
715   while (pos != NULL)
716     {
717       if ( (GNUNET_NO == pos->is_friend) &&
718            (GNUNET_YES == pos->is_connected) )
719         {
720 #if DEBUG_TOPOLOGY
721           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
722                       "Connection to `%s' is not from a friend, forcing disconnect!\n",
723                       GNUNET_i2s (&pos->id));
724 #endif       
725           force_disconnect (pos);
726         }
727       pos = pos->next;
728     }
729 }
730
731
732 /**
733  * Try to add more peers to our connection set.
734  */
735 static void
736 try_add_peers ()
737 {
738   struct PeerList *pos;
739
740   pos = peers;
741   while (pos != NULL)
742     {
743       if ( (GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value == 0) &&
744            ( (GNUNET_YES == pos->is_friend) ||
745              (friend_count >= minimum_friend_count) ) &&
746            (GNUNET_YES != pos->is_connected) )
747         attempt_connect (pos);
748       pos = pos->next;
749     }
750 }
751
752
753 /**
754  * Method called whenever a peer disconnects.
755  *
756  * @param cls closure
757  * @param peer peer identity this notification is about
758  */
759 static void 
760 disconnect_notify (void *cls,
761                    const struct
762                    GNUNET_PeerIdentity * peer)
763 {
764   struct PeerList *pos;
765  
766 #if DEBUG_TOPOLOGY
767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
768               "Core told us that we disconnected from `%s'\n",
769               GNUNET_i2s (peer));
770 #endif       
771   pos = find_peer (peer);
772   if (pos == NULL)
773     {
774       GNUNET_break (0);
775       return;
776     }
777   if (pos->is_connected != GNUNET_YES)
778     {
779       GNUNET_break (0);
780       return;
781     }
782   connection_count--;
783   if (pos->is_friend)
784     friend_count--; 
785   if ( (connection_count < target_connection_count) ||
786        (friend_count < minimum_friend_count) )
787     try_add_peers ();   
788   if (friend_count < minimum_friend_count)
789     {
790       /* disconnect from all non-friends */
791 #if DEBUG_TOPOLOGY
792       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
793                   "Not enough friendly connections, dropping all non-friend connections\n");
794 #endif       
795       drop_non_friends ();
796     }
797 }
798
799
800 /**
801  * Iterator called on each address.
802  *
803  * @param cls flag that we will set if we see any addresses
804  * @param tname name of the transport
805  * @param expiration when will the given address expire
806  * @param addr the address of the peer
807  * @param addrlen number of bytes in addr
808  * @return GNUNET_SYSERR always, to terminate iteration
809  */
810 static int
811 address_iterator (void *cls,
812                   const char *tname,
813                   struct GNUNET_TIME_Absolute expiration,
814                   const void *addr, size_t addrlen)
815 {
816   int *flag = cls;
817   *flag = GNUNET_YES;
818   return GNUNET_SYSERR;
819 }
820
821
822 /**
823  * We've gotten a HELLO from another peer.  Consider it for
824  * advertising.
825  */
826 static void
827 consider_for_advertising (const struct GNUNET_HELLO_Message *hello)
828 {
829   int have_address;
830   struct GNUNET_PeerIdentity pid;
831   struct PeerList *peer;
832   struct PeerList *pos;
833   uint16_t size;
834
835   have_address = GNUNET_NO;
836   GNUNET_HELLO_iterate_addresses (hello,
837                                   GNUNET_NO,
838                                   &address_iterator,
839                                   &have_address);
840   if (GNUNET_NO == have_address)
841     return; /* no point in advertising this one... */
842   GNUNET_break (GNUNET_OK == GNUNET_HELLO_get_id (hello, &pid));
843   peer = find_peer (&pid);
844   if (peer == NULL)
845     peer = make_peer (&pid, hello, GNUNET_NO);
846   // FIXME: check if 'hello' is any different from peer->hello?
847 #if DEBUG_TOPOLOGY
848   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
849               "Found `%s' from peer `%s' for advertising\n",
850               "HELLO",
851               GNUNET_i2s (&pid));
852 #endif 
853   size = GNUNET_HELLO_size (hello);
854   GNUNET_free_non_null (peer->hello);
855   peer->hello = GNUNET_malloc (size);
856   memcpy (peer->hello, hello, size);
857   if (peer->filter != NULL)
858     GNUNET_CONTAINER_bloomfilter_free (peer->filter);
859   setup_filter (peer);
860   /* since we have a new HELLO to pick from, re-schedule all
861      HELLO requests that are not bound by the HELLO send rate! */
862   pos = peers;
863   while (NULL != pos)
864     {
865       if (pos != peer)  
866         {
867           if ( (pos->is_connected) &&
868                (GNUNET_TIME_absolute_get_remaining (pos->next_hello_allowed).value <= HELLO_ADVERTISEMENT_MIN_FREQUENCY.value) )
869             reschedule_hellos (pos);    
870         }
871       pos = pos->next;
872     }
873 }
874
875
876 /**
877  * Peerinfo calls this function to let us know about a possible peer
878  * that we might want to connect to.
879  */
880 static void
881 process_peer (void *cls,
882               const struct GNUNET_PeerIdentity *peer,
883               const struct GNUNET_HELLO_Message *hello,
884               uint32_t trust)
885 {
886   struct PeerList *pos;
887
888   GNUNET_assert (peer != NULL);
889   if (0 == memcmp (&my_identity,
890                    peer, sizeof (struct GNUNET_PeerIdentity)))
891     return;  /* that's me! */
892   if (hello == NULL)
893     {
894       /* free existing HELLO, if any */
895       if (NULL != (pos = find_peer (peer)))
896         {
897           GNUNET_free_non_null (pos->hello);
898           pos->hello = NULL;
899           if (pos->filter != NULL)
900             {
901               GNUNET_CONTAINER_bloomfilter_free (pos->filter);
902               pos->filter = NULL;
903             }
904           if ( (! pos->is_connected) &&
905                (! pos->is_friend) &&
906                (0 == GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value) )
907             free_peer (pos);
908         }
909       return;
910     }
911   consider_for_advertising (hello);
912   pos = find_peer (peer);  
913   GNUNET_assert (NULL != pos);
914 #if DEBUG_TOPOLOGY
915   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
916               "Considering connecting to peer `%s'\n",
917               GNUNET_i2s (peer));
918 #endif 
919   if (GNUNET_YES == pos->is_connected)
920     {
921 #if DEBUG_TOPOLOGY
922       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
923                   "Already connected to peer `%s'\n",
924                   GNUNET_i2s (peer));
925 #endif 
926       return;
927     }
928   if (GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value > 0)
929     {
930 #if DEBUG_TOPOLOGY
931       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
932                   "Already tried peer `%s' recently\n",
933                   GNUNET_i2s (peer));
934 #endif 
935       return; /* peer still blacklisted */
936     }
937   if ( (GNUNET_YES == pos->is_friend) ||
938        (GNUNET_YES != friends_only) ||    
939        (friend_count >= minimum_friend_count) )
940     attempt_connect (pos);
941 }
942
943
944 /**
945  * Discard peer entries for blacklisted peers
946  * where the blacklisting has expired.
947  */
948 static void
949 discard_old_blacklist_entries (void *cls,
950                                const struct GNUNET_SCHEDULER_TaskContext *tc)
951 {
952   struct PeerList *pos;
953   struct PeerList *next;
954
955   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
956     return;
957   next = peers;
958   while (NULL != (pos = next))
959     {
960       next = pos->next;
961       if ( (GNUNET_NO == pos->is_friend) &&
962            (GNUNET_NO == pos->is_connected) &&
963            (GNUNET_NO == pos->is_blocked) &&
964            (0 == GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value) )
965         free_peer (pos);
966     }
967   GNUNET_SCHEDULER_add_delayed (sched,
968                                 BLACKLIST_AFTER_ATTEMPT,
969                                 &discard_old_blacklist_entries,
970                                 NULL);
971 }
972
973
974 /**
975  * Function called after GNUNET_CORE_connect has succeeded
976  * (or failed for good).
977  *
978  * @param cls closure
979  * @param server handle to the server, NULL if we failed
980  * @param my_id ID of this peer, NULL if we failed
981  * @param publicKey public key of this peer, NULL if we failed
982  */
983 static void
984 core_init (void *cls,
985            struct GNUNET_CORE_Handle * server,
986            const struct GNUNET_PeerIdentity *
987            my_id,
988            const struct
989            GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
990            publicKey)
991 {
992   if (server == NULL)
993     {
994       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
995                   _("Failed to connect to core service, can not manage topology!\n"));
996       GNUNET_SCHEDULER_shutdown (sched);
997       return;
998     }
999   handle = server;
1000   my_identity = *my_id;
1001 #if DEBUG_TOPOLOGY
1002   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1003               "I am peer `%s'\n",
1004               GNUNET_i2s (my_id));
1005 #endif  
1006   GNUNET_SCHEDULER_add_delayed (sched,
1007                                 BLACKLIST_AFTER_ATTEMPT,
1008                                 &discard_old_blacklist_entries,
1009                                 NULL);
1010 }
1011
1012
1013 /**
1014  * Read the friends file.
1015  */
1016 static void
1017 read_friends_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1018 {
1019   char *fn;
1020   char *data;
1021   size_t pos;
1022   struct GNUNET_PeerIdentity pid;
1023   struct stat frstat;
1024   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1025   unsigned int entries_found;
1026   struct PeerList *fl;
1027
1028   if (GNUNET_OK !=
1029       GNUNET_CONFIGURATION_get_value_filename (cfg,
1030                                                "TOPOLOGY",
1031                                                "FRIENDS",
1032                                                &fn))
1033     {
1034       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1035                   _("Option `%s' in section `%s' not specified!\n"),
1036                   "FRIENDS",
1037                   "TOPOLOGY");
1038       return;
1039     }
1040   if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1041     GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1042         | GNUNET_DISK_PERM_USER_WRITE);
1043   if (0 != STAT (fn, &frstat))
1044     {
1045       if ((friends_only) || (minimum_friend_count > 0))
1046         {
1047           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1048                       _("Could not read friends list `%s'\n"), fn);
1049           GNUNET_free (fn);
1050           return;
1051         }
1052     }
1053   if (frstat.st_size == 0)
1054     {
1055       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1056                   _("Friends file `%s' is empty.\n"),
1057                   fn);
1058       GNUNET_free (fn);
1059       return;
1060     }
1061   data = GNUNET_malloc_large (frstat.st_size);
1062   if (frstat.st_size !=
1063       GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1064     {
1065       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1066                   _("Failed to read friends list from `%s'\n"), fn);
1067       GNUNET_free (fn);
1068       GNUNET_free (data);
1069       return;
1070     }
1071   entries_found = 0;
1072   pos = 0;
1073   while ((pos < frstat.st_size) && isspace (data[pos]))
1074     pos++;
1075   while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1076          (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1077     {
1078       memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1079       if (!isspace (enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1080         {
1081           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1082                       _("Syntax error in topology specification at offset %llu, skipping bytes.\n"),
1083                       (unsigned long long) pos);
1084           pos++;
1085           while ((pos < frstat.st_size) && (!isspace (data[pos])))
1086             pos++;
1087           continue;
1088         }
1089       enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1090       if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1091         {
1092           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1093                       _("Syntax error in topology specification at offset %llu, skipping bytes `%s'.\n"),
1094                       (unsigned long long) pos,
1095                       &enc);
1096         }
1097       else
1098         {
1099           entries_found++;
1100           fl = make_peer (&pid,
1101                           NULL,
1102                           GNUNET_YES);
1103           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1104                       _("Found friend `%s' in configuration\n"),
1105                       GNUNET_i2s (&fl->id));
1106         }
1107       pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1108       while ((pos < frstat.st_size) && isspace (data[pos]))
1109         pos++;
1110     }
1111   GNUNET_free (data);
1112   GNUNET_free (fn);
1113   if ( (minimum_friend_count > entries_found) &&
1114        (friends_only == GNUNET_NO) )
1115     {
1116       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1117                   _("Fewer friends specified than required by minimum friend count. Will only connect to friends.\n"));
1118     }
1119   if ( (minimum_friend_count > target_connection_count) &&
1120        (friends_only == GNUNET_NO) )
1121     {
1122       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1123                   _("More friendly connections required than target total number of connections.\n"));
1124     }
1125 }
1126
1127
1128 /**
1129  * This function is called whenever an encrypted HELLO message is
1130  * received.
1131  *
1132  * @param cls closure
1133  * @param other the other peer involved (sender or receiver, NULL
1134  *        for loopback messages where we are both sender and receiver)
1135  * @param message the actual HELLO message
1136  * @param latency reported latency of the connection with 'other'
1137  * @param distance reported distance (DV) to 'other' 
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,
1143                         const struct GNUNET_PeerIdentity * other,
1144                         const struct GNUNET_MessageHeader *
1145                         message,
1146                         struct GNUNET_TIME_Relative latency,
1147                         uint32_t distance)
1148 {
1149 #if DEBUG_TOPOLOGY
1150   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1151               "Received encrypted `%s' from peer `%s'",
1152               "HELLO",
1153               GNUNET_i2s (other));
1154 #endif  
1155   if (transport != NULL)
1156     GNUNET_TRANSPORT_offer_hello (transport,
1157                                   message);
1158   return GNUNET_OK;
1159 }
1160
1161
1162 /**
1163  * Function to fill send buffer with HELLO.
1164  *
1165  * @param cls 'struct PeerList' of the target peer
1166  * @param size number of bytes available in buf
1167  * @param buf where the callee should write the message
1168  * @return number of bytes written to buf
1169  */
1170 static size_t
1171 hello_advertising_ready (void *cls,
1172                          size_t size,
1173                          void *buf)
1174 {
1175   struct PeerList *pl = cls;
1176   struct PeerList *pos; 
1177   struct PeerList *next;
1178   uint16_t want;
1179   size_t hs;
1180
1181   pl->hello_req = NULL;
1182 #if DEBUG_TOPOLOGY
1183   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1184               "Data solicited for `%s', considering sending `%s'",
1185               GNUNET_i2s (&pl->id),
1186               "HELLO");
1187 #endif  
1188   /* find applicable HELLOs */
1189   next = peers;
1190   while (NULL != (pos = next))
1191     {
1192       next = pos->next;
1193       if (pos->hello == NULL)
1194         continue;
1195       if (0 == GNUNET_TIME_absolute_get_remaining (pos->filter_expiration).value)
1196         {
1197           /* time to discard... */
1198           GNUNET_CONTAINER_bloomfilter_free (pos->filter);
1199           setup_filter (pos);
1200         }
1201       if (GNUNET_NO ==
1202           GNUNET_CONTAINER_bloomfilter_test (pos->filter,
1203                                              &pl->id.hashPubKey))
1204         break;
1205     }
1206   want = 0;
1207   if (pos != NULL)
1208     {
1209       hs = GNUNET_HELLO_size (pos->hello);
1210       if (hs < size)
1211         {
1212           want = hs;
1213           memcpy (buf, pos->hello, want);
1214           GNUNET_CONTAINER_bloomfilter_add (pos->filter,
1215                                             &pl->id.hashPubKey);
1216           pl->next_hello_allowed = GNUNET_TIME_relative_to_absolute (HELLO_ADVERTISEMENT_MIN_FREQUENCY);
1217 #if DEBUG_TOPOLOGY
1218           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1219                       "Sending %u bytes of `%s's",
1220                       (unsigned int) want,
1221                       "HELLO");
1222 #endif  
1223         }
1224     }
1225   pl->hello_delay_task 
1226     = GNUNET_SCHEDULER_add_now (sched,
1227                                 &schedule_next_hello,
1228                                 pl);
1229   return want;
1230 }
1231
1232
1233 /**
1234  * Last task run during shutdown.  Disconnects us from
1235  * the transport and core.
1236  */
1237 static void
1238 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1239 {
1240   struct DisconnectList *dl;
1241
1242   if (NULL != peerinfo_notify)
1243     {
1244       GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
1245       peerinfo_notify = NULL;
1246     }
1247   GNUNET_TRANSPORT_disconnect (transport);
1248   transport = NULL;
1249   while (NULL != peers)
1250     free_peer (peers);     
1251   if (handle != NULL)
1252     {
1253       GNUNET_CORE_disconnect (handle);
1254       handle = NULL;
1255     }
1256   while (NULL != (dl = disconnect_head))
1257     {
1258       GNUNET_CONTAINER_DLL_remove (disconnect_head,
1259                                    disconnect_tail,
1260                                    dl);
1261       GNUNET_TRANSPORT_blacklist_cancel (dl->rh);
1262       GNUNET_free (dl);
1263     }
1264 }
1265
1266
1267 /**
1268  * Main function that will be run.
1269  *
1270  * @param cls closure
1271  * @param s the scheduler to use
1272  * @param args remaining command-line arguments
1273  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1274  * @param c configuration
1275  */
1276 static void
1277 run (void *cls,
1278      struct GNUNET_SCHEDULER_Handle * s,
1279      char *const *args,
1280      const char *cfgfile,
1281      const struct GNUNET_CONFIGURATION_Handle * c)
1282 {
1283   struct GNUNET_CORE_MessageHandler handlers[] =
1284     {
1285       { &handle_encrypted_hello, GNUNET_MESSAGE_TYPE_HELLO, 0},
1286       { NULL, 0, 0 }
1287     };
1288   unsigned long long opt;
1289
1290   sched = s;
1291   cfg = c;
1292   autoconnect = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1293                                                       "TOPOLOGY",
1294                                                       "AUTOCONNECT");
1295   friends_only = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1296                                                        "TOPOLOGY",
1297                                                        "FRIENDS-ONLY");
1298   if (GNUNET_OK !=
1299       GNUNET_CONFIGURATION_get_value_number (cfg,
1300                                              "TOPOLOGY",
1301                                              "MINIMUM-FRIENDS",
1302                                              &opt))
1303     opt = 0;
1304   minimum_friend_count = (unsigned int) opt;
1305   if (GNUNET_OK !=
1306       GNUNET_CONFIGURATION_get_value_number (cfg,
1307                                              "TOPOLOGY",
1308                                              "TARGET-CONNECTION-COUNT",
1309                                              &opt))
1310     opt = 16;
1311   target_connection_count = (unsigned int) opt;
1312
1313   if ( (friends_only == GNUNET_YES) ||
1314        (minimum_friend_count > 0) )
1315     read_friends_file (cfg);
1316 #if DEBUG_TOPOLOGY
1317   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1318               "Topology would like %u connections with at least %u friends (%s)\n",
1319               target_connection_count,
1320               minimum_friend_count,
1321               autoconnect ? "autoconnect enabled" : "autoconnect disabled");
1322 #endif       
1323   transport = GNUNET_TRANSPORT_connect (sched,
1324                                         cfg,
1325                                         NULL,
1326                                         NULL,
1327                                         NULL,
1328                                         NULL);
1329   handle = GNUNET_CORE_connect (sched,
1330                                 cfg,
1331                                 GNUNET_TIME_UNIT_FOREVER_REL,
1332                                 NULL,
1333                                 &core_init,
1334                                 NULL,
1335                                 &connect_notify,
1336                                 &disconnect_notify,
1337                                 NULL, GNUNET_NO,
1338                                 NULL, GNUNET_NO,
1339                                 handlers);
1340   GNUNET_SCHEDULER_add_delayed (sched,
1341                                 GNUNET_TIME_UNIT_FOREVER_REL,
1342                                 &cleaning_task, NULL);
1343   if (NULL == transport)
1344     {
1345       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1346                   _("Failed to connect to `%s' service.\n"),
1347                   "transport");
1348       GNUNET_SCHEDULER_shutdown (sched);
1349       return;
1350     }
1351   if (NULL == handle)
1352     {
1353       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1354                   _("Failed to connect to `%s' service.\n"),
1355                   "core");
1356       GNUNET_SCHEDULER_shutdown (sched);
1357       return;
1358     }
1359   peerinfo_notify = GNUNET_PEERINFO_notify (cfg, sched,
1360                                             &process_peer,
1361                                             NULL);
1362 }
1363
1364
1365 /**
1366  * gnunet-daemon-topology command line options.
1367  */
1368 static struct GNUNET_GETOPT_CommandLineOption options[] = {
1369   GNUNET_GETOPT_OPTION_END
1370 };
1371
1372
1373 /**
1374  * The main function for the topology daemon.
1375  *
1376  * @param argc number of arguments from the command line
1377  * @param argv command line arguments
1378  * @return 0 ok, 1 on error
1379  */
1380 int
1381 main (int argc, char *const *argv)
1382 {
1383   int ret;
1384
1385   ret = (GNUNET_OK ==
1386          GNUNET_PROGRAM_run (argc,
1387                              argv,
1388                              "topology",
1389                              _("GNUnet topology control (maintaining P2P mesh and F2F constraints)"),
1390                              options,
1391                              &run, NULL)) ? 0 : 1;
1392   return ret;
1393 }
1394
1395 /* end of gnunet-daemon-topology.c */