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