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