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