-adding missing break statements
[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 - 1];
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   cs = &consensi[distance];
709   i = 0;
710   while ( (i < cs->array_length) &&
711           (NULL != cs->targets[i]) ) i++;
712   if (i == cs->array_length)
713   {
714     GNUNET_array_grow (cs->targets,
715                        cs->array_length,
716                        cs->array_length * 2 + 2);
717   }
718   return i;
719 }
720
721
722 /**
723  * Allocate a slot in the consensus set for a route.
724  *
725  * @param route route to initialize
726  * @param distance which consensus set to use
727  */
728 static void
729 allocate_route (struct Route *route,
730                 uint32_t distance)
731 {
732   unsigned int i;
733
734   i = get_consensus_slot (distance);
735   route->set_offset = i;
736   consensi[distance].targets[i] = route;
737   route->target.distance = htonl (distance);
738 }
739
740
741 /**
742  * Release a slot in the consensus set for a route.
743  *
744  * @param route route to release the slot from
745  */
746 static void
747 release_route (struct Route *route)
748 {
749   consensi[ntohl (route->target.distance)].targets[route->set_offset] = NULL;
750   route->set_offset = UINT_MAX; /* indicate invalid slot */
751 }
752
753
754 /**
755  * Move a route from one consensus set to another.
756  *
757  * @param route route to move
758  * @param new_distance new distance for the route (destination set)
759  */
760 static void
761 move_route (struct Route *route,
762             uint32_t new_distance)
763 {
764   unsigned int i;
765
766   release_route (route);
767   i = get_consensus_slot (new_distance);
768   route->set_offset = i;
769   consensi[new_distance].targets[i] = route;
770   route->target.distance = htonl (new_distance);
771 }
772
773
774 /**
775  * Initialize this neighbors 'my_set' and when done give
776  * it to the pending set operation for execution.
777  *
778  * Add a single element to the set per call:
779  *
780  * If we reached the last element of a consensus element: increase distance
781  *
782  *
783  * @param cls the neighbor for which we are building the set
784  */
785 static void
786 build_set (void *cls)
787 {
788   struct DirectNeighbor *neighbor = cls;
789   struct GNUNET_SET_Element element;
790   struct Target *target;
791   target = NULL;
792   while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
793           (consensi[neighbor->consensus_insertion_distance].array_length == neighbor->consensus_insertion_offset) )
794   {
795     /* If we reached the last element of a consensus array element: increase distance and start with next array */
796     neighbor->consensus_insertion_offset = 0;
797     neighbor->consensus_insertion_distance++;
798     /* skip over NULL entries */
799     while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
800             (consensi[neighbor->consensus_insertion_distance].array_length  > neighbor->consensus_insertion_offset) &&
801             (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
802       neighbor->consensus_insertion_offset++;
803   }
804   if (DEFAULT_FISHEYE_DEPTH - 1 == neighbor->consensus_insertion_distance)
805   {
806     /* we have added all elements to the set, run the operation */
807     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
808                 "Finished building my SET for peer `%s' with %u elements, committing\n",
809                 GNUNET_i2s(&neighbor->peer),
810                 neighbor->consensus_elements);
811     GNUNET_SET_commit (neighbor->set_op,
812                        neighbor->my_set);
813     GNUNET_SET_destroy (neighbor->my_set);
814     neighbor->my_set = NULL;
815     return;
816   }
817
818   target = &consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]->target;
819   element.size = sizeof (struct Target);
820   element.type = htons (0); /* do we need this? */
821   element.data = target;
822
823   /* Find next non-NULL entry */
824   neighbor->consensus_insertion_offset++;
825   /* skip over NULL entries */
826   while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
827           (consensi[neighbor->consensus_insertion_distance].array_length > neighbor->consensus_insertion_offset) &&
828           (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
829   {
830     neighbor->consensus_insertion_offset++;
831   }
832
833   if ( (0 != memcmp(&target->peer, &my_identity, sizeof (my_identity))) &&
834        (0 != memcmp(&target->peer, &neighbor->peer, sizeof (neighbor->peer))) )
835   {
836     /* Add target if it is not the neighbor or this peer */
837     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
838                 "Adding peer `%s' with distance %u to SET\n",
839                 GNUNET_i2s (&target->peer),
840                 ntohl (target->distance));
841     GNUNET_SET_add_element (neighbor->my_set,
842                             &element,
843                             &build_set, neighbor);
844     neighbor->consensus_elements++;
845   }
846   else
847     build_set(neighbor);
848 }
849
850
851 /**
852  * A peer is now connected to us at distance 1.  Initiate DV exchange.
853  *
854  * @param neighbor entry for the neighbor at distance 1
855  */
856 static void
857 handle_direct_connect (struct DirectNeighbor *neighbor)
858 {
859   struct Route *route;
860   struct GNUNET_HashCode h1;
861   struct GNUNET_HashCode h2;
862   struct GNUNET_HashCode session_id;
863
864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
865               "Direct connection to %s established, routing table exchange begins.\n",
866               GNUNET_i2s (&neighbor->peer));
867   GNUNET_STATISTICS_update (stats,
868                             "# peers connected (1-hop)",
869                             1, GNUNET_NO);
870   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
871                                              &neighbor->peer);
872   if (NULL != route)
873   {
874     send_disconnect_to_plugin (&neighbor->peer);
875     release_route (route);
876     GNUNET_free (route);
877   }
878
879   neighbor->direct_route = GNUNET_new (struct Route);
880   neighbor->direct_route->next_hop = neighbor;
881   neighbor->direct_route->target.peer= neighbor->peer;
882   neighbor->direct_route->target.distance = DIRECT_NEIGHBOR_COST;
883   allocate_route (neighbor->direct_route, DIRECT_NEIGHBOR_COST);
884
885   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
886               "Adding direct route to %s\n",
887               GNUNET_i2s (&neighbor->direct_route->target.peer));
888
889
890   /* construct session ID seed as XOR of both peer's identities */
891   GNUNET_CRYPTO_hash (&my_identity, sizeof (my_identity), &h1);
892   GNUNET_CRYPTO_hash (&neighbor->peer, sizeof (struct GNUNET_PeerIdentity), &h2);
893   GNUNET_CRYPTO_hash_xor (&h1,
894                           &h2,
895                           &session_id);
896   /* make sure session ID is unique across applications by salting it with 'DV' */
897   GNUNET_CRYPTO_hkdf (&neighbor->real_session_id, sizeof (struct GNUNET_HashCode),
898                       GCRY_MD_SHA512, GCRY_MD_SHA256,
899                       "DV-SALT", 2,
900                       &session_id, sizeof (session_id),
901                       NULL, 0);
902   if (0 < memcmp (&neighbor->peer,
903                   &my_identity,
904                   sizeof (struct GNUNET_PeerIdentity)))
905   {
906     if (NULL != neighbor->listen_handle)
907     {
908       GNUNET_break (0);
909     }
910     else
911       neighbor->initiate_task = GNUNET_SCHEDULER_add_now (&initiate_set_union,
912                                                         neighbor);
913   }
914   else
915   {
916     if (NULL != neighbor->listen_handle)
917     {
918       GNUNET_break (0);
919     }
920     else
921     {
922       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
923                   "Starting SET listen operation with peer `%s'\n",
924                   GNUNET_i2s(&neighbor->peer));
925       neighbor->listen_handle = GNUNET_SET_listen (cfg,
926                                                    GNUNET_SET_OPERATION_UNION,
927                                                    &neighbor->real_session_id,
928                                                    &listen_set_union,
929                                                    neighbor);
930     }
931   }
932 }
933
934
935 /**
936  * Method called whenever a peer connects.
937  *
938  * @param cls closure
939  * @param peer peer identity this notification is about
940  */
941 static void
942 handle_core_connect (void *cls,
943                      const struct GNUNET_PeerIdentity *peer)
944 {
945   struct DirectNeighbor *neighbor;
946
947   /* Check for connect to self message */
948   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
949     return;
950   /* check if entry exists */
951   neighbor = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
952                                                 peer);
953   if (NULL != neighbor)
954   {
955     GNUNET_break (GNUNET_YES != neighbor->connected);
956     neighbor->connected = GNUNET_YES;
957     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
958                 "Core connected to %s (distance %u)\n",
959                 GNUNET_i2s (peer),
960                 (unsigned int) neighbor->distance);
961     if (DIRECT_NEIGHBOR_COST != neighbor->distance)
962       return;
963     handle_direct_connect (neighbor);
964     return;
965   }
966   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
967               "Core connected to %s (distance unknown)\n",
968               GNUNET_i2s (peer));
969   neighbor = GNUNET_new (struct DirectNeighbor);
970   neighbor->peer = *peer;
971   GNUNET_assert (GNUNET_YES ==
972                  GNUNET_CONTAINER_multipeermap_put (direct_neighbors,
973                                                     peer,
974                                                     neighbor,
975                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
976   neighbor->connected = GNUNET_YES;
977   neighbor->distance = 0; /* unknown */
978   neighbor->network = GNUNET_ATS_NET_UNSPECIFIED;
979 }
980
981
982 /**
983  * Called for each 'target' in a neighbor table to free the associated memory.
984  *
985  * @param cls NULL
986  * @param key key of the value
987  * @param value value to free
988  * @return #GNUNET_OK to continue to iterate
989  */
990 static int
991 free_targets (void *cls,
992               const struct GNUNET_PeerIdentity *key,
993               void *value)
994 {
995   GNUNET_free (value);
996   return GNUNET_OK;
997 }
998
999
1000 /**
1001  * Multipeerhmap iterator for checking if a given route is
1002  * (now) useful to this peer.
1003  *
1004  * @param cls the direct neighbor for the given route
1005  * @param key key value stored under
1006  * @param value a 'struct Target' that may or may not be useful; not that
1007  *        the distance in 'target' does not include the first hop yet
1008  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
1009  */
1010 static int
1011 check_possible_route (void *cls,
1012                       const struct GNUNET_PeerIdentity *key,
1013                       void *value)
1014 {
1015   struct DirectNeighbor *neighbor = cls;
1016   struct Target *target = value;
1017   struct Route *route;
1018
1019   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1020                                              key);
1021   if (NULL != route)
1022   {
1023     if (ntohl (route->target.distance) > ntohl (target->distance) + 1)
1024     {
1025       /* this 'target' is cheaper than the existing route; switch to alternative route! */
1026       move_route (route, ntohl (target->distance) + 1);
1027       route->next_hop = neighbor;
1028       send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
1029     }
1030     return GNUNET_YES; /* got a route to this target already */
1031   }
1032   route = GNUNET_new (struct Route);
1033   route->next_hop = neighbor;
1034   route->target.distance = htonl (ntohl (target->distance) + 1);
1035   route->target.peer = target->peer;
1036   allocate_route (route, ntohl (route->target.distance));
1037   GNUNET_assert (GNUNET_YES ==
1038                  GNUNET_CONTAINER_multipeermap_put (all_routes,
1039                                                     &route->target.peer,
1040                                                     route,
1041                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1042   send_connect_to_plugin (&route->target.peer, ntohl (target->distance),
1043       neighbor->network);
1044   return GNUNET_YES;
1045 }
1046
1047
1048 /**
1049  * Multipeermap iterator for finding routes that were previously
1050  * "hidden" due to a better route (called after a disconnect event).
1051  *
1052  * @param cls NULL
1053  * @param key peer identity of the given direct neighbor
1054  * @param value a `struct DirectNeighbor` to check for additional routes
1055  * @return #GNUNET_YES to continue iteration
1056  */
1057 static int
1058 refresh_routes (void *cls,
1059                 const struct GNUNET_PeerIdentity *key,
1060                 void *value)
1061 {
1062   struct DirectNeighbor *neighbor = value;
1063
1064   if ( (GNUNET_YES != neighbor->connected) ||
1065        (DIRECT_NEIGHBOR_COST != neighbor->distance) )
1066     return GNUNET_YES;
1067   if (NULL != neighbor->neighbor_table)
1068     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1069                                            &check_possible_route,
1070                                            neighbor);
1071   return GNUNET_YES;
1072 }
1073
1074
1075 /**
1076  * Task to run #refresh_routes() on all direct neighbours.
1077  *
1078  * @param cls NULL
1079  * @param tc unused
1080  */
1081 static void
1082 refresh_routes_task (void *cls,
1083                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1084 {
1085   rr_task = GNUNET_SCHEDULER_NO_TASK;
1086   GNUNET_CONTAINER_multipeermap_iterate (direct_neighbors,
1087                                          &refresh_routes,
1088                                          NULL);
1089 }
1090
1091
1092 /**
1093  * Asynchronously run #refresh_routes() at the next opportunity
1094  * on all direct neighbours.
1095  */
1096 static void
1097 schedule_refresh_routes ()
1098 {
1099   if (GNUNET_SCHEDULER_NO_TASK == rr_task)
1100     rr_task = GNUNET_SCHEDULER_add_now (&refresh_routes_task,
1101                                         NULL);
1102 }
1103
1104
1105 /**
1106  * Get distance information from 'atsi'.
1107  *
1108  * @param atsi performance data
1109  * @param atsi_count number of entries in atsi
1110  * @return connected transport distance
1111  */
1112 static uint32_t
1113 get_atsi_distance (const struct GNUNET_ATS_Information *atsi,
1114                    uint32_t atsi_count)
1115 {
1116   uint32_t i;
1117
1118   for (i = 0; i < atsi_count; i++)
1119     if (ntohl (atsi[i].type) == GNUNET_ATS_QUALITY_NET_DISTANCE)
1120       return (0 == ntohl (atsi[i].value)) ? DIRECT_NEIGHBOR_COST : ntohl (atsi[i].value); // FIXME: 0 check should not be required once ATS is fixed!
1121   /* If we do not have explicit distance data, assume direct neighbor. */
1122   return DIRECT_NEIGHBOR_COST;
1123 }
1124
1125
1126 /**
1127  * Get network information from 'atsi'.
1128  *
1129  * @param atsi performance data
1130  * @param atsi_count number of entries in atsi
1131  * @return connected transport network
1132  */
1133 static uint32_t
1134 get_atsi_network (const struct GNUNET_ATS_Information *atsi,
1135                    uint32_t atsi_count)
1136 {
1137   uint32_t i;
1138
1139   for (i = 0; i < atsi_count; i++)
1140     if (ntohl (atsi[i].type) == GNUNET_ATS_NETWORK_TYPE)
1141       return ntohl (atsi[i].value);
1142   return GNUNET_ATS_NET_UNSPECIFIED;
1143 }
1144
1145 /**
1146  * Multipeermap iterator for freeing routes that go via a particular
1147  * neighbor that disconnected and is thus no longer available.
1148  *
1149  * @param cls the direct neighbor that is now unavailable
1150  * @param key key value stored under
1151  * @param value a 'struct Route' that may or may not go via neighbor
1152  *
1153  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1154  */
1155 static int
1156 cull_routes (void *cls,
1157              const struct GNUNET_PeerIdentity *key,
1158              void *value)
1159 {
1160   struct DirectNeighbor *neighbor = cls;
1161   struct Route *route = value;
1162
1163   if (route->next_hop != neighbor)
1164     return GNUNET_YES; /* not affected */
1165   GNUNET_assert (GNUNET_YES ==
1166                  GNUNET_CONTAINER_multipeermap_remove (all_routes, key, value));
1167   release_route (route);
1168   send_disconnect_to_plugin (&route->target.peer);
1169   GNUNET_free (route);
1170   return GNUNET_YES;
1171 }
1172
1173
1174 /**
1175  * Handle the case that a direct connection to a peer is
1176  * disrupted.  Remove all routes via that peer and
1177  * stop the consensus with it.
1178  *
1179  * @param neighbor peer that was disconnected (or at least is no
1180  *    longer at distance 1)
1181  */
1182 static void
1183 handle_direct_disconnect (struct DirectNeighbor *neighbor)
1184 {
1185   GNUNET_CONTAINER_multipeermap_iterate (all_routes,
1186                                          &cull_routes,
1187                                          neighbor);
1188   if (NULL != neighbor->cth)
1189   {
1190     GNUNET_CORE_notify_transmit_ready_cancel (neighbor->cth);
1191     neighbor->cth = NULL;
1192   }
1193
1194   if (NULL != neighbor->direct_route)
1195   {
1196     release_route (neighbor->direct_route);
1197     GNUNET_free (neighbor->direct_route);
1198     neighbor->direct_route = NULL;
1199   }
1200
1201   if (NULL != neighbor->neighbor_table_consensus)
1202   {
1203     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table_consensus,
1204                                            &free_targets,
1205                                            NULL);
1206     GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table_consensus);
1207     neighbor->neighbor_table_consensus = NULL;
1208   }
1209   if (NULL != neighbor->neighbor_table)
1210   {
1211     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1212                                            &free_targets,
1213                                            NULL);
1214     GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table);
1215     neighbor->neighbor_table = NULL;
1216   }
1217   if (NULL != neighbor->set_op)
1218   {
1219     GNUNET_SET_operation_cancel (neighbor->set_op);
1220     neighbor->set_op = NULL;
1221   }
1222   if (NULL != neighbor->my_set)
1223   {
1224     GNUNET_SET_destroy (neighbor->my_set);
1225     neighbor->my_set = NULL;
1226   }
1227   if (NULL != neighbor->listen_handle)
1228   {
1229     GNUNET_SET_listen_cancel (neighbor->listen_handle);
1230     neighbor->listen_handle = NULL;
1231   }
1232   if (GNUNET_SCHEDULER_NO_TASK != neighbor->initiate_task)
1233   {
1234     GNUNET_SCHEDULER_cancel (neighbor->initiate_task);
1235     neighbor->initiate_task = GNUNET_SCHEDULER_NO_TASK;
1236   }
1237 }
1238
1239
1240 /**
1241  * Function that is called with QoS information about an address; used
1242  * to update our current distance to another peer.
1243  *
1244  * @param cls closure
1245  * @param address the address
1246  * @param active is this address in active use
1247  * @param bandwidth_out assigned outbound bandwidth for the connection
1248  * @param bandwidth_in assigned inbound bandwidth for the connection
1249  * @param ats performance data for the address (as far as known)
1250  * @param ats_count number of performance records in 'ats'
1251  */
1252 static void
1253 handle_ats_update (void *cls,
1254                    const struct GNUNET_HELLO_Address *address,
1255                    int active,
1256                    struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1257                    struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1258                    const struct GNUNET_ATS_Information *ats,
1259                    uint32_t ats_count)
1260 {
1261   struct DirectNeighbor *neighbor;
1262   uint32_t distance;
1263   uint32_t network = GNUNET_ATS_NET_UNSPECIFIED;
1264
1265   if (GNUNET_NO == active)
1266         return;
1267   distance = get_atsi_distance (ats, ats_count);
1268   network = get_atsi_network (ats, ats_count);
1269
1270   /*
1271   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1272               "ATS says distance to %s is %u\n",
1273               GNUNET_i2s (&address->peer),
1274               (unsigned int) distance);*/
1275   /* check if entry exists */
1276   neighbor = GNUNET_CONTAINER_multipeermap_get (direct_neighbors,
1277                                                 &address->peer);
1278   if (NULL != neighbor)
1279   {
1280     if (GNUNET_ATS_NET_UNSPECIFIED != network)
1281       neighbor->network = network;
1282
1283     if ( (DIRECT_NEIGHBOR_COST == neighbor->distance) &&
1284          (DIRECT_NEIGHBOR_COST == distance) )
1285       return; /* no change */
1286     if (DIRECT_NEIGHBOR_COST == neighbor->distance)
1287     {
1288       neighbor->distance = distance;
1289       GNUNET_STATISTICS_update (stats,
1290                                 "# peers connected (1-hop)",
1291                                 -1, GNUNET_NO);
1292       handle_direct_disconnect (neighbor);
1293       schedule_refresh_routes ();
1294       return;
1295     }
1296     neighbor->distance = distance;
1297     if (DIRECT_NEIGHBOR_COST != neighbor->distance)
1298       return;
1299     if (GNUNET_YES != neighbor->connected)
1300       return;
1301     handle_direct_connect (neighbor);
1302     return;
1303   }
1304   neighbor = GNUNET_new (struct DirectNeighbor);
1305   neighbor->peer = address->peer;
1306   GNUNET_assert (GNUNET_YES ==
1307                  GNUNET_CONTAINER_multipeermap_put (direct_neighbors,
1308                                                     &address->peer,
1309                                                     neighbor,
1310                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1311   neighbor->connected = GNUNET_NO; /* not yet */
1312   neighbor->distance = distance;
1313   neighbor->network = network;
1314 }
1315
1316
1317 /**
1318  * Check if a target was removed from the set of the other peer; if so,
1319  * if we also used it for our route, we need to remove it from our
1320  * 'all_routes' set (and later check if an alternative path now exists).
1321  *
1322  * @param cls the 'struct DirectNeighbor'
1323  * @param key peer identity for the target
1324  * @param value a 'struct Target' previously reachable via the given neighbor
1325  */
1326 static int
1327 check_target_removed (void *cls,
1328                       const struct GNUNET_PeerIdentity *key,
1329                       void *value)
1330 {
1331   struct DirectNeighbor *neighbor = cls;
1332   struct Target *new_target;
1333   struct Route *current_route;
1334
1335   new_target = GNUNET_CONTAINER_multipeermap_get (neighbor->neighbor_table_consensus,
1336                                                   key);
1337   if (NULL == new_target)
1338   {
1339     /* target was revoked, check if it was used */
1340     current_route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1341                                                        key);
1342     if ( (NULL == current_route) ||
1343          (current_route->next_hop != neighbor) )
1344     {
1345       /* didn't matter, wasn't used */
1346       return GNUNET_OK;
1347     }
1348     /* remove existing route */
1349     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1350                 "Lost route to %s\n",
1351                 GNUNET_i2s (&current_route->target.peer));
1352     GNUNET_assert (GNUNET_YES ==
1353                    GNUNET_CONTAINER_multipeermap_remove (all_routes, key, current_route));
1354     send_disconnect_to_plugin (&current_route->target.peer);
1355     GNUNET_free (current_route);
1356     neighbor->target_removed = GNUNET_YES;
1357     return GNUNET_OK;
1358   }
1359   return GNUNET_OK;
1360 }
1361
1362
1363 /**
1364  * Check if a target was added to the set of the other peer; if it
1365  * was added or impoves the existing route, do the needed updates.
1366  *
1367  * @param cls the 'struct DirectNeighbor'
1368  * @param key peer identity for the target
1369  * @param value a 'struct Target' now reachable via the given neighbor
1370  */
1371 static int
1372 check_target_added (void *cls,
1373                     const struct GNUNET_PeerIdentity *key,
1374                     void *value)
1375 {
1376   struct DirectNeighbor *neighbor = cls;
1377   struct Target *target = value;
1378   struct Route *current_route;
1379
1380   /* target was revoked, check if it was used */
1381   current_route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1382                                                      key);
1383   if (NULL != current_route)
1384   {
1385     /* route exists */
1386     if (current_route->next_hop == neighbor)
1387     {
1388       /* we had the same route before, no change */
1389       if (ntohl (target->distance) + 1 != ntohl (current_route->target.distance))
1390       {
1391         current_route->target.distance = htonl (ntohl (target->distance) + 1);
1392         send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
1393       }
1394       return GNUNET_OK;
1395     }
1396     if (ntohl (current_route->target.distance) >= ntohl (target->distance) + 1)
1397     {
1398       /* alternative, shorter route exists, ignore */
1399       return GNUNET_OK;
1400     }
1401     /* new route is better than the existing one, take over! */
1402     /* NOTE: minor security issue: malicious peers may advertise
1403        very short routes to take over longer paths; as we don't
1404        check that the shorter routes actually work, a malicious
1405        direct neighbor can use this to DoS our long routes */
1406     current_route->next_hop = neighbor;
1407     current_route->target.distance = htonl (ntohl (target->distance) + 1);
1408     send_distance_change_to_plugin (&target->peer, ntohl (target->distance) + 1);
1409     return GNUNET_OK;
1410   }
1411   /* new route */
1412   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1413               "Discovered new route to %s using %u hops\n",
1414               GNUNET_i2s (&target->peer),
1415               (unsigned int) (ntohl (target->distance) + 1));
1416   current_route = GNUNET_new (struct Route);
1417   current_route->next_hop = neighbor;
1418   current_route->target.peer = target->peer;
1419   current_route->target.distance = htonl (ntohl (target->distance) + 1);
1420   GNUNET_assert (GNUNET_YES ==
1421                  GNUNET_CONTAINER_multipeermap_put (all_routes,
1422                                                     &current_route->target.peer,
1423                                                     current_route,
1424                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1425
1426   send_connect_to_plugin (&current_route->target.peer,
1427                           ntohl (current_route->target.distance),
1428                           neighbor->network);
1429   return GNUNET_OK;
1430 }
1431
1432
1433 /**
1434  * Callback for set operation results. Called for each element
1435  * in the result set.
1436  * We have learned a new route from the other peer.  Add it to the
1437  * route set we're building.
1438  *
1439  * @param cls the 'struct DirectNeighbor' we're building the consensus with
1440  * @param element a result element, only valid if status is GNUNET_SET_STATUS_OK
1441  * @param status see enum GNUNET_SET_Status
1442  */
1443 static void
1444 handle_set_union_result (void *cls,
1445                          const struct GNUNET_SET_Element *element,
1446                          enum GNUNET_SET_Status status)
1447 {
1448   struct DirectNeighbor *neighbor = cls;
1449   struct Target *target;
1450   char *status_str;
1451
1452   switch (status) {
1453     case GNUNET_SET_STATUS_OK:
1454       status_str = "GNUNET_SET_STATUS_OK";
1455       break;
1456     case GNUNET_SET_STATUS_TIMEOUT:
1457       status_str = "GNUNET_SET_STATUS_TIMEOUT";
1458       break;
1459     case GNUNET_SET_STATUS_FAILURE:
1460       status_str = "GNUNET_SET_STATUS_FAILURE";
1461       break;
1462     case GNUNET_SET_STATUS_HALF_DONE:
1463       status_str = "GNUNET_SET_STATUS_HALF_DONE";
1464       break;
1465     case GNUNET_SET_STATUS_DONE:
1466       status_str = "GNUNET_SET_STATUS_DONE";
1467       break;
1468     default:
1469       status_str = "UNDEFINED";
1470       break;
1471   }
1472
1473   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1474               "Got SET union result: %s\n",
1475               status_str);
1476   switch (status)
1477   {
1478   case GNUNET_SET_STATUS_OK:
1479     if (sizeof (struct Target) != element->size)
1480     {
1481       GNUNET_break_op (0);
1482       return;
1483     }
1484     target = GNUNET_new (struct Target);
1485     memcpy (target, element->data, sizeof (struct Target));
1486     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1487                 "Received information about peer `%s' with distance %u\n",
1488                 GNUNET_i2s (&target->peer), ntohl(target->distance) + 1);
1489     if (NULL == neighbor->neighbor_table_consensus)
1490       neighbor->neighbor_table_consensus = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1491     if (GNUNET_YES !=
1492         GNUNET_CONTAINER_multipeermap_put (neighbor->neighbor_table_consensus,
1493                                            &target->peer,
1494                                            target,
1495                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1496     {
1497       GNUNET_break_op (0);
1498       GNUNET_free (target);
1499     }
1500     break;
1501   case GNUNET_SET_STATUS_TIMEOUT:
1502   case GNUNET_SET_STATUS_FAILURE:
1503     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1504                 "Failed to establish DV union, will try again later\n");
1505     neighbor->set_op = NULL;
1506     if (NULL != neighbor->neighbor_table_consensus)
1507     {
1508       GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table_consensus,
1509                                              &free_targets,
1510                                              NULL);
1511       GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table_consensus);
1512       neighbor->neighbor_table_consensus = NULL;
1513     }
1514     if (0 < memcmp (&neighbor->peer,
1515                     &my_identity,
1516                     sizeof (struct GNUNET_PeerIdentity)))
1517       neighbor->initiate_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1518                                                               &initiate_set_union,
1519                                                               neighbor);
1520     break;
1521   case GNUNET_SET_STATUS_HALF_DONE:
1522     break;
1523   case GNUNET_SET_STATUS_DONE:
1524     /* we got all of our updates; integrate routing table! */
1525     neighbor->target_removed = GNUNET_NO;
1526     if (NULL == neighbor->neighbor_table_consensus)
1527       neighbor->neighbor_table_consensus = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1528     if (NULL != neighbor->neighbor_table)
1529       GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1530                                            &check_target_removed,
1531                                            neighbor);
1532     if (GNUNET_YES == neighbor->target_removed)
1533     {
1534       /* check if we got an alternative for the removed routes */
1535       schedule_refresh_routes ();
1536     }
1537     /* add targets that appeared (and check for improved routes) */
1538     GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table_consensus,
1539                                            &check_target_added,
1540                                            neighbor);
1541     if (NULL != neighbor->neighbor_table)
1542     {
1543       GNUNET_CONTAINER_multipeermap_iterate (neighbor->neighbor_table,
1544                                              &free_targets,
1545                                              NULL);
1546       GNUNET_CONTAINER_multipeermap_destroy (neighbor->neighbor_table);
1547       neighbor->neighbor_table = NULL;
1548     }
1549     neighbor->neighbor_table = neighbor->neighbor_table_consensus;
1550     neighbor->neighbor_table_consensus = NULL;
1551
1552     /* operation done, schedule next run! */
1553     neighbor->set_op = NULL;
1554     if (0 < memcmp (&neighbor->peer,
1555                     &my_identity,
1556                     sizeof (struct GNUNET_PeerIdentity)))
1557       neighbor->initiate_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1558                                                               &initiate_set_union,
1559                                                               neighbor);
1560     break;
1561   default:
1562     GNUNET_break (0);
1563     return;
1564   }
1565 }
1566
1567
1568 /**
1569  * Start creating a new DV set union construction, our neighbour has
1570  * asked for it (callback for listening peer).
1571  *
1572  * @param cls the 'struct DirectNeighbor' of the peer we're building
1573  *        a routing consensus with
1574  * @param other_peer the other peer
1575  * @param context_msg message with application specific information from
1576  *        the other peer
1577  * @param request request from the other peer, use GNUNET_SET_accept
1578  *        to accept it, otherwise the request will be refused
1579  *        Note that we don't use a return value here, as it is also
1580  *        necessary to specify the set we want to do the operation with,
1581  *        whith sometimes can be derived from the context message.
1582  *        Also necessary to specify the timeout.
1583  */
1584 static void
1585 listen_set_union (void *cls,
1586                   const struct GNUNET_PeerIdentity *other_peer,
1587                   const struct GNUNET_MessageHeader *context_msg,
1588                   struct GNUNET_SET_Request *request)
1589 {
1590   struct DirectNeighbor *neighbor = cls;
1591
1592   if (NULL == request)
1593     return; /* why??? */
1594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1595               "Starting to create consensus with %s\n",
1596               GNUNET_i2s (&neighbor->peer));
1597   if (NULL != neighbor->set_op)
1598   {
1599     GNUNET_SET_operation_cancel (neighbor->set_op);
1600     neighbor->set_op = NULL;
1601   }
1602   if (NULL != neighbor->my_set)
1603   {
1604     GNUNET_SET_destroy (neighbor->my_set);
1605     neighbor->my_set = NULL;
1606   }
1607   neighbor->my_set = GNUNET_SET_create (cfg,
1608                                         GNUNET_SET_OPERATION_UNION);
1609   neighbor->set_op = GNUNET_SET_accept (request,
1610                                         GNUNET_SET_RESULT_ADDED,
1611                                         &handle_set_union_result,
1612                                         neighbor);
1613   neighbor->consensus_insertion_offset = 0;
1614   neighbor->consensus_insertion_distance = 0;
1615   neighbor->consensus_elements = 0;
1616   build_set (neighbor);
1617 }
1618
1619
1620 /**
1621  * Start creating a new DV set union by initiating the connection.
1622  *
1623  * @param cls the 'struct DirectNeighbor' of the peer we're building
1624  *        a routing consensus with
1625  * @param tc scheduler context
1626  */
1627 static void
1628 initiate_set_union (void *cls,
1629                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1630 {
1631   struct DirectNeighbor *neighbor = cls;
1632
1633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1634               "Initiating SET union with peer `%s'\n",
1635               GNUNET_i2s (&neighbor->peer));
1636   neighbor->initiate_task = GNUNET_SCHEDULER_NO_TASK;
1637   neighbor->my_set = GNUNET_SET_create (cfg,
1638                                         GNUNET_SET_OPERATION_UNION);
1639   neighbor->set_op = GNUNET_SET_prepare (&neighbor->peer,
1640                                          &neighbor->real_session_id,
1641                                          NULL,
1642                                          0 /* FIXME: salt */,
1643                                          GNUNET_SET_RESULT_ADDED,
1644                                          &handle_set_union_result,
1645                                          neighbor);
1646   neighbor->consensus_insertion_offset = 0;
1647   neighbor->consensus_insertion_distance = 0;
1648   neighbor->consensus_elements = 0;
1649   build_set (neighbor);
1650 }
1651
1652
1653 /**
1654  * Core handler for DV data messages.  Whatever this message
1655  * contains all we really have to do is rip it out of its
1656  * DV layering and give it to our pal the DV plugin to report
1657  * in with.
1658  *
1659  * @param cls closure
1660  * @param peer peer which sent the message (immediate sender)
1661  * @param message the message
1662  * @return GNUNET_OK on success, GNUNET_SYSERR if the other peer violated the protocol
1663  */
1664 static int
1665 handle_dv_route_message (void *cls, const struct GNUNET_PeerIdentity *peer,
1666                          const struct GNUNET_MessageHeader *message)
1667 {
1668   const struct RouteMessage *rm;
1669   const struct GNUNET_MessageHeader *payload;
1670   struct Route *route;
1671
1672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1673               "Handling DV message\n");
1674   if (ntohs (message->size) < sizeof (struct RouteMessage) + sizeof (struct GNUNET_MessageHeader))
1675   {
1676     GNUNET_break_op (0);
1677     return GNUNET_SYSERR;
1678   }
1679   rm = (const struct RouteMessage *) message;
1680   payload = (const struct GNUNET_MessageHeader *) &rm[1];
1681   if (ntohs (message->size) != sizeof (struct RouteMessage) + ntohs (payload->size))
1682   {
1683     GNUNET_break_op (0);
1684     return GNUNET_SYSERR;
1685   }
1686   if (0 == memcmp (&rm->target,
1687                    &my_identity,
1688                    sizeof (struct GNUNET_PeerIdentity)))
1689   {
1690     /* message is for me, check reverse route! */
1691     route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1692                                                &rm->sender);
1693     if (NULL == route)
1694     {
1695       /* don't have reverse route, drop */
1696       GNUNET_STATISTICS_update (stats,
1697                                 "# message discarded (no reverse route)",
1698                                 1, GNUNET_NO);
1699       return GNUNET_OK;
1700     }
1701     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1702                 "Delivering %u bytes to myself!\n",
1703                 ntohs (payload->size));
1704     send_data_to_plugin (payload,
1705                          &rm->sender,
1706                          ntohl (route->target.distance));
1707     return GNUNET_OK;
1708   }
1709   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1710                                              &rm->target);
1711   if (NULL == route)
1712   {
1713     GNUNET_STATISTICS_update (stats,
1714                               "# messages discarded (no route)",
1715                               1, GNUNET_NO);
1716     return GNUNET_OK;
1717   }
1718   if (ntohl (route->target.distance) > ntohl (rm->distance) + 1)
1719   {
1720     GNUNET_STATISTICS_update (stats,
1721                               "# messages discarded (target too far)",
1722                               1, GNUNET_NO);
1723     return GNUNET_OK;
1724   }
1725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1726               "Forwarding message to %s\n",
1727               GNUNET_i2s (&rm->target));
1728   forward_payload (route->next_hop,
1729                    ntohl (route->target.distance),
1730                    0,
1731                    &rm->target,
1732                    &rm->sender,
1733                    payload);
1734   return GNUNET_OK;
1735 }
1736
1737
1738 /**
1739  * Service server's handler for message send requests (which come
1740  * bubbling up to us through the DV plugin).
1741  *
1742  * @param cls closure
1743  * @param client identification of the client
1744  * @param message the actual message
1745  */
1746 static void
1747 handle_dv_send_message (void *cls, struct GNUNET_SERVER_Client *client,
1748                         const struct GNUNET_MessageHeader *message)
1749 {
1750   struct Route *route;
1751   const struct GNUNET_DV_SendMessage *msg;
1752   const struct GNUNET_MessageHeader *payload;
1753
1754   if (ntohs (message->size) < sizeof (struct GNUNET_DV_SendMessage) + sizeof (struct GNUNET_MessageHeader))
1755   {
1756     GNUNET_break (0);
1757     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1758     return;
1759   }
1760   msg = (const struct GNUNET_DV_SendMessage *) message;
1761   GNUNET_break (0 != ntohl (msg->uid));
1762   payload = (const struct GNUNET_MessageHeader *) &msg[1];
1763   if (ntohs (message->size) != sizeof (struct GNUNET_DV_SendMessage) + ntohs (payload->size))
1764   {
1765     GNUNET_break (0);
1766     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1767     return;
1768   }
1769   route = GNUNET_CONTAINER_multipeermap_get (all_routes,
1770                                              &msg->target);
1771   if (NULL == route)
1772   {
1773     /* got disconnected */
1774     GNUNET_STATISTICS_update (stats,
1775                               "# local messages discarded (no route)",
1776                               1, GNUNET_NO);
1777     send_ack_to_plugin (&msg->target, ntohl (msg->uid), GNUNET_YES);
1778     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1779     return;
1780   }
1781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1782               "Forwarding %u bytes to %s\n",
1783               ntohs (payload->size),
1784               GNUNET_i2s (&msg->target));
1785
1786   forward_payload (route->next_hop,
1787                    ntohl (route->target.distance),
1788                    htonl (msg->uid),
1789                    &msg->target,
1790                    &my_identity,
1791                    payload);
1792   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1793 }
1794
1795
1796 /**
1797  * Cleanup all of the data structures associated with a given neighbor.
1798  *
1799  * @param neighbor neighbor to clean up
1800  */
1801 static void
1802 cleanup_neighbor (struct DirectNeighbor *neighbor)
1803 {
1804   struct PendingMessage *pending;
1805
1806   while (NULL != (pending = neighbor->pm_head))
1807   {
1808     neighbor->pm_queue_size--;
1809     GNUNET_CONTAINER_DLL_remove (neighbor->pm_head,
1810                                  neighbor->pm_tail,
1811                                  pending);
1812     GNUNET_free (pending);
1813   }
1814   handle_direct_disconnect (neighbor);
1815   GNUNET_assert (GNUNET_YES ==
1816                  GNUNET_CONTAINER_multipeermap_remove (direct_neighbors,
1817                                                        &neighbor->peer,
1818                                                        neighbor));
1819   GNUNET_free (neighbor);
1820 }
1821
1822
1823 /**
1824  * Method called whenever a given peer disconnects.
1825  *
1826  * @param cls closure
1827  * @param peer peer identity this notification is about
1828  */
1829 static void
1830 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1831 {
1832   struct DirectNeighbor *neighbor;
1833
1834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1835               "Received core peer disconnect message for peer `%s'!\n",
1836               GNUNET_i2s (peer));
1837   /* Check for disconnect from self message */
1838   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1839     return;
1840   neighbor =
1841       GNUNET_CONTAINER_multipeermap_get (direct_neighbors, peer);
1842   if (NULL == neighbor)
1843   {
1844     GNUNET_break (0);
1845     return;
1846   }
1847   GNUNET_break (GNUNET_YES == neighbor->connected);
1848   neighbor->connected = GNUNET_NO;
1849   if (DIRECT_NEIGHBOR_COST == neighbor->distance)
1850   {
1851
1852     GNUNET_STATISTICS_update (stats,
1853                               "# peers connected (1-hop)",
1854                               -1, GNUNET_NO);
1855   }
1856   cleanup_neighbor (neighbor);
1857
1858   if (GNUNET_YES == in_shutdown)
1859     return;
1860   schedule_refresh_routes ();
1861 }
1862
1863
1864 /**
1865  * Multipeermap iterator for freeing routes.  Should never be called.
1866  *
1867  * @param cls NULL
1868  * @param key key value stored under
1869  * @param value the route to be freed
1870  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
1871  */
1872 static int
1873 free_route (void *cls,
1874             const struct GNUNET_PeerIdentity *key,
1875             void *value)
1876 {
1877   struct Route *route = value;
1878
1879   GNUNET_break (0);
1880   GNUNET_assert (GNUNET_YES ==
1881                  GNUNET_CONTAINER_multipeermap_remove (all_routes, key, value));
1882   release_route (route);
1883   send_disconnect_to_plugin (&route->target.peer);
1884   GNUNET_free (route);
1885   return GNUNET_YES;
1886 }
1887
1888
1889 /**
1890  * Multipeermap iterator for freeing direct neighbors. Should never be called.
1891  *
1892  * @param cls NULL
1893  * @param key key value stored under
1894  * @param value the direct neighbor to be freed
1895  * @return #GNUNET_YES to continue iteration, #GNUNET_NO to stop
1896  */
1897 static int
1898 free_direct_neighbors (void *cls,
1899                        const struct GNUNET_PeerIdentity *key,
1900                        void *value)
1901 {
1902   struct DirectNeighbor *neighbor = value;
1903   cleanup_neighbor (neighbor);
1904   return GNUNET_YES;
1905 }
1906
1907
1908 /**
1909  * Task run during shutdown.
1910  *
1911  * @param cls unused
1912  * @param tc unused
1913  */
1914 static void
1915 shutdown_task (void *cls,
1916                const struct GNUNET_SCHEDULER_TaskContext *tc)
1917 {
1918   unsigned int i;
1919
1920   in_shutdown = GNUNET_YES;
1921   GNUNET_assert (NULL != core_api);
1922   GNUNET_CORE_disconnect (core_api);
1923   core_api = NULL;
1924   GNUNET_ATS_performance_done (ats);
1925   ats = NULL;
1926   GNUNET_CONTAINER_multipeermap_iterate (direct_neighbors,
1927                                          &free_direct_neighbors, NULL);
1928   GNUNET_CONTAINER_multipeermap_iterate (all_routes,
1929                                          &free_route, NULL);
1930   GNUNET_CONTAINER_multipeermap_destroy (direct_neighbors);
1931   GNUNET_CONTAINER_multipeermap_destroy (all_routes);
1932   GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1933   stats = NULL;
1934   GNUNET_SERVER_notification_context_destroy (nc);
1935   nc = NULL;
1936   for (i=0;i<DEFAULT_FISHEYE_DEPTH - 1;i++)
1937   {
1938     GNUNET_array_grow (consensi[i].targets,
1939                        consensi[i].array_length,
1940                        0);
1941   }
1942   if (GNUNET_SCHEDULER_NO_TASK != rr_task)
1943   {
1944     GNUNET_SCHEDULER_cancel (rr_task);
1945     rr_task = GNUNET_SCHEDULER_NO_TASK;
1946   }
1947 }
1948
1949
1950 /**
1951  * Notify newly connected client about an existing route.
1952  *
1953  * @param cls the `struct GNUNET_SERVER_Client *`
1954  * @param key peer identity
1955  * @param value the `struct Route *`
1956  * @return #GNUNET_OK (continue to iterate)
1957  */
1958 static int
1959 add_route (void *cls,
1960            const struct GNUNET_PeerIdentity *key,
1961            void *value)
1962 {
1963   struct GNUNET_SERVER_Client *client = cls;
1964   struct Route *route = value;
1965   struct GNUNET_DV_ConnectMessage cm;
1966
1967   memset (&cm, 0, sizeof (cm));
1968   cm.header.size = htons (sizeof (cm));
1969   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
1970   cm.distance = htonl (route->target.distance);
1971   cm.peer = route->target.peer;
1972
1973   GNUNET_SERVER_notification_context_unicast (nc,
1974                                               client,
1975                                               &cm.header,
1976                                               GNUNET_NO);
1977   return GNUNET_OK;
1978 }
1979
1980
1981 /**
1982  * Handle START-message.  This is the first message sent to us
1983  * by the client (can only be one!).
1984  *
1985  * @param cls closure (always NULL)
1986  * @param client identification of the client
1987  * @param message the actual message
1988  */
1989 static void
1990 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
1991               const struct GNUNET_MessageHeader *message)
1992 {
1993   GNUNET_SERVER_notification_context_add (nc, client);
1994   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1995   GNUNET_CONTAINER_multipeermap_iterate (all_routes,
1996                                          &add_route,
1997                                          client);
1998 }
1999
2000
2001 /**
2002  * Called on core init.
2003  *
2004  * @param cls unused
2005  * @param identity this peer's identity
2006  */
2007 static void
2008 core_init (void *cls,
2009            const struct GNUNET_PeerIdentity *identity)
2010 {
2011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2012               "I am peer: %s\n",
2013               GNUNET_i2s (identity));
2014   my_identity = *identity;
2015 }
2016
2017
2018 /**
2019  * Process dv requests.
2020  *
2021  * @param cls closure
2022  * @param server the initialized server
2023  * @param c configuration to use
2024  */
2025 static void
2026 run (void *cls, struct GNUNET_SERVER_Handle *server,
2027      const struct GNUNET_CONFIGURATION_Handle *c)
2028 {
2029   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2030     {&handle_dv_route_message, GNUNET_MESSAGE_TYPE_DV_ROUTE, 0},
2031     {NULL, 0, 0}
2032   };
2033   static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
2034     {&handle_start, NULL,
2035      GNUNET_MESSAGE_TYPE_DV_START,
2036      sizeof (struct GNUNET_MessageHeader) },
2037     { &handle_dv_send_message, NULL,
2038       GNUNET_MESSAGE_TYPE_DV_SEND,
2039       0},
2040     {NULL, NULL, 0, 0}
2041   };
2042   in_shutdown = GNUNET_NO;
2043   cfg = c;
2044   direct_neighbors = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
2045   all_routes = GNUNET_CONTAINER_multipeermap_create (65536, GNUNET_NO);
2046   core_api = GNUNET_CORE_connect (cfg, NULL,
2047                                   &core_init,
2048                                   &handle_core_connect,
2049                                   &handle_core_disconnect,
2050                                   NULL, GNUNET_NO,
2051                                   NULL, GNUNET_NO,
2052                                   core_handlers);
2053
2054   if (NULL == core_api)
2055     return;
2056   ats = GNUNET_ATS_performance_init (cfg, &handle_ats_update, NULL);
2057   if (NULL == ats)
2058   {
2059     GNUNET_CORE_disconnect (core_api);
2060     core_api = NULL;
2061     return;
2062   }
2063   nc = GNUNET_SERVER_notification_context_create (server,
2064                                                   MAX_QUEUE_SIZE_PLUGIN);
2065   stats = GNUNET_STATISTICS_create ("dv", cfg);
2066   GNUNET_SERVER_add_handlers (server, plugin_handlers);
2067   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2068                                 &shutdown_task, NULL);
2069 }
2070
2071
2072 /**
2073  * The main function for the dv service.
2074  *
2075  * @param argc number of arguments from the command line
2076  * @param argv command line arguments
2077  * @return 0 ok, 1 on error
2078  */
2079 int
2080 main (int argc, char *const *argv)
2081 {
2082   return (GNUNET_OK ==
2083           GNUNET_SERVICE_run (argc, argv, "dv", GNUNET_SERVICE_OPTION_NONE,
2084                               &run, NULL)) ? 0 : 1;
2085 }
2086
2087 /* end of gnunet-service-dv.c */