-doxygen
[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 distance 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  */
402 static void
403 send_control_to_plugin (const struct GNUNET_MessageHeader *message)
404 {
405   GNUNET_SERVER_notification_context_broadcast (nc, 
406                                                 message,
407                                                 GNUNET_NO);
408 }
409
410
411 /**
412  * Give an (N)ACK message to the plugin, we transmitted a message for it.
413  *
414  * @param target peer that received the message
415  * @param uid plugin-chosen UID for the message
416  * @param nack GNUNET_NO to send ACK, GNUNET_YES to send NACK
417  */
418 static void
419 send_ack_to_plugin (const struct GNUNET_PeerIdentity *target, 
420                     uint32_t uid,
421                     int nack)
422 {
423   struct GNUNET_DV_AckMessage ack_msg;
424
425   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
426               "Delivering ACK for message to peer `%s'\n",
427               GNUNET_i2s (target));
428   ack_msg.header.size = htons (sizeof (ack_msg));
429   ack_msg.header.type = htons ((GNUNET_YES == nack) 
430                                ? GNUNET_MESSAGE_TYPE_DV_SEND_NACK
431                                : GNUNET_MESSAGE_TYPE_DV_SEND_ACK);
432   ack_msg.uid = htonl (uid);
433   ack_msg.target = *target;
434   send_control_to_plugin (&ack_msg.header);
435 }
436
437
438 /**
439  * Send a DISTANCE_CHANGED message to the plugin.
440  *
441  * @param peer peer with a changed distance
442  * @param distance new distance to the peer
443  */
444 static void
445 send_distance_change_to_plugin (const struct GNUNET_PeerIdentity *peer, 
446                                 uint32_t distance)
447 {
448   struct GNUNET_DV_DistanceUpdateMessage du_msg;
449
450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
451               "Delivering DISTANCE_CHANGED for message about peer `%s'\n",
452               GNUNET_i2s (peer));
453   du_msg.header.size = htons (sizeof (du_msg));
454   du_msg.header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISTANCE_CHANGED);
455   du_msg.distance = htonl (distance);
456   du_msg.peer = *peer;
457   send_control_to_plugin (&du_msg.header);
458 }
459
460
461 /**
462  * Give a CONNECT message to the plugin.
463  *
464  * @param target peer that connected
465  * @param distance distance to the target
466  */
467 static void
468 send_connect_to_plugin (const struct GNUNET_PeerIdentity *target, 
469                         uint32_t distance)
470 {
471   struct GNUNET_DV_ConnectMessage cm;
472
473   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
474               "Delivering CONNECT about peer `%s'\n",
475               GNUNET_i2s (target));
476   cm.header.size = htons (sizeof (cm));
477   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
478   cm.distance = htonl (distance);
479   cm.peer = *target;
480   send_control_to_plugin (&cm.header);
481 }
482
483
484 /**
485  * Give a DISCONNECT message to the plugin.
486  *
487  * @param target peer that disconnected
488  */
489 static void
490 send_disconnect_to_plugin (const struct GNUNET_PeerIdentity *target)
491 {
492   struct GNUNET_DV_DisconnectMessage dm;
493
494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
495               "Delivering DISCONNECT about peer `%s'\n",
496               GNUNET_i2s (target));
497   dm.header.size = htons (sizeof (dm));
498   dm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISCONNECT);
499   dm.reserved = htonl (0);
500   dm.peer = *target;
501   send_control_to_plugin (&dm.header);
502 }
503
504
505 /**
506  * Function called to transfer a message to another peer
507  * via core.
508  *
509  * @param cls closure with the direct neighbor
510  * @param size number of bytes available in buf
511  * @param buf where the callee should write the message
512  * @return number of bytes written to buf
513  */
514 static size_t
515 core_transmit_notify (void *cls, size_t size, void *buf)
516 {
517   struct DirectNeighbor *dn = cls;
518   char *cbuf = buf;
519   struct PendingMessage *pending;
520   size_t off;
521   size_t msize;
522
523   dn->cth = NULL;
524   if (NULL == buf)
525   {
526     /* peer disconnected */
527     return 0;
528   }
529   off = 0;
530   pending = dn->pm_head;
531   off = 0;
532   while ( (NULL != (pending = dn->pm_head)) &&
533           (size >= off + (msize = ntohs (pending->msg->size))))
534   {
535     dn->pm_queue_size--;
536     GNUNET_CONTAINER_DLL_remove (dn->pm_head,
537                                  dn->pm_tail,
538                                  pending);
539     memcpy (&cbuf[off], pending->msg, msize);
540     if (0 != pending->uid) 
541       send_ack_to_plugin (&pending->ultimate_target,
542                           pending->uid,
543                           GNUNET_NO);
544     GNUNET_free (pending);
545     off += msize;
546   }
547   if (NULL != dn->pm_head)
548     dn->cth =
549       GNUNET_CORE_notify_transmit_ready (core_api,
550                                          GNUNET_YES /* cork */,
551                                          0 /* priority */,
552                                          GNUNET_TIME_UNIT_FOREVER_REL,
553                                          &dn->peer,
554                                          msize,                                  
555                                          &core_transmit_notify, dn);
556   return off;
557 }
558
559
560 /**
561  * Forward the given payload to the given target.
562  *
563  * @param target where to send the message
564  * @param uid unique ID for the message
565  * @param ultimate_target ultimate recipient for the message
566  * @param distance expected (remaining) distance to the target
567  * @param sender original sender of the message
568  * @param payload payload of the message
569  */
570 static void
571 forward_payload (struct DirectNeighbor *target,
572                  uint32_t distance,
573                  uint32_t uid,
574                  const struct GNUNET_PeerIdentity *sender,
575                  const struct GNUNET_PeerIdentity *ultimate_target,
576                  const struct GNUNET_MessageHeader *payload)
577 {
578   struct PendingMessage *pm;
579   struct RouteMessage *rm;
580   size_t msize;
581
582   if ( (target->pm_queue_size >= MAX_QUEUE_SIZE) &&
583        (0 != memcmp (sender,
584                      &my_identity,
585                      sizeof (struct GNUNET_PeerIdentity))) )
586   {
587     GNUNET_break (0 == uid);
588     return;
589   }
590   msize = sizeof (struct RouteMessage) + ntohs (payload->size);
591   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
592   {
593     GNUNET_break (0);
594     return;
595   }
596   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
597   pm->ultimate_target = *ultimate_target;
598   pm->uid = uid;
599   pm->msg = (const struct GNUNET_MessageHeader *) &pm[1];
600   rm = (struct RouteMessage *) &pm[1];
601   rm->header.size = htons ((uint16_t) msize);
602   rm->header.type = htons (GNUNET_MESSAGE_TYPE_DV_ROUTE);
603   rm->distance = htonl (distance);
604   rm->target = target->peer;
605   rm->sender = *sender;
606   memcpy (&rm[1], payload, ntohs (payload->size));
607   GNUNET_CONTAINER_DLL_insert_tail (target->pm_head,
608                                     target->pm_tail,
609                                     pm);
610   target->pm_queue_size++;
611   if (NULL == target->cth)
612     target->cth = GNUNET_CORE_notify_transmit_ready (core_api,
613                                                      GNUNET_YES /* cork */,
614                                                      0 /* priority */,
615                                                      GNUNET_TIME_UNIT_FOREVER_REL,
616                                                      &target->peer,
617                                                      msize,                                      
618                                                      &core_transmit_notify, target);
619 }
620
621
622 /**
623  * Find a free slot for storing a 'route' in the 'consensi'
624  * set at the given distance.
625  *
626  * @param distance distance to use for the set slot
627  */
628 static unsigned int
629 get_consensus_slot (uint32_t distance)
630 {
631   struct ConsensusSet *cs;
632   unsigned int i;
633
634   cs = &consensi[distance];
635   i = 0;
636   while ( (i < cs->array_length) &&
637           (NULL != cs->targets[i]) ) i++;
638   if (i == cs->array_length)
639     GNUNET_array_grow (cs->targets,
640                        cs->array_length,
641                        cs->array_length * 2 + 2);
642   return i;
643 }
644
645
646 /**
647  * Allocate a slot in the consensus set for a route.
648  *
649  * @param route route to initialize
650  * @param distance which consensus set to use
651  */
652 static void
653 allocate_route (struct Route *route,
654                 uint32_t distance)
655 {
656   unsigned int i;
657
658   i = get_consensus_slot (distance);
659   route->set_offset = i;
660   consensi[distance].targets[i] = route;
661   route->target.distance = htonl (distance);
662 }
663
664
665 /**
666  * Release a slot in the consensus set for a route.
667  *
668  * @param route route to release the slot from
669  */
670 static void
671 release_route (struct Route *route)
672 {
673   consensi[ntohl (route->target.distance)].targets[route->set_offset] = NULL;
674   route->set_offset = UINT_MAX; /* indicate invalid slot */
675 }
676
677
678 /**
679  * Move a route from one consensus set to another.
680  *
681  * @param route route to move
682  * @param new_distance new distance for the route (destination set)
683  */
684 static void
685 move_route (struct Route *route,
686             uint32_t new_distance)
687 {
688   unsigned int i;
689
690   release_route (route);
691   i = get_consensus_slot (new_distance);
692   route->set_offset = i;
693   consensi[new_distance].targets[i] = route;     
694   route->target.distance = htonl (new_distance);
695 }
696
697
698 /**
699  * Start creating a new consensus from scratch.
700  *
701  * @param cls the 'struct DirectNeighbor' of the peer we're building
702  *        a routing consensus with
703  * @param tc scheduler context
704  */    
705 static void
706 start_consensus (void *cls,
707                  const struct GNUNET_SCHEDULER_TaskContext *tc);
708
709
710 /**
711  * Method called whenever a peer connects.
712  *
713  * @param cls closure
714  * @param peer peer identity this notification is about
715  * @param atsi performance data
716  * @param atsi_count number of entries in atsi
717  */
718 static void
719 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
720                      const struct GNUNET_ATS_Information *atsi,
721                      unsigned int atsi_count)
722 {
723   struct DirectNeighbor *neighbor;
724   struct Route *route;
725   uint32_t distance;
726  
727   /* Check for connect to self message */
728   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
729     return;
730   distance = get_atsi_distance (atsi, atsi_count);
731   neighbor = GNUNET_CONTAINER_multihashmap_get (direct_neighbors, 
732                                                 &peer->hashPubKey);
733   if (NULL != neighbor)
734   {
735     GNUNET_break (0);
736     return;
737   }
738   if (DIRECT_NEIGHBOR_COST != distance) 
739     return; /* is a DV-neighbor */
740   GNUNET_STATISTICS_update (stats,
741                             "# peers connected (1-hop)",
742                             1, GNUNET_NO);
743   neighbor = GNUNET_malloc (sizeof (struct DirectNeighbor));
744   neighbor->peer = *peer;
745   GNUNET_assert (GNUNET_YES ==
746                  GNUNET_CONTAINER_multihashmap_put (direct_neighbors,
747                                                     &peer->hashPubKey,
748                                                     neighbor,
749                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
750   route = GNUNET_CONTAINER_multihashmap_get (all_routes, 
751                                              &peer->hashPubKey);
752   if (NULL != route)  
753   {
754     send_disconnect_to_plugin (peer);
755     release_route (route);
756     GNUNET_free (route);
757   }
758   neighbor->consensus_task = GNUNET_SCHEDULER_add_now (&start_consensus,
759                                                        neighbor);
760 }
761
762
763 /**
764  * Called for each 'target' in a neighbor table to free the associated memory.
765  *
766  * @param cls NULL
767  * @param key key of the value
768  * @param value value to free
769  * @return GNUNET_OK to continue to iterate
770  */
771 static int
772 free_targets (void *cls,
773               const struct GNUNET_HashCode *key,
774               void *value)
775 {
776   GNUNET_free (value);
777   return GNUNET_OK;
778 }
779
780
781 /**
782  * Multihashmap iterator for checking if a given route is
783  * (now) useful to this peer.
784  *
785  * @param cls the direct neighbor for the given route
786  * @param key key value stored under
787  * @param value a 'struct Target' that may or may not be useful; not that
788  *        the distance in 'target' does not include the first hop yet
789  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
790  */
791 static int
792 check_possible_route (void *cls, const struct GNUNET_HashCode * key, void *value)
793 {
794   struct DirectNeighbor *neighbor = cls;
795   struct Target *target = value;
796   struct Route *route;
797   
798   route = GNUNET_CONTAINER_multihashmap_get (all_routes,
799                                            key);
800   if (NULL != route)
801   {
802     if (ntohl (route->target.distance) > ntohl (target->distance) + 1)
803     {
804       /* this 'target' is cheaper than the existing route; switch to alternative route! */
805       move_route (route, ntohl (target->distance) + 1);
806       route->next_hop = neighbor;
807       send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
808     }
809     return GNUNET_YES; /* got a route to this target already */
810   }
811   route = GNUNET_malloc (sizeof (struct Route));
812   route->next_hop = neighbor;
813   route->target.distance = htonl (ntohl (target->distance) + 1);
814   route->target.peer = target->peer;
815   allocate_route (route, ntohl (route->target.distance));
816   GNUNET_assert (GNUNET_YES ==
817                  GNUNET_CONTAINER_multihashmap_put (all_routes,
818                                                     &route->target.peer.hashPubKey,
819                                                     route,
820                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
821   send_connect_to_plugin (&route->target.peer, ntohl (target->distance));
822   return GNUNET_YES;
823 }
824
825
826 /**
827  * Multihashmap iterator for finding routes that were previously
828  * "hidden" due to a better route (called after a disconnect event).
829  *
830  * @param cls NULL
831  * @param key peer identity of the given direct neighbor
832  * @param value a 'struct DirectNeighbor' to check for additional routes
833  * @return GNUNET_YES to continue iteration
834  */
835 static int
836 refresh_routes (void *cls, const struct GNUNET_HashCode * key, void *value)
837 {
838   struct DirectNeighbor *neighbor = value;
839
840   if (NULL != neighbor->neighbor_table)
841     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
842                                            &check_possible_route,
843                                            neighbor);
844   return GNUNET_YES;
845 }
846
847
848 /**
849  * Check if a target was removed from the set of the other peer; if so,
850  * if we also used it for our route, we need to remove it from our
851  * 'all_routes' set (and later check if an alternative path now exists).
852  *
853  * @param cls the 'struct DirectNeighbor'
854  * @param key peer identity for the target
855  * @param value a 'struct Target' previously reachable via the given neighbor
856  */
857 static int
858 check_target_removed (void *cls,
859                       const struct GNUNET_HashCode *key,
860                       void *value)
861 {
862   struct DirectNeighbor *neighbor = cls;
863   struct Target *new_target;
864   struct Route *current_route;
865
866   new_target = GNUNET_CONTAINER_multihashmap_get (neighbor->neighbor_table_consensus,
867                                                   key);
868   if (NULL == new_target)
869   {
870     /* target was revoked, check if it was used */
871     current_route = GNUNET_CONTAINER_multihashmap_get (all_routes,
872                                                        key);
873     if ( (NULL == current_route) ||
874          (current_route->next_hop != neighbor) )
875     {
876       /* didn't matter, wasn't used */
877       return GNUNET_OK;
878     }
879     /* remove existing route */
880     GNUNET_assert (GNUNET_YES ==
881                    GNUNET_CONTAINER_multihashmap_remove (all_routes, key, current_route));
882     send_disconnect_to_plugin (&current_route->target.peer);
883     GNUNET_free (current_route);
884     neighbor->target_removed = GNUNET_YES;
885     return GNUNET_OK;
886   }
887   return GNUNET_OK;
888 }
889
890
891 /**
892  * Check if a target was added to the set of the other peer; if it
893  * was added or impoves the existing route, do the needed updates.
894  *
895  * @param cls the 'struct DirectNeighbor'
896  * @param key peer identity for the target
897  * @param value a 'struct Target' now reachable via the given neighbor
898  */
899 static int
900 check_target_added (void *cls,
901                       const struct GNUNET_HashCode *key,
902                       void *value)
903 {
904   struct DirectNeighbor *neighbor = cls;
905   struct Target *target = value;
906   struct Route *current_route;
907
908   /* target was revoked, check if it was used */
909   current_route = GNUNET_CONTAINER_multihashmap_get (all_routes,
910                                                      key);
911   if (NULL != current_route)
912   {
913     /* route exists */
914     if (current_route->next_hop == neighbor)
915     {
916       /* we had the same route before, no change */
917       if (ntohl (target->distance) + 1 != ntohl (current_route->target.distance))
918       {
919         current_route->target.distance = htonl (ntohl (target->distance) + 1);
920         send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
921       }
922       return GNUNET_OK;
923     }
924     if (ntohl (current_route->target.distance) >= ntohl (target->distance) + 1)
925     {
926       /* alternative, shorter route exists, ignore */
927       return GNUNET_OK;
928     }
929     /* new route is better than the existing one, take over! */
930     /* NOTE: minor security issue: malicious peers may advertise
931        very short routes to take over longer paths; as we don't
932        check that the shorter routes actually work, a malicious
933        direct neighbor can use this to DoS our long routes */
934     current_route->next_hop = neighbor;
935     current_route->target.distance = htonl (ntohl (target->distance) + 1);
936     send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
937     return GNUNET_OK;
938   }
939   /* new route */
940   current_route = GNUNET_malloc (sizeof (struct Route));
941   current_route->next_hop = neighbor;
942   current_route->target.peer = target->peer;
943   current_route->target.distance = htonl (ntohl (target->distance) + 1);
944   GNUNET_assert (GNUNET_YES ==
945                  GNUNET_CONTAINER_multihashmap_put (all_routes,
946                                                     &current_route->target.peer.hashPubKey,
947                                                     current_route,
948                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
949   send_connect_to_plugin (&current_route->target.peer,
950                           ntohl (current_route->target.distance));
951   return GNUNET_OK;
952 }
953
954
955
956 /**
957  * The consensus has concluded, clean up and schedule the next one.
958  *
959  * @param cls the 'struct GNUNET_DirectNeighbor' with which we created the consensus
960  * @param group FIXME
961  */
962 static void
963 consensus_done_cb (void *cls,
964                    const struct GNUNET_CONSENSUS_Group *group)
965 {
966   struct DirectNeighbor *neighbor = cls;
967
968   GNUNET_CONSENSUS_destroy (neighbor->consensus);
969   neighbor->consensus = NULL;
970   /* remove targets that disappeared */
971   neighbor->target_removed = GNUNET_NO;
972   GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
973                                          &check_target_removed,
974                                          neighbor);
975   if (GNUNET_YES == neighbor->target_removed)
976   {
977     /* check if we got an alternative for the removed routes */
978     GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
979                                            &refresh_routes,
980                                            NULL);    
981   }
982   /* add targets that appeared (and check for improved routes) */
983   GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table_consensus,
984                                          &check_target_added,
985                                          neighbor);
986   if (NULL != neighbor->neighbor_table)
987   {
988     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
989                                            &free_targets,
990                                            NULL);
991     GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table);
992     neighbor->neighbor_table = NULL;
993   }
994   neighbor->neighbor_table = neighbor->neighbor_table_consensus;
995   neighbor->neighbor_table_consensus = NULL;
996   neighbor->consensus_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
997                                                            &start_consensus,
998                                                            neighbor);
999 }
1000
1001
1002 /**
1003  * We inserted the last element into the consensus, get ready to
1004  * insert the next element into the consensus or conclude if
1005  * we're done.
1006  *
1007  * @param cls the 'struct DirectNeighbor' of the peer we're building
1008  *        a routing consensus with
1009  * @param success GNUNET_OK if the last element was added successfully,
1010  *                GNUNET_SYSERR if we failed
1011  */
1012 static void
1013 insert_next_element (void *cls,
1014                      int success)
1015 {
1016   struct DirectNeighbor *neighbor = cls;
1017   struct GNUNET_CONSENSUS_Element element;
1018
1019   while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
1020           (consensi[neighbor->consensus_insertion_distance].array_length == neighbor->consensus_insertion_offset) )
1021   {
1022     neighbor->consensus_insertion_offset = 0;
1023     neighbor->consensus_insertion_distance++;
1024     /* skip over NULL entries */
1025     while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
1026             (consensi[neighbor->consensus_insertion_distance].array_length < neighbor->consensus_insertion_offset) &&
1027             (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
1028       neighbor->consensus_insertion_offset++;
1029   }
1030   if (DEFAULT_FISHEYE_DEPTH - 1 == neighbor->consensus_insertion_distance)
1031   {
1032     /* we're done, conclude! */
1033     GNUNET_CONSENSUS_conclude (neighbor->consensus,
1034                                GNUNET_DV_CONSENSUS_FREQUENCY,
1035                                2 /* both peers */,
1036                                &consensus_done_cb,
1037                                neighbor);
1038     return;
1039   }
1040   element.size = sizeof (struct Target);
1041   element.data = &consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset++]->target;
1042
1043   /* skip over NULL entries */
1044   while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
1045           (consensi[neighbor->consensus_insertion_distance].array_length < neighbor->consensus_insertion_offset) &&
1046           (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
1047     neighbor->consensus_insertion_offset++;  
1048   GNUNET_CONSENSUS_insert (neighbor->consensus,
1049                            &element,
1050                            &insert_next_element,
1051                            neighbor);
1052 }
1053
1054
1055 /**
1056  * We have learned a new route from the other peer.  Add it to the
1057  * route set we're building.
1058  *
1059  * @param cls the 'struct DirectNeighbor' we're building the consensus with
1060  * @param element the new element we have learned
1061  * @return GNUNET_OK if the valid is well-formed and should be added to the consensus,
1062  *         GNUNET_SYSERR if the element should be ignored and not be propagated
1063  */
1064 static int
1065 learn_route_cb (void *cls,
1066                 const struct GNUNET_CONSENSUS_Element *element)
1067 {
1068   struct DirectNeighbor *neighbor = cls;
1069   struct Target *target;
1070
1071   if (NULL == element)
1072   {
1073     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1074                 "Failed to establish DV consensus, will try again later\n");
1075     GNUNET_CONSENSUS_destroy (neighbor->consensus);
1076     if (NULL != neighbor->neighbor_table_consensus)
1077     {
1078       GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table_consensus,
1079                                              &free_targets,
1080                                              NULL);
1081       GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table_consensus);
1082       neighbor->neighbor_table_consensus = NULL;
1083     }
1084     neighbor->consensus = NULL;
1085     neighbor->consensus_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1086                                                              &start_consensus,
1087                                                              neighbor);
1088     return GNUNET_SYSERR;
1089   }
1090   if (sizeof (struct Target) != element->size)
1091   {
1092     GNUNET_break_op (0);
1093     return GNUNET_SYSERR;
1094   }
1095   target = GNUNET_malloc (sizeof (struct Target));
1096   memcpy (target, element->data, sizeof (struct Target));
1097   if (GNUNET_YES !=
1098       GNUNET_CONTAINER_multihashmap_put (neighbor->neighbor_table_consensus,
1099                                          &target->peer.hashPubKey,
1100                                          target,
1101                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1102   {
1103     GNUNET_break_op (0);
1104     GNUNET_free (target);
1105     return GNUNET_SYSERR;
1106   }
1107   return GNUNET_OK;
1108 }
1109
1110
1111 /**
1112  * Start creating a new consensus from scratch.
1113  *
1114  * @param cls the 'struct DirectNeighbor' of the peer we're building
1115  *        a routing consensus with
1116  * @param tc scheduler context
1117  */    
1118 static void
1119 start_consensus (void *cls,
1120                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1121 {
1122   struct DirectNeighbor *neighbor = cls;
1123   struct GNUNET_HashCode session_id;
1124   struct GNUNET_HashCode real_session_id;
1125
1126   neighbor->consensus_task = GNUNET_SCHEDULER_NO_TASK;
1127   neighbor->consensus_insertion_offset = 0;
1128   neighbor->consensus_insertion_distance = 0;
1129   GNUNET_assert (NULL == neighbor->neighbor_table_consensus);
1130   GNUNET_assert (NULL == neighbor->consensus);
1131   neighbor->neighbor_table_consensus = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
1132   /* construct session ID seed as XOR of both peer's identities */
1133   GNUNET_CRYPTO_hash_xor (&my_identity.hashPubKey, 
1134                           &neighbor->peer.hashPubKey, 
1135                           &session_id);
1136   /* make sure session ID is unique across applications by salting it with 'DV' */
1137   GNUNET_CRYPTO_hkdf (&real_session_id, sizeof (real_session_id),
1138                       GCRY_MD_SHA512, GCRY_MD_SHA256,
1139                       "DV-SALT", 2,
1140                       &session_id, sizeof (session_id),
1141                       NULL, 0);
1142   neighbor->consensus = GNUNET_CONSENSUS_create (cfg,
1143                                                  1,
1144                                                  &neighbor->peer,
1145                                                  &real_session_id,
1146                                                  &learn_route_cb,
1147                                                  neighbor);
1148   if (NULL == neighbor->consensus)
1149   {
1150     neighbor->consensus_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1151                                                              &start_consensus,
1152                                                              neighbor);
1153     return;
1154   }
1155   insert_next_element (neighbor, GNUNET_OK);
1156 }
1157
1158
1159 /**
1160  * Core handler for DV data messages.  Whatever this message
1161  * contains all we really have to do is rip it out of its
1162  * DV layering and give it to our pal the DV plugin to report
1163  * in with.
1164  *
1165  * @param cls closure
1166  * @param peer peer which sent the message (immediate sender)
1167  * @param message the message
1168  * @param atsi transport ATS information (latency, distance, etc.)
1169  * @param atsi_count number of entries in atsi
1170  * @return GNUNET_OK on success, GNUNET_SYSERR if the other peer violated the protocol
1171  */
1172 static int
1173 handle_dv_route_message (void *cls, const struct GNUNET_PeerIdentity *peer,
1174                          const struct GNUNET_MessageHeader *message,
1175                          const struct GNUNET_ATS_Information *atsi,
1176                          unsigned int atsi_count)
1177 {
1178   const struct RouteMessage *rm;
1179   const struct GNUNET_MessageHeader *payload;
1180   struct Route *route;
1181
1182   if (ntohs (message->size) < sizeof (struct RouteMessage) + sizeof (struct GNUNET_MessageHeader))
1183   {
1184     GNUNET_break_op (0);
1185     return GNUNET_SYSERR;
1186   }
1187   rm = (const struct RouteMessage *) message;
1188   payload = (const struct GNUNET_MessageHeader *) &rm[1];
1189   if (ntohs (message->size) != sizeof (struct RouteMessage) + ntohs (payload->size))
1190   {
1191     GNUNET_break_op (0);
1192     return GNUNET_SYSERR;
1193   }
1194   if (0 == memcmp (&rm->target,
1195                    &my_identity,
1196                    sizeof (struct GNUNET_PeerIdentity)))
1197   {
1198     /* message is for me, check reverse route! */
1199     route = GNUNET_CONTAINER_multihashmap_get (all_routes,
1200                                                &rm->sender.hashPubKey);
1201     if (NULL == route)
1202     {
1203       /* don't have reverse route, drop */
1204       GNUNET_STATISTICS_update (stats,
1205                                 "# message discarded (no reverse route)",
1206                                 1, GNUNET_NO);
1207       return GNUNET_OK;
1208     }
1209     send_data_to_plugin (payload,
1210                          &rm->sender,
1211                          ntohl (route->target.distance));
1212     return GNUNET_OK;
1213   }
1214   route = GNUNET_CONTAINER_multihashmap_get (all_routes,
1215                                              &rm->target.hashPubKey);
1216   if (NULL == route)
1217   {
1218     GNUNET_STATISTICS_update (stats,
1219                               "# messages discarded (no route)",
1220                               1, GNUNET_NO);
1221     return GNUNET_OK;
1222   }
1223   if (ntohl (route->target.distance) > ntohl (rm->distance) + 1)
1224   {
1225     GNUNET_STATISTICS_update (stats,
1226                               "# messages discarded (target too far)",
1227                               1, GNUNET_NO);
1228     return GNUNET_OK;
1229   }
1230   forward_payload (route->next_hop,
1231                    ntohl (route->target.distance),
1232                    0,
1233                    &rm->target,
1234                    &rm->sender,
1235                    payload);
1236   return GNUNET_OK;  
1237 }
1238
1239
1240 /**
1241  * Service server's handler for message send requests (which come
1242  * bubbling up to us through the DV plugin).
1243  *
1244  * @param cls closure
1245  * @param client identification of the client
1246  * @param message the actual message
1247  */
1248 static void
1249 handle_dv_send_message (void *cls, struct GNUNET_SERVER_Client *client,
1250                         const struct GNUNET_MessageHeader *message)
1251 {
1252   struct Route *route;
1253   const struct GNUNET_DV_SendMessage *msg;
1254   const struct GNUNET_MessageHeader *payload;
1255
1256   if (ntohs (message->size) < sizeof (struct GNUNET_DV_SendMessage) + sizeof (struct GNUNET_MessageHeader))
1257   {
1258     GNUNET_break (0);
1259     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1260     return;
1261   }
1262   msg = (const struct GNUNET_DV_SendMessage *) message;
1263   GNUNET_break (0 != ntohl (msg->uid));
1264   payload = (const struct GNUNET_MessageHeader *) &msg[1];
1265   if (ntohs (message->size) != sizeof (struct GNUNET_DV_SendMessage) + ntohs (payload->size))
1266   {
1267     GNUNET_break (0);
1268     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1269     return;
1270   }
1271   route = GNUNET_CONTAINER_multihashmap_get (all_routes,
1272                                              &msg->target.hashPubKey);
1273   if (NULL == route)
1274   {
1275     /* got disconnected */
1276     GNUNET_STATISTICS_update (stats,
1277                               "# local messages discarded (no route)",
1278                               1, GNUNET_NO);
1279     send_ack_to_plugin (&msg->target, ntohl (msg->uid), GNUNET_YES);
1280     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1281     return;
1282   }
1283   forward_payload (route->next_hop,
1284                    ntohl (route->target.distance),
1285                    htonl (msg->uid),
1286                    &msg->target,
1287                    &my_identity,
1288                    payload);
1289   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1290 }
1291
1292
1293 /**
1294  * Multihashmap iterator for freeing routes that go via a particular
1295  * neighbor that disconnected and is thus no longer available.
1296  *
1297  * @param cls the direct neighbor that is now unavailable
1298  * @param key key value stored under
1299  * @param value a 'struct Route' that may or may not go via neighbor
1300  *
1301  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1302  */
1303 static int
1304 cull_routes (void *cls, const struct GNUNET_HashCode * key, void *value)
1305 {
1306   struct DirectNeighbor *neighbor = cls;
1307   struct Route *route = value;
1308
1309   if (route->next_hop != neighbor)
1310     return GNUNET_YES; /* not affected */
1311   GNUNET_assert (GNUNET_YES ==
1312                  GNUNET_CONTAINER_multihashmap_remove (all_routes, key, value));
1313   release_route (route);
1314   send_disconnect_to_plugin (&route->target.peer);
1315   GNUNET_free (route);
1316   return GNUNET_YES;
1317 }
1318
1319
1320 /**
1321  * Cleanup all of the data structures associated with a given neighbor.
1322  *
1323  * @param neighbor neighbor to clean up
1324  */
1325 static void
1326 cleanup_neighbor (struct DirectNeighbor *neighbor)
1327 {
1328   struct PendingMessage *pending;
1329
1330   while (NULL != (pending = neighbor->pm_head))
1331   {
1332     neighbor->pm_queue_size--;
1333     GNUNET_CONTAINER_DLL_remove (neighbor->pm_head,
1334                                  neighbor->pm_tail,
1335                                  pending);    
1336     GNUNET_free (pending);
1337   }
1338   GNUNET_CONTAINER_multihashmap_iterate (all_routes,
1339                                          &cull_routes,
1340                                          neighbor);
1341   if (NULL != neighbor->cth)
1342   {
1343     GNUNET_CORE_notify_transmit_ready_cancel (neighbor->cth);
1344     neighbor->cth = NULL;
1345   }
1346   if (NULL != neighbor->neighbor_table_consensus)
1347   {
1348     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table_consensus,
1349                                            &free_targets,
1350                                            NULL);
1351     GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table_consensus);
1352     neighbor->neighbor_table_consensus = NULL;
1353   }
1354   if (NULL != neighbor->neighbor_table)
1355   {
1356     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
1357                                            &free_targets,
1358                                            NULL);
1359     GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table);
1360     neighbor->neighbor_table = NULL;
1361   }
1362   if (GNUNET_SCHEDULER_NO_TASK != neighbor->consensus_task)
1363   {
1364     GNUNET_SCHEDULER_cancel (neighbor->consensus_task);
1365     neighbor->consensus_task = GNUNET_SCHEDULER_NO_TASK;
1366   }
1367   if (NULL != neighbor->consensus)
1368   {
1369     GNUNET_CONSENSUS_destroy (neighbor->consensus);
1370     neighbor->consensus = NULL;
1371   }
1372   GNUNET_assert (GNUNET_YES ==
1373                  GNUNET_CONTAINER_multihashmap_remove (direct_neighbors, 
1374                                                        &neighbor->peer.hashPubKey,
1375                                                        neighbor));
1376   GNUNET_free (neighbor);
1377 }
1378
1379
1380 /**
1381  * Method called whenever a given peer disconnects.
1382  *
1383  * @param cls closure
1384  * @param peer peer identity this notification is about
1385  */
1386 static void
1387 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1388 {
1389   struct DirectNeighbor *neighbor;
1390
1391   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1392               "Received core peer disconnect message for peer `%s'!\n",
1393               GNUNET_i2s (peer));
1394   /* Check for disconnect from self message */
1395   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1396     return;
1397   neighbor =
1398       GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
1399   if (NULL == neighbor)
1400   {
1401     /* must have been a DV-neighbor, ignore */
1402     return;
1403   }
1404   GNUNET_STATISTICS_update (stats,
1405                             "# peers connected (1-hop)",
1406                             -1, GNUNET_NO);  
1407   cleanup_neighbor (neighbor);
1408   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
1409                                          &refresh_routes,
1410                                          NULL);
1411 }
1412
1413
1414 /**
1415  * Multihashmap iterator for freeing routes.  Should never be called.
1416  *
1417  * @param cls NULL
1418  * @param key key value stored under
1419  * @param value the route to be freed
1420  *
1421  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1422  */
1423 static int
1424 free_route (void *cls, const struct GNUNET_HashCode * key, void *value)
1425 {
1426   struct Route *route = value;
1427
1428   GNUNET_break (0);
1429   GNUNET_assert (GNUNET_YES ==
1430                  GNUNET_CONTAINER_multihashmap_remove (all_routes, key, value));
1431   release_route (route);
1432   send_disconnect_to_plugin (&route->target.peer);
1433   GNUNET_free (route);
1434   return GNUNET_YES;
1435 }
1436
1437
1438 /**
1439  * Multihashmap iterator for freeing direct neighbors. Should never be called.
1440  *
1441  * @param cls NULL
1442  * @param key key value stored under
1443  * @param value the direct neighbor to be freed
1444  *
1445  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1446  */
1447 static int
1448 free_direct_neighbors (void *cls, const struct GNUNET_HashCode * key, void *value)
1449 {
1450   struct DirectNeighbor *neighbor = value;
1451
1452   GNUNET_break (0);
1453   cleanup_neighbor (neighbor);
1454   return GNUNET_YES;
1455 }
1456
1457
1458 /**
1459  * Task run during shutdown.
1460  *
1461  * @param cls unused
1462  * @param tc unused
1463  */
1464 static void
1465 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1466 {
1467   unsigned int i;
1468
1469   GNUNET_CORE_disconnect (core_api);
1470   core_api = NULL;
1471   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
1472                                          &free_direct_neighbors, NULL);
1473   GNUNET_CONTAINER_multihashmap_iterate (all_routes,
1474                                          &free_route, NULL);
1475   GNUNET_CONTAINER_multihashmap_destroy (direct_neighbors);
1476   GNUNET_CONTAINER_multihashmap_destroy (all_routes);
1477   GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1478   stats = NULL;
1479   GNUNET_SERVER_notification_context_destroy (nc);
1480   nc = NULL;
1481   for (i=0;i<DEFAULT_FISHEYE_DEPTH - 1;i++)
1482     GNUNET_array_grow (consensi[i].targets,
1483                        consensi[i].array_length,
1484                        0);
1485 }
1486
1487
1488 /**
1489  * Notify newly connected client about an existing route.
1490  *
1491  * @param cls the 'struct GNUNET_SERVER_Client'
1492  * @param key peer identity
1493  * @param value the XXX.
1494  * @return GNUNET_OK (continue to iterate)
1495  */
1496 static int
1497 add_route (void *cls,
1498            const struct GNUNET_HashCode *key,
1499            void *value)
1500 {
1501   struct GNUNET_SERVER_Client *client = cls;
1502   struct Route *route = value;
1503   struct GNUNET_DV_ConnectMessage cm;
1504   
1505   cm.header.size = htons (sizeof (cm));
1506   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
1507   cm.distance = htonl (route->target.distance);
1508   cm.peer = route->target.peer;
1509
1510   GNUNET_SERVER_notification_context_unicast (nc, 
1511                                               client,
1512                                               &cm.header,
1513                                               GNUNET_NO);
1514   return GNUNET_OK;
1515 }
1516
1517
1518 /**
1519  * Handle START-message.  This is the first message sent to us
1520  * by the client (can only be one!).
1521  *
1522  * @param cls closure (always NULL)
1523  * @param client identification of the client
1524  * @param message the actual message
1525  */
1526 static void
1527 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
1528               const struct GNUNET_MessageHeader *message)
1529 {
1530   GNUNET_SERVER_notification_context_add (nc, client);  
1531   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1532   GNUNET_CONTAINER_multihashmap_iterate (all_routes,
1533                                          &add_route,
1534                                          client);
1535 }
1536
1537
1538 /**
1539  * Called on core init.
1540  *
1541  * @param cls unused
1542  * @param server legacy
1543  * @param identity this peer's identity
1544  */
1545 static void
1546 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1547            const struct GNUNET_PeerIdentity *identity)
1548 {
1549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1550               "I am peer: %s\n",
1551               GNUNET_i2s (identity));
1552   my_identity = *identity;
1553 }
1554
1555
1556 /**
1557  * Process dv requests.
1558  *
1559  * @param cls closure
1560  * @param server the initialized server
1561  * @param c configuration to use
1562  */
1563 static void
1564 run (void *cls, struct GNUNET_SERVER_Handle *server,
1565      const struct GNUNET_CONFIGURATION_Handle *c)
1566 {
1567   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1568     {&handle_dv_route_message, GNUNET_MESSAGE_TYPE_DV_ROUTE, 0},
1569     {NULL, 0, 0}
1570   };
1571   static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
1572     {&handle_start, NULL, 
1573      GNUNET_MESSAGE_TYPE_DV_START, 
1574      sizeof (struct GNUNET_MessageHeader) },
1575     { &handle_dv_send_message, NULL, 
1576       GNUNET_MESSAGE_TYPE_DV_SEND, 
1577       0},
1578     {NULL, NULL, 0, 0}
1579   };
1580
1581   cfg = c;
1582   direct_neighbors = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
1583   all_routes = GNUNET_CONTAINER_multihashmap_create (65536, GNUNET_NO);
1584   core_api = GNUNET_CORE_connect (cfg, NULL,
1585                                   &core_init, 
1586                                   &handle_core_connect,
1587                                   &handle_core_disconnect,
1588                                   NULL, GNUNET_NO, 
1589                                   NULL, GNUNET_NO, 
1590                                   core_handlers);
1591
1592   if (NULL == core_api)
1593     return;
1594   nc = GNUNET_SERVER_notification_context_create (server,
1595                                                   MAX_QUEUE_SIZE_PLUGIN);
1596   stats = GNUNET_STATISTICS_create ("dv", cfg);
1597   GNUNET_SERVER_add_handlers (server, plugin_handlers);
1598   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1599                                 &shutdown_task, NULL);
1600 }
1601
1602
1603 /**
1604  * The main function for the dv service.
1605  *
1606  * @param argc number of arguments from the command line
1607  * @param argv command line arguments
1608  * @return 0 ok, 1 on error
1609  */
1610 int
1611 main (int argc, char *const *argv)
1612 {
1613   return (GNUNET_OK ==
1614           GNUNET_SERVICE_run (argc, argv, "dv", GNUNET_SERVICE_OPTION_NONE,
1615                               &run, NULL)) ? 0 : 1;
1616 }
1617
1618 /* end of gnunet-service-dv.c */