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