social cli
[oweals/gnunet.git] / src / dv / gnunet-service-dv.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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_set_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    * Next target for the message (a neighbour of ours).
149    */
150   struct GNUNET_PeerIdentity next_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    * Session ID we use whenever we create a set union with
174    * this neighbor; constructed from the XOR of our peer
175    * IDs and then salted with "DV-SALT" to avoid conflicts
176    * with other applications.
177    */
178   struct GNUNET_HashCode real_session_id;
179
180   /**
181    * Head of linked list of messages to send to this peer.
182    */
183   struct PendingMessage *pm_head;
184
185   /**
186    * Tail of linked list of messages to send to this peer.
187    */
188   struct PendingMessage *pm_tail;
189
190   /**
191    * Transmit handle to core service.
192    */
193   struct GNUNET_CORE_TransmitHandle *cth;
194
195   /**
196    * Routing table of the neighbor, NULL if not yet established.
197    * Keys are peer identities, values are 'struct Target' entries.
198    * Note that the distances in the targets are from the point-of-view
199    * of the peer, not from us!
200    */
201   struct GNUNET_CONTAINER_MultiPeerMap *neighbor_table;
202
203   /**
204    * Updated routing table of the neighbor, under construction,
205    * NULL if we are not currently building it.
206    * Keys are peer identities, values are 'struct Target' entries.
207    * Note that the distances in the targets are from the point-of-view
208    * of the other peer, not from us!
209    */
210   struct GNUNET_CONTAINER_MultiPeerMap *neighbor_table_consensus;
211
212   /**
213    * Our current (exposed) routing table as a set.
214    */
215   struct GNUNET_SET_Handle *my_set;
216
217   /**
218    * Handle for our current active set union operation.
219    */
220   struct GNUNET_SET_OperationHandle *set_op;
221
222   /**
223    * Handle used if we are listening for this peer, waiting for the
224    * other peer to initiate construction of the set union.  NULL if
225    * we ar the initiating peer.
226    */
227   struct GNUNET_SET_ListenHandle *listen_handle;
228
229   /**
230    * ID of the task we use to (periodically) update our consensus
231    * with this peer.  Used if we are the initiating peer.
232    */
233   struct GNUNET_SCHEDULER_Task * initiate_task;
234
235   /**
236    * At what offset are we, with respect to inserting our own routes
237    * into the consensus?
238    */
239   unsigned int consensus_insertion_offset;
240
241   /**
242    * At what distance are we, with respect to inserting our own routes
243    * into the consensus?
244    */
245   unsigned int consensus_insertion_distance;
246
247   /**
248    * Number of messages currently in the 'pm_XXXX'-DLL.
249    */
250   unsigned int pm_queue_size;
251
252   /**
253    * Elements in consensus
254    */
255   unsigned int consensus_elements;
256
257   /**
258    * Direct one hop route
259    */
260   struct Route *direct_route;
261
262   /**
263    * Flag set within 'check_target_removed' to trigger full global route refresh.
264    */
265   int target_removed;
266
267   /**
268    * Our distance to this peer, 0 for unknown.
269    */
270   uint32_t distance;
271
272   /**
273    * The network this peer is in
274    */
275   enum GNUNET_ATS_Network_Type network;
276
277   /**
278    * Is this neighbor connected at the core level?
279    */
280   int connected;
281
282 };
283
284
285 /**
286  * A route includes information about the next hop,
287  * the target, and the ultimate distance to the
288  * target.
289  */
290 struct Route
291 {
292
293   /**
294    * Which peer do we need to forward the message to?
295    */
296   struct DirectNeighbor *next_hop;
297
298   /**
299    * What would be the target, and how far is it away?
300    */
301   struct Target target;
302
303   /**
304    * Offset of this target in the respective consensus set.
305    */
306   unsigned int set_offset;
307
308 };
309
310
311 /**
312  * Set of targets we bring to a consensus; all targets in a set have a
313  * distance equal to the sets distance (which is implied by the array
314  * index of the set).
315  */
316 struct ConsensusSet
317 {
318
319   /**
320    * Array of targets in the set, may include NULL entries if a
321    * neighbor has disconnected; the targets are allocated with the
322    * respective container (all_routes), not here.
323    */
324   struct Route **targets;
325
326   /**
327    * Size of the @e targets array.
328    */
329   unsigned int array_length;
330
331 };
332
333
334 /**
335  * Peermap of all of our neighbors; processing these usually requires
336  * first checking to see if the peer is core-connected and if the
337  * distance is 1, in which case they are direct neighbors.
338  */
339 static struct GNUNET_CONTAINER_MultiPeerMap *direct_neighbors;
340
341 /**
342  * Hashmap with all routes that we currently support; contains
343  * routing information for all peers from distance 2
344  * up to distance #DEFAULT_FISHEYE_DEPTH.
345  */
346 static struct GNUNET_CONTAINER_MultiPeerMap *all_routes;
347
348 /**
349  * Array of consensus sets we expose to the outside world.  Sets
350  * are structured by the distance to the target.
351  */
352 static struct ConsensusSet consensi[DEFAULT_FISHEYE_DEPTH];
353
354 /**
355  * Handle to the core service api.
356  */
357 static struct GNUNET_CORE_Handle *core_api;
358
359 /**
360  * The identity of our peer.
361  */
362 static struct GNUNET_PeerIdentity my_identity;
363
364 /**
365  * The configuration for this service.
366  */
367 static const struct GNUNET_CONFIGURATION_Handle *cfg;
368
369 /**
370  * The client, the DV plugin connected to us (or an event monitor).
371  * Hopefully this client will never change, although if the plugin
372  * dies and returns for some reason it may happen.
373  */
374 static struct GNUNET_SERVER_NotificationContext *nc;
375
376 /**
377  * Handle for the statistics service.
378  */
379 static struct GNUNET_STATISTICS_Handle *stats;
380
381 /**
382  * Handle to ATS service.
383  */
384 static struct GNUNET_ATS_PerformanceHandle *ats;
385
386 /**
387  * Task scheduled to refresh routes based on direct neighbours.
388  */
389 static struct GNUNET_SCHEDULER_Task * rr_task;
390
391 /**
392  * #GNUNET_YES if we are shutting down.
393  */
394 static int in_shutdown;
395
396 /**
397  * Start creating a new DV set union by initiating the connection.
398  *
399  * @param cls the 'struct DirectNeighbor' of the peer we're building
400  *        a routing consensus with
401  */
402 static void
403 initiate_set_union (void *cls);
404
405
406 /**
407  * Start creating a new DV set union construction, our neighbour has
408  * asked for it (callback for listening peer).
409  *
410  * @param cls the 'struct DirectNeighbor' of the peer we're building
411  *        a routing consensus with
412  * @param other_peer the other peer
413  * @param context_msg message with application specific information from
414  *        the other peer
415  * @param request request from the other peer, use GNUNET_SET_accept
416  *        to accept it, otherwise the request will be refused
417  *        Note that we don't use a return value here, as it is also
418  *        necessary to specify the set we want to do the operation with,
419  *        whith sometimes can be derived from the context message.
420  *        Also necessary to specify the timeout.
421  */
422 static void
423 listen_set_union (void *cls,
424                   const struct GNUNET_PeerIdentity *other_peer,
425                   const struct GNUNET_MessageHeader *context_msg,
426                   struct GNUNET_SET_Request *request);
427
428
429 /**
430  * Forward a message from another peer to the plugin.
431  *
432  * @param message the message to send to the plugin
433  * @param origin the original sender of the message
434  * @param distance distance to the original sender of the message
435  */
436 static void
437 send_data_to_plugin (const struct GNUNET_MessageHeader *message,
438                      const struct GNUNET_PeerIdentity *origin,
439                      uint32_t distance)
440 {
441   struct GNUNET_DV_ReceivedMessage *received_msg;
442   size_t size;
443
444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
445               "Delivering message from peer `%s' at distance %u\n",
446               GNUNET_i2s (origin),
447               (unsigned int) distance);
448   size = sizeof (struct GNUNET_DV_ReceivedMessage) +
449     ntohs (message->size);
450   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
451   {
452     GNUNET_break (0); /* too big */
453     return;
454   }
455   received_msg = GNUNET_malloc (size);
456   received_msg->header.size = htons (size);
457   received_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DV_RECV);
458   received_msg->distance = htonl (distance);
459   received_msg->sender = *origin;
460   memcpy (&received_msg[1], message, ntohs (message->size));
461   GNUNET_SERVER_notification_context_broadcast (nc,
462                                                 &received_msg->header,
463                                                 GNUNET_YES);
464   GNUNET_free (received_msg);
465 }
466
467
468 /**
469  * Forward a control message to the plugin.
470  *
471  * @param message the message to send to the plugin
472  */
473 static void
474 send_control_to_plugin (const struct GNUNET_MessageHeader *message)
475 {
476   GNUNET_SERVER_notification_context_broadcast (nc,
477                                                 message,
478                                                 GNUNET_NO);
479 }
480
481
482 /**
483  * Give an (N)ACK message to the plugin, we transmitted a message for it.
484  *
485  * @param target peer that received the message
486  * @param uid plugin-chosen UID for the message
487  * @param nack #GNUNET_NO to send ACK, #GNUNET_YES to send NACK
488  */
489 static void
490 send_ack_to_plugin (const struct GNUNET_PeerIdentity *target,
491                     uint32_t uid,
492                     int nack)
493 {
494   struct GNUNET_DV_AckMessage ack_msg;
495
496   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
497               "Delivering ACK for message to peer `%s'\n",
498               GNUNET_i2s (target));
499   ack_msg.header.size = htons (sizeof (ack_msg));
500   ack_msg.header.type = htons ((GNUNET_YES == nack)
501                                ? GNUNET_MESSAGE_TYPE_DV_SEND_NACK
502                                : GNUNET_MESSAGE_TYPE_DV_SEND_ACK);
503   ack_msg.uid = htonl (uid);
504   ack_msg.target = *target;
505   send_control_to_plugin (&ack_msg.header);
506 }
507
508
509 /**
510  * Send a DISTANCE_CHANGED message to the plugin.
511  *
512  * @param peer peer with a changed distance
513  * @param distance new distance to the peer
514  * @param network network used by the neighbor
515  */
516 static void
517 send_distance_change_to_plugin (const struct GNUNET_PeerIdentity *peer,
518                                 uint32_t distance,
519                                 enum GNUNET_ATS_Network_Type network)
520 {
521   struct GNUNET_DV_DistanceUpdateMessage du_msg;
522
523   GNUNET_break (GNUNET_ATS_NET_UNSPECIFIED != network);
524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
525               "Delivering DISTANCE_CHANGED for message about peer `%s'\n",
526               GNUNET_i2s (peer));
527   du_msg.header.size = htons (sizeof (du_msg));
528   du_msg.header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISTANCE_CHANGED);
529   du_msg.distance = htonl (distance);
530   du_msg.peer = *peer;
531   du_msg.network = htonl ((uint32_t) network);
532   send_control_to_plugin (&du_msg.header);
533 }
534
535
536 /**
537  * Give a CONNECT message to the plugin.
538  *
539  * @param target peer that connected
540  * @param distance distance to the target
541  * @param network the network the next hop is located in
542  */
543 static void
544 send_connect_to_plugin (const struct GNUNET_PeerIdentity *target,
545                         uint32_t distance,
546                         enum GNUNET_ATS_Network_Type network)
547 {
548   struct GNUNET_DV_ConnectMessage cm;
549
550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551               "Delivering CONNECT about peer %s with distance %u\n",
552               GNUNET_i2s (target), distance);
553   cm.header.size = htons (sizeof (cm));
554   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
555   cm.distance = htonl (distance);
556   cm.network = htonl ((uint32_t) network);
557   cm.peer = *target;
558   send_control_to_plugin (&cm.header);
559 }
560
561
562 /**
563  * Give a DISCONNECT message to the plugin.
564  *
565  * @param target peer that disconnected
566  */
567 static void
568 send_disconnect_to_plugin (const struct GNUNET_PeerIdentity *target)
569 {
570   struct GNUNET_DV_DisconnectMessage dm;
571
572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
573               "Delivering DISCONNECT about peer `%s'\n",
574               GNUNET_i2s (target));
575   dm.header.size = htons (sizeof (dm));
576   dm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISCONNECT);
577   dm.reserved = htonl (0);
578   dm.peer = *target;
579   send_control_to_plugin (&dm.header);
580 }
581
582
583 /**
584  * Function called to transfer a message to another peer
585  * via core.
586  *
587  * @param cls closure with the direct neighbor
588  * @param size number of bytes available in buf
589  * @param buf where the callee should write the message
590  * @return number of bytes written to buf
591  */
592 static size_t
593 core_transmit_notify (void *cls, size_t size, void *buf)
594 {
595   struct DirectNeighbor *dn = cls;
596   char *cbuf = buf;
597   struct PendingMessage *pending;
598   size_t off;
599   size_t msize;
600
601   dn->cth = NULL;
602   if (NULL == buf)
603   {
604     /* client disconnected */
605     return 0;
606   }
607   off = 0;
608   while ( (NULL != (pending = dn->pm_head)) &&
609           (size >= off + (msize = ntohs (pending->msg->size))))
610   {
611     dn->pm_queue_size--;
612     GNUNET_CONTAINER_DLL_remove (dn->pm_head,
613                                  dn->pm_tail,
614                                  pending);
615     memcpy (&cbuf[off], pending->msg, msize);
616     if (0 != pending->uid)
617     {
618       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
619                   "Acking transmission of %u bytes to %s with plugin\n",
620                   msize,
621                   GNUNET_i2s (&pending->next_target));
622       send_ack_to_plugin (&pending->next_target,
623                           pending->uid,
624                           GNUNET_NO);
625     }
626     GNUNET_free (pending);
627     off += msize;
628   }
629   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
630               "Transmitting total of %u bytes to %s\n",
631               off,
632               GNUNET_i2s (&dn->peer));
633   GNUNET_assert (NULL != core_api);
634   if (NULL != pending)
635     dn->cth =
636       GNUNET_CORE_notify_transmit_ready (core_api,
637                                          GNUNET_YES /* cork */,
638                                          GNUNET_CORE_PRIO_BEST_EFFORT,
639                                          GNUNET_TIME_UNIT_FOREVER_REL,
640                                          &dn->peer,
641                                          msize,
642                                          &core_transmit_notify, dn);
643   return off;
644 }
645
646
647 /**
648  * Forward the given payload to the given target.
649  *
650  * @param target where to send the message
651  * @param distance distance to the @a sender
652  * @param uid unique ID for the message
653  * @param sender original sender of the message
654  * @param actual_target ultimate recipient for the message
655  * @param payload payload of the message
656  */
657 static void
658 forward_payload (struct DirectNeighbor *target,
659                  uint32_t distance,
660                  uint32_t uid,
661                  const struct GNUNET_PeerIdentity *sender,
662                  const struct GNUNET_PeerIdentity *actual_target,
663                  const struct GNUNET_MessageHeader *payload)
664 {
665   struct PendingMessage *pm;
666   struct RouteMessage *rm;
667   size_t msize;
668
669   if ( (target->pm_queue_size >= MAX_QUEUE_SIZE) &&
670        (0 == uid) &&
671        (0 != memcmp (sender,
672                      &my_identity,
673                      sizeof (struct GNUNET_PeerIdentity))) )
674   {
675     /* not _our_ client and queue is full, drop */
676     GNUNET_STATISTICS_update (stats,
677                               "# messages dropped",
678                               1, GNUNET_NO);
679     return;
680   }
681   msize = sizeof (struct RouteMessage) + ntohs (payload->size);
682   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
683   {
684     GNUNET_break (0);
685     return;
686   }
687   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
688   pm->next_target = target->peer;
689   pm->uid = uid;
690   pm->msg = (const struct GNUNET_MessageHeader *) &pm[1];
691   rm = (struct RouteMessage *) &pm[1];
692   rm->header.size = htons ((uint16_t) msize);
693   rm->header.type = htons (GNUNET_MESSAGE_TYPE_DV_ROUTE);
694   rm->distance = htonl (distance);
695   rm->target = *actual_target;
696   rm->sender = *sender;
697   memcpy (&rm[1], payload, ntohs (payload->size));
698   GNUNET_CONTAINER_DLL_insert_tail (target->pm_head,
699                                     target->pm_tail,
700                                     pm);
701   target->pm_queue_size++;
702   GNUNET_assert (NULL != core_api);
703   if (NULL == target->cth)
704     target->cth = GNUNET_CORE_notify_transmit_ready (core_api,
705                                                      GNUNET_YES /* cork */,
706                                                      GNUNET_CORE_PRIO_BEST_EFFORT,
707                                                      GNUNET_TIME_UNIT_FOREVER_REL,
708                                                      &target->peer,
709                                                      msize,
710                                                      &core_transmit_notify, target);
711 }
712
713
714 /**
715  * Find a free slot for storing a 'route' in the 'consensi'
716  * set at the given distance.
717  *
718  * @param distance distance to use for the set slot
719  */
720 static unsigned int
721 get_consensus_slot (uint32_t distance)
722 {
723   struct ConsensusSet *cs;
724   unsigned int i;
725
726   GNUNET_assert (distance < DEFAULT_FISHEYE_DEPTH);
727   cs = &consensi[distance];
728   i = 0;
729   while ( (i < cs->array_length) &&
730           (NULL != cs->targets[i]) ) i++;
731   if (i == cs->array_length)
732   {
733     GNUNET_array_grow (cs->targets,
734                        cs->array_length,
735                        cs->array_length * 2 + 2);
736   }
737   return i;
738 }
739
740
741 /**
742  * Allocate a slot in the consensus set for a route.
743  *
744  * @param route route to initialize
745  * @param distance which consensus set to use
746  */
747 static void
748 allocate_route (struct Route *route,
749                 uint32_t distance)
750 {
751   unsigned int i;
752
753   if (distance >= DEFAULT_FISHEYE_DEPTH)
754   {
755     route->target.distance = htonl (distance);
756     route->set_offset = UINT_MAX; /* invalid slot */
757     return;
758   }
759   i = get_consensus_slot (distance);
760   route->set_offset = i;
761   consensi[distance].targets[i] = route;
762   route->target.distance = htonl (distance);
763 }
764
765
766 /**
767  * Release a slot in the consensus set for a route.
768  *
769  * @param route route to release the slot from
770  */
771 static void
772 release_route (struct Route *route)
773 {
774   if (UINT_MAX == route->set_offset)
775     return;
776   GNUNET_assert (ntohl (route->target.distance) < DEFAULT_FISHEYE_DEPTH);
777   consensi[ntohl (route->target.distance)].targets[route->set_offset] = NULL;
778   route->set_offset = UINT_MAX; /* indicate invalid slot */
779 }
780
781
782 /**
783  * Move a route from one consensus set to another.
784  *
785  * @param route route to move
786  * @param new_distance new distance for the route (destination set)
787  */
788 static void
789 move_route (struct Route *route,
790             uint32_t new_distance)
791 {
792   release_route (route);
793   allocate_route (route, new_distance);
794 }
795
796
797 /**
798  * Initialize this neighbors 'my_set' and when done give
799  * it to the pending set operation for execution.
800  *
801  * Add a single element to the set per call:
802  *
803  * If we reached the last element of a consensus element: increase distance
804  *
805  *
806  * @param cls the neighbor for which we are building the set
807  */
808 static void
809 build_set (void *cls)
810 {
811   struct DirectNeighbor *neighbor = cls;
812   struct GNUNET_SET_Element element;
813   struct Target *target;
814   struct Route *route;
815
816   target = NULL;
817   /* skip over NULL entries */
818   while ( (DEFAULT_FISHEYE_DEPTH > neighbor->consensus_insertion_distance) &&
819           (consensi[neighbor->consensus_insertion_distance].array_length > neighbor->consensus_insertion_offset) &&
820           (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
821     neighbor->consensus_insertion_offset++;
822   while ( (DEFAULT_FISHEYE_DEPTH > neighbor->consensus_insertion_distance) &&
823           (consensi[neighbor->consensus_insertion_distance].array_length == neighbor->consensus_insertion_offset) )
824   {
825     /* If we reached the last element of a consensus array element: increase distance and start with next array */
826     neighbor->consensus_insertion_offset = 0;
827     neighbor->consensus_insertion_distance++;
828     /* skip over NULL entries */
829     while ( (DEFAULT_FISHEYE_DEPTH > neighbor->consensus_insertion_distance) &&
830             (consensi[neighbor->consensus_insertion_distance].array_length  > neighbor->consensus_insertion_offset) &&
831             (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
832       neighbor->consensus_insertion_offset++;
833   }
834   if (DEFAULT_FISHEYE_DEPTH == neighbor->consensus_insertion_distance)
835   {
836     /* we have added all elements to the set, run the operation */
837     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
838                 "Finished building my SET for peer `%s' with %u elements, committing\n",
839                 GNUNET_i2s (&neighbor->peer),
840                 neighbor->consensus_elements);
841     GNUNET_SET_commit (neighbor->set_op,
842                        neighbor->my_set);
843     GNUNET_SET_destroy (neighbor->my_set);
844     neighbor->my_set = NULL;
845     return;
846   }
847
848   route = consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset];
849   GNUNET_assert (NULL != route);
850   target = &route->target;
851   GNUNET_assert (ntohl (target->distance) < DEFAULT_FISHEYE_DEPTH);
852   element.size = sizeof (struct Target);
853   element.element_type = htons (0);
854   element.data = target;
855
856   /* Find next non-NULL entry */
857   neighbor->consensus_insertion_offset++;
858   if ( (0 != memcmp (&target->peer, &my_identity, sizeof (my_identity))) &&
859        (0 != memcmp (&target->peer, &neighbor->peer, sizeof (neighbor->peer))) )
860   {
861     /* Add target if it is not the neighbor or this peer */
862     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
863                 "Adding peer `%s' with distance %u to SET\n",
864                 GNUNET_i2s (&target->peer),
865                 ntohl (target->distance) + 1);
866     GNUNET_SET_add_element (neighbor->my_set,
867                             &element,
868                             &build_set, neighbor);
869     neighbor->consensus_elements++;
870   }
871   else
872     build_set (neighbor);
873 }
874
875
876 /**
877  * A peer is now connected to us at distance 1.  Initiate DV exchange.
878  *
879  * @param neighbor entry for the neighbor at distance 1
880  */
881 static void
882 handle_direct_connect (struct DirectNeighbor *neighbor)
883 {
884   struct Route *route;
885   struct GNUNET_HashCode h1;
886   struct GNUNET_HashCode h2;
887   struct GNUNET_HashCode session_id;
888
889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890               "Direct connection to %s established, routing table exchange begins.\n",
891               GNUNET_i2s (&neighbor->peer));
892   GNUNET_STATISTICS_update (stats,
893                             "# peers connected (1-hop)",
894                             1, GNUNET_NO);
895   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
896                                              &neighbor->peer);
897   if (NULL != route)
898   {
899     GNUNET_assert (GNUNET_YES ==
900                    GNUNET_CONTAINER_multipeermap_remove (all_routes,
901                                                          &neighbor->peer,
902                                                          route));
903     send_disconnect_to_plugin (&neighbor->peer);
904     release_route (route);
905     GNUNET_free (route);
906   }
907
908   neighbor->direct_route = GNUNET_new (struct Route);
909   neighbor->direct_route->next_hop = neighbor;
910   neighbor->direct_route->target.peer = neighbor->peer;
911   allocate_route (neighbor->direct_route, DIRECT_NEIGHBOR_COST);
912
913   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
914               "Adding direct route to %s\n",
915               GNUNET_i2s (&neighbor->direct_route->target.peer));
916
917
918   /* construct session ID seed as XOR of both peer's identities */
919   GNUNET_CRYPTO_hash (&my_identity, sizeof (my_identity), &h1);
920   GNUNET_CRYPTO_hash (&neighbor->peer, sizeof (struct GNUNET_PeerIdentity), &h2);
921   GNUNET_CRYPTO_hash_xor (&h1,
922                           &h2,
923                           &session_id);
924   /* make sure session ID is unique across applications by salting it with 'DV' */
925   GNUNET_CRYPTO_hkdf (&neighbor->real_session_id, sizeof (struct GNUNET_HashCode),
926                       GCRY_MD_SHA512, GCRY_MD_SHA256,
927                       "DV-SALT", 2,
928                       &session_id, sizeof (session_id),
929                       NULL, 0);
930   if (0 < memcmp (&neighbor->peer,
931                   &my_identity,
932                   sizeof (struct GNUNET_PeerIdentity)))
933   {
934     if (NULL != neighbor->listen_handle)
935     {
936       GNUNET_break (0);
937     }
938     else
939       neighbor->initiate_task = GNUNET_SCHEDULER_add_now (&initiate_set_union,
940                                                           neighbor);
941   }
942   else
943   {
944     if (NULL != neighbor->listen_handle)
945     {
946       GNUNET_break (0);
947     }
948     else
949     {
950       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
951                   "Starting SET listen operation with peer `%s'\n",
952                   GNUNET_i2s(&neighbor->peer));
953       neighbor->listen_handle = GNUNET_SET_listen (cfg,
954                                                    GNUNET_SET_OPERATION_UNION,
955                                                    &neighbor->real_session_id,
956                                                    &listen_set_union,
957                                                    neighbor);
958     }
959   }
960 }
961
962
963 /**
964  * Method called whenever a peer connects.
965  *
966  * @param cls closure
967  * @param peer peer identity this notification is about
968  */
969 static void
970 handle_core_connect (void *cls,
971                      const struct GNUNET_PeerIdentity *peer)
972 {
973   struct DirectNeighbor *neighbor;
974
975   /* Check for connect to self message */
976   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
977     return;
978   /* check if entry exists */
979   neighbor = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
980                                                 peer);
981   if (NULL != neighbor)
982   {
983     GNUNET_break (GNUNET_ATS_NET_UNSPECIFIED != neighbor->network);
984     GNUNET_break (GNUNET_YES != neighbor->connected);
985     neighbor->connected = GNUNET_YES;
986     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
987                 "Core connected to %s (distance %u)\n",
988                 GNUNET_i2s (peer),
989                 (unsigned int) neighbor->distance);
990     if (DIRECT_NEIGHBOR_COST != neighbor->distance)
991       return;
992     handle_direct_connect (neighbor);
993     return;
994   }
995   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
996               "Core connected to %s (distance unknown)\n",
997               GNUNET_i2s (peer));
998   neighbor = GNUNET_new (struct DirectNeighbor);
999   neighbor->peer = *peer;
1000   GNUNET_assert (GNUNET_YES ==
1001                  GNUNET_CONTAINER_multipeermap_put (direct_neighbors,
1002                                                     peer,
1003                                                     neighbor,
1004                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1005   neighbor->connected = GNUNET_YES;
1006   neighbor->distance = 0; /* unknown */
1007   neighbor->network = GNUNET_ATS_NET_UNSPECIFIED;
1008 }
1009
1010
1011 /**
1012  * Called for each 'target' in a neighbor table to free the associated memory.
1013  *
1014  * @param cls NULL
1015  * @param key key of the value
1016  * @param value value to free
1017  * @return #GNUNET_OK to continue to iterate
1018  */
1019 static int
1020 free_targets (void *cls,
1021               const struct GNUNET_PeerIdentity *key,
1022               void *value)
1023 {
1024   GNUNET_free (value);
1025   return GNUNET_OK;
1026 }
1027
1028
1029 /**
1030  * Add a new route to the given @a target via the given @a neighbor.
1031  *
1032  * @param target the target of the route
1033  * @param neighbor the next hop for communicating with the @a target
1034  */
1035 static void
1036 add_new_route (struct Target *target,
1037                struct DirectNeighbor *neighbor)
1038 {
1039   struct Route *route;
1040
1041   route = GNUNET_new (struct Route);
1042   route->next_hop = neighbor;
1043   route->target.peer = target->peer;
1044   allocate_route (route, ntohl (target->distance) + 1);
1045   GNUNET_assert (GNUNET_YES ==
1046                  GNUNET_CONTAINER_multipeermap_put (all_routes,
1047                                                     &route->target.peer,
1048                                                     route,
1049                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1050   send_connect_to_plugin (&route->target.peer,
1051                           ntohl (route->target.distance),
1052                           neighbor->network);
1053 }
1054
1055
1056 /**
1057  * Multipeerhmap iterator for checking if a given route is
1058  * (now) useful to this peer.
1059  *
1060  * @param cls the direct neighbor for the given route
1061  * @param key key value stored under
1062  * @param value a 'struct Target' that may or may not be useful; not that
1063  *        the distance in 'target' does not include the first hop yet
1064  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
1065  */
1066 static int
1067 check_possible_route (void *cls,
1068                       const struct GNUNET_PeerIdentity *key,
1069                       void *value)
1070 {
1071   struct DirectNeighbor *neighbor = cls;
1072   struct Target *target = value;
1073   struct Route *route;
1074
1075   if (GNUNET_YES ==
1076       GNUNET_CONTAINER_multipeermap_contains (direct_neighbors,
1077                                               key))
1078     return GNUNET_YES; /* direct route, do not care about alternatives */
1079   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1080                                              key);
1081   if (NULL != route)
1082   {
1083     /* we have an existing route, check how it compares with going via 'target' */
1084     if (ntohl (route->target.distance) > ntohl (target->distance) + 1)
1085     {
1086       /* via 'target' is cheaper than the existing route; switch to alternative route! */
1087       move_route (route, ntohl (target->distance) + 1);
1088       route->next_hop = neighbor;
1089       send_distance_change_to_plugin (&target->peer,
1090                                       ntohl (target->distance) + 1,
1091                                       neighbor->network);
1092     }
1093     return GNUNET_YES; /* got a route to this target already */
1094   }
1095   if (ntohl (target->distance) >= DEFAULT_FISHEYE_DEPTH)
1096     return GNUNET_YES; /* distance is too large to be interesting */
1097   add_new_route (target, neighbor);
1098   return GNUNET_YES;
1099 }
1100
1101
1102 /**
1103  * Multipeermap iterator for finding routes that were previously
1104  * "hidden" due to a better route (called after a disconnect event).
1105  *
1106  * @param cls NULL
1107  * @param key peer identity of the given direct neighbor
1108  * @param value a `struct DirectNeighbor` to check for additional routes
1109  * @return #GNUNET_YES to continue iteration
1110  */
1111 static int
1112 refresh_routes (void *cls,
1113                 const struct GNUNET_PeerIdentity *key,
1114                 void *value)
1115 {
1116   struct DirectNeighbor *neighbor = value;
1117
1118   if ( (GNUNET_YES != neighbor->connected) ||
1119        (DIRECT_NEIGHBOR_COST != neighbor->distance) )
1120     return GNUNET_YES;
1121   if (NULL != neighbor->neighbor_table)
1122     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1123                                            &check_possible_route,
1124                                            neighbor);
1125   return GNUNET_YES;
1126 }
1127
1128
1129 /**
1130  * Task to run #refresh_routes() on all direct neighbours.
1131  *
1132  * @param cls NULL
1133  */
1134 static void
1135 refresh_routes_task (void *cls)
1136 {
1137   rr_task = NULL;
1138   GNUNET_CONTAINER_multipeermap_iterate (direct_neighbors,
1139                                          &refresh_routes,
1140                                          NULL);
1141 }
1142
1143
1144 /**
1145  * Asynchronously run #refresh_routes() at the next opportunity
1146  * on all direct neighbours.
1147  */
1148 static void
1149 schedule_refresh_routes ()
1150 {
1151   if (NULL == rr_task)
1152     rr_task = GNUNET_SCHEDULER_add_now (&refresh_routes_task,
1153                                         NULL);
1154 }
1155
1156
1157 /**
1158  * Multipeermap iterator for freeing routes that go via a particular
1159  * neighbor that disconnected and is thus no longer available.
1160  *
1161  * @param cls the direct neighbor that is now unavailable
1162  * @param key key value stored under
1163  * @param value a `struct Route` that may or may not go via neighbor
1164  *
1165  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
1166  */
1167 static int
1168 cull_routes (void *cls,
1169              const struct GNUNET_PeerIdentity *key,
1170              void *value)
1171 {
1172   struct DirectNeighbor *neighbor = cls;
1173   struct Route *route = value;
1174
1175   if (route->next_hop != neighbor)
1176     return GNUNET_YES; /* not affected */
1177   GNUNET_assert (GNUNET_YES ==
1178                  GNUNET_CONTAINER_multipeermap_remove (all_routes, key, value));
1179   release_route (route);
1180   send_disconnect_to_plugin (&route->target.peer);
1181   GNUNET_free (route);
1182   return GNUNET_YES;
1183 }
1184
1185
1186 /**
1187  * Handle the case that a direct connection to a peer is
1188  * disrupted.  Remove all routes via that peer and
1189  * stop the consensus with it.
1190  *
1191  * @param neighbor peer that was disconnected (or at least is no
1192  *    longer at distance 1)
1193  */
1194 static void
1195 handle_direct_disconnect (struct DirectNeighbor *neighbor)
1196 {
1197   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1198               "Culling routes via %s due to direct disconnect\n",
1199               GNUNET_i2s (&neighbor->peer));
1200   GNUNET_CONTAINER_multipeermap_iterate (all_routes,
1201                                          &cull_routes,
1202                                          neighbor);
1203   if (NULL != neighbor->cth)
1204   {
1205     GNUNET_CORE_notify_transmit_ready_cancel (neighbor->cth);
1206     neighbor->cth = NULL;
1207   }
1208
1209   if (NULL != neighbor->direct_route)
1210   {
1211     release_route (neighbor->direct_route);
1212     GNUNET_free (neighbor->direct_route);
1213     neighbor->direct_route = NULL;
1214   }
1215
1216   if (NULL != neighbor->neighbor_table_consensus)
1217   {
1218     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table_consensus,
1219                                            &free_targets,
1220                                            NULL);
1221     GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table_consensus);
1222     neighbor->neighbor_table_consensus = NULL;
1223   }
1224   if (NULL != neighbor->neighbor_table)
1225   {
1226     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1227                                            &free_targets,
1228                                            NULL);
1229     GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table);
1230     neighbor->neighbor_table = NULL;
1231   }
1232   if (NULL != neighbor->set_op)
1233   {
1234     GNUNET_SET_operation_cancel (neighbor->set_op);
1235     neighbor->set_op = NULL;
1236   }
1237   if (NULL != neighbor->my_set)
1238   {
1239     GNUNET_SET_destroy (neighbor->my_set);
1240     neighbor->my_set = NULL;
1241   }
1242   if (NULL != neighbor->listen_handle)
1243   {
1244     GNUNET_SET_listen_cancel (neighbor->listen_handle);
1245     neighbor->listen_handle = NULL;
1246   }
1247   if (NULL != neighbor->initiate_task)
1248   {
1249     GNUNET_SCHEDULER_cancel (neighbor->initiate_task);
1250     neighbor->initiate_task = NULL;
1251   }
1252 }
1253
1254
1255 /**
1256  * Function that is called with QoS information about an address; used
1257  * to update our current distance to another peer.
1258  *
1259  * @param cls closure
1260  * @param address the address
1261  * @param active #GNUNET_YES if this address is actively used
1262  *        to maintain a connection to a peer;
1263  *        #GNUNET_NO if the address is not actively used;
1264  *        #GNUNET_SYSERR if this address is no longer available for ATS
1265  * @param bandwidth_out assigned outbound bandwidth for the connection
1266  * @param bandwidth_in assigned inbound bandwidth for the connection
1267  * @param prop performance data for the address (as far as known)
1268  */
1269 static void
1270 handle_ats_update (void *cls,
1271                    const struct GNUNET_HELLO_Address *address,
1272                    int active,
1273                    struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1274                    struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1275                    const struct GNUNET_ATS_Properties *prop)
1276 {
1277   struct DirectNeighbor *neighbor;
1278   uint32_t distance;
1279   enum GNUNET_ATS_Network_Type network;
1280
1281   if (NULL == address)
1282   {
1283     /* ATS service temporarily disconnected */
1284     return;
1285   }
1286
1287   if (GNUNET_YES != active)
1288   {
1289     // FIXME: handle disconnect/inactive case too!
1290     return;
1291   }
1292   distance = prop->distance;
1293   network = prop->scope;
1294   GNUNET_break (GNUNET_ATS_NET_UNSPECIFIED != network);
1295   /* check if entry exists */
1296   neighbor = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
1297                                                 &address->peer);
1298   if (NULL != neighbor)
1299   {
1300     neighbor->network = network;
1301     if (neighbor->distance == distance)
1302       return; /* nothing new to see here, move along */
1303     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1304                 "ATS says distance to %s is now %u\n",
1305                 GNUNET_i2s (&address->peer),
1306                 (unsigned int) distance);
1307     if ( (DIRECT_NEIGHBOR_COST == neighbor->distance) &&
1308          (DIRECT_NEIGHBOR_COST == distance) )
1309       return; /* no change */
1310     if (DIRECT_NEIGHBOR_COST == neighbor->distance)
1311     {
1312       neighbor->distance = distance;
1313       GNUNET_STATISTICS_update (stats,
1314                                 "# peers connected (1-hop)",
1315                                 -1, GNUNET_NO);
1316       handle_direct_disconnect (neighbor);
1317       schedule_refresh_routes ();
1318       return;
1319     }
1320     neighbor->distance = distance;
1321     if (DIRECT_NEIGHBOR_COST != neighbor->distance)
1322       return;
1323     if (GNUNET_YES != neighbor->connected)
1324       return;
1325     handle_direct_connect (neighbor);
1326     return;
1327   }
1328   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1329               "ATS says distance to %s is now %u\n",
1330               GNUNET_i2s (&address->peer),
1331               (unsigned int) distance);
1332   neighbor = GNUNET_new (struct DirectNeighbor);
1333   neighbor->peer = address->peer;
1334   GNUNET_assert (GNUNET_YES ==
1335                  GNUNET_CONTAINER_multipeermap_put (direct_neighbors,
1336                                                     &address->peer,
1337                                                     neighbor,
1338                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1339   neighbor->connected = GNUNET_NO; /* not yet */
1340   neighbor->distance = distance;
1341   neighbor->network = network;
1342 }
1343
1344
1345 /**
1346  * Check if a target was removed from the set of the other peer; if so,
1347  * if we also used it for our route, we need to remove it from our
1348  * 'all_routes' set (and later check if an alternative path now exists).
1349  *
1350  * @param cls the `struct DirectNeighbor`
1351  * @param key peer identity for the target
1352  * @param value a `struct Target` previously reachable via the given neighbor
1353  */
1354 static int
1355 check_target_removed (void *cls,
1356                       const struct GNUNET_PeerIdentity *key,
1357                       void *value)
1358 {
1359   struct DirectNeighbor *neighbor = cls;
1360   struct Target *new_target;
1361   struct Route *current_route;
1362
1363   new_target = GNUNET_CONTAINER_multipeermap_get (neighbor->neighbor_table_consensus,
1364                                                   key);
1365   current_route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1366                                                      key);
1367   if (NULL != new_target)
1368   {
1369     /* target was in old set, is in new set */
1370     if ( (NULL != current_route) &&
1371          (current_route->next_hop == neighbor) &&
1372          (current_route->target.distance != new_target->distance) )
1373     {
1374       /* need to recalculate routes due to distance change */
1375       neighbor->target_removed = GNUNET_YES;
1376     }
1377     return GNUNET_OK;
1378   }
1379   /* target was revoked, check if it was used */
1380   if ( (NULL == current_route) ||
1381        (current_route->next_hop != neighbor) )
1382   {
1383     /* didn't matter, wasn't used */
1384     return GNUNET_OK;
1385   }
1386   /* remove existing route */
1387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1388               "Lost route to %s\n",
1389               GNUNET_i2s (&current_route->target.peer));
1390   GNUNET_assert (GNUNET_YES ==
1391                  GNUNET_CONTAINER_multipeermap_remove (all_routes, key, current_route));
1392   send_disconnect_to_plugin (&current_route->target.peer);
1393   release_route (current_route);
1394   GNUNET_free (current_route);
1395   neighbor->target_removed = GNUNET_YES;
1396   return GNUNET_OK;
1397 }
1398
1399
1400 /**
1401  * Check if a target was added to the set of the other peer; if it
1402  * was added or impoves the existing route, do the needed updates.
1403  *
1404  * @param cls the `struct DirectNeighbor`
1405  * @param key peer identity for the target
1406  * @param value a `struct Target` now reachable via the given neighbor
1407  */
1408 static int
1409 check_target_added (void *cls,
1410                     const struct GNUNET_PeerIdentity *key,
1411                     void *value)
1412 {
1413   struct DirectNeighbor *neighbor = cls;
1414   struct Target *target = value;
1415   struct Route *current_route;
1416
1417   /* target was revoked, check if it was used */
1418   current_route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1419                                                      key);
1420   if (NULL != current_route)
1421   {
1422     /* route exists */
1423     if (current_route->next_hop == neighbor)
1424     {
1425       /* we had the same route before, no change in target */
1426       if (ntohl (target->distance) + 1 != ntohl (current_route->target.distance))
1427       {
1428         /* but distance changed! */
1429         if (ntohl (target->distance) + 1 > DEFAULT_FISHEYE_DEPTH)
1430         {
1431           /* distance increased beyond what is allowed, kill route */
1432           GNUNET_assert (GNUNET_YES ==
1433                          GNUNET_CONTAINER_multipeermap_remove (all_routes,
1434                                                                key,
1435                                                                current_route));
1436           send_disconnect_to_plugin (key);
1437           release_route (current_route);
1438           GNUNET_free (current_route);
1439         }
1440         else
1441         {
1442           /* distance decreased, update route */
1443           move_route (current_route,
1444                       ntohl (target->distance) + 1);
1445           send_distance_change_to_plugin (&target->peer,
1446                                           ntohl (target->distance) + 1,
1447                                           neighbor->network);
1448         }
1449       }
1450       return GNUNET_OK;
1451     }
1452     if (ntohl (current_route->target.distance) <= ntohl (target->distance) + 1)
1453     {
1454       /* alternative, shorter route exists, ignore */
1455       return GNUNET_OK;
1456     }
1457     /* new route is better than the existing one, take over! */
1458     /* NOTE: minor security issue: malicious peers may advertise
1459        very short routes to take over longer paths; as we don't
1460        check that the shorter routes actually work, a malicious
1461        direct neighbor can use this to DoS our long routes */
1462
1463     move_route (current_route, ntohl (target->distance) + 1);
1464     current_route->next_hop = neighbor;
1465     send_distance_change_to_plugin (&target->peer,
1466                                     ntohl (target->distance) + 1,
1467                                     neighbor->network);
1468     return GNUNET_OK;
1469   }
1470   /* new route */
1471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1472               "Discovered new route to %s using %u hops\n",
1473               GNUNET_i2s (&target->peer),
1474               (unsigned int) (ntohl (target->distance) + 1));
1475   current_route = GNUNET_new (struct Route);
1476   current_route->next_hop = neighbor;
1477   current_route->target.peer = target->peer;
1478   allocate_route (current_route, ntohl (target->distance) + 1);
1479   GNUNET_assert (GNUNET_YES ==
1480                  GNUNET_CONTAINER_multipeermap_put (all_routes,
1481                                                     &current_route->target.peer,
1482                                                     current_route,
1483                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1484
1485   send_connect_to_plugin (&current_route->target.peer,
1486                           ntohl (current_route->target.distance),
1487                           neighbor->network);
1488   return GNUNET_OK;
1489 }
1490
1491
1492 /**
1493  * Callback for set operation results. Called for each element
1494  * in the result set.
1495  * We have learned a new route from the other peer.  Add it to the
1496  * route set we're building.
1497  *
1498  * @param cls the `struct DirectNeighbor` we're building the consensus with
1499  * @param element a result element, only valid if status is #GNUNET_SET_STATUS_OK
1500  * @param status see `enum GNUNET_SET_Status`
1501  */
1502 static void
1503 handle_set_union_result (void *cls,
1504                          const struct GNUNET_SET_Element *element,
1505                          enum GNUNET_SET_Status status)
1506 {
1507   struct DirectNeighbor *neighbor = cls;
1508   struct DirectNeighbor *dn;
1509   struct Target *target;
1510   char *status_str;
1511
1512   switch (status)
1513   {
1514   case GNUNET_SET_STATUS_OK:
1515     status_str = "GNUNET_SET_STATUS_OK";
1516     break;
1517   case GNUNET_SET_STATUS_FAILURE:
1518     status_str = "GNUNET_SET_STATUS_FAILURE";
1519     break;
1520   case GNUNET_SET_STATUS_HALF_DONE:
1521     status_str = "GNUNET_SET_STATUS_HALF_DONE";
1522     break;
1523   case GNUNET_SET_STATUS_DONE:
1524     status_str = "GNUNET_SET_STATUS_DONE";
1525     break;
1526   default:
1527     status_str = "UNDEFINED";
1528     break;
1529   }
1530
1531   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1532               "Got SET union result: %s\n",
1533               status_str);
1534   switch (status)
1535   {
1536   case GNUNET_SET_STATUS_OK:
1537     if (sizeof (struct Target) != element->size)
1538     {
1539       GNUNET_break_op (0);
1540       return;
1541     }
1542     if ( (NULL != (dn = GNUNET_CONTAINER_multipeermap_get (direct_neighbors, &((struct Target *) element->data)->peer))) && (DIRECT_NEIGHBOR_COST == dn->distance) )
1543     {
1544       /* this is a direct neighbor of ours, we do not care about routes
1545          to this peer */
1546       return;
1547     }
1548     target = GNUNET_new (struct Target);
1549     memcpy (target, element->data, sizeof (struct Target));
1550     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1551                 "Received information about peer `%s' with distance %u from SET\n",
1552                 GNUNET_i2s (&target->peer),
1553                 ntohl (target->distance) + 1);
1554
1555     if (NULL == neighbor->neighbor_table_consensus)
1556       neighbor->neighbor_table_consensus
1557         = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1558     if (GNUNET_YES !=
1559         GNUNET_CONTAINER_multipeermap_put (neighbor->neighbor_table_consensus,
1560                                            &target->peer,
1561                                            target,
1562                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1563     {
1564       GNUNET_break_op (0);
1565       GNUNET_free (target);
1566     }
1567     break;
1568   case GNUNET_SET_STATUS_FAILURE:
1569     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1570                 "Failed to establish DV union, will try again later\n");
1571     neighbor->set_op = NULL;
1572     if (NULL != neighbor->neighbor_table_consensus)
1573     {
1574       GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table_consensus,
1575                                              &free_targets,
1576                                              NULL);
1577       GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table_consensus);
1578       neighbor->neighbor_table_consensus = NULL;
1579     }
1580     if (0 < memcmp (&neighbor->peer,
1581                     &my_identity,
1582                     sizeof (struct GNUNET_PeerIdentity)))
1583       neighbor->initiate_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1584                                                               &initiate_set_union,
1585                                                               neighbor);
1586     break;
1587   case GNUNET_SET_STATUS_HALF_DONE:
1588     break;
1589   case GNUNET_SET_STATUS_DONE:
1590     /* we got all of our updates; integrate routing table! */
1591     neighbor->target_removed = GNUNET_NO;
1592     if (NULL == neighbor->neighbor_table_consensus)
1593       neighbor->neighbor_table_consensus = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1594     if (NULL != neighbor->neighbor_table)
1595       GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1596                                              &check_target_removed,
1597                                              neighbor);
1598     if (GNUNET_YES == neighbor->target_removed)
1599     {
1600       /* check if we got an alternative for the removed routes */
1601       schedule_refresh_routes ();
1602     }
1603     /* add targets that appeared (and check for improved routes) */
1604     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table_consensus,
1605                                            &check_target_added,
1606                                            neighbor);
1607     if (NULL != neighbor->neighbor_table)
1608     {
1609       GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1610                                              &free_targets,
1611                                              NULL);
1612       GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table);
1613       neighbor->neighbor_table = NULL;
1614     }
1615     neighbor->neighbor_table = neighbor->neighbor_table_consensus;
1616     neighbor->neighbor_table_consensus = NULL;
1617
1618     /* operation done, schedule next run! */
1619     neighbor->set_op = NULL;
1620     if (0 < memcmp (&neighbor->peer,
1621                     &my_identity,
1622                     sizeof (struct GNUNET_PeerIdentity)))
1623       neighbor->initiate_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1624                                                               &initiate_set_union,
1625                                                               neighbor);
1626     break;
1627   default:
1628     GNUNET_break (0);
1629     return;
1630   }
1631 }
1632
1633
1634 /**
1635  * Start creating a new DV set union construction, our neighbour has
1636  * asked for it (callback for listening peer).
1637  *
1638  * @param cls the 'struct DirectNeighbor' of the peer we're building
1639  *        a routing consensus with
1640  * @param other_peer the other peer
1641  * @param context_msg message with application specific information from
1642  *        the other peer
1643  * @param request request from the other peer, use GNUNET_SET_accept
1644  *        to accept it, otherwise the request will be refused
1645  *        Note that we don't use a return value here, as it is also
1646  *        necessary to specify the set we want to do the operation with,
1647  *        whith sometimes can be derived from the context message.
1648  *        Also necessary to specify the timeout.
1649  */
1650 static void
1651 listen_set_union (void *cls,
1652                   const struct GNUNET_PeerIdentity *other_peer,
1653                   const struct GNUNET_MessageHeader *context_msg,
1654                   struct GNUNET_SET_Request *request)
1655 {
1656   struct DirectNeighbor *neighbor = cls;
1657
1658   if (NULL == request)
1659     return; /* why??? */
1660   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1661               "Starting to create consensus with %s\n",
1662               GNUNET_i2s (&neighbor->peer));
1663   if (NULL != neighbor->set_op)
1664   {
1665     GNUNET_SET_operation_cancel (neighbor->set_op);
1666     neighbor->set_op = NULL;
1667   }
1668   if (NULL != neighbor->my_set)
1669   {
1670     GNUNET_SET_destroy (neighbor->my_set);
1671     neighbor->my_set = NULL;
1672   }
1673   neighbor->my_set = GNUNET_SET_create (cfg,
1674                                         GNUNET_SET_OPERATION_UNION);
1675   neighbor->set_op = GNUNET_SET_accept (request,
1676                                         GNUNET_SET_RESULT_ADDED,
1677                                         &handle_set_union_result,
1678                                         neighbor);
1679   neighbor->consensus_insertion_offset = 0;
1680   neighbor->consensus_insertion_distance = 0;
1681   neighbor->consensus_elements = 0;
1682   build_set (neighbor);
1683 }
1684
1685
1686 /**
1687  * Start creating a new DV set union by initiating the connection.
1688  *
1689  * @param cls the `struct DirectNeighbor *` of the peer we're building
1690  *        a routing consensus with
1691  */
1692 static void
1693 initiate_set_union (void *cls)
1694 {
1695   struct DirectNeighbor *neighbor = cls;
1696
1697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1698               "Initiating SET union with peer `%s'\n",
1699               GNUNET_i2s (&neighbor->peer));
1700   neighbor->initiate_task = NULL;
1701   neighbor->my_set = GNUNET_SET_create (cfg,
1702                                         GNUNET_SET_OPERATION_UNION);
1703   neighbor->set_op = GNUNET_SET_prepare (&neighbor->peer,
1704                                          &neighbor->real_session_id,
1705                                          NULL,
1706                                          GNUNET_SET_RESULT_ADDED,
1707                                          &handle_set_union_result,
1708                                          neighbor);
1709   neighbor->consensus_insertion_offset = 0;
1710   neighbor->consensus_insertion_distance = 0;
1711   neighbor->consensus_elements = 0;
1712   build_set (neighbor);
1713 }
1714
1715
1716 /**
1717  * Core handler for DV data messages.  Whatever this message
1718  * contains all we really have to do is rip it out of its
1719  * DV layering and give it to our pal the DV plugin to report
1720  * in with.
1721  *
1722  * @param cls closure
1723  * @param peer peer which sent the message (immediate sender)
1724  * @param message the message
1725  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the other peer violated the protocol
1726  */
1727 static int
1728 handle_dv_route_message (void *cls,
1729                          const struct GNUNET_PeerIdentity *peer,
1730                          const struct GNUNET_MessageHeader *message)
1731 {
1732   const struct RouteMessage *rm;
1733   const struct GNUNET_MessageHeader *payload;
1734   struct Route *route;
1735   struct DirectNeighbor *neighbor;
1736   struct DirectNeighbor *dn;
1737   struct Target *target;
1738   uint32_t distance;
1739   char me[5];
1740   char src[5];
1741   char prev[5];
1742   char dst[5];
1743
1744   if (ntohs (message->size) < sizeof (struct RouteMessage) + sizeof (struct GNUNET_MessageHeader))
1745   {
1746     GNUNET_break_op (0);
1747     return GNUNET_SYSERR;
1748   }
1749   rm = (const struct RouteMessage *) message;
1750   distance = ntohl (rm->distance);
1751   payload = (const struct GNUNET_MessageHeader *) &rm[1];
1752   if (ntohs (message->size) != sizeof (struct RouteMessage) + ntohs (payload->size))
1753   {
1754     GNUNET_break_op (0);
1755     return GNUNET_SYSERR;
1756   }
1757   strncpy (prev, GNUNET_i2s (peer), 4);
1758   strncpy (me, GNUNET_i2s (&my_identity), 4);
1759   strncpy (src, GNUNET_i2s (&rm->sender), 4);
1760   strncpy (dst, GNUNET_i2s (&rm->target), 4);
1761   prev[4] = me[4] = src[4] = dst[4] = '\0';
1762   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1763               "Handling DV message with %u bytes payload of type %u from %s to %s routed by %s to me (%s @ hop %u)\n",
1764               ntohs (message->size) - sizeof (struct RouteMessage),
1765               ntohs (payload->type),
1766               src, dst,
1767               prev, me,
1768               (unsigned int) distance + 1);
1769
1770   if (0 == memcmp (&rm->target,
1771                    &my_identity,
1772                    sizeof (struct GNUNET_PeerIdentity)))
1773   {
1774     if ((NULL
1775         != (dn = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
1776             &rm->sender))) && (DIRECT_NEIGHBOR_COST == dn->distance))
1777     {
1778       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1779                   "Discarding DV message, as %s is a direct neighbor\n",
1780                   GNUNET_i2s (&rm->sender));
1781       GNUNET_STATISTICS_update (stats,
1782                                 "# messages discarded (direct neighbor)",
1783                                 1, GNUNET_NO);
1784       return GNUNET_OK;
1785     }
1786     /* message is for me, check reverse route! */
1787     route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1788                                                &rm->sender);
1789     if ( (NULL == route) &&
1790          (distance < DEFAULT_FISHEYE_DEPTH) )
1791     {
1792       /* don't have reverse route yet, learn it! */
1793       neighbor = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
1794                                                     peer);
1795       if (NULL == neighbor)
1796       {
1797         GNUNET_break (0);
1798         return GNUNET_OK;
1799       }
1800       target = GNUNET_new (struct Target);
1801       target->peer = rm->sender;
1802       target->distance = htonl (distance);
1803       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1804                   "Learning sender %s at distance %u from delivery!\n",
1805                   GNUNET_i2s (&rm->sender),
1806                   (unsigned int) distance + 1);
1807       if (NULL == neighbor->neighbor_table)
1808         neighbor->neighbor_table = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1809       if (GNUNET_YES !=
1810           GNUNET_CONTAINER_multipeermap_put (neighbor->neighbor_table,
1811                                              &target->peer,
1812                                              target,
1813                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1814       {
1815         GNUNET_break_op (0);
1816         GNUNET_free (target);
1817         return GNUNET_OK;
1818       }
1819       add_new_route (target, neighbor);
1820     }
1821     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1822                 "Delivering %u bytes from %s to myself!\n",
1823                 ntohs (payload->size),
1824                 GNUNET_i2s (&rm->sender));
1825     send_data_to_plugin (payload,
1826                          &rm->sender,
1827                          1 + distance);
1828     return GNUNET_OK;
1829   }
1830   if ( (NULL == GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
1831                                                    &rm->sender)) &&
1832        (NULL == GNUNET_CONTAINER_multipeermap_get (all_routes,
1833                                                    &rm->sender)) )
1834   {
1835     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1836                 "Learning sender %s at distance %u from forwarding!\n",
1837                 GNUNET_i2s (&rm->sender),
1838                 1 + distance);
1839     neighbor = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
1840                                                   peer);
1841     if (NULL == neighbor)
1842     {
1843       GNUNET_break (0);
1844       return GNUNET_OK;
1845     }
1846     target = GNUNET_new (struct Target);
1847     target->peer = rm->sender;
1848     target->distance = htonl (distance);
1849     if (NULL == neighbor->neighbor_table)
1850       neighbor->neighbor_table = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1851     if (GNUNET_YES !=
1852         GNUNET_CONTAINER_multipeermap_put (neighbor->neighbor_table,
1853                                            &target->peer,
1854                                            target,
1855                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1856     {
1857       GNUNET_break_op (0);
1858       GNUNET_free (target);
1859       return GNUNET_OK;
1860     }
1861     add_new_route (target, neighbor);
1862   }
1863
1864   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1865                                              &rm->target);
1866   if (NULL == route)
1867   {
1868     neighbor = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
1869                                                   &rm->target);
1870     if (NULL == neighbor)
1871     {
1872       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1873                   "No route to %s, not routing %u bytes!\n",
1874                   GNUNET_i2s (&rm->target),
1875                   ntohs (payload->size));
1876       GNUNET_STATISTICS_update (stats,
1877                                 "# messages discarded (no route)",
1878                                 1, GNUNET_NO);
1879       return GNUNET_OK;
1880     }
1881   }
1882   else
1883   {
1884     neighbor = route->next_hop;
1885   }
1886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1887               "Forwarding message to %s\n",
1888               GNUNET_i2s (&neighbor->peer));
1889   forward_payload (neighbor,
1890                    distance + 1,
1891                    0,
1892                    &rm->sender,
1893                    &rm->target,
1894                    payload);
1895   return GNUNET_OK;
1896 }
1897
1898
1899 /**
1900  * Service server's handler for message send requests (which come
1901  * bubbling up to us through the DV plugin).
1902  *
1903  * @param cls closure
1904  * @param client identification of the client
1905  * @param message the actual message
1906  */
1907 static void
1908 handle_dv_send_message (void *cls, struct GNUNET_SERVER_Client *client,
1909                         const struct GNUNET_MessageHeader *message)
1910 {
1911   struct Route *route;
1912   const struct GNUNET_DV_SendMessage *msg;
1913   const struct GNUNET_MessageHeader *payload;
1914
1915   if (ntohs (message->size) < sizeof (struct GNUNET_DV_SendMessage) + sizeof (struct GNUNET_MessageHeader))
1916   {
1917     GNUNET_break (0);
1918     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1919     return;
1920   }
1921   msg = (const struct GNUNET_DV_SendMessage *) message;
1922   GNUNET_break (0 != ntohl (msg->uid));
1923   payload = (const struct GNUNET_MessageHeader *) &msg[1];
1924   if (ntohs (message->size) != sizeof (struct GNUNET_DV_SendMessage) + ntohs (payload->size))
1925   {
1926     GNUNET_break (0);
1927     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1928     return;
1929   }
1930   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1931                                              &msg->target);
1932   if (NULL == route)
1933   {
1934     /* got disconnected */
1935     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1936                 "No route to %s, dropping local message of type %u\n",
1937                 GNUNET_i2s (&msg->target),
1938                 ntohs (payload->type));
1939     GNUNET_STATISTICS_update (stats,
1940                               "# local messages discarded (no route)",
1941                               1, GNUNET_NO);
1942     send_ack_to_plugin (&msg->target, ntohl (msg->uid), GNUNET_YES);
1943     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1944     return;
1945   }
1946   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1947               "Forwarding %u bytes of type %u to %s\n",
1948               ntohs (payload->size),
1949               ntohs (payload->type),
1950               GNUNET_i2s (&msg->target));
1951
1952   forward_payload (route->next_hop,
1953                    0 /* first hop, distance is zero */,
1954                    htonl (msg->uid),
1955                    &my_identity,
1956                    &msg->target,
1957                    payload);
1958   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1959 }
1960
1961
1962 /**
1963  * Cleanup all of the data structures associated with a given neighbor.
1964  *
1965  * @param neighbor neighbor to clean up
1966  */
1967 static void
1968 cleanup_neighbor (struct DirectNeighbor *neighbor)
1969 {
1970   struct PendingMessage *pending;
1971
1972   while (NULL != (pending = neighbor->pm_head))
1973   {
1974     neighbor->pm_queue_size--;
1975     GNUNET_CONTAINER_DLL_remove (neighbor->pm_head,
1976                                  neighbor->pm_tail,
1977                                  pending);
1978     GNUNET_free (pending);
1979   }
1980   handle_direct_disconnect (neighbor);
1981   GNUNET_assert (GNUNET_YES ==
1982                  GNUNET_CONTAINER_multipeermap_remove (direct_neighbors,
1983                                                        &neighbor->peer,
1984                                                        neighbor));
1985   GNUNET_free (neighbor);
1986 }
1987
1988
1989 /**
1990  * Method called whenever a given peer disconnects.
1991  *
1992  * @param cls closure
1993  * @param peer peer identity this notification is about
1994  */
1995 static void
1996 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1997 {
1998   struct DirectNeighbor *neighbor;
1999
2000   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001               "Received core peer disconnect message for peer `%s'!\n",
2002               GNUNET_i2s (peer));
2003   /* Check for disconnect from self message */
2004   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
2005     return;
2006   neighbor =
2007       GNUNET_CONTAINER_multipeermap_get (direct_neighbors, peer);
2008   if (NULL == neighbor)
2009   {
2010     GNUNET_break (0);
2011     return;
2012   }
2013   GNUNET_break (GNUNET_YES == neighbor->connected);
2014   neighbor->connected = GNUNET_NO;
2015   if (DIRECT_NEIGHBOR_COST == neighbor->distance)
2016   {
2017
2018     GNUNET_STATISTICS_update (stats,
2019                               "# peers connected (1-hop)",
2020                               -1, GNUNET_NO);
2021   }
2022   cleanup_neighbor (neighbor);
2023
2024   if (GNUNET_YES == in_shutdown)
2025     return;
2026   schedule_refresh_routes ();
2027 }
2028
2029
2030 /**
2031  * Multipeermap iterator for freeing routes.  Should never be called.
2032  *
2033  * @param cls NULL
2034  * @param key key value stored under
2035  * @param value the route to be freed
2036  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
2037  */
2038 static int
2039 free_route (void *cls,
2040             const struct GNUNET_PeerIdentity *key,
2041             void *value)
2042 {
2043   struct Route *route = value;
2044
2045   GNUNET_break (0);
2046   GNUNET_assert (GNUNET_YES ==
2047                  GNUNET_CONTAINER_multipeermap_remove (all_routes, key, value));
2048   release_route (route);
2049   send_disconnect_to_plugin (&route->target.peer);
2050   GNUNET_free (route);
2051   return GNUNET_YES;
2052 }
2053
2054
2055 /**
2056  * Multipeermap iterator for freeing direct neighbors. Should never be called.
2057  *
2058  * @param cls NULL
2059  * @param key key value stored under
2060  * @param value the direct neighbor to be freed
2061  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
2062  */
2063 static int
2064 free_direct_neighbors (void *cls,
2065                        const struct GNUNET_PeerIdentity *key,
2066                        void *value)
2067 {
2068   struct DirectNeighbor *neighbor = value;
2069
2070   cleanup_neighbor (neighbor);
2071   return GNUNET_YES;
2072 }
2073
2074
2075 /**
2076  * Task run during shutdown.
2077  *
2078  * @param cls unused
2079  */
2080 static void
2081 shutdown_task (void *cls)
2082 {
2083   unsigned int i;
2084
2085   in_shutdown = GNUNET_YES;
2086   GNUNET_assert (NULL != core_api);
2087   GNUNET_CORE_disconnect (core_api);
2088   core_api = NULL;
2089   GNUNET_ATS_performance_done (ats);
2090   ats = NULL;
2091   GNUNET_CONTAINER_multipeermap_iterate (direct_neighbors,
2092                                          &free_direct_neighbors, NULL);
2093   GNUNET_CONTAINER_multipeermap_iterate (all_routes,
2094                                          &free_route, NULL);
2095   GNUNET_CONTAINER_multipeermap_destroy (direct_neighbors);
2096   GNUNET_CONTAINER_multipeermap_destroy (all_routes);
2097   GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2098   stats = NULL;
2099   GNUNET_SERVER_notification_context_destroy (nc);
2100   nc = NULL;
2101   for (i=0;i<DEFAULT_FISHEYE_DEPTH;i++)
2102   {
2103     GNUNET_array_grow (consensi[i].targets,
2104                        consensi[i].array_length,
2105                        0);
2106   }
2107   if (NULL != rr_task)
2108   {
2109     GNUNET_SCHEDULER_cancel (rr_task);
2110     rr_task = NULL;
2111   }
2112 }
2113
2114
2115 /**
2116  * Notify newly connected client about an existing route.
2117  *
2118  * @param cls the `struct GNUNET_SERVER_Client *`
2119  * @param key peer identity
2120  * @param value the `struct Route *`
2121  * @return #GNUNET_OK (continue to iterate)
2122  */
2123 static int
2124 notify_client_about_route (void *cls,
2125                            const struct GNUNET_PeerIdentity *key,
2126                            void *value)
2127 {
2128   struct GNUNET_SERVER_Client *client = cls;
2129   struct Route *route = value;
2130   struct GNUNET_DV_ConnectMessage cm;
2131
2132   memset (&cm, 0, sizeof (cm));
2133   cm.header.size = htons (sizeof (cm));
2134   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
2135   cm.distance = htonl (route->target.distance);
2136   cm.peer = route->target.peer;
2137
2138   GNUNET_SERVER_notification_context_unicast (nc,
2139                                               client,
2140                                               &cm.header,
2141                                               GNUNET_NO);
2142   return GNUNET_OK;
2143 }
2144
2145
2146 /**
2147  * Handle START-message.  This is the first message sent to us
2148  * by the client (can only be one!).
2149  *
2150  * @param cls closure (always NULL)
2151  * @param client identification of the client
2152  * @param message the actual message
2153  */
2154 static void
2155 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
2156               const struct GNUNET_MessageHeader *message)
2157 {
2158   GNUNET_SERVER_notification_context_add (nc, client);
2159   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2160   GNUNET_CONTAINER_multipeermap_iterate (all_routes,
2161                                          &notify_client_about_route,
2162                                          client);
2163 }
2164
2165
2166 /**
2167  * Called on core init.
2168  *
2169  * @param cls unused
2170  * @param identity this peer's identity
2171  */
2172 static void
2173 core_init (void *cls,
2174            const struct GNUNET_PeerIdentity *identity)
2175 {
2176   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2177               "I am peer: %s\n",
2178               GNUNET_i2s (identity));
2179   my_identity = *identity;
2180 }
2181
2182
2183 /**
2184  * Process dv requests.
2185  *
2186  * @param cls closure
2187  * @param server the initialized server
2188  * @param c configuration to use
2189  */
2190 static void
2191 run (void *cls, struct GNUNET_SERVER_Handle *server,
2192      const struct GNUNET_CONFIGURATION_Handle *c)
2193 {
2194   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2195     {&handle_dv_route_message, GNUNET_MESSAGE_TYPE_DV_ROUTE, 0},
2196     {NULL, 0, 0}
2197   };
2198   static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
2199     {&handle_start, NULL,
2200      GNUNET_MESSAGE_TYPE_DV_START,
2201      sizeof (struct GNUNET_MessageHeader) },
2202     { &handle_dv_send_message, NULL,
2203       GNUNET_MESSAGE_TYPE_DV_SEND,
2204       0},
2205     {NULL, NULL, 0, 0}
2206   };
2207   in_shutdown = GNUNET_NO;
2208   cfg = c;
2209   direct_neighbors = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
2210   all_routes = GNUNET_CONTAINER_multipeermap_create (65536, GNUNET_NO);
2211   core_api = GNUNET_CORE_connect (cfg, NULL,
2212                                   &core_init,
2213                                   &handle_core_connect,
2214                                   &handle_core_disconnect,
2215                                   NULL, GNUNET_NO,
2216                                   NULL, GNUNET_NO,
2217                                   core_handlers);
2218
2219   if (NULL == core_api)
2220     return;
2221   ats = GNUNET_ATS_performance_init (cfg, &handle_ats_update, NULL);
2222   if (NULL == ats)
2223   {
2224     GNUNET_CORE_disconnect (core_api);
2225     core_api = NULL;
2226     return;
2227   }
2228   nc = GNUNET_SERVER_notification_context_create (server,
2229                                                   MAX_QUEUE_SIZE_PLUGIN);
2230   stats = GNUNET_STATISTICS_create ("dv", cfg);
2231   GNUNET_SERVER_add_handlers (server, plugin_handlers);
2232   GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
2233 }
2234
2235
2236 /**
2237  * The main function for the dv service.
2238  *
2239  * @param argc number of arguments from the command line
2240  * @param argv command line arguments
2241  * @return 0 ok, 1 on error
2242  */
2243 int
2244 main (int argc, char *const *argv)
2245 {
2246   return (GNUNET_OK ==
2247           GNUNET_SERVICE_run (argc, argv, "dv", GNUNET_SERVICE_OPTION_NONE,
2248                               &run, NULL)) ? 0 : 1;
2249 }
2250
2251 /* end of gnunet-service-dv.c */