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