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