876d056ac6ee4b28a2fa11f71c54fc3ef0f566ea
[oweals/gnunet.git] / src / dv / gnunet-service-dv.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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  */
31 #include "platform.h"
32 #include "gnunet_client_lib.h"
33 #include "gnunet_getopt_lib.h"
34 #include "gnunet_os_lib.h"
35 #include "gnunet_protocols.h"
36 #include "gnunet_service_lib.h"
37 #include "gnunet_core_service.h"
38 #include "gnunet_signal_lib.h"
39 #include "gnunet_util_lib.h"
40 #include "gnunet_hello_lib.h"
41 #include "gnunet_peerinfo_service.h"
42 #include "gnunet_crypto_lib.h"
43 #include "gnunet_statistics_service.h"
44 #include "dv.h"
45
46 /**
47  * For testing mostly, remember only the
48  * shortest path to a distant neighbor.
49  */
50 #define AT_MOST_ONE GNUNET_NO
51
52 #define USE_PEER_ID GNUNET_YES
53
54 /**
55  * How many outstanding messages (unknown sender) will we allow per peer?
56  */
57 #define MAX_OUTSTANDING_MESSAGES 5
58
59 /**
60  * How often do we check about sending out more peer information (if
61  * we are connected to no peers previously).
62  */
63 #define GNUNET_DV_DEFAULT_SEND_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 500000)
64
65 /**
66  * How long do we wait at most between sending out information?
67  */
68 #define GNUNET_DV_MAX_SEND_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 500000)
69
70 /**
71  * How long can we have not heard from a peer and
72  * still have it in our tables?
73  */
74 #define GNUNET_DV_PEER_EXPIRATION_TIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1000))
75
76 /**
77  * Priority for gossip.
78  */
79 #define GNUNET_DV_DHT_GOSSIP_PRIORITY (GNUNET_EXTREME_PRIORITY / 10)
80
81 /**
82  * How often should we check if expiration time has elapsed for
83  * some peer?
84  */
85 #define GNUNET_DV_MAINTAIN_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5))
86
87 /**
88  * How long to allow a message to be delayed?
89  */
90 #define DV_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5))
91
92 /**
93  * Priority to use for DV data messages.
94  */
95 #define DV_PRIORITY 0
96
97 /**
98  * The cost to a direct neighbor.  We used to use 0, but 1 makes more sense.
99  */
100 #define DIRECT_NEIGHBOR_COST 1
101
102 /**
103  * The default number of direct connections to store in DV (max)
104  */
105 #define DEFAULT_DIRECT_CONNECTIONS 50
106
107 /**
108  * The default size of direct + extended peers in DV (max)
109  */
110 #define DEFAULT_DV_SIZE 100
111
112 /**
113  * The default fisheye depth, from how many hops away will
114  * we keep peers?
115  */
116 #define DEFAULT_FISHEYE_DEPTH 4
117
118 /**
119  * Linked list of messages to send to clients.
120  */
121 struct PendingMessage
122 {
123   /**
124    * Pointer to next item in the list
125    */
126   struct PendingMessage *next;
127
128   /**
129    * Pointer to previous item in the list
130    */
131   struct PendingMessage *prev;
132
133   /**
134    * The PeerIdentity to send to
135    */
136   struct GNUNET_PeerIdentity recipient;
137
138   /**
139    * The result of message sending.
140    */
141   struct GNUNET_DV_SendResultMessage *send_result;
142
143   /**
144    * Message importance level.
145    */
146   unsigned int importance;
147
148   /**
149    * Size of message.
150    */
151   unsigned int msg_size;
152
153   /**
154    * How long to wait before sending message.
155    */
156   struct GNUNET_TIME_Relative timeout;
157
158   /**
159    * Actual message to be sent; // avoid allocation
160    */
161   const struct GNUNET_MessageHeader *msg;       // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
162
163 };
164
165 struct FastGossipNeighborList
166 {
167   /**
168    * Next element of DLL
169    */
170   struct FastGossipNeighborList *next;
171
172   /**
173    * Prev element of DLL
174    */
175   struct FastGossipNeighborList *prev;
176
177   /**
178    * The neighbor to gossip about
179    */
180   struct DistantNeighbor *about;
181 };
182
183 /**
184  * Context created whenever a direct peer connects to us,
185  * used to gossip other peers to it.
186  */
187 struct NeighborSendContext
188 {
189   /**
190    * The peer we will gossip to.
191    */
192   struct DirectNeighbor *toNeighbor;
193
194   /**
195    * The task associated with this context.
196    */
197   GNUNET_SCHEDULER_TaskIdentifier task;
198
199   /**
200    * Head of DLL of peers to gossip about
201    * as fast as possible to this peer, for initial
202    * set up.
203    */
204   struct FastGossipNeighborList *fast_gossip_list_head;
205
206   /**
207    * Tail of DLL of peers to gossip about
208    * as fast as possible to this peer, for initial
209    * set up.
210    */
211   struct FastGossipNeighborList *fast_gossip_list_tail;
212
213 };
214
215
216 /**
217  * Struct to hold information for updating existing neighbors
218  */
219 struct NeighborUpdateInfo
220 {
221   /**
222    * Cost
223    */
224   unsigned int cost;
225
226   /**
227    * The existing neighbor
228    */
229   struct DistantNeighbor *neighbor;
230
231   /**
232    * The referrer of the possibly existing peer
233    */
234   struct DirectNeighbor *referrer;
235
236   /**
237    * The time we heard about this peer
238    */
239   struct GNUNET_TIME_Absolute now;
240
241   /**
242    * Peer id this peer uses to refer to neighbor.
243    */
244   unsigned int referrer_peer_id;
245
246 };
247
248 /**
249  * Struct to store a single message received with
250  * an unknown sender.
251  */
252 struct UnknownSenderMessage
253 {
254   /**
255    * Message sender (immediate)
256    */
257   struct GNUNET_PeerIdentity sender;
258
259   /**
260    * The actual message received
261    */
262   struct GNUNET_MessageHeader *message;
263
264   /**
265    * Latency of connection
266    */
267   struct GNUNET_TIME_Relative latency;
268
269   /**
270    * Distance to destination
271    */
272   uint32_t distance;
273
274   /**
275    * Unknown sender id
276    */
277   uint32_t sender_id;
278 };
279
280 /**
281  * Struct where actual neighbor information is stored,
282  * referenced by min_heap and max_heap.  Freeing dealt
283  * with when items removed from hashmap.
284  */
285 struct DirectNeighbor
286 {
287   /**
288    * Identity of neighbor.
289    */
290   struct GNUNET_PeerIdentity identity;
291
292   /**
293    * PublicKey of neighbor.
294    */
295   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
296
297   /**
298    * Head of DLL of nodes that this direct neighbor referred to us.
299    */
300   struct DistantNeighbor *referee_head;
301
302   /**
303    * Tail of DLL of nodes that this direct neighbor referred to us.
304    */
305   struct DistantNeighbor *referee_tail;
306
307   /**
308    * The sending context for gossiping peers to this neighbor.
309    */
310   struct NeighborSendContext *send_context;
311
312   /**
313    * Is this one of the direct neighbors that we are "hiding"
314    * from DV?
315    */
316   int hidden;
317
318   /**
319    * Save messages immediately from this direct neighbor from a
320    * distan peer we don't know on the chance that it will be
321    * gossiped about and we can deliver the message.
322    */
323   struct UnknownSenderMessage pending_messages[MAX_OUTSTANDING_MESSAGES];
324 };
325
326
327 /**
328  * Struct where actual neighbor information is stored,
329  * referenced by min_heap and max_heap.  Freeing dealt
330  * with when items removed from hashmap.
331  */
332 struct DistantNeighbor
333 {
334   /**
335    * We keep distant neighbor's of the same referrer in a DLL.
336    */
337   struct DistantNeighbor *next;
338
339   /**
340    * We keep distant neighbor's of the same referrer in a DLL.
341    */
342   struct DistantNeighbor *prev;
343
344   /**
345    * Node in min heap
346    */
347   struct GNUNET_CONTAINER_HeapNode *min_loc;
348
349   /**
350    * Node in max heap
351    */
352   struct GNUNET_CONTAINER_HeapNode *max_loc;
353
354   /**
355    * Identity of referrer (next hop towards 'neighbor').
356    */
357   struct DirectNeighbor *referrer;
358
359   /**
360    * Identity of neighbor.
361    */
362   struct GNUNET_PeerIdentity identity;
363
364   /**
365    * PublicKey of neighbor.
366    */
367   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey;
368
369   /**
370    * Last time we received routing information from this peer
371    */
372   struct GNUNET_TIME_Absolute last_activity;
373
374   /**
375    * Last time we sent routing information about this peer
376    */
377   struct GNUNET_TIME_Absolute last_gossip;
378
379   /**
380    * Cost to neighbor, used for actual distance vector computations
381    */
382   unsigned int cost;
383
384   /**
385    * Random identifier *we* use for this peer, to be used as shortcut
386    * instead of sending full peer id for each message
387    */
388   unsigned int our_id;
389
390   /**
391    * Random identifier the *referrer* uses for this peer.
392    */
393   unsigned int referrer_id;
394
395   /**
396    * Is this one of the direct neighbors that we are "hiding"
397    * from DV?
398    */
399   int hidden;
400
401 };
402
403 struct PeerIteratorContext
404 {
405   /**
406    * The actual context, to be freed later.
407    */
408   struct GNUNET_PEERINFO_IteratorContext *ic;
409
410   /**
411    * The neighbor about which we are concerned.
412    */
413   struct DirectNeighbor *neighbor;
414
415   /**
416    * The distant neighbor entry for this direct neighbor.
417    */
418   struct DistantNeighbor *distant;
419
420 };
421
422 /**
423  * Context used for creating hello messages when
424  * gossips are received.
425  */
426 struct HelloContext
427 {
428   /**
429    * Identity of distant neighbor.
430    */
431   struct GNUNET_PeerIdentity distant_peer;
432
433   /**
434    * Identity of direct neighbor, via which we send this message.
435    */
436   const struct GNUNET_PeerIdentity *direct_peer;
437
438   /**
439    * How many addresses do we need to add (always starts at 1, then set to 0)
440    */
441   int addresses_to_add;
442
443 };
444
445 struct DV_SendContext
446 {
447   /**
448    * The distant peer (should always match)
449    */
450   struct GNUNET_PeerIdentity *distant_peer;
451
452   /**
453    * The direct peer, we need to verify the referrer of.
454    */
455   struct GNUNET_PeerIdentity *direct_peer;
456
457   /**
458    * The message to be sent
459    */
460   struct GNUNET_MessageHeader *message;
461
462   /**
463    * The pre-built send result message.  Simply needs to be queued
464    * and freed once send has been called!
465    */
466   struct GNUNET_DV_SendResultMessage *send_result;
467
468   /**
469    * The size of the message being sent, may be larger
470    * than message->header.size because it's multiple
471    * messages packed into one!
472    */
473   size_t message_size;
474
475   /**
476    * How important is this message?
477    */
478   unsigned int importance;
479
480   /**
481    * Timeout for this message
482    */
483   struct GNUNET_TIME_Relative timeout;
484
485   /**
486    * Unique ID for DV message
487    */
488   unsigned int uid;
489 };
490
491 struct FindDestinationContext
492 {
493   unsigned int tid;
494   struct DistantNeighbor *dest;
495 };
496
497 struct FindIDContext
498 {
499   unsigned int tid;
500   struct GNUNET_PeerIdentity *dest;
501   const struct GNUNET_PeerIdentity *via;
502 };
503
504 struct DisconnectContext
505 {
506   /**
507    * Distant neighbor to get pid from.
508    */
509   struct DistantNeighbor *distant;
510
511   /**
512    * Direct neighbor that disconnected.
513    */
514   struct DirectNeighbor *direct;
515 };
516
517 struct TokenizedMessageContext
518 {
519   /**
520    * Immediate sender of this message
521    */
522   const struct GNUNET_PeerIdentity *peer;
523
524   /**
525    * Distant sender of the message
526    */
527   struct DistantNeighbor *distant;
528
529   /**
530    * Uid for this set of messages
531    */
532   uint32_t uid;
533 };
534
535 /**
536  * Context for finding the least cost peer to send to.
537  * Transport selection can only go so far.
538  */
539 struct FindLeastCostContext
540 {
541   struct DistantNeighbor *target;
542   unsigned int least_cost;
543 };
544
545 /**
546  * Handle to the core service api.
547  */
548 static struct GNUNET_CORE_Handle *coreAPI;
549
550 /**
551  * Stream tokenizer to handle messages coming in from core.
552  */
553 static struct GNUNET_SERVER_MessageStreamTokenizer *coreMST;
554
555 /**
556  * The identity of our peer.
557  */
558 static struct GNUNET_PeerIdentity my_identity;
559
560 /**
561  * The configuration for this service.
562  */
563 static const struct GNUNET_CONFIGURATION_Handle *cfg;
564
565
566 /**
567  * The client, the DV plugin connected to us.  Hopefully
568  * this client will never change, although if the plugin dies
569  * and returns for some reason it may happen.
570  */
571 static struct GNUNET_SERVER_Client *client_handle;
572
573 /**
574  * Task to run when we shut down, cleaning up all our trash
575  */
576 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
577
578 static size_t default_dv_priority = 0;
579
580 static char *my_short_id;
581
582 /**
583  * Transmit handle to the plugin.
584  */
585 static struct GNUNET_CONNECTION_TransmitHandle *plugin_transmit_handle;
586
587 /**
588  * Head of DLL for client messages
589  */
590 static struct PendingMessage *plugin_pending_head;
591
592 /**
593  * Tail of DLL for client messages
594  */
595 static struct PendingMessage *plugin_pending_tail;
596
597 /**
598  * Handle to the peerinfo service
599  */
600 static struct GNUNET_PEERINFO_Handle *peerinfo_handle;
601
602 /**
603  * Transmit handle to core service.
604  */
605 static struct GNUNET_CORE_TransmitHandle *core_transmit_handle;
606
607 /**
608  * Head of DLL for core messages
609  */
610 static struct PendingMessage *core_pending_head;
611
612 /**
613  * Tail of DLL for core messages
614  */
615 static struct PendingMessage *core_pending_tail;
616
617 /**
618  * Map of PeerIdentifiers to 'struct GNUNET_dv_neighbor*'s for all
619  * directly connected peers.
620  */
621 static struct GNUNET_CONTAINER_MultiHashMap *direct_neighbors;
622
623 /**
624  * Map of PeerIdentifiers to 'struct GNUNET_dv_neighbor*'s for
625  * peers connected via DV (extended neighborhood).  Does ALSO
626  * include any peers that are in 'direct_neighbors'; for those
627  * peers, the cost will be zero and the referrer all zeros.
628  */
629 static struct GNUNET_CONTAINER_MultiHashMap *extended_neighbors;
630
631 /**
632  * We use the min heap (min refers to cost) to prefer
633  * gossipping about peers with small costs.
634  */
635 static struct GNUNET_CONTAINER_Heap *neighbor_min_heap;
636
637 /**
638  * We use the max heap (max refers to cost) for general
639  * iterations over all peers and to remove the most costly
640  * connection if we have too many.
641  */
642 static struct GNUNET_CONTAINER_Heap *neighbor_max_heap;
643
644 /**
645  * Handle for the statistics service.
646  */
647 struct GNUNET_STATISTICS_Handle *stats;
648
649 /**
650  * How far out to keep peers we learn about.
651  */
652 static unsigned long long fisheye_depth;
653
654 /**
655  * How many peers to store at most.
656  */
657 static unsigned long long max_table_size;
658
659 /**
660  * We've been given a target ID based on the random numbers that
661  * we assigned to our DV-neighborhood.  Find the entry for the
662  * respective neighbor.
663  */
664 static int
665 find_destination (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
666                   void *element, GNUNET_CONTAINER_HeapCostType cost)
667 {
668   struct FindDestinationContext *fdc = cls;
669   struct DistantNeighbor *dn = element;
670
671   if (fdc->tid != dn->our_id)
672     return GNUNET_YES;
673   fdc->dest = dn;
674   return GNUNET_NO;
675 }
676
677
678 /**
679  * We've been given a target ID based on the random numbers that
680  * we assigned to our DV-neighborhood.  Find the entry for the
681  * respective neighbor.
682  */
683 static int
684 find_specific_id (void *cls, const GNUNET_HashCode * key, void *value)
685 {
686   struct FindIDContext *fdc = cls;
687   struct DistantNeighbor *dn = value;
688
689   if (memcmp
690       (&dn->referrer->identity, fdc->via,
691        sizeof (struct GNUNET_PeerIdentity)) == 0)
692   {
693     fdc->tid = dn->referrer_id;
694     return GNUNET_NO;
695   }
696   return GNUNET_YES;
697 }
698
699 /**
700  * Find a distant peer whose referrer_id matches what we're
701  * looking for.  For looking up a peer we've gossipped about
702  * but is now disconnected.  Need to do this because we don't
703  * want to remove those that may be accessible via a different
704  * route.
705  */
706 static int
707 find_distant_peer (void *cls, const GNUNET_HashCode * key, void *value)
708 {
709   struct FindDestinationContext *fdc = cls;
710   struct DistantNeighbor *distant = value;
711
712   if (fdc->tid == distant->referrer_id)
713   {
714     fdc->dest = distant;
715     return GNUNET_NO;
716   }
717   return GNUNET_YES;
718 }
719
720 /**
721  * Function called to notify a client about the socket
722  * begin ready to queue more data.  "buf" will be
723  * NULL and "size" zero if the socket was closed for
724  * writing in the meantime.
725  *
726  * @param cls closure
727  * @param size number of bytes available in buf
728  * @param buf where the callee should write the message
729  * @return number of bytes written to buf
730  */
731 size_t
732 transmit_to_plugin (void *cls, size_t size, void *buf)
733 {
734   char *cbuf = buf;
735   struct PendingMessage *reply;
736   size_t off;
737   size_t msize;
738
739   if (buf == NULL)
740   {
741     /* client disconnected */
742 #if DEBUG_DV_MESSAGES
743     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
744                 "%s: %s buffer was NULL (client disconnect?)\n", my_short_id,
745                 "transmit_to_plugin");
746 #endif
747     return 0;
748   }
749   plugin_transmit_handle = NULL;
750   off = 0;
751   while ((NULL != (reply = plugin_pending_head)) &&
752          (size >= off + (msize = ntohs (reply->msg->size))))
753   {
754     GNUNET_CONTAINER_DLL_remove (plugin_pending_head, plugin_pending_tail,
755                                  reply);
756     memcpy (&cbuf[off], reply->msg, msize);
757     GNUNET_free (reply);
758     off += msize;
759   }
760
761   if (plugin_pending_head != NULL)
762     plugin_transmit_handle =
763         GNUNET_SERVER_notify_transmit_ready (client_handle,
764                                              ntohs (plugin_pending_head->
765                                                     msg->size),
766                                              GNUNET_TIME_UNIT_FOREVER_REL,
767                                              &transmit_to_plugin, NULL);
768
769   return off;
770 }
771
772 /**
773  * Send a message to the dv plugin.
774  *
775  * @param sender the direct sender of the message
776  * @param message the message to send to the plugin
777  *        (may be an encapsulated type)
778  * @param message_size the size of the message to be sent
779  * @param distant_neighbor the original sender of the message
780  * @param cost the cost to the original sender of the message
781  */
782 void
783 send_to_plugin (const struct GNUNET_PeerIdentity *sender,
784                 const struct GNUNET_MessageHeader *message, size_t message_size,
785                 struct GNUNET_PeerIdentity *distant_neighbor, size_t cost)
786 {
787   struct GNUNET_DV_MessageReceived *received_msg;
788   struct PendingMessage *pending_message;
789   char *sender_address;
790   size_t sender_address_len;
791   char *packed_msg_start;
792   int size;
793
794 #if DEBUG_DV
795   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
796               "send_to_plugin called with peer %s as sender\n",
797               GNUNET_i2s (distant_neighbor));
798 #endif
799
800   if (memcmp (sender, distant_neighbor, sizeof (struct GNUNET_PeerIdentity)) !=
801       0)
802   {
803     sender_address_len = sizeof (struct GNUNET_PeerIdentity) * 2;
804     sender_address = GNUNET_malloc (sender_address_len);
805     memcpy (sender_address, distant_neighbor,
806             sizeof (struct GNUNET_PeerIdentity));
807     memcpy (&sender_address[sizeof (struct GNUNET_PeerIdentity)], sender,
808             sizeof (struct GNUNET_PeerIdentity));
809   }
810   else
811   {
812     sender_address_len = sizeof (struct GNUNET_PeerIdentity);
813     sender_address = GNUNET_malloc (sender_address_len);
814     memcpy (sender_address, sender, sizeof (struct GNUNET_PeerIdentity));
815   }
816
817   size =
818       sizeof (struct GNUNET_DV_MessageReceived) + sender_address_len +
819       message_size;
820   received_msg = GNUNET_malloc (size);
821   received_msg->header.size = htons (size);
822   received_msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DV_RECEIVE);
823   received_msg->distance = htonl (cost);
824   received_msg->msg_len = htonl (message_size);
825   /* Set the sender in this message to be the original sender! */
826   memcpy (&received_msg->sender, distant_neighbor,
827           sizeof (struct GNUNET_PeerIdentity));
828   /* Copy the intermediate sender to the end of the message, this is how the transport identifies this peer */
829   memcpy (&received_msg[1], sender_address, sender_address_len);
830   GNUNET_free (sender_address);
831   /* Copy the actual message after the sender */
832   packed_msg_start = (char *) &received_msg[1];
833   packed_msg_start = &packed_msg_start[sender_address_len];
834   memcpy (packed_msg_start, message, message_size);
835   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + size);
836   pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
837   memcpy (&pending_message[1], received_msg, size);
838   GNUNET_free (received_msg);
839
840   GNUNET_CONTAINER_DLL_insert_after (plugin_pending_head, plugin_pending_tail,
841                                      plugin_pending_tail, pending_message);
842
843   if (client_handle != NULL)
844   {
845     if (plugin_transmit_handle == NULL)
846     {
847       plugin_transmit_handle =
848           GNUNET_SERVER_notify_transmit_ready (client_handle, size,
849                                                GNUNET_TIME_UNIT_FOREVER_REL,
850                                                &transmit_to_plugin, NULL);
851     }
852   }
853   else
854   {
855     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
856                 "Failed to queue message for plugin, client_handle not yet set (how?)!\n");
857   }
858 }
859
860 /* Declare here so retry_core_send is aware of it */
861 size_t core_transmit_notify (void *cls, size_t size, void *buf);
862
863 /**
864  *  Try to send another message from our core sending list
865  */
866 static void
867 try_core_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
868 {
869   struct PendingMessage *pending;
870
871   pending = core_pending_head;
872
873   if (core_transmit_handle != NULL)
874     return;                     /* Message send already in progress */
875
876   if ((pending != NULL) && (coreAPI != NULL))
877     core_transmit_handle =
878         GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
879                                            pending->importance,
880                                            pending->timeout,
881                                            &pending->recipient,
882                                            pending->msg_size,
883                                            &core_transmit_notify, NULL);
884 }
885
886
887 /**
888  * Function called to notify a client about the socket
889  * being ready to queue more data.  "buf" will be
890  * NULL and "size" zero if the socket was closed for
891  * writing in the meantime.
892  *
893  * @param cls closure (NULL)
894  * @param size number of bytes available in buf
895  * @param buf where the callee should write the message
896  * @return number of bytes written to buf
897  */
898 size_t
899 core_transmit_notify (void *cls, size_t size, void *buf)
900 {
901   char *cbuf = buf;
902   struct PendingMessage *pending;
903   struct PendingMessage *client_reply;
904   size_t off;
905   size_t msize;
906
907   if (buf == NULL)
908   {
909     /* client disconnected */
910 #if DEBUG_DV
911     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s': buffer was NULL\n", "DHT");
912 #endif
913     return 0;
914   }
915
916   core_transmit_handle = NULL;
917   off = 0;
918   pending = core_pending_head;
919   if ((pending != NULL) && (size >= (msize = ntohs (pending->msg->size))))
920   {
921 #if DEBUG_DV
922     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
923                 "`%s' : transmit_notify (core) called with size %d\n",
924                 "dv service", msize);
925 #endif
926     GNUNET_CONTAINER_DLL_remove (core_pending_head, core_pending_tail, pending);
927     if (pending->send_result != NULL)   /* Will only be non-null if a real client asked for this send */
928     {
929       client_reply =
930           GNUNET_malloc (sizeof (struct PendingMessage) +
931                          sizeof (struct GNUNET_DV_SendResultMessage));
932       client_reply->msg = (struct GNUNET_MessageHeader *) &client_reply[1];
933       memcpy (&client_reply[1], pending->send_result,
934               sizeof (struct GNUNET_DV_SendResultMessage));
935       GNUNET_free (pending->send_result);
936
937       GNUNET_CONTAINER_DLL_insert_after (plugin_pending_head,
938                                          plugin_pending_tail,
939                                          plugin_pending_tail, client_reply);
940       if (client_handle != NULL)
941       {
942         if (plugin_transmit_handle == NULL)
943         {
944           plugin_transmit_handle =
945               GNUNET_SERVER_notify_transmit_ready (client_handle,
946                                                    sizeof (struct
947                                                            GNUNET_DV_SendResultMessage),
948                                                    GNUNET_TIME_UNIT_FOREVER_REL,
949                                                    &transmit_to_plugin, NULL);
950         }
951         else
952         {
953           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
954                       "Failed to queue message for plugin, must be one in progress already!!\n");
955         }
956       }
957     }
958     memcpy (&cbuf[off], pending->msg, msize);
959     GNUNET_free (pending);
960     off += msize;
961   }
962   /*reply = core_pending_head; */
963
964   GNUNET_SCHEDULER_add_now (&try_core_send, NULL);
965   /*if (reply != NULL)
966    * core_transmit_handle = GNUNET_CORE_notify_transmit_ready(coreAPI, GNUNET_YES,  reply->importance, reply->timeout, &reply->recipient, reply->msg_size, &core_transmit_notify, NULL); */
967
968   return off;
969 }
970
971
972 /**
973  * Send a DV data message via DV.
974  *
975  * @param sender the original sender of the message
976  * @param recipient the next hop recipient, may be our direct peer, maybe not
977  * @param send_context the send context
978  */
979 static int
980 send_message_via (const struct GNUNET_PeerIdentity *sender,
981                   const struct GNUNET_PeerIdentity *recipient,
982                   struct DV_SendContext *send_context)
983 {
984   p2p_dv_MESSAGE_Data *toSend;
985   unsigned int msg_size;
986   unsigned int recipient_id;
987   unsigned int sender_id;
988   struct DistantNeighbor *source;
989   struct PendingMessage *pending_message;
990   struct FindIDContext find_context;
991
992 #if DEBUG_DV
993   char shortname[5];
994 #endif
995
996   msg_size = send_context->message_size + sizeof (p2p_dv_MESSAGE_Data);
997
998   find_context.dest = send_context->distant_peer;
999   find_context.via = recipient;
1000   find_context.tid = 0;
1001   GNUNET_CONTAINER_multihashmap_get_multiple (extended_neighbors,
1002                                               &send_context->distant_peer->
1003                                               hashPubKey, &find_specific_id,
1004                                               &find_context);
1005
1006   if (find_context.tid == 0)
1007   {
1008     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1009                 "%s: find_specific_id failed to find peer!\n", my_short_id);
1010     /* target unknown to us, drop! */
1011     return GNUNET_SYSERR;
1012   }
1013   recipient_id = find_context.tid;
1014
1015   if (0 == (memcmp (&my_identity, sender, sizeof (struct GNUNET_PeerIdentity))))
1016   {
1017     sender_id = 0;
1018     source =
1019         GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
1020                                            &sender->hashPubKey);
1021     if (source != NULL)
1022       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1023                   "%s: send_message_via found %s, myself in extended peer list???\n",
1024                   my_short_id, GNUNET_i2s (&source->identity));
1025   }
1026   else
1027   {
1028     source =
1029         GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
1030                                            &sender->hashPubKey);
1031     if (source == NULL)
1032     {
1033       /* sender unknown to us, drop! */
1034       return GNUNET_SYSERR;
1035     }
1036     sender_id = source->our_id;
1037   }
1038
1039   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
1040   pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1041   pending_message->send_result = send_context->send_result;
1042   memcpy (&pending_message->recipient, recipient,
1043           sizeof (struct GNUNET_PeerIdentity));
1044   pending_message->msg_size = msg_size;
1045   pending_message->importance = send_context->importance;
1046   pending_message->timeout = send_context->timeout;
1047   toSend = (p2p_dv_MESSAGE_Data *) pending_message->msg;
1048   toSend->header.size = htons (msg_size);
1049   toSend->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DATA);
1050   toSend->sender = htonl (sender_id);
1051   toSend->recipient = htonl (recipient_id);
1052 #if DEBUG_DV_MESSAGES
1053   toSend->uid = send_context->uid;      /* Still sent around in network byte order */
1054 #else
1055   toSend->uid = htonl (0);
1056 #endif
1057
1058   memcpy (&toSend[1], send_context->message, send_context->message_size);
1059
1060 #if DEBUG_DV
1061   memcpy (&shortname, GNUNET_i2s (send_context->distant_peer), 4);
1062   shortname[4] = '\0';
1063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1064               "%s: Notifying core of send to destination `%s' via `%s' size %u\n",
1065               "DV", &shortname, GNUNET_i2s (recipient), msg_size);
1066 #endif
1067
1068   GNUNET_CONTAINER_DLL_insert_after (core_pending_head, core_pending_tail,
1069                                      core_pending_tail, pending_message);
1070
1071   GNUNET_SCHEDULER_add_now (try_core_send, NULL);
1072
1073   return GNUNET_YES;
1074 }
1075
1076 /**
1077  * Given a FindLeastCostContext, and a set
1078  * of peers that match the target, return the cheapest.
1079  *
1080  * @param cls closure, a struct FindLeastCostContext
1081  * @param key the key identifying the target peer
1082  * @param value the target peer
1083  *
1084  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1085  */
1086 static int
1087 find_least_cost_peer (void *cls, const GNUNET_HashCode * key, void *value)
1088 {
1089   struct FindLeastCostContext *find_context = cls;
1090   struct DistantNeighbor *dn = value;
1091
1092   if (dn->cost < find_context->least_cost)
1093   {
1094     find_context->target = dn;
1095   }
1096   if (dn->cost == DIRECT_NEIGHBOR_COST)
1097     return GNUNET_NO;
1098   return GNUNET_YES;
1099 }
1100
1101 /**
1102  * Send a DV data message via DV.
1103  *
1104  * @param recipient the ultimate recipient of this message
1105  * @param sender the original sender of the message
1106  * @param specific_neighbor the specific neighbor to send this message via
1107  * @param message the packed message
1108  * @param message_size size of the message
1109  * @param importance what priority to send this message with
1110  * @param uid the unique identifier of this message (or 0 for none)
1111  * @param timeout how long to possibly delay sending this message
1112  */
1113 static int
1114 send_message (const struct GNUNET_PeerIdentity *recipient,
1115               const struct GNUNET_PeerIdentity *sender,
1116               const struct DistantNeighbor *specific_neighbor,
1117               const struct GNUNET_MessageHeader *message, size_t message_size,
1118               unsigned int importance, unsigned int uid,
1119               struct GNUNET_TIME_Relative timeout)
1120 {
1121   p2p_dv_MESSAGE_Data *toSend;
1122   unsigned int msg_size;
1123   unsigned int cost;
1124   unsigned int recipient_id;
1125   unsigned int sender_id;
1126   struct DistantNeighbor *target;
1127   struct DistantNeighbor *source;
1128   struct PendingMessage *pending_message;
1129   struct FindLeastCostContext find_least_ctx;
1130
1131 #if DEBUG_DV_PEER_NUMBERS
1132   struct GNUNET_CRYPTO_HashAsciiEncoded encPeerFrom;
1133   struct GNUNET_CRYPTO_HashAsciiEncoded encPeerTo;
1134   struct GNUNET_CRYPTO_HashAsciiEncoded encPeerVia;
1135 #endif
1136   msg_size = message_size + sizeof (p2p_dv_MESSAGE_Data);
1137
1138   find_least_ctx.least_cost = -1;
1139   find_least_ctx.target = NULL;
1140   /*
1141    * Need to find the least cost peer, lest the transport selection keep
1142    * picking the same DV route for the same destination which results
1143    * in messages looping forever.  Relatively cheap, we don't iterate
1144    * over all known peers, just those that apply.
1145    */
1146   GNUNET_CONTAINER_multihashmap_get_multiple (extended_neighbors,
1147                                               &recipient->hashPubKey,
1148                                               &find_least_cost_peer,
1149                                               &find_least_ctx);
1150   target = find_least_ctx.target;
1151
1152   if (target == NULL)
1153   {
1154     /* target unknown to us, drop! */
1155     return GNUNET_SYSERR;
1156   }
1157   recipient_id = target->referrer_id;
1158
1159   source =
1160       GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
1161                                          &sender->hashPubKey);
1162   if (source == NULL)
1163   {
1164     if (0 !=
1165         (memcmp (&my_identity, sender, sizeof (struct GNUNET_PeerIdentity))))
1166     {
1167       /* sender unknown to us, drop! */
1168       return GNUNET_SYSERR;
1169     }
1170     sender_id = 0;              /* 0 == us */
1171   }
1172   else
1173   {
1174     /* find out the number that we use when we gossip about
1175      * the sender */
1176     sender_id = source->our_id;
1177   }
1178
1179 #if DEBUG_DV_PEER_NUMBERS
1180   GNUNET_CRYPTO_hash_to_enc (&source->identity.hashPubKey, &encPeerFrom);
1181   GNUNET_CRYPTO_hash_to_enc (&target->referrer->identity.hashPubKey,
1182                              &encPeerVia);
1183   encPeerFrom.encoding[4] = '\0';
1184   encPeerVia.encoding[4] = '\0';
1185 #endif
1186   if ((sender_id != 0) &&
1187       (0 ==
1188        memcmp (&source->identity, &target->referrer->identity,
1189                sizeof (struct GNUNET_PeerIdentity))))
1190   {
1191     return 0;
1192   }
1193
1194   cost = target->cost;
1195   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
1196   pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1197   pending_message->send_result = NULL;
1198   pending_message->importance = importance;
1199   pending_message->timeout = timeout;
1200   memcpy (&pending_message->recipient, &target->referrer->identity,
1201           sizeof (struct GNUNET_PeerIdentity));
1202   pending_message->msg_size = msg_size;
1203   toSend = (p2p_dv_MESSAGE_Data *) pending_message->msg;
1204   toSend->header.size = htons (msg_size);
1205   toSend->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DATA);
1206   toSend->sender = htonl (sender_id);
1207   toSend->recipient = htonl (recipient_id);
1208 #if DEBUG_DV_MESSAGES
1209   toSend->uid = htonl (uid);
1210 #else
1211   toSend->uid = htonl (0);
1212 #endif
1213
1214 #if DEBUG_DV_PEER_NUMBERS
1215   GNUNET_CRYPTO_hash_to_enc (&target->identity.hashPubKey, &encPeerTo);
1216   encPeerTo.encoding[4] = '\0';
1217   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1218               "%s: Sending DATA message. Sender id %u, source %s, destination %s, via %s\n",
1219               GNUNET_i2s (&my_identity), sender_id, &encPeerFrom, &encPeerTo,
1220               &encPeerVia);
1221 #endif
1222   memcpy (&toSend[1], message, message_size);
1223   if ((source != NULL) && (source->pkey == NULL))       /* Test our hypothesis about message failures! */
1224   {
1225     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1226                 "%s: Sending message, but anticipate recipient will not know sender!!!\n\n\n",
1227                 my_short_id);
1228   }
1229   GNUNET_CONTAINER_DLL_insert_after (core_pending_head, core_pending_tail,
1230                                      core_pending_tail, pending_message);
1231 #if DEBUG_DV
1232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1233               "%s: Notifying core of send size %d to destination `%s'\n",
1234               "DV SEND MESSAGE", msg_size, GNUNET_i2s (recipient));
1235 #endif
1236
1237   GNUNET_SCHEDULER_add_now (try_core_send, NULL);
1238   return (int) cost;
1239 }
1240
1241 #if USE_PEER_ID
1242 struct CheckPeerContext
1243 {
1244   /**
1245    * Peer we found
1246    */
1247   struct DistantNeighbor *peer;
1248
1249   /**
1250    * Sender id to search for
1251    */
1252   unsigned int sender_id;
1253 };
1254
1255 /**
1256  * Iterator over hash map entries.
1257  *
1258  * @param cls closure
1259  * @param key current key code
1260  * @param value value in the hash map
1261  * @return GNUNET_YES if we should continue to
1262  *         iterate,
1263  *         GNUNET_NO if not.
1264  */
1265 int
1266 checkPeerID (void *cls, const GNUNET_HashCode * key, void *value)
1267 {
1268   struct CheckPeerContext *ctx = cls;
1269   struct DistantNeighbor *distant = value;
1270
1271   if (memcmp (key, &ctx->sender_id, sizeof (unsigned int)) == 0)
1272   {
1273     ctx->peer = distant;
1274     return GNUNET_NO;
1275   }
1276   return GNUNET_YES;
1277
1278 }
1279 #endif
1280
1281
1282 /**
1283  * Handler for messages parsed out by the tokenizer from
1284  * DV DATA received for this peer.
1285  *
1286  * @param cls NULL
1287  * @param client the TokenizedMessageContext which contains message information
1288  * @param message the actual message
1289  */
1290 void
1291 tokenized_message_handler (void *cls, void *client,
1292                            const struct GNUNET_MessageHeader *message)
1293 {
1294   struct TokenizedMessageContext *ctx = client;
1295
1296   GNUNET_break_op (ntohs (message->type) != GNUNET_MESSAGE_TYPE_DV_GOSSIP);
1297   GNUNET_break_op (ntohs (message->type) != GNUNET_MESSAGE_TYPE_DV_DATA);
1298   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_DV_GOSSIP) &&
1299       (ntohs (message->type) != GNUNET_MESSAGE_TYPE_DV_DATA))
1300   {
1301 #if DEBUG_DV_MESSAGES
1302     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1303                 "%s: Receives %s message for me, uid %u, size %d, type %d cost %u from %s!\n",
1304                 my_short_id, "DV DATA", ctx->uid, ntohs (message->size),
1305                 ntohs (message->type), ctx->distant->cost,
1306                 GNUNET_i2s (&ctx->distant->identity));
1307 #endif
1308     GNUNET_assert (memcmp
1309                    (ctx->peer, &ctx->distant->identity,
1310                     sizeof (struct GNUNET_PeerIdentity)) != 0);
1311     send_to_plugin (ctx->peer, message, ntohs (message->size),
1312                     &ctx->distant->identity, ctx->distant->cost);
1313   }
1314 }
1315
1316 #if DELAY_FORWARDS
1317 struct DelayedMessageContext
1318 {
1319   struct GNUNET_PeerIdentity dest;
1320   struct GNUNET_PeerIdentity sender;
1321   struct GNUNET_MessageHeader *message;
1322   size_t message_size;
1323   uint32_t uid;
1324 };
1325
1326 void
1327 send_message_delayed (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1328 {
1329   struct DelayedMessageContext *msg_ctx = cls;
1330
1331   if (msg_ctx != NULL)
1332   {
1333     send_message (&msg_ctx->dest, &msg_ctx->sender, NULL, msg_ctx->message,
1334                   msg_ctx->message_size, default_dv_priority, msg_ctx->uid,
1335                   GNUNET_TIME_relative_get_forever ());
1336     GNUNET_free (msg_ctx->message);
1337     GNUNET_free (msg_ctx);
1338   }
1339 }
1340 #endif
1341
1342 /**
1343  * Get distance information from 'atsi'.
1344  *
1345  * @param atsi performance data
1346  * @return connected transport distance
1347  */
1348 static uint32_t
1349 get_atsi_distance (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1350 {
1351   while ((ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) &&
1352          (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE))
1353     atsi++;
1354   if (ntohl (atsi->type) == GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR)
1355   {
1356     GNUNET_break (0);
1357     /* FIXME: we do not have distance data? Assume direct neighbor. */
1358     return DIRECT_NEIGHBOR_COST;
1359   }
1360   return ntohl (atsi->value);
1361 }
1362
1363 /**
1364  * Find latency information in 'atsi'.
1365  *
1366  * @param atsi performance data
1367  * @return connection latency
1368  */
1369 static struct GNUNET_TIME_Relative
1370 get_atsi_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1371 {
1372   while ((ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) &&
1373          (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY))
1374     atsi++;
1375   if (ntohl (atsi->type) == GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR)
1376   {
1377     GNUNET_break (0);
1378     /* how can we not have latency data? */
1379     return GNUNET_TIME_UNIT_SECONDS;
1380   }
1381   /* FIXME: Multiply by GNUNET_TIME_UNIT_MILLISECONDS (1) to get as a GNUNET_TIME_Relative */
1382   return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1383                                         ntohl (atsi->value));
1384 }
1385
1386 /**
1387  * Core handler for dv data messages.  Whatever this message
1388  * contains all we really have to do is rip it out of its
1389  * DV layering and give it to our pal the DV plugin to report
1390  * in with.
1391  *
1392  * @param cls closure
1393  * @param peer peer which sent the message (immediate sender)
1394  * @param message the message
1395  * @param atsi transport ATS information (latency, distance, etc.)
1396  */
1397 static int
1398 handle_dv_data_message (void *cls, const struct GNUNET_PeerIdentity *peer,
1399                         const struct GNUNET_MessageHeader *message,
1400                         const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1401 {
1402   const p2p_dv_MESSAGE_Data *incoming = (const p2p_dv_MESSAGE_Data *) message;
1403   const struct GNUNET_MessageHeader *packed_message;
1404   struct DirectNeighbor *dn;
1405   struct DistantNeighbor *pos;
1406   unsigned int sid;             /* Sender id */
1407   unsigned int tid;             /* Target id */
1408   struct GNUNET_PeerIdentity *original_sender;
1409   struct GNUNET_PeerIdentity *destination;
1410   struct FindDestinationContext fdc;
1411   struct TokenizedMessageContext tkm_ctx;
1412   int i;
1413   int found_pos;
1414
1415 #if DELAY_FORWARDS
1416   struct DelayedMessageContext *delayed_context;
1417 #endif
1418 #if USE_PEER_ID
1419   struct CheckPeerContext checkPeerCtx;
1420 #endif
1421 #if DEBUG_DV_MESSAGES
1422   char *sender_id;
1423 #endif
1424   int ret;
1425   size_t packed_message_size;
1426   char *cbuf;
1427   uint32_t distance;            /* Distance information */
1428   struct GNUNET_TIME_Relative latency;  /* Latency information */
1429
1430   packed_message_size =
1431       ntohs (incoming->header.size) - sizeof (p2p_dv_MESSAGE_Data);
1432 #if DEBUG_DV
1433   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1434               "%s: Receives DATA message from %s size %d, packed size %d!\n",
1435               my_short_id, GNUNET_i2s (peer), ntohs (incoming->header.size),
1436               packed_message_size);
1437 #endif
1438
1439   if (ntohs (incoming->header.size) <
1440       sizeof (p2p_dv_MESSAGE_Data) + sizeof (struct GNUNET_MessageHeader))
1441   {
1442 #if DEBUG_DV
1443     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1444                 "`%s': Message sizes don't add up, total size %u, expected at least %u!\n",
1445                 "dv service", ntohs (incoming->header.size),
1446                 sizeof (p2p_dv_MESSAGE_Data) +
1447                 sizeof (struct GNUNET_MessageHeader));
1448 #endif
1449     return GNUNET_SYSERR;
1450   }
1451
1452   /* Iterate over ATS_Information to get distance and latency */
1453   latency = get_atsi_latency (atsi);
1454   distance = get_atsi_distance (atsi);
1455   dn = GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
1456   if (dn == NULL)
1457     return GNUNET_OK;
1458
1459   sid = ntohl (incoming->sender);
1460 #if USE_PEER_ID
1461   if (sid != 0)
1462   {
1463     checkPeerCtx.sender_id = sid;
1464     checkPeerCtx.peer = NULL;
1465     GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors, &checkPeerID,
1466                                            &checkPeerCtx);
1467     pos = checkPeerCtx.peer;
1468   }
1469   else
1470   {
1471     pos =
1472         GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
1473                                            &peer->hashPubKey);
1474   }
1475 #else
1476   pos = dn->referee_head;
1477   while ((NULL != pos) && (pos->referrer_id != sid))
1478     pos = pos->next;
1479 #endif
1480
1481   if (pos == NULL)
1482   {
1483 #if DEBUG_DV_MESSAGES
1484     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1485                 "%s: unknown sender (%u), Message uid %u from %s!\n",
1486                 my_short_id, ntohl (incoming->sender), ntohl (incoming->uid),
1487                 GNUNET_i2s (&dn->identity));
1488     pos = dn->referee_head;
1489     while ((NULL != pos) && (pos->referrer_id != sid))
1490     {
1491       sender_id = strdup (GNUNET_i2s (&pos->identity));
1492       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "I know sender %u %s\n",
1493                   pos->referrer_id, sender_id);
1494       GNUNET_free (sender_id);
1495       pos = pos->next;
1496     }
1497 #endif
1498
1499     found_pos = -1;
1500     for (i = 0; i < MAX_OUTSTANDING_MESSAGES; i++)
1501     {
1502       if (dn->pending_messages[i].sender_id == 0)
1503       {
1504         found_pos = i;
1505         break;
1506       }
1507     }
1508
1509     if (found_pos == -1)
1510     {
1511       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1512                   "%s: Too many unknown senders (%u), ignoring message! Message uid %llu from %s!\n",
1513                   my_short_id, ntohl (incoming->sender), ntohl (incoming->uid),
1514                   GNUNET_i2s (&dn->identity));
1515     }
1516     else
1517     {
1518       dn->pending_messages[found_pos].message =
1519           GNUNET_malloc (ntohs (message->size));
1520       memcpy (dn->pending_messages[found_pos].message, message,
1521               ntohs (message->size));
1522       dn->pending_messages[found_pos].distance = distance;
1523       dn->pending_messages[found_pos].latency = latency;
1524       memcpy (&dn->pending_messages[found_pos].sender, peer,
1525               sizeof (struct GNUNET_PeerIdentity));
1526       dn->pending_messages[found_pos].sender_id = sid;
1527     }
1528     /* unknown sender */
1529     return GNUNET_OK;
1530   }
1531   original_sender = &pos->identity;
1532   tid = ntohl (incoming->recipient);
1533   if (tid == 0)
1534   {
1535     /* 0 == us */
1536     cbuf = (char *) &incoming[1];
1537
1538     tkm_ctx.peer = peer;
1539     tkm_ctx.distant = pos;
1540     tkm_ctx.uid = ntohl (incoming->uid);
1541     if (GNUNET_OK !=
1542         GNUNET_SERVER_mst_receive (coreMST, &tkm_ctx, cbuf, packed_message_size,
1543                                    GNUNET_NO, GNUNET_NO))
1544     {
1545       GNUNET_break_op (0);
1546       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1547                   "%s: %s Received corrupt data, discarding!", my_short_id,
1548                   "DV SERVICE");
1549     }
1550     return GNUNET_OK;
1551   }
1552   else
1553   {
1554     packed_message = (struct GNUNET_MessageHeader *) &incoming[1];
1555   }
1556
1557   /* FIXME: this is the *only* per-request operation we have in DV
1558    * that is O(n) in relation to the number of connected peers; a
1559    * hash-table lookup could easily solve this (minor performance
1560    * issue) */
1561   fdc.tid = tid;
1562   fdc.dest = NULL;
1563   GNUNET_CONTAINER_heap_iterate (neighbor_max_heap, &find_destination, &fdc);
1564
1565 #if DEBUG_DV
1566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1567               "%s: Receives %s message for someone else!\n", "dv", "DV DATA");
1568 #endif
1569
1570   if (fdc.dest == NULL)
1571   {
1572 #if DEBUG_DV_MESSAGES
1573     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1574                 "%s: Receives %s message uid %u for someone we don't know (id %u)!\n",
1575                 my_short_id, "DV DATA", ntohl (incoming->uid), tid);
1576 #endif
1577     return GNUNET_OK;
1578   }
1579   destination = &fdc.dest->identity;
1580
1581   if (0 == memcmp (destination, peer, sizeof (struct GNUNET_PeerIdentity)))
1582   {
1583     /* FIXME: create stat: routing loop-discard! */
1584
1585 #if DEBUG_DV_MESSAGES
1586     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1587                 "%s: DROPPING MESSAGE uid %u type %d, routing loop! Message immediately from %s!\n",
1588                 my_short_id, ntohl (incoming->uid),
1589                 ntohs (packed_message->type), GNUNET_i2s (&dn->identity));
1590 #endif
1591     return GNUNET_OK;
1592   }
1593
1594   /* At this point we have a message, and we need to forward it on to the
1595    * next DV hop.
1596    */
1597 #if DEBUG_DV_MESSAGES
1598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1599               "%s: FORWARD %s message for %s, uid %u, size %d type %d, cost %u!\n",
1600               my_short_id, "DV DATA", GNUNET_i2s (destination),
1601               ntohl (incoming->uid), ntohs (packed_message->size),
1602               ntohs (packed_message->type), pos->cost);
1603 #endif
1604
1605 #if DELAY_FORWARDS
1606   if (GNUNET_TIME_absolute_get_duration (pos->last_gossip).abs_value <
1607       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2).abs_value)
1608   {
1609     delayed_context = GNUNET_malloc (sizeof (struct DelayedMessageContext));
1610     memcpy (&delayed_context->dest, destination,
1611             sizeof (struct GNUNET_PeerIdentity));
1612     memcpy (&delayed_context->sender, original_sender,
1613             sizeof (struct GNUNET_PeerIdentity));
1614     delayed_context->message = GNUNET_malloc (packed_message_size);
1615     memcpy (delayed_context->message, packed_message, packed_message_size);
1616     delayed_context->message_size = packed_message_size;
1617     delayed_context->uid = ntohl (incoming->uid);
1618     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1619                                   (GNUNET_TIME_UNIT_MILLISECONDS, 2500),
1620                                   &send_message_delayed, delayed_context);
1621     return GNUNET_OK;
1622   }
1623   else
1624 #endif
1625   {
1626     ret =
1627         send_message (destination, original_sender, NULL, packed_message,
1628                       packed_message_size, default_dv_priority,
1629                       ntohl (incoming->uid),
1630                       GNUNET_TIME_relative_get_forever ());
1631   }
1632   if (ret != GNUNET_SYSERR)
1633     return GNUNET_OK;
1634   else
1635   {
1636 #if DEBUG_MESSAGE_DROP
1637     char *direct_id = GNUNET_strdup (GNUNET_i2s (&dn->identity));
1638
1639     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1640                 "%s: DROPPING MESSAGE type %d, forwarding failed! Message immediately from %s!\n",
1641                 GNUNET_i2s (&my_identity),
1642                 ntohs (((struct GNUNET_MessageHeader *) &incoming[1])->type),
1643                 direct_id);
1644     GNUNET_free (direct_id);
1645 #endif
1646     return GNUNET_SYSERR;
1647   }
1648 }
1649
1650 #if DEBUG_DV
1651 /**
1652  * Iterator over hash map entries.
1653  *
1654  * @param cls closure (NULL)
1655  * @param key current key code
1656  * @param value value in the hash map (DistantNeighbor)
1657  * @return GNUNET_YES if we should continue to
1658  *         iterate,
1659  *         GNUNET_NO if not.
1660  */
1661 int
1662 print_neighbors (void *cls, const GNUNET_HashCode * key, void *abs_value)
1663 {
1664   struct DistantNeighbor *distant_neighbor = abs_value;
1665   char my_shortname[5];
1666   char referrer_shortname[5];
1667
1668   memcpy (&my_shortname, GNUNET_i2s (&my_identity), 4);
1669   my_shortname[4] = '\0';
1670   memcpy (&referrer_shortname,
1671           GNUNET_i2s (&distant_neighbor->referrer->identity), 4);
1672   referrer_shortname[4] = '\0';
1673
1674   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1675               "`%s' %s: Peer `%s', distance %d, referrer `%s' pkey: %s\n",
1676               &my_shortname, "DV", GNUNET_i2s (&distant_neighbor->identity),
1677               distant_neighbor->cost, &referrer_shortname,
1678               distant_neighbor->pkey == NULL ? "no" : "yes");
1679   return GNUNET_YES;
1680 }
1681 #endif
1682
1683 /**
1684  *  Scheduled task which gossips about known direct peers to other connected
1685  *  peers.  Will run until called with reason shutdown.
1686  */
1687 static void
1688 neighbor_send_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1689 {
1690   struct NeighborSendContext *send_context = cls;
1691
1692 #if DEBUG_DV_GOSSIP_SEND
1693   char *encPeerAbout;
1694   char *encPeerTo;
1695 #endif
1696   struct DistantNeighbor *about;
1697   struct DirectNeighbor *to;
1698   struct FastGossipNeighborList *about_list;
1699
1700   p2p_dv_MESSAGE_NeighborInfo *message;
1701   struct PendingMessage *pending_message;
1702
1703   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1704   {
1705 #if DEBUG_DV_GOSSIP
1706     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1707                 "%s: Called with reason shutdown, shutting down!\n",
1708                 GNUNET_i2s (&my_identity));
1709 #endif
1710     return;
1711   }
1712
1713   if (send_context->fast_gossip_list_head != NULL)
1714   {
1715     about_list = send_context->fast_gossip_list_head;
1716     about = about_list->about;
1717     GNUNET_CONTAINER_DLL_remove (send_context->fast_gossip_list_head,
1718                                  send_context->fast_gossip_list_tail,
1719                                  about_list);
1720     GNUNET_free (about_list);
1721   }
1722   else
1723   {
1724     /* FIXME: this may become a problem, because the heap walk has only one internal "walker".  This means
1725      * that if two neighbor_send_tasks are operating in lockstep (which is quite possible, given default
1726      * values for all connected peers) there may be a serious bias as to which peers get gossiped about!
1727      * Probably the *best* way to fix would be to have an opaque pointer to the walk position passed as
1728      * part of the walk_get_next call.  Then the heap would have to keep a list of walks, or reset the walk
1729      * whenever a modification has been detected.  Yuck either way.  Perhaps we could iterate over the heap
1730      * once to get a list of peers to gossip about and gossip them over time... But then if one goes away
1731      * in the mean time that becomes nasty.  For now we'll just assume that the walking is done
1732      * asynchronously enough to avoid major problems (-;
1733      *
1734      * NOTE: probably fixed once we decided send rate based on allowed bandwidth.
1735      */
1736     about = GNUNET_CONTAINER_heap_walk_get_next (neighbor_min_heap);
1737   }
1738   to = send_context->toNeighbor;
1739
1740   if ((about != NULL) && (to != about->referrer /* split horizon */ ) &&
1741 #if SUPPORT_HIDING
1742       (about->hidden == GNUNET_NO) &&
1743 #endif
1744       (to != NULL) &&
1745       (0 !=
1746        memcmp (&about->identity, &to->identity,
1747                sizeof (struct GNUNET_PeerIdentity))) && (about->pkey != NULL))
1748   {
1749 #if DEBUG_DV_GOSSIP_SEND
1750     encPeerAbout = GNUNET_strdup (GNUNET_i2s (&about->identity));
1751     encPeerTo = GNUNET_strdup (GNUNET_i2s (&to->identity));
1752     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1753                 "%s: Sending info about peer %s id %u to directly connected peer %s\n",
1754                 GNUNET_i2s (&my_identity), encPeerAbout, about->our_id,
1755                 encPeerTo);
1756     GNUNET_free (encPeerAbout);
1757     GNUNET_free (encPeerTo);
1758 #endif
1759     about->last_gossip = GNUNET_TIME_absolute_get ();
1760     pending_message =
1761         GNUNET_malloc (sizeof (struct PendingMessage) +
1762                        sizeof (p2p_dv_MESSAGE_NeighborInfo));
1763     pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1764     pending_message->importance = default_dv_priority;
1765     pending_message->timeout = GNUNET_TIME_relative_get_forever ();
1766     memcpy (&pending_message->recipient, &to->identity,
1767             sizeof (struct GNUNET_PeerIdentity));
1768     pending_message->msg_size = sizeof (p2p_dv_MESSAGE_NeighborInfo);
1769     message = (p2p_dv_MESSAGE_NeighborInfo *) pending_message->msg;
1770     message->header.size = htons (sizeof (p2p_dv_MESSAGE_NeighborInfo));
1771     message->header.type = htons (GNUNET_MESSAGE_TYPE_DV_GOSSIP);
1772     message->cost = htonl (about->cost);
1773     message->neighbor_id = htonl (about->our_id);
1774
1775     memcpy (&message->pkey, about->pkey,
1776             sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1777     memcpy (&message->neighbor, &about->identity,
1778             sizeof (struct GNUNET_PeerIdentity));
1779
1780     GNUNET_CONTAINER_DLL_insert_after (core_pending_head, core_pending_tail,
1781                                        core_pending_tail, pending_message);
1782
1783     GNUNET_SCHEDULER_add_now (try_core_send, NULL);
1784     /*if (core_transmit_handle == NULL)
1785      * core_transmit_handle = GNUNET_CORE_notify_transmit_ready(coreAPI, GNUNET_YES,  default_dv_priority, GNUNET_TIME_relative_get_forever(), &to->identity, sizeof(p2p_dv_MESSAGE_NeighborInfo), &core_transmit_notify, NULL); */
1786
1787   }
1788
1789   if (send_context->fast_gossip_list_head != NULL)      /* If there are other peers in the fast list, schedule right away */
1790   {
1791 #if DEBUG_DV_PEER_NUMBERS
1792     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1793                 "DV SERVICE: still in fast send mode\n");
1794 #endif
1795     send_context->task =
1796         GNUNET_SCHEDULER_add_now (&neighbor_send_task, send_context);
1797   }
1798   else
1799   {
1800 #if DEBUG_DV_PEER_NUMBERS
1801     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1802                 "DV SERVICE: entering slow send mode\n");
1803 #endif
1804     send_context->task =
1805         GNUNET_SCHEDULER_add_delayed (GNUNET_DV_DEFAULT_SEND_INTERVAL,
1806                                       &neighbor_send_task, send_context);
1807   }
1808
1809   return;
1810 }
1811
1812
1813 /**
1814  * Handle START-message.  This is the first message sent to us
1815  * by the client (can only be one!).
1816  *
1817  * @param cls closure (always NULL)
1818  * @param client identification of the client
1819  * @param message the actual message
1820  */
1821 static void
1822 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
1823               const struct GNUNET_MessageHeader *message)
1824 {
1825
1826 #if DEBUG_DV
1827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' request from client\n",
1828               "START");
1829 #endif
1830
1831   client_handle = client;
1832
1833   GNUNET_SERVER_client_keep (client_handle);
1834   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1835 }
1836
1837 #if UNSIMPLER
1838 /**
1839  * Iterate over hash map entries for a distant neighbor,
1840  * if direct neighbor matches context call send message
1841  *
1842  * @param cls closure, a DV_SendContext
1843  * @param key current key code
1844  * @param value value in the hash map
1845  * @return GNUNET_YES if we should continue to
1846  *         iterate,
1847  *         GNUNET_NO if not.
1848  */
1849 int
1850 send_iterator (void *cls, const GNUNET_HashCode * key, void *abs_value)
1851 {
1852   struct DV_SendContext *send_context = cls;
1853   struct DistantNeighbor *distant_neighbor = abs_value;
1854
1855   if (memcmp (distant_neighbor->referrer, send_context->direct_peer, sizeof (struct GNUNET_PeerIdentity)) == 0) /* They match, send and free */
1856   {
1857     send_message_via (&my_identity, distant_neighbor, send_context);
1858     return GNUNET_NO;
1859   }
1860   return GNUNET_YES;
1861 }
1862 #endif
1863
1864 /**
1865  * Service server's handler for message send requests (which come
1866  * bubbling up to us through the DV plugin).
1867  *
1868  * @param cls closure
1869  * @param client identification of the client
1870  * @param message the actual message
1871  */
1872 void
1873 handle_dv_send_message (void *cls, struct GNUNET_SERVER_Client *client,
1874                         const struct GNUNET_MessageHeader *message)
1875 {
1876   struct GNUNET_DV_SendMessage *send_msg;
1877   struct GNUNET_DV_SendResultMessage *send_result_msg;
1878   struct PendingMessage *pending_message;
1879   size_t address_len;
1880   size_t message_size;
1881   struct GNUNET_PeerIdentity *destination;
1882   struct GNUNET_PeerIdentity *direct;
1883   struct GNUNET_MessageHeader *message_buf;
1884   char *temp_pos;
1885   int offset;
1886   static struct GNUNET_CRYPTO_HashAsciiEncoded dest_hash;
1887   struct DV_SendContext *send_context;
1888
1889 #if DEBUG_DV_MESSAGES
1890   char *cbuf;
1891   struct GNUNET_MessageHeader *packed_message;
1892 #endif
1893
1894   if (client_handle == NULL)
1895   {
1896     client_handle = client;
1897     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1898                 "%s: Setting initial client handle, never received `%s' message?\n",
1899                 "dv", "START");
1900   }
1901   else if (client_handle != client)
1902   {
1903     client_handle = client;
1904     /* What should we do in this case, assert fail or just log the warning? */
1905 #if DEBUG_DV
1906     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1907                 "%s: Setting client handle (was a different client!)!\n", "dv");
1908 #endif
1909   }
1910
1911   GNUNET_assert (ntohs (message->size) > sizeof (struct GNUNET_DV_SendMessage));
1912   send_msg = (struct GNUNET_DV_SendMessage *) message;
1913
1914   address_len = ntohl (send_msg->addrlen);
1915   GNUNET_assert (address_len == sizeof (struct GNUNET_PeerIdentity) * 2);
1916   message_size =
1917       ntohs (message->size) - sizeof (struct GNUNET_DV_SendMessage) -
1918       address_len;
1919   destination = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
1920   direct = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
1921   message_buf = GNUNET_malloc (message_size);
1922
1923   temp_pos = (char *) &send_msg[1];     /* Set pointer to end of message */
1924   offset = 0;                   /* Offset starts at zero */
1925
1926   memcpy (destination, &temp_pos[offset], sizeof (struct GNUNET_PeerIdentity));
1927   offset += sizeof (struct GNUNET_PeerIdentity);
1928
1929   memcpy (direct, &temp_pos[offset], sizeof (struct GNUNET_PeerIdentity));
1930   offset += sizeof (struct GNUNET_PeerIdentity);
1931
1932
1933   memcpy (message_buf, &temp_pos[offset], message_size);
1934   if (memcmp
1935       (&send_msg->target, destination,
1936        sizeof (struct GNUNET_PeerIdentity)) != 0)
1937   {
1938     GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash);   /* GNUNET_i2s won't properly work, need to hash one ourselves */
1939     dest_hash.encoding[4] = '\0';
1940     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1941                 "%s: asked to send message to `%s', but address is for `%s'!",
1942                 "DV SERVICE", GNUNET_i2s (&send_msg->target),
1943                 (const char *) &dest_hash.encoding);
1944   }
1945
1946 #if DEBUG_DV_MESSAGES
1947   cbuf = (char *) message_buf;
1948   offset = 0;
1949   while (offset < message_size)
1950   {
1951     packed_message = (struct GNUNET_MessageHeader *) &cbuf[offset];
1952     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1953                 "%s: DV PLUGIN SEND uid %u type %d to %s\n", my_short_id,
1954                 ntohl (send_msg->uid), ntohs (packed_message->type),
1955                 GNUNET_i2s (destination));
1956     offset += ntohs (packed_message->size);
1957   }
1958   /*GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s: DV PLUGIN SEND uid %u type %d to %s\n", my_short_id, ntohl(send_msg->uid), ntohs(message_buf->type), GNUNET_i2s(destination)); */
1959 #endif
1960   GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash);     /* GNUNET_i2s won't properly work, need to hash one ourselves */
1961   dest_hash.encoding[4] = '\0';
1962   send_context = GNUNET_malloc (sizeof (struct DV_SendContext));
1963
1964   send_result_msg = GNUNET_malloc (sizeof (struct GNUNET_DV_SendResultMessage));
1965   send_result_msg->header.size =
1966       htons (sizeof (struct GNUNET_DV_SendResultMessage));
1967   send_result_msg->header.type =
1968       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND_RESULT);
1969   send_result_msg->uid = send_msg->uid; /* No need to ntohl->htonl this */
1970
1971   send_context->importance = ntohl (send_msg->priority);
1972   send_context->timeout = send_msg->timeout;
1973   send_context->direct_peer = direct;
1974   send_context->distant_peer = destination;
1975   send_context->message = message_buf;
1976   send_context->message_size = message_size;
1977   send_context->send_result = send_result_msg;
1978 #if DEBUG_DV_MESSAGES
1979   send_context->uid = send_msg->uid;
1980 #endif
1981
1982   if (send_message_via (&my_identity, direct, send_context) != GNUNET_YES)
1983   {
1984     send_result_msg->result = htons (1);
1985     pending_message =
1986         GNUNET_malloc (sizeof (struct PendingMessage) +
1987                        sizeof (struct GNUNET_DV_SendResultMessage));
1988     pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1989     memcpy (&pending_message[1], send_result_msg,
1990             sizeof (struct GNUNET_DV_SendResultMessage));
1991     GNUNET_free (send_result_msg);
1992
1993     GNUNET_CONTAINER_DLL_insert_after (plugin_pending_head, plugin_pending_tail,
1994                                        plugin_pending_tail, pending_message);
1995
1996     if (client_handle != NULL)
1997     {
1998       if (plugin_transmit_handle == NULL)
1999       {
2000         plugin_transmit_handle =
2001             GNUNET_SERVER_notify_transmit_ready (client_handle,
2002                                                  sizeof (struct
2003                                                          GNUNET_DV_SendResultMessage),
2004                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2005                                                  &transmit_to_plugin, NULL);
2006       }
2007       else
2008       {
2009         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2010                     "Failed to queue message for plugin, must be one in progress already!!\n");
2011       }
2012     }
2013     GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash);   /* GNUNET_i2s won't properly work, need to hash one ourselves */
2014     dest_hash.encoding[4] = '\0';
2015     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2016                 "%s DV SEND failed to send message to destination `%s' via `%s'\n",
2017                 my_short_id, (const char *) &dest_hash.encoding,
2018                 GNUNET_i2s (direct));
2019   }
2020
2021   /* In bizarro world GNUNET_SYSERR indicates that we succeeded */
2022 #if UNSIMPLER
2023   if (GNUNET_SYSERR !=
2024       GNUNET_CONTAINER_multihashmap_get_multiple (extended_neighbors,
2025                                                   &destination->hashPubKey,
2026                                                   &send_iterator, send_context))
2027   {
2028     send_result_msg->result = htons (1);
2029     pending_message =
2030         GNUNET_malloc (sizeof (struct PendingMessage) +
2031                        sizeof (struct GNUNET_DV_SendResultMessage));
2032     pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
2033     memcpy (&pending_message[1], send_result_msg,
2034             sizeof (struct GNUNET_DV_SendResultMessage));
2035     GNUNET_free (send_result_msg);
2036
2037     GNUNET_CONTAINER_DLL_insert_after (plugin_pending_head, plugin_pending_tail,
2038                                        plugin_pending_tail, pending_message);
2039
2040     if (client_handle != NULL)
2041     {
2042       if (plugin_transmit_handle == NULL)
2043       {
2044         plugin_transmit_handle =
2045             GNUNET_SERVER_notify_transmit_ready (client_handle,
2046                                                  sizeof (struct
2047                                                          GNUNET_DV_SendResultMessage),
2048                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2049                                                  &transmit_to_plugin, NULL);
2050       }
2051       else
2052       {
2053         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054                     "Failed to queue message for plugin, must be one in progress already!!\n");
2055       }
2056     }
2057     GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash);   /* GNUNET_i2s won't properly work, need to hash one ourselves */
2058     dest_hash.encoding[4] = '\0';
2059     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2060                 "%s DV SEND failed to send message to destination `%s' via `%s'\n",
2061                 my_short_id, (const char *) &dest_hash.encoding,
2062                 GNUNET_i2s (direct));
2063   }
2064 #endif
2065   GNUNET_free (message_buf);
2066   GNUNET_free (send_context);
2067   GNUNET_free (direct);
2068   GNUNET_free (destination);
2069
2070   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2071 }
2072
2073 /** Forward declarations **/
2074 static int handle_dv_gossip_message (void *cls,
2075                                      const struct GNUNET_PeerIdentity *peer,
2076                                      const struct GNUNET_MessageHeader *message,
2077                                      const struct
2078                                      GNUNET_TRANSPORT_ATS_Information *atsi);
2079
2080 static int handle_dv_disconnect_message (void *cls,
2081                                          const struct GNUNET_PeerIdentity *peer,
2082                                          const struct GNUNET_MessageHeader
2083                                          *message,
2084                                          const struct
2085                                          GNUNET_TRANSPORT_ATS_Information
2086                                          *atsi);
2087 /** End forward declarations **/
2088
2089
2090 /**
2091  * List of handlers for the messages understood by this
2092  * service.
2093  *
2094  * Hmm... will we need to register some handlers with core and
2095  * some handlers with our server here?  Because core should be
2096  * getting the incoming DV messages (from whichever lower level
2097  * transport) and then our server should be getting messages
2098  * from the dv_plugin, right?
2099  */
2100 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2101   {&handle_dv_data_message, GNUNET_MESSAGE_TYPE_DV_DATA, 0},
2102   {&handle_dv_gossip_message, GNUNET_MESSAGE_TYPE_DV_GOSSIP, 0},
2103   {&handle_dv_disconnect_message, GNUNET_MESSAGE_TYPE_DV_DISCONNECT, 0},
2104   {NULL, 0, 0}
2105 };
2106
2107 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
2108   {&handle_dv_send_message, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND, 0},
2109   {&handle_start, NULL, GNUNET_MESSAGE_TYPE_DV_START, 0},
2110   {NULL, NULL, 0, 0}
2111 };
2112
2113 /**
2114  * Free a DistantNeighbor node, including removing it
2115  * from the referer's list.
2116  */
2117 static void
2118 distant_neighbor_free (struct DistantNeighbor *referee)
2119 {
2120   struct DirectNeighbor *referrer;
2121
2122   referrer = referee->referrer;
2123   if (referrer != NULL)
2124   {
2125     GNUNET_CONTAINER_DLL_remove (referrer->referee_head, referrer->referee_tail,
2126                                  referee);
2127   }
2128   GNUNET_CONTAINER_heap_remove_node (referee->max_loc);
2129   GNUNET_CONTAINER_heap_remove_node (referee->min_loc);
2130   GNUNET_CONTAINER_multihashmap_remove_all (extended_neighbors,
2131                                             &referee->identity.hashPubKey);
2132   GNUNET_free_non_null (referee->pkey);
2133   GNUNET_free (referee);
2134 }
2135
2136 /**
2137  * Free a DirectNeighbor node, including removing it
2138  * from the referer's list.
2139  */
2140 static void
2141 direct_neighbor_free (struct DirectNeighbor *direct)
2142 {
2143   struct NeighborSendContext *send_context;
2144   struct FastGossipNeighborList *about_list;
2145   struct FastGossipNeighborList *prev_about;
2146
2147   send_context = direct->send_context;
2148
2149   if (send_context->task != GNUNET_SCHEDULER_NO_TASK)
2150     GNUNET_SCHEDULER_cancel (send_context->task);
2151
2152   about_list = send_context->fast_gossip_list_head;
2153   while (about_list != NULL)
2154   {
2155     GNUNET_CONTAINER_DLL_remove (send_context->fast_gossip_list_head,
2156                                  send_context->fast_gossip_list_tail,
2157                                  about_list);
2158     prev_about = about_list;
2159     about_list = about_list->next;
2160     GNUNET_free (prev_about);
2161   }
2162   GNUNET_free (send_context);
2163   GNUNET_free (direct);
2164 }
2165
2166 /**
2167  * Multihashmap iterator for sending out disconnect messages
2168  * for a peer.
2169  *
2170  * @param cls the peer that was disconnected
2171  * @param key key value stored under
2172  * @param value the direct neighbor to send disconnect to
2173  *
2174  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
2175  */
2176 static int
2177 schedule_disconnect_messages (void *cls, const GNUNET_HashCode * key,
2178                               void *value)
2179 {
2180   struct DisconnectContext *disconnect_context = cls;
2181   struct DirectNeighbor *disconnected = disconnect_context->direct;
2182   struct DirectNeighbor *notify = value;
2183   struct PendingMessage *pending_message;
2184   p2p_dv_MESSAGE_Disconnect *disconnect_message;
2185
2186   if (memcmp
2187       (&notify->identity, &disconnected->identity,
2188        sizeof (struct GNUNET_PeerIdentity)) == 0)
2189     return GNUNET_YES;          /* Don't send disconnect message to peer that disconnected! */
2190
2191   pending_message =
2192       GNUNET_malloc (sizeof (struct PendingMessage) +
2193                      sizeof (p2p_dv_MESSAGE_Disconnect));
2194   pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
2195   pending_message->importance = default_dv_priority;
2196   pending_message->timeout = GNUNET_TIME_relative_get_forever ();
2197   memcpy (&pending_message->recipient, &notify->identity,
2198           sizeof (struct GNUNET_PeerIdentity));
2199   pending_message->msg_size = sizeof (p2p_dv_MESSAGE_Disconnect);
2200   disconnect_message = (p2p_dv_MESSAGE_Disconnect *) pending_message->msg;
2201   disconnect_message->header.size = htons (sizeof (p2p_dv_MESSAGE_Disconnect));
2202   disconnect_message->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISCONNECT);
2203   disconnect_message->peer_id = htonl (disconnect_context->distant->our_id);
2204
2205   GNUNET_CONTAINER_DLL_insert_after (core_pending_head, core_pending_tail,
2206                                      core_pending_tail, pending_message);
2207
2208   GNUNET_SCHEDULER_add_now (try_core_send, NULL);
2209   /*if (core_transmit_handle == NULL)
2210    * core_transmit_handle = GNUNET_CORE_notify_transmit_ready(coreAPI, GNUNET_YES, default_dv_priority, GNUNET_TIME_relative_get_forever(), &notify->identity, sizeof(p2p_dv_MESSAGE_Disconnect), &core_transmit_notify, NULL); */
2211
2212   return GNUNET_YES;
2213 }
2214
2215 /**
2216  * Multihashmap iterator for freeing extended neighbors.
2217  *
2218  * @param cls NULL
2219  * @param key key value stored under
2220  * @param value the distant neighbor to be freed
2221  *
2222  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
2223  */
2224 static int
2225 free_extended_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
2226 {
2227   struct DistantNeighbor *distant = value;
2228
2229   distant_neighbor_free (distant);
2230   return GNUNET_YES;
2231 }
2232
2233 /**
2234  * Multihashmap iterator for freeing direct neighbors.
2235  *
2236  * @param cls NULL
2237  * @param key key value stored under
2238  * @param value the direct neighbor to be freed
2239  *
2240  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
2241  */
2242 static int
2243 free_direct_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
2244 {
2245   struct DirectNeighbor *direct = value;
2246
2247   direct_neighbor_free (direct);
2248   return GNUNET_YES;
2249 }
2250
2251
2252 /**
2253  * Task run during shutdown.
2254  *
2255  * @param cls unused
2256  * @param tc unused
2257  */
2258 static void
2259 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2260 {
2261 #if DEBUG_DV
2262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "calling CORE_DISCONNECT\n");
2263   GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors, &print_neighbors,
2264                                          NULL);
2265 #endif
2266   GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors,
2267                                          &free_extended_neighbors, NULL);
2268   GNUNET_CONTAINER_multihashmap_destroy (extended_neighbors);
2269   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
2270                                          &free_direct_neighbors, NULL);
2271   GNUNET_CONTAINER_multihashmap_destroy (direct_neighbors);
2272
2273   GNUNET_CONTAINER_heap_destroy (neighbor_max_heap);
2274   GNUNET_CONTAINER_heap_destroy (neighbor_min_heap);
2275
2276   GNUNET_CORE_disconnect (coreAPI);
2277   coreAPI = NULL;
2278   GNUNET_PEERINFO_disconnect (peerinfo_handle);
2279   GNUNET_SERVER_mst_destroy (coreMST);
2280   GNUNET_free_non_null (my_short_id);
2281 #if DEBUG_DV
2282   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CORE_DISCONNECT completed\n");
2283 #endif
2284 }
2285
2286 /**
2287  * To be called on core init/fail.
2288  */
2289 void
2290 core_init (void *cls, struct GNUNET_CORE_Handle *server,
2291            const struct GNUNET_PeerIdentity *identity,
2292            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
2293 {
2294
2295   if (server == NULL)
2296   {
2297     GNUNET_SCHEDULER_cancel (cleanup_task);
2298     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
2299     return;
2300   }
2301 #if DEBUG_DV
2302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2303               "%s: Core connection initialized, I am peer: %s\n", "dv",
2304               GNUNET_i2s (identity));
2305 #endif
2306   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
2307   my_short_id = GNUNET_strdup (GNUNET_i2s (&my_identity));
2308   coreAPI = server;
2309 }
2310
2311
2312 #if PKEY_NO_NEIGHBOR_ON_ADD
2313 /**
2314  * Iterator over hash map entries.
2315  *
2316  * @param cls closure
2317  * @param key current key code
2318  * @param value value in the hash map
2319  * @return GNUNET_YES if we should continue to
2320  *         iterate,
2321  *         GNUNET_NO if not.
2322  */
2323 static int
2324 add_pkey_to_extended (void *cls, const GNUNET_HashCode * key, void *abs_value)
2325 {
2326   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey = cls;
2327   struct DistantNeighbor *distant_neighbor = abs_value;
2328
2329   if (distant_neighbor->pkey == NULL)
2330   {
2331     distant_neighbor->pkey =
2332         GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2333     memcpy (distant_neighbor->pkey, pkey,
2334             sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2335   }
2336
2337   return GNUNET_YES;
2338 }
2339 #endif
2340
2341 /**
2342  * Iterator over hash map entries.
2343  *
2344  * @param cls closure
2345  * @param key current key code
2346  * @param value value in the hash map
2347  * @return GNUNET_YES if we should continue to
2348  *         iterate,
2349  *         GNUNET_NO if not.
2350  */
2351 static int
2352 update_matching_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
2353 {
2354   struct NeighborUpdateInfo *update_info = cls;
2355   struct DistantNeighbor *distant_neighbor = value;
2356
2357   if (update_info->referrer == distant_neighbor->referrer)      /* Direct neighbor matches, update it's info and return GNUNET_NO */
2358   {
2359     /* same referrer, cost change! */
2360     GNUNET_CONTAINER_heap_update_cost (neighbor_max_heap,
2361                                        update_info->neighbor->max_loc,
2362                                        update_info->cost);
2363     GNUNET_CONTAINER_heap_update_cost (neighbor_min_heap,
2364                                        update_info->neighbor->min_loc,
2365                                        update_info->cost);
2366     update_info->neighbor->last_activity = update_info->now;
2367     update_info->neighbor->cost = update_info->cost;
2368     update_info->neighbor->referrer_id = update_info->referrer_peer_id;
2369     return GNUNET_NO;
2370   }
2371
2372   return GNUNET_YES;
2373 }
2374
2375
2376 /**
2377  * Iterate over all current direct peers, add DISTANT newly connected
2378  * peer to the fast gossip list for that peer so we get DV routing
2379  * information out as fast as possible!
2380  *
2381  * @param cls the newly connected neighbor we will gossip about
2382  * @param key the hashcode of the peer
2383  * @param value the direct neighbor we should gossip to
2384  *
2385  * @return GNUNET_YES to continue iteration, GNUNET_NO otherwise
2386  */
2387 static int
2388 add_distant_all_direct_neighbors (void *cls, const GNUNET_HashCode * key,
2389                                   void *value)
2390 {
2391   struct DirectNeighbor *direct = (struct DirectNeighbor *) value;
2392   struct DistantNeighbor *distant = (struct DistantNeighbor *) cls;
2393   struct NeighborSendContext *send_context = direct->send_context;
2394   struct FastGossipNeighborList *gossip_entry;
2395
2396 #if DEBUG_DV
2397   char *encPeerAbout;
2398   char *encPeerTo;
2399 #endif
2400
2401   if (distant == NULL)
2402   {
2403     return GNUNET_YES;
2404   }
2405
2406   if (memcmp
2407       (&direct->identity, &distant->identity,
2408        sizeof (struct GNUNET_PeerIdentity)) == 0)
2409   {
2410     return GNUNET_YES;          /* Don't gossip to a peer about itself! */
2411   }
2412
2413 #if SUPPORT_HIDING
2414   if (distant->hidden == GNUNET_YES)
2415     return GNUNET_YES;          /* This peer should not be gossipped about (hidden) */
2416 #endif
2417   gossip_entry = GNUNET_malloc (sizeof (struct FastGossipNeighborList));
2418   gossip_entry->about = distant;
2419
2420   GNUNET_CONTAINER_DLL_insert_after (send_context->fast_gossip_list_head,
2421                                      send_context->fast_gossip_list_tail,
2422                                      send_context->fast_gossip_list_tail,
2423                                      gossip_entry);
2424 #if DEBUG_DV
2425   encPeerAbout = GNUNET_strdup (GNUNET_i2s (&distant->identity));
2426   encPeerTo = GNUNET_strdup (GNUNET_i2s (&direct->identity));
2427
2428   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2429               "%s: Fast send info about peer %s id %u for directly connected peer %s\n",
2430               GNUNET_i2s (&my_identity), encPeerAbout, distant->our_id,
2431               encPeerTo);
2432   GNUNET_free (encPeerAbout);
2433   GNUNET_free (encPeerTo);
2434 #endif
2435   /*if (send_context->task != GNUNET_SCHEDULER_NO_TASK)
2436    * GNUNET_SCHEDULER_cancel(send_context->task); */
2437
2438   send_context->task =
2439       GNUNET_SCHEDULER_add_now (&neighbor_send_task, send_context);
2440   return GNUNET_YES;
2441 }
2442
2443 /**
2444  * Callback for hello address creation.
2445  *
2446  * @param cls closure, a struct HelloContext
2447  * @param max maximum number of bytes that can be written to buf
2448  * @param buf where to write the address information
2449  *
2450  * @return number of bytes written, 0 to signal the
2451  *         end of the iteration.
2452  */
2453 static size_t
2454 generate_hello_address (void *cls, size_t max, void *buf)
2455 {
2456   struct HelloContext *hello_context = cls;
2457   char *addr_buffer;
2458   size_t offset;
2459   size_t size;
2460   size_t ret;
2461
2462   if (hello_context->addresses_to_add == 0)
2463     return 0;
2464
2465   /* Hello "address" will be concatenation of distant peer and direct peer identities */
2466   size = 2 * sizeof (struct GNUNET_PeerIdentity);
2467   GNUNET_assert (max >= size);
2468
2469   addr_buffer = GNUNET_malloc (size);
2470   offset = 0;
2471   /* Copy the distant peer identity to buffer */
2472   memcpy (addr_buffer, &hello_context->distant_peer,
2473           sizeof (struct GNUNET_PeerIdentity));
2474   offset += sizeof (struct GNUNET_PeerIdentity);
2475   /* Copy the direct peer identity to buffer */
2476   memcpy (&addr_buffer[offset], hello_context->direct_peer,
2477           sizeof (struct GNUNET_PeerIdentity));
2478   ret =
2479       GNUNET_HELLO_add_address ("dv",
2480                                 GNUNET_TIME_relative_to_absolute
2481                                 (GNUNET_TIME_UNIT_HOURS), addr_buffer, size,
2482                                 buf, max);
2483
2484   hello_context->addresses_to_add--;
2485
2486   GNUNET_free (addr_buffer);
2487   return ret;
2488 }
2489
2490
2491 /**
2492  * Handles when a peer is either added due to being newly connected
2493  * or having been gossiped about, also called when the cost for a neighbor
2494  * needs to be updated.
2495  *
2496  * @param peer identity of the peer whose info is being added/updated
2497  * @param pkey public key of the peer whose info is being added/updated
2498  * @param referrer_peer_id id to use when sending to 'peer'
2499  * @param referrer if this is a gossiped peer, who did we hear it from?
2500  * @param cost the cost of communicating with this peer via 'referrer'
2501  *
2502  * @return the added neighbor, the updated neighbor or NULL (neighbor
2503  *         not added)
2504  */
2505 static struct DistantNeighbor *
2506 addUpdateNeighbor (const struct GNUNET_PeerIdentity *peer,
2507                    struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
2508                    unsigned int referrer_peer_id,
2509                    struct DirectNeighbor *referrer, unsigned int cost)
2510 {
2511   struct DistantNeighbor *neighbor;
2512   struct DistantNeighbor *max;
2513   struct GNUNET_TIME_Absolute now;
2514   struct NeighborUpdateInfo *neighbor_update;
2515   struct HelloContext *hello_context;
2516   struct GNUNET_HELLO_Message *hello_msg;
2517   unsigned int our_id;
2518   char *addr1;
2519   char *addr2;
2520   int i;
2521
2522 #if DEBUG_DV_PEER_NUMBERS
2523   char *encAbout;
2524
2525   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s Received sender id (%u)!\n",
2526               "DV SERVICE", referrer_peer_id);
2527 #endif
2528
2529   now = GNUNET_TIME_absolute_get ();
2530   neighbor =
2531       GNUNET_CONTAINER_multihashmap_get (extended_neighbors, &peer->hashPubKey);
2532   neighbor_update = GNUNET_malloc (sizeof (struct NeighborUpdateInfo));
2533   neighbor_update->neighbor = neighbor;
2534   neighbor_update->cost = cost;
2535   neighbor_update->now = now;
2536   neighbor_update->referrer = referrer;
2537   neighbor_update->referrer_peer_id = referrer_peer_id;
2538
2539   if (neighbor != NULL)
2540   {
2541 #if USE_PEER_ID
2542     memcpy (&our_id, &neighbor->identity, sizeof (unsigned int));
2543 #else
2544     our_id = neighbor->our_id;
2545 #endif
2546   }
2547   else
2548   {
2549 #if USE_PEER_ID
2550     memcpy (&our_id, peer, sizeof (unsigned int));
2551 #else
2552     our_id =
2553         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG,
2554                                   RAND_MAX - 1) + 1;
2555 #endif
2556   }
2557
2558   /* Either we do not know this peer, or we already do but via a different immediate peer */
2559   if ((neighbor == NULL) ||
2560       (GNUNET_CONTAINER_multihashmap_get_multiple
2561        (extended_neighbors, &peer->hashPubKey, &update_matching_neighbors,
2562         neighbor_update) != GNUNET_SYSERR))
2563   {
2564 #if AT_MOST_ONE
2565     if ((neighbor != NULL) && (cost < neighbor->cost))  /* New cost is less than old, remove old */
2566     {
2567       distant_neighbor_free (neighbor);
2568     }
2569     else if (neighbor != NULL)  /* Only allow one DV connection to each peer */
2570     {
2571       return NULL;
2572     }
2573 #endif
2574     /* new neighbor! */
2575     if (cost > fisheye_depth)
2576     {
2577       /* too costly */
2578       GNUNET_free (neighbor_update);
2579       return NULL;
2580     }
2581
2582 #if DEBUG_DV_PEER_NUMBERS
2583     encAbout = GNUNET_strdup (GNUNET_i2s (peer));
2584     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2585                 "%s: %s Chose NEW id (%u) for peer %s!\n",
2586                 GNUNET_i2s (&my_identity), "DV SERVICE", our_id, encAbout);
2587     GNUNET_free (encAbout);
2588 #endif
2589
2590     if (max_table_size <=
2591         GNUNET_CONTAINER_multihashmap_size (extended_neighbors))
2592     {
2593       /* remove most expensive entry */
2594       max = GNUNET_CONTAINER_heap_peek (neighbor_max_heap);
2595       GNUNET_assert (max != NULL);
2596       if (cost > max->cost)
2597       {
2598         /* new entry most expensive, don't create */
2599         GNUNET_free (neighbor_update);
2600         return NULL;
2601       }
2602       if (max->cost > 1)
2603       {
2604         /* only free if this is not a direct connection;
2605          * we could theoretically have more direct
2606          * connections than DV entries allowed total! */
2607         distant_neighbor_free (max);
2608       }
2609     }
2610
2611     neighbor = GNUNET_malloc (sizeof (struct DistantNeighbor));
2612     GNUNET_CONTAINER_DLL_insert (referrer->referee_head, referrer->referee_tail,
2613                                  neighbor);
2614     neighbor->max_loc =
2615         GNUNET_CONTAINER_heap_insert (neighbor_max_heap, neighbor, cost);
2616     neighbor->min_loc =
2617         GNUNET_CONTAINER_heap_insert (neighbor_min_heap, neighbor, cost);
2618     neighbor->referrer = referrer;
2619     memcpy (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity));
2620     if (pkey != NULL)           /* pkey will be null on direct neighbor addition */
2621     {
2622       neighbor->pkey =
2623           GNUNET_malloc (sizeof
2624                          (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2625       memcpy (neighbor->pkey, pkey,
2626               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2627     }
2628     else
2629       neighbor->pkey = pkey;
2630
2631     neighbor->last_activity = now;
2632     neighbor->cost = cost;
2633     neighbor->referrer_id = referrer_peer_id;
2634     neighbor->our_id = our_id;
2635     neighbor->hidden =
2636         (cost ==
2637          DIRECT_NEIGHBOR_COST)
2638         ? (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 4) ==
2639            0) : GNUNET_NO;
2640
2641     GNUNET_CONTAINER_multihashmap_put (extended_neighbors, &peer->hashPubKey,
2642                                        neighbor,
2643                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2644     if (referrer_peer_id != 0)
2645     {
2646       for (i = 0; i < MAX_OUTSTANDING_MESSAGES; i++)
2647       {
2648         if (referrer->pending_messages[i].sender_id == referrer_peer_id)        /* We have a queued message from just learned about peer! */
2649         {
2650 #if DEBUG_DV_MESSAGES
2651           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2652                       "%s: learned about peer %llu from which we have a previous unknown message, processing!\n",
2653                       my_short_id, referrer_peer_id);
2654 #endif
2655           struct GNUNET_TRANSPORT_ATS_Information atsi[3];
2656
2657           atsi[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2658           atsi[0].value = htonl (referrer->pending_messages[i].distance);
2659           atsi[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
2660           atsi[1].value =
2661               htonl ((uint32_t) referrer->pending_messages[i].latency.
2662                      rel_value);
2663           atsi[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2664           atsi[2].value = htonl (0);
2665           handle_dv_data_message (NULL, &referrer->pending_messages[i].sender,
2666                                   referrer->pending_messages[i].message,
2667                                   (const struct GNUNET_TRANSPORT_ATS_Information
2668                                    *) &atsi);
2669           GNUNET_free (referrer->pending_messages[i].message);
2670           referrer->pending_messages[i].sender_id = 0;
2671         }
2672       }
2673     }
2674     if ((cost != DIRECT_NEIGHBOR_COST) && (neighbor->pkey != NULL))
2675     {
2676       /* Added neighbor, now send HELLO to transport */
2677       hello_context = GNUNET_malloc (sizeof (struct HelloContext));
2678       hello_context->direct_peer = &referrer->identity;
2679       memcpy (&hello_context->distant_peer, peer,
2680               sizeof (struct GNUNET_PeerIdentity));
2681       hello_context->addresses_to_add = 1;
2682       hello_msg =
2683           GNUNET_HELLO_create (pkey, &generate_hello_address, hello_context);
2684       GNUNET_assert (memcmp
2685                      (hello_context->direct_peer, &hello_context->distant_peer,
2686                       sizeof (struct GNUNET_PeerIdentity)) != 0);
2687       addr1 = GNUNET_strdup (GNUNET_i2s (hello_context->direct_peer));
2688       addr2 = GNUNET_strdup (GNUNET_i2s (&hello_context->distant_peer));
2689 #if DEBUG_DV
2690       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2691                   "%s: GIVING HELLO size %d for %s via %s to TRANSPORT\n",
2692                   my_short_id, GNUNET_HELLO_size (hello_msg), addr2, addr1);
2693 #endif
2694       GNUNET_free (addr1);
2695       GNUNET_free (addr2);
2696       send_to_plugin (hello_context->direct_peer,
2697                       GNUNET_HELLO_get_header (hello_msg),
2698                       GNUNET_HELLO_size (hello_msg),
2699                       &hello_context->distant_peer, cost);
2700       GNUNET_free (hello_context);
2701       GNUNET_free (hello_msg);
2702     }
2703
2704   }
2705   else
2706   {
2707 #if DEBUG_DV_GOSSIP
2708     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2709                 "%s: Already know peer %s distance %d, referrer id %d!\n", "dv",
2710                 GNUNET_i2s (peer), cost, referrer_peer_id);
2711 #endif
2712   }
2713 #if DEBUG_DV
2714   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s: Size of extended_neighbors is %d\n",
2715               "dv", GNUNET_CONTAINER_multihashmap_size (extended_neighbors));
2716 #endif
2717
2718   GNUNET_free (neighbor_update);
2719   return neighbor;
2720 }
2721
2722
2723 /**
2724  * Core handler for dv disconnect messages.  These will be used
2725  * by us to tell transport via the dv plugin that a peer can
2726  * no longer be contacted by us via a certain address.  We should
2727  * then propagate these messages on, given that the distance to
2728  * the peer indicates we would have gossiped about it to others.
2729  *
2730  * @param cls closure
2731  * @param peer peer which sent the message (immediate sender)
2732  * @param message the message
2733  * @param atsi performance data
2734  */
2735 static int
2736 handle_dv_disconnect_message (void *cls, const struct GNUNET_PeerIdentity *peer,
2737                               const struct GNUNET_MessageHeader *message,
2738                               const struct GNUNET_TRANSPORT_ATS_Information
2739                               *atsi)
2740 {
2741   struct DirectNeighbor *referrer;
2742   struct DistantNeighbor *distant;
2743   p2p_dv_MESSAGE_Disconnect *enc_message =
2744       (p2p_dv_MESSAGE_Disconnect *) message;
2745
2746   if (ntohs (message->size) < sizeof (p2p_dv_MESSAGE_Disconnect))
2747   {
2748     return GNUNET_SYSERR;       /* invalid message */
2749   }
2750
2751   referrer =
2752       GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
2753   if (referrer == NULL)
2754     return GNUNET_OK;
2755
2756   distant = referrer->referee_head;
2757   while (distant != NULL)
2758   {
2759     if (distant->referrer_id == ntohl (enc_message->peer_id))
2760     {
2761       distant_neighbor_free (distant);
2762       distant = referrer->referee_head;
2763     }
2764     else
2765       distant = distant->next;
2766   }
2767
2768   return GNUNET_OK;
2769 }
2770
2771
2772 /**
2773  * Core handler for dv gossip messages.  These will be used
2774  * by us to create a HELLO message for the newly peer containing
2775  * which direct peer we can connect through, and what the cost
2776  * is.  This HELLO will then be scheduled for validation by the
2777  * transport service so that it can be used by all others.
2778  *
2779  * @param cls closure
2780  * @param peer peer which sent the message (immediate sender)
2781  * @param message the message
2782  * @param atsi performance data
2783  */
2784 static int
2785 handle_dv_gossip_message (void *cls, const struct GNUNET_PeerIdentity *peer,
2786                           const struct GNUNET_MessageHeader *message,
2787                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2788 {
2789   struct DirectNeighbor *referrer;
2790   p2p_dv_MESSAGE_NeighborInfo *enc_message =
2791       (p2p_dv_MESSAGE_NeighborInfo *) message;
2792
2793   if (ntohs (message->size) < sizeof (p2p_dv_MESSAGE_NeighborInfo))
2794   {
2795     return GNUNET_SYSERR;       /* invalid message */
2796   }
2797
2798 #if DEBUG_DV_GOSSIP_RECEIPT
2799   char *encPeerAbout;
2800   char *encPeerFrom;
2801
2802   encPeerAbout = GNUNET_strdup (GNUNET_i2s (&enc_message->neighbor));
2803   encPeerFrom = GNUNET_strdup (GNUNET_i2s (peer));
2804   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2805               "%s: Received %s message from peer %s about peer %s id %u distance %d!\n",
2806               GNUNET_i2s (&my_identity), "DV GOSSIP", encPeerFrom, encPeerAbout,
2807               ntohl (enc_message->neighbor_id), ntohl (enc_message->cost) + 1);
2808   GNUNET_free (encPeerAbout);
2809   GNUNET_free (encPeerFrom);
2810 #endif
2811
2812   referrer =
2813       GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
2814   if (referrer == NULL)
2815     return GNUNET_OK;
2816
2817   addUpdateNeighbor (&enc_message->neighbor, &enc_message->pkey,
2818                      ntohl (enc_message->neighbor_id), referrer,
2819                      ntohl (enc_message->cost) + 1);
2820
2821   return GNUNET_OK;
2822 }
2823
2824
2825 /**
2826  * Iterate over all currently known peers, add them to the
2827  * fast gossip list for this peer so we get DV routing information
2828  * out as fast as possible!
2829  *
2830  * @param cls the direct neighbor we will gossip to
2831  * @param key the hashcode of the peer
2832  * @param value the distant neighbor we should add to the list
2833  *
2834  * @return GNUNET_YES to continue iteration, GNUNET_NO otherwise
2835  */
2836 static int
2837 add_all_extended_peers (void *cls, const GNUNET_HashCode * key, void *value)
2838 {
2839   struct NeighborSendContext *send_context = (struct NeighborSendContext *) cls;
2840   struct DistantNeighbor *distant = (struct DistantNeighbor *) value;
2841   struct FastGossipNeighborList *gossip_entry;
2842
2843   if (memcmp
2844       (&send_context->toNeighbor->identity, &distant->identity,
2845        sizeof (struct GNUNET_PeerIdentity)) == 0)
2846     return GNUNET_YES;          /* Don't gossip to a peer about itself! */
2847
2848 #if SUPPORT_HIDING
2849   if (distant->hidden == GNUNET_YES)
2850     return GNUNET_YES;          /* This peer should not be gossipped about (hidden) */
2851 #endif
2852   gossip_entry = GNUNET_malloc (sizeof (struct FastGossipNeighborList));
2853   gossip_entry->about = distant;
2854
2855   GNUNET_CONTAINER_DLL_insert_after (send_context->fast_gossip_list_head,
2856                                      send_context->fast_gossip_list_tail,
2857                                      send_context->fast_gossip_list_tail,
2858                                      gossip_entry);
2859
2860   return GNUNET_YES;
2861 }
2862
2863 #if INSANE_GOSSIP
2864 /**
2865  * Iterator over hash map entries.
2866  *
2867  * @param cls closure
2868  * @param key current key code
2869  * @param value value in the hash map
2870  * @return GNUNET_YES if we should continue to
2871  *         iterate,
2872  *         GNUNET_NO if not.
2873  */
2874 static int
2875 gossip_all_to_all_iterator (void *cls, const GNUNET_HashCode * key,
2876                             void *abs_value)
2877 {
2878   struct DirectNeighbor *direct = abs_value;
2879
2880   GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors,
2881                                          &add_all_extended_peers,
2882                                          direct->send_context);
2883
2884   if (direct->send_context->task != GNUNET_SCHEDULER_NO_TASK)
2885     GNUNET_SCHEDULER_cancel (direct->send_context->task);
2886
2887   direct->send_context->task =
2888       GNUNET_SCHEDULER_add_now (&neighbor_send_task, direct->send_context);
2889   return GNUNET_YES;
2890 }
2891
2892 /**
2893  * Task run during shutdown.
2894  *
2895  * @param cls unused
2896  * @param tc unused
2897  */
2898 static void
2899 gossip_all_to_all (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2900 {
2901   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
2902                                          &gossip_all_to_all_iterator, NULL);
2903
2904   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2905                                 (GNUNET_TIME_UNIT_SECONDS, 5),
2906                                 &gossip_all_to_all, NULL);
2907
2908 }
2909 #endif
2910 /**
2911  * Iterate over all current direct peers, add newly connected peer
2912  * to the fast gossip list for that peer so we get DV routing
2913  * information out as fast as possible!
2914  *
2915  * @param cls the newly connected neighbor we will gossip about
2916  * @param key the hashcode of the peer
2917  * @param value the direct neighbor we should gossip to
2918  *
2919  * @return GNUNET_YES to continue iteration, GNUNET_NO otherwise
2920  */
2921 static int
2922 add_all_direct_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
2923 {
2924   struct DirectNeighbor *direct = (struct DirectNeighbor *) value;
2925   struct DirectNeighbor *to = (struct DirectNeighbor *) cls;
2926   struct DistantNeighbor *distant;
2927   struct NeighborSendContext *send_context = direct->send_context;
2928   struct FastGossipNeighborList *gossip_entry;
2929   char *direct_id;
2930
2931
2932   distant =
2933       GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
2934                                          &to->identity.hashPubKey);
2935   if (distant == NULL)
2936   {
2937     return GNUNET_YES;
2938   }
2939
2940   if (memcmp
2941       (&direct->identity, &to->identity,
2942        sizeof (struct GNUNET_PeerIdentity)) == 0)
2943   {
2944     return GNUNET_YES;          /* Don't gossip to a peer about itself! */
2945   }
2946
2947 #if SUPPORT_HIDING
2948   if (distant->hidden == GNUNET_YES)
2949     return GNUNET_YES;          /* This peer should not be gossipped about (hidden) */
2950 #endif
2951   direct_id = GNUNET_strdup (GNUNET_i2s (&direct->identity));
2952 #if DEBUG_DV_GOSSIP
2953   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2954               "%s: adding peer %s to fast send list for %s\n", my_short_id,
2955               GNUNET_i2s (&distant->identity), direct_id);
2956 #endif
2957   GNUNET_free (direct_id);
2958   gossip_entry = GNUNET_malloc (sizeof (struct FastGossipNeighborList));
2959   gossip_entry->about = distant;
2960
2961   GNUNET_CONTAINER_DLL_insert_after (send_context->fast_gossip_list_head,
2962                                      send_context->fast_gossip_list_tail,
2963                                      send_context->fast_gossip_list_tail,
2964                                      gossip_entry);
2965   if (send_context->task != GNUNET_SCHEDULER_NO_TASK)
2966     GNUNET_SCHEDULER_cancel (send_context->task);
2967
2968   send_context->task =
2969       GNUNET_SCHEDULER_add_now (&neighbor_send_task, send_context);
2970   //tc.reason = GNUNET_SCHEDULER_REASON_TIMEOUT;
2971   //neighbor_send_task(send_context, &tc);
2972   return GNUNET_YES;
2973 }
2974
2975 /**
2976  * Type of an iterator over the hosts.  Note that each
2977  * host will be called with each available protocol.
2978  *
2979  * @param cls closure
2980  * @param peer id of the peer, NULL for last call
2981  * @param hello hello message for the peer (can be NULL)
2982  * @param err_msg NULL if successful, otherwise contains error message
2983  */
2984 static void
2985 process_peerinfo (void *cls, const struct GNUNET_PeerIdentity *peer,
2986                   const struct GNUNET_HELLO_Message *hello, const char *err_msg)
2987 {
2988   struct PeerIteratorContext *peerinfo_iterator = cls;
2989   struct DirectNeighbor *neighbor = peerinfo_iterator->neighbor;
2990   struct DistantNeighbor *distant = peerinfo_iterator->distant;
2991
2992 #if DEBUG_DV_PEER_NUMBERS
2993   char *neighbor_pid;
2994 #endif
2995   int sent;
2996
2997   if (err_msg != NULL)
2998   {
2999     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3000                 _("Error in communication with PEERINFO service\n"));
3001     /* return; */
3002   }
3003   if (peer == NULL)
3004   {
3005     if (distant->pkey == NULL)
3006     {
3007 #if DEBUG_DV
3008       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3009                   "Failed to get peerinfo information for this peer, retrying!\n");
3010 #endif
3011       peerinfo_iterator->ic =
3012           GNUNET_PEERINFO_iterate (peerinfo_handle,
3013                                    &peerinfo_iterator->neighbor->identity,
3014                                    GNUNET_TIME_relative_multiply
3015                                    (GNUNET_TIME_UNIT_SECONDS, 3),
3016                                    &process_peerinfo, peerinfo_iterator);
3017     }
3018     else
3019     {
3020       GNUNET_free (peerinfo_iterator);
3021     }
3022     return;
3023   }
3024
3025   if (memcmp
3026       (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity) != 0))
3027     return;
3028
3029   if ((hello != NULL) &&
3030       (GNUNET_HELLO_get_key (hello, &neighbor->pkey) == GNUNET_OK))
3031   {
3032     if (distant->pkey == NULL)
3033     {
3034       distant->pkey =
3035           GNUNET_malloc (sizeof
3036                          (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3037       memcpy (distant->pkey, &neighbor->pkey,
3038               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3039     }
3040
3041     sent =
3042         GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors,
3043                                                &add_all_extended_peers,
3044                                                neighbor->send_context);
3045     if (stats != NULL)
3046     {
3047       GNUNET_STATISTICS_update (stats,
3048                                 "# distant peers gossiped to direct neighbors",
3049                                 sent, GNUNET_NO);
3050     }
3051 #if DEBUG_DV_PEER_NUMBERS
3052     neighbor_pid = GNUNET_strdup (GNUNET_i2s (&neighbor->identity));
3053     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3054                 "%s: Gossipped %d extended peers to %s\n",
3055                 GNUNET_i2s (&my_identity), sent, neighbor_pid);
3056 #endif
3057     sent =
3058         GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
3059                                                &add_all_direct_neighbors,
3060                                                neighbor);
3061     if (stats != NULL)
3062     {
3063       GNUNET_STATISTICS_update (stats,
3064                                 "# direct peers gossiped to direct neighbors",
3065                                 sent, GNUNET_NO);
3066     }
3067 #if DEBUG_DV_PEER_NUMBERS
3068     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3069                 "%s: Gossipped about %s to %d direct peers\n",
3070                 GNUNET_i2s (&my_identity), neighbor_pid, sent);
3071     GNUNET_free (neighbor_pid);
3072 #endif
3073     neighbor->send_context->task =
3074         GNUNET_SCHEDULER_add_now (&neighbor_send_task, neighbor->send_context);
3075   }
3076 }
3077
3078
3079 /**
3080  * Method called whenever a peer connects.
3081  *
3082  * @param cls closure
3083  * @param peer peer identity this notification is about
3084  * @param atsi performance data
3085  */
3086 static void
3087 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3088                      const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3089 {
3090   struct DirectNeighbor *neighbor;
3091   struct DistantNeighbor *about;
3092   struct PeerIteratorContext *peerinfo_iterator;
3093   int sent;
3094
3095   uint32_t distance;
3096
3097   /* Check for connect to self message */
3098   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
3099     return;
3100
3101   distance = get_atsi_distance (atsi);
3102   if ((distance == DIRECT_NEIGHBOR_COST) &&
3103       (GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey)
3104        == NULL))
3105   {
3106     peerinfo_iterator = GNUNET_malloc (sizeof (struct PeerIteratorContext));
3107     neighbor = GNUNET_malloc (sizeof (struct DirectNeighbor));
3108     neighbor->send_context =
3109         GNUNET_malloc (sizeof (struct NeighborSendContext));
3110     neighbor->send_context->toNeighbor = neighbor;
3111     memcpy (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity));
3112
3113     GNUNET_assert (GNUNET_SYSERR !=
3114                    GNUNET_CONTAINER_multihashmap_put (direct_neighbors,
3115                                                       &peer->hashPubKey,
3116                                                       neighbor,
3117                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3118     about = addUpdateNeighbor (peer, NULL, 0, neighbor, DIRECT_NEIGHBOR_COST);
3119     peerinfo_iterator->distant = about;
3120     peerinfo_iterator->neighbor = neighbor;
3121     peerinfo_iterator->ic =
3122         GNUNET_PEERINFO_iterate (peerinfo_handle, peer,
3123                                  GNUNET_TIME_relative_multiply
3124                                  (GNUNET_TIME_UNIT_SECONDS, 3),
3125                                  &process_peerinfo, peerinfo_iterator);
3126
3127     if ((about != NULL) && (about->pkey == NULL))
3128     {
3129 #if DEBUG_DV
3130       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3131                   "Newly added peer %s has NULL pkey!\n", GNUNET_i2s (peer));
3132 #endif
3133     }
3134     else if (about != NULL)
3135     {
3136       GNUNET_free (peerinfo_iterator);
3137     }
3138   }
3139   else
3140   {
3141     about =
3142         GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
3143                                            &peer->hashPubKey);
3144     if ((GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey)
3145          == NULL) && (about != NULL))
3146     {
3147       sent =
3148           GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
3149                                                  &add_distant_all_direct_neighbors,
3150                                                  about);
3151       if (stats != NULL)
3152         GNUNET_STATISTICS_update (stats,
3153                                   "# direct peers gossiped to new direct neighbors",
3154                                   sent, GNUNET_NO);
3155     }
3156 #if DEBUG_DV
3157     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3158                 "%s: Distance (%d) greater than %d or already know about peer (%s), not re-adding!\n",
3159                 "dv", distance, DIRECT_NEIGHBOR_COST, GNUNET_i2s (peer));
3160 #endif
3161     return;
3162   }
3163 }
3164
3165 /**
3166  * Method called whenever a given peer disconnects.
3167  *
3168  * @param cls closure
3169  * @param peer peer identity this notification is about
3170  */
3171 void
3172 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3173 {
3174   struct DirectNeighbor *neighbor;
3175   struct DistantNeighbor *referee;
3176   struct FindDestinationContext fdc;
3177   struct DisconnectContext disconnect_context;
3178   struct PendingMessage *pending_pos;
3179
3180 #if DEBUG_DV
3181   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3182               "%s: Receives core peer disconnect message!\n", "dv");
3183 #endif
3184
3185   /* Check for disconnect from self message */
3186   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
3187     return;
3188
3189   neighbor =
3190       GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
3191
3192   if (neighbor == NULL)
3193   {
3194     return;
3195   }
3196
3197   pending_pos = core_pending_head;
3198   while (NULL != pending_pos)
3199   {
3200     if (0 ==
3201         memcmp (&pending_pos->recipient, &neighbor->identity,
3202                 sizeof (struct GNUNET_PeerIdentity)))
3203     {
3204       GNUNET_CONTAINER_DLL_remove (core_pending_head, core_pending_tail,
3205                                    pending_pos);
3206       pending_pos = core_pending_head;
3207     }
3208     else
3209       pending_pos = pending_pos->next;
3210   }
3211
3212   while (NULL != (referee = neighbor->referee_head))
3213     distant_neighbor_free (referee);
3214
3215   fdc.dest = NULL;
3216   fdc.tid = 0;
3217
3218   GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors, &find_distant_peer,
3219                                          &fdc);
3220
3221   if (fdc.dest != NULL)
3222   {
3223     disconnect_context.direct = neighbor;
3224     disconnect_context.distant = fdc.dest;
3225     GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
3226                                            &schedule_disconnect_messages,
3227                                            &disconnect_context);
3228   }
3229
3230   GNUNET_assert (neighbor->referee_tail == NULL);
3231   if (GNUNET_NO ==
3232       GNUNET_CONTAINER_multihashmap_remove (direct_neighbors, &peer->hashPubKey,
3233                                             neighbor))
3234   {
3235     GNUNET_break (0);
3236   }
3237   if ((neighbor->send_context != NULL) &&
3238       (neighbor->send_context->task != GNUNET_SCHEDULER_NO_TASK))
3239     GNUNET_SCHEDULER_cancel (neighbor->send_context->task);
3240   GNUNET_free (neighbor);
3241 }
3242
3243
3244 /**
3245  * Process dv requests.
3246  *
3247  * @param cls closure
3248  * @param server the initialized server
3249  * @param c configuration to use
3250  */
3251 static void
3252 run (void *cls, struct GNUNET_SERVER_Handle *server,
3253      const struct GNUNET_CONFIGURATION_Handle *c)
3254 {
3255   unsigned long long max_hosts;
3256
3257   cfg = c;
3258
3259   /* FIXME: Read from config, or calculate, or something other than this! */
3260   max_hosts = DEFAULT_DIRECT_CONNECTIONS;
3261   max_table_size = DEFAULT_DV_SIZE;
3262   fisheye_depth = DEFAULT_FISHEYE_DEPTH;
3263
3264   if (GNUNET_CONFIGURATION_have_value (cfg, "dv", "max_direct_connections"))
3265     GNUNET_assert (GNUNET_OK ==
3266                    GNUNET_CONFIGURATION_get_value_number (cfg, "dv",
3267                                                           "max_direct_connections",
3268                                                           &max_hosts));
3269
3270   if (GNUNET_CONFIGURATION_have_value (cfg, "dv", "max_total_connections"))
3271     GNUNET_assert (GNUNET_OK ==
3272                    GNUNET_CONFIGURATION_get_value_number (cfg, "dv",
3273                                                           "max_total_connections",
3274                                                           &max_table_size));
3275
3276
3277   if (GNUNET_CONFIGURATION_have_value (cfg, "dv", "fisheye_depth"))
3278     GNUNET_assert (GNUNET_OK ==
3279                    GNUNET_CONFIGURATION_get_value_number (cfg, "dv",
3280                                                           "fisheye_depth",
3281                                                           &fisheye_depth));
3282
3283   neighbor_min_heap =
3284       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3285   neighbor_max_heap =
3286       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MAX);
3287
3288   direct_neighbors = GNUNET_CONTAINER_multihashmap_create (max_hosts);
3289   extended_neighbors =
3290       GNUNET_CONTAINER_multihashmap_create (max_table_size * 3);
3291
3292   GNUNET_SERVER_add_handlers (server, plugin_handlers);
3293   coreAPI = GNUNET_CORE_connect (cfg, 1, NULL,  /* FIXME: anything we want to pass around? */
3294                                  &core_init, &handle_core_connect,
3295                                  &handle_core_disconnect, NULL, NULL, GNUNET_NO,
3296                                  NULL, GNUNET_NO, core_handlers);
3297
3298   if (coreAPI == NULL)
3299     return;
3300
3301   coreMST = GNUNET_SERVER_mst_create (&tokenized_message_handler, NULL);
3302
3303   peerinfo_handle = GNUNET_PEERINFO_connect (cfg);
3304
3305   if (peerinfo_handle == NULL)
3306   {
3307     GNUNET_CORE_disconnect (coreAPI);
3308     return;
3309   }
3310
3311   /* Scheduled the task to clean up when shutdown is called */
3312   cleanup_task =
3313       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
3314                                     &shutdown_task, NULL);
3315 }
3316
3317
3318 /**
3319  * The main function for the dv service.
3320  *
3321  * @param argc number of arguments from the command line
3322  * @param argv command line arguments
3323  * @return 0 ok, 1 on error
3324  */
3325 int
3326 main (int argc, char *const *argv)
3327 {
3328   return (GNUNET_OK ==
3329           GNUNET_SERVICE_run (argc, argv, "dv", GNUNET_SERVICE_OPTION_NONE,
3330                               &run, NULL)) ? 0 : 1;
3331 }