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