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