fixing mess with search update serialization and parenting
[oweals/gnunet.git] / src / dv / gnunet-service-dv.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file dv/gnunet-service-dv.c
23  * @brief the distance vector service, primarily handles gossip of nearby
24  * peers and sending/receiving DV messages from core and decapsulating
25  * them
26  *
27  * @author Christian Grothoff
28  * @author Nathan Evans
29  *
30  * TODO: The gossip rates need to be worked out.  Probably many other things
31  * as well.
32  *
33  */
34 #include "platform.h"
35 #include "gnunet_client_lib.h"
36 #include "gnunet_getopt_lib.h"
37 #include "gnunet_os_lib.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_service_lib.h"
40 #include "gnunet_core_service.h"
41 #include "gnunet_signal_lib.h"
42 #include "gnunet_util_lib.h"
43 #include "gnunet_hello_lib.h"
44 #include "gnunet_peerinfo_service.h"
45 #include "gnunet_crypto_lib.h"
46 #include "dv.h"
47
48 /**
49  * DV Service Context stuff goes here...
50  */
51
52 /**
53  * Handle to the core service api.
54  */
55 static struct GNUNET_CORE_Handle *coreAPI;
56
57 /**
58  * The identity of our peer.
59  */
60 static struct GNUNET_PeerIdentity my_identity;
61
62 /**
63  * The configuration for this service.
64  */
65 static const struct GNUNET_CONFIGURATION_Handle *cfg;
66
67 /**
68  * The scheduler for this service.
69  */
70 static struct GNUNET_SCHEDULER_Handle *sched;
71
72 /**
73  * How often do we check about sending out more peer information (if
74  * we are connected to no peers previously).
75  */
76 #define GNUNET_DV_DEFAULT_SEND_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 50000)
77
78 /**
79  * How long do we wait at most between sending out information?
80  */
81 #define GNUNET_DV_MAX_SEND_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 50000)
82
83 /**
84  * How long can we have not heard from a peer and
85  * still have it in our tables?
86  */
87 #define GNUNET_DV_PEER_EXPIRATION_TIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1000))
88
89 /**
90  * Priority for gossip.
91  */
92 #define GNUNET_DV_DHT_GOSSIP_PRIORITY (GNUNET_EXTREME_PRIORITY / 10)
93
94 /**
95  * How often should we check if expiration time has elapsed for
96  * some peer?
97  */
98 #define GNUNET_DV_MAINTAIN_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5))
99
100 /**
101  * How long to allow a message to be delayed?
102  */
103 #define DV_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5))
104
105 /**
106  * Priority to use for DV data messages.
107  */
108 #define DV_PRIORITY 0
109
110 /**
111  * The cost to a direct neighbor.  We used to use 0, but 1 makes more sense.
112  */
113 #define DIRECT_NEIGHBOR_COST 1
114
115 /**
116  * The default number of direct connections to store in DV (max)
117  */
118 #define DEFAULT_DIRECT_CONNECTIONS 50
119
120 /**
121  * The default size of direct + extended peers in DV (max)
122  */
123 #define DEFAULT_DV_SIZE 100
124
125 /**
126  * The default fisheye depth, from how many hops away will
127  * we keep peers?
128  */
129 #define DEFAULT_FISHEYE_DEPTH 4
130
131 /**
132  * The client, the DV plugin connected to us.  Hopefully
133  * this client will never change, although if the plugin dies
134  * and returns for some reason it may happen.
135  */
136 static struct GNUNET_SERVER_Client * client_handle;
137
138 /**
139  * Task to run when we shut down, cleaning up all our trash
140  */
141 GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
142
143 /**
144  * Task to run to gossip about peers.  Will reschedule itself forever until shutdown!
145  */
146 GNUNET_SCHEDULER_TaskIdentifier gossip_task;
147
148 /**
149  * Struct where neighbor information is stored.
150  */
151 struct DistantNeighbor *referees;
152
153 static size_t default_dv_priority = 0;
154
155
156 /**
157  * Linked list of messages to send to clients.
158  */
159 struct PendingMessage
160 {
161   /**
162    * Pointer to next item in the list
163    */
164   struct PendingMessage *next;
165
166   /**
167    * Pointer to previous item in the list
168    */
169   struct PendingMessage *prev;
170
171   struct GNUNET_DV_SendResultMessage *send_result;
172   /**
173    * Actual message to be sent; // avoid allocation
174    */
175   const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
176
177 };
178
179 /**
180  * Transmit handle to the plugin.
181  */
182 struct GNUNET_CONNECTION_TransmitHandle * plugin_transmit_handle;
183
184 /**
185  * Head of DLL for client messages
186  */
187 struct PendingMessage *plugin_pending_head;
188
189 /**
190  * Tail of DLL for client messages
191  */
192 struct PendingMessage *plugin_pending_tail;
193
194 /**
195  * Handle to the peerinfo service
196  */
197 struct GNUNET_PEERINFO_Handle *peerinfo_handle;
198
199 /**
200  * Transmit handle to core service.
201  */
202 struct GNUNET_CORE_TransmitHandle * core_transmit_handle;
203
204 /**
205  * Head of DLL for core messages
206  */
207 struct PendingMessage *core_pending_head;
208
209 /**
210  * Tail of DLL for core messages
211  */
212 struct PendingMessage *core_pending_tail;
213
214
215 struct FastGossipNeighborList
216 {
217   /**
218    * Next element of DLL
219    */
220   struct FastGossipNeighborList *next;
221
222   /**
223    * Prev element of DLL
224    */
225   struct FastGossipNeighborList *prev;
226
227   /**
228    * The neighbor to gossip about
229    */
230   struct DistantNeighbor *about;
231 };
232
233 /**
234  * Context created whenever a direct peer connects to us,
235  * used to gossip other peers to it.
236  */
237 struct NeighborSendContext
238 {
239   /**
240    * The peer we will gossip to.
241    */
242   struct DirectNeighbor *toNeighbor;
243
244   /**
245    * The task associated with this context.
246    */
247   GNUNET_SCHEDULER_TaskIdentifier task;
248
249   /**
250    * Head of DLL of peers to gossip about
251    * as fast as possible to this peer, for initial
252    * set up.
253    */
254   struct FastGossipNeighborList *fast_gossip_list_head;
255
256   /**
257    * Tail of DLL of peers to gossip about
258    * as fast as possible to this peer, for initial
259    * set up.
260    */
261   struct FastGossipNeighborList *fast_gossip_list_tail;
262
263 };
264
265
266 /**
267  * Struct to hold information for updating existing neighbors
268  */
269 struct NeighborUpdateInfo
270 {
271   /**
272    * Cost
273    */
274   unsigned int cost;
275
276   /**
277    * The existing neighbor
278    */
279   struct DistantNeighbor *neighbor;
280
281   /**
282    * The referrer of the possibly existing peer
283    */
284   struct DirectNeighbor *referrer;
285
286   /**
287    * The time we heard about this peer
288    */
289   struct GNUNET_TIME_Absolute now;
290 };
291
292 /**
293  * Struct where actual neighbor information is stored,
294  * referenced by min_heap and max_heap.  Freeing dealt
295  * with when items removed from hashmap.
296  */
297 struct DirectNeighbor
298 {
299   /**
300    * Identity of neighbor.
301    */
302   struct GNUNET_PeerIdentity identity;
303
304   /**
305    * PublicKey of neighbor.
306    */
307   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
308
309   /**
310    * Head of DLL of nodes that this direct neighbor referred to us.
311    */
312   struct DistantNeighbor *referee_head;
313
314   /**
315    * Tail of DLL of nodes that this direct neighbor referred to us.
316    */
317   struct DistantNeighbor *referee_tail;
318
319   /**
320    * The sending context for gossiping peers to this neighbor.
321    */
322   struct NeighborSendContext *send_context;
323
324   /**
325    * Is this one of the direct neighbors that we are "hiding"
326    * from DV?
327    */
328   int hidden;
329 };
330
331
332 /**
333  * Struct where actual neighbor information is stored,
334  * referenced by min_heap and max_heap.  Freeing dealt
335  * with when items removed from hashmap.
336  */
337 struct DistantNeighbor
338 {
339   /**
340    * We keep distant neighbor's of the same referrer in a DLL.
341    */
342   struct DistantNeighbor *next;
343
344   /**
345    * We keep distant neighbor's of the same referrer in a DLL.
346    */
347   struct DistantNeighbor *prev;
348
349   /**
350    * Node in min heap
351    */
352   struct GNUNET_CONTAINER_HeapNode *min_loc;
353
354   /**
355    * Node in max heap
356    */
357   struct GNUNET_CONTAINER_HeapNode *max_loc;
358
359   /**
360    * Identity of referrer (next hop towards 'neighbor').
361    */
362   struct DirectNeighbor *referrer;
363
364   /**
365    * Identity of neighbor.
366    */
367   struct GNUNET_PeerIdentity identity;
368
369   /**
370    * PublicKey of neighbor.
371    */
372   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey;
373
374   /**
375    * Last time we received routing information from this peer
376    */
377   struct GNUNET_TIME_Absolute last_activity;
378
379   /**
380    * Cost to neighbor, used for actual distance vector computations
381    */
382   unsigned int cost;
383
384   /**
385    * Random identifier *we* use for this peer, to be used as shortcut
386    * instead of sending full peer id for each message
387    */
388   unsigned int our_id;
389
390   /**
391    * Random identifier the *referrer* uses for this peer.
392    */
393   unsigned int referrer_id;
394
395   /**
396    * Is this one of the direct neighbors that we are "hiding"
397    * from DV?
398    */
399   int hidden;
400
401 };
402
403 struct PeerIteratorContext
404 {
405   /**
406    * The actual context, to be freed later.
407    */
408   struct GNUNET_PEERINFO_IteratorContext *ic;
409
410   /**
411    * The neighbor about which we are concerned.
412    */
413   struct DirectNeighbor *neighbor;
414
415 };
416
417 /**
418  * Context used for creating hello messages when
419  * gossips are received.
420  */
421 struct HelloContext
422 {
423   /**
424    * Identity of distant neighbor.
425    */
426   struct GNUNET_PeerIdentity distant_peer;
427
428   /**
429    * Identity of direct neighbor, via which we send this message.
430    */
431   const struct GNUNET_PeerIdentity *direct_peer;
432
433   /**
434    * How many addresses do we need to add (always starts at 1, then set to 0)
435    */
436   int addresses_to_add;
437
438 };
439
440 struct DV_SendContext
441 {
442   /**
443    * The distant peer (should always match)
444    */
445   struct GNUNET_PeerIdentity *distant_peer;
446
447   /**
448    * The direct peer, we need to verify the referrer of.
449    */
450   struct GNUNET_PeerIdentity *direct_peer;
451
452   /**
453    * The message to be sent
454    */
455   struct GNUNET_MessageHeader *message;
456
457   /**
458    * The pre-built send result message.  Simply needs to be queued
459    * and freed once send has been called!
460    */
461   struct GNUNET_DV_SendResultMessage *send_result;
462
463   /**
464    * The size of the message being sent, may be larger
465    * than message->header.size because it's multiple
466    * messages packed into one!
467    */
468   size_t message_size;
469
470   /**
471    * How important is this message?
472    */
473   unsigned int importance;
474
475   /**
476    * Timeout for this message
477    */
478   struct GNUNET_TIME_Relative timeout;
479 };
480
481 /**
482  * Global construct
483  */
484 struct GNUNET_DV_Context
485 {
486   /**
487    * Map of PeerIdentifiers to 'struct GNUNET_dv_neighbor*'s for all
488    * directly connected peers.
489    */
490   struct GNUNET_CONTAINER_MultiHashMap *direct_neighbors;
491
492   /**
493    * Map of PeerIdentifiers to 'struct GNUNET_dv_neighbor*'s for
494    * peers connected via DV (extended neighborhood).  Does ALSO
495    * include any peers that are in 'direct_neighbors'; for those
496    * peers, the cost will be zero and the referrer all zeros.
497    */
498   struct GNUNET_CONTAINER_MultiHashMap *extended_neighbors;
499
500   /**
501    * We use the min heap (min refers to cost) to prefer
502    * gossipping about peers with small costs.
503    */
504   struct GNUNET_CONTAINER_Heap *neighbor_min_heap;
505
506   /**
507    * We use the max heap (max refers to cost) for general
508    * iterations over all peers and to remove the most costly
509    * connection if we have too many.
510    */
511   struct GNUNET_CONTAINER_Heap *neighbor_max_heap;
512
513   unsigned long long fisheye_depth;
514
515   unsigned long long max_table_size;
516
517   unsigned int neighbor_id_loc;
518
519   int closing;
520
521 };
522
523 static struct GNUNET_DV_Context ctx;
524
525 struct FindDestinationContext
526 {
527   unsigned int tid;
528   struct DistantNeighbor *dest;
529 };
530
531 struct DisconnectContext
532 {
533   /**
534    * Distant neighbor to get pid from.
535    */
536   struct DistantNeighbor *distant;
537
538   /**
539    * Direct neighbor that disconnected.
540    */
541   struct DirectNeighbor *direct;
542 };
543
544 /**
545  * We've been given a target ID based on the random numbers that
546  * we assigned to our DV-neighborhood.  Find the entry for the
547  * respective neighbor.
548  */
549 static int
550 find_destination (void *cls,
551                   struct GNUNET_CONTAINER_HeapNode *node,
552                   void *element, GNUNET_CONTAINER_HeapCostType cost)
553 {
554   struct FindDestinationContext *fdc = cls;
555   struct DistantNeighbor *dn = element;
556
557   if (fdc->tid != dn->our_id)
558     return GNUNET_YES;
559   fdc->dest = dn;
560   return GNUNET_NO;
561 }
562
563 /**
564  * Find a distant peer whose referrer_id matches what we're
565  * looking for.  For looking up a peer we've gossipped about
566  * but is now disconnected.  Need to do this because we don't
567  * want to remove those that may be accessible via a different
568  * route.
569  */
570 static int find_distant_peer (void *cls,
571                               const GNUNET_HashCode * key,
572                               void *value)
573 {
574   struct FindDestinationContext *fdc = cls;
575   struct DistantNeighbor *distant = value;
576
577   if (fdc->tid == distant->referrer_id)
578     {
579       fdc->dest = distant;
580       return GNUNET_NO;
581     }
582   return GNUNET_YES;
583 }
584
585 /**
586  * Function called to notify a client about the socket
587  * begin ready to queue more data.  "buf" will be
588  * NULL and "size" zero if the socket was closed for
589  * writing in the meantime.
590  *
591  * @param cls closure
592  * @param size number of bytes available in buf
593  * @param buf where the callee should write the message
594  * @return number of bytes written to buf
595  */
596 size_t transmit_to_plugin (void *cls,
597                            size_t size, void *buf)
598 {
599   char *cbuf = buf;
600   struct PendingMessage *reply;
601   size_t off;
602   size_t msize;
603
604   if (buf == NULL)
605     {
606       /* client disconnected */
607 #if DEBUG_DV
608       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s': buffer was NULL\n", "DHT");
609 #endif
610       return 0;
611     }
612   plugin_transmit_handle = NULL;
613   off = 0;
614   while ( (NULL != (reply = plugin_pending_head)) &&
615           (size >= off + (msize = ntohs (reply->msg->size))))
616     {
617 #if DEBUG_DV
618     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s' : transmit_notify (plugin) called with size %d\n", "dv service", msize);
619 #endif
620       GNUNET_CONTAINER_DLL_remove (plugin_pending_head,
621                                    plugin_pending_tail,
622                                    reply);
623       memcpy (&cbuf[off], reply->msg, msize);
624       GNUNET_free (reply);
625       off += msize;
626     }
627
628   if (plugin_pending_head != NULL)
629     plugin_transmit_handle = GNUNET_SERVER_notify_transmit_ready (client_handle,
630                                                                   ntohs(plugin_pending_head->msg->size),
631                                                                   GNUNET_TIME_UNIT_FOREVER_REL,
632                                                                   &transmit_to_plugin, NULL);
633
634   return off;
635 }
636
637 /**
638  * Send a message to the dv plugin.
639  *
640  * @param sender the direct sender of the message
641  * @param message the message to send to the plugin
642  *        (may be an encapsulated type)
643  * @param message_size the size of the message to be sent
644  * @param distant_neighbor the original sender of the message
645  * @param cost the cost to the original sender of the message
646  */
647 void send_to_plugin(const struct GNUNET_PeerIdentity * sender,
648                     const struct GNUNET_MessageHeader *message,
649                     size_t message_size,
650                     struct GNUNET_PeerIdentity *distant_neighbor,
651                     size_t cost)
652 {
653   struct GNUNET_DV_MessageReceived *received_msg;
654   struct PendingMessage *pending_message;
655 #if DEBUG_DV
656   struct GNUNET_MessageHeader * packed_message_header;
657   struct GNUNET_HELLO_Message *hello_msg;
658   struct GNUNET_PeerIdentity hello_identity;
659 #endif
660   char *sender_address;
661   size_t sender_address_len;
662   char *packed_msg_start;
663   int size;
664
665 #if DEBUG_DV
666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_to_plugin called with peer %s as sender\n", GNUNET_i2s(distant_neighbor));
667 #endif
668
669   if (memcmp(sender, distant_neighbor, sizeof(struct GNUNET_PeerIdentity)) != 0)
670   {
671     sender_address_len = sizeof(struct GNUNET_PeerIdentity) * 2;
672     sender_address = GNUNET_malloc(sender_address_len);
673     memcpy(sender_address, distant_neighbor, sizeof(struct GNUNET_PeerIdentity));
674     memcpy(&sender_address[sizeof(struct GNUNET_PeerIdentity)], sender, sizeof(struct GNUNET_PeerIdentity));
675   }
676   else
677   {
678     sender_address_len = sizeof(struct GNUNET_PeerIdentity);
679     sender_address = GNUNET_malloc(sender_address_len);
680     memcpy(sender_address, sender, sizeof(struct GNUNET_PeerIdentity));
681   }
682
683   size = sizeof(struct GNUNET_DV_MessageReceived) + sender_address_len + message_size;
684   received_msg = GNUNET_malloc(size);
685   received_msg->header.size = htons(size);
686   received_msg->header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_DV_RECEIVE);
687   received_msg->sender_address_len = htonl(sender_address_len);
688   received_msg->distance = htonl(cost);
689   received_msg->msg_len = htonl(message_size);
690   /* Set the sender in this message to be the original sender! */
691   memcpy(&received_msg->sender, distant_neighbor, sizeof(struct GNUNET_PeerIdentity));
692   /* Copy the intermediate sender to the end of the message, this is how the transport identifies this peer */
693   memcpy(&received_msg[1], sender_address, sender_address_len);
694   GNUNET_free(sender_address);
695   /* Copy the actual message after the sender */
696   packed_msg_start = (char *)&received_msg[1];
697   packed_msg_start = &packed_msg_start[sender_address_len];
698   memcpy(packed_msg_start, message, message_size);
699 #if DEBUG_DV
700   packed_message_header = (struct GNUNET_MessageHeader *)packed_msg_start;
701   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "dv service created received message. sender_address_len %lu, packed message len %d, total len %d\n", sender_address_len, ntohl(received_msg->msg_len), ntohs(received_msg->header.size));
702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "dv packed message len %d, type %d\n", ntohs(packed_message_header->size), ntohs(packed_message_header->type));
703   if (ntohs(packed_message_header->type) == GNUNET_MESSAGE_TYPE_HELLO)
704   {
705     hello_msg = (struct GNUNET_HELLO_Message *)packed_message_header;
706     GNUNET_assert(GNUNET_OK == GNUNET_HELLO_get_id(hello_msg, &hello_identity));
707     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Packed HELLO message is about peer %s\n", GNUNET_i2s(&hello_identity));
708   }
709 #endif
710   pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + size);
711   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
712   memcpy(&pending_message[1], received_msg, size);
713   GNUNET_free(received_msg);
714
715   GNUNET_CONTAINER_DLL_insert_after(plugin_pending_head, plugin_pending_tail, plugin_pending_tail, pending_message);
716
717   if (client_handle != NULL)
718     {
719       if (plugin_transmit_handle == NULL)
720         {
721           plugin_transmit_handle = GNUNET_SERVER_notify_transmit_ready (client_handle,
722                                                                         size, GNUNET_TIME_UNIT_FOREVER_REL,
723                                                                         &transmit_to_plugin, NULL);
724         }
725       else
726         {
727           GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Failed to queue message for plugin, must be one in progress already!!\n");
728         }
729     }
730 }
731
732
733 /**
734  * Function called to notify a client about the socket
735  * being ready to queue more data.  "buf" will be
736  * NULL and "size" zero if the socket was closed for
737  * writing in the meantime.
738  *
739  * @param cls closure
740  * @param size number of bytes available in buf
741  * @param buf where the callee should write the message
742  * @return number of bytes written to buf
743  */
744 size_t core_transmit_notify (void *cls,
745                              size_t size, void *buf)
746 {
747   char *cbuf = buf;
748   struct PendingMessage *reply;
749   struct PendingMessage *client_reply;
750   size_t off;
751   size_t msize;
752
753   if (buf == NULL)
754     {
755       /* client disconnected */
756 #if DEBUG_DV
757       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "`%s': buffer was NULL\n", "DHT");
758 #endif
759       return 0;
760     }
761
762   core_transmit_handle = NULL;
763   off = 0;
764   while ( (NULL != (reply = core_pending_head)) &&
765           (size >= off + (msize = ntohs (reply->msg->size))))
766     {
767 #if DEBUG_DV
768     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s' : transmit_notify (core) called with size %d\n", "dv service", msize);
769 #endif
770       GNUNET_CONTAINER_DLL_remove (core_pending_head,
771                                    core_pending_tail,
772                                    reply);
773       if (reply->send_result != NULL) /* Will only be non-null if a real client asked for this send */
774         {
775           client_reply = GNUNET_malloc(sizeof(struct PendingMessage) + sizeof(struct GNUNET_DV_SendResultMessage));
776           client_reply->msg = (struct GNUNET_MessageHeader *)&client_reply[1];
777           memcpy(&client_reply[1], reply->send_result, sizeof(struct GNUNET_DV_SendResultMessage));
778           GNUNET_free(reply->send_result);
779
780           GNUNET_CONTAINER_DLL_insert_after(plugin_pending_head, plugin_pending_tail, plugin_pending_tail, client_reply);
781           GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Queued client send receipt success message!\n");
782           if (client_handle != NULL)
783             {
784               if (plugin_transmit_handle == NULL)
785                 {
786                   plugin_transmit_handle = GNUNET_SERVER_notify_transmit_ready (client_handle,
787                                                                                 sizeof(struct GNUNET_DV_SendResultMessage),
788                                                                                 GNUNET_TIME_UNIT_FOREVER_REL,
789                                                                                 &transmit_to_plugin, NULL);
790                 }
791               else
792                 {
793                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to queue message for plugin, must be one in progress already!!\n");
794                 }
795             }
796         }
797       memcpy (&cbuf[off], reply->msg, msize);
798       GNUNET_free (reply);
799       off += msize;
800     }
801   return off;
802 }
803
804
805 /**
806  * Send a DV data message via DV.
807  *
808  * @param sender the original sender of the message
809  * @param specific_neighbor the specific DistantNeighbor to use, complete with referrer!
810  * @param send_context the send context
811  */
812 static int
813 send_message_via (const struct GNUNET_PeerIdentity * sender,
814               const struct DistantNeighbor * specific_neighbor,
815               struct DV_SendContext *send_context)
816 {
817   p2p_dv_MESSAGE_Data *toSend;
818   unsigned int msg_size;
819   unsigned int cost;
820   unsigned int recipient_id;
821   unsigned int sender_id;
822   struct DistantNeighbor *source;
823   struct PendingMessage *pending_message;
824 #if DEBUG_DV
825   char shortname[5];
826 #endif
827
828   msg_size = send_context->message_size + sizeof (p2p_dv_MESSAGE_Data);
829
830   if (specific_neighbor == NULL)
831     {
832       /* target unknown to us, drop! */
833       return GNUNET_SYSERR;
834     }
835   recipient_id = specific_neighbor->referrer_id;
836
837   source = GNUNET_CONTAINER_multihashmap_get (ctx.extended_neighbors,
838                                       &sender->hashPubKey);
839   if (source == NULL)
840     {
841       if (0 != (memcmp (&my_identity,
842                         sender, sizeof (struct GNUNET_PeerIdentity))))
843         {
844           /* sender unknown to us, drop! */
845           return GNUNET_SYSERR;
846         }
847       sender_id = 0;            /* 0 == us */
848     }
849   else
850     {
851       /* find out the number that we use when we gossip about
852          the sender */
853       sender_id = source->our_id;
854     }
855
856   cost = specific_neighbor->cost;
857   pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + msg_size);
858   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
859   pending_message->send_result = send_context->send_result;
860   toSend = (p2p_dv_MESSAGE_Data *)pending_message->msg;
861   toSend->header.size = htons (msg_size);
862   toSend->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DATA);
863   toSend->sender = htonl (sender_id);
864   toSend->recipient = htonl (recipient_id);
865   memcpy (&toSend[1], send_context->message, send_context->message_size);
866
867 #if DEBUG_DV
868   memcpy(&shortname, GNUNET_i2s(&specific_neighbor->identity), 4);
869   shortname[4] = '\0';
870   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s: Notifying core of send to destination `%s' via `%s' size %u\n", "DV", &shortname, GNUNET_i2s(&specific_neighbor->referrer->identity), msg_size);
871 #endif
872
873   GNUNET_CONTAINER_DLL_insert_after (core_pending_head,
874                                      core_pending_tail,
875                                      core_pending_tail,
876                                      pending_message);
877   if (core_transmit_handle == NULL)
878     core_transmit_handle = GNUNET_CORE_notify_transmit_ready(coreAPI, send_context->importance, send_context->timeout, &specific_neighbor->referrer->identity, msg_size, &core_transmit_notify, NULL);
879   else
880     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s': Failed to schedule pending transmission (must be one in progress!)\n", "dv service");
881
882   return (int) cost;
883 }
884
885
886 /**
887  * Send a DV data message via DV.
888  *
889  * @param recipient the ultimate recipient of this message
890  * @param sender the original sender of the message
891  * @param specific_neighbor the specific neighbor to send this message via
892  * @param message the packed message
893  * @param message_size size of the message
894  * @param importance what priority to send this message with
895  * @param timeout how long to possibly delay sending this message
896  */
897 static int
898 send_message (const struct GNUNET_PeerIdentity * recipient,
899               const struct GNUNET_PeerIdentity * sender,
900               const struct DistantNeighbor * specific_neighbor,
901               const struct GNUNET_MessageHeader * message,
902               size_t message_size,
903               unsigned int importance, struct GNUNET_TIME_Relative timeout)
904 {
905   p2p_dv_MESSAGE_Data *toSend;
906   unsigned int msg_size;
907   unsigned int cost;
908   unsigned int recipient_id;
909   unsigned int sender_id;
910   struct DistantNeighbor *target;
911   struct DistantNeighbor *source;
912   struct PendingMessage *pending_message;
913
914   msg_size = message_size + sizeof (p2p_dv_MESSAGE_Data);
915
916   target = GNUNET_CONTAINER_multihashmap_get (ctx.extended_neighbors,
917                                               &recipient->hashPubKey);
918   if (target == NULL)
919     {
920       /* target unknown to us, drop! */
921       return GNUNET_SYSERR;
922     }
923   recipient_id = target->referrer_id;
924
925   source = GNUNET_CONTAINER_multihashmap_get (ctx.extended_neighbors,
926                                       &sender->hashPubKey);
927   if (source == NULL)
928     {
929       if (0 != (memcmp (&my_identity,
930                         sender, sizeof (struct GNUNET_PeerIdentity))))
931         {
932           /* sender unknown to us, drop! */
933           return GNUNET_SYSERR;
934         }
935       sender_id = 0;            /* 0 == us */
936     }
937   else
938     {
939       /* find out the number that we use when we gossip about
940          the sender */
941       sender_id = source->our_id;
942     }
943
944   cost = target->cost;
945   pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + msg_size);
946   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
947   pending_message->send_result = NULL;
948   toSend = (p2p_dv_MESSAGE_Data *)pending_message->msg;
949   toSend->header.size = htons (msg_size);
950   toSend->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DATA);
951   toSend->sender = htonl (sender_id);
952   toSend->recipient = htonl (recipient_id);
953   memcpy (&toSend[1], message, message_size);
954
955   GNUNET_CONTAINER_DLL_insert_after (core_pending_head,
956                                      core_pending_tail,
957                                      core_pending_tail,
958                                      pending_message);
959 #if DEBUG_DV
960   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));
961 #endif
962   if (core_transmit_handle == NULL)
963     core_transmit_handle = GNUNET_CORE_notify_transmit_ready(coreAPI, importance, timeout, &target->referrer->identity, msg_size, &core_transmit_notify, NULL);
964
965   return (int) cost;
966 }
967
968
969 /**
970  * Core handler for dv data messages.  Whatever this message
971  * contains all we really have to do is rip it out of its
972  * DV layering and give it to our pal the DV plugin to report
973  * in with.
974  *
975  * @param cls closure
976  * @param peer peer which sent the message (immediate sender)
977  * @param message the message
978  * @param latency the latency of the connection we received the message from
979  * @param distance the distance to the immediate peer
980  */
981 static int handle_dv_data_message (void *cls,
982                              const struct GNUNET_PeerIdentity * peer,
983                              const struct GNUNET_MessageHeader * message,
984                              struct GNUNET_TIME_Relative latency,
985                              uint32_t distance)
986 {
987   const p2p_dv_MESSAGE_Data *incoming = (const p2p_dv_MESSAGE_Data *) message;
988   const struct GNUNET_MessageHeader *packed_message;
989   struct DirectNeighbor *dn;
990   struct DistantNeighbor *pos;
991   unsigned int sid;             /* Sender id */
992   unsigned int tid;             /* Target id */
993   struct GNUNET_PeerIdentity original_sender;
994   struct GNUNET_PeerIdentity destination;
995   struct FindDestinationContext fdc;
996   int ret;
997   size_t packed_message_size;
998   char *cbuf;
999   size_t offset;
1000
1001   packed_message_size = ntohs(incoming->header.size) - sizeof(p2p_dv_MESSAGE_Data);
1002
1003 #if DEBUG_DV
1004   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1005               "%s: Receives %s message size %d, packed message size %d!\n", "dv", "DV DATA", ntohs(incoming->header.size), packed_message_size);
1006 #endif
1007   if (ntohs (incoming->header.size) <  sizeof (p2p_dv_MESSAGE_Data) + sizeof (struct GNUNET_MessageHeader))
1008     {
1009 #if DEBUG_DV
1010   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1011               "`%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));
1012 #endif
1013       return GNUNET_SYSERR;
1014     }
1015
1016   dn = GNUNET_CONTAINER_multihashmap_get (ctx.direct_neighbors,
1017                                   &peer->hashPubKey);
1018   if (dn == NULL)
1019     {
1020 #if DEBUG_DV
1021       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1022                   "%s: dn NULL!\n", "dv");
1023 #endif
1024       return GNUNET_OK;
1025     }
1026   sid = ntohl (incoming->sender);
1027   pos = dn->referee_head;
1028   while ((NULL != pos) && (pos->referrer_id != sid))
1029     pos = pos->next;
1030   if (pos == NULL)
1031     {
1032 #if DEBUG_DV
1033       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1034                   "%s: unknown sender (%d), size of extended_peers is %d!\n", "dv", ntohl(incoming->sender), GNUNET_CONTAINER_multihashmap_size (ctx.extended_neighbors));
1035 #endif
1036       /* unknown sender */
1037       return GNUNET_OK;
1038     }
1039   original_sender = pos->identity;
1040   tid = ntohl (incoming->recipient);
1041   if (tid == 0)
1042     {
1043       /* 0 == us */
1044
1045       cbuf = (char *)&incoming[1];
1046       offset = 0;
1047       while(offset < packed_message_size)
1048         {
1049           packed_message = (struct GNUNET_MessageHeader *)&cbuf[offset];
1050 #if DEBUG_DV
1051           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1052                       "%s: Receives %s message for me, size %d type %d, cost %u!\n", "dv", "DV DATA", ntohs(packed_message->size), ntohs(packed_message->type), pos->cost);
1053 #endif
1054           GNUNET_break_op (ntohs (packed_message->type) != GNUNET_MESSAGE_TYPE_DV_GOSSIP);
1055           GNUNET_break_op (ntohs (packed_message->type) != GNUNET_MESSAGE_TYPE_DV_DATA);
1056           if ( (ntohs (packed_message->type) != GNUNET_MESSAGE_TYPE_DV_GOSSIP) &&
1057               (ntohs (packed_message->type) != GNUNET_MESSAGE_TYPE_DV_DATA) )
1058           {
1059             send_to_plugin(peer, packed_message, ntohs(packed_message->size), &pos->identity, pos->cost);
1060           }
1061           offset += ntohs(packed_message->size);
1062         }
1063
1064       return GNUNET_OK;
1065     }
1066   else
1067     {
1068       packed_message = (struct GNUNET_MessageHeader *)&incoming[1];
1069     }
1070
1071   /* FIXME: this is the *only* per-request operation we have in DV
1072      that is O(n) in relation to the number of connected peers; a
1073      hash-table lookup could easily solve this (minor performance
1074      issue) */
1075   fdc.tid = tid;
1076   fdc.dest = NULL;
1077   GNUNET_CONTAINER_heap_iterate (ctx.neighbor_max_heap,
1078                                  &find_destination, &fdc);
1079
1080 #if DEBUG_DV
1081       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082                   "%s: Receives %s message for someone else!\n", "dv", "DV DATA");
1083 #endif
1084
1085   if (fdc.dest == NULL)
1086     {
1087       return GNUNET_OK;
1088     }
1089   destination = fdc.dest->identity;
1090
1091   if (0 == memcmp (&destination, peer, sizeof (struct GNUNET_PeerIdentity)))
1092     {
1093       /* FIXME: create stat: routing loop-discard! */
1094 #if DEBUG_DV
1095       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "\n\n\nLoopy loo message\n\n\n");
1096 #endif
1097       return GNUNET_OK;
1098     }
1099
1100   /* At this point we have a message, and we need to forward it on to the
1101    * next DV hop.
1102    */
1103   /* FIXME: Can't send message on, we have to behave.
1104    * We have to tell core we have a message for the next peer, and let
1105    * transport do transport selection on how to get this message to 'em */
1106   /*ret = send_message (&destination,
1107                       &original_sender,
1108                       packed_message, DV_PRIORITY, DV_DELAY);*/
1109 #if DEBUG_DV
1110   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1111               "%s: Sends message size %d on!\n", "dv", packed_message_size);
1112 #endif
1113   ret = send_message(&destination, &original_sender, NULL, packed_message, packed_message_size, default_dv_priority, GNUNET_TIME_relative_get_forever());
1114
1115   if (ret != GNUNET_SYSERR)
1116     return GNUNET_OK;
1117   else
1118     return GNUNET_SYSERR;
1119 }
1120
1121
1122 /**
1123  *  Scheduled task which gossips about known direct peers to other connected
1124  *  peers.  Will run until called with reason shutdown.
1125  */
1126 static void
1127 neighbor_send_task (void *cls,
1128                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1129 {
1130   struct NeighborSendContext *send_context = cls;
1131 #if DEBUG_DV_GOSSIP_SEND
1132   char * encPeerAbout;
1133   char * encPeerTo;
1134 #endif
1135   struct DistantNeighbor *about;
1136   struct DirectNeighbor *to;
1137   struct FastGossipNeighborList *about_list;
1138
1139   p2p_dv_MESSAGE_NeighborInfo *message;
1140   struct PendingMessage *pending_message;
1141
1142   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1143   {
1144 #if DEBUG_DV_GOSSIP
1145   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1146               "%s: Called with reason shutdown, shutting down!\n",
1147               GNUNET_i2s(&my_identity));
1148 #endif
1149     send_context->task = GNUNET_SCHEDULER_NO_TASK;
1150     return;
1151   }
1152
1153   if (send_context->fast_gossip_list_head != NULL)
1154     {
1155       about_list = send_context->fast_gossip_list_head;
1156       about = send_context->fast_gossip_list_head->about;
1157       GNUNET_CONTAINER_DLL_remove(send_context->fast_gossip_list_head,
1158                                   send_context->fast_gossip_list_tail,
1159                                   about_list);
1160       GNUNET_free(about_list);
1161     }
1162   else
1163     {
1164       /* FIXME: this may become a problem, because the heap walk has only one internal "walker".  This means
1165        * that if two neighbor_send_tasks are operating in lockstep (which is quite possible, given default
1166        * values for all connected peers) there may be a serious bias as to which peers get gossiped about!
1167        * Probably the *best* way to fix would be to have an opaque pointer to the walk position passed as
1168        * part of the walk_get_next call.  Then the heap would have to keep a list of walks, or reset the walk
1169        * whenever a modification has been detected.  Yuck either way.  Perhaps we could iterate over the heap
1170        * once to get a list of peers to gossip about and gossip them over time... But then if one goes away
1171        * in the mean time that becomes nasty.  For now we'll just assume that the walking is done
1172        * asynchronously enough to avoid major problems (-;
1173        */
1174       about = GNUNET_CONTAINER_heap_walk_get_next (ctx.neighbor_min_heap);
1175     }
1176   to = send_context->toNeighbor;
1177
1178   if ((about != NULL) && (to != about->referrer /* split horizon */ ) &&
1179 #if SUPPORT_HIDING
1180       (about->hidden == GNUNET_NO) &&
1181 #endif
1182       (to != NULL) &&
1183       (0 != memcmp (&about->identity,
1184                         &to->identity, sizeof (struct GNUNET_PeerIdentity))) &&
1185       (about->pkey != NULL))
1186     {
1187 #if DEBUG_DV_GOSSIP_SEND
1188       encPeerAbout = GNUNET_strdup(GNUNET_i2s(&about->identity));
1189       encPeerTo = GNUNET_strdup(GNUNET_i2s(&to->identity));
1190       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1191                   "%s: Sending info about peer %s to directly connected peer %s\n",
1192                   GNUNET_i2s(&my_identity),
1193                   encPeerAbout, encPeerTo);
1194       GNUNET_free(encPeerAbout);
1195       GNUNET_free(encPeerTo);
1196 #endif
1197       pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + sizeof(p2p_dv_MESSAGE_NeighborInfo));
1198       pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1199       message = (p2p_dv_MESSAGE_NeighborInfo *)pending_message->msg;
1200       message->header.size = htons (sizeof (p2p_dv_MESSAGE_NeighborInfo));
1201       message->header.type = htons (GNUNET_MESSAGE_TYPE_DV_GOSSIP);
1202       message->cost = htonl (about->cost);
1203       message->neighbor_id = htonl (about->our_id);
1204
1205       memcpy (&message->pkey, about->pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1206       memcpy (&message->neighbor,
1207               &about->identity, sizeof (struct GNUNET_PeerIdentity));
1208
1209       GNUNET_CONTAINER_DLL_insert_after (core_pending_head,
1210                                          core_pending_tail,
1211                                          core_pending_tail,
1212                                          pending_message);
1213
1214       if (core_transmit_handle == NULL)
1215         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);
1216
1217     }
1218
1219   if (send_context->fast_gossip_list_head != NULL) /* If there are other peers in the fast list, schedule right away */
1220     {
1221       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "DV SERVICE: still in fast send mode\n");
1222       send_context->task = GNUNET_SCHEDULER_add_now(sched, &neighbor_send_task, send_context);
1223     }
1224   else
1225     {
1226       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "DV SERVICE: entering slow send mode\n");
1227       send_context->task = GNUNET_SCHEDULER_add_delayed(sched, GNUNET_DV_DEFAULT_SEND_INTERVAL, &neighbor_send_task, send_context);
1228     }
1229
1230   return;
1231 }
1232
1233
1234 /**
1235  * Handle START-message.  This is the first message sent to us
1236  * by the client (can only be one!).
1237  *
1238  * @param cls closure (always NULL)
1239  * @param client identification of the client
1240  * @param message the actual message
1241  */
1242 static void
1243 handle_start (void *cls,
1244               struct GNUNET_SERVER_Client *client,
1245               const struct GNUNET_MessageHeader *message)
1246 {
1247
1248 #if DEBUG_DV
1249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1250               "Received `%s' request from client\n", "START");
1251 #endif
1252
1253   client_handle = client;
1254
1255   GNUNET_SERVER_client_keep(client_handle);
1256   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1257 }
1258
1259
1260 /**
1261  * Iterate over hash map entries for a distant neighbor,
1262  * if direct neighbor matches context call send message
1263  *
1264  * @param cls closure, a DV_SendContext
1265  * @param key current key code
1266  * @param value value in the hash map
1267  * @return GNUNET_YES if we should continue to
1268  *         iterate,
1269  *         GNUNET_NO if not.
1270  */
1271 int send_iterator (void *cls,
1272                    const GNUNET_HashCode * key,
1273                    void *value)
1274 {
1275   struct DV_SendContext *send_context = cls;
1276   struct DistantNeighbor *distant_neighbor = value;
1277
1278   if (memcmp(distant_neighbor->referrer, send_context->direct_peer, sizeof(struct GNUNET_PeerIdentity)) == 0) /* They match, send and free */
1279     {
1280       send_message_via(&my_identity, distant_neighbor, send_context);
1281       return GNUNET_NO;
1282     }
1283   return GNUNET_YES;
1284 }
1285
1286 /**
1287  * Service server's handler for message send requests (which come
1288  * bubbling up to us through the DV plugin).
1289  *
1290  * @param cls closure
1291  * @param client identification of the client
1292  * @param message the actual message
1293  */
1294 void handle_dv_send_message (void *cls,
1295                              struct GNUNET_SERVER_Client * client,
1296                              const struct GNUNET_MessageHeader * message)
1297 {
1298   struct GNUNET_DV_SendMessage *send_msg;
1299   struct GNUNET_DV_SendResultMessage *send_result_msg;
1300   struct PendingMessage *pending_message;
1301   size_t address_len;
1302   size_t message_size;
1303   struct GNUNET_PeerIdentity *destination;
1304   struct GNUNET_PeerIdentity *direct;
1305   struct GNUNET_MessageHeader *message_buf;
1306   char *temp_pos;
1307   int offset;
1308   static struct GNUNET_CRYPTO_HashAsciiEncoded dest_hash;
1309   struct DV_SendContext *send_context;
1310
1311   if (client_handle == NULL)
1312   {
1313     client_handle = client;
1314     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1315               "%s: Setting initial client handle, never received `%s' message?\n", "dv", "START");
1316   }
1317   else if (client_handle != client)
1318   {
1319     client_handle = client;
1320     /* What should we do in this case, assert fail or just log the warning? */
1321     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1322                 "%s: Setting client handle (was a different client!)!\n", "dv");
1323   }
1324
1325   GNUNET_assert(ntohs(message->size) > sizeof(struct GNUNET_DV_SendMessage));
1326   send_msg = (struct GNUNET_DV_SendMessage *)message;
1327
1328   address_len = ntohl(send_msg->addrlen);
1329   GNUNET_assert(address_len == sizeof(struct GNUNET_PeerIdentity) * 2);
1330   message_size = ntohl(send_msg->msgbuf_size);
1331
1332 #if 1
1333   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1334               "%s: Receives %s message size %u!\n\n\n", "dv", "SEND", message_size);
1335 #endif
1336   GNUNET_assert(ntohs(message->size) == sizeof(struct GNUNET_DV_SendMessage) + address_len + message_size);
1337   destination = GNUNET_malloc(sizeof(struct GNUNET_PeerIdentity));
1338   direct = GNUNET_malloc(sizeof(struct GNUNET_PeerIdentity));
1339   message_buf = GNUNET_malloc(message_size);
1340
1341   temp_pos = (char *)&send_msg[1]; /* Set pointer to end of message */
1342   offset = 0; /* Offset starts at zero */
1343
1344   memcpy(destination, &temp_pos[offset], sizeof(struct GNUNET_PeerIdentity));
1345   offset += sizeof(struct GNUNET_PeerIdentity);
1346
1347   memcpy(direct, &temp_pos[offset], sizeof(struct GNUNET_PeerIdentity));
1348   offset += sizeof(struct GNUNET_PeerIdentity);
1349
1350
1351   memcpy(message_buf, &temp_pos[offset], message_size);
1352   if (memcmp(&send_msg->target, destination, sizeof(struct GNUNET_PeerIdentity)) != 0)
1353     {
1354       GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash); /* GNUNET_i2s won't properly work, need to hash one ourselves */
1355       dest_hash.encoding[4] = '\0';
1356       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);
1357     }
1358
1359 #if 1
1360   GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash); /* GNUNET_i2s won't properly work, need to hash one ourselves */
1361   dest_hash.encoding[4] = '\0';
1362   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "DV SEND called with message of size %d type %d, destination `%s' via `%s'\n", message_size, ntohs(message_buf->type), (const char *)&dest_hash.encoding, GNUNET_i2s(direct));
1363 #endif
1364   send_context = GNUNET_malloc(sizeof(struct DV_SendContext));
1365
1366   send_result_msg = GNUNET_malloc(sizeof(struct GNUNET_DV_SendResultMessage));
1367   send_result_msg->header.size = htons(sizeof(struct GNUNET_DV_SendResultMessage));
1368   send_result_msg->header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND_RESULT);
1369   send_result_msg->uid = send_msg->uid; /* No need to ntohl->htonl this */
1370
1371   send_context->importance = ntohl(send_msg->priority);
1372   send_context->timeout = send_msg->timeout;
1373   send_context->direct_peer = direct;
1374   send_context->distant_peer = destination;
1375   send_context->message = message_buf;
1376   send_context->message_size = message_size;
1377   send_context->send_result = send_result_msg;
1378
1379   /* In bizarro world GNUNET_SYSERR indicates that we succeeded */
1380   if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple(ctx.extended_neighbors, &destination->hashPubKey, &send_iterator, send_context))
1381     {
1382       send_result_msg->result = htons(1);
1383       pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + sizeof(struct GNUNET_DV_SendResultMessage));
1384       pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1385       memcpy(&pending_message[1], send_result_msg, sizeof(struct GNUNET_DV_SendResultMessage));
1386       GNUNET_free(send_result_msg);
1387
1388       GNUNET_CONTAINER_DLL_insert_after(plugin_pending_head, plugin_pending_tail, plugin_pending_tail, pending_message);
1389
1390       if (client_handle != NULL)
1391         {
1392           if (plugin_transmit_handle == NULL)
1393             {
1394               plugin_transmit_handle = GNUNET_SERVER_notify_transmit_ready (client_handle,
1395                                                                             sizeof(struct GNUNET_DV_SendResultMessage),
1396                                                                             GNUNET_TIME_UNIT_FOREVER_REL,
1397                                                                             &transmit_to_plugin, NULL);
1398             }
1399           else
1400             {
1401               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to queue message for plugin, must be one in progress already!!\n");
1402             }
1403         }
1404       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "DV SEND failed to send message to destination `%s' via `%s'\n", (const char *)&dest_hash.encoding, GNUNET_i2s(direct));
1405     }
1406   else
1407     {
1408
1409     }
1410
1411   GNUNET_free(message_buf);
1412   GNUNET_free(send_context);
1413   GNUNET_free(direct);
1414   GNUNET_free(destination);
1415
1416   GNUNET_SERVER_receive_done(client, GNUNET_OK);
1417 }
1418
1419 /** Forward declarations **/
1420 static int handle_dv_gossip_message (void *cls,
1421                                      const struct GNUNET_PeerIdentity *peer,
1422                                      const struct GNUNET_MessageHeader *message,
1423                                      struct GNUNET_TIME_Relative latency,
1424                                      uint32_t distance);
1425
1426 static int handle_dv_disconnect_message (void *cls,
1427                                          const struct GNUNET_PeerIdentity *peer,
1428                                          const struct GNUNET_MessageHeader *message,
1429                                          struct GNUNET_TIME_Relative latency,
1430                                          uint32_t distance);
1431 /** End forward declarations **/
1432
1433
1434 /**
1435  * List of handlers for the messages understood by this
1436  * service.
1437  *
1438  * Hmm... will we need to register some handlers with core and
1439  * some handlers with our server here?  Because core should be
1440  * getting the incoming DV messages (from whichever lower level
1441  * transport) and then our server should be getting messages
1442  * from the dv_plugin, right?
1443  */
1444 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1445   {&handle_dv_data_message, GNUNET_MESSAGE_TYPE_DV_DATA, 0},
1446   {&handle_dv_gossip_message, GNUNET_MESSAGE_TYPE_DV_GOSSIP, 0},
1447   {&handle_dv_disconnect_message, GNUNET_MESSAGE_TYPE_DV_DISCONNECT, 0},
1448   {NULL, 0, 0}
1449 };
1450
1451 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
1452   {&handle_dv_send_message, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND, 0},
1453   {&handle_start, NULL, GNUNET_MESSAGE_TYPE_DV_START, 0},
1454   {NULL, NULL, 0, 0}
1455 };
1456
1457 /**
1458  * Free a DistantNeighbor node, including removing it
1459  * from the referer's list.
1460  */
1461 static void
1462 distant_neighbor_free (struct DistantNeighbor *referee)
1463 {
1464   struct DirectNeighbor *referrer;
1465
1466   referrer = referee->referrer;
1467   if (referrer != NULL)
1468     {
1469       GNUNET_CONTAINER_DLL_remove (referrer->referee_head,
1470                          referrer->referee_tail, referee);
1471     }
1472   GNUNET_CONTAINER_heap_remove_node (ctx.neighbor_max_heap, referee->max_loc);
1473   GNUNET_CONTAINER_heap_remove_node (ctx.neighbor_min_heap, referee->min_loc);
1474   GNUNET_CONTAINER_multihashmap_remove_all (ctx.extended_neighbors,
1475                                     &referee->identity.hashPubKey);
1476   GNUNET_free (referee->pkey);
1477   GNUNET_free (referee);
1478 }
1479
1480 /**
1481  * Free a DirectNeighbor node, including removing it
1482  * from the referer's list.
1483  */
1484 static void
1485 direct_neighbor_free (struct DirectNeighbor *direct)
1486 {
1487   struct NeighborSendContext *send_context;
1488   struct FastGossipNeighborList *about_list;
1489   struct FastGossipNeighborList *prev_about;
1490
1491   send_context = direct->send_context;
1492
1493   if (send_context->task != GNUNET_SCHEDULER_NO_TASK)
1494     GNUNET_SCHEDULER_cancel(sched, send_context->task);
1495
1496   about_list = send_context->fast_gossip_list_head;
1497   while (about_list != NULL)
1498     {
1499       GNUNET_CONTAINER_DLL_remove(send_context->fast_gossip_list_head, send_context->fast_gossip_list_tail, about_list);
1500       prev_about = about_list;
1501       about_list = about_list->next;
1502       GNUNET_free(prev_about);
1503     }
1504   GNUNET_free(send_context);
1505   GNUNET_free(direct);
1506 }
1507
1508 /**
1509  * Multihashmap iterator for sending out disconnect messages
1510  * for a peer.
1511  *
1512  * @param cls the peer that was disconnected
1513  * @param key key value stored under
1514  * @param value the direct neighbor to send disconnect to
1515  *
1516  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1517  */
1518 static int schedule_disconnect_messages (void *cls,
1519                                     const GNUNET_HashCode * key,
1520                                     void *value)
1521 {
1522   struct DisconnectContext *disconnect_context = cls;
1523   struct DirectNeighbor *disconnected = disconnect_context->direct;
1524   struct DirectNeighbor *notify = value;
1525   struct PendingMessage *pending_message;
1526   p2p_dv_MESSAGE_Disconnect *disconnect_message;
1527
1528   if (memcmp(&notify->identity, &disconnected->identity, sizeof(struct GNUNET_PeerIdentity)) == 0)
1529     return GNUNET_YES; /* Don't send disconnect message to peer that disconnected! */
1530
1531   pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + sizeof(p2p_dv_MESSAGE_Disconnect));
1532   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1533   disconnect_message = (p2p_dv_MESSAGE_Disconnect *)pending_message->msg;
1534   disconnect_message->header.size = htons (sizeof (p2p_dv_MESSAGE_Disconnect));
1535   disconnect_message->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DISCONNECT);
1536   disconnect_message->peer_id = htonl(disconnect_context->distant->our_id);
1537
1538   GNUNET_CONTAINER_DLL_insert_after (core_pending_head,
1539                                      core_pending_tail,
1540                                      core_pending_tail,
1541                                      pending_message);
1542
1543   if (core_transmit_handle == NULL)
1544     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);
1545
1546   return GNUNET_YES;
1547 }
1548
1549 /**
1550  * Multihashmap iterator for freeing extended neighbors.
1551  *
1552  * @param cls NULL
1553  * @param key key value stored under
1554  * @param value the distant neighbor to be freed
1555  *
1556  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1557  */
1558 static int free_extended_neighbors (void *cls,
1559                                     const GNUNET_HashCode * key,
1560                                     void *value)
1561 {
1562   struct DistantNeighbor *distant = value;
1563   distant_neighbor_free(distant);
1564   return GNUNET_YES;
1565 }
1566
1567 /**
1568  * Multihashmap iterator for freeing direct neighbors.
1569  *
1570  * @param cls NULL
1571  * @param key key value stored under
1572  * @param value the direct neighbor to be freed
1573  *
1574  * @return GNUNET_YES to continue iteration, GNUNET_NO to stop
1575  */
1576 static int free_direct_neighbors (void *cls,
1577                                     const GNUNET_HashCode * key,
1578                                     void *value)
1579 {
1580   struct DirectNeighbor *direct = value;
1581   direct_neighbor_free(direct);
1582   return GNUNET_YES;
1583 }
1584
1585 /**
1586  * Task run during shutdown.
1587  *
1588  * @param cls unused
1589  * @param tc unused
1590  */
1591 static void
1592 shutdown_task (void *cls,
1593                const struct GNUNET_SCHEDULER_TaskContext *tc)
1594 {
1595 #if DEBUG_DV
1596   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "calling CORE_DISCONNECT\n");
1597 #endif
1598   GNUNET_CONTAINER_multihashmap_iterate(ctx.extended_neighbors, &free_extended_neighbors, NULL);
1599   GNUNET_CONTAINER_multihashmap_destroy(ctx.extended_neighbors);
1600   GNUNET_CONTAINER_multihashmap_iterate(ctx.direct_neighbors, &free_direct_neighbors, NULL);
1601   GNUNET_CONTAINER_multihashmap_destroy(ctx.direct_neighbors);
1602
1603   GNUNET_CONTAINER_heap_destroy(ctx.neighbor_max_heap);
1604   GNUNET_CONTAINER_heap_destroy(ctx.neighbor_min_heap);
1605
1606   GNUNET_CORE_disconnect (coreAPI);
1607   GNUNET_PEERINFO_disconnect(peerinfo_handle);
1608 #if DEBUG_DV
1609   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "CORE_DISCONNECT completed\n");
1610 #endif
1611 }
1612
1613 /**
1614  * To be called on core init/fail.
1615  */
1616 void core_init (void *cls,
1617                 struct GNUNET_CORE_Handle * server,
1618                 const struct GNUNET_PeerIdentity *identity,
1619                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded * publicKey)
1620 {
1621
1622   if (server == NULL)
1623     {
1624       GNUNET_SCHEDULER_cancel(sched, cleanup_task);
1625       GNUNET_SCHEDULER_add_now(sched, &shutdown_task, NULL);
1626       return;
1627     }
1628 #if DEBUG_DV
1629   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1630               "%s: Core connection initialized, I am peer: %s\n", "dv", GNUNET_i2s(identity));
1631 #endif
1632   memcpy(&my_identity, identity, sizeof(struct GNUNET_PeerIdentity));
1633   coreAPI = server;
1634 }
1635
1636 /**
1637  * Iterator over hash map entries.
1638  *
1639  * @param cls closure
1640  * @param key current key code
1641  * @param value value in the hash map
1642  * @return GNUNET_YES if we should continue to
1643  *         iterate,
1644  *         GNUNET_NO if not.
1645  */
1646 static int add_pkey_to_extended (void *cls,
1647                                  const GNUNET_HashCode * key,
1648                                  void *value)
1649 {
1650   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey = cls;
1651   struct DistantNeighbor *distant_neighbor = value;
1652
1653   if (distant_neighbor->pkey == NULL)
1654   {
1655     distant_neighbor->pkey = GNUNET_malloc(sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1656     memcpy(distant_neighbor->pkey, pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1657   }
1658
1659   return GNUNET_YES;
1660 }
1661
1662 /**
1663  * Iterator over hash map entries.
1664  *
1665  * @param cls closure
1666  * @param key current key code
1667  * @param value value in the hash map
1668  * @return GNUNET_YES if we should continue to
1669  *         iterate,
1670  *         GNUNET_NO if not.
1671  */
1672 static int update_matching_neighbors (void *cls,
1673                                       const GNUNET_HashCode * key,
1674                                       void *value)
1675 {
1676   struct NeighborUpdateInfo * update_info = cls;
1677   struct DistantNeighbor *distant_neighbor = value;
1678
1679   if (update_info->referrer == distant_neighbor->referrer) /* Direct neighbor matches, update it's info and return GNUNET_NO */
1680   {
1681     /* same referrer, cost change! */
1682     GNUNET_CONTAINER_heap_update_cost (ctx.neighbor_max_heap,
1683                                        update_info->neighbor->max_loc, update_info->cost);
1684     GNUNET_CONTAINER_heap_update_cost (ctx.neighbor_min_heap,
1685                                        update_info->neighbor->min_loc, update_info->cost);
1686     update_info->neighbor->last_activity = update_info->now;
1687     update_info->neighbor->cost = update_info->cost;
1688     return GNUNET_NO;
1689   }
1690
1691   return GNUNET_YES;
1692 }
1693
1694
1695 #if DEBUG_DV_GOSSIP
1696 /**
1697  * Iterator over hash map entries.
1698  *
1699  * @param cls closure (NULL)
1700  * @param key current key code
1701  * @param value value in the hash map (DistantNeighbor)
1702  * @return GNUNET_YES if we should continue to
1703  *         iterate,
1704  *         GNUNET_NO if not.
1705  */
1706 int print_neighbors (void *cls,
1707                      const GNUNET_HashCode * key,
1708                      void *value)
1709 {
1710   struct DistantNeighbor *distant_neighbor = value;
1711   char my_shortname[5];
1712   char referrer_shortname[5];
1713   memcpy(&my_shortname, GNUNET_i2s(&my_identity), 4);
1714   my_shortname[4] = '\0';
1715   memcpy(&referrer_shortname, GNUNET_i2s(&distant_neighbor->referrer->identity), 4);
1716   referrer_shortname[4] = '\0';
1717
1718   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s' %s: Peer `%s', distance %d, referrer `%s'\n", &my_shortname, "DV", GNUNET_i2s(&distant_neighbor->identity), distant_neighbor->cost, &referrer_shortname);
1719   return GNUNET_YES;
1720 }
1721
1722 #endif
1723
1724 /**
1725  * Handles when a peer is either added due to being newly connected
1726  * or having been gossiped about, also called when the cost for a neighbor
1727  * needs to be updated.
1728  *
1729  * @param peer identity of the peer whose info is being added/updated
1730  * @param pkey public key of the peer whose info is being added/updated
1731  * @param referrer_peer_id id to use when sending to 'peer'
1732  * @param referrer if this is a gossiped peer, who did we hear it from?
1733  * @param cost the cost of communicating with this peer via 'referrer'
1734  */
1735 static void
1736 addUpdateNeighbor (const struct GNUNET_PeerIdentity * peer, struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
1737                    unsigned int referrer_peer_id,
1738                    struct DirectNeighbor *referrer, unsigned int cost)
1739 {
1740   struct DistantNeighbor *neighbor;
1741   struct DistantNeighbor *max;
1742   struct GNUNET_TIME_Absolute now;
1743   struct NeighborUpdateInfo *neighbor_update;
1744   unsigned int our_id;
1745
1746   now = GNUNET_TIME_absolute_get ();
1747   our_id = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, RAND_MAX - 1) + 1;
1748
1749   neighbor = GNUNET_CONTAINER_multihashmap_get (ctx.extended_neighbors,
1750                                                 &peer->hashPubKey);
1751   neighbor_update = GNUNET_malloc(sizeof(struct NeighborUpdateInfo));
1752   neighbor_update->neighbor = neighbor;
1753   neighbor_update->cost = cost;
1754   neighbor_update->now = now;
1755   neighbor_update->referrer = referrer;
1756
1757   /* Either we do not know this peer, or we already do but via a different immediate peer */
1758   if ((neighbor == NULL) ||
1759       (GNUNET_CONTAINER_multihashmap_get_multiple(ctx.extended_neighbors,
1760                                                   &peer->hashPubKey,
1761                                                   &update_matching_neighbors,
1762                                                   neighbor_update) != GNUNET_SYSERR))
1763     {
1764       /* new neighbor! */
1765       if (cost > ctx.fisheye_depth)
1766         {
1767           /* too costly */
1768           GNUNET_free(neighbor_update);
1769           return;
1770         }
1771       if (ctx.max_table_size <=
1772           GNUNET_CONTAINER_multihashmap_size (ctx.extended_neighbors))
1773         {
1774           /* remove most expensive entry */
1775           max = GNUNET_CONTAINER_heap_peek (ctx.neighbor_max_heap);
1776           if (cost > max->cost)
1777             {
1778               /* new entry most expensive, don't create */
1779               GNUNET_free(neighbor_update);
1780               return;
1781             }
1782           if (max->cost > 1)
1783             {
1784               /* only free if this is not a direct connection;
1785                  we could theoretically have more direct
1786                  connections than DV entries allowed total! */
1787               distant_neighbor_free (max);
1788             }
1789         }
1790
1791       neighbor = GNUNET_malloc (sizeof (struct DistantNeighbor));
1792       GNUNET_CONTAINER_DLL_insert (referrer->referee_head,
1793                          referrer->referee_tail, neighbor);
1794       neighbor->max_loc = GNUNET_CONTAINER_heap_insert (ctx.neighbor_max_heap,
1795                                                         neighbor, cost);
1796       neighbor->min_loc = GNUNET_CONTAINER_heap_insert (ctx.neighbor_min_heap,
1797                                                         neighbor, cost);
1798       neighbor->referrer = referrer;
1799       memcpy (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity));
1800       if (pkey != NULL) /* pkey will be null on direct neighbor addition */
1801       {
1802         neighbor->pkey = GNUNET_malloc(sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1803         memcpy (neighbor->pkey, pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1804       }
1805       else
1806         neighbor->pkey = pkey;
1807
1808       neighbor->last_activity = now;
1809       neighbor->cost = cost;
1810       neighbor->referrer_id = referrer_peer_id;
1811       neighbor->our_id = our_id;
1812       neighbor->hidden =
1813         (cost == DIRECT_NEIGHBOR_COST) ? (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 4) ==
1814                        0) : GNUNET_NO;
1815       GNUNET_CONTAINER_multihashmap_put (ctx.extended_neighbors, &peer->hashPubKey,
1816                                  neighbor,
1817                                  GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1818     }
1819   else
1820     {
1821 #if DEBUG_DV_GOSSIP
1822       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1823                   "%s: Already know peer %s distance %d, referrer id %d!\n", "dv", GNUNET_i2s(peer), cost, referrer_peer_id);
1824 #endif
1825     }
1826 #if DEBUG_DV_GOSSIP
1827     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1828                 "%s: Size of extended_neighbors is %d\n", "dv", GNUNET_CONTAINER_multihashmap_size(ctx.extended_neighbors));
1829     GNUNET_CONTAINER_multihashmap_iterate(ctx.extended_neighbors, &print_neighbors, NULL);
1830 #endif
1831   GNUNET_free(neighbor_update);
1832
1833 }
1834
1835
1836 static size_t
1837 generate_hello_address (void *cls, size_t max, void *buf)
1838 {
1839   struct HelloContext *hello_context = cls;
1840   char *addr_buffer;
1841   size_t offset;
1842   size_t size;
1843   size_t ret;
1844
1845   if (hello_context->addresses_to_add == 0)
1846     return 0;
1847
1848   /* Hello "address" will be concatenation of distant peer and direct peer identities */
1849   size = 2 * sizeof(struct GNUNET_PeerIdentity);
1850   GNUNET_assert(max >= size);
1851
1852   addr_buffer = GNUNET_malloc(size);
1853   offset = 0;
1854   /* Copy the distant peer identity to buffer */
1855   memcpy(addr_buffer, &hello_context->distant_peer, sizeof(struct GNUNET_PeerIdentity));
1856   offset += sizeof(struct GNUNET_PeerIdentity);
1857   /* Copy the direct peer identity to buffer */
1858   memcpy(&addr_buffer[offset], hello_context->direct_peer, sizeof(struct GNUNET_PeerIdentity));
1859   ret = GNUNET_HELLO_add_address ("dv",
1860                                   GNUNET_TIME_relative_to_absolute
1861                                   (GNUNET_TIME_UNIT_HOURS), addr_buffer, size,
1862                                   buf, max);
1863
1864   hello_context->addresses_to_add--;
1865
1866   GNUNET_free(addr_buffer);
1867   return ret;
1868 }
1869
1870
1871 /**
1872  * Core handler for dv disconnect messages.  These will be used
1873  * by us to tell transport via the dv plugin that a peer can
1874  * no longer be contacted by us via a certain address.  We should
1875  * then propagate these messages on, given that the distance to
1876  * the peer indicates we would have gossiped about it to others.
1877  *
1878  * @param cls closure
1879  * @param peer peer which sent the message (immediate sender)
1880  * @param message the message
1881  * @param latency the latency of the connection we received the message from
1882  * @param distance the distance to the immediate peer
1883  */
1884 static int handle_dv_disconnect_message (void *cls,
1885                                          const struct GNUNET_PeerIdentity *peer,
1886                                          const struct GNUNET_MessageHeader *message,
1887                                          struct GNUNET_TIME_Relative latency,
1888                                          uint32_t distance)
1889 {
1890   struct DirectNeighbor *referrer;
1891   struct DistantNeighbor *distant;
1892   p2p_dv_MESSAGE_Disconnect *enc_message = (p2p_dv_MESSAGE_Disconnect *)message;
1893
1894   if (ntohs (message->size) < sizeof (p2p_dv_MESSAGE_Disconnect))
1895     {
1896       return GNUNET_SYSERR;     /* invalid message */
1897     }
1898
1899   referrer = GNUNET_CONTAINER_multihashmap_get (ctx.direct_neighbors,
1900                                                 &peer->hashPubKey);
1901   if (referrer == NULL)
1902     return GNUNET_OK;
1903
1904   distant = referrer->referee_head;
1905   while (distant != NULL)
1906     {
1907       if (distant->referrer_id == ntohl(enc_message->peer_id))
1908         {
1909           distant_neighbor_free(distant);
1910         }
1911     }
1912
1913   return GNUNET_OK;
1914 }
1915
1916
1917 /**
1918  * Core handler for dv gossip messages.  These will be used
1919  * by us to create a HELLO message for the newly peer containing
1920  * which direct peer we can connect through, and what the cost
1921  * is.  This HELLO will then be scheduled for validation by the
1922  * transport service so that it can be used by all others.
1923  *
1924  * @param cls closure
1925  * @param peer peer which sent the message (immediate sender)
1926  * @param message the message
1927  * @param latency the latency of the connection we received the message from
1928  * @param distance the distance to the immediate peer
1929  */
1930 static int handle_dv_gossip_message (void *cls,
1931                                      const struct GNUNET_PeerIdentity *peer,
1932                                      const struct GNUNET_MessageHeader *message,
1933                                      struct GNUNET_TIME_Relative latency,
1934                                      uint32_t distance)
1935 {
1936   struct HelloContext *hello_context;
1937   struct GNUNET_HELLO_Message *hello_msg;
1938   struct DirectNeighbor *referrer;
1939   p2p_dv_MESSAGE_NeighborInfo *enc_message = (p2p_dv_MESSAGE_NeighborInfo *)message;
1940
1941   if (ntohs (message->size) < sizeof (p2p_dv_MESSAGE_NeighborInfo))
1942     {
1943       return GNUNET_SYSERR;     /* invalid message */
1944     }
1945
1946 #if DEBUG_DV_GOSSIP_RECEIPT
1947   char * encPeerAbout;
1948   char * encPeerFrom;
1949
1950   encPeerAbout = GNUNET_strdup(GNUNET_i2s(&enc_message->neighbor));
1951   encPeerFrom = GNUNET_strdup(GNUNET_i2s(peer));
1952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1953               "%s: Receives %s message from peer %s about peer %s distance %d!\n", "dv", "DV GOSSIP", encPeerFrom, encPeerAbout, ntohl (enc_message->cost) + 1);
1954   GNUNET_free(encPeerAbout);
1955   GNUNET_free(encPeerFrom);
1956 #endif
1957
1958   referrer = GNUNET_CONTAINER_multihashmap_get (ctx.direct_neighbors,
1959                                                 &peer->hashPubKey);
1960   if (referrer == NULL)
1961     return GNUNET_OK;
1962
1963   addUpdateNeighbor (&enc_message->neighbor, &enc_message->pkey,
1964                      ntohl (enc_message->neighbor_id),
1965                      referrer, ntohl (enc_message->cost) + 1);
1966
1967   hello_context = GNUNET_malloc(sizeof(struct HelloContext));
1968   hello_context->direct_peer = peer;
1969   memcpy(&hello_context->distant_peer, &enc_message->neighbor, sizeof(struct GNUNET_PeerIdentity));
1970   hello_context->addresses_to_add = 1;
1971   hello_msg = GNUNET_HELLO_create(&enc_message->pkey, &generate_hello_address, hello_context);
1972
1973   send_to_plugin(hello_context->direct_peer, GNUNET_HELLO_get_header(hello_msg), GNUNET_HELLO_size(hello_msg), &hello_context->distant_peer, ntohl(enc_message->cost) + 1);
1974   GNUNET_free(hello_context);
1975   GNUNET_free(hello_msg);
1976   return GNUNET_OK;
1977 }
1978
1979
1980 /**
1981  * Iterate over all currently known peers, add them to the
1982  * fast gossip list for this peer so we get DV routing information
1983  * out as fast as possible!
1984  *
1985  * @param cls the direct neighbor we will gossip to
1986  * @param key the hashcode of the peer
1987  * @param value the distant neighbor we should add to the list
1988  *
1989  * @return GNUNET_YES to continue iteration, GNUNET_NO otherwise
1990  */
1991 static int add_all_extended_peers (void *cls,
1992                                    const GNUNET_HashCode * key,
1993                                    void *value)
1994 {
1995   struct NeighborSendContext *send_context = (struct NeighborSendContext *)cls;
1996   struct DistantNeighbor *distant = (struct DistantNeighbor *)value;
1997   struct FastGossipNeighborList *gossip_entry;
1998
1999   if (memcmp(&send_context->toNeighbor->identity, &distant->identity, sizeof(struct GNUNET_PeerIdentity)) == 0)
2000     return GNUNET_YES; /* Don't gossip to a peer about itself! */
2001
2002   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "DV SERVICE: adding extended neighbor to fast send list\n");
2003 #if SUPPORT_HIDING
2004   if (distant->hidden == GNUNET_YES)
2005     return GNUNET_YES; /* This peer should not be gossipped about (hidden) */
2006 #endif
2007   gossip_entry = GNUNET_malloc(sizeof(struct FastGossipNeighborList));
2008   gossip_entry->about = distant;
2009
2010   GNUNET_CONTAINER_DLL_insert_after(send_context->fast_gossip_list_head,
2011                                     send_context->fast_gossip_list_tail,
2012                                     send_context->fast_gossip_list_tail,
2013                                     gossip_entry);
2014
2015   return GNUNET_YES;
2016 }
2017
2018
2019 /**
2020  * Iterate over all current direct peers, add newly connected peer
2021  * to the fast gossip list for that peer so we get DV routing
2022  * information out as fast as possible!
2023  *
2024  * @param cls the newly connected neighbor we will gossip about
2025  * @param key the hashcode of the peer
2026  * @param value the direct neighbor we should gossip to
2027  *
2028  * @return GNUNET_YES to continue iteration, GNUNET_NO otherwise
2029  */
2030 static int add_all_direct_neighbors (void *cls,
2031                                      const GNUNET_HashCode * key,
2032                                      void *value)
2033 {
2034   struct DirectNeighbor *direct = (struct DirectNeighbor *)value;
2035   struct DirectNeighbor *to = (struct DirectNeighbor *)cls;
2036   struct DistantNeighbor *distant;
2037   struct NeighborSendContext *send_context = direct->send_context;
2038   struct FastGossipNeighborList *gossip_entry;
2039
2040   distant = GNUNET_CONTAINER_multihashmap_get(ctx.extended_neighbors, &to->identity.hashPubKey);
2041   if (distant == NULL)
2042     return GNUNET_YES;
2043
2044   if (memcmp(&direct->identity, &to->identity, sizeof(struct GNUNET_PeerIdentity)) == 0)
2045     return GNUNET_YES; /* Don't gossip to a peer about itself! */
2046
2047   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "DV SERVICE: adding new DISTANT neighbor to fast send list\n");
2048 #if SUPPORT_HIDING
2049   if (distant->hidden == GNUNET_YES)
2050     return GNUNET_YES; /* This peer should not be gossipped about (hidden) */
2051 #endif
2052   gossip_entry = GNUNET_malloc(sizeof(struct FastGossipNeighborList));
2053   gossip_entry->about = distant;
2054
2055   GNUNET_CONTAINER_DLL_insert_after(send_context->fast_gossip_list_head,
2056                                     send_context->fast_gossip_list_tail,
2057                                     send_context->fast_gossip_list_tail,
2058                                     gossip_entry);
2059   if (send_context->task != GNUNET_SCHEDULER_NO_TASK)
2060     GNUNET_SCHEDULER_cancel(sched, send_context->task);
2061
2062   send_context->task = GNUNET_SCHEDULER_add_now(sched, &neighbor_send_task, send_context);
2063   return GNUNET_YES;
2064 }
2065
2066
2067 static void
2068 process_peerinfo (void *cls,
2069                   const struct GNUNET_PeerIdentity *peer,
2070                   const struct GNUNET_HELLO_Message *hello, uint32_t trust)
2071 {
2072   struct PeerIteratorContext *peerinfo_iterator = cls;
2073   struct DirectNeighbor *neighbor = peerinfo_iterator->neighbor;
2074
2075   if ((peer == NULL))/* && (neighbor->pkey == NULL))*/
2076     {
2077       /* FIXME: Remove peer! */
2078       GNUNET_free(peerinfo_iterator);
2079       return;
2080     }
2081
2082   if (memcmp(&neighbor->identity, peer, sizeof(struct GNUNET_PeerIdentity) != 0))
2083     return;
2084
2085   if ((hello != NULL) && (GNUNET_HELLO_get_key (hello, &neighbor->pkey) == GNUNET_OK))
2086     {
2087       GNUNET_CONTAINER_multihashmap_get_multiple(ctx.extended_neighbors,
2088                                                  &peer->hashPubKey,
2089                                                  &add_pkey_to_extended,
2090                                                  &neighbor->pkey);
2091
2092       GNUNET_CONTAINER_multihashmap_iterate (ctx.extended_neighbors, &add_all_extended_peers, neighbor->send_context);
2093
2094       GNUNET_CONTAINER_multihashmap_iterate (ctx.direct_neighbors, &add_all_direct_neighbors, neighbor);
2095       neighbor->send_context->task = GNUNET_SCHEDULER_add_now(sched, &neighbor_send_task, neighbor->send_context);
2096     }
2097 }
2098
2099
2100 /**
2101  * Method called whenever a peer connects.
2102  *
2103  * @param cls closure
2104  * @param peer peer identity this notification is about
2105  * @param latency reported latency of the connection with peer
2106  * @param distance reported distance (DV) to peer
2107  */
2108 void handle_core_connect (void *cls,
2109                           const struct GNUNET_PeerIdentity * peer,
2110                           struct GNUNET_TIME_Relative latency,
2111                           uint32_t distance)
2112 {
2113   struct DirectNeighbor *neighbor;
2114   struct DistantNeighbor *about;
2115   struct PeerIteratorContext *peerinfo_iterator;
2116 #if DEBUG_DV
2117   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2118               "%s: Receives core connect message for peer %s distance %d!\n", "dv", GNUNET_i2s(peer), distance);
2119 #endif
2120
2121   if ((distance == DIRECT_NEIGHBOR_COST) && (GNUNET_CONTAINER_multihashmap_get(ctx.direct_neighbors, &peer->hashPubKey) == NULL))
2122   {
2123     peerinfo_iterator = GNUNET_malloc(sizeof(struct PeerIteratorContext));
2124     neighbor = GNUNET_malloc (sizeof (struct DirectNeighbor));
2125     neighbor->send_context = GNUNET_malloc(sizeof(struct NeighborSendContext));
2126     neighbor->send_context->toNeighbor = neighbor;
2127     memcpy (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity));
2128
2129     GNUNET_CONTAINER_multihashmap_put (ctx.direct_neighbors,
2130                                &peer->hashPubKey,
2131                                neighbor, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2132     addUpdateNeighbor (peer, NULL, 0, neighbor, DIRECT_NEIGHBOR_COST);
2133     peerinfo_iterator->neighbor = neighbor;
2134     peerinfo_iterator->ic = GNUNET_PEERINFO_iterate (peerinfo_handle,
2135                                                      peer,
2136                                                      0,
2137                                                      GNUNET_TIME_UNIT_FOREVER_REL,
2138                                                      &process_peerinfo,
2139                                                      peerinfo_iterator);
2140
2141     /* Only add once we get the publicKey of this guy
2142      *
2143      * neighbor->send_context->task = GNUNET_SCHEDULER_add_now(sched, &neighbor_send_task, neighbor->send_context);
2144      */
2145   }
2146   else
2147   {
2148     about = GNUNET_CONTAINER_multihashmap_get(ctx.extended_neighbors, &peer->hashPubKey);
2149     if ((GNUNET_CONTAINER_multihashmap_get(ctx.direct_neighbors, &peer->hashPubKey) == NULL) && (about != NULL))
2150       GNUNET_CONTAINER_multihashmap_iterate(ctx.direct_neighbors, &add_all_direct_neighbors, about);
2151
2152 #if DEBUG_DV
2153     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2154                 "%s: Distance (%d) greater than %d or already know about peer (%s), not re-adding!\n", "dv", distance, DIRECT_NEIGHBOR_COST, GNUNET_i2s(peer));
2155 #endif
2156     return;
2157   }
2158 }
2159
2160 /**
2161  * Method called whenever a given peer disconnects.
2162  *
2163  * @param cls closure
2164  * @param peer peer identity this notification is about
2165  */
2166 void handle_core_disconnect (void *cls,
2167                              const struct GNUNET_PeerIdentity * peer)
2168 {
2169   struct DirectNeighbor *neighbor;
2170   struct DistantNeighbor *referee;
2171   struct FindDestinationContext fdc;
2172   struct DisconnectContext disconnect_context;
2173 #if DEBUG_DV
2174   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2175               "%s: Receives core peer disconnect message!\n", "dv");
2176 #endif
2177
2178   neighbor =
2179     GNUNET_CONTAINER_multihashmap_get (ctx.direct_neighbors, &peer->hashPubKey);
2180   if (neighbor == NULL)
2181     {
2182       return;
2183     }
2184   while (NULL != (referee = neighbor->referee_head))
2185     distant_neighbor_free (referee);
2186
2187   fdc.dest = NULL;
2188   fdc.tid = 0;
2189
2190   GNUNET_CONTAINER_multihashmap_iterate (ctx.extended_neighbors, &find_distant_peer, &fdc);
2191
2192   if (fdc.dest != NULL)
2193     {
2194       disconnect_context.direct = neighbor;
2195       disconnect_context.distant = fdc.dest;
2196       GNUNET_CONTAINER_multihashmap_iterate (ctx.direct_neighbors, &schedule_disconnect_messages, &disconnect_context);
2197     }
2198
2199   GNUNET_assert (neighbor->referee_tail == NULL);
2200   GNUNET_CONTAINER_multihashmap_remove (ctx.direct_neighbors,
2201                                         &peer->hashPubKey, neighbor);
2202   if ((neighbor->send_context != NULL) && (neighbor->send_context->task != GNUNET_SCHEDULER_NO_TASK))
2203     GNUNET_SCHEDULER_cancel(sched, neighbor->send_context->task);
2204   GNUNET_free (neighbor);
2205 }
2206
2207
2208 /**
2209  * Process dv requests.
2210  *
2211  * @param cls closure
2212  * @param scheduler scheduler to use
2213  * @param server the initialized server
2214  * @param c configuration to use
2215  */
2216 static void
2217 run (void *cls,
2218      struct GNUNET_SCHEDULER_Handle *scheduler,
2219      struct GNUNET_SERVER_Handle *server,
2220      const struct GNUNET_CONFIGURATION_Handle *c)
2221 {
2222   unsigned long long max_hosts;
2223   sched = scheduler;
2224   cfg = c;
2225
2226   /* FIXME: Read from config, or calculate, or something other than this! */
2227   max_hosts = DEFAULT_DIRECT_CONNECTIONS;
2228   ctx.max_table_size = DEFAULT_DV_SIZE;
2229   ctx.fisheye_depth = DEFAULT_FISHEYE_DEPTH;
2230
2231   if (GNUNET_CONFIGURATION_have_value(cfg, "dv", "max_direct_connections"))
2232     {
2233       GNUNET_CONFIGURATION_get_value_number(cfg, "dv", "max_direct_connections", &max_hosts);
2234     }
2235
2236   if (GNUNET_CONFIGURATION_have_value(cfg, "dv", "max_total_connections"))
2237     {
2238       GNUNET_CONFIGURATION_get_value_number(cfg, "dv", "max_total_connections", &ctx.max_table_size);
2239     }
2240
2241   if (GNUNET_CONFIGURATION_have_value(cfg, "dv", "fisheye_depth"))
2242     {
2243       GNUNET_CONFIGURATION_get_value_number(cfg, "dv", "fisheye_depth", &ctx.fisheye_depth);
2244     }
2245
2246   ctx.neighbor_min_heap =
2247     GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2248   ctx.neighbor_max_heap =
2249     GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MAX);
2250
2251   ctx.direct_neighbors = GNUNET_CONTAINER_multihashmap_create (max_hosts);
2252   ctx.extended_neighbors =
2253     GNUNET_CONTAINER_multihashmap_create (ctx.max_table_size * 3);
2254
2255   GNUNET_SERVER_add_handlers (server, plugin_handlers);
2256   coreAPI =
2257   GNUNET_CORE_connect (sched,
2258                        cfg,
2259                        GNUNET_TIME_relative_get_forever(),
2260                        NULL, /* FIXME: anything we want to pass around? */
2261                        &core_init,
2262                        &handle_core_connect,
2263                        &handle_core_disconnect,
2264                        NULL,
2265                        GNUNET_NO,
2266                        NULL,
2267                        GNUNET_NO,
2268                        core_handlers);
2269
2270   if (coreAPI == NULL)
2271     return;
2272
2273    peerinfo_handle = GNUNET_PEERINFO_connect(sched, cfg);
2274
2275    if (peerinfo_handle == NULL)
2276      {
2277        GNUNET_CORE_disconnect(coreAPI);
2278        return;
2279      }
2280
2281   /* Scheduled the task to clean up when shutdown is called */
2282   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
2283                                 GNUNET_TIME_UNIT_FOREVER_REL,
2284                                 &shutdown_task,
2285                                 NULL);
2286 }
2287
2288
2289 /**
2290  * The main function for the dv service.
2291  *
2292  * @param argc number of arguments from the command line
2293  * @param argv command line arguments
2294  * @return 0 ok, 1 on error
2295  */
2296 int
2297 main (int argc, char *const *argv)
2298 {
2299   return (GNUNET_OK ==
2300           GNUNET_SERVICE_run (argc,
2301                               argv,
2302                               "dv",
2303                               GNUNET_SERVICE_OPTION_NONE,
2304                               &run, NULL)) ? 0 : 1;
2305 }