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