04176d747db51775dfd6c8a5f61727e23f79fdcc
[oweals/gnunet.git] / src / dv / gnunet-service-dv.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file dv/gnunet-service-dv.c
23  * @brief the distance vector service, primarily handles gossip of nearby
24  * peers and sending/receiving DV messages from core and decapsulating
25  * them
26  *
27  * @author Christian Grothoff
28  * @author Nathan Evans
29  */
30 #include "platform.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_core_service.h"
34 #include "gnunet_hello_lib.h"
35 #include "gnunet_peerinfo_service.h"
36 #include "gnunet_statistics_service.h"
37 #include "gnunet_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    * Ultimate target for the message.
149    */
150   struct GNUNET_PeerIdentity ultimate_target;
151
152   /**
153    * Unique ID of the message.
154    */
155   uint32_t uid;
156
157 };
158
159
160 /**
161  * Information about a direct neighbor (core-level, excluding
162  * DV-links, only DV-enabled peers).
163  */
164 struct DirectNeighbor
165 {
166
167   /**
168    * Identity of the peer.
169    */
170   struct GNUNET_PeerIdentity peer;
171
172   /**
173    * 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 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   GNUNET_SCHEDULER_TaskIdentifier 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   uint32_t 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 GNUNET_SCHEDULER_TaskIdentifier 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  * @param tc scheduler context
402  */
403 static void
404 initiate_set_union (void *cls,
405                     const struct GNUNET_SCHEDULER_TaskContext *tc);
406
407
408 /**
409  * Start creating a new DV set union construction, our neighbour has
410  * asked for it (callback for listening peer).
411  *
412  * @param cls the 'struct DirectNeighbor' of the peer we're building
413  *        a routing consensus with
414  * @param other_peer the other peer
415  * @param context_msg message with application specific information from
416  *        the other peer
417  * @param request request from the other peer, use GNUNET_SET_accept
418  *        to accept it, otherwise the request will be refused
419  *        Note that we don't use a return value here, as it is also
420  *        necessary to specify the set we want to do the operation with,
421  *        whith sometimes can be derived from the context message.
422  *        Also necessary to specify the timeout.
423  */
424 static void
425 listen_set_union (void *cls,
426                   const struct GNUNET_PeerIdentity *other_peer,
427                   const struct GNUNET_MessageHeader *context_msg,
428                   struct GNUNET_SET_Request *request);
429
430
431 /**
432  * Forward a message from another peer to the plugin.
433  *
434  * @param message the message to send to the plugin
435  * @param origin the original sender of the message
436  * @param distance distance to the original sender of the message
437  */
438 static void
439 send_data_to_plugin (const struct GNUNET_MessageHeader *message,
440                      const struct GNUNET_PeerIdentity *origin,
441                      uint32_t distance)
442 {
443   struct GNUNET_DV_ReceivedMessage *received_msg;
444   size_t size;
445
446   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
447               "Delivering message from peer `%s'\n",
448               GNUNET_i2s (origin));
449   size = sizeof (struct GNUNET_DV_ReceivedMessage) +
450     ntohs (message->size);
451   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
452   {
453     GNUNET_break (0); /* too big */
454     return;
455   }
456   received_msg = GNUNET_malloc (size);
457   received_msg->header.size = htons (size);
458   received_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DV_RECV);
459   received_msg->distance = htonl (distance);
460   received_msg->sender = *origin;
461   memcpy (&received_msg[1], message, ntohs (message->size));
462   GNUNET_SERVER_notification_context_broadcast (nc,
463                                                 &received_msg->header,
464                                                 GNUNET_YES);
465   GNUNET_free (received_msg);
466 }
467
468
469 /**
470  * Forward a control message to the plugin.
471  *
472  * @param message the message to send to the plugin
473  */
474 static void
475 send_control_to_plugin (const struct GNUNET_MessageHeader *message)
476 {
477   GNUNET_SERVER_notification_context_broadcast (nc,
478                                                 message,
479                                                 GNUNET_NO);
480 }
481
482
483 /**
484  * Give an (N)ACK message to the plugin, we transmitted a message for it.
485  *
486  * @param target peer that received the message
487  * @param uid plugin-chosen UID for the message
488  * @param nack #GNUNET_NO to send ACK, #GNUNET_YES to send NACK
489  */
490 static void
491 send_ack_to_plugin (const struct GNUNET_PeerIdentity *target,
492                     uint32_t uid,
493                     int nack)
494 {
495   struct GNUNET_DV_AckMessage ack_msg;
496
497   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
498               "Delivering ACK for message to peer `%s'\n",
499               GNUNET_i2s (target));
500   ack_msg.header.size = htons (sizeof (ack_msg));
501   ack_msg.header.type = htons ((GNUNET_YES == nack)
502                                ? GNUNET_MESSAGE_TYPE_DV_SEND_NACK
503                                : GNUNET_MESSAGE_TYPE_DV_SEND_ACK);
504   ack_msg.uid = htonl (uid);
505   ack_msg.target = *target;
506   send_control_to_plugin (&ack_msg.header);
507 }
508
509
510 /**
511  * Send a DISTANCE_CHANGED message to the plugin.
512  *
513  * @param peer peer with a changed distance
514  * @param distance new distance to the peer
515  */
516 static void
517 send_distance_change_to_plugin (const struct GNUNET_PeerIdentity *peer,
518                                 uint32_t distance)
519 {
520   struct GNUNET_DV_DistanceUpdateMessage du_msg;
521
522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
523               "Delivering DISTANCE_CHANGED for message about peer `%s'\n",
524               GNUNET_i2s (peer));
525   du_msg.header.size = htons (sizeof (du_msg));
526   du_msg.header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISTANCE_CHANGED);
527   du_msg.distance = htonl (distance);
528   du_msg.peer = *peer;
529   send_control_to_plugin (&du_msg.header);
530 }
531
532
533 /**
534  * Give a CONNECT message to the plugin.
535  *
536  * @param target peer that connected
537  * @param distance distance to the target
538  * @param network the network the next hop is located in
539  */
540 static void
541 send_connect_to_plugin (const struct GNUNET_PeerIdentity *target,
542                         uint32_t distance, uint32_t network)
543 {
544   struct GNUNET_DV_ConnectMessage cm;
545
546   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
547               "Delivering CONNECT about peer `%s' with distance %u\n",
548               GNUNET_i2s (target), distance);
549   cm.header.size = htons (sizeof (cm));
550   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
551   cm.distance = htonl (distance);
552   cm.network = htonl (network);
553   cm.peer = *target;
554   send_control_to_plugin (&cm.header);
555 }
556
557
558 /**
559  * Give a DISCONNECT message to the plugin.
560  *
561  * @param target peer that disconnected
562  */
563 static void
564 send_disconnect_to_plugin (const struct GNUNET_PeerIdentity *target)
565 {
566   struct GNUNET_DV_DisconnectMessage dm;
567
568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
569               "Delivering DISCONNECT about peer `%s'\n",
570               GNUNET_i2s (target));
571   dm.header.size = htons (sizeof (dm));
572   dm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISCONNECT);
573   dm.reserved = htonl (0);
574   dm.peer = *target;
575   send_control_to_plugin (&dm.header);
576 }
577
578
579 /**
580  * Function called to transfer a message to another peer
581  * via core.
582  *
583  * @param cls closure with the direct neighbor
584  * @param size number of bytes available in buf
585  * @param buf where the callee should write the message
586  * @return number of bytes written to buf
587  */
588 static size_t
589 core_transmit_notify (void *cls, size_t size, void *buf)
590 {
591   struct DirectNeighbor *dn = cls;
592   char *cbuf = buf;
593   struct PendingMessage *pending;
594   size_t off;
595   size_t msize;
596
597   dn->cth = NULL;
598   if (NULL == buf)
599   {
600     /* peer disconnected */
601     return 0;
602   }
603   off = 0;
604   while ( (NULL != (pending = dn->pm_head)) &&
605           (size >= off + (msize = ntohs (pending->msg->size))))
606   {
607     dn->pm_queue_size--;
608     GNUNET_CONTAINER_DLL_remove (dn->pm_head,
609                                  dn->pm_tail,
610                                  pending);
611     memcpy (&cbuf[off], pending->msg, msize);
612     if (0 != pending->uid)
613       send_ack_to_plugin (&pending->ultimate_target,
614                           pending->uid,
615                           GNUNET_NO);
616     GNUNET_free (pending);
617     off += msize;
618   }
619   GNUNET_assert (NULL != core_api);
620   if (NULL != dn->pm_head)
621     dn->cth =
622       GNUNET_CORE_notify_transmit_ready (core_api,
623                                          GNUNET_YES /* cork */,
624                                          0 /* priority */,
625                                          GNUNET_TIME_UNIT_FOREVER_REL,
626                                          &dn->peer,
627                                          msize,
628                                          &core_transmit_notify, dn);
629   return off;
630 }
631
632
633 /**
634  * Forward the given payload to the given target.
635  *
636  * @param target where to send the message
637  * @param uid unique ID for the message
638  * @param ultimate_target ultimate recipient for the message
639  * @param distance expected (remaining) distance to the target
640  * @param sender original sender of the message
641  * @param payload payload of the message
642  */
643 static void
644 forward_payload (struct DirectNeighbor *target,
645                  uint32_t distance,
646                  uint32_t uid,
647                  const struct GNUNET_PeerIdentity *sender,
648                  const struct GNUNET_PeerIdentity *ultimate_target,
649                  const struct GNUNET_MessageHeader *payload)
650 {
651   struct PendingMessage *pm;
652   struct RouteMessage *rm;
653   size_t msize;
654
655   if ( (target->pm_queue_size >= MAX_QUEUE_SIZE) &&
656        (0 != memcmp (sender,
657                      &my_identity,
658                      sizeof (struct GNUNET_PeerIdentity))) )
659   {
660     GNUNET_break (0 == uid);
661     return;
662   }
663   msize = sizeof (struct RouteMessage) + ntohs (payload->size);
664   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
665   {
666     GNUNET_break (0);
667     return;
668   }
669   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
670   pm->ultimate_target = *ultimate_target;
671   pm->uid = uid;
672   pm->msg = (const struct GNUNET_MessageHeader *) &pm[1];
673   rm = (struct RouteMessage *) &pm[1];
674   rm->header.size = htons ((uint16_t) msize);
675   rm->header.type = htons (GNUNET_MESSAGE_TYPE_DV_ROUTE);
676   rm->distance = htonl (distance);
677   rm->target = target->peer;
678   rm->sender = *sender;
679   memcpy (&rm[1], payload, ntohs (payload->size));
680   GNUNET_CONTAINER_DLL_insert_tail (target->pm_head,
681                                     target->pm_tail,
682                                     pm);
683   target->pm_queue_size++;
684   GNUNET_assert (NULL != core_api);
685   if (NULL == target->cth)
686     target->cth = GNUNET_CORE_notify_transmit_ready (core_api,
687                                                      GNUNET_YES /* cork */,
688                                                      0 /* priority */,
689                                                      GNUNET_TIME_UNIT_FOREVER_REL,
690                                                      &target->peer,
691                                                      msize,
692                                                      &core_transmit_notify, target);
693 }
694
695
696 /**
697  * Find a free slot for storing a 'route' in the 'consensi'
698  * set at the given distance.
699  *
700  * @param distance distance to use for the set slot
701  */
702 static unsigned int
703 get_consensus_slot (uint32_t distance)
704 {
705   struct ConsensusSet *cs;
706   unsigned int i;
707
708   GNUNET_assert (distance < DEFAULT_FISHEYE_DEPTH);
709   cs = &consensi[distance];
710   i = 0;
711   while ( (i < cs->array_length) &&
712           (NULL != cs->targets[i]) ) i++;
713   if (i == cs->array_length)
714   {
715     GNUNET_array_grow (cs->targets,
716                        cs->array_length,
717                        cs->array_length * 2 + 2);
718   }
719   return i;
720 }
721
722
723 /**
724  * Allocate a slot in the consensus set for a route.
725  *
726  * @param route route to initialize
727  * @param distance which consensus set to use
728  */
729 static void
730 allocate_route (struct Route *route,
731                 uint32_t distance)
732 {
733   unsigned int i;
734
735   if (distance >= DEFAULT_FISHEYE_DEPTH)
736   {
737     route->set_offset = UINT_MAX; /* invalid slot */
738     return;
739   }
740   i = get_consensus_slot (distance);
741   route->set_offset = i;
742   consensi[distance].targets[i] = route;
743   route->target.distance = htonl (distance);
744 }
745
746
747 /**
748  * Release a slot in the consensus set for a route.
749  *
750  * @param route route to release the slot from
751  */
752 static void
753 release_route (struct Route *route)
754 {
755   if (UINT_MAX == route->set_offset)
756     return;
757   GNUNET_assert (ntohl (route->target.distance) < DEFAULT_FISHEYE_DEPTH);
758   consensi[ntohl (route->target.distance)].targets[route->set_offset] = NULL;
759   route->set_offset = UINT_MAX; /* indicate invalid slot */
760 }
761
762
763 /**
764  * Move a route from one consensus set to another.
765  *
766  * @param route route to move
767  * @param new_distance new distance for the route (destination set)
768  */
769 static void
770 move_route (struct Route *route,
771             uint32_t new_distance)
772 {
773   unsigned int i;
774
775   release_route (route);
776   if (new_distance >= DEFAULT_FISHEYE_DEPTH)
777     return; /* no longer interesting for 'consensi' */
778   i = get_consensus_slot (new_distance);
779   route->set_offset = i;
780   consensi[new_distance].targets[i] = route;
781   route->target.distance = htonl (new_distance);
782 }
783
784
785 /**
786  * Initialize this neighbors 'my_set' and when done give
787  * it to the pending set operation for execution.
788  *
789  * Add a single element to the set per call:
790  *
791  * If we reached the last element of a consensus element: increase distance
792  *
793  *
794  * @param cls the neighbor for which we are building the set
795  */
796 static void
797 build_set (void *cls)
798 {
799   struct DirectNeighbor *neighbor = cls;
800   struct GNUNET_SET_Element element;
801   struct Target *target;
802   target = NULL;
803   while ( (DEFAULT_FISHEYE_DEPTH > neighbor->consensus_insertion_distance) &&
804           (consensi[neighbor->consensus_insertion_distance].array_length == neighbor->consensus_insertion_offset) )
805   {
806     /* If we reached the last element of a consensus array element: increase distance and start with next array */
807     neighbor->consensus_insertion_offset = 0;
808     neighbor->consensus_insertion_distance++;
809     /* skip over NULL entries */
810     while ( (DEFAULT_FISHEYE_DEPTH > neighbor->consensus_insertion_distance) &&
811             (consensi[neighbor->consensus_insertion_distance].array_length  > neighbor->consensus_insertion_offset) &&
812             (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
813       neighbor->consensus_insertion_offset++;
814   }
815   if (DEFAULT_FISHEYE_DEPTH == neighbor->consensus_insertion_distance)
816   {
817     /* we have added all elements to the set, run the operation */
818     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
819                 "Finished building my SET for peer `%s' with %u elements, committing\n",
820                 GNUNET_i2s (&neighbor->peer),
821                 neighbor->consensus_elements);
822     GNUNET_SET_commit (neighbor->set_op,
823                        neighbor->my_set);
824     GNUNET_SET_destroy (neighbor->my_set);
825     neighbor->my_set = NULL;
826     return;
827   }
828
829   target = &consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]->target;
830   element.size = sizeof (struct Target);
831   element.type = htons (0); /* do we need this? */
832   element.data = target;
833
834   /* Find next non-NULL entry */
835   neighbor->consensus_insertion_offset++;
836   /* skip over NULL entries */
837   while ( (DEFAULT_FISHEYE_DEPTH > neighbor->consensus_insertion_distance) &&
838           (consensi[neighbor->consensus_insertion_distance].array_length > neighbor->consensus_insertion_offset) &&
839           (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
840   {
841     neighbor->consensus_insertion_offset++;
842   }
843
844   if ( (0 != memcmp(&target->peer, &my_identity, sizeof (my_identity))) &&
845        (0 != memcmp(&target->peer, &neighbor->peer, sizeof (neighbor->peer))) )
846   {
847     /* Add target if it is not the neighbor or this peer */
848     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
849                 "Adding peer `%s' with distance %u to SET\n",
850                 GNUNET_i2s (&target->peer),
851                 ntohl (target->distance));
852     GNUNET_SET_add_element (neighbor->my_set,
853                             &element,
854                             &build_set, neighbor);
855     neighbor->consensus_elements++;
856   }
857   else
858     build_set(neighbor);
859 }
860
861
862 /**
863  * A peer is now connected to us at distance 1.  Initiate DV exchange.
864  *
865  * @param neighbor entry for the neighbor at distance 1
866  */
867 static void
868 handle_direct_connect (struct DirectNeighbor *neighbor)
869 {
870   struct Route *route;
871   struct GNUNET_HashCode h1;
872   struct GNUNET_HashCode h2;
873   struct GNUNET_HashCode session_id;
874
875   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
876               "Direct connection to %s established, routing table exchange begins.\n",
877               GNUNET_i2s (&neighbor->peer));
878   GNUNET_STATISTICS_update (stats,
879                             "# peers connected (1-hop)",
880                             1, GNUNET_NO);
881   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
882                                              &neighbor->peer);
883   if (NULL != route)
884   {
885     GNUNET_assert (GNUNET_YES ==
886                    GNUNET_CONTAINER_multipeermap_remove (all_routes,
887                                                          &neighbor->peer,
888                                                          route));
889     send_disconnect_to_plugin (&neighbor->peer);
890     release_route (route);
891     GNUNET_free (route);
892   }
893
894   neighbor->direct_route = GNUNET_new (struct Route);
895   neighbor->direct_route->next_hop = neighbor;
896   neighbor->direct_route->target.peer= neighbor->peer;
897   neighbor->direct_route->target.distance = DIRECT_NEIGHBOR_COST;
898   allocate_route (neighbor->direct_route, DIRECT_NEIGHBOR_COST);
899
900   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
901               "Adding direct route to %s\n",
902               GNUNET_i2s (&neighbor->direct_route->target.peer));
903
904
905   /* construct session ID seed as XOR of both peer's identities */
906   GNUNET_CRYPTO_hash (&my_identity, sizeof (my_identity), &h1);
907   GNUNET_CRYPTO_hash (&neighbor->peer, sizeof (struct GNUNET_PeerIdentity), &h2);
908   GNUNET_CRYPTO_hash_xor (&h1,
909                           &h2,
910                           &session_id);
911   /* make sure session ID is unique across applications by salting it with 'DV' */
912   GNUNET_CRYPTO_hkdf (&neighbor->real_session_id, sizeof (struct GNUNET_HashCode),
913                       GCRY_MD_SHA512, GCRY_MD_SHA256,
914                       "DV-SALT", 2,
915                       &session_id, sizeof (session_id),
916                       NULL, 0);
917   if (0 < memcmp (&neighbor->peer,
918                   &my_identity,
919                   sizeof (struct GNUNET_PeerIdentity)))
920   {
921     if (NULL != neighbor->listen_handle)
922     {
923       GNUNET_break (0);
924     }
925     else
926       neighbor->initiate_task = GNUNET_SCHEDULER_add_now (&initiate_set_union,
927                                                         neighbor);
928   }
929   else
930   {
931     if (NULL != neighbor->listen_handle)
932     {
933       GNUNET_break (0);
934     }
935     else
936     {
937       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938                   "Starting SET listen operation with peer `%s'\n",
939                   GNUNET_i2s(&neighbor->peer));
940       neighbor->listen_handle = GNUNET_SET_listen (cfg,
941                                                    GNUNET_SET_OPERATION_UNION,
942                                                    &neighbor->real_session_id,
943                                                    &listen_set_union,
944                                                    neighbor);
945     }
946   }
947 }
948
949
950 /**
951  * Method called whenever a peer connects.
952  *
953  * @param cls closure
954  * @param peer peer identity this notification is about
955  */
956 static void
957 handle_core_connect (void *cls,
958                      const struct GNUNET_PeerIdentity *peer)
959 {
960   struct DirectNeighbor *neighbor;
961
962   /* Check for connect to self message */
963   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
964     return;
965   /* check if entry exists */
966   neighbor = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
967                                                 peer);
968   if (NULL != neighbor)
969   {
970     GNUNET_break (GNUNET_YES != neighbor->connected);
971     neighbor->connected = GNUNET_YES;
972     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
973                 "Core connected to %s (distance %u)\n",
974                 GNUNET_i2s (peer),
975                 (unsigned int) neighbor->distance);
976     if (DIRECT_NEIGHBOR_COST != neighbor->distance)
977       return;
978     handle_direct_connect (neighbor);
979     return;
980   }
981   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
982               "Core connected to %s (distance unknown)\n",
983               GNUNET_i2s (peer));
984   neighbor = GNUNET_new (struct DirectNeighbor);
985   neighbor->peer = *peer;
986   GNUNET_assert (GNUNET_YES ==
987                  GNUNET_CONTAINER_multipeermap_put (direct_neighbors,
988                                                     peer,
989                                                     neighbor,
990                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
991   neighbor->connected = GNUNET_YES;
992   neighbor->distance = 0; /* unknown */
993   neighbor->network = GNUNET_ATS_NET_UNSPECIFIED;
994 }
995
996
997 /**
998  * Called for each 'target' in a neighbor table to free the associated memory.
999  *
1000  * @param cls NULL
1001  * @param key key of the value
1002  * @param value value to free
1003  * @return #GNUNET_OK to continue to iterate
1004  */
1005 static int
1006 free_targets (void *cls,
1007               const struct GNUNET_PeerIdentity *key,
1008               void *value)
1009 {
1010   GNUNET_free (value);
1011   return GNUNET_OK;
1012 }
1013
1014
1015 /**
1016  * Multipeerhmap iterator for checking if a given route is
1017  * (now) useful to this peer.
1018  *
1019  * @param cls the direct neighbor for the given route
1020  * @param key key value stored under
1021  * @param value a 'struct Target' that may or may not be useful; not that
1022  *        the distance in 'target' does not include the first hop yet
1023  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
1024  */
1025 static int
1026 check_possible_route (void *cls,
1027                       const struct GNUNET_PeerIdentity *key,
1028                       void *value)
1029 {
1030   struct DirectNeighbor *neighbor = cls;
1031   struct Target *target = value;
1032   struct Route *route;
1033
1034   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1035                                              key);
1036   if (NULL != route)
1037   {
1038     if (ntohl (route->target.distance) > ntohl (target->distance) + 1)
1039     {
1040       /* this '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, ntohl (target->distance) + 1);
1044     }
1045     return GNUNET_YES; /* got a route to this target already */
1046   }
1047   if (ntohl (target->distance) >= DEFAULT_FISHEYE_DEPTH)
1048     return GNUNET_YES; /* distance is too large to be interesting */
1049   route = GNUNET_new (struct Route);
1050   route->next_hop = neighbor;
1051   route->target.distance = htonl (ntohl (target->distance) + 1);
1052   route->target.peer = target->peer;
1053   allocate_route (route, ntohl (route->target.distance));
1054   GNUNET_assert (GNUNET_YES ==
1055                  GNUNET_CONTAINER_multipeermap_put (all_routes,
1056                                                     &route->target.peer,
1057                                                     route,
1058                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1059   send_connect_to_plugin (&route->target.peer, ntohl (target->distance),
1060                           neighbor->network);
1061   return GNUNET_YES;
1062 }
1063
1064
1065 /**
1066  * Multipeermap iterator for finding routes that were previously
1067  * "hidden" due to a better route (called after a disconnect event).
1068  *
1069  * @param cls NULL
1070  * @param key peer identity of the given direct neighbor
1071  * @param value a `struct DirectNeighbor` to check for additional routes
1072  * @return #GNUNET_YES to continue iteration
1073  */
1074 static int
1075 refresh_routes (void *cls,
1076                 const struct GNUNET_PeerIdentity *key,
1077                 void *value)
1078 {
1079   struct DirectNeighbor *neighbor = value;
1080
1081   if ( (GNUNET_YES != neighbor->connected) ||
1082        (DIRECT_NEIGHBOR_COST != neighbor->distance) )
1083     return GNUNET_YES;
1084   if (NULL != neighbor->neighbor_table)
1085     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1086                                            &check_possible_route,
1087                                            neighbor);
1088   return GNUNET_YES;
1089 }
1090
1091
1092 /**
1093  * Task to run #refresh_routes() on all direct neighbours.
1094  *
1095  * @param cls NULL
1096  * @param tc unused
1097  */
1098 static void
1099 refresh_routes_task (void *cls,
1100                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1101 {
1102   rr_task = GNUNET_SCHEDULER_NO_TASK;
1103   GNUNET_CONTAINER_multipeermap_iterate (direct_neighbors,
1104                                          &refresh_routes,
1105                                          NULL);
1106 }
1107
1108
1109 /**
1110  * Asynchronously run #refresh_routes() at the next opportunity
1111  * on all direct neighbours.
1112  */
1113 static void
1114 schedule_refresh_routes ()
1115 {
1116   if (GNUNET_SCHEDULER_NO_TASK == rr_task)
1117     rr_task = GNUNET_SCHEDULER_add_now (&refresh_routes_task,
1118                                         NULL);
1119 }
1120
1121
1122 /**
1123  * Get distance information from 'atsi'.
1124  *
1125  * @param atsi performance data
1126  * @param atsi_count number of entries in atsi
1127  * @return connected transport distance
1128  */
1129 static uint32_t
1130 get_atsi_distance (const struct GNUNET_ATS_Information *atsi,
1131                    uint32_t atsi_count)
1132 {
1133   uint32_t i;
1134
1135   for (i = 0; i < atsi_count; i++)
1136     if (ntohl (atsi[i].type) == GNUNET_ATS_QUALITY_NET_DISTANCE)
1137       return (0 == ntohl (atsi[i].value)) ? DIRECT_NEIGHBOR_COST : ntohl (atsi[i].value); // FIXME: 0 check should not be required once ATS is fixed!
1138   /* If we do not have explicit distance data, assume direct neighbor. */
1139   return DIRECT_NEIGHBOR_COST;
1140 }
1141
1142
1143 /**
1144  * Get network information from 'atsi'.
1145  *
1146  * @param atsi performance data
1147  * @param atsi_count number of entries in atsi
1148  * @return connected transport network
1149  */
1150 static uint32_t
1151 get_atsi_network (const struct GNUNET_ATS_Information *atsi,
1152                    uint32_t atsi_count)
1153 {
1154   uint32_t i;
1155
1156   for (i = 0; i < atsi_count; i++)
1157     if (ntohl (atsi[i].type) == GNUNET_ATS_NETWORK_TYPE)
1158       return ntohl (atsi[i].value);
1159   return GNUNET_ATS_NET_UNSPECIFIED;
1160 }
1161
1162 /**
1163  * Multipeermap iterator for freeing routes that go via a particular
1164  * neighbor that disconnected and is thus no longer available.
1165  *
1166  * @param cls the direct neighbor that is now unavailable
1167  * @param key key value stored under
1168  * @param value a `struct Route` that may or may not go via neighbor
1169  *
1170  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
1171  */
1172 static int
1173 cull_routes (void *cls,
1174              const struct GNUNET_PeerIdentity *key,
1175              void *value)
1176 {
1177   struct DirectNeighbor *neighbor = cls;
1178   struct Route *route = value;
1179
1180   if (route->next_hop != neighbor)
1181     return GNUNET_YES; /* not affected */
1182   GNUNET_assert (GNUNET_YES ==
1183                  GNUNET_CONTAINER_multipeermap_remove (all_routes, key, value));
1184   release_route (route);
1185   send_disconnect_to_plugin (&route->target.peer);
1186   GNUNET_free (route);
1187   return GNUNET_YES;
1188 }
1189
1190
1191 /**
1192  * Handle the case that a direct connection to a peer is
1193  * disrupted.  Remove all routes via that peer and
1194  * stop the consensus with it.
1195  *
1196  * @param neighbor peer that was disconnected (or at least is no
1197  *    longer at distance 1)
1198  */
1199 static void
1200 handle_direct_disconnect (struct DirectNeighbor *neighbor)
1201 {
1202   GNUNET_CONTAINER_multipeermap_iterate (all_routes,
1203                                          &cull_routes,
1204                                          neighbor);
1205   if (NULL != neighbor->cth)
1206   {
1207     GNUNET_CORE_notify_transmit_ready_cancel (neighbor->cth);
1208     neighbor->cth = NULL;
1209   }
1210
1211   if (NULL != neighbor->direct_route)
1212   {
1213     release_route (neighbor->direct_route);
1214     GNUNET_free (neighbor->direct_route);
1215     neighbor->direct_route = NULL;
1216   }
1217
1218   if (NULL != neighbor->neighbor_table_consensus)
1219   {
1220     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table_consensus,
1221                                            &free_targets,
1222                                            NULL);
1223     GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table_consensus);
1224     neighbor->neighbor_table_consensus = NULL;
1225   }
1226   if (NULL != neighbor->neighbor_table)
1227   {
1228     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1229                                            &free_targets,
1230                                            NULL);
1231     GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table);
1232     neighbor->neighbor_table = NULL;
1233   }
1234   if (NULL != neighbor->set_op)
1235   {
1236     GNUNET_SET_operation_cancel (neighbor->set_op);
1237     neighbor->set_op = NULL;
1238   }
1239   if (NULL != neighbor->my_set)
1240   {
1241     GNUNET_SET_destroy (neighbor->my_set);
1242     neighbor->my_set = NULL;
1243   }
1244   if (NULL != neighbor->listen_handle)
1245   {
1246     GNUNET_SET_listen_cancel (neighbor->listen_handle);
1247     neighbor->listen_handle = NULL;
1248   }
1249   if (GNUNET_SCHEDULER_NO_TASK != neighbor->initiate_task)
1250   {
1251     GNUNET_SCHEDULER_cancel (neighbor->initiate_task);
1252     neighbor->initiate_task = GNUNET_SCHEDULER_NO_TASK;
1253   }
1254 }
1255
1256
1257 /**
1258  * Function that is called with QoS information about an address; used
1259  * to update our current distance to another peer.
1260  *
1261  * @param cls closure
1262  * @param address the address
1263  * @param active is this address in active use
1264  * @param bandwidth_out assigned outbound bandwidth for the connection
1265  * @param bandwidth_in assigned inbound bandwidth for the connection
1266  * @param ats performance data for the address (as far as known)
1267  * @param ats_count number of performance records in @a ats
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_Information *ats,
1276                    uint32_t ats_count)
1277 {
1278   struct DirectNeighbor *neighbor;
1279   uint32_t distance;
1280   uint32_t network = GNUNET_ATS_NET_UNSPECIFIED;
1281
1282   if (GNUNET_NO == active)
1283         return;
1284   distance = get_atsi_distance (ats, ats_count);
1285   network = get_atsi_network (ats, ats_count);
1286
1287   /*
1288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1289               "ATS says distance to %s is %u\n",
1290               GNUNET_i2s (&address->peer),
1291               (unsigned int) distance);*/
1292   /* check if entry exists */
1293   neighbor = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
1294                                                 &address->peer);
1295   if (NULL != neighbor)
1296   {
1297     if (GNUNET_ATS_NET_UNSPECIFIED != network)
1298       neighbor->network = network;
1299
1300     if ( (DIRECT_NEIGHBOR_COST == neighbor->distance) &&
1301          (DIRECT_NEIGHBOR_COST == distance) )
1302       return; /* no change */
1303     if (DIRECT_NEIGHBOR_COST == neighbor->distance)
1304     {
1305       neighbor->distance = distance;
1306       GNUNET_STATISTICS_update (stats,
1307                                 "# peers connected (1-hop)",
1308                                 -1, GNUNET_NO);
1309       handle_direct_disconnect (neighbor);
1310       schedule_refresh_routes ();
1311       return;
1312     }
1313     neighbor->distance = distance;
1314     if (DIRECT_NEIGHBOR_COST != neighbor->distance)
1315       return;
1316     if (GNUNET_YES != neighbor->connected)
1317       return;
1318     handle_direct_connect (neighbor);
1319     return;
1320   }
1321   neighbor = GNUNET_new (struct DirectNeighbor);
1322   neighbor->peer = address->peer;
1323   GNUNET_assert (GNUNET_YES ==
1324                  GNUNET_CONTAINER_multipeermap_put (direct_neighbors,
1325                                                     &address->peer,
1326                                                     neighbor,
1327                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1328   neighbor->connected = GNUNET_NO; /* not yet */
1329   neighbor->distance = distance;
1330   neighbor->network = network;
1331 }
1332
1333
1334 /**
1335  * Check if a target was removed from the set of the other peer; if so,
1336  * if we also used it for our route, we need to remove it from our
1337  * 'all_routes' set (and later check if an alternative path now exists).
1338  *
1339  * @param cls the `struct DirectNeighbor`
1340  * @param key peer identity for the target
1341  * @param value a `struct Target` previously reachable via the given neighbor
1342  */
1343 static int
1344 check_target_removed (void *cls,
1345                       const struct GNUNET_PeerIdentity *key,
1346                       void *value)
1347 {
1348   struct DirectNeighbor *neighbor = cls;
1349   struct Target *new_target;
1350   struct Route *current_route;
1351
1352   new_target = GNUNET_CONTAINER_multipeermap_get (neighbor->neighbor_table_consensus,
1353                                                   key);
1354   if (NULL == new_target)
1355   {
1356     /* target was revoked, check if it was used */
1357     current_route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1358                                                        key);
1359     if ( (NULL == current_route) ||
1360          (current_route->next_hop != neighbor) )
1361     {
1362       /* didn't matter, wasn't used */
1363       return GNUNET_OK;
1364     }
1365     /* remove existing route */
1366     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1367                 "Lost route to %s\n",
1368                 GNUNET_i2s (&current_route->target.peer));
1369     GNUNET_assert (GNUNET_YES ==
1370                    GNUNET_CONTAINER_multipeermap_remove (all_routes, key, current_route));
1371     send_disconnect_to_plugin (&current_route->target.peer);
1372     GNUNET_free (current_route);
1373     neighbor->target_removed = GNUNET_YES;
1374     return GNUNET_OK;
1375   }
1376   return GNUNET_OK;
1377 }
1378
1379
1380 /**
1381  * Check if a target was added to the set of the other peer; if it
1382  * was added or impoves the existing route, do the needed updates.
1383  *
1384  * @param cls the `struct DirectNeighbor`
1385  * @param key peer identity for the target
1386  * @param value a `struct Target` now reachable via the given neighbor
1387  */
1388 static int
1389 check_target_added (void *cls,
1390                     const struct GNUNET_PeerIdentity *key,
1391                     void *value)
1392 {
1393   struct DirectNeighbor *neighbor = cls;
1394   struct Target *target = value;
1395   struct Route *current_route;
1396
1397   /* target was revoked, check if it was used */
1398   current_route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1399                                                      key);
1400   if (NULL != current_route)
1401   {
1402     /* route exists */
1403     if (current_route->next_hop == neighbor)
1404     {
1405       /* we had the same route before, no change */
1406       if (ntohl (target->distance) + 1 != ntohl (current_route->target.distance))
1407       {
1408         current_route->target.distance = htonl (ntohl (target->distance) + 1);
1409         send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
1410       }
1411       return GNUNET_OK;
1412     }
1413     if (ntohl (current_route->target.distance) >= ntohl (target->distance) + 1)
1414     {
1415       /* alternative, shorter route exists, ignore */
1416       return GNUNET_OK;
1417     }
1418     /* new route is better than the existing one, take over! */
1419     /* NOTE: minor security issue: malicious peers may advertise
1420        very short routes to take over longer paths; as we don't
1421        check that the shorter routes actually work, a malicious
1422        direct neighbor can use this to DoS our long routes */
1423     current_route->next_hop = neighbor;
1424     current_route->target.distance = htonl (ntohl (target->distance) + 1);
1425     send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
1426     return GNUNET_OK;
1427   }
1428   /* new route */
1429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1430               "Discovered new route to %s using %u hops\n",
1431               GNUNET_i2s (&target->peer),
1432               (unsigned int) (ntohl (target->distance) + 1));
1433   current_route = GNUNET_new (struct Route);
1434   current_route->next_hop = neighbor;
1435   current_route->target.peer = target->peer;
1436   current_route->target.distance = htonl (ntohl (target->distance) + 1);
1437   allocate_route (current_route, ntohl (current_route->target.distance));
1438   GNUNET_assert (GNUNET_YES ==
1439                  GNUNET_CONTAINER_multipeermap_put (all_routes,
1440                                                     &current_route->target.peer,
1441                                                     current_route,
1442                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1443
1444   send_connect_to_plugin (&current_route->target.peer,
1445                           ntohl (current_route->target.distance),
1446                           neighbor->network);
1447   return GNUNET_OK;
1448 }
1449
1450
1451 /**
1452  * Callback for set operation results. Called for each element
1453  * in the result set.
1454  * We have learned a new route from the other peer.  Add it to the
1455  * route set we're building.
1456  *
1457  * @param cls the `struct DirectNeighbor` we're building the consensus with
1458  * @param element a result element, only valid if status is #GNUNET_SET_STATUS_OK
1459  * @param status see enum GNUNET_SET_Status
1460  */
1461 static void
1462 handle_set_union_result (void *cls,
1463                          const struct GNUNET_SET_Element *element,
1464                          enum GNUNET_SET_Status status)
1465 {
1466   struct DirectNeighbor *neighbor = cls;
1467   struct Target *target;
1468   char *status_str;
1469
1470   switch (status) {
1471     case GNUNET_SET_STATUS_OK:
1472       status_str = "GNUNET_SET_STATUS_OK";
1473       break;
1474     case GNUNET_SET_STATUS_TIMEOUT:
1475       status_str = "GNUNET_SET_STATUS_TIMEOUT";
1476       break;
1477     case GNUNET_SET_STATUS_FAILURE:
1478       status_str = "GNUNET_SET_STATUS_FAILURE";
1479       break;
1480     case GNUNET_SET_STATUS_HALF_DONE:
1481       status_str = "GNUNET_SET_STATUS_HALF_DONE";
1482       break;
1483     case GNUNET_SET_STATUS_DONE:
1484       status_str = "GNUNET_SET_STATUS_DONE";
1485       break;
1486     default:
1487       status_str = "UNDEFINED";
1488       break;
1489   }
1490
1491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1492               "Got SET union result: %s\n",
1493               status_str);
1494   switch (status)
1495   {
1496   case GNUNET_SET_STATUS_OK:
1497     if (sizeof (struct Target) != element->size)
1498     {
1499       GNUNET_break_op (0);
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\n",
1506                 GNUNET_i2s (&target->peer), ntohl(target->distance) + 1);
1507     if (NULL == neighbor->neighbor_table_consensus)
1508       neighbor->neighbor_table_consensus = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1509     if (GNUNET_YES !=
1510         GNUNET_CONTAINER_multipeermap_put (neighbor->neighbor_table_consensus,
1511                                            &target->peer,
1512                                            target,
1513                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1514     {
1515       GNUNET_break_op (0);
1516       GNUNET_free (target);
1517     }
1518     break;
1519   case GNUNET_SET_STATUS_TIMEOUT:
1520   case GNUNET_SET_STATUS_FAILURE:
1521     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1522                 "Failed to establish DV union, will try again later\n");
1523     neighbor->set_op = NULL;
1524     if (NULL != neighbor->neighbor_table_consensus)
1525     {
1526       GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table_consensus,
1527                                              &free_targets,
1528                                              NULL);
1529       GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table_consensus);
1530       neighbor->neighbor_table_consensus = NULL;
1531     }
1532     if (0 < memcmp (&neighbor->peer,
1533                     &my_identity,
1534                     sizeof (struct GNUNET_PeerIdentity)))
1535       neighbor->initiate_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1536                                                               &initiate_set_union,
1537                                                               neighbor);
1538     break;
1539   case GNUNET_SET_STATUS_HALF_DONE:
1540     break;
1541   case GNUNET_SET_STATUS_DONE:
1542     /* we got all of our updates; integrate routing table! */
1543     neighbor->target_removed = GNUNET_NO;
1544     if (NULL == neighbor->neighbor_table_consensus)
1545       neighbor->neighbor_table_consensus = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1546     if (NULL != neighbor->neighbor_table)
1547       GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1548                                            &check_target_removed,
1549                                            neighbor);
1550     if (GNUNET_YES == neighbor->target_removed)
1551     {
1552       /* check if we got an alternative for the removed routes */
1553       schedule_refresh_routes ();
1554     }
1555     /* add targets that appeared (and check for improved routes) */
1556     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table_consensus,
1557                                            &check_target_added,
1558                                            neighbor);
1559     if (NULL != neighbor->neighbor_table)
1560     {
1561       GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1562                                              &free_targets,
1563                                              NULL);
1564       GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table);
1565       neighbor->neighbor_table = NULL;
1566     }
1567     neighbor->neighbor_table = neighbor->neighbor_table_consensus;
1568     neighbor->neighbor_table_consensus = NULL;
1569
1570     /* operation done, schedule next run! */
1571     neighbor->set_op = NULL;
1572     if (0 < memcmp (&neighbor->peer,
1573                     &my_identity,
1574                     sizeof (struct GNUNET_PeerIdentity)))
1575       neighbor->initiate_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1576                                                               &initiate_set_union,
1577                                                               neighbor);
1578     break;
1579   default:
1580     GNUNET_break (0);
1581     return;
1582   }
1583 }
1584
1585
1586 /**
1587  * Start creating a new DV set union construction, our neighbour has
1588  * asked for it (callback for listening peer).
1589  *
1590  * @param cls the 'struct DirectNeighbor' of the peer we're building
1591  *        a routing consensus with
1592  * @param other_peer the other peer
1593  * @param context_msg message with application specific information from
1594  *        the other peer
1595  * @param request request from the other peer, use GNUNET_SET_accept
1596  *        to accept it, otherwise the request will be refused
1597  *        Note that we don't use a return value here, as it is also
1598  *        necessary to specify the set we want to do the operation with,
1599  *        whith sometimes can be derived from the context message.
1600  *        Also necessary to specify the timeout.
1601  */
1602 static void
1603 listen_set_union (void *cls,
1604                   const struct GNUNET_PeerIdentity *other_peer,
1605                   const struct GNUNET_MessageHeader *context_msg,
1606                   struct GNUNET_SET_Request *request)
1607 {
1608   struct DirectNeighbor *neighbor = cls;
1609
1610   if (NULL == request)
1611     return; /* why??? */
1612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1613               "Starting to create consensus with %s\n",
1614               GNUNET_i2s (&neighbor->peer));
1615   if (NULL != neighbor->set_op)
1616   {
1617     GNUNET_SET_operation_cancel (neighbor->set_op);
1618     neighbor->set_op = NULL;
1619   }
1620   if (NULL != neighbor->my_set)
1621   {
1622     GNUNET_SET_destroy (neighbor->my_set);
1623     neighbor->my_set = NULL;
1624   }
1625   neighbor->my_set = GNUNET_SET_create (cfg,
1626                                         GNUNET_SET_OPERATION_UNION);
1627   neighbor->set_op = GNUNET_SET_accept (request,
1628                                         GNUNET_SET_RESULT_ADDED,
1629                                         &handle_set_union_result,
1630                                         neighbor);
1631   neighbor->consensus_insertion_offset = 0;
1632   neighbor->consensus_insertion_distance = 0;
1633   neighbor->consensus_elements = 0;
1634   build_set (neighbor);
1635 }
1636
1637
1638 /**
1639  * Start creating a new DV set union by initiating the connection.
1640  *
1641  * @param cls the 'struct DirectNeighbor' of the peer we're building
1642  *        a routing consensus with
1643  * @param tc scheduler context
1644  */
1645 static void
1646 initiate_set_union (void *cls,
1647                     const struct GNUNET_SCHEDULER_TaskContext *tc)
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 = GNUNET_SCHEDULER_NO_TASK;
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                                          0 /* FIXME: salt */,
1661                                          GNUNET_SET_RESULT_ADDED,
1662                                          &handle_set_union_result,
1663                                          neighbor);
1664   neighbor->consensus_insertion_offset = 0;
1665   neighbor->consensus_insertion_distance = 0;
1666   neighbor->consensus_elements = 0;
1667   build_set (neighbor);
1668 }
1669
1670
1671 /**
1672  * Core handler for DV data messages.  Whatever this message
1673  * contains all we really have to do is rip it out of its
1674  * DV layering and give it to our pal the DV plugin to report
1675  * in with.
1676  *
1677  * @param cls closure
1678  * @param peer peer which sent the message (immediate sender)
1679  * @param message the message
1680  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the other peer violated the protocol
1681  */
1682 static int
1683 handle_dv_route_message (void *cls, 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
1690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1691               "Handling DV message\n");
1692   if (ntohs (message->size) < sizeof (struct RouteMessage) + sizeof (struct GNUNET_MessageHeader))
1693   {
1694     GNUNET_break_op (0);
1695     return GNUNET_SYSERR;
1696   }
1697   rm = (const struct RouteMessage *) message;
1698   payload = (const struct GNUNET_MessageHeader *) &rm[1];
1699   if (ntohs (message->size) != sizeof (struct RouteMessage) + ntohs (payload->size))
1700   {
1701     GNUNET_break_op (0);
1702     return GNUNET_SYSERR;
1703   }
1704   if (0 == memcmp (&rm->target,
1705                    &my_identity,
1706                    sizeof (struct GNUNET_PeerIdentity)))
1707   {
1708     /* message is for me, check reverse route! */
1709     route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1710                                                &rm->sender);
1711     if (NULL == route)
1712     {
1713       /* don't have reverse route, drop */
1714       GNUNET_STATISTICS_update (stats,
1715                                 "# message discarded (no reverse route)",
1716                                 1, GNUNET_NO);
1717       return GNUNET_OK;
1718     }
1719     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1720                 "Delivering %u bytes to myself!\n",
1721                 ntohs (payload->size));
1722     send_data_to_plugin (payload,
1723                          &rm->sender,
1724                          ntohl (route->target.distance));
1725     return GNUNET_OK;
1726   }
1727   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1728                                              &rm->target);
1729   if (NULL == route)
1730   {
1731     GNUNET_STATISTICS_update (stats,
1732                               "# messages discarded (no route)",
1733                               1, GNUNET_NO);
1734     return GNUNET_OK;
1735   }
1736   if (ntohl (route->target.distance) > ntohl (rm->distance) + 1)
1737   {
1738     GNUNET_STATISTICS_update (stats,
1739                               "# messages discarded (target too far)",
1740                               1, GNUNET_NO);
1741     return GNUNET_OK;
1742   }
1743   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1744               "Forwarding message to %s\n",
1745               GNUNET_i2s (&rm->target));
1746   forward_payload (route->next_hop,
1747                    ntohl (route->target.distance),
1748                    0,
1749                    &rm->target,
1750                    &rm->sender,
1751                    payload);
1752   return GNUNET_OK;
1753 }
1754
1755
1756 /**
1757  * Service server's handler for message send requests (which come
1758  * bubbling up to us through the DV plugin).
1759  *
1760  * @param cls closure
1761  * @param client identification of the client
1762  * @param message the actual message
1763  */
1764 static void
1765 handle_dv_send_message (void *cls, struct GNUNET_SERVER_Client *client,
1766                         const struct GNUNET_MessageHeader *message)
1767 {
1768   struct Route *route;
1769   const struct GNUNET_DV_SendMessage *msg;
1770   const struct GNUNET_MessageHeader *payload;
1771
1772   if (ntohs (message->size) < sizeof (struct GNUNET_DV_SendMessage) + sizeof (struct GNUNET_MessageHeader))
1773   {
1774     GNUNET_break (0);
1775     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1776     return;
1777   }
1778   msg = (const struct GNUNET_DV_SendMessage *) message;
1779   GNUNET_break (0 != ntohl (msg->uid));
1780   payload = (const struct GNUNET_MessageHeader *) &msg[1];
1781   if (ntohs (message->size) != sizeof (struct GNUNET_DV_SendMessage) + ntohs (payload->size))
1782   {
1783     GNUNET_break (0);
1784     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1785     return;
1786   }
1787   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1788                                              &msg->target);
1789   if (NULL == route)
1790   {
1791     /* got disconnected */
1792     GNUNET_STATISTICS_update (stats,
1793                               "# local messages discarded (no route)",
1794                               1, GNUNET_NO);
1795     send_ack_to_plugin (&msg->target, ntohl (msg->uid), GNUNET_YES);
1796     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1797     return;
1798   }
1799   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1800               "Forwarding %u bytes to %s\n",
1801               ntohs (payload->size),
1802               GNUNET_i2s (&msg->target));
1803
1804   forward_payload (route->next_hop,
1805                    ntohl (route->target.distance),
1806                    htonl (msg->uid),
1807                    &msg->target,
1808                    &my_identity,
1809                    payload);
1810   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1811 }
1812
1813
1814 /**
1815  * Cleanup all of the data structures associated with a given neighbor.
1816  *
1817  * @param neighbor neighbor to clean up
1818  */
1819 static void
1820 cleanup_neighbor (struct DirectNeighbor *neighbor)
1821 {
1822   struct PendingMessage *pending;
1823
1824   while (NULL != (pending = neighbor->pm_head))
1825   {
1826     neighbor->pm_queue_size--;
1827     GNUNET_CONTAINER_DLL_remove (neighbor->pm_head,
1828                                  neighbor->pm_tail,
1829                                  pending);
1830     GNUNET_free (pending);
1831   }
1832   handle_direct_disconnect (neighbor);
1833   GNUNET_assert (GNUNET_YES ==
1834                  GNUNET_CONTAINER_multipeermap_remove (direct_neighbors,
1835                                                        &neighbor->peer,
1836                                                        neighbor));
1837   GNUNET_free (neighbor);
1838 }
1839
1840
1841 /**
1842  * Method called whenever a given peer disconnects.
1843  *
1844  * @param cls closure
1845  * @param peer peer identity this notification is about
1846  */
1847 static void
1848 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1849 {
1850   struct DirectNeighbor *neighbor;
1851
1852   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1853               "Received core peer disconnect message for peer `%s'!\n",
1854               GNUNET_i2s (peer));
1855   /* Check for disconnect from self message */
1856   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1857     return;
1858   neighbor =
1859       GNUNET_CONTAINER_multipeermap_get (direct_neighbors, peer);
1860   if (NULL == neighbor)
1861   {
1862     GNUNET_break (0);
1863     return;
1864   }
1865   GNUNET_break (GNUNET_YES == neighbor->connected);
1866   neighbor->connected = GNUNET_NO;
1867   if (DIRECT_NEIGHBOR_COST == neighbor->distance)
1868   {
1869
1870     GNUNET_STATISTICS_update (stats,
1871                               "# peers connected (1-hop)",
1872                               -1, GNUNET_NO);
1873   }
1874   cleanup_neighbor (neighbor);
1875
1876   if (GNUNET_YES == in_shutdown)
1877     return;
1878   schedule_refresh_routes ();
1879 }
1880
1881
1882 /**
1883  * Multipeermap iterator for freeing routes.  Should never be called.
1884  *
1885  * @param cls NULL
1886  * @param key key value stored under
1887  * @param value the route to be freed
1888  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
1889  */
1890 static int
1891 free_route (void *cls,
1892             const struct GNUNET_PeerIdentity *key,
1893             void *value)
1894 {
1895   struct Route *route = value;
1896
1897   GNUNET_break (0);
1898   GNUNET_assert (GNUNET_YES ==
1899                  GNUNET_CONTAINER_multipeermap_remove (all_routes, key, value));
1900   release_route (route);
1901   send_disconnect_to_plugin (&route->target.peer);
1902   GNUNET_free (route);
1903   return GNUNET_YES;
1904 }
1905
1906
1907 /**
1908  * Multipeermap iterator for freeing direct neighbors. Should never be called.
1909  *
1910  * @param cls NULL
1911  * @param key key value stored under
1912  * @param value the direct neighbor to be freed
1913  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
1914  */
1915 static int
1916 free_direct_neighbors (void *cls,
1917                        const struct GNUNET_PeerIdentity *key,
1918                        void *value)
1919 {
1920   struct DirectNeighbor *neighbor = value;
1921   cleanup_neighbor (neighbor);
1922   return GNUNET_YES;
1923 }
1924
1925
1926 /**
1927  * Task run during shutdown.
1928  *
1929  * @param cls unused
1930  * @param tc unused
1931  */
1932 static void
1933 shutdown_task (void *cls,
1934                const struct GNUNET_SCHEDULER_TaskContext *tc)
1935 {
1936   unsigned int i;
1937
1938   in_shutdown = GNUNET_YES;
1939   GNUNET_assert (NULL != core_api);
1940   GNUNET_CORE_disconnect (core_api);
1941   core_api = NULL;
1942   GNUNET_ATS_performance_done (ats);
1943   ats = NULL;
1944   GNUNET_CONTAINER_multipeermap_iterate (direct_neighbors,
1945                                          &free_direct_neighbors, NULL);
1946   GNUNET_CONTAINER_multipeermap_iterate (all_routes,
1947                                          &free_route, NULL);
1948   GNUNET_CONTAINER_multipeermap_destroy (direct_neighbors);
1949   GNUNET_CONTAINER_multipeermap_destroy (all_routes);
1950   GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1951   stats = NULL;
1952   GNUNET_SERVER_notification_context_destroy (nc);
1953   nc = NULL;
1954   for (i=0;i<DEFAULT_FISHEYE_DEPTH;i++)
1955   {
1956     GNUNET_array_grow (consensi[i].targets,
1957                        consensi[i].array_length,
1958                        0);
1959   }
1960   if (GNUNET_SCHEDULER_NO_TASK != rr_task)
1961   {
1962     GNUNET_SCHEDULER_cancel (rr_task);
1963     rr_task = GNUNET_SCHEDULER_NO_TASK;
1964   }
1965 }
1966
1967
1968 /**
1969  * Notify newly connected client about an existing route.
1970  *
1971  * @param cls the `struct GNUNET_SERVER_Client *`
1972  * @param key peer identity
1973  * @param value the `struct Route *`
1974  * @return #GNUNET_OK (continue to iterate)
1975  */
1976 static int
1977 add_route (void *cls,
1978            const struct GNUNET_PeerIdentity *key,
1979            void *value)
1980 {
1981   struct GNUNET_SERVER_Client *client = cls;
1982   struct Route *route = value;
1983   struct GNUNET_DV_ConnectMessage cm;
1984
1985   memset (&cm, 0, sizeof (cm));
1986   cm.header.size = htons (sizeof (cm));
1987   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
1988   cm.distance = htonl (route->target.distance);
1989   cm.peer = route->target.peer;
1990
1991   GNUNET_SERVER_notification_context_unicast (nc,
1992                                               client,
1993                                               &cm.header,
1994                                               GNUNET_NO);
1995   return GNUNET_OK;
1996 }
1997
1998
1999 /**
2000  * Handle START-message.  This is the first message sent to us
2001  * by the client (can only be one!).
2002  *
2003  * @param cls closure (always NULL)
2004  * @param client identification of the client
2005  * @param message the actual message
2006  */
2007 static void
2008 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
2009               const struct GNUNET_MessageHeader *message)
2010 {
2011   GNUNET_SERVER_notification_context_add (nc, client);
2012   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2013   GNUNET_CONTAINER_multipeermap_iterate (all_routes,
2014                                          &add_route,
2015                                          client);
2016 }
2017
2018
2019 /**
2020  * Called on core init.
2021  *
2022  * @param cls unused
2023  * @param identity this peer's identity
2024  */
2025 static void
2026 core_init (void *cls,
2027            const struct GNUNET_PeerIdentity *identity)
2028 {
2029   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2030               "I am peer: %s\n",
2031               GNUNET_i2s (identity));
2032   my_identity = *identity;
2033 }
2034
2035
2036 /**
2037  * Process dv requests.
2038  *
2039  * @param cls closure
2040  * @param server the initialized server
2041  * @param c configuration to use
2042  */
2043 static void
2044 run (void *cls, struct GNUNET_SERVER_Handle *server,
2045      const struct GNUNET_CONFIGURATION_Handle *c)
2046 {
2047   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2048     {&handle_dv_route_message, GNUNET_MESSAGE_TYPE_DV_ROUTE, 0},
2049     {NULL, 0, 0}
2050   };
2051   static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
2052     {&handle_start, NULL,
2053      GNUNET_MESSAGE_TYPE_DV_START,
2054      sizeof (struct GNUNET_MessageHeader) },
2055     { &handle_dv_send_message, NULL,
2056       GNUNET_MESSAGE_TYPE_DV_SEND,
2057       0},
2058     {NULL, NULL, 0, 0}
2059   };
2060   in_shutdown = GNUNET_NO;
2061   cfg = c;
2062   direct_neighbors = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
2063   all_routes = GNUNET_CONTAINER_multipeermap_create (65536, GNUNET_NO);
2064   core_api = GNUNET_CORE_connect (cfg, NULL,
2065                                   &core_init,
2066                                   &handle_core_connect,
2067                                   &handle_core_disconnect,
2068                                   NULL, GNUNET_NO,
2069                                   NULL, GNUNET_NO,
2070                                   core_handlers);
2071
2072   if (NULL == core_api)
2073     return;
2074   ats = GNUNET_ATS_performance_init (cfg, &handle_ats_update, NULL);
2075   if (NULL == ats)
2076   {
2077     GNUNET_CORE_disconnect (core_api);
2078     core_api = NULL;
2079     return;
2080   }
2081   nc = GNUNET_SERVER_notification_context_create (server,
2082                                                   MAX_QUEUE_SIZE_PLUGIN);
2083   stats = GNUNET_STATISTICS_create ("dv", cfg);
2084   GNUNET_SERVER_add_handlers (server, plugin_handlers);
2085   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2086                                 &shutdown_task, NULL);
2087 }
2088
2089
2090 /**
2091  * The main function for the dv service.
2092  *
2093  * @param argc number of arguments from the command line
2094  * @param argv command line arguments
2095  * @return 0 ok, 1 on error
2096  */
2097 int
2098 main (int argc, char *const *argv)
2099 {
2100   return (GNUNET_OK ==
2101           GNUNET_SERVICE_run (argc, argv, "dv", GNUNET_SERVICE_OPTION_NONE,
2102                               &run, NULL)) ? 0 : 1;
2103 }
2104
2105 /* end of gnunet-service-dv.c */