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