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