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