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