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