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