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