c42d9344eebe6b93f1957844acfddec34e543b85
[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  * TODO:
31  * - even _local_ flow control (send ACK only after core took our message) is
32  *   not implemented, but should be (easy fix, but needs adjustments to data
33  *   structures)
34  * - distance updates are not properly communicate to US by core,
35  *   and conversely we don't give distance updates properly to the plugin yet
36  * - we send 'ACK' even if a message was dropped due to no route (may
37  *   be harmless, but should at least be documented)
38  */
39 #include "platform.h"
40 #include "gnunet_util_lib.h"
41 #include "gnunet_protocols.h"
42 #include "gnunet_core_service.h"
43 #include "gnunet_hello_lib.h"
44 #include "gnunet_peerinfo_service.h"
45 #include "gnunet_statistics_service.h"
46 #include "gnunet_consensus_service.h"
47 #include "dv.h"
48 #include <gcrypt.h>
49
50 /**
51  * How often do we establish the consensu?
52  */
53 #define GNUNET_DV_CONSENSUS_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
54
55 /**
56  * Maximum number of messages we queue per peer.
57  */
58 #define MAX_QUEUE_SIZE 16
59
60 /**
61  * The default fisheye depth, from how many hops away will
62  * we keep peers?
63  */
64 #define DEFAULT_FISHEYE_DEPTH 3
65
66 /**
67  * How many hops is a direct neighbor away?
68  */
69 #define DIRECT_NEIGHBOR_COST 1
70
71
72 GNUNET_NETWORK_STRUCT_BEGIN
73
74 /**
75  * Information about a peer DV can route to.  These entries are what
76  * we use as the binary format to establish consensus to create our
77  * routing table and as the address format in the HELLOs.
78  */
79 struct Target
80 {
81
82   /**
83    * Identity of the peer we can reach.
84    */
85   struct GNUNET_PeerIdentity peer;
86
87   /**
88    * How many hops (1-3) is this peer away? in network byte order
89    */
90   uint32_t distance GNUNET_PACKED;
91
92 };
93
94
95 /**
96  * Message exchanged between DV services (via core), requesting a
97  * message to be routed.  
98  */
99 struct RouteMessage
100 {
101   /**
102    * Type: GNUNET_MESSAGE_TYPE_DV_ROUTE
103    */
104   struct GNUNET_MessageHeader header;
105
106   /**
107    * Expected (remaining) distance.  Must be always smaller than
108    * DEFAULT_FISHEYE_DEPTH, should be zero at the target.  Must
109    * be decremented by one at each hop.  Peers must not forward
110    * these messages further once the counter has reached zero.
111    */
112   uint32_t distance GNUNET_PACKED;
113
114   /**
115    * The (actual) target of the message (this peer, if distance is zero).
116    */
117   struct GNUNET_PeerIdentity target;
118
119   /**
120    * The (actual) sender of the message.
121    */
122   struct GNUNET_PeerIdentity sender;
123
124 };
125
126 GNUNET_NETWORK_STRUCT_END
127
128
129 /**
130  * Linked list of messages to send to clients.
131  */
132 struct PendingMessage
133 {
134   /**
135    * Pointer to next item in the list
136    */
137   struct PendingMessage *next;
138
139   /**
140    * Pointer to previous item in the list
141    */
142   struct PendingMessage *prev;
143
144   /**
145    * Actual message to be sent, allocated after this struct.
146    */
147   const struct GNUNET_MessageHeader *msg;
148
149   /**
150    * Ultimate target for the message.
151    */
152   struct GNUNET_PeerIdentity ultimate_target;
153
154   /**
155    * Unique ID of the message.
156    */
157   uint32_t uid;
158
159 };
160
161
162 /**
163  * Information about a direct neighbor (core-level, excluding
164  * DV-links, only DV-enabled peers).
165  */
166 struct DirectNeighbor
167 {
168
169   /**
170    * Identity of the peer.
171    */
172   struct GNUNET_PeerIdentity peer;
173   
174   /**
175    * Head of linked list of messages to send to this peer.
176    */
177   struct PendingMessage *pm_head;
178
179   /**
180    * Tail of linked list of messages to send to this peer.
181    */
182   struct PendingMessage *pm_tail;
183
184   /**
185    * Transmit handle to core service.
186    */
187   struct GNUNET_CORE_TransmitHandle *cth;
188
189   /**
190    * Routing table of the neighbor, NULL if not yet established.
191    * Keys are peer identities, values are 'struct Target' entries.
192    * Note that the distances in the targets are from the point-of-view
193    * of the peer, not from us!
194    */ 
195   struct GNUNET_CONTAINER_MultiHashMap *neighbor_table;
196
197   /**
198    * Updated routing table of the neighbor, under construction,
199    * NULL if we are not currently building it.
200    * Keys are peer identities, values are 'struct Target' entries.
201    * Note that the distances in the targets are from the point-of-view
202    * of the peer, not from us!
203    */ 
204   struct GNUNET_CONTAINER_MultiHashMap *neighbor_table_consensus;
205
206   /**
207    * Active consensus, if we are currently synchronizing the
208    * routing tables.
209    */
210   struct GNUNET_CONSENSUS_Handle *consensus;
211
212   /**
213    * ID of the task we use to (periodically) update our consensus
214    * with this peer.
215    */
216   GNUNET_SCHEDULER_TaskIdentifier consensus_task;
217
218   /**
219    * At what offset are we, with respect to inserting our own routes
220    * into the consensus?
221    */
222   unsigned int consensus_insertion_offset;
223
224   /**
225    * At what distance are we, with respect to inserting our own routes
226    * into the consensus?
227    */
228   unsigned int consensus_insertion_distance;
229
230   /**
231    * Number of messages currently in the 'pm_XXXX'-DLL.
232    */
233   unsigned int pm_queue_size;
234
235   /**
236    * Flag set within 'check_target_removed' to trigger full global route refresh.
237    */
238   int target_removed;
239
240 };
241
242
243 /**
244  * A route includes information about the next hop,
245  * the target, and the ultimate distance to the
246  * target.
247  */
248 struct Route
249 {
250
251   /**
252    * Which peer do we need to forward the message to?
253    */
254   struct DirectNeighbor *next_hop;
255
256   /**
257    * What would be the target, and how far is it away?
258    */
259   struct Target target;
260
261   /**
262    * Offset of this target in the respective consensus set.
263    */
264   unsigned int set_offset;
265
266 };
267
268
269 /**
270  * Set of targets we bring to a consensus; all targets in a set have a
271  * distance equal to the sets distance (which is implied by the array
272  * index of the set).
273  */
274 struct ConsensusSet
275 {
276
277   /**
278    * Array of targets in the set, may include NULL entries if a
279    * neighbor has disconnected; the targets are allocated with the
280    * respective container (all_routes), not here.
281    */
282   struct Route **targets;
283
284   /**
285    * Size of the 'targets' array.
286    */
287   unsigned int array_length;
288
289 };
290
291
292 /**
293  * Hashmap of all of our direct neighbors (no DV routing).
294  */
295 static struct GNUNET_CONTAINER_MultiHashMap *direct_neighbors;
296
297 /**
298  * Hashmap with all routes that we currently support; contains 
299  * routing information for all peers from distance 2
300  * up to distance DEFAULT_FISHEYE_DEPTH.
301  */
302 static struct GNUNET_CONTAINER_MultiHashMap *all_routes;
303
304 /**
305  * Array of consensus sets we expose to the outside world.  Sets
306  * are structured by the distance to the target.
307  */
308 static struct ConsensusSet consensi[DEFAULT_FISHEYE_DEPTH - 1];
309
310 /**
311  * Handle to the core service api.
312  */
313 static struct GNUNET_CORE_Handle *core_api;
314
315 /**
316  * The identity of our peer.
317  */
318 static struct GNUNET_PeerIdentity my_identity;
319
320 /**
321  * The configuration for this service.
322  */
323 static const struct GNUNET_CONFIGURATION_Handle *cfg;
324
325 /**
326  * The client, the DV plugin connected to us.  Hopefully
327  * this client will never change, although if the plugin dies
328  * and returns for some reason it may happen.
329  */
330 static struct GNUNET_SERVER_Client *client_handle;
331
332 /**
333  * Transmit handle to the plugin.
334  */
335 static struct GNUNET_SERVER_TransmitHandle *plugin_transmit_handle;
336
337 /**
338  * Head of DLL for client messages
339  */
340 static struct PendingMessage *plugin_pending_head;
341
342 /**
343  * Tail of DLL for client messages
344  */
345 static struct PendingMessage *plugin_pending_tail;
346
347 /**
348  * Handle for the statistics service.
349  */
350 struct GNUNET_STATISTICS_Handle *stats;
351
352
353 /**
354  * Get distance information from 'atsi'.
355  *
356  * @param atsi performance data
357  * @param atsi_count number of entries in atsi
358  * @return connected transport distance
359  */
360 static uint32_t
361 get_atsi_distance (const struct GNUNET_ATS_Information *atsi,
362                    unsigned int atsi_count)
363 {
364   unsigned int i;
365
366   for (i = 0; i < atsi_count; i++)
367     if (ntohl (atsi[i].type) == GNUNET_ATS_QUALITY_NET_DISTANCE)
368       return ntohl (atsi->value);
369   /* FIXME: we do not have distance data? Assume direct neighbor. */
370   return DIRECT_NEIGHBOR_COST;
371 }
372
373
374 /**
375  * Function called to notify a client about the socket
376  * begin ready to queue more data.  "buf" will be
377  * NULL and "size" zero if the socket was closed for
378  * writing in the meantime.
379  *
380  * @param cls closure
381  * @param size number of bytes available in buf
382  * @param buf where the callee should write the message
383  * @return number of bytes written to buf
384  */
385 static size_t
386 transmit_to_plugin (void *cls, size_t size, void *buf)
387 {
388   char *cbuf = buf;
389   struct PendingMessage *reply;
390   size_t off;
391   size_t msize;
392
393   plugin_transmit_handle = NULL;
394   if (NULL == buf)
395   {
396     /* client disconnected */    
397     return 0;
398   }
399   off = 0;
400   while ( (NULL != (reply = plugin_pending_head)) &&
401           (size >= off + (msize = ntohs (reply->msg->size))))
402   {
403     GNUNET_CONTAINER_DLL_remove (plugin_pending_head, plugin_pending_tail,
404                                  reply);
405     memcpy (&cbuf[off], reply->msg, msize);
406     GNUNET_free (reply);
407     off += msize;
408   }
409   if (NULL != plugin_pending_head)
410     plugin_transmit_handle =
411       GNUNET_SERVER_notify_transmit_ready (client_handle,
412                                            msize,
413                                            GNUNET_TIME_UNIT_FOREVER_REL,
414                                            &transmit_to_plugin, NULL);
415   return off;
416 }
417
418
419 /**
420  * Forward a message from another peer to the plugin.
421  *
422  * @param message the message to send to the plugin
423  * @param distant_neighbor the original sender of the message
424  * @param distnace distance to the original sender of the message
425  */
426 static void
427 send_data_to_plugin (const struct GNUNET_MessageHeader *message, 
428                      const struct GNUNET_PeerIdentity *distant_neighbor, 
429                      uint32_t distance)
430 {
431   struct GNUNET_DV_ReceivedMessage *received_msg;
432   struct PendingMessage *pending_message;
433   size_t size;
434
435   if (NULL == client_handle)
436   {
437     GNUNET_STATISTICS_update (stats,
438                               "# messages discarded (no plugin)",
439                               1, GNUNET_NO);
440     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
441                 _("Refusing to queue messages, DV plugin not active.\n"));
442     return;
443   }
444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
445               "Delivering message from peer `%s'\n",
446               GNUNET_i2s (distant_neighbor));
447   size = sizeof (struct GNUNET_DV_ReceivedMessage) + 
448     ntohs (message->size);
449   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
450   {    
451     GNUNET_break (0); /* too big */
452     return;
453   }
454   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + size);
455   received_msg = (struct GNUNET_DV_ReceivedMessage *) &pending_message[1];
456   received_msg->header.size = htons (size);
457   received_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DV_RECV);
458   received_msg->distance = htonl (distance);
459   received_msg->sender = *distant_neighbor;
460   memcpy (&received_msg[1], message, ntohs (message->size));
461   GNUNET_CONTAINER_DLL_insert_tail (plugin_pending_head, 
462                                     plugin_pending_tail,
463                                     pending_message);  
464   if (NULL == plugin_transmit_handle)
465     plugin_transmit_handle =
466       GNUNET_SERVER_notify_transmit_ready (client_handle, size,
467                                            GNUNET_TIME_UNIT_FOREVER_REL,
468                                            &transmit_to_plugin, NULL);
469 }
470
471
472 /**
473  * Forward a control message to the plugin.
474  *
475  * @param message the message to send to the plugin
476  * @param distant_neighbor the original sender of the message
477  * @param distnace distance to the original sender of the message
478  */
479 static void
480 send_control_to_plugin (const struct GNUNET_MessageHeader *message)
481 {
482   struct PendingMessage *pending_message;
483   size_t size;
484
485   if (NULL == client_handle)
486   {
487     GNUNET_STATISTICS_update (stats,
488                               "# control messages discarded (no plugin)",
489                               1, GNUNET_NO);
490     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
491                 _("Refusing to queue messages, DV plugin not active.\n"));
492     return;
493   }
494   size = ntohs (message->size);
495   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + size);
496   memcpy (&pending_message[1], message, size);
497   GNUNET_CONTAINER_DLL_insert_tail (plugin_pending_head, 
498                                     plugin_pending_tail,
499                                     pending_message);  
500   if (NULL == plugin_transmit_handle)
501     plugin_transmit_handle =
502       GNUNET_SERVER_notify_transmit_ready (client_handle, size,
503                                            GNUNET_TIME_UNIT_FOREVER_REL,
504                                            &transmit_to_plugin, NULL);
505 }
506
507
508 /**
509  * Give an ACK message to the plugin, we transmitted a message for it.
510  *
511  * @param target peer that received the message
512  * @param uid plugin-chosen UID for the message
513  */
514 static void
515 send_ack_to_plugin (const struct GNUNET_PeerIdentity *target, 
516                     uint32_t uid)
517 {
518   struct GNUNET_DV_AckMessage ack_msg;
519
520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
521               "Delivering ACK for message to peer `%s'\n",
522               GNUNET_i2s (target));
523   ack_msg.header.size = htons (sizeof (ack_msg));
524   ack_msg.header.type = htons (GNUNET_MESSAGE_TYPE_DV_SEND_ACK);
525   ack_msg.uid = htonl (uid);
526   ack_msg.target = *target;
527   send_control_to_plugin (&ack_msg.header);
528 }
529
530
531 /**
532  * Give a CONNECT message to the plugin.
533  *
534  * @param target peer that connected
535  * @param distance distance to the target
536  */
537 static void
538 send_connect_to_plugin (const struct GNUNET_PeerIdentity *target, 
539                         uint32_t distance)
540 {
541   struct GNUNET_DV_ConnectMessage cm;
542
543   if (NULL == client_handle)
544     return;
545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
546               "Delivering CONNECT about peer `%s'\n",
547               GNUNET_i2s (target));
548   cm.header.size = htons (sizeof (cm));
549   cm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_CONNECT);
550   cm.distance = htonl (distance);
551   cm.peer = *target;
552   send_control_to_plugin (&cm.header);
553 }
554
555
556 /**
557  * Give a DISCONNECT message to the plugin.
558  *
559  * @param target peer that disconnected
560  */
561 static void
562 send_disconnect_to_plugin (const struct GNUNET_PeerIdentity *target)
563 {
564   struct GNUNET_DV_DisconnectMessage dm;
565
566   if (NULL == client_handle)
567     return;
568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
569               "Delivering DISCONNECT about peer `%s'\n",
570               GNUNET_i2s (target));
571   dm.header.size = htons (sizeof (dm));
572   dm.header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISCONNECT);
573   dm.reserved = htonl (0);
574   dm.peer = *target;
575   send_control_to_plugin (&dm.header);
576 }
577
578
579 /**
580  * Function called to transfer a message to another peer
581  * via core.
582  *
583  * @param cls closure with the direct neighbor
584  * @param size number of bytes available in buf
585  * @param buf where the callee should write the message
586  * @return number of bytes written to buf
587  */
588 static size_t
589 core_transmit_notify (void *cls, size_t size, void *buf)
590 {
591   struct DirectNeighbor *dn = cls;
592   char *cbuf = buf;
593   struct PendingMessage *pending;
594   size_t off;
595   size_t msize;
596
597   dn->cth = NULL;
598   if (NULL == buf)
599   {
600     /* peer disconnected */
601     return 0;
602   }
603   off = 0;
604   pending = dn->pm_head;
605   off = 0;
606   while ( (NULL != (pending = dn->pm_head)) &&
607           (size >= off + (msize = ntohs (pending->msg->size))))
608   {
609     dn->pm_queue_size--;
610     GNUNET_CONTAINER_DLL_remove (dn->pm_head,
611                                  dn->pm_tail,
612                                  pending);
613     memcpy (&cbuf[off], pending->msg, msize);
614     send_ack_to_plugin (&pending->ultimate_target,
615                         pending->uid);
616     GNUNET_free (pending);
617     off += msize;
618   }
619   if (NULL != dn->pm_head)
620     dn->cth =
621       GNUNET_CORE_notify_transmit_ready (core_api,
622                                          GNUNET_YES /* cork */,
623                                          0 /* priority */,
624                                          GNUNET_TIME_UNIT_FOREVER_REL,
625                                          &dn->peer,
626                                          msize,                                  
627                                          &core_transmit_notify, dn);
628   return off;
629 }
630
631
632 /**
633  * Forward the given payload to the given target.
634  *
635  * @param target where to send the message
636  * @param distance expected (remaining) distance to the target
637  * @param sender original sender of the message
638  * @param payload payload of the message
639  */
640 static void
641 forward_payload (struct DirectNeighbor *target,
642                  uint32_t distance,
643                  const struct GNUNET_PeerIdentity *sender,
644                  const struct GNUNET_MessageHeader *payload)
645 {
646   struct PendingMessage *pm;
647   struct RouteMessage *rm;
648   size_t msize;
649
650   if ( (target->pm_queue_size >= MAX_QUEUE_SIZE) &&
651        (0 != memcmp (sender,
652                      &my_identity,
653                      sizeof (struct GNUNET_PeerIdentity))) )
654     return;
655   msize = sizeof (struct RouteMessage) + ntohs (payload->size);
656   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
657   {
658     GNUNET_break (0);
659     return;
660   }
661   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
662   pm->msg = (const struct GNUNET_MessageHeader *) &pm[1];
663   rm = (struct RouteMessage *) &pm[1];
664   rm->header.size = htons ((uint16_t) msize);
665   rm->header.type = htons (GNUNET_MESSAGE_TYPE_DV_ROUTE);
666   rm->distance = htonl (distance);
667   rm->target = target->peer;
668   rm->sender = *sender;
669   memcpy (&rm[1], payload, ntohs (payload->size));
670   GNUNET_CONTAINER_DLL_insert_tail (target->pm_head,
671                                     target->pm_tail,
672                                     pm);
673   target->pm_queue_size++;
674   if (NULL == target->cth)
675     target->cth = GNUNET_CORE_notify_transmit_ready (core_api,
676                                                      GNUNET_YES /* cork */,
677                                                      0 /* priority */,
678                                                      GNUNET_TIME_UNIT_FOREVER_REL,
679                                                      &target->peer,
680                                                      msize,                                      
681                                                      &core_transmit_notify, target);
682 }
683
684
685 /**
686  * Find a free slot for storing a 'route' in the 'consensi'
687  * set at the given distance.
688  *
689  * @param distance distance to use for the set slot
690  */
691 static unsigned int
692 get_consensus_slot (uint32_t distance)
693 {
694   struct ConsensusSet *cs;
695   unsigned int i;
696
697   cs = &consensi[distance];
698   i = 0;
699   while ( (i < cs->array_length) &&
700           (NULL != cs->targets[i]) ) i++;
701   if (i == cs->array_length)
702     GNUNET_array_grow (cs->targets,
703                        cs->array_length,
704                        cs->array_length * 2 + 2);
705   return i;
706 }
707
708
709 /**
710  * Allocate a slot in the consensus set for a route.
711  *
712  * @param route route to initialize
713  * @param distance which consensus set to use
714  */
715 static void
716 allocate_route (struct Route *route,
717                 uint32_t distance)
718 {
719   unsigned int i;
720
721   i = get_consensus_slot (distance);
722   route->set_offset = i;
723   consensi[distance].targets[i] = route;
724   route->target.distance = htonl (distance);
725 }
726
727
728 /**
729  * Release a slot in the consensus set for a route.
730  *
731  * @param route route to release the slot from
732  */
733 static void
734 release_route (struct Route *route)
735 {
736   consensi[ntohl (route->target.distance)].targets[route->set_offset] = NULL;
737   route->set_offset = UINT_MAX; /* indicate invalid slot */
738 }
739
740
741 /**
742  * Move a route from one consensus set to another.
743  *
744  * @param route route to move
745  * @param new_distance new distance for the route (destination set)
746  */
747 static void
748 move_route (struct Route *route,
749             uint32_t new_distance)
750 {
751   unsigned int i;
752
753   release_route (route);
754   i = get_consensus_slot (new_distance);
755   route->set_offset = i;
756   consensi[new_distance].targets[i] = route;     
757   route->target.distance = htonl (new_distance);
758 }
759
760
761 /**
762  * Start creating a new consensus from scratch.
763  *
764  * @param cls the 'struct DirectNeighbor' of the peer we're building
765  *        a routing consensus with
766  * @param tc scheduler context
767  */    
768 static void
769 start_consensus (void *cls,
770                  const struct GNUNET_SCHEDULER_TaskContext *tc);
771
772
773 /**
774  * Method called whenever a peer connects.
775  *
776  * @param cls closure
777  * @param peer peer identity this notification is about
778  * @param atsi performance data
779  * @param atsi_count number of entries in atsi
780  */
781 static void
782 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
783                      const struct GNUNET_ATS_Information *atsi,
784                      unsigned int atsi_count)
785 {
786   struct DirectNeighbor *neighbor;
787   struct Route *route;
788   uint32_t distance;
789  
790   /* Check for connect to self message */
791   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
792     return;
793   distance = get_atsi_distance (atsi, atsi_count);
794   neighbor = GNUNET_CONTAINER_multihashmap_get (direct_neighbors, 
795                                                 &peer->hashPubKey);
796   if (NULL != neighbor)
797   {
798     GNUNET_break (0);
799     return;
800   }
801   if (DIRECT_NEIGHBOR_COST != distance) 
802     return; /* is a DV-neighbor */
803   neighbor = GNUNET_malloc (sizeof (struct DirectNeighbor));
804   neighbor->peer = *peer;
805   GNUNET_assert (GNUNET_YES ==
806                  GNUNET_CONTAINER_multihashmap_put (direct_neighbors,
807                                                     &peer->hashPubKey,
808                                                     neighbor,
809                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
810   route = GNUNET_CONTAINER_multihashmap_get (all_routes, 
811                                              &peer->hashPubKey);
812   if (NULL != route)  
813   {
814     send_disconnect_to_plugin (peer);
815     release_route (route);
816     GNUNET_free (route);
817   }
818   route->next_hop = neighbor;
819   neighbor->consensus_task = GNUNET_SCHEDULER_add_now (&start_consensus,
820                                                        neighbor);
821 }
822
823
824 /**
825  * Called for each 'target' in a neighbor table to free the associated memory.
826  *
827  * @param cls NULL
828  * @param key key of the value
829  * @param value value to free
830  * @return GNUNET_OK to continue to iterate
831  */
832 static int
833 free_targets (void *cls,
834               const struct GNUNET_HashCode *key,
835               void *value)
836 {
837   GNUNET_free (value);
838   return GNUNET_OK;
839 }
840
841
842 /**
843  * Multihashmap iterator for checking if a given route is
844  * (now) useful to this peer.
845  *
846  * @param cls the direct neighbor for the given route
847  * @param key key value stored under
848  * @param value a 'struct Target' that may or may not be useful; not that
849  *        the distance in 'target' does not include the first hop yet
850  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
851  */
852 static int
853 check_possible_route (void *cls, const struct GNUNET_HashCode * key, void *value)
854 {
855   struct DirectNeighbor *neighbor = cls;
856   struct Target *target = value;
857   struct Route *route;
858   
859   route = GNUNET_CONTAINER_multihashmap_get (all_routes,
860                                            key);
861   if (NULL != route)
862   {
863     if (ntohl (route->target.distance) > ntohl (target->distance) + 1)
864     {
865       /* this 'target' is cheaper than the existing route; switch to alternative route! */
866       move_route (route, ntohl (target->distance) + 1);
867       route->next_hop = neighbor;
868       // FIXME: notify plugin about distance update?
869     }
870     return GNUNET_YES; /* got a route to this target already */
871   }
872   route = GNUNET_malloc (sizeof (struct Route));
873   route->next_hop = neighbor;
874   route->target.distance = htonl (ntohl (target->distance) + 1);
875   route->target.peer = target->peer;
876   allocate_route (route, ntohl (route->target.distance));
877   GNUNET_assert (GNUNET_YES ==
878                  GNUNET_CONTAINER_multihashmap_put (all_routes,
879                                                     &route->target.peer.hashPubKey,
880                                                     route,
881                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
882   send_connect_to_plugin (&route->target.peer, ntohl (target->distance));
883   return GNUNET_YES;
884 }
885
886
887 /**
888  * Multihashmap iterator for finding routes that were previously
889  * "hidden" due to a better route (called after a disconnect event).
890  *
891  * @param cls NULL
892  * @param key peer identity of the given direct neighbor
893  * @param value a 'struct DirectNeighbor' to check for additional routes
894  * @return GNUNET_YES to continue iteration
895  */
896 static int
897 refresh_routes (void *cls, const struct GNUNET_HashCode * key, void *value)
898 {
899   struct DirectNeighbor *neighbor = value;
900
901   if (NULL != neighbor->neighbor_table)
902     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
903                                            &check_possible_route,
904                                            neighbor);
905   return GNUNET_YES;
906 }
907
908
909 /**
910  * Check if a target was removed from the set of the other peer; if so,
911  * if we also used it for our route, we need to remove it from our
912  * 'all_routes' set (and later check if an alternative path now exists).
913  *
914  * @param cls the 'struct DirectNeighbor'
915  * @param key peer identity for the target
916  * @param value a 'struct Target' previously reachable via the given neighbor
917  */
918 static int
919 check_target_removed (void *cls,
920                       const struct GNUNET_HashCode *key,
921                       void *value)
922 {
923   struct DirectNeighbor *neighbor = cls;
924   struct Target *new_target;
925   struct Route *current_route;
926
927   new_target = GNUNET_CONTAINER_multihashmap_get (neighbor->neighbor_table_consensus,
928                                                   key);
929   if (NULL == new_target)
930   {
931     /* target was revoked, check if it was used */
932     current_route = GNUNET_CONTAINER_multihashmap_get (all_routes,
933                                                        key);
934     if ( (NULL == current_route) ||
935          (current_route->next_hop != neighbor) )
936     {
937       /* didn't matter, wasn't used */
938       return GNUNET_OK;
939     }
940     /* remove existing route */
941     GNUNET_assert (GNUNET_YES ==
942                    GNUNET_CONTAINER_multihashmap_remove (all_routes, key, current_route));
943     send_disconnect_to_plugin (&current_route->target.peer);
944     GNUNET_free (current_route);
945     neighbor->target_removed = GNUNET_YES;
946     return GNUNET_OK;
947   }
948   return GNUNET_OK;
949 }
950
951
952 /**
953  * Check if a target was added to the set of the other peer; if it
954  * was added or impoves the existing route, do the needed updates.
955  *
956  * @param cls the 'struct DirectNeighbor'
957  * @param key peer identity for the target
958  * @param value a 'struct Target' now reachable via the given neighbor
959  */
960 static int
961 check_target_added (void *cls,
962                       const struct GNUNET_HashCode *key,
963                       void *value)
964 {
965   struct DirectNeighbor *neighbor = cls;
966   struct Target *target = value;
967   struct Route *current_route;
968
969   /* target was revoked, check if it was used */
970   current_route = GNUNET_CONTAINER_multihashmap_get (all_routes,
971                                                      key);
972   if (NULL != current_route)
973   {
974     /* route exists */
975     if (current_route->next_hop == neighbor)
976     {
977       /* we had the same route before, no change */
978       if (ntohl (target->distance) != ntohl (current_route->target.distance))
979       {
980         current_route->target.distance = target->distance;
981         // FIXME: notify about distance change...
982       }
983       return GNUNET_OK;
984     }
985     if (ntohl (current_route->target.distance) >= ntohl (target->distance))
986     {
987       /* alternative, shorter route exists, ignore */
988       return GNUNET_OK;
989     }
990     /* new route is better than the existing one, take over! */
991     /* NOTE: minor security issue: malicious peers may advertise
992        very short routes to take over longer paths; as we don't
993        check that the shorter routes actually work, a malicious
994        direct neighbor can use this to DoS our long routes */
995     current_route->next_hop = neighbor;
996     current_route->target.distance = target->distance;
997     // FIXME: notify about distance change
998     return GNUNET_OK;
999   }
1000   /* new route */
1001   current_route = GNUNET_malloc (sizeof (struct Route));
1002   current_route->next_hop = neighbor;
1003   current_route->target.peer = target->peer;
1004   current_route->target.distance = htonl (ntohl (target->distance) + 1);
1005   GNUNET_assert (GNUNET_YES ==
1006                  GNUNET_CONTAINER_multihashmap_put (all_routes,
1007                                                     &current_route->target.peer.hashPubKey,
1008                                                     current_route,
1009                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1010   send_connect_to_plugin (&current_route->target.peer,
1011                           ntohl (current_route->target.distance));
1012   return GNUNET_OK;
1013 }
1014
1015
1016
1017 /**
1018  * The consensus has concluded, clean up and schedule the next one.
1019  *
1020  * @param cls the 'struct GNUNET_DirectNeighbor' with which we created the consensus
1021  * @param group FIXME
1022  */
1023 static void
1024 consensus_done_cb (void *cls,
1025                    const struct GNUNET_CONSENSUS_Group *group)
1026 {
1027   struct DirectNeighbor *neighbor = cls;
1028
1029   GNUNET_CONSENSUS_destroy (neighbor->consensus);
1030   neighbor->consensus = NULL;
1031   /* remove targets that disappeared */
1032   neighbor->target_removed = GNUNET_NO;
1033   GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
1034                                          &check_target_removed,
1035                                          neighbor);
1036   if (GNUNET_YES == neighbor->target_removed)
1037   {
1038     /* check if we got an alternative for the removed routes */
1039     GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
1040                                            &refresh_routes,
1041                                            NULL);    
1042   }
1043   /* add targets that appeared (and check for improved routes) */
1044   GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table_consensus,
1045                                          &check_target_added,
1046                                          neighbor);
1047   if (NULL != neighbor->neighbor_table)
1048   {
1049     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
1050                                            &free_targets,
1051                                            NULL);
1052     GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table);
1053     neighbor->neighbor_table = NULL;
1054   }
1055   neighbor->neighbor_table = neighbor->neighbor_table_consensus;
1056   neighbor->neighbor_table_consensus = NULL;
1057   neighbor->consensus_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1058                                                            &start_consensus,
1059                                                            neighbor);
1060 }
1061
1062
1063 /**
1064  * We inserted the last element into the consensus, get ready to
1065  * insert the next element into the consensus or conclude if
1066  * we're done.
1067  *
1068  * @param cls the 'struct DirectNeighbor' of the peer we're building
1069  *        a routing consensus with
1070  * @param success GNUNET_OK if the last element was added successfully,
1071  *                GNUNET_SYSERR if we failed
1072  */
1073 static void
1074 insert_next_element (void *cls,
1075                      int success)
1076 {
1077   struct DirectNeighbor *neighbor = cls;
1078   struct GNUNET_CONSENSUS_Element element;
1079
1080   while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
1081           (consensi[neighbor->consensus_insertion_distance].array_length == neighbor->consensus_insertion_offset) )
1082   {
1083     neighbor->consensus_insertion_offset = 0;
1084     neighbor->consensus_insertion_distance++;
1085     /* skip over NULL entries */
1086     while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
1087             (consensi[neighbor->consensus_insertion_distance].array_length < neighbor->consensus_insertion_offset) &&
1088             (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
1089       neighbor->consensus_insertion_offset++;
1090   }
1091   if (DEFAULT_FISHEYE_DEPTH - 1 == neighbor->consensus_insertion_distance)
1092   {
1093     /* we're done, conclude! */
1094     GNUNET_CONSENSUS_conclude (neighbor->consensus,
1095                                GNUNET_DV_CONSENSUS_FREQUENCY,
1096                                2 /* both peers */,
1097                                &consensus_done_cb,
1098                                neighbor);
1099     return;
1100   }
1101   element.size = sizeof (struct Target);
1102   element.data = &consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset++]->target;
1103
1104   /* skip over NULL entries */
1105   while ( (DEFAULT_FISHEYE_DEPTH - 1 > neighbor->consensus_insertion_distance) &&
1106           (consensi[neighbor->consensus_insertion_distance].array_length < neighbor->consensus_insertion_offset) &&
1107           (NULL == consensi[neighbor->consensus_insertion_distance].targets[neighbor->consensus_insertion_offset]) )
1108     neighbor->consensus_insertion_offset++;  
1109   GNUNET_CONSENSUS_insert (neighbor->consensus,
1110                            &element,
1111                            &insert_next_element,
1112                            neighbor);
1113 }
1114
1115
1116 /**
1117  * We have learned a new route from the other peer.  Add it to the
1118  * route set we're building.
1119  *
1120  * @param cls the 'struct DirectNeighbor' we're building the consensus with
1121  * @param element the new element we have learned
1122  * @return GNUNET_OK if the valid is well-formed and should be added to the consensus,
1123  *         GNUNET_SYSERR if the element should be ignored and not be propagated
1124  */
1125 static int
1126 learn_route_cb (void *cls,
1127                 const struct GNUNET_CONSENSUS_Element *element)
1128 {
1129   struct DirectNeighbor *neighbor = cls;
1130   struct Target *target;
1131
1132   if (sizeof (struct Target) != element->size)
1133   {
1134     GNUNET_break_op (0);
1135     return GNUNET_SYSERR;
1136   }
1137   target = GNUNET_malloc (sizeof (struct Target));
1138   memcpy (target, element->data, sizeof (struct Target));
1139   if (GNUNET_YES !=
1140       GNUNET_CONTAINER_multihashmap_put (neighbor->neighbor_table_consensus,
1141                                          &target->peer.hashPubKey,
1142                                          target,
1143                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1144   {
1145     GNUNET_break_op (0);
1146     GNUNET_free (target);
1147     return GNUNET_SYSERR;
1148   }
1149   return GNUNET_OK;
1150 }
1151
1152
1153 /**
1154  * Start creating a new consensus from scratch.
1155  *
1156  * @param cls the 'struct DirectNeighbor' of the peer we're building
1157  *        a routing consensus with
1158  * @param tc scheduler context
1159  */    
1160 static void
1161 start_consensus (void *cls,
1162                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1163 {
1164   struct DirectNeighbor *neighbor = cls;
1165   struct GNUNET_HashCode session_id;
1166   struct GNUNET_HashCode real_session_id;
1167
1168   neighbor->consensus_task = GNUNET_SCHEDULER_NO_TASK;
1169   neighbor->consensus_insertion_offset = 0;
1170   neighbor->consensus_insertion_distance = 0;
1171   GNUNET_assert (NULL == neighbor->neighbor_table_consensus);
1172   GNUNET_assert (NULL == neighbor->consensus);
1173   neighbor->neighbor_table_consensus = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
1174   /* construct session ID seed as XOR of both peer's identities */
1175   GNUNET_CRYPTO_hash_xor (&my_identity.hashPubKey, 
1176                           &neighbor->peer.hashPubKey, 
1177                           &session_id);
1178   /* make sure session ID is unique across applications by salting it with 'DV' */
1179   GNUNET_CRYPTO_hkdf (&real_session_id, sizeof (real_session_id),
1180                       GCRY_MD_SHA512, GCRY_MD_SHA256,
1181                       "DV-SALT", 2,
1182                       &session_id, sizeof (session_id),
1183                       NULL, 0);
1184   neighbor->consensus = GNUNET_CONSENSUS_create (cfg,
1185                                                  1,
1186                                                  &neighbor->peer,
1187                                                  &real_session_id,
1188                                                  &learn_route_cb,
1189                                                  neighbor);
1190   if (NULL == neighbor->consensus)
1191   {
1192     neighbor->consensus_task = GNUNET_SCHEDULER_add_delayed (GNUNET_DV_CONSENSUS_FREQUENCY,
1193                                                              &start_consensus,
1194                                                              neighbor);
1195     return;
1196   }
1197   insert_next_element (neighbor, GNUNET_OK);
1198 }
1199
1200
1201 /**
1202  * Core handler for DV data messages.  Whatever this message
1203  * contains all we really have to do is rip it out of its
1204  * DV layering and give it to our pal the DV plugin to report
1205  * in with.
1206  *
1207  * @param cls closure
1208  * @param peer peer which sent the message (immediate sender)
1209  * @param message the message
1210  * @param atsi transport ATS information (latency, distance, etc.)
1211  * @param atsi_count number of entries in atsi
1212  * @return GNUNET_OK on success, GNUNET_SYSERR if the other peer violated the protocol
1213  */
1214 static int
1215 handle_dv_route_message (void *cls, const struct GNUNET_PeerIdentity *peer,
1216                          const struct GNUNET_MessageHeader *message,
1217                          const struct GNUNET_ATS_Information *atsi,
1218                          unsigned int atsi_count)
1219 {
1220   const struct RouteMessage *rm;
1221   const struct GNUNET_MessageHeader *payload;
1222   struct Route *route;
1223
1224   if (ntohs (message->size) < sizeof (struct RouteMessage) + sizeof (struct GNUNET_MessageHeader))
1225   {
1226     GNUNET_break_op (0);
1227     return GNUNET_SYSERR;
1228   }
1229   rm = (const struct RouteMessage *) message;
1230   payload = (const struct GNUNET_MessageHeader *) &rm[1];
1231   if (ntohs (message->size) != sizeof (struct RouteMessage) + ntohs (payload->size))
1232   {
1233     GNUNET_break_op (0);
1234     return GNUNET_SYSERR;
1235   }
1236   if (0 == memcmp (&rm->target,
1237                    &my_identity,
1238                    sizeof (struct GNUNET_PeerIdentity)))
1239   {
1240     /* message is for me, check reverse route! */
1241     route = GNUNET_CONTAINER_multihashmap_get (all_routes,
1242                                                &rm->sender.hashPubKey);
1243     if (NULL == route)
1244     {
1245       /* don't have reverse route, drop */
1246       GNUNET_STATISTICS_update (stats,
1247                                 "# message discarded (no reverse route)",
1248                                 1, GNUNET_NO);
1249       return GNUNET_OK;
1250     }
1251     send_data_to_plugin (payload,
1252                          &rm->sender,
1253                          ntohl (route->target.distance));
1254     return GNUNET_OK;
1255   }
1256   route = GNUNET_CONTAINER_multihashmap_get (all_routes,
1257                                              &rm->target.hashPubKey);
1258   if (NULL == route)
1259   {
1260     GNUNET_STATISTICS_update (stats,
1261                               "# messages discarded (no route)",
1262                               1, GNUNET_NO);
1263     return GNUNET_OK;
1264   }
1265   if (ntohl (route->target.distance) > ntohl (rm->distance) + 1)
1266   {
1267     GNUNET_STATISTICS_update (stats,
1268                               "# messages discarded (target too far)",
1269                               1, GNUNET_NO);
1270     return GNUNET_OK;
1271   }
1272   forward_payload (route->next_hop,
1273                    ntohl (route->target.distance),
1274                    &rm->sender,
1275                    payload);
1276   return GNUNET_OK;  
1277 }
1278
1279
1280 /**
1281  * Service server's handler for message send requests (which come
1282  * bubbling up to us through the DV plugin).
1283  *
1284  * @param cls closure
1285  * @param client identification of the client
1286  * @param message the actual message
1287  */
1288 static void
1289 handle_dv_send_message (void *cls, struct GNUNET_SERVER_Client *client,
1290                         const struct GNUNET_MessageHeader *message)
1291 {
1292   struct Route *route;
1293   const struct GNUNET_DV_SendMessage *msg;
1294   const struct GNUNET_MessageHeader *payload;
1295
1296   if (ntohs (message->size) < sizeof (struct GNUNET_DV_SendMessage) + sizeof (struct GNUNET_MessageHeader))
1297   {
1298     GNUNET_break (0);
1299     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1300     return;
1301   }
1302   msg = (const struct GNUNET_DV_SendMessage *) message;
1303   payload = (const struct GNUNET_MessageHeader *) &msg[1];
1304   if (ntohs (message->size) != sizeof (struct GNUNET_DV_SendMessage) + ntohs (payload->size))
1305   {
1306     GNUNET_break (0);
1307     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1308     return;
1309   }
1310   route = GNUNET_CONTAINER_multihashmap_get (all_routes,
1311                                              &msg->target.hashPubKey);
1312   if (NULL == route)
1313   {
1314     /* got disconnected, send ACK anyway? 
1315        FIXME: What we really want is an 'NACK' here... */
1316     GNUNET_STATISTICS_update (stats,
1317                               "# local messages discarded (no route)",
1318                               1, GNUNET_NO);
1319     send_ack_to_plugin (&msg->target, htonl (msg->uid));
1320     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1321     return;
1322   }
1323   // FIXME: flow control (send ACK only once message has left the queue...)
1324   send_ack_to_plugin (&msg->target, htonl (msg->uid));
1325   forward_payload (route->next_hop,
1326                    ntohl (route->target.distance),
1327                    &my_identity,
1328                    payload);
1329   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1330 }
1331
1332
1333 /**
1334  * Multihashmap iterator for freeing routes that go via a particular
1335  * neighbor that disconnected and is thus no longer available.
1336  *
1337  * @param cls the direct neighbor that is now unavailable
1338  * @param key key value stored under
1339  * @param value a 'struct Route' that may or may not go via neighbor
1340  *
1341  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1342  */
1343 static int
1344 cull_routes (void *cls, const struct GNUNET_HashCode * key, void *value)
1345 {
1346   struct DirectNeighbor *neighbor = cls;
1347   struct Route *route = value;
1348
1349   if (route->next_hop != neighbor)
1350     return GNUNET_YES; /* not affected */
1351   GNUNET_assert (GNUNET_YES ==
1352                  GNUNET_CONTAINER_multihashmap_remove (all_routes, key, value));
1353   release_route (route);
1354   send_disconnect_to_plugin (&route->target.peer);
1355   GNUNET_free (route);
1356   return GNUNET_YES;
1357 }
1358
1359
1360 /**
1361  * Cleanup all of the data structures associated with a given neighbor.
1362  *
1363  * @param neighbor neighbor to clean up
1364  */
1365 static void
1366 cleanup_neighbor (struct DirectNeighbor *neighbor)
1367 {
1368   struct PendingMessage *pending;
1369
1370   while (NULL != (pending = neighbor->pm_head))
1371   {
1372     neighbor->pm_queue_size--;
1373     GNUNET_CONTAINER_DLL_remove (neighbor->pm_head,
1374                                  neighbor->pm_tail,
1375                                  pending);    
1376     GNUNET_free (pending);
1377   }
1378   GNUNET_CONTAINER_multihashmap_iterate (all_routes,
1379                                          &cull_routes,
1380                                          neighbor);
1381   if (NULL != neighbor->cth)
1382   {
1383     GNUNET_CORE_notify_transmit_ready_cancel (neighbor->cth);
1384     neighbor->cth = NULL;
1385   }
1386   if (NULL != neighbor->neighbor_table_consensus)
1387   {
1388     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table_consensus,
1389                                            &free_targets,
1390                                            NULL);
1391     GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table_consensus);
1392     neighbor->neighbor_table_consensus = NULL;
1393   }
1394   if (NULL != neighbor->neighbor_table)
1395   {
1396     GNUNET_CONTAINER_multihashmap_iterate (neighbor->neighbor_table,
1397                                            &free_targets,
1398                                            NULL);
1399     GNUNET_CONTAINER_multihashmap_destroy (neighbor->neighbor_table);
1400     neighbor->neighbor_table = NULL;
1401   }
1402   if (GNUNET_SCHEDULER_NO_TASK != neighbor->consensus_task)
1403   {
1404     GNUNET_SCHEDULER_cancel (neighbor->consensus_task);
1405     neighbor->consensus_task = GNUNET_SCHEDULER_NO_TASK;
1406   }
1407   if (NULL != neighbor->consensus)
1408   {
1409     GNUNET_CONSENSUS_destroy (neighbor->consensus);
1410     neighbor->consensus = NULL;
1411   }
1412   GNUNET_assert (GNUNET_YES ==
1413                  GNUNET_CONTAINER_multihashmap_remove (direct_neighbors, 
1414                                                        &neighbor->peer.hashPubKey,
1415                                                        neighbor));
1416   GNUNET_free (neighbor);
1417 }
1418
1419
1420 /**
1421  * Method called whenever a given peer disconnects.
1422  *
1423  * @param cls closure
1424  * @param peer peer identity this notification is about
1425  */
1426 static void
1427 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1428 {
1429   struct DirectNeighbor *neighbor;
1430
1431   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1432               "Received core peer disconnect message for peer `%s'!\n",
1433               GNUNET_i2s (peer));
1434   /* Check for disconnect from self message */
1435   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1436     return;
1437   neighbor =
1438       GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
1439   if (NULL == neighbor)
1440   {
1441     /* must have been a DV-neighbor, ignore */
1442     return;
1443   }
1444   cleanup_neighbor (neighbor);
1445   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
1446                                          &refresh_routes,
1447                                          NULL);
1448 }
1449
1450
1451 /**
1452  * Multihashmap iterator for freeing routes.  Should never be called.
1453  *
1454  * @param cls NULL
1455  * @param key key value stored under
1456  * @param value the route to be freed
1457  *
1458  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1459  */
1460 static int
1461 free_route (void *cls, const struct GNUNET_HashCode * key, void *value)
1462 {
1463   struct Route *route = value;
1464
1465   GNUNET_break (0);
1466   GNUNET_assert (GNUNET_YES ==
1467                  GNUNET_CONTAINER_multihashmap_remove (all_routes, key, value));
1468   release_route (route);
1469   send_disconnect_to_plugin (&route->target.peer);
1470   GNUNET_free (route);
1471   return GNUNET_YES;
1472 }
1473
1474
1475 /**
1476  * Multihashmap iterator for freeing direct neighbors. Should never be called.
1477  *
1478  * @param cls NULL
1479  * @param key key value stored under
1480  * @param value the direct neighbor to be freed
1481  *
1482  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1483  */
1484 static int
1485 free_direct_neighbors (void *cls, const struct GNUNET_HashCode * key, void *value)
1486 {
1487   struct DirectNeighbor *neighbor = value;
1488
1489   GNUNET_break (0);
1490   cleanup_neighbor (neighbor);
1491   return GNUNET_YES;
1492 }
1493
1494
1495 /**
1496  * Task run during shutdown.
1497  *
1498  * @param cls unused
1499  * @param tc unused
1500  */
1501 static void
1502 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1503 {
1504   struct PendingMessage *pending;
1505   unsigned int i;
1506
1507   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
1508                                          &free_direct_neighbors, NULL);
1509   GNUNET_CONTAINER_multihashmap_destroy (direct_neighbors);
1510   GNUNET_CONTAINER_multihashmap_iterate (all_routes,
1511                                          &free_route, NULL);
1512   GNUNET_CONTAINER_multihashmap_destroy (all_routes);
1513   GNUNET_CORE_disconnect (core_api);
1514   core_api = NULL;
1515   GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1516   stats = NULL;
1517   while (NULL != (pending = plugin_pending_head))
1518   {
1519     GNUNET_CONTAINER_DLL_remove (plugin_pending_head,
1520                                  plugin_pending_tail,
1521                                  pending);
1522     GNUNET_free (pending);
1523   }
1524   for (i=0;i<DEFAULT_FISHEYE_DEPTH - 1;i++)
1525     GNUNET_array_grow (consensi[i].targets,
1526                        consensi[i].array_length,
1527                        0);
1528 }
1529
1530
1531 /**
1532  * Handle START-message.  This is the first message sent to us
1533  * by the client (can only be one!).
1534  *
1535  * @param cls closure (always NULL)
1536  * @param client identification of the client
1537  * @param message the actual message
1538  */
1539 static void
1540 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
1541               const struct GNUNET_MessageHeader *message)
1542 {
1543   if (NULL != client_handle)
1544   {
1545     /* forcefully drop old client */
1546     GNUNET_SERVER_client_disconnect (client_handle);
1547     GNUNET_SERVER_client_drop (client_handle);
1548   }
1549   client_handle = client;
1550   GNUNET_SERVER_client_keep (client_handle);
1551   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1552 }
1553
1554
1555 /**
1556  * Called on core init.
1557  *
1558  * @param cls unused
1559  * @param server legacy
1560  * @param identity this peer's identity
1561  */
1562 static void
1563 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1564            const struct GNUNET_PeerIdentity *identity)
1565 {
1566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1567               "I am peer: %s\n",
1568               GNUNET_i2s (identity));
1569   my_identity = *identity;
1570 }
1571
1572
1573 /**
1574  * Process dv requests.
1575  *
1576  * @param cls closure
1577  * @param server the initialized server
1578  * @param c configuration to use
1579  */
1580 static void
1581 run (void *cls, struct GNUNET_SERVER_Handle *server,
1582      const struct GNUNET_CONFIGURATION_Handle *c)
1583 {
1584   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1585     {&handle_dv_route_message, GNUNET_MESSAGE_TYPE_DV_ROUTE, 0},
1586     {NULL, 0, 0}
1587   };
1588   static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
1589     {&handle_start, NULL, 
1590      GNUNET_MESSAGE_TYPE_DV_START, 
1591      sizeof (struct GNUNET_MessageHeader) },
1592     { &handle_dv_send_message, NULL, 
1593       GNUNET_MESSAGE_TYPE_DV_SEND, 
1594       0},
1595     {NULL, NULL, 0, 0}
1596   };
1597
1598   cfg = c;
1599   direct_neighbors = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
1600   all_routes = GNUNET_CONTAINER_multihashmap_create (65536, GNUNET_NO);
1601   core_api = GNUNET_CORE_connect (cfg, NULL,
1602                                   &core_init, 
1603                                   &handle_core_connect,
1604                                   &handle_core_disconnect,
1605                                   NULL, GNUNET_NO, 
1606                                   NULL, GNUNET_NO, 
1607                                   core_handlers);
1608
1609   if (NULL == core_api)
1610     return;
1611   stats = GNUNET_STATISTICS_create ("dv", cfg);
1612   GNUNET_SERVER_add_handlers (server, plugin_handlers);
1613   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1614                                 &shutdown_task, NULL);
1615 }
1616
1617
1618 /**
1619  * The main function for the dv service.
1620  *
1621  * @param argc number of arguments from the command line
1622  * @param argv command line arguments
1623  * @return 0 ok, 1 on error
1624  */
1625 int
1626 main (int argc, char *const *argv)
1627 {
1628   return (GNUNET_OK ==
1629           GNUNET_SERVICE_run (argc, argv, "dv", GNUNET_SERVICE_OPTION_NONE,
1630                               &run, NULL)) ? 0 : 1;
1631 }
1632
1633 /* end of gnunet-service-dv.c */