407bea4a04c7bdd507f78c62d8170addea3617eb
[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       if (NULL != (pos = find_peer (peer)))
860         {
861           GNUNET_free_non_null (pos->hello);
862           pos->hello = NULL;
863           if (pos->filter != NULL)
864             {
865               GNUNET_CONTAINER_bloomfilter_free (pos->filter);
866               pos->filter = NULL;
867             }
868           if ( (! pos->is_connected) &&
869                (! pos->is_friend) &&
870                (0 == GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value) )
871             free_peer (pos);
872         }
873       return;
874     }
875   consider_for_advertising (hello);
876   pos = find_peer (peer);  
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                                 &connect_notify,
1293                                 &disconnect_notify,
1294                                 NULL, GNUNET_NO,
1295                                 NULL, GNUNET_NO,
1296                                 handlers);
1297   GNUNET_SCHEDULER_add_delayed (sched,
1298                                 GNUNET_TIME_UNIT_FOREVER_REL,
1299                                 &cleaning_task, NULL);
1300   if (NULL == transport)
1301     {
1302       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1303                   _("Failed to connect to `%s' service.\n"),
1304                   "transport");
1305       GNUNET_SCHEDULER_shutdown (sched);
1306       return;
1307     }
1308   if (NULL == handle)
1309     {
1310       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1311                   _("Failed to connect to `%s' service.\n"),
1312                   "core");
1313       GNUNET_SCHEDULER_shutdown (sched);
1314       return;
1315     }
1316   peerinfo_notify = GNUNET_PEERINFO_notify (cfg, sched,
1317                                             &process_peer,
1318                                             NULL);
1319 }
1320
1321
1322 /**
1323  * gnunet-daemon-topology command line options.
1324  */
1325 static struct GNUNET_GETOPT_CommandLineOption options[] = {
1326   GNUNET_GETOPT_OPTION_END
1327 };
1328
1329
1330 /**
1331  * The main function for the topology daemon.
1332  *
1333  * @param argc number of arguments from the command line
1334  * @param argv command line arguments
1335  * @return 0 ok, 1 on error
1336  */
1337 int
1338 main (int argc, char *const *argv)
1339 {
1340   int ret;
1341
1342   ret = (GNUNET_OK ==
1343          GNUNET_PROGRAM_run (argc,
1344                              argv,
1345                              "topology",
1346                              _("GNUnet topology control (maintaining P2P mesh and F2F constraints)"),
1347                              options,
1348                              &run, NULL)) ? 0 : 1;
1349   return ret;
1350 }
1351
1352 /* end of gnunet-daemon-topology.c */