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