- fix
[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->msg->
765                                                     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
862 core_transmit_notify (void *cls, size_t size, void *buf);
863
864 /**
865  *  Try to send another message from our core sending list
866  */
867 static void
868 try_core_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
869 {
870   struct PendingMessage *pending;
871
872   pending = core_pending_head;
873
874   if (core_transmit_handle != NULL)
875     return;                     /* Message send already in progress */
876
877   if ((pending != NULL) && (coreAPI != NULL))
878     core_transmit_handle =
879         GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
880                                            pending->importance,
881                                            pending->timeout,
882                                            &pending->recipient,
883                                            pending->msg_size,
884                                            &core_transmit_notify, NULL);
885 }
886
887
888 /**
889  * Function called to notify a client about the socket
890  * being ready to queue more data.  "buf" will be
891  * NULL and "size" zero if the socket was closed for
892  * writing in the meantime.
893  *
894  * @param cls closure (NULL)
895  * @param size number of bytes available in buf
896  * @param buf where the callee should write the message
897  * @return number of bytes written to buf
898  */
899 size_t
900 core_transmit_notify (void *cls, size_t size, void *buf)
901 {
902   char *cbuf = buf;
903   struct PendingMessage *pending;
904   struct PendingMessage *client_reply;
905   size_t off;
906   size_t msize;
907
908   if (buf == NULL)
909   {
910     /* client disconnected */
911 #if DEBUG_DV
912     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s': buffer was NULL\n", "DHT");
913 #endif
914     return 0;
915   }
916
917   core_transmit_handle = NULL;
918   off = 0;
919   pending = core_pending_head;
920   if ((pending != NULL) && (size >= (msize = ntohs (pending->msg->size))))
921   {
922 #if DEBUG_DV
923     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
924                 "`%s' : transmit_notify (core) called with size %d\n",
925                 "dv service", msize);
926 #endif
927     GNUNET_CONTAINER_DLL_remove (core_pending_head, core_pending_tail, pending);
928     if (pending->send_result != NULL)   /* Will only be non-null if a real client asked for this send */
929     {
930       client_reply =
931           GNUNET_malloc (sizeof (struct PendingMessage) +
932                          sizeof (struct GNUNET_DV_SendResultMessage));
933       client_reply->msg = (struct GNUNET_MessageHeader *) &client_reply[1];
934       memcpy (&client_reply[1], pending->send_result,
935               sizeof (struct GNUNET_DV_SendResultMessage));
936       GNUNET_free (pending->send_result);
937
938       GNUNET_CONTAINER_DLL_insert_after (plugin_pending_head,
939                                          plugin_pending_tail,
940                                          plugin_pending_tail, client_reply);
941       if (client_handle != NULL)
942       {
943         if (plugin_transmit_handle == NULL)
944         {
945           plugin_transmit_handle =
946               GNUNET_SERVER_notify_transmit_ready (client_handle,
947                                                    sizeof (struct
948                                                            GNUNET_DV_SendResultMessage),
949                                                    GNUNET_TIME_UNIT_FOREVER_REL,
950                                                    &transmit_to_plugin, NULL);
951         }
952         else
953         {
954           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
955                       "Failed to queue message for plugin, must be one in progress already!!\n");
956         }
957       }
958     }
959     memcpy (&cbuf[off], pending->msg, msize);
960     GNUNET_free (pending);
961     off += msize;
962   }
963   /*reply = core_pending_head; */
964
965   GNUNET_SCHEDULER_add_now (&try_core_send, NULL);
966   /*if (reply != NULL)
967    * core_transmit_handle = GNUNET_CORE_notify_transmit_ready(coreAPI, GNUNET_YES,  reply->importance, reply->timeout, &reply->recipient, reply->msg_size, &core_transmit_notify, NULL); */
968
969   return off;
970 }
971
972
973 /**
974  * Send a DV data message via DV.
975  *
976  * @param sender the original sender of the message
977  * @param recipient the next hop recipient, may be our direct peer, maybe not
978  * @param send_context the send context
979  */
980 static int
981 send_message_via (const struct GNUNET_PeerIdentity *sender,
982                   const struct GNUNET_PeerIdentity *recipient,
983                   struct DV_SendContext *send_context)
984 {
985   p2p_dv_MESSAGE_Data *toSend;
986   unsigned int msg_size;
987   unsigned int recipient_id;
988   unsigned int sender_id;
989   struct DistantNeighbor *source;
990   struct PendingMessage *pending_message;
991   struct FindIDContext find_context;
992
993 #if DEBUG_DV
994   char shortname[5];
995 #endif
996
997   msg_size = send_context->message_size + sizeof (p2p_dv_MESSAGE_Data);
998
999   find_context.dest = send_context->distant_peer;
1000   find_context.via = recipient;
1001   find_context.tid = 0;
1002   GNUNET_CONTAINER_multihashmap_get_multiple (extended_neighbors,
1003                                               &send_context->
1004                                               distant_peer->hashPubKey,
1005                                               &find_specific_id, &find_context);
1006
1007   if (find_context.tid == 0)
1008   {
1009     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1010                 "%s: find_specific_id failed to find peer!\n", my_short_id);
1011     /* target unknown to us, drop! */
1012     return GNUNET_SYSERR;
1013   }
1014   recipient_id = find_context.tid;
1015
1016   if (0 == (memcmp (&my_identity, sender, sizeof (struct GNUNET_PeerIdentity))))
1017   {
1018     sender_id = 0;
1019     source =
1020         GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
1021                                            &sender->hashPubKey);
1022     if (source != NULL)
1023       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1024                   "%s: send_message_via found %s, myself in extended peer list???\n",
1025                   my_short_id, GNUNET_i2s (&source->identity));
1026   }
1027   else
1028   {
1029     source =
1030         GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
1031                                            &sender->hashPubKey);
1032     if (source == NULL)
1033     {
1034       /* sender unknown to us, drop! */
1035       return GNUNET_SYSERR;
1036     }
1037     sender_id = source->our_id;
1038   }
1039
1040   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
1041   pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1042   pending_message->send_result = send_context->send_result;
1043   memcpy (&pending_message->recipient, recipient,
1044           sizeof (struct GNUNET_PeerIdentity));
1045   pending_message->msg_size = msg_size;
1046   pending_message->importance = send_context->importance;
1047   pending_message->timeout = send_context->timeout;
1048   toSend = (p2p_dv_MESSAGE_Data *) pending_message->msg;
1049   toSend->header.size = htons (msg_size);
1050   toSend->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DATA);
1051   toSend->sender = htonl (sender_id);
1052   toSend->recipient = htonl (recipient_id);
1053 #if DEBUG_DV_MESSAGES
1054   toSend->uid = send_context->uid;      /* Still sent around in network byte order */
1055 #else
1056   toSend->uid = htonl (0);
1057 #endif
1058
1059   memcpy (&toSend[1], send_context->message, send_context->message_size);
1060
1061 #if DEBUG_DV
1062   memcpy (&shortname, GNUNET_i2s (send_context->distant_peer), 4);
1063   shortname[4] = '\0';
1064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1065               "%s: Notifying core of send to destination `%s' via `%s' size %u\n",
1066               "DV", &shortname, GNUNET_i2s (recipient), msg_size);
1067 #endif
1068
1069   GNUNET_CONTAINER_DLL_insert_after (core_pending_head, core_pending_tail,
1070                                      core_pending_tail, pending_message);
1071
1072   GNUNET_SCHEDULER_add_now (try_core_send, NULL);
1073
1074   return GNUNET_YES;
1075 }
1076
1077 /**
1078  * Given a FindLeastCostContext, and a set
1079  * of peers that match the target, return the cheapest.
1080  *
1081  * @param cls closure, a struct FindLeastCostContext
1082  * @param key the key identifying the target peer
1083  * @param value the target peer
1084  *
1085  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1086  */
1087 static int
1088 find_least_cost_peer (void *cls, const GNUNET_HashCode * key, void *value)
1089 {
1090   struct FindLeastCostContext *find_context = cls;
1091   struct DistantNeighbor *dn = value;
1092
1093   if (dn->cost < find_context->least_cost)
1094   {
1095     find_context->target = dn;
1096   }
1097   if (dn->cost == DIRECT_NEIGHBOR_COST)
1098     return GNUNET_NO;
1099   return GNUNET_YES;
1100 }
1101
1102 /**
1103  * Send a DV data message via DV.
1104  *
1105  * @param recipient the ultimate recipient of this message
1106  * @param sender the original sender of the message
1107  * @param specific_neighbor the specific neighbor to send this message via
1108  * @param message the packed message
1109  * @param message_size size of the message
1110  * @param importance what priority to send this message with
1111  * @param uid the unique identifier of this message (or 0 for none)
1112  * @param timeout how long to possibly delay sending this message
1113  */
1114 static int
1115 send_message (const struct GNUNET_PeerIdentity *recipient,
1116               const struct GNUNET_PeerIdentity *sender,
1117               const struct DistantNeighbor *specific_neighbor,
1118               const struct GNUNET_MessageHeader *message, size_t message_size,
1119               unsigned int importance, unsigned int uid,
1120               struct GNUNET_TIME_Relative timeout)
1121 {
1122   p2p_dv_MESSAGE_Data *toSend;
1123   unsigned int msg_size;
1124   unsigned int cost;
1125   unsigned int recipient_id;
1126   unsigned int sender_id;
1127   struct DistantNeighbor *target;
1128   struct DistantNeighbor *source;
1129   struct PendingMessage *pending_message;
1130   struct FindLeastCostContext find_least_ctx;
1131
1132 #if DEBUG_DV_PEER_NUMBERS
1133   struct GNUNET_CRYPTO_HashAsciiEncoded encPeerFrom;
1134   struct GNUNET_CRYPTO_HashAsciiEncoded encPeerTo;
1135   struct GNUNET_CRYPTO_HashAsciiEncoded encPeerVia;
1136 #endif
1137   msg_size = message_size + sizeof (p2p_dv_MESSAGE_Data);
1138
1139   find_least_ctx.least_cost = -1;
1140   find_least_ctx.target = NULL;
1141   /*
1142    * Need to find the least cost peer, lest the transport selection keep
1143    * picking the same DV route for the same destination which results
1144    * in messages looping forever.  Relatively cheap, we don't iterate
1145    * over all known peers, just those that apply.
1146    */
1147   GNUNET_CONTAINER_multihashmap_get_multiple (extended_neighbors,
1148                                               &recipient->hashPubKey,
1149                                               &find_least_cost_peer,
1150                                               &find_least_ctx);
1151   target = find_least_ctx.target;
1152
1153   if (target == NULL)
1154   {
1155     /* target unknown to us, drop! */
1156     return GNUNET_SYSERR;
1157   }
1158   recipient_id = target->referrer_id;
1159
1160   source =
1161       GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
1162                                          &sender->hashPubKey);
1163   if (source == NULL)
1164   {
1165     if (0 !=
1166         (memcmp (&my_identity, sender, sizeof (struct GNUNET_PeerIdentity))))
1167     {
1168       /* sender unknown to us, drop! */
1169       return GNUNET_SYSERR;
1170     }
1171     sender_id = 0;              /* 0 == us */
1172   }
1173   else
1174   {
1175     /* find out the number that we use when we gossip about
1176      * the sender */
1177     sender_id = source->our_id;
1178   }
1179
1180 #if DEBUG_DV_PEER_NUMBERS
1181   GNUNET_CRYPTO_hash_to_enc (&source->identity.hashPubKey, &encPeerFrom);
1182   GNUNET_CRYPTO_hash_to_enc (&target->referrer->identity.hashPubKey,
1183                              &encPeerVia);
1184   encPeerFrom.encoding[4] = '\0';
1185   encPeerVia.encoding[4] = '\0';
1186 #endif
1187   if ((sender_id != 0) &&
1188       (0 ==
1189        memcmp (&source->identity, &target->referrer->identity,
1190                sizeof (struct GNUNET_PeerIdentity))))
1191   {
1192     return 0;
1193   }
1194
1195   cost = target->cost;
1196   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
1197   pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1198   pending_message->send_result = NULL;
1199   pending_message->importance = importance;
1200   pending_message->timeout = timeout;
1201   memcpy (&pending_message->recipient, &target->referrer->identity,
1202           sizeof (struct GNUNET_PeerIdentity));
1203   pending_message->msg_size = msg_size;
1204   toSend = (p2p_dv_MESSAGE_Data *) pending_message->msg;
1205   toSend->header.size = htons (msg_size);
1206   toSend->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DATA);
1207   toSend->sender = htonl (sender_id);
1208   toSend->recipient = htonl (recipient_id);
1209 #if DEBUG_DV_MESSAGES
1210   toSend->uid = htonl (uid);
1211 #else
1212   toSend->uid = htonl (0);
1213 #endif
1214
1215 #if DEBUG_DV_PEER_NUMBERS
1216   GNUNET_CRYPTO_hash_to_enc (&target->identity.hashPubKey, &encPeerTo);
1217   encPeerTo.encoding[4] = '\0';
1218   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1219               "%s: Sending DATA message. Sender id %u, source %s, destination %s, via %s\n",
1220               GNUNET_i2s (&my_identity), sender_id, &encPeerFrom, &encPeerTo,
1221               &encPeerVia);
1222 #endif
1223   memcpy (&toSend[1], message, message_size);
1224   if ((source != NULL) && (source->pkey == NULL))       /* Test our hypothesis about message failures! */
1225   {
1226     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1227                 "%s: Sending message, but anticipate recipient will not know sender!!!\n\n\n",
1228                 my_short_id);
1229   }
1230   GNUNET_CONTAINER_DLL_insert_after (core_pending_head, core_pending_tail,
1231                                      core_pending_tail, pending_message);
1232 #if DEBUG_DV
1233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1234               "%s: Notifying core of send size %d to destination `%s'\n",
1235               "DV SEND MESSAGE", msg_size, GNUNET_i2s (recipient));
1236 #endif
1237
1238   GNUNET_SCHEDULER_add_now (try_core_send, NULL);
1239   return (int) cost;
1240 }
1241
1242 #if USE_PEER_ID
1243 struct CheckPeerContext
1244 {
1245   /**
1246    * Peer we found
1247    */
1248   struct DistantNeighbor *peer;
1249
1250   /**
1251    * Sender id to search for
1252    */
1253   unsigned int sender_id;
1254 };
1255
1256 /**
1257  * Iterator over hash map entries.
1258  *
1259  * @param cls closure
1260  * @param key current key code
1261  * @param value value in the hash map
1262  * @return GNUNET_YES if we should continue to
1263  *         iterate,
1264  *         GNUNET_NO if not.
1265  */
1266 int
1267 checkPeerID (void *cls, const GNUNET_HashCode * key, void *value)
1268 {
1269   struct CheckPeerContext *ctx = cls;
1270   struct DistantNeighbor *distant = value;
1271
1272   if (memcmp (key, &ctx->sender_id, sizeof (unsigned int)) == 0)
1273   {
1274     ctx->peer = distant;
1275     return GNUNET_NO;
1276   }
1277   return GNUNET_YES;
1278
1279 }
1280 #endif
1281
1282
1283 /**
1284  * Handler for messages parsed out by the tokenizer from
1285  * DV DATA received for this peer.
1286  *
1287  * @param cls NULL
1288  * @param client the TokenizedMessageContext which contains message information
1289  * @param message the actual message
1290  */
1291 void
1292 tokenized_message_handler (void *cls, void *client,
1293                            const struct GNUNET_MessageHeader *message)
1294 {
1295   struct TokenizedMessageContext *ctx = client;
1296
1297   GNUNET_break_op (ntohs (message->type) != GNUNET_MESSAGE_TYPE_DV_GOSSIP);
1298   GNUNET_break_op (ntohs (message->type) != GNUNET_MESSAGE_TYPE_DV_DATA);
1299   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_DV_GOSSIP) &&
1300       (ntohs (message->type) != GNUNET_MESSAGE_TYPE_DV_DATA))
1301   {
1302 #if DEBUG_DV_MESSAGES
1303     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1304                 "%s: Receives %s message for me, uid %u, size %d, type %d cost %u from %s!\n",
1305                 my_short_id, "DV DATA", ctx->uid, ntohs (message->size),
1306                 ntohs (message->type), ctx->distant->cost,
1307                 GNUNET_i2s (&ctx->distant->identity));
1308 #endif
1309     GNUNET_assert (memcmp
1310                    (ctx->peer, &ctx->distant->identity,
1311                     sizeof (struct GNUNET_PeerIdentity)) != 0);
1312     send_to_plugin (ctx->peer, message, ntohs (message->size),
1313                     &ctx->distant->identity, ctx->distant->cost);
1314   }
1315 }
1316
1317 #if DELAY_FORWARDS
1318 struct DelayedMessageContext
1319 {
1320   struct GNUNET_PeerIdentity dest;
1321   struct GNUNET_PeerIdentity sender;
1322   struct GNUNET_MessageHeader *message;
1323   size_t message_size;
1324   uint32_t uid;
1325 };
1326
1327 void
1328 send_message_delayed (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1329 {
1330   struct DelayedMessageContext *msg_ctx = cls;
1331
1332   if (msg_ctx != NULL)
1333   {
1334     send_message (&msg_ctx->dest, &msg_ctx->sender, NULL, msg_ctx->message,
1335                   msg_ctx->message_size, default_dv_priority, msg_ctx->uid,
1336                   GNUNET_TIME_relative_get_forever ());
1337     GNUNET_free (msg_ctx->message);
1338     GNUNET_free (msg_ctx);
1339   }
1340 }
1341 #endif
1342
1343 /**
1344  * Get distance information from 'atsi'.
1345  *
1346  * @param atsi performance data
1347  * @param atsi_count number of entries in atsi
1348  * @return connected transport distance
1349  */
1350 static uint32_t
1351 get_atsi_distance (const struct GNUNET_ATS_Information *atsi,
1352                    unsigned int atsi_count)
1353 {
1354   unsigned int i;
1355
1356   for (i = 0; i < atsi_count; i++)
1357     if (ntohl (atsi[i].type) == GNUNET_ATS_QUALITY_NET_DISTANCE)
1358       return ntohl (atsi->value);
1359   /* FIXME: we do not have distance data? Assume direct neighbor. */
1360   return DIRECT_NEIGHBOR_COST;
1361 }
1362
1363 /**
1364  * Find latency information in 'atsi'.
1365  *
1366  * @param atsi performance data
1367  * @param atsi_count number of entries in atsi
1368  * @return connection latency
1369  */
1370 static struct GNUNET_TIME_Relative
1371 get_atsi_latency (const struct GNUNET_ATS_Information *atsi,
1372                   unsigned int atsi_count)
1373 {
1374   unsigned int i;
1375
1376   for (i = 0; i < atsi_count; i++)
1377     if (ntohl (atsi[i].type) == GNUNET_ATS_QUALITY_NET_DELAY)
1378       return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1379                                             ntohl (atsi->value));
1380   GNUNET_break (0);
1381   /* how can we not have latency data? */
1382   return GNUNET_TIME_UNIT_SECONDS;
1383 }
1384
1385 /**
1386  * Core handler for dv data messages.  Whatever this message
1387  * contains all we really have to do is rip it out of its
1388  * DV layering and give it to our pal the DV plugin to report
1389  * in with.
1390  *
1391  * @param cls closure
1392  * @param peer peer which sent the message (immediate sender)
1393  * @param message the message
1394  * @param atsi transport ATS information (latency, distance, etc.)
1395  * @param atsi_count number of entries in atsi
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_ATS_Information *atsi,
1401                         unsigned int atsi_count)
1402 {
1403   const p2p_dv_MESSAGE_Data *incoming = (const p2p_dv_MESSAGE_Data *) message;
1404   const struct GNUNET_MessageHeader *packed_message;
1405   struct DirectNeighbor *dn;
1406   struct DistantNeighbor *pos;
1407   unsigned int sid;             /* Sender id */
1408   unsigned int tid;             /* Target id */
1409   struct GNUNET_PeerIdentity *original_sender;
1410   struct GNUNET_PeerIdentity *destination;
1411   struct FindDestinationContext fdc;
1412   struct TokenizedMessageContext tkm_ctx;
1413   int i;
1414   int found_pos;
1415
1416 #if DELAY_FORWARDS
1417   struct DelayedMessageContext *delayed_context;
1418 #endif
1419 #if USE_PEER_ID
1420   struct CheckPeerContext checkPeerCtx;
1421 #endif
1422 #if DEBUG_DV_MESSAGES
1423   char *sender_id;
1424 #endif
1425   int ret;
1426   size_t packed_message_size;
1427   char *cbuf;
1428   uint32_t distance;            /* Distance information */
1429   struct GNUNET_TIME_Relative latency;  /* Latency information */
1430
1431   packed_message_size =
1432       ntohs (incoming->header.size) - sizeof (p2p_dv_MESSAGE_Data);
1433 #if DEBUG_DV
1434   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1435               "%s: Receives DATA message from %s size %d, packed size %d!\n",
1436               my_short_id, GNUNET_i2s (peer), ntohs (incoming->header.size),
1437               packed_message_size);
1438 #endif
1439
1440   if (ntohs (incoming->header.size) <
1441       sizeof (p2p_dv_MESSAGE_Data) + sizeof (struct GNUNET_MessageHeader))
1442   {
1443 #if DEBUG_DV
1444     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1445                 "`%s': Message sizes don't add up, total size %u, expected at least %u!\n",
1446                 "dv service", ntohs (incoming->header.size),
1447                 sizeof (p2p_dv_MESSAGE_Data) +
1448                 sizeof (struct GNUNET_MessageHeader));
1449 #endif
1450     return GNUNET_SYSERR;
1451   }
1452
1453   /* Iterate over ATS_Information to get distance and latency */
1454   latency = get_atsi_latency (atsi, atsi_count);
1455   distance = get_atsi_distance (atsi, atsi_count);
1456   dn = GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
1457   if (dn == NULL)
1458     return GNUNET_OK;
1459
1460   sid = ntohl (incoming->sender);
1461 #if USE_PEER_ID
1462   if (sid != 0)
1463   {
1464     checkPeerCtx.sender_id = sid;
1465     checkPeerCtx.peer = NULL;
1466     GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors, &checkPeerID,
1467                                            &checkPeerCtx);
1468     pos = checkPeerCtx.peer;
1469   }
1470   else
1471   {
1472     pos =
1473         GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
1474                                            &peer->hashPubKey);
1475   }
1476 #else
1477   pos = dn->referee_head;
1478   while ((NULL != pos) && (pos->referrer_id != sid))
1479     pos = pos->next;
1480 #endif
1481
1482   if (pos == NULL)
1483   {
1484 #if DEBUG_DV_MESSAGES
1485     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1486                 "%s: unknown sender (%u), Message uid %u from %s!\n",
1487                 my_short_id, ntohl (incoming->sender), ntohl (incoming->uid),
1488                 GNUNET_i2s (&dn->identity));
1489     pos = dn->referee_head;
1490     while ((NULL != pos) && (pos->referrer_id != sid))
1491     {
1492       sender_id = GNUNET_strdup (GNUNET_i2s (&pos->identity));
1493       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "I know sender %u %s\n",
1494                   pos->referrer_id, sender_id);
1495       GNUNET_free (sender_id);
1496       pos = pos->next;
1497     }
1498 #endif
1499
1500     found_pos = -1;
1501     for (i = 0; i < MAX_OUTSTANDING_MESSAGES; i++)
1502     {
1503       if (dn->pending_messages[i].sender_id == 0)
1504       {
1505         found_pos = i;
1506         break;
1507       }
1508     }
1509
1510     if (found_pos == -1)
1511     {
1512       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1513                   "%s: Too many unknown senders (%u), ignoring message! Message uid %llu from %s!\n",
1514                   my_short_id, ntohl (incoming->sender), ntohl (incoming->uid),
1515                   GNUNET_i2s (&dn->identity));
1516     }
1517     else
1518     {
1519       dn->pending_messages[found_pos].message =
1520           GNUNET_malloc (ntohs (message->size));
1521       memcpy (dn->pending_messages[found_pos].message, message,
1522               ntohs (message->size));
1523       dn->pending_messages[found_pos].distance = distance;
1524       dn->pending_messages[found_pos].latency = latency;
1525       memcpy (&dn->pending_messages[found_pos].sender, peer,
1526               sizeof (struct GNUNET_PeerIdentity));
1527       dn->pending_messages[found_pos].sender_id = sid;
1528     }
1529     /* unknown sender */
1530     return GNUNET_OK;
1531   }
1532   original_sender = &pos->identity;
1533   tid = ntohl (incoming->recipient);
1534   if (tid == 0)
1535   {
1536     /* 0 == us */
1537     cbuf = (char *) &incoming[1];
1538
1539     tkm_ctx.peer = peer;
1540     tkm_ctx.distant = pos;
1541     tkm_ctx.uid = ntohl (incoming->uid);
1542     if (GNUNET_OK !=
1543         GNUNET_SERVER_mst_receive (coreMST, &tkm_ctx, cbuf, packed_message_size,
1544                                    GNUNET_NO, GNUNET_NO))
1545     {
1546       GNUNET_break_op (0);
1547       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1548                   "%s: %s Received corrupt data, discarding!", my_short_id,
1549                   "DV SERVICE");
1550     }
1551     return GNUNET_OK;
1552   }
1553   else
1554   {
1555     packed_message = (struct GNUNET_MessageHeader *) &incoming[1];
1556   }
1557
1558   /* FIXME: this is the *only* per-request operation we have in DV
1559    * that is O(n) in relation to the number of connected peers; a
1560    * hash-table lookup could easily solve this (minor performance
1561    * issue) */
1562   fdc.tid = tid;
1563   fdc.dest = NULL;
1564   GNUNET_CONTAINER_heap_iterate (neighbor_max_heap, &find_destination, &fdc);
1565
1566 #if DEBUG_DV
1567   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1568               "%s: Receives %s message for someone else!\n", "dv", "DV DATA");
1569 #endif
1570
1571   if (fdc.dest == NULL)
1572   {
1573 #if DEBUG_DV_MESSAGES
1574     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1575                 "%s: Receives %s message uid %u for someone we don't know (id %u)!\n",
1576                 my_short_id, "DV DATA", ntohl (incoming->uid), tid);
1577 #endif
1578     return GNUNET_OK;
1579   }
1580   destination = &fdc.dest->identity;
1581
1582   if (0 == memcmp (destination, peer, sizeof (struct GNUNET_PeerIdentity)))
1583   {
1584     /* FIXME: create stat: routing loop-discard! */
1585
1586 #if DEBUG_DV_MESSAGES
1587     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1588                 "%s: DROPPING MESSAGE uid %u type %d, routing loop! Message immediately from %s!\n",
1589                 my_short_id, ntohl (incoming->uid),
1590                 ntohs (packed_message->type), GNUNET_i2s (&dn->identity));
1591 #endif
1592     return GNUNET_OK;
1593   }
1594
1595   /* At this point we have a message, and we need to forward it on to the
1596    * next DV hop.
1597    */
1598 #if DEBUG_DV_MESSAGES
1599   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1600               "%s: FORWARD %s message for %s, uid %u, size %d type %d, cost %u!\n",
1601               my_short_id, "DV DATA", GNUNET_i2s (destination),
1602               ntohl (incoming->uid), ntohs (packed_message->size),
1603               ntohs (packed_message->type), pos->cost);
1604 #endif
1605
1606 #if DELAY_FORWARDS
1607   if (GNUNET_TIME_absolute_get_duration (pos->last_gossip).abs_value <
1608       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2).abs_value)
1609   {
1610     delayed_context = GNUNET_malloc (sizeof (struct DelayedMessageContext));
1611     memcpy (&delayed_context->dest, destination,
1612             sizeof (struct GNUNET_PeerIdentity));
1613     memcpy (&delayed_context->sender, original_sender,
1614             sizeof (struct GNUNET_PeerIdentity));
1615     delayed_context->message = GNUNET_malloc (packed_message_size);
1616     memcpy (delayed_context->message, packed_message, packed_message_size);
1617     delayed_context->message_size = packed_message_size;
1618     delayed_context->uid = ntohl (incoming->uid);
1619     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1620                                   (GNUNET_TIME_UNIT_MILLISECONDS, 2500),
1621                                   &send_message_delayed, delayed_context);
1622     return GNUNET_OK;
1623   }
1624   else
1625 #endif
1626   {
1627     ret =
1628         send_message (destination, original_sender, NULL, packed_message,
1629                       packed_message_size, default_dv_priority,
1630                       ntohl (incoming->uid),
1631                       GNUNET_TIME_relative_get_forever ());
1632   }
1633   if (ret != GNUNET_SYSERR)
1634     return GNUNET_OK;
1635   else
1636   {
1637 #if DEBUG_MESSAGE_DROP
1638     char *direct_id = GNUNET_strdup (GNUNET_i2s (&dn->identity));
1639
1640     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1641                 "%s: DROPPING MESSAGE type %d, forwarding failed! Message immediately from %s!\n",
1642                 GNUNET_i2s (&my_identity),
1643                 ntohs (((struct GNUNET_MessageHeader *) &incoming[1])->type),
1644                 direct_id);
1645     GNUNET_free (direct_id);
1646 #endif
1647     return GNUNET_SYSERR;
1648   }
1649 }
1650
1651 #if DEBUG_DV
1652 /**
1653  * Iterator over hash map entries.
1654  *
1655  * @param cls closure (NULL)
1656  * @param key current key code
1657  * @param value value in the hash map (DistantNeighbor)
1658  * @return GNUNET_YES if we should continue to
1659  *         iterate,
1660  *         GNUNET_NO if not.
1661  */
1662 int
1663 print_neighbors (void *cls, const GNUNET_HashCode * key, void *abs_value)
1664 {
1665   struct DistantNeighbor *distant_neighbor = abs_value;
1666   char my_shortname[5];
1667   char referrer_shortname[5];
1668
1669   memcpy (&my_shortname, GNUNET_i2s (&my_identity), 4);
1670   my_shortname[4] = '\0';
1671   memcpy (&referrer_shortname,
1672           GNUNET_i2s (&distant_neighbor->referrer->identity), 4);
1673   referrer_shortname[4] = '\0';
1674
1675   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1676               "`%s' %s: Peer `%s', distance %d, referrer `%s' pkey: %s\n",
1677               &my_shortname, "DV", GNUNET_i2s (&distant_neighbor->identity),
1678               distant_neighbor->cost, &referrer_shortname,
1679               distant_neighbor->pkey == NULL ? "no" : "yes");
1680   return GNUNET_YES;
1681 }
1682 #endif
1683
1684 /**
1685  *  Scheduled task which gossips about known direct peers to other connected
1686  *  peers.  Will run until called with reason shutdown.
1687  */
1688 static void
1689 neighbor_send_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1690 {
1691   struct NeighborSendContext *send_context = cls;
1692
1693 #if DEBUG_DV_GOSSIP_SEND
1694   char *encPeerAbout;
1695   char *encPeerTo;
1696 #endif
1697   struct DistantNeighbor *about;
1698   struct DirectNeighbor *to;
1699   struct FastGossipNeighborList *about_list;
1700
1701   p2p_dv_MESSAGE_NeighborInfo *message;
1702   struct PendingMessage *pending_message;
1703
1704   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1705   {
1706 #if DEBUG_DV_GOSSIP
1707     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1708                 "%s: Called with reason shutdown, shutting down!\n",
1709                 GNUNET_i2s (&my_identity));
1710 #endif
1711     return;
1712   }
1713
1714   if (send_context->fast_gossip_list_head != NULL)
1715   {
1716     about_list = send_context->fast_gossip_list_head;
1717     about = about_list->about;
1718     GNUNET_CONTAINER_DLL_remove (send_context->fast_gossip_list_head,
1719                                  send_context->fast_gossip_list_tail,
1720                                  about_list);
1721     GNUNET_free (about_list);
1722   }
1723   else
1724   {
1725     /* FIXME: this may become a problem, because the heap walk has only one internal "walker".  This means
1726      * that if two neighbor_send_tasks are operating in lockstep (which is quite possible, given default
1727      * values for all connected peers) there may be a serious bias as to which peers get gossiped about!
1728      * Probably the *best* way to fix would be to have an opaque pointer to the walk position passed as
1729      * part of the walk_get_next call.  Then the heap would have to keep a list of walks, or reset the walk
1730      * whenever a modification has been detected.  Yuck either way.  Perhaps we could iterate over the heap
1731      * once to get a list of peers to gossip about and gossip them over time... But then if one goes away
1732      * in the mean time that becomes nasty.  For now we'll just assume that the walking is done
1733      * asynchronously enough to avoid major problems (-;
1734      *
1735      * NOTE: probably fixed once we decided send rate based on allowed bandwidth.
1736      */
1737     about = GNUNET_CONTAINER_heap_walk_get_next (neighbor_min_heap);
1738   }
1739   to = send_context->toNeighbor;
1740
1741   if ((about != NULL) && (to != about->referrer /* split horizon */ ) &&
1742 #if SUPPORT_HIDING
1743       (about->hidden == GNUNET_NO) &&
1744 #endif
1745       (to != NULL) &&
1746       (0 !=
1747        memcmp (&about->identity, &to->identity,
1748                sizeof (struct GNUNET_PeerIdentity))) && (about->pkey != NULL))
1749   {
1750 #if DEBUG_DV_GOSSIP_SEND
1751     encPeerAbout = GNUNET_strdup (GNUNET_i2s (&about->identity));
1752     encPeerTo = GNUNET_strdup (GNUNET_i2s (&to->identity));
1753     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1754                 "%s: Sending info about peer %s id %u to directly connected peer %s\n",
1755                 GNUNET_i2s (&my_identity), encPeerAbout, about->our_id,
1756                 encPeerTo);
1757     GNUNET_free (encPeerAbout);
1758     GNUNET_free (encPeerTo);
1759 #endif
1760     about->last_gossip = GNUNET_TIME_absolute_get ();
1761     pending_message =
1762         GNUNET_malloc (sizeof (struct PendingMessage) +
1763                        sizeof (p2p_dv_MESSAGE_NeighborInfo));
1764     pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1765     pending_message->importance = default_dv_priority;
1766     pending_message->timeout = GNUNET_TIME_relative_get_forever ();
1767     memcpy (&pending_message->recipient, &to->identity,
1768             sizeof (struct GNUNET_PeerIdentity));
1769     pending_message->msg_size = sizeof (p2p_dv_MESSAGE_NeighborInfo);
1770     message = (p2p_dv_MESSAGE_NeighborInfo *) pending_message->msg;
1771     message->header.size = htons (sizeof (p2p_dv_MESSAGE_NeighborInfo));
1772     message->header.type = htons (GNUNET_MESSAGE_TYPE_DV_GOSSIP);
1773     message->cost = htonl (about->cost);
1774     message->neighbor_id = htonl (about->our_id);
1775
1776     memcpy (&message->pkey, about->pkey,
1777             sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1778     memcpy (&message->neighbor, &about->identity,
1779             sizeof (struct GNUNET_PeerIdentity));
1780
1781     GNUNET_CONTAINER_DLL_insert_after (core_pending_head, core_pending_tail,
1782                                        core_pending_tail, pending_message);
1783
1784     GNUNET_SCHEDULER_add_now (try_core_send, NULL);
1785     /*if (core_transmit_handle == NULL)
1786      * 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); */
1787
1788   }
1789
1790   if (send_context->fast_gossip_list_head != NULL)      /* If there are other peers in the fast list, schedule right away */
1791   {
1792 #if DEBUG_DV_PEER_NUMBERS
1793     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1794                 "DV SERVICE: still in fast send mode\n");
1795 #endif
1796     send_context->task =
1797         GNUNET_SCHEDULER_add_now (&neighbor_send_task, send_context);
1798   }
1799   else
1800   {
1801 #if DEBUG_DV_PEER_NUMBERS
1802     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1803                 "DV SERVICE: entering slow send mode\n");
1804 #endif
1805     send_context->task =
1806         GNUNET_SCHEDULER_add_delayed (GNUNET_DV_DEFAULT_SEND_INTERVAL,
1807                                       &neighbor_send_task, send_context);
1808   }
1809
1810   return;
1811 }
1812
1813
1814 /**
1815  * Handle START-message.  This is the first message sent to us
1816  * by the client (can only be one!).
1817  *
1818  * @param cls closure (always NULL)
1819  * @param client identification of the client
1820  * @param message the actual message
1821  */
1822 static void
1823 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
1824               const struct GNUNET_MessageHeader *message)
1825 {
1826
1827 #if DEBUG_DV
1828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' request from client\n",
1829               "START");
1830 #endif
1831
1832   client_handle = client;
1833
1834   GNUNET_SERVER_client_keep (client_handle);
1835   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1836 }
1837
1838 #if UNSIMPLER
1839 /**
1840  * Iterate over hash map entries for a distant neighbor,
1841  * if direct neighbor matches context call send message
1842  *
1843  * @param cls closure, a DV_SendContext
1844  * @param key current key code
1845  * @param value value in the hash map
1846  * @return GNUNET_YES if we should continue to
1847  *         iterate,
1848  *         GNUNET_NO if not.
1849  */
1850 int
1851 send_iterator (void *cls, const GNUNET_HashCode * key, void *abs_value)
1852 {
1853   struct DV_SendContext *send_context = cls;
1854   struct DistantNeighbor *distant_neighbor = abs_value;
1855
1856   if (memcmp (distant_neighbor->referrer, send_context->direct_peer, sizeof (struct GNUNET_PeerIdentity)) == 0) /* They match, send and free */
1857   {
1858     send_message_via (&my_identity, distant_neighbor, send_context);
1859     return GNUNET_NO;
1860   }
1861   return GNUNET_YES;
1862 }
1863 #endif
1864
1865 /**
1866  * Service server's handler for message send requests (which come
1867  * bubbling up to us through the DV plugin).
1868  *
1869  * @param cls closure
1870  * @param client identification of the client
1871  * @param message the actual message
1872  */
1873 void
1874 handle_dv_send_message (void *cls, struct GNUNET_SERVER_Client *client,
1875                         const struct GNUNET_MessageHeader *message)
1876 {
1877   struct GNUNET_DV_SendMessage *send_msg;
1878   struct GNUNET_DV_SendResultMessage *send_result_msg;
1879   struct PendingMessage *pending_message;
1880   size_t address_len;
1881   size_t message_size;
1882   struct GNUNET_PeerIdentity *destination;
1883   struct GNUNET_PeerIdentity *direct;
1884   struct GNUNET_MessageHeader *message_buf;
1885   char *temp_pos;
1886   int offset;
1887   static struct GNUNET_CRYPTO_HashAsciiEncoded dest_hash;
1888   struct DV_SendContext *send_context;
1889
1890 #if DEBUG_DV_MESSAGES
1891   char *cbuf;
1892   struct GNUNET_MessageHeader *packed_message;
1893 #endif
1894
1895   if (client_handle == NULL)
1896   {
1897     client_handle = client;
1898     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1899                 "%s: Setting initial client handle, never received `%s' message?\n",
1900                 "dv", "START");
1901   }
1902   else if (client_handle != client)
1903   {
1904     client_handle = client;
1905     /* What should we do in this case, assert fail or just log the warning? */
1906 #if DEBUG_DV
1907     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1908                 "%s: Setting client handle (was a different client!)!\n", "dv");
1909 #endif
1910   }
1911
1912   GNUNET_assert (ntohs (message->size) > sizeof (struct GNUNET_DV_SendMessage));
1913   send_msg = (struct GNUNET_DV_SendMessage *) message;
1914
1915   address_len = ntohl (send_msg->addrlen);
1916   GNUNET_assert (address_len == sizeof (struct GNUNET_PeerIdentity) * 2);
1917   message_size =
1918       ntohs (message->size) - sizeof (struct GNUNET_DV_SendMessage) -
1919       address_len;
1920   destination = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
1921   direct = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
1922   message_buf = GNUNET_malloc (message_size);
1923
1924   temp_pos = (char *) &send_msg[1];     /* Set pointer to end of message */
1925   offset = 0;                   /* Offset starts at zero */
1926
1927   memcpy (destination, &temp_pos[offset], sizeof (struct GNUNET_PeerIdentity));
1928   offset += sizeof (struct GNUNET_PeerIdentity);
1929
1930   memcpy (direct, &temp_pos[offset], sizeof (struct GNUNET_PeerIdentity));
1931   offset += sizeof (struct GNUNET_PeerIdentity);
1932
1933
1934   memcpy (message_buf, &temp_pos[offset], message_size);
1935   if (memcmp
1936       (&send_msg->target, destination,
1937        sizeof (struct GNUNET_PeerIdentity)) != 0)
1938   {
1939     GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash);   /* GNUNET_i2s won't properly work, need to hash one ourselves */
1940     dest_hash.encoding[4] = '\0';
1941     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1942                 "%s: asked to send message to `%s', but address is for `%s'!",
1943                 "DV SERVICE", GNUNET_i2s (&send_msg->target),
1944                 (const char *) &dest_hash.encoding);
1945   }
1946
1947 #if DEBUG_DV_MESSAGES
1948   cbuf = (char *) message_buf;
1949   offset = 0;
1950   while (offset < message_size)
1951   {
1952     packed_message = (struct GNUNET_MessageHeader *) &cbuf[offset];
1953     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1954                 "%s: DV PLUGIN SEND uid %u type %d to %s\n", my_short_id,
1955                 ntohl (send_msg->uid), ntohs (packed_message->type),
1956                 GNUNET_i2s (destination));
1957     offset += ntohs (packed_message->size);
1958   }
1959   /*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)); */
1960 #endif
1961   GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash);     /* GNUNET_i2s won't properly work, need to hash one ourselves */
1962   dest_hash.encoding[4] = '\0';
1963   send_context = GNUNET_malloc (sizeof (struct DV_SendContext));
1964
1965   send_result_msg = GNUNET_malloc (sizeof (struct GNUNET_DV_SendResultMessage));
1966   send_result_msg->header.size =
1967       htons (sizeof (struct GNUNET_DV_SendResultMessage));
1968   send_result_msg->header.type =
1969       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND_RESULT);
1970   send_result_msg->uid = send_msg->uid; /* No need to ntohl->htonl this */
1971
1972   send_context->importance = ntohl (send_msg->priority);
1973   send_context->timeout = send_msg->timeout;
1974   send_context->direct_peer = direct;
1975   send_context->distant_peer = destination;
1976   send_context->message = message_buf;
1977   send_context->message_size = message_size;
1978   send_context->send_result = send_result_msg;
1979 #if DEBUG_DV_MESSAGES
1980   send_context->uid = send_msg->uid;
1981 #endif
1982
1983   if (send_message_via (&my_identity, direct, send_context) != GNUNET_YES)
1984   {
1985     send_result_msg->result = htons (1);
1986     pending_message =
1987         GNUNET_malloc (sizeof (struct PendingMessage) +
1988                        sizeof (struct GNUNET_DV_SendResultMessage));
1989     pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1990     memcpy (&pending_message[1], send_result_msg,
1991             sizeof (struct GNUNET_DV_SendResultMessage));
1992     GNUNET_free (send_result_msg);
1993
1994     GNUNET_CONTAINER_DLL_insert_after (plugin_pending_head, plugin_pending_tail,
1995                                        plugin_pending_tail, pending_message);
1996
1997     if (client_handle != NULL)
1998     {
1999       if (plugin_transmit_handle == NULL)
2000       {
2001         plugin_transmit_handle =
2002             GNUNET_SERVER_notify_transmit_ready (client_handle,
2003                                                  sizeof (struct
2004                                                          GNUNET_DV_SendResultMessage),
2005                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2006                                                  &transmit_to_plugin, NULL);
2007       }
2008       else
2009       {
2010         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2011                     "Failed to queue message for plugin, must be one in progress already!!\n");
2012       }
2013     }
2014     GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash);   /* GNUNET_i2s won't properly work, need to hash one ourselves */
2015     dest_hash.encoding[4] = '\0';
2016     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2017                 "%s DV SEND failed to send message to destination `%s' via `%s'\n",
2018                 my_short_id, (const char *) &dest_hash.encoding,
2019                 GNUNET_i2s (direct));
2020   }
2021
2022   /* In bizarro world GNUNET_SYSERR indicates that we succeeded */
2023 #if UNSIMPLER
2024   if (GNUNET_SYSERR !=
2025       GNUNET_CONTAINER_multihashmap_get_multiple (extended_neighbors,
2026                                                   &destination->hashPubKey,
2027                                                   &send_iterator, send_context))
2028   {
2029     send_result_msg->result = htons (1);
2030     pending_message =
2031         GNUNET_malloc (sizeof (struct PendingMessage) +
2032                        sizeof (struct GNUNET_DV_SendResultMessage));
2033     pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
2034     memcpy (&pending_message[1], send_result_msg,
2035             sizeof (struct GNUNET_DV_SendResultMessage));
2036     GNUNET_free (send_result_msg);
2037
2038     GNUNET_CONTAINER_DLL_insert_after (plugin_pending_head, plugin_pending_tail,
2039                                        plugin_pending_tail, pending_message);
2040
2041     if (client_handle != NULL)
2042     {
2043       if (plugin_transmit_handle == NULL)
2044       {
2045         plugin_transmit_handle =
2046             GNUNET_SERVER_notify_transmit_ready (client_handle,
2047                                                  sizeof (struct
2048                                                          GNUNET_DV_SendResultMessage),
2049                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2050                                                  &transmit_to_plugin, NULL);
2051       }
2052       else
2053       {
2054         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2055                     "Failed to queue message for plugin, must be one in progress already!!\n");
2056       }
2057     }
2058     GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash);   /* GNUNET_i2s won't properly work, need to hash one ourselves */
2059     dest_hash.encoding[4] = '\0';
2060     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2061                 "%s DV SEND failed to send message to destination `%s' via `%s'\n",
2062                 my_short_id, (const char *) &dest_hash.encoding,
2063                 GNUNET_i2s (direct));
2064   }
2065 #endif
2066   GNUNET_free (message_buf);
2067   GNUNET_free (send_context);
2068   GNUNET_free (direct);
2069   GNUNET_free (destination);
2070
2071   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2072 }
2073
2074 /** Forward declarations **/
2075 static int
2076 handle_dv_gossip_message (void *cls, const struct GNUNET_PeerIdentity *peer,
2077                           const struct GNUNET_MessageHeader *message,
2078                           const struct GNUNET_ATS_Information *atsi,
2079                           unsigned int atsi_count);
2080
2081 static int
2082 handle_dv_disconnect_message (void *cls, const struct GNUNET_PeerIdentity *peer,
2083                               const struct GNUNET_MessageHeader *message,
2084                               const struct GNUNET_ATS_Information *atsi,
2085                               unsigned int atsi_count);
2086 /** End forward declarations **/
2087
2088
2089 /**
2090  * List of handlers for the messages understood by this
2091  * service.
2092  *
2093  * Hmm... will we need to register some handlers with core and
2094  * some handlers with our server here?  Because core should be
2095  * getting the incoming DV messages (from whichever lower level
2096  * transport) and then our server should be getting messages
2097  * from the dv_plugin, right?
2098  */
2099 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2100   {&handle_dv_data_message, GNUNET_MESSAGE_TYPE_DV_DATA, 0},
2101   {&handle_dv_gossip_message, GNUNET_MESSAGE_TYPE_DV_GOSSIP, 0},
2102   {&handle_dv_disconnect_message, GNUNET_MESSAGE_TYPE_DV_DISCONNECT, 0},
2103   {NULL, 0, 0}
2104 };
2105
2106 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
2107   {&handle_dv_send_message, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND, 0},
2108   {&handle_start, NULL, GNUNET_MESSAGE_TYPE_DV_START, 0},
2109   {NULL, NULL, 0, 0}
2110 };
2111
2112 /**
2113  * Free a DistantNeighbor node, including removing it
2114  * from the referer's list.
2115  */
2116 static void
2117 distant_neighbor_free (struct DistantNeighbor *referee)
2118 {
2119   struct DirectNeighbor *referrer;
2120
2121   referrer = referee->referrer;
2122   if (referrer != NULL)
2123   {
2124     GNUNET_CONTAINER_DLL_remove (referrer->referee_head, referrer->referee_tail,
2125                                  referee);
2126   }
2127   GNUNET_CONTAINER_heap_remove_node (referee->max_loc);
2128   GNUNET_CONTAINER_heap_remove_node (referee->min_loc);
2129   GNUNET_CONTAINER_multihashmap_remove_all (extended_neighbors,
2130                                             &referee->identity.hashPubKey);
2131   GNUNET_free_non_null (referee->pkey);
2132   GNUNET_free (referee);
2133 }
2134
2135 /**
2136  * Free a DirectNeighbor node, including removing it
2137  * from the referer's list.
2138  */
2139 static void
2140 direct_neighbor_free (struct DirectNeighbor *direct)
2141 {
2142   struct NeighborSendContext *send_context;
2143   struct FastGossipNeighborList *about_list;
2144   struct FastGossipNeighborList *prev_about;
2145
2146   send_context = direct->send_context;
2147
2148   if (send_context->task != GNUNET_SCHEDULER_NO_TASK)
2149     GNUNET_SCHEDULER_cancel (send_context->task);
2150
2151   about_list = send_context->fast_gossip_list_head;
2152   while (about_list != NULL)
2153   {
2154     GNUNET_CONTAINER_DLL_remove (send_context->fast_gossip_list_head,
2155                                  send_context->fast_gossip_list_tail,
2156                                  about_list);
2157     prev_about = about_list;
2158     about_list = about_list->next;
2159     GNUNET_free (prev_about);
2160   }
2161   GNUNET_free (send_context);
2162   GNUNET_free (direct);
2163 }
2164
2165 /**
2166  * Multihashmap iterator for sending out disconnect messages
2167  * for a peer.
2168  *
2169  * @param cls the peer that was disconnected
2170  * @param key key value stored under
2171  * @param value the direct neighbor to send disconnect to
2172  *
2173  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
2174  */
2175 static int
2176 schedule_disconnect_messages (void *cls, const GNUNET_HashCode * key,
2177                               void *value)
2178 {
2179   struct DisconnectContext *disconnect_context = cls;
2180   struct DirectNeighbor *disconnected = disconnect_context->direct;
2181   struct DirectNeighbor *notify = value;
2182   struct PendingMessage *pending_message;
2183   p2p_dv_MESSAGE_Disconnect *disconnect_message;
2184
2185   if (memcmp
2186       (&notify->identity, &disconnected->identity,
2187        sizeof (struct GNUNET_PeerIdentity)) == 0)
2188     return GNUNET_YES;          /* Don't send disconnect message to peer that disconnected! */
2189
2190   pending_message =
2191       GNUNET_malloc (sizeof (struct PendingMessage) +
2192                      sizeof (p2p_dv_MESSAGE_Disconnect));
2193   pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
2194   pending_message->importance = default_dv_priority;
2195   pending_message->timeout = GNUNET_TIME_relative_get_forever ();
2196   memcpy (&pending_message->recipient, &notify->identity,
2197           sizeof (struct GNUNET_PeerIdentity));
2198   pending_message->msg_size = sizeof (p2p_dv_MESSAGE_Disconnect);
2199   disconnect_message = (p2p_dv_MESSAGE_Disconnect *) pending_message->msg;
2200   disconnect_message->header.size = htons (sizeof (p2p_dv_MESSAGE_Disconnect));
2201   disconnect_message->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISCONNECT);
2202   disconnect_message->peer_id = htonl (disconnect_context->distant->our_id);
2203
2204   GNUNET_CONTAINER_DLL_insert_after (core_pending_head, core_pending_tail,
2205                                      core_pending_tail, pending_message);
2206
2207   GNUNET_SCHEDULER_add_now (try_core_send, NULL);
2208   /*if (core_transmit_handle == NULL)
2209    * 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); */
2210
2211   return GNUNET_YES;
2212 }
2213
2214 /**
2215  * Multihashmap iterator for freeing extended neighbors.
2216  *
2217  * @param cls NULL
2218  * @param key key value stored under
2219  * @param value the distant neighbor to be freed
2220  *
2221  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
2222  */
2223 static int
2224 free_extended_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
2225 {
2226   struct DistantNeighbor *distant = value;
2227
2228   distant_neighbor_free (distant);
2229   return GNUNET_YES;
2230 }
2231
2232 /**
2233  * Multihashmap iterator for freeing direct neighbors.
2234  *
2235  * @param cls NULL
2236  * @param key key value stored under
2237  * @param value the direct neighbor to be freed
2238  *
2239  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
2240  */
2241 static int
2242 free_direct_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
2243 {
2244   struct DirectNeighbor *direct = value;
2245
2246   direct_neighbor_free (direct);
2247   return GNUNET_YES;
2248 }
2249
2250
2251 /**
2252  * Task run during shutdown.
2253  *
2254  * @param cls unused
2255  * @param tc unused
2256  */
2257 static void
2258 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2259 {
2260 #if DEBUG_DV
2261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "calling CORE_DISCONNECT\n");
2262   GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors, &print_neighbors,
2263                                          NULL);
2264 #endif
2265   GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors,
2266                                          &free_extended_neighbors, NULL);
2267   GNUNET_CONTAINER_multihashmap_destroy (extended_neighbors);
2268   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
2269                                          &free_direct_neighbors, NULL);
2270   GNUNET_CONTAINER_multihashmap_destroy (direct_neighbors);
2271
2272   GNUNET_CONTAINER_heap_destroy (neighbor_max_heap);
2273   GNUNET_CONTAINER_heap_destroy (neighbor_min_heap);
2274
2275   GNUNET_CORE_disconnect (coreAPI);
2276   coreAPI = NULL;
2277   GNUNET_PEERINFO_disconnect (peerinfo_handle);
2278   GNUNET_SERVER_mst_destroy (coreMST);
2279   GNUNET_free_non_null (my_short_id);
2280 #if DEBUG_DV
2281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CORE_DISCONNECT completed\n");
2282 #endif
2283 }
2284
2285 /**
2286  * To be called on core init/fail.
2287  */
2288 void
2289 core_init (void *cls, struct GNUNET_CORE_Handle *server,
2290            const struct GNUNET_PeerIdentity *identity)
2291 {
2292
2293   if (server == NULL)
2294   {
2295     GNUNET_SCHEDULER_cancel (cleanup_task);
2296     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
2297     return;
2298   }
2299 #if DEBUG_DV
2300   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2301               "%s: Core connection initialized, I am peer: %s\n", "dv",
2302               GNUNET_i2s (identity));
2303 #endif
2304   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
2305   my_short_id = GNUNET_strdup (GNUNET_i2s (&my_identity));
2306   coreAPI = server;
2307 }
2308
2309
2310 #if PKEY_NO_NEIGHBOR_ON_ADD
2311 /**
2312  * Iterator over hash map entries.
2313  *
2314  * @param cls closure
2315  * @param key current key code
2316  * @param value value in the hash map
2317  * @return GNUNET_YES if we should continue to
2318  *         iterate,
2319  *         GNUNET_NO if not.
2320  */
2321 static int
2322 add_pkey_to_extended (void *cls, const GNUNET_HashCode * key, void *abs_value)
2323 {
2324   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey = cls;
2325   struct DistantNeighbor *distant_neighbor = abs_value;
2326
2327   if (distant_neighbor->pkey == NULL)
2328   {
2329     distant_neighbor->pkey =
2330         GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2331     memcpy (distant_neighbor->pkey, pkey,
2332             sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2333   }
2334
2335   return GNUNET_YES;
2336 }
2337 #endif
2338
2339 /**
2340  * Iterator over hash map entries.
2341  *
2342  * @param cls closure
2343  * @param key current key code
2344  * @param value value in the hash map
2345  * @return GNUNET_YES if we should continue to
2346  *         iterate,
2347  *         GNUNET_NO if not.
2348  */
2349 static int
2350 update_matching_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
2351 {
2352   struct NeighborUpdateInfo *update_info = cls;
2353   struct DistantNeighbor *distant_neighbor = value;
2354
2355   if (update_info->referrer == distant_neighbor->referrer)      /* Direct neighbor matches, update it's info and return GNUNET_NO */
2356   {
2357     /* same referrer, cost change! */
2358     GNUNET_CONTAINER_heap_update_cost (neighbor_max_heap,
2359                                        update_info->neighbor->max_loc,
2360                                        update_info->cost);
2361     GNUNET_CONTAINER_heap_update_cost (neighbor_min_heap,
2362                                        update_info->neighbor->min_loc,
2363                                        update_info->cost);
2364     update_info->neighbor->last_activity = update_info->now;
2365     update_info->neighbor->cost = update_info->cost;
2366     update_info->neighbor->referrer_id = update_info->referrer_peer_id;
2367     return GNUNET_NO;
2368   }
2369
2370   return GNUNET_YES;
2371 }
2372
2373
2374 /**
2375  * Iterate over all current direct peers, add DISTANT newly connected
2376  * peer to the fast gossip list for that peer so we get DV routing
2377  * information out as fast as possible!
2378  *
2379  * @param cls the newly connected neighbor we will gossip about
2380  * @param key the hashcode of the peer
2381  * @param value the direct neighbor we should gossip to
2382  *
2383  * @return GNUNET_YES to continue iteration, GNUNET_NO otherwise
2384  */
2385 static int
2386 add_distant_all_direct_neighbors (void *cls, const GNUNET_HashCode * key,
2387                                   void *value)
2388 {
2389   struct DirectNeighbor *direct = (struct DirectNeighbor *) value;
2390   struct DistantNeighbor *distant = (struct DistantNeighbor *) cls;
2391   struct NeighborSendContext *send_context = direct->send_context;
2392   struct FastGossipNeighborList *gossip_entry;
2393
2394 #if DEBUG_DV
2395   char *encPeerAbout;
2396   char *encPeerTo;
2397 #endif
2398
2399   if (distant == NULL)
2400   {
2401     return GNUNET_YES;
2402   }
2403
2404   if (memcmp
2405       (&direct->identity, &distant->identity,
2406        sizeof (struct GNUNET_PeerIdentity)) == 0)
2407   {
2408     return GNUNET_YES;          /* Don't gossip to a peer about itself! */
2409   }
2410
2411 #if SUPPORT_HIDING
2412   if (distant->hidden == GNUNET_YES)
2413     return GNUNET_YES;          /* This peer should not be gossipped about (hidden) */
2414 #endif
2415   gossip_entry = GNUNET_malloc (sizeof (struct FastGossipNeighborList));
2416   gossip_entry->about = distant;
2417
2418   GNUNET_CONTAINER_DLL_insert_after (send_context->fast_gossip_list_head,
2419                                      send_context->fast_gossip_list_tail,
2420                                      send_context->fast_gossip_list_tail,
2421                                      gossip_entry);
2422 #if DEBUG_DV
2423   encPeerAbout = GNUNET_strdup (GNUNET_i2s (&distant->identity));
2424   encPeerTo = GNUNET_strdup (GNUNET_i2s (&direct->identity));
2425
2426   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2427               "%s: Fast send info about peer %s id %u for directly connected peer %s\n",
2428               GNUNET_i2s (&my_identity), encPeerAbout, distant->our_id,
2429               encPeerTo);
2430   GNUNET_free (encPeerAbout);
2431   GNUNET_free (encPeerTo);
2432 #endif
2433   /*if (send_context->task != GNUNET_SCHEDULER_NO_TASK)
2434    * GNUNET_SCHEDULER_cancel(send_context->task); */
2435
2436   send_context->task =
2437       GNUNET_SCHEDULER_add_now (&neighbor_send_task, send_context);
2438   return GNUNET_YES;
2439 }
2440
2441 /**
2442  * Callback for hello address creation.
2443  *
2444  * @param cls closure, a struct HelloContext
2445  * @param max maximum number of bytes that can be written to buf
2446  * @param buf where to write the address information
2447  *
2448  * @return number of bytes written, 0 to signal the
2449  *         end of the iteration.
2450  */
2451 static size_t
2452 generate_hello_address (void *cls, size_t max, void *buf)
2453 {
2454   struct HelloContext *hello_context = cls;
2455   struct GNUNET_HELLO_Address hello_address;
2456   char *addr_buffer;
2457   size_t offset;
2458   size_t size;
2459   size_t ret;
2460
2461   if (hello_context->addresses_to_add == 0)
2462     return 0;
2463
2464   /* Hello "address" will be concatenation of distant peer and direct peer identities */
2465   size = 2 * sizeof (struct GNUNET_PeerIdentity);
2466   GNUNET_assert (max >= size);
2467
2468   addr_buffer = GNUNET_malloc (size);
2469   offset = 0;
2470   /* Copy the distant peer identity to buffer */
2471   memcpy (addr_buffer, &hello_context->distant_peer,
2472           sizeof (struct GNUNET_PeerIdentity));
2473   offset += sizeof (struct GNUNET_PeerIdentity);
2474   /* Copy the direct peer identity to buffer */
2475   memcpy (&addr_buffer[offset], hello_context->direct_peer,
2476           sizeof (struct GNUNET_PeerIdentity));
2477   memset (&hello_address.peer, 0, sizeof (struct GNUNET_PeerIdentity));
2478   hello_address.address = addr_buffer;
2479   hello_address.transport_name = "dv";
2480   hello_address.address_length = size;
2481   ret =
2482       GNUNET_HELLO_add_address (&hello_address,
2483                                 GNUNET_TIME_relative_to_absolute
2484                                 (GNUNET_TIME_UNIT_HOURS), buf, max);
2485
2486   hello_context->addresses_to_add--;
2487
2488   GNUNET_free (addr_buffer);
2489   return ret;
2490 }
2491
2492
2493 /**
2494  * Handles when a peer is either added due to being newly connected
2495  * or having been gossiped about, also called when the cost for a neighbor
2496  * needs to be updated.
2497  *
2498  * @param peer identity of the peer whose info is being added/updated
2499  * @param pkey public key of the peer whose info is being added/updated
2500  * @param referrer_peer_id id to use when sending to 'peer'
2501  * @param referrer if this is a gossiped peer, who did we hear it from?
2502  * @param cost the cost of communicating with this peer via 'referrer'
2503  *
2504  * @return the added neighbor, the updated neighbor or NULL (neighbor
2505  *         not added)
2506  */
2507 static struct DistantNeighbor *
2508 addUpdateNeighbor (const struct GNUNET_PeerIdentity *peer,
2509                    struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
2510                    unsigned int referrer_peer_id,
2511                    struct DirectNeighbor *referrer, unsigned int cost)
2512 {
2513   struct DistantNeighbor *neighbor;
2514   struct DistantNeighbor *max;
2515   struct GNUNET_TIME_Absolute now;
2516   struct NeighborUpdateInfo *neighbor_update;
2517   struct HelloContext *hello_context;
2518   struct GNUNET_HELLO_Message *hello_msg;
2519   unsigned int our_id;
2520   char *addr1;
2521   char *addr2;
2522   int i;
2523
2524 #if DEBUG_DV_PEER_NUMBERS
2525   char *encAbout;
2526
2527   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s Received sender id (%u)!\n",
2528               "DV SERVICE", referrer_peer_id);
2529 #endif
2530
2531   now = GNUNET_TIME_absolute_get ();
2532   neighbor =
2533       GNUNET_CONTAINER_multihashmap_get (extended_neighbors, &peer->hashPubKey);
2534   neighbor_update = GNUNET_malloc (sizeof (struct NeighborUpdateInfo));
2535   neighbor_update->neighbor = neighbor;
2536   neighbor_update->cost = cost;
2537   neighbor_update->now = now;
2538   neighbor_update->referrer = referrer;
2539   neighbor_update->referrer_peer_id = referrer_peer_id;
2540
2541   if (neighbor != NULL)
2542   {
2543 #if USE_PEER_ID
2544     memcpy (&our_id, &neighbor->identity, sizeof (unsigned int));
2545 #else
2546     our_id = neighbor->our_id;
2547 #endif
2548   }
2549   else
2550   {
2551 #if USE_PEER_ID
2552     memcpy (&our_id, peer, sizeof (unsigned int));
2553 #else
2554     our_id =
2555         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG,
2556                                   RAND_MAX - 1) + 1;
2557 #endif
2558   }
2559
2560   /* Either we do not know this peer, or we already do but via a different immediate peer */
2561   if ((neighbor == NULL) ||
2562       (GNUNET_CONTAINER_multihashmap_get_multiple
2563        (extended_neighbors, &peer->hashPubKey, &update_matching_neighbors,
2564         neighbor_update) != GNUNET_SYSERR))
2565   {
2566 #if AT_MOST_ONE
2567     if ((neighbor != NULL) && (cost < neighbor->cost))  /* New cost is less than old, remove old */
2568     {
2569       distant_neighbor_free (neighbor);
2570     }
2571     else if (neighbor != NULL)  /* Only allow one DV connection to each peer */
2572     {
2573       return NULL;
2574     }
2575 #endif
2576     /* new neighbor! */
2577     if (cost > fisheye_depth)
2578     {
2579       /* too costly */
2580       GNUNET_free (neighbor_update);
2581       return NULL;
2582     }
2583
2584 #if DEBUG_DV_PEER_NUMBERS
2585     encAbout = GNUNET_strdup (GNUNET_i2s (peer));
2586     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2587                 "%s: %s Chose NEW id (%u) for peer %s!\n",
2588                 GNUNET_i2s (&my_identity), "DV SERVICE", our_id, encAbout);
2589     GNUNET_free (encAbout);
2590 #endif
2591
2592     if (max_table_size <=
2593         GNUNET_CONTAINER_multihashmap_size (extended_neighbors))
2594     {
2595       /* remove most expensive entry */
2596       max = GNUNET_CONTAINER_heap_peek (neighbor_max_heap);
2597       GNUNET_assert (max != NULL);
2598       if (cost > max->cost)
2599       {
2600         /* new entry most expensive, don't create */
2601         GNUNET_free (neighbor_update);
2602         return NULL;
2603       }
2604       if (max->cost > 1)
2605       {
2606         /* only free if this is not a direct connection;
2607          * we could theoretically have more direct
2608          * connections than DV entries allowed total! */
2609         distant_neighbor_free (max);
2610       }
2611     }
2612
2613     neighbor = GNUNET_malloc (sizeof (struct DistantNeighbor));
2614     GNUNET_CONTAINER_DLL_insert (referrer->referee_head, referrer->referee_tail,
2615                                  neighbor);
2616     neighbor->max_loc =
2617         GNUNET_CONTAINER_heap_insert (neighbor_max_heap, neighbor, cost);
2618     neighbor->min_loc =
2619         GNUNET_CONTAINER_heap_insert (neighbor_min_heap, neighbor, cost);
2620     neighbor->referrer = referrer;
2621     memcpy (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity));
2622     if (pkey != NULL)           /* pkey will be null on direct neighbor addition */
2623     {
2624       neighbor->pkey =
2625           GNUNET_malloc (sizeof
2626                          (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2627       memcpy (neighbor->pkey, pkey,
2628               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2629     }
2630     else
2631       neighbor->pkey = pkey;
2632
2633     neighbor->last_activity = now;
2634     neighbor->cost = cost;
2635     neighbor->referrer_id = referrer_peer_id;
2636     neighbor->our_id = our_id;
2637     neighbor->hidden =
2638         (cost ==
2639          DIRECT_NEIGHBOR_COST)
2640         ? (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 4) ==
2641            0) : GNUNET_NO;
2642
2643     GNUNET_CONTAINER_multihashmap_put (extended_neighbors, &peer->hashPubKey,
2644                                        neighbor,
2645                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2646     if (referrer_peer_id != 0)
2647     {
2648       for (i = 0; i < MAX_OUTSTANDING_MESSAGES; i++)
2649       {
2650         if (referrer->pending_messages[i].sender_id == referrer_peer_id)        /* We have a queued message from just learned about peer! */
2651         {
2652 #if DEBUG_DV_MESSAGES
2653           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2654                       "%s: learned about peer %llu from which we have a previous unknown message, processing!\n",
2655                       my_short_id, referrer_peer_id);
2656 #endif
2657           struct GNUNET_ATS_Information atsi[2];
2658
2659           atsi[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
2660           atsi[0].value = htonl (referrer->pending_messages[i].distance);
2661           atsi[1].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
2662           atsi[1].value =
2663               htonl ((uint32_t) referrer->pending_messages[i].
2664                      latency.rel_value);
2665           handle_dv_data_message (NULL, &referrer->pending_messages[i].sender,
2666                                   referrer->pending_messages[i].message, atsi,
2667                                   2);
2668           GNUNET_free (referrer->pending_messages[i].message);
2669           referrer->pending_messages[i].sender_id = 0;
2670         }
2671       }
2672     }
2673     if ((cost != DIRECT_NEIGHBOR_COST) && (neighbor->pkey != NULL))
2674     {
2675       /* Added neighbor, now send HELLO to transport */
2676       hello_context = GNUNET_malloc (sizeof (struct HelloContext));
2677       hello_context->direct_peer = &referrer->identity;
2678       memcpy (&hello_context->distant_peer, peer,
2679               sizeof (struct GNUNET_PeerIdentity));
2680       hello_context->addresses_to_add = 1;
2681       hello_msg =
2682           GNUNET_HELLO_create (pkey, &generate_hello_address, hello_context);
2683       GNUNET_assert (memcmp
2684                      (hello_context->direct_peer, &hello_context->distant_peer,
2685                       sizeof (struct GNUNET_PeerIdentity)) != 0);
2686       addr1 = GNUNET_strdup (GNUNET_i2s (hello_context->direct_peer));
2687       addr2 = GNUNET_strdup (GNUNET_i2s (&hello_context->distant_peer));
2688 #if DEBUG_DV
2689       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2690                   "%s: GIVING HELLO size %d for %s via %s to TRANSPORT\n",
2691                   my_short_id, GNUNET_HELLO_size (hello_msg), addr2, addr1);
2692 #endif
2693       GNUNET_free (addr1);
2694       GNUNET_free (addr2);
2695       send_to_plugin (hello_context->direct_peer,
2696                       GNUNET_HELLO_get_header (hello_msg),
2697                       GNUNET_HELLO_size (hello_msg),
2698                       &hello_context->distant_peer, cost);
2699       GNUNET_free (hello_context);
2700       GNUNET_free (hello_msg);
2701     }
2702
2703   }
2704   else
2705   {
2706 #if DEBUG_DV_GOSSIP
2707     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2708                 "%s: Already know peer %s distance %d, referrer id %d!\n", "dv",
2709                 GNUNET_i2s (peer), cost, referrer_peer_id);
2710 #endif
2711   }
2712 #if DEBUG_DV
2713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s: Size of extended_neighbors is %d\n",
2714               "dv", GNUNET_CONTAINER_multihashmap_size (extended_neighbors));
2715 #endif
2716
2717   GNUNET_free (neighbor_update);
2718   return neighbor;
2719 }
2720
2721
2722 /**
2723  * Core handler for dv disconnect messages.  These will be used
2724  * by us to tell transport via the dv plugin that a peer can
2725  * no longer be contacted by us via a certain address.  We should
2726  * then propagate these messages on, given that the distance to
2727  * the peer indicates we would have gossiped about it to others.
2728  *
2729  * @param cls closure
2730  * @param peer peer which sent the message (immediate sender)
2731  * @param message the message
2732  * @param atsi performance data
2733  * @param atsi_count number of entries in atsi
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_ATS_Information *atsi,
2739                               unsigned int atsi_count)
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  * @param atsi_count number of entries in atsi
2784  */
2785 static int
2786 handle_dv_gossip_message (void *cls, const struct GNUNET_PeerIdentity *peer,
2787                           const struct GNUNET_MessageHeader *message,
2788                           const struct GNUNET_ATS_Information *atsi,
2789                           unsigned int atsi_count)
2790 {
2791   struct DirectNeighbor *referrer;
2792   p2p_dv_MESSAGE_NeighborInfo *enc_message =
2793       (p2p_dv_MESSAGE_NeighborInfo *) message;
2794
2795   if (ntohs (message->size) < sizeof (p2p_dv_MESSAGE_NeighborInfo))
2796   {
2797     return GNUNET_SYSERR;       /* invalid message */
2798   }
2799
2800 #if DEBUG_DV_GOSSIP_RECEIPT
2801   char *encPeerAbout;
2802   char *encPeerFrom;
2803
2804   encPeerAbout = GNUNET_strdup (GNUNET_i2s (&enc_message->neighbor));
2805   encPeerFrom = GNUNET_strdup (GNUNET_i2s (peer));
2806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2807               "%s: Received %s message from peer %s about peer %s id %u distance %d!\n",
2808               GNUNET_i2s (&my_identity), "DV GOSSIP", encPeerFrom, encPeerAbout,
2809               ntohl (enc_message->neighbor_id), ntohl (enc_message->cost) + 1);
2810   GNUNET_free (encPeerAbout);
2811   GNUNET_free (encPeerFrom);
2812 #endif
2813
2814   referrer =
2815       GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
2816   if (referrer == NULL)
2817     return GNUNET_OK;
2818
2819   addUpdateNeighbor (&enc_message->neighbor, &enc_message->pkey,
2820                      ntohl (enc_message->neighbor_id), referrer,
2821                      ntohl (enc_message->cost) + 1);
2822
2823   return GNUNET_OK;
2824 }
2825
2826
2827 /**
2828  * Iterate over all currently known peers, add them to the
2829  * fast gossip list for this peer so we get DV routing information
2830  * out as fast as possible!
2831  *
2832  * @param cls the direct neighbor we will gossip to
2833  * @param key the hashcode of the peer
2834  * @param value the distant neighbor we should add to the list
2835  *
2836  * @return GNUNET_YES to continue iteration, GNUNET_NO otherwise
2837  */
2838 static int
2839 add_all_extended_peers (void *cls, const GNUNET_HashCode * key, void *value)
2840 {
2841   struct NeighborSendContext *send_context = (struct NeighborSendContext *) cls;
2842   struct DistantNeighbor *distant = (struct DistantNeighbor *) value;
2843   struct FastGossipNeighborList *gossip_entry;
2844
2845   if (memcmp
2846       (&send_context->toNeighbor->identity, &distant->identity,
2847        sizeof (struct GNUNET_PeerIdentity)) == 0)
2848     return GNUNET_YES;          /* Don't gossip to a peer about itself! */
2849
2850 #if SUPPORT_HIDING
2851   if (distant->hidden == GNUNET_YES)
2852     return GNUNET_YES;          /* This peer should not be gossipped about (hidden) */
2853 #endif
2854   gossip_entry = GNUNET_malloc (sizeof (struct FastGossipNeighborList));
2855   gossip_entry->about = distant;
2856
2857   GNUNET_CONTAINER_DLL_insert_after (send_context->fast_gossip_list_head,
2858                                      send_context->fast_gossip_list_tail,
2859                                      send_context->fast_gossip_list_tail,
2860                                      gossip_entry);
2861
2862   return GNUNET_YES;
2863 }
2864
2865 #if INSANE_GOSSIP
2866 /**
2867  * Iterator over hash map entries.
2868  *
2869  * @param cls closure
2870  * @param key current key code
2871  * @param value value in the hash map
2872  * @return GNUNET_YES if we should continue to
2873  *         iterate,
2874  *         GNUNET_NO if not.
2875  */
2876 static int
2877 gossip_all_to_all_iterator (void *cls, const GNUNET_HashCode * key,
2878                             void *abs_value)
2879 {
2880   struct DirectNeighbor *direct = abs_value;
2881
2882   GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors,
2883                                          &add_all_extended_peers,
2884                                          direct->send_context);
2885
2886   if (direct->send_context->task != GNUNET_SCHEDULER_NO_TASK)
2887     GNUNET_SCHEDULER_cancel (direct->send_context->task);
2888
2889   direct->send_context->task =
2890       GNUNET_SCHEDULER_add_now (&neighbor_send_task, direct->send_context);
2891   return GNUNET_YES;
2892 }
2893
2894 /**
2895  * Task run during shutdown.
2896  *
2897  * @param cls unused
2898  * @param tc unused
2899  */
2900 static void
2901 gossip_all_to_all (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2902 {
2903   GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
2904                                          &gossip_all_to_all_iterator, NULL);
2905
2906   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2907                                 (GNUNET_TIME_UNIT_SECONDS, 5),
2908                                 &gossip_all_to_all, NULL);
2909
2910 }
2911 #endif
2912 /**
2913  * Iterate over all current direct peers, add newly connected peer
2914  * to the fast gossip list for that peer so we get DV routing
2915  * information out as fast as possible!
2916  *
2917  * @param cls the newly connected neighbor we will gossip about
2918  * @param key the hashcode of the peer
2919  * @param value the direct neighbor we should gossip to
2920  *
2921  * @return GNUNET_YES to continue iteration, GNUNET_NO otherwise
2922  */
2923 static int
2924 add_all_direct_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
2925 {
2926   struct DirectNeighbor *direct = (struct DirectNeighbor *) value;
2927   struct DirectNeighbor *to = (struct DirectNeighbor *) cls;
2928   struct DistantNeighbor *distant;
2929   struct NeighborSendContext *send_context = direct->send_context;
2930   struct FastGossipNeighborList *gossip_entry;
2931   char *direct_id;
2932
2933
2934   distant =
2935       GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
2936                                          &to->identity.hashPubKey);
2937   if (distant == NULL)
2938   {
2939     return GNUNET_YES;
2940   }
2941
2942   if (memcmp
2943       (&direct->identity, &to->identity,
2944        sizeof (struct GNUNET_PeerIdentity)) == 0)
2945   {
2946     return GNUNET_YES;          /* Don't gossip to a peer about itself! */
2947   }
2948
2949 #if SUPPORT_HIDING
2950   if (distant->hidden == GNUNET_YES)
2951     return GNUNET_YES;          /* This peer should not be gossipped about (hidden) */
2952 #endif
2953   direct_id = GNUNET_strdup (GNUNET_i2s (&direct->identity));
2954 #if DEBUG_DV_GOSSIP
2955   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2956               "%s: adding peer %s to fast send list for %s\n", my_short_id,
2957               GNUNET_i2s (&distant->identity), direct_id);
2958 #endif
2959   GNUNET_free (direct_id);
2960   gossip_entry = GNUNET_malloc (sizeof (struct FastGossipNeighborList));
2961   gossip_entry->about = distant;
2962
2963   GNUNET_CONTAINER_DLL_insert_after (send_context->fast_gossip_list_head,
2964                                      send_context->fast_gossip_list_tail,
2965                                      send_context->fast_gossip_list_tail,
2966                                      gossip_entry);
2967   if (send_context->task != GNUNET_SCHEDULER_NO_TASK)
2968     GNUNET_SCHEDULER_cancel (send_context->task);
2969
2970   send_context->task =
2971       GNUNET_SCHEDULER_add_now (&neighbor_send_task, send_context);
2972   //tc.reason = GNUNET_SCHEDULER_REASON_TIMEOUT;
2973   //neighbor_send_task(send_context, &tc);
2974   return GNUNET_YES;
2975 }
2976
2977 /**
2978  * Type of an iterator over the hosts.  Note that each
2979  * host will be called with each available protocol.
2980  *
2981  * @param cls closure
2982  * @param peer id of the peer, NULL for last call
2983  * @param hello hello message for the peer (can be NULL)
2984  * @param err_msg NULL if successful, otherwise contains error message
2985  */
2986 static void
2987 process_peerinfo (void *cls, const struct GNUNET_PeerIdentity *peer,
2988                   const struct GNUNET_HELLO_Message *hello, const char *err_msg)
2989 {
2990   struct PeerIteratorContext *peerinfo_iterator = cls;
2991   struct DirectNeighbor *neighbor = peerinfo_iterator->neighbor;
2992   struct DistantNeighbor *distant = peerinfo_iterator->distant;
2993
2994 #if DEBUG_DV_PEER_NUMBERS
2995   char *neighbor_pid;
2996 #endif
2997   int sent;
2998
2999   if (err_msg != NULL)
3000   {
3001     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3002                 _("Error in communication with PEERINFO service\n"));
3003     /* return; */
3004   }
3005   if (peer == NULL)
3006   {
3007     if (distant->pkey == NULL)
3008     {
3009 #if DEBUG_DV
3010       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3011                   "Failed to get peerinfo information for this peer, retrying!\n");
3012 #endif
3013       peerinfo_iterator->ic =
3014           GNUNET_PEERINFO_iterate (peerinfo_handle,
3015                                    &peerinfo_iterator->neighbor->identity,
3016                                    GNUNET_TIME_relative_multiply
3017                                    (GNUNET_TIME_UNIT_SECONDS, 3),
3018                                    &process_peerinfo, peerinfo_iterator);
3019     }
3020     else
3021     {
3022       GNUNET_free (peerinfo_iterator);
3023     }
3024     return;
3025   }
3026
3027   if (memcmp
3028       (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity) != 0))
3029     return;
3030
3031   if ((hello != NULL) &&
3032       (GNUNET_HELLO_get_key (hello, &neighbor->pkey) == GNUNET_OK))
3033   {
3034     if (distant->pkey == NULL)
3035     {
3036       distant->pkey =
3037           GNUNET_malloc (sizeof
3038                          (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3039       memcpy (distant->pkey, &neighbor->pkey,
3040               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3041     }
3042
3043     sent =
3044         GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors,
3045                                                &add_all_extended_peers,
3046                                                neighbor->send_context);
3047     if (stats != NULL)
3048     {
3049       GNUNET_STATISTICS_update (stats,
3050                                 "# distant peers gossiped to direct neighbors",
3051                                 sent, GNUNET_NO);
3052     }
3053 #if DEBUG_DV_PEER_NUMBERS
3054     neighbor_pid = GNUNET_strdup (GNUNET_i2s (&neighbor->identity));
3055     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3056                 "%s: Gossipped %d extended peers to %s\n",
3057                 GNUNET_i2s (&my_identity), sent, neighbor_pid);
3058 #endif
3059     sent =
3060         GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
3061                                                &add_all_direct_neighbors,
3062                                                neighbor);
3063     if (stats != NULL)
3064     {
3065       GNUNET_STATISTICS_update (stats,
3066                                 "# direct peers gossiped to direct neighbors",
3067                                 sent, GNUNET_NO);
3068     }
3069 #if DEBUG_DV_PEER_NUMBERS
3070     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3071                 "%s: Gossipped about %s to %d direct peers\n",
3072                 GNUNET_i2s (&my_identity), neighbor_pid, sent);
3073     GNUNET_free (neighbor_pid);
3074 #endif
3075     neighbor->send_context->task =
3076         GNUNET_SCHEDULER_add_now (&neighbor_send_task, neighbor->send_context);
3077   }
3078 }
3079
3080
3081 /**
3082  * Method called whenever a peer connects.
3083  *
3084  * @param cls closure
3085  * @param peer peer identity this notification is about
3086  * @param atsi performance data
3087  * @param atsi_count number of entries in atsi
3088  */
3089 static void
3090 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3091                      const struct GNUNET_ATS_Information *atsi,
3092                      unsigned int atsi_count)
3093 {
3094   struct DirectNeighbor *neighbor;
3095   struct DistantNeighbor *about;
3096   struct PeerIteratorContext *peerinfo_iterator;
3097   int sent;
3098
3099   uint32_t distance;
3100
3101   /* Check for connect to self message */
3102   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
3103     return;
3104
3105   distance = get_atsi_distance (atsi, atsi_count);
3106   if ((distance == DIRECT_NEIGHBOR_COST) &&
3107       (GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey)
3108        == NULL))
3109   {
3110     peerinfo_iterator = GNUNET_malloc (sizeof (struct PeerIteratorContext));
3111     neighbor = GNUNET_malloc (sizeof (struct DirectNeighbor));
3112     neighbor->send_context =
3113         GNUNET_malloc (sizeof (struct NeighborSendContext));
3114     neighbor->send_context->toNeighbor = neighbor;
3115     memcpy (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity));
3116
3117     GNUNET_assert (GNUNET_SYSERR !=
3118                    GNUNET_CONTAINER_multihashmap_put (direct_neighbors,
3119                                                       &peer->hashPubKey,
3120                                                       neighbor,
3121                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3122     about = addUpdateNeighbor (peer, NULL, 0, neighbor, DIRECT_NEIGHBOR_COST);
3123     peerinfo_iterator->distant = about;
3124     peerinfo_iterator->neighbor = neighbor;
3125     peerinfo_iterator->ic =
3126         GNUNET_PEERINFO_iterate (peerinfo_handle, peer,
3127                                  GNUNET_TIME_relative_multiply
3128                                  (GNUNET_TIME_UNIT_SECONDS, 3),
3129                                  &process_peerinfo, peerinfo_iterator);
3130
3131     if ((about != NULL) && (about->pkey == NULL))
3132     {
3133 #if DEBUG_DV
3134       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3135                   "Newly added peer %s has NULL pkey!\n", GNUNET_i2s (peer));
3136 #endif
3137     }
3138     else if (about != NULL)
3139     {
3140       GNUNET_free (peerinfo_iterator);
3141     }
3142   }
3143   else
3144   {
3145     about =
3146         GNUNET_CONTAINER_multihashmap_get (extended_neighbors,
3147                                            &peer->hashPubKey);
3148     if ((GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey)
3149          == NULL) && (about != NULL))
3150     {
3151       sent =
3152           GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
3153                                                  &add_distant_all_direct_neighbors,
3154                                                  about);
3155       if (stats != NULL)
3156         GNUNET_STATISTICS_update (stats,
3157                                   "# direct peers gossiped to new direct neighbors",
3158                                   sent, GNUNET_NO);
3159     }
3160 #if DEBUG_DV
3161     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3162                 "%s: Distance (%d) greater than %d or already know about peer (%s), not re-adding!\n",
3163                 "dv", distance, DIRECT_NEIGHBOR_COST, GNUNET_i2s (peer));
3164 #endif
3165     return;
3166   }
3167 }
3168
3169 /**
3170  * Method called whenever a given peer disconnects.
3171  *
3172  * @param cls closure
3173  * @param peer peer identity this notification is about
3174  */
3175 void
3176 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3177 {
3178   struct DirectNeighbor *neighbor;
3179   struct DistantNeighbor *referee;
3180   struct FindDestinationContext fdc;
3181   struct DisconnectContext disconnect_context;
3182   struct PendingMessage *pending_pos;
3183
3184 #if DEBUG_DV
3185   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3186               "%s: Receives core peer disconnect message!\n", "dv");
3187 #endif
3188
3189   /* Check for disconnect from self message */
3190   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
3191     return;
3192
3193   neighbor =
3194       GNUNET_CONTAINER_multihashmap_get (direct_neighbors, &peer->hashPubKey);
3195
3196   if (neighbor == NULL)
3197   {
3198     return;
3199   }
3200
3201   pending_pos = core_pending_head;
3202   while (NULL != pending_pos)
3203   {
3204     if (0 ==
3205         memcmp (&pending_pos->recipient, &neighbor->identity,
3206                 sizeof (struct GNUNET_PeerIdentity)))
3207     {
3208       GNUNET_CONTAINER_DLL_remove (core_pending_head, core_pending_tail,
3209                                    pending_pos);
3210       pending_pos = core_pending_head;
3211     }
3212     else
3213       pending_pos = pending_pos->next;
3214   }
3215
3216   while (NULL != (referee = neighbor->referee_head))
3217     distant_neighbor_free (referee);
3218
3219   fdc.dest = NULL;
3220   fdc.tid = 0;
3221
3222   GNUNET_CONTAINER_multihashmap_iterate (extended_neighbors, &find_distant_peer,
3223                                          &fdc);
3224
3225   if (fdc.dest != NULL)
3226   {
3227     disconnect_context.direct = neighbor;
3228     disconnect_context.distant = fdc.dest;
3229     GNUNET_CONTAINER_multihashmap_iterate (direct_neighbors,
3230                                            &schedule_disconnect_messages,
3231                                            &disconnect_context);
3232   }
3233
3234   GNUNET_assert (neighbor->referee_tail == NULL);
3235   if (GNUNET_NO ==
3236       GNUNET_CONTAINER_multihashmap_remove (direct_neighbors, &peer->hashPubKey,
3237                                             neighbor))
3238   {
3239     GNUNET_break (0);
3240   }
3241   if ((neighbor->send_context != NULL) &&
3242       (neighbor->send_context->task != GNUNET_SCHEDULER_NO_TASK))
3243     GNUNET_SCHEDULER_cancel (neighbor->send_context->task);
3244   GNUNET_free (neighbor);
3245 }
3246
3247
3248 /**
3249  * Process dv requests.
3250  *
3251  * @param cls closure
3252  * @param server the initialized server
3253  * @param c configuration to use
3254  */
3255 static void
3256 run (void *cls, struct GNUNET_SERVER_Handle *server,
3257      const struct GNUNET_CONFIGURATION_Handle *c)
3258 {
3259   unsigned long long max_hosts;
3260
3261   cfg = c;
3262
3263   /* FIXME: Read from config, or calculate, or something other than this! */
3264   max_hosts = DEFAULT_DIRECT_CONNECTIONS;
3265   max_table_size = DEFAULT_DV_SIZE;
3266   fisheye_depth = DEFAULT_FISHEYE_DEPTH;
3267
3268   if (GNUNET_CONFIGURATION_have_value (cfg, "dv", "max_direct_connections"))
3269     GNUNET_assert (GNUNET_OK ==
3270                    GNUNET_CONFIGURATION_get_value_number (cfg, "dv",
3271                                                           "max_direct_connections",
3272                                                           &max_hosts));
3273
3274   if (GNUNET_CONFIGURATION_have_value (cfg, "dv", "max_total_connections"))
3275     GNUNET_assert (GNUNET_OK ==
3276                    GNUNET_CONFIGURATION_get_value_number (cfg, "dv",
3277                                                           "max_total_connections",
3278                                                           &max_table_size));
3279
3280
3281   if (GNUNET_CONFIGURATION_have_value (cfg, "dv", "fisheye_depth"))
3282     GNUNET_assert (GNUNET_OK ==
3283                    GNUNET_CONFIGURATION_get_value_number (cfg, "dv",
3284                                                           "fisheye_depth",
3285                                                           &fisheye_depth));
3286
3287   neighbor_min_heap =
3288       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3289   neighbor_max_heap =
3290       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MAX);
3291
3292   direct_neighbors = GNUNET_CONTAINER_multihashmap_create (max_hosts);
3293   extended_neighbors =
3294       GNUNET_CONTAINER_multihashmap_create (max_table_size * 3);
3295
3296   GNUNET_SERVER_add_handlers (server, plugin_handlers);
3297   coreAPI = GNUNET_CORE_connect (cfg, 1, NULL,  /* FIXME: anything we want to pass around? */
3298                                  &core_init, &handle_core_connect,
3299                                  &handle_core_disconnect, NULL, GNUNET_NO, NULL,
3300                                  GNUNET_NO, core_handlers);
3301
3302   if (coreAPI == NULL)
3303     return;
3304
3305   coreMST = GNUNET_SERVER_mst_create (&tokenized_message_handler, NULL);
3306
3307   peerinfo_handle = GNUNET_PEERINFO_connect (cfg);
3308
3309   if (peerinfo_handle == NULL)
3310   {
3311     GNUNET_CORE_disconnect (coreAPI);
3312     return;
3313   }
3314
3315   /* Scheduled the task to clean up when shutdown is called */
3316   cleanup_task =
3317       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
3318                                     &shutdown_task, NULL);
3319 }
3320
3321
3322 /**
3323  * The main function for the dv service.
3324  *
3325  * @param argc number of arguments from the command line
3326  * @param argv command line arguments
3327  * @return 0 ok, 1 on error
3328  */
3329 int
3330 main (int argc, char *const *argv)
3331 {
3332   return (GNUNET_OK ==
3333           GNUNET_SERVICE_run (argc, argv, "dv", GNUNET_SERVICE_OPTION_NONE,
3334                               &run, NULL)) ? 0 : 1;
3335 }