3c29c229deaea7da9c7b86364b178cc286800ccf
[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 #if DEBUG_TOPOLOGY
877   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
878               "Considering connecting to peer `%s'\n",
879               GNUNET_i2s (peer));
880 #endif 
881   if (GNUNET_YES == pos->is_connected)
882     {
883 #if DEBUG_TOPOLOGY
884       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
885                   "Already connected to peer `%s'\n",
886                   GNUNET_i2s (peer));
887 #endif 
888       return;
889     }
890   if (GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value > 0)
891     {
892 #if DEBUG_TOPOLOGY
893       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
894                   "Already tried peer `%s' recently\n",
895                   GNUNET_i2s (peer));
896 #endif 
897       return; /* peer still blacklisted */
898     }
899   if ( (GNUNET_YES == pos->is_friend) ||
900        (GNUNET_YES != friends_only) ||    
901        (friend_count >= minimum_friend_count) )
902     attempt_connect (pos);
903 }
904
905
906 /**
907  * Discard peer entries for blacklisted peers
908  * where the blacklisting has expired.
909  */
910 static void
911 discard_old_blacklist_entries (void *cls,
912                                const struct GNUNET_SCHEDULER_TaskContext *tc)
913 {
914   struct PeerList *pos;
915   struct PeerList *next;
916
917   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
918     return;
919   next = peers;
920   while (NULL != (pos = next))
921     {
922       next = pos->next;
923       if ( (GNUNET_NO == pos->is_friend) &&
924            (GNUNET_NO == pos->is_connected) &&
925            (0 == GNUNET_TIME_absolute_get_remaining (pos->blacklisted_until).value) )
926         free_peer (pos);
927     }
928   GNUNET_SCHEDULER_add_delayed (sched,
929                                 BLACKLIST_AFTER_ATTEMPT,
930                                 &discard_old_blacklist_entries,
931                                 NULL);
932 }
933
934
935 /**
936  * Function called after GNUNET_CORE_connect has succeeded
937  * (or failed for good).
938  *
939  * @param cls closure
940  * @param server handle to the server, NULL if we failed
941  * @param my_id ID of this peer, NULL if we failed
942  * @param publicKey public key of this peer, NULL if we failed
943  */
944 static void
945 core_init (void *cls,
946            struct GNUNET_CORE_Handle * server,
947            const struct GNUNET_PeerIdentity *
948            my_id,
949            const struct
950            GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
951            publicKey)
952 {
953   if (server == NULL)
954     {
955       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
956                   _("Failed to connect to core service, can not manage topology!\n"));
957       GNUNET_SCHEDULER_shutdown (sched);
958       return;
959     }
960   handle = server;
961   my_identity = *my_id;
962 #if DEBUG_TOPOLOGY
963   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964               "I am peer `%s'\n",
965               GNUNET_i2s (my_id));
966 #endif  
967   GNUNET_SCHEDULER_add_delayed (sched,
968                                 BLACKLIST_AFTER_ATTEMPT,
969                                 &discard_old_blacklist_entries,
970                                 NULL);
971 }
972
973
974 /**
975  * Read the friends file.
976  */
977 static void
978 read_friends_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
979 {
980   char *fn;
981   char *data;
982   size_t pos;
983   struct GNUNET_PeerIdentity pid;
984   struct stat frstat;
985   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
986   unsigned int entries_found;
987   struct PeerList *fl;
988
989   if (GNUNET_OK !=
990       GNUNET_CONFIGURATION_get_value_filename (cfg,
991                                                "TOPOLOGY",
992                                                "FRIENDS",
993                                                &fn))
994     {
995       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
996                   _("Option `%s' in section `%s' not specified!\n"),
997                   "FRIENDS",
998                   "TOPOLOGY");
999       return;
1000     }
1001   if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1002     GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1003         | GNUNET_DISK_PERM_USER_WRITE);
1004   if (0 != STAT (fn, &frstat))
1005     {
1006       if ((friends_only) || (minimum_friend_count > 0))
1007         {
1008           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1009                       _("Could not read friends list `%s'\n"), fn);
1010           GNUNET_free (fn);
1011           return;
1012         }
1013     }
1014   if (frstat.st_size == 0)
1015     {
1016       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1017                   _("Friends file `%s' is empty.\n"),
1018                   fn);
1019       GNUNET_free (fn);
1020       return;
1021     }
1022   data = GNUNET_malloc_large (frstat.st_size);
1023   if (frstat.st_size !=
1024       GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1025     {
1026       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1027                   _("Failed to read friends list from `%s'\n"), fn);
1028       GNUNET_free (fn);
1029       GNUNET_free (data);
1030       return;
1031     }
1032   entries_found = 0;
1033   pos = 0;
1034   while ((pos < frstat.st_size) && isspace (data[pos]))
1035     pos++;
1036   while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1037          (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1038     {
1039       memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1040       if (!isspace (enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1041         {
1042           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1043                       _("Syntax error in topology specification at offset %llu, skipping bytes.\n"),
1044                       (unsigned long long) pos);
1045           pos++;
1046           while ((pos < frstat.st_size) && (!isspace (data[pos])))
1047             pos++;
1048           continue;
1049         }
1050       enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1051       if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1052         {
1053           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1054                       _("Syntax error in topology specification at offset %llu, skipping bytes `%s'.\n"),
1055                       (unsigned long long) pos,
1056                       &enc);
1057         }
1058       else
1059         {
1060           entries_found++;
1061           fl = make_peer (&pid,
1062                           NULL,
1063                           GNUNET_YES);
1064           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1065                       _("Found friend `%s' in configuration\n"),
1066                       GNUNET_i2s (&fl->id));
1067         }
1068       pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1069       while ((pos < frstat.st_size) && isspace (data[pos]))
1070         pos++;
1071     }
1072   GNUNET_free (data);
1073   GNUNET_free (fn);
1074   if ( (minimum_friend_count > entries_found) &&
1075        (friends_only == GNUNET_NO) )
1076     {
1077       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1078                   _("Fewer friends specified than required by minimum friend count. Will only connect to friends.\n"));
1079     }
1080   if ( (minimum_friend_count > target_connection_count) &&
1081        (friends_only == GNUNET_NO) )
1082     {
1083       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1084                   _("More friendly connections required than target total number of connections.\n"));
1085     }
1086 }
1087
1088
1089 /**
1090  * This function is called whenever an encrypted HELLO message is
1091  * received.
1092  *
1093  * @param cls closure
1094  * @param other the other peer involved (sender or receiver, NULL
1095  *        for loopback messages where we are both sender and receiver)
1096  * @param message the actual HELLO message
1097  * @return GNUNET_OK to keep the connection open,
1098  *         GNUNET_SYSERR to close it (signal serious error)
1099  */
1100 static int
1101 handle_encrypted_hello (void *cls,
1102                         const struct GNUNET_PeerIdentity * other,
1103                         const struct GNUNET_MessageHeader *
1104                         message)
1105 {
1106 #if DEBUG_TOPOLOGY
1107   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1108               "Received encrypted `%s' from peer `%s'",
1109               "HELLO",
1110               GNUNET_i2s (other));
1111 #endif  
1112   if (transport != NULL)
1113     GNUNET_TRANSPORT_offer_hello (transport,
1114                                   message);
1115   return GNUNET_OK;
1116 }
1117
1118
1119 /**
1120  * Function to fill send buffer with HELLO.
1121  *
1122  * @param cls 'struct PeerList' of the target peer
1123  * @param size number of bytes available in buf
1124  * @param buf where the callee should write the message
1125  * @return number of bytes written to buf
1126  */
1127 static size_t
1128 hello_advertising_ready (void *cls,
1129                          size_t size,
1130                          void *buf)
1131 {
1132   struct PeerList *pl = cls;
1133   struct PeerList *pos; 
1134   struct PeerList *next;
1135   uint16_t want;
1136   size_t hs;
1137
1138   pl->hello_req = NULL;
1139 #if DEBUG_TOPOLOGY
1140   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1141               "Data solicited for `%s', considering sending `%s'",
1142               GNUNET_i2s (&pl->id),
1143               "HELLO");
1144 #endif  
1145   /* find applicable HELLOs */
1146   next = peers;
1147   while (NULL != (pos = next))
1148     {
1149       next = pos->next;
1150       if (pos->hello == NULL)
1151         continue;
1152       if (0 == GNUNET_TIME_absolute_get_remaining (pos->filter_expiration).value)
1153         {
1154           /* time to discard... */
1155           GNUNET_CONTAINER_bloomfilter_free (pos->filter);
1156           setup_filter (pos);
1157         }
1158       if (GNUNET_NO ==
1159           GNUNET_CONTAINER_bloomfilter_test (pos->filter,
1160                                              &pl->id.hashPubKey))
1161         break;
1162     }
1163   want = 0;
1164   if (pos != NULL)
1165     {
1166       hs = GNUNET_HELLO_size (pos->hello);
1167       if (hs < size)
1168         {
1169           want = hs;
1170           memcpy (buf, pos->hello, want);
1171           GNUNET_CONTAINER_bloomfilter_add (pos->filter,
1172                                             &pl->id.hashPubKey);
1173           pl->next_hello_allowed = GNUNET_TIME_relative_to_absolute (HELLO_ADVERTISEMENT_MIN_FREQUENCY);
1174 #if DEBUG_TOPOLOGY
1175           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1176                       "Sending %u bytes of `%s's",
1177                       (unsigned int) want,
1178                       "HELLO");
1179 #endif  
1180         }
1181     }
1182   pl->hello_delay_task 
1183     = GNUNET_SCHEDULER_add_now (sched,
1184                                 &schedule_next_hello,
1185                                 pl);
1186   return want;
1187 }
1188
1189
1190 /**
1191  * Last task run during shutdown.  Disconnects us from
1192  * the transport and core.
1193  */
1194 static void
1195 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1196 {
1197   struct DisconnectList *dl;
1198
1199   if (NULL != peerinfo_notify)
1200     {
1201       GNUNET_PEERINFO_notify_cancel (peerinfo_notify);
1202       peerinfo_notify = NULL;
1203     }
1204   GNUNET_TRANSPORT_disconnect (transport);
1205   transport = NULL;
1206   while (NULL != peers)
1207     free_peer (peers);     
1208   if (handle != NULL)
1209     {
1210       GNUNET_CORE_disconnect (handle);
1211       handle = NULL;
1212     }
1213   while (NULL != (dl = disconnect_head))
1214     {
1215       GNUNET_CONTAINER_DLL_remove (disconnect_head,
1216                                    disconnect_tail,
1217                                    dl);
1218       GNUNET_CORE_peer_get_info_cancel (dl->rh);
1219       GNUNET_free (dl);
1220     }
1221 }
1222
1223
1224 /**
1225  * Main function that will be run.
1226  *
1227  * @param cls closure
1228  * @param s the scheduler to use
1229  * @param args remaining command-line arguments
1230  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1231  * @param c configuration
1232  */
1233 static void
1234 run (void *cls,
1235      struct GNUNET_SCHEDULER_Handle * s,
1236      char *const *args,
1237      const char *cfgfile,
1238      const struct GNUNET_CONFIGURATION_Handle * c)
1239 {
1240   struct GNUNET_CORE_MessageHandler handlers[] =
1241     {
1242       { &handle_encrypted_hello, GNUNET_MESSAGE_TYPE_HELLO, 0},
1243       { NULL, 0, 0 }
1244     };
1245   unsigned long long opt;
1246
1247   sched = s;
1248   cfg = c;
1249   autoconnect = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1250                                                       "TOPOLOGY",
1251                                                       "AUTOCONNECT");
1252   friends_only = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1253                                                        "TOPOLOGY",
1254                                                        "FRIENDS-ONLY");
1255   if (GNUNET_OK !=
1256       GNUNET_CONFIGURATION_get_value_number (cfg,
1257                                              "TOPOLOGY",
1258                                              "MINIMUM-FRIENDS",
1259                                              &opt))
1260     opt = 0;
1261   minimum_friend_count = (unsigned int) opt;
1262   if (GNUNET_OK !=
1263       GNUNET_CONFIGURATION_get_value_number (cfg,
1264                                              "TOPOLOGY",
1265                                              "TARGET-CONNECTION-COUNT",
1266                                              &opt))
1267     opt = 16;
1268   target_connection_count = (unsigned int) opt;
1269
1270   if ( (friends_only == GNUNET_YES) ||
1271        (minimum_friend_count > 0) )
1272     read_friends_file (cfg);
1273 #if DEBUG_TOPOLOGY
1274   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1275               "Topology would like %u connections with at least %u friends (%s)\n",
1276               target_connection_count,
1277               minimum_friend_count,
1278               autoconnect ? "autoconnect enabled" : "autoconnect disabled");
1279 #endif       
1280   transport = GNUNET_TRANSPORT_connect (sched,
1281                                         cfg,
1282                                         NULL,
1283                                         NULL,
1284                                         NULL,
1285                                         NULL);
1286   handle = GNUNET_CORE_connect (sched,
1287                                 cfg,
1288                                 GNUNET_TIME_UNIT_FOREVER_REL,
1289                                 NULL,
1290                                 &core_init,
1291                                 &connect_notify,
1292                                 &disconnect_notify,
1293                                 NULL, GNUNET_NO,
1294                                 NULL, GNUNET_NO,
1295                                 handlers);
1296   GNUNET_SCHEDULER_add_delayed (sched,
1297                                 GNUNET_TIME_UNIT_FOREVER_REL,
1298                                 &cleaning_task, NULL);
1299   if (NULL == transport)
1300     {
1301       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1302                   _("Failed to connect to `%s' service.\n"),
1303                   "transport");
1304       GNUNET_SCHEDULER_shutdown (sched);
1305       return;
1306     }
1307   if (NULL == handle)
1308     {
1309       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1310                   _("Failed to connect to `%s' service.\n"),
1311                   "core");
1312       GNUNET_SCHEDULER_shutdown (sched);
1313       return;
1314     }
1315   peerinfo_notify = GNUNET_PEERINFO_notify (cfg, sched,
1316                                             &process_peer,
1317                                             NULL);
1318 }
1319
1320
1321 /**
1322  * gnunet-daemon-topology command line options.
1323  */
1324 static struct GNUNET_GETOPT_CommandLineOption options[] = {
1325   GNUNET_GETOPT_OPTION_END
1326 };
1327
1328
1329 /**
1330  * The main function for the topology daemon.
1331  *
1332  * @param argc number of arguments from the command line
1333  * @param argv command line arguments
1334  * @return 0 ok, 1 on error
1335  */
1336 int
1337 main (int argc, char *const *argv)
1338 {
1339   int ret;
1340
1341   ret = (GNUNET_OK ==
1342          GNUNET_PROGRAM_run (argc,
1343                              argv,
1344                              "topology",
1345                              _("GNUnet topology control (maintaining P2P mesh and F2F constraints)"),
1346                              options,
1347                              &run, NULL)) ? 0 : 1;
1348   return ret;
1349 }
1350
1351 /* end of gnunet-daemon-topology.c */