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