44e786589b0cbbe0196a6d3e0a73ded7fd73b29b
[oweals/gnunet.git] / src / dv / gnunet-service-dv.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 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 3, 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 dv/gnunet-service-dv.c
23  * @brief the distance vector service, primarily handles gossip of nearby
24  * peers and sending/receiving DV messages from core and decapsulating
25  * them
26  *
27  * @author Christian Grothoff
28  * @author Nathan Evans
29  *
30  * TODO:
31  * - distance updates are not properly communicate to US by core/transport/ats
32  */
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_protocols.h"
36 #include "gnunet_core_service.h"
37 #include "gnunet_hello_lib.h"
38 #include "gnunet_peerinfo_service.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet_consensus_service.h"
41 #include "dv.h"
42 #include <gcrypt.h>
43
44
45 /**
46  * How often do we establish the consensu?
47  */
48 #define GNUNET_DV_CONSENSUS_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
49
50 /**
51  * Maximum number of messages we queue per peer.
52  */
53 #define MAX_QUEUE_SIZE 16
54
55 /**
56  * Maximum number of messages we queue towards the clients/plugin.
57  */
58 #define MAX_QUEUE_SIZE_PLUGIN 1024
59
60 /**
61  * The default fisheye depth, from how many hops away will
62  * we keep peers?
63  */
64 #define DEFAULT_FISHEYE_DEPTH 3
65
66 /**
67  * How many hops is a direct neighbor away?
68  */
69 #define DIRECT_NEIGHBOR_COST 1
70
71
72 GNUNET_NETWORK_STRUCT_BEGIN
73
74 /**
75  * Information about a peer DV can route to.  These entries are what
76  * we use as the binary format to establish consensus to create our
77  * routing table and as the address format in the HELLOs.
78  */
79 struct Target
80 {
81
82   /**
83    * Identity of the peer we can reach.
84    */
85   struct GNUNET_PeerIdentity peer;
86
87   /**
88    * How many hops (1-3) is this peer away? in network byte order
89    */
90   uint32_t distance GNUNET_PACKED;
91
92 };
93
94
95 /**
96  * Message exchanged between DV services (via core), requesting a
97  * message to be routed.  
98  */
99 struct RouteMessage
100 {
101   /**
102    * Type: GNUNET_MESSAGE_TYPE_DV_ROUTE
103    */
104   struct GNUNET_MessageHeader header;
105
106   /**
107    * Expected (remaining) distance.  Must be always smaller than
108    * DEFAULT_FISHEYE_DEPTH, should be zero at the target.  Must
109    * be decremented by one at each hop.  Peers must not forward
110    * these messages further once the counter has reached zero.
111    */
112   uint32_t distance GNUNET_PACKED;
113
114   /**
115    * The (actual) target of the message (this peer, if distance is zero).
116    */
117   struct GNUNET_PeerIdentity target;
118
119   /**
120    * The (actual) sender of the message.
121    */
122   struct GNUNET_PeerIdentity sender;
123
124 };
125
126 GNUNET_NETWORK_STRUCT_END
127
128
129 /**
130  * Linked list of messages to send to clients.
131  */
132 struct PendingMessage
133 {
134   /**
135    * Pointer to next item in the list
136    */
137   struct PendingMessage *next;
138
139   /**
140    * Pointer to previous item in the list
141    */
142   struct PendingMessage *prev;
143
144   /**
145    * Actual message to be sent, allocated after this struct.
146    */
147   const struct GNUNET_MessageHeader *msg;
148
149   /**
150    * Ultimate target for the message.
151    */
152   struct GNUNET_PeerIdentity ultimate_target;
153
154   /**
155    * Unique ID of the message.
156    */
157   uint32_t uid;
158
159 };
160
161
162 /**
163  * Information about a direct neighbor (core-level, excluding
164  * DV-links, only DV-enabled peers).
165  */
166 struct DirectNeighbor
167 {
168
169   /**
170    * Identity of the peer.
171    */
172   struct GNUNET_PeerIdentity peer;
173   
174   /**
175    * Head of linked list of messages to send to this peer.
176    */
177   struct PendingMessage *pm_head;
178
179   /**
180    * Tail of linked list of messages to send to this peer.
181    */
182   struct PendingMessage *pm_tail;
183
184   /**
185    * Transmit handle to core service.
186    */
187   struct GNUNET_CORE_TransmitHandle *cth;
188
189   /**
190    * Routing table of the neighbor, NULL if not yet established.
191    * Keys are peer identities, values are 'struct Target' entries.
192    * Note that the distances in the targets are from the point-of-view
193    * of the peer, not from us!
194    */ 
195   struct GNUNET_CONTAINER_MultiHashMap *neighbor_table;
196
197   /**
198    * Updated routing table of the neighbor, under construction,
199    * NULL if we are not currently building it.
200    * Keys are peer identities, values are 'struct Target' entries.
201    * Note that the distances in the targets are from the point-of-view
202    * of the peer, not from us!
203    */ 
204   struct GNUNET_CONTAINER_MultiHashMap *neighbor_table_consensus;
205
206   /**
207    * Active consensus, if we are currently synchronizing the
208    * routing tables.
209    */
210   struct GNUNET_CONSENSUS_Handle *consensus;
211
212   /**
213    * ID of the task we use to (periodically) update our consensus
214    * with this peer.
215    */
216   GNUNET_SCHEDULER_TaskIdentifier consensus_task;
217
218   /**
219    * At what offset are we, with respect to inserting our own routes
220    * into the consensus?
221    */
222   unsigned int consensus_insertion_offset;
223
224   /**
225    * At what distance are we, with respect to inserting our own routes
226    * into the consensus?
227    */
228   unsigned int consensus_insertion_distance;
229
230   /**
231    * Number of messages currently in the 'pm_XXXX'-DLL.
232    */
233   unsigned int pm_queue_size;
234
235   /**
236    * Flag set within 'check_target_removed' to trigger full global route refresh.
237    */
238   int target_removed;
239
240 };
241
242
243 /**
244  * A route includes information about the next hop,
245  * the target, and the ultimate distance to the
246  * target.
247  */
248 struct Route
249 {
250
251   /**
252    * Which peer do we need to forward the message to?
253    */
254   struct DirectNeighbor *next_hop;
255
256   /**
257    * What would be the target, and how far is it away?
258    */
259   struct Target target;
260
261   /**
262    * Offset of this target in the respective consensus set.
263    */
264   unsigned int set_offset;
265
266 };
267
268
269 /**
270  * Set of targets we bring to a consensus; all targets in a set have a
271  * distance equal to the sets distance (which is implied by the array
272  * index of the set).
273  */
274 struct ConsensusSet
275 {
276
277   /**
278    * Array of targets in the set, may include NULL entries if a
279    * neighbor has disconnected; the targets are allocated with the
280    * respective container (all_routes), not here.
281    */
282   struct Route **targets;
283
284   /**
285    * Size of the 'targets' array.
286    */
287   unsigned int array_length;
288
289 };
290
291
292 /**
293  * Hashmap of all of our direct neighbors (no DV routing).
294  */
295 static struct GNUNET_CONTAINER_MultiHashMap *direct_neighbors;
296
297 /**
298  * Hashmap with all routes that we currently support; contains 
299  * routing information for all peers from distance 2
300  * up to distance DEFAULT_FISHEYE_DEPTH.
301  */
302 static struct GNUNET_CONTAINER_MultiHashMap *all_routes;
303
304 /**
305  * Array of consensus sets we expose to the outside world.  Sets
306  * are structured by the distance to the target.
307  */
308 static struct ConsensusSet consensi[DEFAULT_FISHEYE_DEPTH - 1];
309
310 /**
311  * Handle to the core service api.
312  */
313 static struct GNUNET_CORE_Handle *core_api;
314
315 /**
316  * The identity of our peer.
317  */
318 static struct GNUNET_PeerIdentity my_identity;
319
320 /**
321  * The configuration for this service.
322  */
323 static const struct GNUNET_CONFIGURATION_Handle *cfg;
324
325 /**
326  * The client, the DV plugin connected to us (or an event monitor).
327  * Hopefully this client will never change, although if the plugin
328  * dies and returns for some reason it may happen.
329  */
330 static struct GNUNET_SERVER_NotificationContext *nc;
331
332 /**
333  * Handle for the statistics service.
334  */
335 struct GNUNET_STATISTICS_Handle *stats;
336
337
338 /**
339  * Get distance information from 'atsi'.
340  *
341  * @param atsi performance data
342  * @param atsi_count number of entries in atsi
343  * @return connected transport distance
344  */
345 static uint32_t
346 get_atsi_distance (const struct GNUNET_ATS_Information *atsi,
347                    unsigned int atsi_count)
348 {
349   unsigned int i;
350
351   for (i = 0; i < atsi_count; i++)
352     if (ntohl (atsi[i].type) == GNUNET_ATS_QUALITY_NET_DISTANCE)
353       return ntohl (atsi->value);
354   /* FIXME: we do not have distance data? Assume direct neighbor. */
355   return DIRECT_NEIGHBOR_COST;
356 }
357
358
359 /**
360  * Forward a message from another peer to the plugin.
361  *
362  * @param message the message to send to the plugin
363  * @param origin the original sender of the message
364  * @param distnace distance to the original sender of the message
365  */
366 static void
367 send_data_to_plugin (const struct GNUNET_MessageHeader *message, 
368                      const struct GNUNET_PeerIdentity *origin,
369                      uint32_t distance)
370 {
371   struct GNUNET_DV_ReceivedMessage *received_msg;
372   size_t size;
373
374   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
375               "Delivering message from peer `%s'\n",
376               GNUNET_i2s (origin));
377   size = sizeof (struct GNUNET_DV_ReceivedMessage) + 
378     ntohs (message->size);
379   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
380   {    
381     GNUNET_break (0); /* too big */
382     return;
383   }
384   received_msg = GNUNET_malloc (size);
385   received_msg->header.size = htons (size);
386   received_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DV_RECV);
387   received_msg->distance = htonl (distance);
388   received_msg->sender = *origin;
389   memcpy (&received_msg[1], message, ntohs (message->size));
390   GNUNET_SERVER_notification_context_broadcast (nc, 
391                                                 &received_msg->header,
392                                                 GNUNET_YES);
393   GNUNET_free (received_msg);
394 }
395
396
397 /**
398  * Forward a control message to the plugin.
399  *
400  * @param message the message to send to the plugin
401  * @param distant_neighbor the original sender of the message
402  * @param distnace distance to the original sender of the message
403  */
404 static void
405 send_control_to_plugin (const struct GNUNET_MessageHeader *message)
406 {
407   GNUNET_SERVER_notification_context_broadcast (nc, 
408                                                 message,
409                                                 GNUNET_NO);
410 }
411
412
413 /**
414  * Give an (N)ACK message to the plugin, we transmitted a message for it.
415  *
416  * @param target peer that received the message
417  * @param uid plugin-chosen UID for the message
418  * @param nack GNUNET_NO to send ACK, GNUNET_YES to send NACK
419  */
420 static void
421 send_ack_to_plugin (const struct GNUNET_PeerIdentity *target, 
422                     uint32_t uid,
423                     int nack)
424 {
425   struct GNUNET_DV_AckMessage ack_msg;
426
427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
428               "Delivering ACK for message to peer `%s'\n",
429               GNUNET_i2s (target));
430   ack_msg.header.size = htons (sizeof (ack_msg));
431   ack_msg.header.type = htons ((GNUNET_YES == nack) 
432                                ? GNUNET_MESSAGE_TYPE_DV_SEND_NACK
433                                : GNUNET_MESSAGE_TYPE_DV_SEND_ACK);
434   ack_msg.uid = htonl (uid);
435   ack_msg.target = *target;
436   send_control_to_plugin (&ack_msg.header);
437 }
438
439
440 /**
441  * Send a DISTANCE_CHANGED message to the plugin.
442  *
443  * @param peer peer with a changed distance
444  * @param distance new distance to the peer
445  */
446 static void
447 send_distance_change_to_plugin (const struct GNUNET_PeerIdentity *peer, 
448                                 uint32_t distance)
449 {
450   struct GNUNET_DV_DistanceUpdateMessage du_msg;
451
452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
453               "Delivering DISTANCE_CHANGED for message about peer `%s'\n",
454               GNUNET_i2s (peer));
455   du_msg.header.size = htons (sizeof (du_msg));
456   du_msg.header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISTANCE_CHANGED);
457   du_msg.distance = htonl (distance);
458   du_msg.peer = *peer;
459   send_control_to_plugin (&du_msg.header);
460 }
461
462
463 /**
464  * Give a CONNECT message to the plugin.
465  *
466  * @param target peer that connected
467  * @param distance distance to the target
468  */
469 static void
470 send_connect_to_plugin (const struct GNUNET_PeerIdentity *target, 
471                         uint32_t distance)
472 {
473   struct GNUNET_DV_ConnectMessage cm;
474
475   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
476               "Delivering CONNECT about peer `%s'\n",
477               GNUNET_i2s (target));
478   cm.header.size = htons (sizeof (cm));
479   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
480   cm.distance = htonl (distance);
481   cm.peer = *target;
482   send_control_to_plugin (&cm.header);
483 }
484
485
486 /**
487  * Give a DISCONNECT message to the plugin.
488  *
489  * @param target peer that disconnected
490  */
491 static void
492 send_disconnect_to_plugin (const struct GNUNET_PeerIdentity *target)
493 {
494   struct GNUNET_DV_DisconnectMessage dm;
495
496   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
497               "Delivering DISCONNECT about peer `%s'\n",
498               GNUNET_i2s (target));
499   dm.header.size = htons (sizeof (dm));
500   dm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISCONNECT);
501   dm.reserved = htonl (0);
502   dm.peer = *target;
503   send_control_to_plugin (&dm.header);
504 }
505
506
507 /**
508  * Function called to transfer a message to another peer
509  * via core.
510  *
511  * @param cls closure with the direct neighbor
512  * @param size number of bytes available in buf
513  * @param buf where the callee should write the message
514  * @return number of bytes written to buf
515  */
516 static size_t
517 core_transmit_notify (void *cls, size_t size, void *buf)
518 {
519   struct DirectNeighbor *dn = cls;
520   char *cbuf = buf;
521   struct PendingMessage *pending;
522   size_t off;
523   size_t msize;
524
525   dn->cth = NULL;
526   if (NULL == buf)
527   {
528     /* peer disconnected */
529     return 0;
530   }
531   off = 0;
532   pending = dn->pm_head;
533   off = 0;
534   while ( (NULL != (pending = dn->pm_head)) &&
535           (size >= off + (msize = ntohs (pending->msg->size))))
536   {
537     dn->pm_queue_size--;
538     GNUNET_CONTAINER_DLL_remove (dn->pm_head,
539                                  dn->pm_tail,
540                                  pending);
541     memcpy (&cbuf[off], pending->msg, msize);
542     if (0 != pending->uid) 
543       send_ack_to_plugin (&pending->ultimate_target,
544                           pending->uid,
545                           GNUNET_NO);
546     GNUNET_free (pending);
547     off += msize;
548   }
549   if (NULL != dn->pm_head)
550     dn->cth =
551       GNUNET_CORE_notify_transmit_ready (core_api,
552                                          GNUNET_YES /* cork */,
553                                          0 /* priority */,
554                                          GNUNET_TIME_UNIT_FOREVER_REL,
555                                          &dn->peer,
556                                          msize,                                  
557                                          &core_transmit_notify, dn);
558   return off;
559 }
560
561
562 /**
563  * Forward the given payload to the given target.
564  *
565  * @param target where to send the message
566  * @param uid unique ID for the message
567  * @param ultimate_target ultimate recipient for the message
568  * @param distance expected (remaining) distance to the target
569  * @param sender original sender of the message
570  * @param payload payload of the message
571  */
572 static void
573 forward_payload (struct DirectNeighbor *target,
574                  uint32_t distance,
575                  uint32_t uid,
576                  const struct GNUNET_PeerIdentity *sender,
577                  const struct GNUNET_PeerIdentity *ultimate_target,
578                  const struct GNUNET_MessageHeader *payload)
579 {
580   struct PendingMessage *pm;
581   struct RouteMessage *rm;
582   size_t msize;
583
584   if ( (target->pm_queue_size >= MAX_QUEUE_SIZE) &&
585        (0 != memcmp (sender,
586                      &my_identity,
587                      sizeof (struct GNUNET_PeerIdentity))) )
588   {
589     GNUNET_break (0 == uid);
590     return;
591   }
592   msize = sizeof (struct RouteMessage) + ntohs (payload->size);
593   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
594   {
595     GNUNET_break (0);
596     return;
597   }
598   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
599   pm->ultimate_target = *ultimate_target;
600   pm->uid = uid;
601   pm->msg = (const struct GNUNET_MessageHeader *) &pm[1];
602   rm = (struct RouteMessage *) &pm[1];
603   rm->header.size = htons ((uint16_t) msize);
604   rm->header.type = htons (GNUNET_MESSAGE_TYPE_DV_ROUTE);
605   rm->distance = htonl (distance);
606   rm->target = target->peer;
607   rm->sender = *sender;
608   memcpy (&rm[1], payload, ntohs (payload->size));
609   GNUNET_CONTAINER_DLL_insert_tail (target->pm_head,
610                                     target->pm_tail,
611                                     pm);
612   target->pm_queue_size++;
613   if (NULL == target->cth)
614     target->cth = GNUNET_CORE_notify_transmit_ready (core_api,
615                                                      GNUNET_YES /* cork */,
616                                                      0 /* priority */,
617                                                      GNUNET_TIME_UNIT_FOREVER_REL,
618                                                      &target->peer,
619                                                      msize,                                      
620                                                      &core_transmit_notify, target);
621 }
622
623
624 /**
625  * Find a free slot for storing a 'route' in the 'consensi'
626  * set at the given distance.
627  *
628  * @param distance distance to use for the set slot
629  */
630 static unsigned int
631 get_consensus_slot (uint32_t distance)
632 {
633   struct ConsensusSet *cs;
634   unsigned int i;
635
636   cs = &consensi[distance];
637   i = 0;
638   while ( (i < cs->array_length) &&
639           (NULL != cs->targets[i]) ) i++;
640   if (i == cs->array_length)
641     GNUNET_array_grow (cs->targets,
642                        cs->array_length,
643                        cs->array_length * 2 + 2);
644   return i;
645 }
646
647
648 /**
649  * Allocate a slot in the consensus set for a route.
650  *
651  * @param route route to initialize
652  * @param distance which consensus set to use
653  */
654 static void
655 allocate_route (struct Route *route,
656                 uint32_t distance)
657 {
658   unsigned int i;
659
660   i = get_consensus_slot (distance);
661   route->set_offset = i;
662   consensi[distance].targets[i] = route;
663   route->target.distance = htonl (distance);
664 }
665
666
667 /**
668  * Release a slot in the consensus set for a route.
669  *
670  * @param route route to release the slot from
671  */
672 static void
673 release_route (struct Route *route)
674 {
675   consensi[ntohl (route->target.distance)].targets[route->set_offset] = NULL;
676   route->set_offset = UINT_MAX; /* indicate invalid slot */
677 }
678
679
680 /**
681  * Move a route from one consensus set to another.
682  *
683  * @param route route to move
684  * @param new_distance new distance for the route (destination set)
685  */
686 static void
687 move_route (struct Route *route,
688             uint32_t new_distance)
689 {
690   unsigned int i;
691
692   release_route (route);
693   i = get_consensus_slot (new_distance);
694   route->set_offset = i;
695   consensi[new_distance].targets[i] = route;     
696   route->target.distance = htonl (new_distance);
697 }
698
699
700 /**
701  * Start creating a new consensus from scratch.
702  *
703  * @param cls the 'struct DirectNeighbor' of the peer we're building
704  *        a routing consensus with
705  * @param tc scheduler context
706  */    
707 static void
708 start_consensus (void *cls,
709                  const struct GNUNET_SCHEDULER_TaskContext *tc);
710
711
712 /**
713  * Method called whenever a peer connects.
714  *
715  * @param cls closure
716  * @param peer peer identity this notification is about
717  * @param atsi performance data
718  * @param atsi_count number of entries in atsi
719  */
720 static void
721 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
722                      const struct GNUNET_ATS_Information *atsi,
723                      unsigned int atsi_count)
724 {
725   struct DirectNeighbor *neighbor;
726   struct Route *route;
727   uint32_t distance;
728  
729   /* Check for connect to self message */
730   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
731     return;
732   distance = get_atsi_distance (atsi, atsi_count);
733   neighbor = GNUNET_CONTAINER_multihashmap_get (direct_neighbors, 
734                                                 &peer->hashPubKey);
735   if (NULL != neighbor)
736   {
737     GNUNET_break (0);
738     return;
739   }
740   if (DIRECT_NEIGHBOR_COST != distance) 
741     return; /* is a DV-neighbor */
742   GNUNET_STATISTICS_update (stats,
743                             "# peers connected (1-hop)",
744                             1, GNUNET_NO);
745   neighbor = GNUNET_malloc (sizeof (struct DirectNeighbor));
746   neighbor->peer = *peer;
747   GNUNET_assert (GNUNET_YES ==
748                  GNUNET_CONTAINER_multihashmap_put (direct_neighbors,
749                                                     &peer->hashPubKey,
750                                                     neighbor,
751                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
752   route = GNUNET_CONTAINER_multihashmap_get (all_routes, 
753                                              &peer->hashPubKey);
754   if (NULL != route)  
755   {
756     send_disconnect_to_plugin (peer);
757     release_route (route);
758     GNUNET_free (route);
759   }
760   neighbor->consensus_task = GNUNET_SCHEDULER_add_now (&start_consensus,
761                                                        neighbor);
762 }
763
764
765 /**
766  * Called for each 'target' in a neighbor table to free the associated memory.
767  *
768  * @param cls NULL
769  * @param key key of the value
770  * @param value value to free
771  * @return GNUNET_OK to continue to iterate
772  */
773 static int
774 free_targets (void *cls,
775               const struct GNUNET_HashCode *key,
776               void *value)
777 {
778   GNUNET_free (value);
779   return GNUNET_OK;
780 }
781
782
783 /**
784  * Multihashmap iterator for checking if a given route is
785  * (now) useful to this peer.
786  *
787  * @param cls the direct neighbor for the given route
788  * @param key key value stored under
789  * @param value a 'struct Target' that may or may not be useful; not that
790  *        the distance in 'target' does not include the first hop yet
791  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
792  */
793 static int
794 check_possible_route (void *cls, const struct GNUNET_HashCode * key, void *value)
795 {
796   struct DirectNeighbor *neighbor = cls;
797   struct Target *target = value;
798   struct Route *route;
799   
800   route = GNUNET_CONTAINER_multihashmap_get (all_routes,
801                                            key);
802   if (NULL != route)
803   {
804     if (ntohl (route->target.distance) > ntohl (target->distance) + 1)
805     {
806       /* this 'target' is cheaper than the existing route; switch to alternative route! */
807       move_route (route, ntohl (target->distance) + 1);
808       route->next_hop = neighbor;
809       send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
810     }
811     return GNUNET_YES; /* got a route to this target already */
812   }
813   route = GNUNET_malloc (sizeof (struct Route));
814   route->next_hop = neighbor;
815   route->target.distance = htonl (ntohl (target->distance) + 1);
816   route->target.peer = target->peer;
817   allocate_route (route, ntohl (route->target.distance));
818   GNUNET_assert (GNUNET_YES ==
819                  GNUNET_CONTAINER_multihashmap_put (all_routes,
820                                                     &route->target.peer.hashPubKey,
821                                                     route,
822                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
823   send_connect_to_plugin (&route->target.peer, ntohl (target->distance));
824   return GNUNET_YES;
825 }
826
827
828 /**
829  * Multihashmap iterator for finding routes that were previously
830  * "hidden" due to a better route (called after a disconnect event).
831  *
832  * @param cls NULL
833  * @param key peer identity of the given direct neighbor
834  * @param value a 'struct DirectNeighbor' to check for additional routes
835  * @return GNUNET_YES to continue iteration
836  */
837 static int
838 refresh_routes (void *cls, const struct GNUNET_HashCode * key, void *value)
839 {
840   struct DirectNeighbor *neighbor = value;
841
842   if (NULL != neighbor->neighbor_table)
843     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
844                                            &check_possible_route,
845                                            neighbor);
846   return GNUNET_YES;
847 }
848
849
850 /**
851  * Check if a target was removed from the set of the other peer; if so,
852  * if we also used it for our route, we need to remove it from our
853  * 'all_routes' set (and later check if an alternative path now exists).
854  *
855  * @param cls the 'struct DirectNeighbor'
856  * @param key peer identity for the target
857  * @param value a 'struct Target' previously reachable via the given neighbor
858  */
859 static int
860 check_target_removed (void *cls,
861                       const struct GNUNET_HashCode *key,
862                       void *value)
863 {
864   struct DirectNeighbor *neighbor = cls;
865   struct Target *new_target;
866   struct Route *current_route;
867
868   new_target = GNUNET_CONTAINER_multihashmap_get (neighbor->neighbor_table_consensus,
869                                                   key);
870   if (NULL == new_target)
871   {
872     /* target was revoked, check if it was used */
873     current_route = GNUNET_CONTAINER_multihashmap_get (all_routes,
874                                                        key);
875     if ( (NULL == current_route) ||
876          (current_route->next_hop != neighbor) )
877     {
878       /* didn't matter, wasn't used */
879       return GNUNET_OK;
880     }
881     /* remove existing route */
882     GNUNET_assert (GNUNET_YES ==
883                    GNUNET_CONTAINER_multihashmap_remove (all_routes, key, current_route));
884     send_disconnect_to_plugin (&current_route->target.peer);
885     GNUNET_free (current_route);
886     neighbor->target_removed = GNUNET_YES;
887     return GNUNET_OK;
888   }
889   return GNUNET_OK;
890 }
891
892
893 /**
894  * Check if a target was added to the set of the other peer; if it
895  * was added or impoves the existing route, do the needed updates.
896  *
897  * @param cls the 'struct DirectNeighbor'
898  * @param key peer identity for the target
899  * @param value a 'struct Target' now reachable via the given neighbor
900  */
901 static int
902 check_target_added (void *cls,
903                       const struct GNUNET_HashCode *key,
904                       void *value)
905 {
906   struct DirectNeighbor *neighbor = cls;
907   struct Target *target = value;
908   struct Route *current_route;
909
910   /* target was revoked, check if it was used */
911   current_route = GNUNET_CONTAINER_multihashmap_get (all_routes,
912                                                      key);
913   if (NULL != current_route)
914   {
915     /* route exists */
916     if (current_route->next_hop == neighbor)
917     {
918       /* we had the same route before, no change */
919       if (ntohl (target->distance) + 1 != ntohl (current_route->target.distance))
920       {
921         current_route->target.distance = htonl (ntohl (target->distance) + 1);
922         send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
923       }
924       return GNUNET_OK;
925     }
926     if (ntohl (current_route->target.distance) >= ntohl (target->distance) + 1)
927     {
928       /* alternative, shorter route exists, ignore */
929       return GNUNET_OK;
930     }
931     /* new route is better than the existing one, take over! */
932     /* NOTE: minor security issue: malicious peers may advertise
933        very short routes to take over longer paths; as we don't
934        check that the shorter routes actually work, a malicious
935        direct neighbor can use this to DoS our long routes */
936     current_route->next_hop = neighbor;
937     current_route->target.distance = htonl (ntohl (target->distance) + 1);
938     send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
939     return GNUNET_OK;
940   }
941   /* new route */
942   current_route = GNUNET_malloc (sizeof (struct Route));
943   current_route->next_hop = neighbor;
944   current_route->target.peer = target->peer;
945   current_route->target.distance = htonl (ntohl (target->distance) + 1);
946   GNUNET_assert (GNUNET_YES ==
947                  GNUNET_CONTAINER_multihashmap_put (all_routes,
948                                                     &current_route->target.peer.hashPubKey,
949                                                     current_route,
950                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
951   send_connect_to_plugin (&current_route->target.peer,
952                           ntohl (current_route->target.distance));
953   return GNUNET_OK;
954 }
955
956
957
958 /**
959  * The consensus has concluded, clean up and schedule the next one.
960  *
961  * @param cls the 'struct GNUNET_DirectNeighbor' with which we created the consensus
962  * @param group FIXME
963  */
964 static void
965 consensus_done_cb (void *cls,
966                    const struct GNUNET_CONSENSUS_Group *group)
967 {
968   struct DirectNeighbor *neighbor = cls;
969
970   GNUNET_CONSENSUS_destroy (neighbor->consensus);
971   neighbor->consensus = NULL;
972   /* remove targets that disappeared */
973   neighbor->target_removed = GNUNET_NO;
974   GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
975                                          &check_target_removed,
976                                          neighbor);
977   if (GNUNET_YES == neighbor->target_removed)
978   {
979     /* check if we got an alternative for the removed routes */
980     GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
981                                            &refresh_routes,
982                                            NULL);    
983   }
984   /* add targets that appeared (and check for improved routes) */
985   GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table_consensus,
986                                          &check_target_added,
987                                          neighbor);
988   if (NULL != neighbor->neighbor_table)
989   {
990     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
991                                            &free_targets,
992                                            NULL);
993     GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table);
994     neighbor->neighbor_table = NULL;
995   }
996   neighbor->neighbor_table = neighbor->neighbor_table_consensus;
997   neighbor->neighbor_table_consensus = NULL;
998   neighbor->consensus_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
999                                                            &start_consensus,
1000                                                            neighbor);
1001 }
1002
1003
1004 /**
1005  * We inserted the last element into the consensus, get ready to
1006  * insert the next element into the consensus or conclude if
1007  * we're done.
1008  *
1009  * @param cls the 'struct DirectNeighbor' of the peer we're building
1010  *        a routing consensus with
1011  * @param success GNUNET_OK if the last element was added successfully,
1012  *                GNUNET_SYSERR if we failed
1013  */
1014 static void
1015 insert_next_element (void *cls,
1016                      int success)
1017 {
1018   struct DirectNeighbor *neighbor = cls;
1019   struct GNUNET_CONSENSUS_Element element;
1020
1021   while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
1022           (consensi[neighbor->consensus_insertion_distance].array_length == neighbor->consensus_insertion_offset) )
1023   {
1024     neighbor->consensus_insertion_offset = 0;
1025     neighbor->consensus_insertion_distance++;
1026     /* skip over NULL entries */
1027     while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
1028             (consensi[neighbor->consensus_insertion_distance].array_length < neighbor->consensus_insertion_offset) &&
1029             (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
1030       neighbor->consensus_insertion_offset++;
1031   }
1032   if (DEFAULT_FISHEYE_DEPTH - 1 == neighbor->consensus_insertion_distance)
1033   {
1034     /* we're done, conclude! */
1035     GNUNET_CONSENSUS_conclude (neighbor->consensus,
1036                                GNUNET_DV_CONSENSUS_FREQUENCY,
1037                                2 /* both peers */,
1038                                &consensus_done_cb,
1039                                neighbor);
1040     return;
1041   }
1042   element.size = sizeof (struct Target);
1043   element.data = &consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset++]->target;
1044
1045   /* skip over NULL entries */
1046   while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
1047           (consensi[neighbor->consensus_insertion_distance].array_length < neighbor->consensus_insertion_offset) &&
1048           (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
1049     neighbor->consensus_insertion_offset++;  
1050   GNUNET_CONSENSUS_insert (neighbor->consensus,
1051                            &element,
1052                            &insert_next_element,
1053                            neighbor);
1054 }
1055
1056
1057 /**
1058  * We have learned a new route from the other peer.  Add it to the
1059  * route set we're building.
1060  *
1061  * @param cls the 'struct DirectNeighbor' we're building the consensus with
1062  * @param element the new element we have learned
1063  * @return GNUNET_OK if the valid is well-formed and should be added to the consensus,
1064  *         GNUNET_SYSERR if the element should be ignored and not be propagated
1065  */
1066 static int
1067 learn_route_cb (void *cls,
1068                 const struct GNUNET_CONSENSUS_Element *element)
1069 {
1070   struct DirectNeighbor *neighbor = cls;
1071   struct Target *target;
1072
1073   if (NULL == element)
1074   {
1075     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1076                 "Failed to establish DV consensus, will try again later\n");
1077     GNUNET_CONSENSUS_destroy (neighbor->consensus);
1078     if (NULL != neighbor->neighbor_table_consensus)
1079     {
1080       GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table_consensus,
1081                                              &free_targets,
1082                                              NULL);
1083       GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table_consensus);
1084       neighbor->neighbor_table_consensus = NULL;
1085     }
1086     neighbor->consensus = NULL;
1087     neighbor->consensus_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1088                                                              &start_consensus,
1089                                                              neighbor);
1090     return GNUNET_SYSERR;
1091   }
1092   if (sizeof (struct Target) != element->size)
1093   {
1094     GNUNET_break_op (0);
1095     return GNUNET_SYSERR;
1096   }
1097   target = GNUNET_malloc (sizeof (struct Target));
1098   memcpy (target, element->data, sizeof (struct Target));
1099   if (GNUNET_YES !=
1100       GNUNET_CONTAINER_multihashmap_put (neighbor->neighbor_table_consensus,
1101                                          &target->peer.hashPubKey,
1102                                          target,
1103                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1104   {
1105     GNUNET_break_op (0);
1106     GNUNET_free (target);
1107     return GNUNET_SYSERR;
1108   }
1109   return GNUNET_OK;
1110 }
1111
1112
1113 /**
1114  * Start creating a new consensus from scratch.
1115  *
1116  * @param cls the 'struct DirectNeighbor' of the peer we're building
1117  *        a routing consensus with
1118  * @param tc scheduler context
1119  */    
1120 static void
1121 start_consensus (void *cls,
1122                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1123 {
1124   struct DirectNeighbor *neighbor = cls;
1125   struct GNUNET_HashCode session_id;
1126   struct GNUNET_HashCode real_session_id;
1127
1128   neighbor->consensus_task = GNUNET_SCHEDULER_NO_TASK;
1129   neighbor->consensus_insertion_offset = 0;
1130   neighbor->consensus_insertion_distance = 0;
1131   GNUNET_assert (NULL == neighbor->neighbor_table_consensus);
1132   GNUNET_assert (NULL == neighbor->consensus);
1133   neighbor->neighbor_table_consensus = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
1134   /* construct session ID seed as XOR of both peer's identities */
1135   GNUNET_CRYPTO_hash_xor (&my_identity.hashPubKey, 
1136                           &neighbor->peer.hashPubKey, 
1137                           &session_id);
1138   /* make sure session ID is unique across applications by salting it with 'DV' */
1139   GNUNET_CRYPTO_hkdf (&real_session_id, sizeof (real_session_id),
1140                       GCRY_MD_SHA512, GCRY_MD_SHA256,
1141                       "DV-SALT", 2,
1142                       &session_id, sizeof (session_id),
1143                       NULL, 0);
1144   neighbor->consensus = GNUNET_CONSENSUS_create (cfg,
1145                                                  1,
1146                                                  &neighbor->peer,
1147                                                  &real_session_id,
1148                                                  &learn_route_cb,
1149                                                  neighbor);
1150   if (NULL == neighbor->consensus)
1151   {
1152     neighbor->consensus_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1153                                                              &start_consensus,
1154                                                              neighbor);
1155     return;
1156   }
1157   insert_next_element (neighbor, GNUNET_OK);
1158 }
1159
1160
1161 /**
1162  * Core handler for DV data messages.  Whatever this message
1163  * contains all we really have to do is rip it out of its
1164  * DV layering and give it to our pal the DV plugin to report
1165  * in with.
1166  *
1167  * @param cls closure
1168  * @param peer peer which sent the message (immediate sender)
1169  * @param message the message
1170  * @param atsi transport ATS information (latency, distance, etc.)
1171  * @param atsi_count number of entries in atsi
1172  * @return GNUNET_OK on success, GNUNET_SYSERR if the other peer violated the protocol
1173  */
1174 static int
1175 handle_dv_route_message (void *cls, const struct GNUNET_PeerIdentity *peer,
1176                          const struct GNUNET_MessageHeader *message,
1177                          const struct GNUNET_ATS_Information *atsi,
1178                          unsigned int atsi_count)
1179 {
1180   const struct RouteMessage *rm;
1181   const struct GNUNET_MessageHeader *payload;
1182   struct Route *route;
1183
1184   if (ntohs (message->size) < sizeof (struct RouteMessage) + sizeof (struct GNUNET_MessageHeader))
1185   {
1186     GNUNET_break_op (0);
1187     return GNUNET_SYSERR;
1188   }
1189   rm = (const struct RouteMessage *) message;
1190   payload = (const struct GNUNET_MessageHeader *) &rm[1];
1191   if (ntohs (message->size) != sizeof (struct RouteMessage) + ntohs (payload->size))
1192   {
1193     GNUNET_break_op (0);
1194     return GNUNET_SYSERR;
1195   }
1196   if (0 == memcmp (&rm->target,
1197                    &my_identity,
1198                    sizeof (struct GNUNET_PeerIdentity)))
1199   {
1200     /* message is for me, check reverse route! */
1201     route = GNUNET_CONTAINER_multihashmap_get (all_routes,
1202                                                &rm->sender.hashPubKey);
1203     if (NULL == route)
1204     {
1205       /* don't have reverse route, drop */
1206       GNUNET_STATISTICS_update (stats,
1207                                 "# message discarded (no reverse route)",
1208                                 1, GNUNET_NO);
1209       return GNUNET_OK;
1210     }
1211     send_data_to_plugin (payload,
1212                          &rm->sender,
1213                          ntohl (route->target.distance));
1214     return GNUNET_OK;
1215   }
1216   route = GNUNET_CONTAINER_multihashmap_get (all_routes,
1217                                              &rm->target.hashPubKey);
1218   if (NULL == route)
1219   {
1220     GNUNET_STATISTICS_update (stats,
1221                               "# messages discarded (no route)",
1222                               1, GNUNET_NO);
1223     return GNUNET_OK;
1224   }
1225   if (ntohl (route->target.distance) > ntohl (rm->distance) + 1)
1226   {
1227     GNUNET_STATISTICS_update (stats,
1228                               "# messages discarded (target too far)",
1229                               1, GNUNET_NO);
1230     return GNUNET_OK;
1231   }
1232   forward_payload (route->next_hop,
1233                    ntohl (route->target.distance),
1234                    0,
1235                    &rm->target,
1236                    &rm->sender,
1237                    payload);
1238   return GNUNET_OK;  
1239 }
1240
1241
1242 /**
1243  * Service server's handler for message send requests (which come
1244  * bubbling up to us through the DV plugin).
1245  *
1246  * @param cls closure
1247  * @param client identification of the client
1248  * @param message the actual message
1249  */
1250 static void
1251 handle_dv_send_message (void *cls, struct GNUNET_SERVER_Client *client,
1252                         const struct GNUNET_MessageHeader *message)
1253 {
1254   struct Route *route;
1255   const struct GNUNET_DV_SendMessage *msg;
1256   const struct GNUNET_MessageHeader *payload;
1257
1258   if (ntohs (message->size) < sizeof (struct GNUNET_DV_SendMessage) + sizeof (struct GNUNET_MessageHeader))
1259   {
1260     GNUNET_break (0);
1261     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1262     return;
1263   }
1264   msg = (const struct GNUNET_DV_SendMessage *) message;
1265   GNUNET_break (0 != ntohl (msg->uid));
1266   payload = (const struct GNUNET_MessageHeader *) &msg[1];
1267   if (ntohs (message->size) != sizeof (struct GNUNET_DV_SendMessage) + ntohs (payload->size))
1268   {
1269     GNUNET_break (0);
1270     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1271     return;
1272   }
1273   route = GNUNET_CONTAINER_multihashmap_get (all_routes,
1274                                              &msg->target.hashPubKey);
1275   if (NULL == route)
1276   {
1277     /* got disconnected */
1278     GNUNET_STATISTICS_update (stats,
1279                               "# local messages discarded (no route)",
1280                               1, GNUNET_NO);
1281     send_ack_to_plugin (&msg->target, ntohl (msg->uid), GNUNET_YES);
1282     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1283     return;
1284   }
1285   forward_payload (route->next_hop,
1286                    ntohl (route->target.distance),
1287                    htonl (msg->uid),
1288                    &msg->target,
1289                    &my_identity,
1290                    payload);
1291   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1292 }
1293
1294
1295 /**
1296  * Multihashmap iterator for freeing routes that go via a particular
1297  * neighbor that disconnected and is thus no longer available.
1298  *
1299  * @param cls the direct neighbor that is now unavailable
1300  * @param key key value stored under
1301  * @param value a 'struct Route' that may or may not go via neighbor
1302  *
1303  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1304  */
1305 static int
1306 cull_routes (void *cls, const struct GNUNET_HashCode * key, void *value)
1307 {
1308   struct DirectNeighbor *neighbor = cls;
1309   struct Route *route = value;
1310
1311   if (route->next_hop != neighbor)
1312     return GNUNET_YES; /* not affected */
1313   GNUNET_assert (GNUNET_YES ==
1314                  GNUNET_CONTAINER_multihashmap_remove (all_routes, key, value));
1315   release_route (route);
1316   send_disconnect_to_plugin (&route->target.peer);
1317   GNUNET_free (route);
1318   return GNUNET_YES;
1319 }
1320
1321
1322 /**
1323  * Cleanup all of the data structures associated with a given neighbor.
1324  *
1325  * @param neighbor neighbor to clean up
1326  */
1327 static void
1328 cleanup_neighbor (struct DirectNeighbor *neighbor)
1329 {
1330   struct PendingMessage *pending;
1331
1332   while (NULL != (pending = neighbor->pm_head))
1333   {
1334     neighbor->pm_queue_size--;
1335     GNUNET_CONTAINER_DLL_remove (neighbor->pm_head,
1336                                  neighbor->pm_tail,
1337                                  pending);    
1338     GNUNET_free (pending);
1339   }
1340   GNUNET_CONTAINER_multihashmap_iterate (all_routes,
1341                                          &cull_routes,
1342                                          neighbor);
1343   if (NULL != neighbor->cth)
1344   {
1345     GNUNET_CORE_notify_transmit_ready_cancel (neighbor->cth);
1346     neighbor->cth = NULL;
1347   }
1348   if (NULL != neighbor->neighbor_table_consensus)
1349   {
1350     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table_consensus,
1351                                            &free_targets,
1352                                            NULL);
1353     GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table_consensus);
1354     neighbor->neighbor_table_consensus = NULL;
1355   }
1356   if (NULL != neighbor->neighbor_table)
1357   {
1358     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
1359                                            &free_targets,
1360                                            NULL);
1361     GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table);
1362     neighbor->neighbor_table = NULL;
1363   }
1364   if (GNUNET_SCHEDULER_NO_TASK != neighbor->consensus_task)
1365   {
1366     GNUNET_SCHEDULER_cancel (neighbor->consensus_task);
1367     neighbor->consensus_task = GNUNET_SCHEDULER_NO_TASK;
1368   }
1369   if (NULL != neighbor->consensus)
1370   {
1371     GNUNET_CONSENSUS_destroy (neighbor->consensus);
1372     neighbor->consensus = NULL;
1373   }
1374   GNUNET_assert (GNUNET_YES ==
1375                  GNUNET_CONTAINER_multihashmap_remove (direct_neighbors, 
1376                                                        &neighbor->peer.hashPubKey,
1377                                                        neighbor));
1378   GNUNET_free (neighbor);
1379 }
1380
1381
1382 /**
1383  * Method called whenever a given peer disconnects.
1384  *
1385  * @param cls closure
1386  * @param peer peer identity this notification is about
1387  */
1388 static void
1389 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1390 {
1391   struct DirectNeighbor *neighbor;
1392
1393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1394               "Received core peer disconnect message for peer `%s'!\n",
1395               GNUNET_i2s (peer));
1396   /* Check for disconnect from self message */
1397   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1398     return;
1399   neighbor =
1400       GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
1401   if (NULL == neighbor)
1402   {
1403     /* must have been a DV-neighbor, ignore */
1404     return;
1405   }
1406   GNUNET_STATISTICS_update (stats,
1407                             "# peers connected (1-hop)",
1408                             -1, GNUNET_NO);  
1409   cleanup_neighbor (neighbor);
1410   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
1411                                          &refresh_routes,
1412                                          NULL);
1413 }
1414
1415
1416 /**
1417  * Multihashmap iterator for freeing routes.  Should never be called.
1418  *
1419  * @param cls NULL
1420  * @param key key value stored under
1421  * @param value the route to be freed
1422  *
1423  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1424  */
1425 static int
1426 free_route (void *cls, const struct GNUNET_HashCode * key, void *value)
1427 {
1428   struct Route *route = value;
1429
1430   GNUNET_break (0);
1431   GNUNET_assert (GNUNET_YES ==
1432                  GNUNET_CONTAINER_multihashmap_remove (all_routes, key, value));
1433   release_route (route);
1434   send_disconnect_to_plugin (&route->target.peer);
1435   GNUNET_free (route);
1436   return GNUNET_YES;
1437 }
1438
1439
1440 /**
1441  * Multihashmap iterator for freeing direct neighbors. Should never be called.
1442  *
1443  * @param cls NULL
1444  * @param key key value stored under
1445  * @param value the direct neighbor to be freed
1446  *
1447  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1448  */
1449 static int
1450 free_direct_neighbors (void *cls, const struct GNUNET_HashCode * key, void *value)
1451 {
1452   struct DirectNeighbor *neighbor = value;
1453
1454   GNUNET_break (0);
1455   cleanup_neighbor (neighbor);
1456   return GNUNET_YES;
1457 }
1458
1459
1460 /**
1461  * Task run during shutdown.
1462  *
1463  * @param cls unused
1464  * @param tc unused
1465  */
1466 static void
1467 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1468 {
1469   unsigned int i;
1470
1471   GNUNET_CORE_disconnect (core_api);
1472   core_api = NULL;
1473   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
1474                                          &free_direct_neighbors, NULL);
1475   GNUNET_CONTAINER_multihashmap_iterate (all_routes,
1476                                          &free_route, NULL);
1477   GNUNET_CONTAINER_multihashmap_destroy (direct_neighbors);
1478   GNUNET_CONTAINER_multihashmap_destroy (all_routes);
1479   GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1480   stats = NULL;
1481   GNUNET_SERVER_notification_context_destroy (nc);
1482   nc = NULL;
1483   for (i=0;i<DEFAULT_FISHEYE_DEPTH - 1;i++)
1484     GNUNET_array_grow (consensi[i].targets,
1485                        consensi[i].array_length,
1486                        0);
1487 }
1488
1489
1490 /**
1491  * Notify newly connected client about an existing route.
1492  *
1493  * @param cls the 'struct GNUNET_SERVER_Client'
1494  * @param key peer identity
1495  * @param value the XXX.
1496  * @return GNUNET_OK (continue to iterate)
1497  */
1498 static int
1499 add_route (void *cls,
1500            const struct GNUNET_HashCode *key,
1501            void *value)
1502 {
1503   struct GNUNET_SERVER_Client *client = cls;
1504   struct Route *route = value;
1505   struct GNUNET_DV_ConnectMessage cm;
1506   
1507   cm.header.size = htons (sizeof (cm));
1508   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
1509   cm.distance = htonl (route->target.distance);
1510   cm.peer = route->target.peer;
1511
1512   GNUNET_SERVER_notification_context_unicast (nc, 
1513                                               client,
1514                                               &cm.header,
1515                                               GNUNET_NO);
1516   return GNUNET_OK;
1517 }
1518
1519
1520 /**
1521  * Handle START-message.  This is the first message sent to us
1522  * by the client (can only be one!).
1523  *
1524  * @param cls closure (always NULL)
1525  * @param client identification of the client
1526  * @param message the actual message
1527  */
1528 static void
1529 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
1530               const struct GNUNET_MessageHeader *message)
1531 {
1532   GNUNET_SERVER_notification_context_add (nc, client);  
1533   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1534   GNUNET_CONTAINER_multihashmap_iterate (all_routes,
1535                                          &add_route,
1536                                          client);
1537 }
1538
1539
1540 /**
1541  * Called on core init.
1542  *
1543  * @param cls unused
1544  * @param server legacy
1545  * @param identity this peer's identity
1546  */
1547 static void
1548 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1549            const struct GNUNET_PeerIdentity *identity)
1550 {
1551   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1552               "I am peer: %s\n",
1553               GNUNET_i2s (identity));
1554   my_identity = *identity;
1555 }
1556
1557
1558 /**
1559  * Process dv requests.
1560  *
1561  * @param cls closure
1562  * @param server the initialized server
1563  * @param c configuration to use
1564  */
1565 static void
1566 run (void *cls, struct GNUNET_SERVER_Handle *server,
1567      const struct GNUNET_CONFIGURATION_Handle *c)
1568 {
1569   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1570     {&handle_dv_route_message, GNUNET_MESSAGE_TYPE_DV_ROUTE, 0},
1571     {NULL, 0, 0}
1572   };
1573   static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
1574     {&handle_start, NULL, 
1575      GNUNET_MESSAGE_TYPE_DV_START, 
1576      sizeof (struct GNUNET_MessageHeader) },
1577     { &handle_dv_send_message, NULL, 
1578       GNUNET_MESSAGE_TYPE_DV_SEND, 
1579       0},
1580     {NULL, NULL, 0, 0}
1581   };
1582
1583   cfg = c;
1584   direct_neighbors = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
1585   all_routes = GNUNET_CONTAINER_multihashmap_create (65536, GNUNET_NO);
1586   core_api = GNUNET_CORE_connect (cfg, NULL,
1587                                   &core_init, 
1588                                   &handle_core_connect,
1589                                   &handle_core_disconnect,
1590                                   NULL, GNUNET_NO, 
1591                                   NULL, GNUNET_NO, 
1592                                   core_handlers);
1593
1594   if (NULL == core_api)
1595     return;
1596   nc = GNUNET_SERVER_notification_context_create (server,
1597                                                   MAX_QUEUE_SIZE_PLUGIN);
1598   stats = GNUNET_STATISTICS_create ("dv", cfg);
1599   GNUNET_SERVER_add_handlers (server, plugin_handlers);
1600   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1601                                 &shutdown_task, NULL);
1602 }
1603
1604
1605 /**
1606  * The main function for the dv service.
1607  *
1608  * @param argc number of arguments from the command line
1609  * @param argv command line arguments
1610  * @return 0 ok, 1 on error
1611  */
1612 int
1613 main (int argc, char *const *argv)
1614 {
1615   return (GNUNET_OK ==
1616           GNUNET_SERVICE_run (argc, argv, "dv", GNUNET_SERVICE_OPTION_NONE,
1617                               &run, NULL)) ? 0 : 1;
1618 }
1619
1620 /* end of gnunet-service-dv.c */