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