fd0eacf2c4e8b70dc57ca84702f3c7aa44adbb22
[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: Currently the final hop of a DV message assigns a 0 to the receiver
31  * id field.  This probably can't work(!) even if we know that the peer is
32  * a direct neighbor (unless we can trust that transport will choose that
33  * address for the peer).  So the DV message will likely need to have the
34  * peer identity of the recipient.
35  *
36  * Also the gossip rates need to be worked out.  Probably many other things
37  * as well.
38  *
39  */
40 #include "platform.h"
41 #include "gnunet_client_lib.h"
42 #include "gnunet_getopt_lib.h"
43 #include "gnunet_os_lib.h"
44 #include "gnunet_protocols.h"
45 #include "gnunet_service_lib.h"
46 #include "gnunet_core_service.h"
47 #include "gnunet_signal_lib.h"
48 #include "gnunet_util_lib.h"
49 #include "gnunet_hello_lib.h"
50 #include "gnunet_peerinfo_service.h"
51 #include "gnunet_crypto_lib.h"
52 #include "dv.h"
53
54 /**
55  * DV Service Context stuff goes here...
56  */
57
58 /**
59  * Handle to the core service api.
60  */
61 static struct GNUNET_CORE_Handle *coreAPI;
62
63 /**
64  * The identity of our peer.
65  */
66 static struct GNUNET_PeerIdentity my_identity;
67
68 /**
69  * The configuration for this service.
70  */
71 static const struct GNUNET_CONFIGURATION_Handle *cfg;
72
73 /**
74  * The scheduler for this service.
75  */
76 static struct GNUNET_SCHEDULER_Handle *sched;
77
78 /**
79  * How often do we check about sending out more peer information (if
80  * we are connected to no peers previously).
81  */
82 #define GNUNET_DV_DEFAULT_SEND_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 500))
83
84 /**
85  * How long do we wait at most between sending out information?
86  */
87 #define GNUNET_DV_MAX_SEND_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5))
88
89 /**
90  * How long can we have not heard from a peer and
91  * still have it in our tables?
92  */
93 #define GNUNET_DV_PEER_EXPIRATION_TIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1000))
94
95 /**
96  * Priority for gossip.
97  */
98 #define GNUNET_DV_DHT_GOSSIP_PRIORITY (GNUNET_EXTREME_PRIORITY / 10)
99
100 /**
101  * How often should we check if expiration time has elapsed for
102  * some peer?
103  */
104 #define GNUNET_DV_MAINTAIN_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5))
105
106 /**
107  * How long to allow a message to be delayed?
108  */
109 #define DV_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5))
110
111 /**
112  * Priority to use for DV data messages.
113  */
114 #define DV_PRIORITY 0
115
116 /**
117  * The client, should be the DV plugin connected to us.  Hopefully
118  * this client will never change, although if the plugin dies
119  * and returns for some reason it may happen.
120  */
121 static struct GNUNET_SERVER_Client * client_handle;
122
123 /**
124  * Task to run when we shut down, cleaning up all our trash
125  */
126 GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
127
128 /**
129  * Task to run to gossip about peers.  Will reschedule itself forever until shutdown!
130  */
131 GNUNET_SCHEDULER_TaskIdentifier gossip_task;
132
133 /**
134  * Struct where neighbor information is stored.
135  */
136 struct DistantNeighbor *referees;
137
138 static struct GNUNET_TIME_Relative client_transmit_timeout;
139
140 static struct GNUNET_TIME_Relative default_dv_delay;
141
142 static size_t default_dv_priority = 0;
143
144
145 /**
146  * Linked list of messages to send to clients.
147  */
148 struct PendingMessage
149 {
150   /**
151    * Pointer to next item in the list
152    */
153   struct PendingMessage *next;
154
155   /**
156    * Pointer to previous item in the list
157    */
158   struct PendingMessage *prev;
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 /**
168  * Transmit handle to the plugin.
169  */
170 struct GNUNET_CONNECTION_TransmitHandle * plugin_transmit_handle;
171
172 /**
173  * Head of DLL for client messages
174  */
175 struct PendingMessage *plugin_pending_head;
176
177 /**
178  * Tail of DLL for client messages
179  */
180 struct PendingMessage *plugin_pending_tail;
181
182
183 /**
184  * Transmit handle to core service.
185  */
186 struct GNUNET_CORE_TransmitHandle * core_transmit_handle;
187
188 /**
189  * Head of DLL for core messages
190  */
191 struct PendingMessage *core_pending_head;
192
193 /**
194  * Tail of DLL for core messages
195  */
196 struct PendingMessage *core_pending_tail;
197
198
199
200
201 /**
202  * Context created whenever a direct peer connects to us,
203  * used to gossip other peers to it.
204  */
205 struct NeighborSendContext
206 {
207   /**
208    * The peer we will gossip to.
209    */
210   struct DirectNeighbor *toNeighbor;
211
212   /**
213    * The timeout for this task.
214    */
215   struct GNUNET_TIME_Relative timeout;
216
217   /**
218    * The task associated with this context.
219    */
220   GNUNET_SCHEDULER_TaskIdentifier task;
221
222 };
223
224
225 /**
226  * Struct to hold information for updating existing neighbors
227  */
228 struct NeighborUpdateInfo
229 {
230   /**
231    * Cost
232    */
233   unsigned int cost;
234
235   /**
236    * The existing neighbor
237    */
238   struct DistantNeighbor *neighbor;
239
240   /**
241    * The referrer of the possibly existing peer
242    */
243   struct DirectNeighbor *referrer;
244
245   /**
246    * The time we heard about this peer
247    */
248   struct GNUNET_TIME_Absolute now;
249 };
250
251 /**
252  * Struct where actual neighbor information is stored,
253  * referenced by min_heap and max_heap.  Freeing dealt
254  * with when items removed from hashmap.
255  */
256 struct DirectNeighbor
257 {
258   /**
259    * Identity of neighbor.
260    */
261   struct GNUNET_PeerIdentity identity;
262
263   /**
264    * PublicKey of neighbor.
265    */
266   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
267
268   /**
269    * Head of DLL of nodes that this direct neighbor referred to us.
270    */
271   struct DistantNeighbor *referee_head;
272
273   /**
274    * Tail of DLL of nodes that this direct neighbor referred to us.
275    */
276   struct DistantNeighbor *referee_tail;
277
278   /**
279    * The sending context for gossiping peers to this neighbor.
280    */
281   struct NeighborSendContext *send_context;
282
283   /**
284    * Is this one of the direct neighbors that we are "hiding"
285    * from DV?
286    */
287   int hidden;
288 };
289
290
291 /**
292  * Struct where actual neighbor information is stored,
293  * referenced by min_heap and max_heap.  Freeing dealt
294  * with when items removed from hashmap.
295  */
296 struct DistantNeighbor
297 {
298   /**
299    * We keep distant neighbor's of the same referrer in a DLL.
300    */
301   struct DistantNeighbor *next;
302
303   /**
304    * We keep distant neighbor's of the same referrer in a DLL.
305    */
306   struct DistantNeighbor *prev;
307
308   /**
309    * Node in min heap
310    */
311   struct GNUNET_CONTAINER_HeapNode *min_loc;
312
313   /**
314    * Node in max heap
315    */
316   struct GNUNET_CONTAINER_HeapNode *max_loc;
317
318   /**
319    * Identity of referrer (next hop towards 'neighbor').
320    */
321   struct DirectNeighbor *referrer;
322
323   /**
324    * Identity of neighbor.
325    */
326   struct GNUNET_PeerIdentity identity;
327
328   /**
329    * PublicKey of neighbor.
330    */
331   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey;
332
333   /**
334    * Last time we received routing information from this peer
335    */
336   struct GNUNET_TIME_Absolute last_activity;
337
338   /**
339    * Cost to neighbor, used for actual distance vector computations
340    */
341   unsigned int cost;
342
343   /**
344    * Random identifier *we* use for this peer, to be used as shortcut
345    * instead of sending full peer id for each message
346    */
347   unsigned int our_id;
348
349   /**
350    * Random identifier the *referrer* uses for this peer.
351    */
352   unsigned int referrer_id;
353
354   /**
355    * Is this one of the direct neighbors that we are "hiding"
356    * from DV?
357    */
358   int hidden;
359
360 };
361
362 struct PeerIteratorContext
363 {
364   /**
365    * The actual context, to be freed later.
366    */
367   struct GNUNET_PEERINFO_IteratorContext *ic;
368
369   /**
370    * The neighbor about which we are concerned.
371    */
372   struct DirectNeighbor *neighbor;
373
374 };
375
376 /**
377  * Context used for creating hello messages when
378  * gossips are received.
379  */
380 struct HelloContext
381 {
382   /**
383    * Identity of distant neighbor.
384    */
385   struct GNUNET_PeerIdentity distant_peer;
386
387   /**
388    * Identity of direct neighbor, via which we send this message.
389    */
390   const struct GNUNET_PeerIdentity *direct_peer;
391
392   /**
393    * How many addresses do we need to add (always starts at 1, then set to 0)
394    */
395   int addresses_to_add;
396
397 };
398
399 struct DV_SendContext
400 {
401   /**
402    * The distant peer (should always match)
403    */
404   struct GNUNET_PeerIdentity *distant_peer;
405
406   /**
407    * The direct peer, we need to verify the referrer of.
408    */
409   struct GNUNET_PeerIdentity *direct_peer;
410
411   /**
412    * The message to be sent
413    */
414   struct GNUNET_MessageHeader *message;
415
416   /**
417    * The size of the message being sent, may be larger
418    * than message->header.size because it's multiple
419    * messages packed into one!
420    */
421   size_t message_size;
422
423   /**
424    * How important is this message?
425    */
426   unsigned int importance;
427
428   /**
429    * Timeout for this message
430    */
431   struct GNUNET_TIME_Relative timeout;
432 };
433
434 /**
435  * Global construct
436  */
437 struct GNUNET_DV_Context
438 {
439   /**
440    * Map of PeerIdentifiers to 'struct GNUNET_dv_neighbor*'s for all
441    * directly connected peers.
442    */
443   struct GNUNET_CONTAINER_MultiHashMap *direct_neighbors;
444
445   /**
446    * Map of PeerIdentifiers to 'struct GNUNET_dv_neighbor*'s for
447    * peers connected via DV (extended neighborhood).  Does ALSO
448    * include any peers that are in 'direct_neighbors'; for those
449    * peers, the cost will be zero and the referrer all zeros.
450    */
451   struct GNUNET_CONTAINER_MultiHashMap *extended_neighbors;
452
453   /**
454    * We use the min heap (min refers to cost) to prefer
455    * gossipping about peers with small costs.
456    */
457   struct GNUNET_CONTAINER_Heap *neighbor_min_heap;
458
459   /**
460    * We use the max heap (max refers to cost) for general
461    * iterations over all peers and to remove the most costly
462    * connection if we have too many.
463    */
464   struct GNUNET_CONTAINER_Heap *neighbor_max_heap;
465
466   unsigned long long fisheye_depth;
467
468   unsigned long long max_table_size;
469
470   unsigned int neighbor_id_loc;
471
472   int closing;
473
474 };
475
476 static struct GNUNET_DV_Context ctx;
477
478 struct FindDestinationContext
479 {
480   unsigned int tid;
481   struct DistantNeighbor *dest;
482 };
483
484
485 /**
486  * We've been given a target ID based on the random numbers that
487  * we assigned to our DV-neighborhood.  Find the entry for the
488  * respective neighbor.
489  */
490 static int
491 find_destination (void *cls,
492                   struct GNUNET_CONTAINER_HeapNode *node,
493                   void *element, GNUNET_CONTAINER_HeapCostType cost)
494 {
495   struct FindDestinationContext *fdc = cls;
496   struct DistantNeighbor *dn = element;
497
498   if (fdc->tid != dn->our_id)
499     return GNUNET_YES;
500   fdc->dest = dn;
501   return GNUNET_NO;
502 }
503
504 /**
505  * Function called to notify a client about the socket
506  * begin ready to queue more data.  "buf" will be
507  * NULL and "size" zero if the socket was closed for
508  * writing in the meantime.
509  *
510  * @param cls closure
511  * @param size number of bytes available in buf
512  * @param buf where the callee should write the message
513  * @return number of bytes written to buf
514  */
515 size_t transmit_to_plugin (void *cls,
516                            size_t size, void *buf)
517 {
518   char *cbuf = buf;
519   struct PendingMessage *reply;
520   size_t off;
521   size_t msize;
522
523   if (buf == NULL)
524     {
525       /* client disconnected */
526 #if DEBUG_DV
527       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s': buffer was NULL\n", "DHT");
528 #endif
529       return 0;
530     }
531   plugin_transmit_handle = NULL;
532   off = 0;
533   while ( (NULL != (reply = plugin_pending_head)) &&
534           (size >= off + (msize = ntohs (reply->msg->size))))
535     {
536 #if DEBUG_DV
537     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s' : transmit_notify (plugin) called with size %d\n", "dv service", msize);
538 #endif
539       GNUNET_CONTAINER_DLL_remove (plugin_pending_head,
540                                    plugin_pending_tail,
541                                    reply);
542       memcpy (&cbuf[off], reply->msg, msize);
543       GNUNET_free (reply);
544       off += msize;
545     }
546
547   if (plugin_pending_head != NULL)
548     plugin_transmit_handle = GNUNET_SERVER_notify_transmit_ready (client_handle,
549                                                                   ntohs(plugin_pending_head->msg->size),
550                                                                   GNUNET_TIME_UNIT_FOREVER_REL,
551                                                                   &transmit_to_plugin, NULL);
552
553   return off;
554 }
555
556
557 void send_to_plugin(const struct GNUNET_PeerIdentity * sender,
558                     const struct GNUNET_MessageHeader *message,
559                     size_t message_size,
560                     struct GNUNET_PeerIdentity *distant_neighbor,
561                     size_t cost)
562 {
563   struct GNUNET_DV_MessageReceived *received_msg;
564   struct PendingMessage *pending_message;
565 #if DEBUG_DV
566   struct GNUNET_MessageHeader * packed_message_header;
567   struct GNUNET_HELLO_Message *hello_msg;
568   struct GNUNET_PeerIdentity hello_identity;
569 #endif
570   char *sender_address;
571   size_t sender_address_len;
572   char *packed_msg_start;
573   int size;
574
575 #if DEBUG_DV
576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_to_plugin called with peer %s as sender\n", GNUNET_i2s(distant_neighbor));
577 #endif
578
579   if (memcmp(sender, distant_neighbor, sizeof(struct GNUNET_PeerIdentity)) != 0)
580   {
581     sender_address_len = sizeof(struct GNUNET_PeerIdentity) * 2;
582     sender_address = GNUNET_malloc(sender_address_len);
583     memcpy(sender_address, distant_neighbor, sizeof(struct GNUNET_PeerIdentity));
584     memcpy(&sender_address[sizeof(struct GNUNET_PeerIdentity)], sender, sizeof(struct GNUNET_PeerIdentity));
585   }
586   else
587   {
588     sender_address_len = sizeof(struct GNUNET_PeerIdentity);
589     sender_address = GNUNET_malloc(sender_address_len);
590     memcpy(sender_address, sender, sizeof(struct GNUNET_PeerIdentity));
591   }
592
593   size = sizeof(struct GNUNET_DV_MessageReceived) + sender_address_len + message_size;
594   received_msg = GNUNET_malloc(size);
595   received_msg->header.size = htons(size);
596   received_msg->header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_DV_RECEIVE);
597   received_msg->sender_address_len = htons(sender_address_len);
598   received_msg->distance = htonl(cost);
599   received_msg->msg_len = htons(message_size);
600   /* Set the sender in this message to be the original sender! */
601   memcpy(&received_msg->sender, distant_neighbor, sizeof(struct GNUNET_PeerIdentity));
602   /* Copy the intermediate sender to the end of the message, this is how the transport identifies this peer */
603   memcpy(&received_msg[1], sender_address, sender_address_len);
604   GNUNET_free(sender_address);
605   /* Copy the actual message after the sender */
606   packed_msg_start = (char *)&received_msg[1];
607   packed_msg_start = &packed_msg_start[sender_address_len];
608   memcpy(packed_msg_start, message, message_size);
609 #if DEBUG_DV
610   packed_message_header = (struct GNUNET_MessageHeader *)packed_msg_start;
611   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, ntohs(received_msg->msg_len), ntohs(received_msg->header.size));
612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "dv packed message len %d, type %d\n", ntohs(packed_message_header->size), ntohs(packed_message_header->type));
613   if (ntohs(packed_message_header->type) == GNUNET_MESSAGE_TYPE_HELLO)
614   {
615     hello_msg = (struct GNUNET_HELLO_Message *)packed_message_header;
616     GNUNET_assert(GNUNET_OK == GNUNET_HELLO_get_id(hello_msg, &hello_identity));
617     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Packed HELLO message is about peer %s\n", GNUNET_i2s(&hello_identity));
618   }
619 #endif
620   pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + size);
621   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
622   memcpy(&pending_message[1], received_msg, size);
623   GNUNET_free(received_msg);
624
625   GNUNET_CONTAINER_DLL_insert_after(plugin_pending_head, plugin_pending_tail, plugin_pending_tail, pending_message);
626
627   if (client_handle != NULL)
628     {
629       if (plugin_transmit_handle == NULL)
630         {
631           plugin_transmit_handle = GNUNET_SERVER_notify_transmit_ready (client_handle,
632                                                                         size, GNUNET_TIME_UNIT_FOREVER_REL,
633                                                                         &transmit_to_plugin, NULL);
634         }
635       else
636         {
637           GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Failed to queue message for plugin, must be one in progress already!!\n");
638         }
639     }
640 }
641
642
643 /**
644  * Function called to notify a client about the socket
645  * begin ready to queue more data.  "buf" will be
646  * NULL and "size" zero if the socket was closed for
647  * writing in the meantime.
648  *
649  * @param cls closure
650  * @param size number of bytes available in buf
651  * @param buf where the callee should write the message
652  * @return number of bytes written to buf
653  */
654 size_t core_transmit_notify (void *cls,
655                              size_t size, void *buf)
656 {
657   char *cbuf = buf;
658   struct PendingMessage *reply;
659   size_t off;
660   size_t msize;
661
662   if (buf == NULL)
663     {
664       /* client disconnected */
665 #if DEBUG_DV
666       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s': buffer was NULL\n", "DHT");
667 #endif
668       return 0;
669     }
670
671   core_transmit_handle = NULL;
672   off = 0;
673   while ( (NULL != (reply = core_pending_head)) &&
674           (size >= off + (msize = ntohs (reply->msg->size))))
675     {
676 #if DEBUG_DV
677     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s' : transmit_notify (core) called with size %d\n", "dv service", msize);
678 #endif
679       GNUNET_CONTAINER_DLL_remove (core_pending_head,
680                                    core_pending_tail,
681                                    reply);
682       memcpy (&cbuf[off], reply->msg, msize);
683       GNUNET_free (reply);
684       off += msize;
685     }
686   return off;
687 }
688
689
690 /**
691  * Send a DV data message via DV.
692  *
693  * @param sender the original sender of the message
694  * @param specific_neighbor the specific DistantNeighbor to use, complete with referrer!
695  * @param message the packed message
696  * @param importance what priority to send this message with
697  * @param timeout how long to possibly delay sending this message
698  */
699 static int
700 send_message_via (const struct GNUNET_PeerIdentity * sender,
701               const struct DistantNeighbor * specific_neighbor,
702               struct DV_SendContext *send_context)
703 {
704   p2p_dv_MESSAGE_Data *toSend;
705   unsigned int msg_size;
706   unsigned int cost;
707   unsigned int recipient_id;
708   unsigned int sender_id;
709   struct DistantNeighbor *source;
710   struct PendingMessage *pending_message;
711 #if DEBUG_DV
712   char shortname[5];
713 #endif
714
715   msg_size = send_context->message_size + sizeof (p2p_dv_MESSAGE_Data);
716
717   if (specific_neighbor == NULL)
718     {
719       /* target unknown to us, drop! */
720       return GNUNET_SYSERR;
721     }
722   recipient_id = specific_neighbor->referrer_id;
723
724   source = GNUNET_CONTAINER_multihashmap_get (ctx.extended_neighbors,
725                                       &sender->hashPubKey);
726   if (source == NULL)
727     {
728       if (0 != (memcmp (&my_identity,
729                         sender, sizeof (struct GNUNET_PeerIdentity))))
730         {
731           /* sender unknown to us, drop! */
732           return GNUNET_SYSERR;
733         }
734       sender_id = 0;            /* 0 == us */
735     }
736   else
737     {
738       /* find out the number that we use when we gossip about
739          the sender */
740       sender_id = source->our_id;
741     }
742
743   cost = specific_neighbor->cost;
744   pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + msg_size);
745   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
746   toSend = (p2p_dv_MESSAGE_Data *)pending_message->msg;
747   toSend->header.size = htons (msg_size);
748   toSend->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DATA);
749   toSend->sender = htonl (sender_id);
750   toSend->recipient = htonl (recipient_id);
751   memcpy (&toSend[1], send_context->message, send_context->message_size);
752
753 #if DEBUG_DV
754   memcpy(&shortname, GNUNET_i2s(&specific_neighbor->identity), 4);
755   shortname[4] = '\0';
756   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);
757 #endif
758
759   GNUNET_CONTAINER_DLL_insert_after (core_pending_head,
760                                      core_pending_tail,
761                                      core_pending_tail,
762                                      pending_message);
763   if (core_transmit_handle == NULL)
764     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);
765   else
766     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "`%s': Failed to schedule pending transmission (must be one in progress!)\n", "dv service");
767
768   return (int) cost;
769 }
770
771
772 /**
773  * Send a DV data message via DV.
774  *
775  * @param recipient the ultimate recipient of this message
776  * @param sender the original sender of the message
777  * @param specific_neighbor the specific neighbor to send this message via
778  * @param message the packed message
779  * @param importance what priority to send this message with
780  * @param timeout how long to possibly delay sending this message
781  */
782 static int
783 send_message (const struct GNUNET_PeerIdentity * recipient,
784               const struct GNUNET_PeerIdentity * sender,
785               const struct DistantNeighbor * specific_neighbor,
786               const struct GNUNET_MessageHeader * message,
787               size_t message_size,
788               unsigned int importance, struct GNUNET_TIME_Relative timeout)
789 {
790   p2p_dv_MESSAGE_Data *toSend;
791   unsigned int msg_size;
792   unsigned int cost;
793   unsigned int recipient_id;
794   unsigned int sender_id;
795   struct DistantNeighbor *target;
796   struct DistantNeighbor *source;
797   struct PendingMessage *pending_message;
798
799   msg_size = message_size + sizeof (p2p_dv_MESSAGE_Data);
800
801   target = GNUNET_CONTAINER_multihashmap_get (ctx.extended_neighbors,
802                                               &recipient->hashPubKey);
803   if (target == NULL)
804     {
805       /* target unknown to us, drop! */
806       return GNUNET_SYSERR;
807     }
808   recipient_id = target->referrer_id;
809
810   source = GNUNET_CONTAINER_multihashmap_get (ctx.extended_neighbors,
811                                       &sender->hashPubKey);
812   if (source == NULL)
813     {
814       if (0 != (memcmp (&my_identity,
815                         sender, sizeof (struct GNUNET_PeerIdentity))))
816         {
817           /* sender unknown to us, drop! */
818           return GNUNET_SYSERR;
819         }
820       sender_id = 0;            /* 0 == us */
821     }
822   else
823     {
824       /* find out the number that we use when we gossip about
825          the sender */
826       sender_id = source->our_id;
827     }
828
829   cost = target->cost;
830   pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + msg_size);
831   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
832   toSend = (p2p_dv_MESSAGE_Data *)pending_message->msg;
833   toSend->header.size = htons (msg_size);
834   toSend->header.type = htons (GNUNET_MESSAGE_TYPE_DV_DATA);
835   toSend->sender = htonl (sender_id);
836   toSend->recipient = htonl (recipient_id);
837   memcpy (&toSend[1], message, message_size);
838
839   GNUNET_CONTAINER_DLL_insert_after (core_pending_head,
840                                      core_pending_tail,
841                                      core_pending_tail,
842                                      pending_message);
843 #if DEBUG_DV
844   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));
845 #endif
846   if (core_transmit_handle == NULL)
847     core_transmit_handle = GNUNET_CORE_notify_transmit_ready(coreAPI, importance, timeout, &target->referrer->identity, msg_size, &core_transmit_notify, NULL);
848
849   return (int) cost;
850 }
851
852
853 /**
854  * Core handler for dv data messages.  Whatever this message
855  * contains all we really have to do is rip it out of its
856  * DV layering and give it to our pal the DV plugin to report
857  * in with.
858  *
859  * @param cls closure
860  * @param peer peer which sent the message (immediate sender)
861  * @param message the message
862  * @param latency the latency of the connection we received the message from
863  * @param distance the distance to the immediate peer
864  */
865 static int handle_dv_data_message (void *cls,
866                              const struct GNUNET_PeerIdentity * peer,
867                              const struct GNUNET_MessageHeader * message,
868                              struct GNUNET_TIME_Relative latency,
869                              uint32_t distance)
870 {
871   const p2p_dv_MESSAGE_Data *incoming = (const p2p_dv_MESSAGE_Data *) message;
872   const struct GNUNET_MessageHeader *packed_message;
873   struct DirectNeighbor *dn;
874   struct DistantNeighbor *pos;
875   unsigned int sid;             /* Sender id */
876   unsigned int tid;             /* Target id */
877   struct GNUNET_PeerIdentity original_sender;
878   struct GNUNET_PeerIdentity destination;
879   struct FindDestinationContext fdc;
880   int ret;
881   size_t packed_message_size;
882   char *cbuf;
883   size_t offset;
884
885   packed_message_size = ntohs(incoming->header.size) - sizeof(p2p_dv_MESSAGE_Data);
886
887 #if DEBUG_DV
888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
889               "%s: Receives %s message size %d, packed message size %d!\n", "dv", "DV DATA", ntohs(incoming->header.size), packed_message_size);
890 #endif
891   if (ntohs (incoming->header.size) <  sizeof (p2p_dv_MESSAGE_Data) + sizeof (struct GNUNET_MessageHeader))
892     {
893 #if DEBUG_DV
894   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
895               "`%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));
896 #endif
897       return GNUNET_SYSERR;
898     }
899
900   dn = GNUNET_CONTAINER_multihashmap_get (ctx.direct_neighbors,
901                                   &peer->hashPubKey);
902   if (dn == NULL)
903     {
904 #if DEBUG_DV
905       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
906                   "%s: dn NULL!\n", "dv");
907 #endif
908       return GNUNET_OK;
909     }
910   sid = ntohl (incoming->sender);
911   pos = dn->referee_head;
912   while ((NULL != pos) && (pos->referrer_id != sid))
913     pos = pos->next;
914   if (pos == NULL)
915     {
916 #if DEBUG_DV
917       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
918                   "%s: unknown sender (%d), size of extended_peers is %d!\n", "dv", ntohl(incoming->sender), GNUNET_CONTAINER_multihashmap_size (ctx.extended_neighbors));
919 #endif
920       /* unknown sender */
921       return GNUNET_OK;
922     }
923   original_sender = pos->identity;
924   tid = ntohl (incoming->recipient);
925   if (tid == 0)
926     {
927       /* 0 == us */
928
929       cbuf = (char *)&incoming[1];
930       offset = 0;
931       while(offset < packed_message_size)
932         {
933           packed_message = (struct GNUNET_MessageHeader *)&cbuf[offset];
934 #if DEBUG_DV
935           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
936                       "%s: Receives %s message for me, size %d type %d!\n", "dv", "DV DATA", ntohs(packed_message->size), ntohs(packed_message->type));
937 #endif
938           GNUNET_break_op (ntohs (packed_message->type) != GNUNET_MESSAGE_TYPE_DV_GOSSIP);
939           GNUNET_break_op (ntohs (packed_message->type) != GNUNET_MESSAGE_TYPE_DV_DATA);
940           if ( (ntohs (packed_message->type) != GNUNET_MESSAGE_TYPE_DV_GOSSIP) &&
941               (ntohs (packed_message->type) != GNUNET_MESSAGE_TYPE_DV_DATA) )
942           {
943             send_to_plugin(peer, packed_message, ntohs(packed_message->size), &pos->identity, pos->cost);
944           }
945           offset += ntohs(packed_message->size);
946         }
947
948       return GNUNET_OK;
949     }
950   else
951     {
952       packed_message = (struct GNUNET_MessageHeader *)&incoming[1];
953     }
954
955   /* FIXME: this is the *only* per-request operation we have in DV
956      that is O(n) in relation to the number of connected peers; a
957      hash-table lookup could easily solve this (minor performance
958      issue) */
959   fdc.tid = tid;
960   fdc.dest = NULL;
961   GNUNET_CONTAINER_heap_iterate (ctx.neighbor_max_heap,
962                                  &find_destination, &fdc);
963
964 #if DEBUG_DV
965       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
966                   "%s: Receives %s message for someone else!\n", "dv", "DV DATA");
967 #endif
968
969   if (fdc.dest == NULL)
970     {
971       return GNUNET_OK;
972     }
973   destination = fdc.dest->identity;
974
975   if (0 == memcmp (&destination, peer, sizeof (struct GNUNET_PeerIdentity)))
976     {
977       /* FIXME: create stat: routing loop-discard! */
978 #if DEBUG_DV
979       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "\n\n\nLoopy loo message\n\n\n");
980 #endif
981       return GNUNET_OK;
982     }
983
984   /* At this point we have a message, and we need to forward it on to the
985    * next DV hop.
986    */
987   /* FIXME: Can't send message on, we have to behave.
988    * We have to tell core we have a message for the next peer, and let
989    * transport do transport selection on how to get this message to 'em */
990   /*ret = send_message (&destination,
991                       &original_sender,
992                       packed_message, DV_PRIORITY, DV_DELAY);*/
993 #if DEBUG_DV
994   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
995               "%s: Sends message size %d on!\n", "dv", packed_message_size);
996 #endif
997   ret = send_message(&destination, &original_sender, NULL, packed_message, packed_message_size, default_dv_priority, default_dv_delay);
998
999   if (ret != GNUNET_SYSERR)
1000     return GNUNET_OK;
1001   else
1002     return GNUNET_SYSERR;
1003 }
1004
1005
1006 /**
1007  * Thread which chooses a peer to gossip about and a peer to gossip
1008  * to, then constructs the message and sends it out.  Will run until
1009  * done_module_dv is called.
1010  */
1011 static void
1012 neighbor_send_task (void *cls,
1013                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1014 {
1015   struct NeighborSendContext *send_context = cls;
1016 #if DEBUG_DV_GOSSIP
1017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1018               "%s: Entering neighbor_send_task...\n",
1019               GNUNET_i2s(&my_identity));
1020   char * encPeerAbout;
1021   char * encPeerTo;
1022 #endif
1023   struct DistantNeighbor *about;
1024   struct DirectNeighbor *to;
1025
1026   p2p_dv_MESSAGE_NeighborInfo *message;
1027   struct PendingMessage *pending_message;
1028
1029   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1030   {
1031 #if DEBUG_DV_GOSSIP
1032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1033               "%s: Called with reason shutdown, shutting down!\n",
1034               GNUNET_i2s(&my_identity));
1035 #endif
1036     send_context->toNeighbor->send_context = NULL;
1037     GNUNET_free(send_context);
1038     return;
1039   }
1040
1041
1042   /* FIXME: this may become a problem, because the heap walk has only one internal "walker".  This means
1043    * that if two neighbor_send_tasks are operating in lockstep (which is quite possible, given default
1044    * values for all connected peers) there may be a serious bias as to which peers get gossiped about!
1045    * Probably the *best* way to fix would be to have an opaque pointer to the walk position passed as
1046    * part of the walk_get_next call.  Then the heap would have to keep a list of walks, or reset the walk
1047    * whenever a modification has been detected.  Yuck either way.  Perhaps we could iterate over the heap
1048    * once to get a list of peers to gossip about and gossip them over time... But then if one goes away
1049    * in the mean time that becomes nasty.  For now we'll just assume that the walking is done
1050    * asynchronously enough to avoid major problems (-;
1051    */
1052   about = GNUNET_CONTAINER_heap_walk_get_next (ctx.neighbor_min_heap);
1053   to = send_context->toNeighbor;
1054
1055   if ((about != NULL) && (to != about->referrer /* split horizon */ ) &&
1056 #if SUPPORT_HIDING
1057       (about->hidden == GNUNET_NO) &&
1058 #endif
1059       (to != NULL) &&
1060       (0 != memcmp (&about->identity,
1061                         &to->identity, sizeof (struct GNUNET_PeerIdentity))) &&
1062       (about->pkey != NULL))
1063     {
1064 #if DEBUG_DV_GOSSIP
1065       encPeerAbout = GNUNET_strdup(GNUNET_i2s(&about->identity));
1066       encPeerTo = GNUNET_strdup(GNUNET_i2s(&to->identity));
1067       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1068                   "%s: Sending info about peer %s to directly connected peer %s\n",
1069                   GNUNET_i2s(&my_identity),
1070                   encPeerAbout, encPeerTo);
1071       GNUNET_free(encPeerAbout);
1072       GNUNET_free(encPeerTo);
1073 #endif
1074       pending_message = GNUNET_malloc(sizeof(struct PendingMessage) + sizeof(p2p_dv_MESSAGE_NeighborInfo));
1075       pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1076       message = (p2p_dv_MESSAGE_NeighborInfo *)pending_message->msg;
1077       message->header.size = htons (sizeof (p2p_dv_MESSAGE_NeighborInfo));
1078       message->header.type = htons (GNUNET_MESSAGE_TYPE_DV_GOSSIP);
1079       message->cost = htonl (about->cost);
1080       message->neighbor_id = htonl (about->our_id);
1081
1082       memcpy (&message->pkey, about->pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1083       memcpy (&message->neighbor,
1084               &about->identity, sizeof (struct GNUNET_PeerIdentity));
1085
1086       GNUNET_CONTAINER_DLL_insert_after (core_pending_head,
1087                                          core_pending_tail,
1088                                          core_pending_tail,
1089                                          pending_message);
1090
1091       if (core_transmit_handle == NULL)
1092         core_transmit_handle = GNUNET_CORE_notify_transmit_ready(coreAPI, default_dv_priority, default_dv_delay, &to->identity, sizeof(p2p_dv_MESSAGE_NeighborInfo), &core_transmit_notify, NULL);
1093
1094     }
1095
1096   send_context->task = GNUNET_SCHEDULER_add_delayed(sched, send_context->timeout, &neighbor_send_task, send_context);
1097   return;
1098 }
1099
1100
1101 /**
1102  * Handle START-message.  This is the first message sent to us
1103  * by the client (can only be one!).
1104  *
1105  * @param cls closure (always NULL)
1106  * @param client identification of the client
1107  * @param message the actual message
1108  */
1109 static void
1110 handle_start (void *cls,
1111               struct GNUNET_SERVER_Client *client,
1112               const struct GNUNET_MessageHeader *message)
1113 {
1114
1115 #if DEBUG_DV
1116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1117               "Received `%s' request from client\n", "START");
1118 #endif
1119
1120   client_handle = client;
1121
1122   GNUNET_SERVER_client_keep(client_handle);
1123   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1124 }
1125
1126
1127 /**
1128  * Iterate over hash map entries for a distant neighbor,
1129  * if direct neighbor matches context call send message
1130  *
1131  * @param cls closure, a DV_SendContext
1132  * @param key current key code
1133  * @param value value in the hash map
1134  * @return GNUNET_YES if we should continue to
1135  *         iterate,
1136  *         GNUNET_NO if not.
1137  */
1138 int send_iterator (void *cls,
1139                    const GNUNET_HashCode * key,
1140                    void *value)
1141 {
1142   struct DV_SendContext *send_context = cls;
1143   struct DistantNeighbor *distant_neighbor = value;
1144
1145   if (memcmp(distant_neighbor->referrer, send_context->direct_peer, sizeof(struct GNUNET_PeerIdentity)) == 0) /* They match, send and free */
1146     {
1147       send_message_via(&my_identity, distant_neighbor, send_context);
1148       return GNUNET_NO;
1149     }
1150   return GNUNET_YES;
1151 }
1152
1153 /**
1154  * Service server's handler for message send requests (which come
1155  * bubbling up to us through the DV plugin).
1156  *
1157  * @param cls closure
1158  * @param client identification of the client
1159  * @param message the actual message
1160  */
1161 void handle_dv_send_message (void *cls,
1162                       struct GNUNET_SERVER_Client * client,
1163                       const struct GNUNET_MessageHeader * message)
1164 {
1165   struct GNUNET_DV_SendMessage *send_msg;
1166   size_t address_len;
1167   size_t message_size;
1168   struct GNUNET_PeerIdentity *destination;
1169   struct GNUNET_PeerIdentity *direct;
1170   struct GNUNET_MessageHeader *message_buf;
1171   char *temp_pos;
1172   int offset;
1173   static struct GNUNET_CRYPTO_HashAsciiEncoded dest_hash;
1174   struct DV_SendContext *send_context;
1175
1176   if (client_handle == NULL)
1177   {
1178     client_handle = client;
1179     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1180               "%s: Setting initial client handle, never received `%s' message?\n", "dv", "START");
1181   }
1182   else if (client_handle != client)
1183   {
1184     client_handle = client;
1185     /* What should we do in this case, assert fail or just log the warning? */
1186     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1187                 "%s: Setting client handle (was a different client!)!\n", "dv");
1188   }
1189
1190   GNUNET_assert(ntohs(message->size) > sizeof(struct GNUNET_DV_SendMessage));
1191   send_msg = (struct GNUNET_DV_SendMessage *)message;
1192
1193   address_len = ntohs(send_msg->addrlen);
1194   GNUNET_assert(address_len == sizeof(struct GNUNET_PeerIdentity) * 2);
1195   message_size = ntohs(send_msg->msgbuf_size);
1196
1197 #if DEBUG_DV
1198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1199               "%s: Receives %s message size %u!\n\n\n", "dv", "SEND", message_size);
1200 #endif
1201   GNUNET_assert(ntohs(message->size) == sizeof(struct GNUNET_DV_SendMessage) + address_len + message_size);
1202   destination = GNUNET_malloc(sizeof(struct GNUNET_PeerIdentity));
1203   direct = GNUNET_malloc(sizeof(struct GNUNET_PeerIdentity));
1204   message_buf = GNUNET_malloc(message_size);
1205
1206   temp_pos = (char *)&send_msg[1]; /* Set pointer to end of message */
1207   offset = 0; /* Offset starts at zero */
1208
1209   memcpy(destination, &temp_pos[offset], sizeof(struct GNUNET_PeerIdentity));
1210   offset += sizeof(struct GNUNET_PeerIdentity);
1211
1212   memcpy(direct, &temp_pos[offset], sizeof(struct GNUNET_PeerIdentity));
1213   offset += sizeof(struct GNUNET_PeerIdentity);
1214
1215
1216   memcpy(message_buf, &temp_pos[offset], message_size);
1217   if (memcmp(&send_msg->target, destination, sizeof(struct GNUNET_PeerIdentity)) != 0)
1218     {
1219       GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash); /* GNUNET_i2s won't properly work, need to hash one ourselves */
1220       dest_hash.encoding[4] = '\0';
1221       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);
1222     }
1223
1224 #if DEBUG_DV
1225   GNUNET_CRYPTO_hash_to_enc (&destination->hashPubKey, &dest_hash); /* GNUNET_i2s won't properly work, need to hash one ourselves */
1226   dest_hash.encoding[4] = '\0';
1227   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "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));
1228 #endif
1229   send_context = GNUNET_malloc(sizeof(struct DV_SendContext));
1230
1231   send_context->importance = ntohs(send_msg->priority);
1232   send_context->timeout = send_msg->timeout;
1233   send_context->direct_peer = direct;
1234   send_context->distant_peer = destination;
1235   send_context->message = message_buf;
1236   send_context->message_size = message_size;
1237
1238   /* In bizarro world GNUNET_SYSERR indicates that we succeeded */
1239   if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple(ctx.extended_neighbors, &destination->hashPubKey, &send_iterator, send_context))
1240     {
1241       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));
1242     }
1243
1244   GNUNET_free(message_buf);
1245   GNUNET_free(send_context);
1246   GNUNET_free(direct);
1247   GNUNET_free(destination);
1248
1249   GNUNET_SERVER_receive_done(client, GNUNET_OK);
1250 }
1251
1252 static int handle_dv_gossip_message (void *cls,
1253                                      const struct GNUNET_PeerIdentity *peer,
1254                                      const struct GNUNET_MessageHeader *message,
1255                                      struct GNUNET_TIME_Relative latency,
1256                                      uint32_t distance);
1257
1258 /**
1259  * List of handlers for the messages understood by this
1260  * service.
1261  *
1262  * Hmm... will we need to register some handlers with core and
1263  * some handlers with our server here?  Because core should be
1264  * getting the incoming DV messages (from whichever lower level
1265  * transport) and then our server should be getting messages
1266  * from the dv_plugin, right?
1267  */
1268 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1269   {&handle_dv_data_message, GNUNET_MESSAGE_TYPE_DV_DATA, 0},
1270   {&handle_dv_gossip_message, GNUNET_MESSAGE_TYPE_DV_GOSSIP, 0},
1271   {NULL, 0, 0}
1272 };
1273
1274 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
1275   {&handle_dv_send_message, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_DV_SEND, 0},
1276   {&handle_start, NULL, GNUNET_MESSAGE_TYPE_DV_START, 0},
1277   {NULL, NULL, 0, 0}
1278 };
1279
1280
1281 /**
1282  * Task run during shutdown.
1283  *
1284  * @param cls unused
1285  * @param tc unused
1286  */
1287 static void
1288 shutdown_task (void *cls,
1289                const struct GNUNET_SCHEDULER_TaskContext *tc)
1290 {
1291 #if DEBUG_DV
1292   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "calling CORE_DISCONNECT\n");
1293 #endif
1294   GNUNET_CORE_disconnect (coreAPI);
1295 #if DEBUG_DV
1296   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "CORE_DISCONNECT completed\n");
1297 #endif
1298 }
1299
1300 /**
1301  * To be called on core init/fail.
1302  */
1303 void core_init (void *cls,
1304                 struct GNUNET_CORE_Handle * server,
1305                 const struct GNUNET_PeerIdentity *identity,
1306                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded * publicKey)
1307 {
1308
1309   if (server == NULL)
1310     {
1311       GNUNET_SCHEDULER_cancel(sched, cleanup_task);
1312       GNUNET_SCHEDULER_add_now(sched, &shutdown_task, NULL);
1313       return;
1314     }
1315 #if DEBUG_DV
1316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1317               "%s: Core connection initialized, I am peer: %s\n", "dv", GNUNET_i2s(identity));
1318 #endif
1319   memcpy(&my_identity, identity, sizeof(struct GNUNET_PeerIdentity));
1320   coreAPI = server;
1321 }
1322
1323 /**
1324  * Iterator over hash map entries.
1325  *
1326  * @param cls closure
1327  * @param key current key code
1328  * @param value value in the hash map
1329  * @return GNUNET_YES if we should continue to
1330  *         iterate,
1331  *         GNUNET_NO if not.
1332  */
1333 static int add_pkey_to_extended (void *cls,
1334                                  const GNUNET_HashCode * key,
1335                                  void *value)
1336 {
1337   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey = cls;
1338   struct DistantNeighbor *distant_neighbor = value;
1339
1340   if (distant_neighbor->pkey == NULL)
1341   {
1342     distant_neighbor->pkey = GNUNET_malloc(sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1343     memcpy(distant_neighbor->pkey, pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1344   }
1345
1346   return GNUNET_YES;
1347 }
1348
1349 /**
1350  * Iterator over hash map entries.
1351  *
1352  * @param cls closure
1353  * @param key current key code
1354  * @param value value in the hash map
1355  * @return GNUNET_YES if we should continue to
1356  *         iterate,
1357  *         GNUNET_NO if not.
1358  */
1359 static int update_matching_neighbors (void *cls,
1360                                       const GNUNET_HashCode * key,
1361                                       void *value)
1362 {
1363   struct NeighborUpdateInfo * update_info = cls;
1364   struct DistantNeighbor *distant_neighbor = value;
1365
1366   if (update_info->referrer == distant_neighbor->referrer) /* Direct neighbor matches, update it's info and return GNUNET_NO */
1367   {
1368     /* same referrer, cost change! */
1369     GNUNET_CONTAINER_heap_update_cost (ctx.neighbor_max_heap,
1370                                        update_info->neighbor->max_loc, update_info->cost);
1371     GNUNET_CONTAINER_heap_update_cost (ctx.neighbor_min_heap,
1372                                        update_info->neighbor->min_loc, update_info->cost);
1373     update_info->neighbor->last_activity = update_info->now;
1374     update_info->neighbor->cost = update_info->cost;
1375     return GNUNET_NO;
1376   }
1377
1378   return GNUNET_YES;
1379 }
1380
1381
1382 /**
1383  * Free a DistantNeighbor node, including removing it
1384  * from the referer's list.
1385  */
1386 static void
1387 distant_neighbor_free (struct DistantNeighbor *referee)
1388 {
1389   struct DirectNeighbor *referrer;
1390
1391   referrer = referee->referrer;
1392   if (referrer != NULL)
1393     {
1394       GNUNET_CONTAINER_DLL_remove (referrer->referee_head,
1395                          referrer->referee_tail, referee);
1396     }
1397   GNUNET_CONTAINER_heap_remove_node (ctx.neighbor_max_heap, referee->max_loc);
1398   GNUNET_CONTAINER_heap_remove_node (ctx.neighbor_min_heap, referee->min_loc);
1399   GNUNET_CONTAINER_multihashmap_remove_all (ctx.extended_neighbors,
1400                                     &referee->identity.hashPubKey);
1401   GNUNET_free (referee);
1402 }
1403
1404
1405 #if DEBUG_DV_GOSSIP
1406 /**
1407  * Iterator over hash map entries.
1408  *
1409  * @param cls closure (NULL)
1410  * @param key current key code
1411  * @param value value in the hash map (DistantNeighbor)
1412  * @return GNUNET_YES if we should continue to
1413  *         iterate,
1414  *         GNUNET_NO if not.
1415  */
1416 int print_neighbors (void *cls,
1417                      const GNUNET_HashCode * key,
1418                      void *value)
1419 {
1420   struct DistantNeighbor *distant_neighbor = value;
1421   char my_shortname[5];
1422   char referrer_shortname[5];
1423   memcpy(&my_shortname, GNUNET_i2s(&my_identity), 4);
1424   my_shortname[4] = '\0';
1425   memcpy(&referrer_shortname, GNUNET_i2s(&distant_neighbor->referrer->identity), 4);
1426   referrer_shortname[4] = '\0';
1427
1428   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);
1429   return GNUNET_YES;
1430 }
1431
1432 #endif
1433
1434 /**
1435  * Handles when a peer is either added due to being newly connected
1436  * or having been gossiped about, also called when the cost for a neighbor
1437  * needs to be updated.
1438  *
1439  * @param peer identity of the peer whose info is being added/updated
1440  * @param pkey public key of the peer whose info is being added/updated
1441  * @param referrer_peer_id id to use when sending to 'peer'
1442  * @param referrer if this is a gossiped peer, who did we hear it from?
1443  * @param cost the cost of communicating with this peer via 'referrer'
1444  */
1445 static void
1446 addUpdateNeighbor (const struct GNUNET_PeerIdentity * peer, struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
1447                    unsigned int referrer_peer_id,
1448                    struct DirectNeighbor *referrer, unsigned int cost)
1449 {
1450   struct DistantNeighbor *neighbor;
1451   struct DistantNeighbor *max;
1452   struct GNUNET_TIME_Absolute now;
1453   struct NeighborUpdateInfo *neighbor_update;
1454   unsigned int our_id;
1455
1456   now = GNUNET_TIME_absolute_get ();
1457   our_id = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, RAND_MAX - 1) + 1;
1458
1459   neighbor = GNUNET_CONTAINER_multihashmap_get (ctx.extended_neighbors,
1460                                                 &peer->hashPubKey);
1461   neighbor_update = GNUNET_malloc(sizeof(struct NeighborUpdateInfo));
1462   neighbor_update->neighbor = neighbor;
1463   neighbor_update->cost = cost;
1464   neighbor_update->now = now;
1465   neighbor_update->referrer = referrer;
1466
1467   /* Either we do not know this peer, or we already do but via a different immediate peer */
1468   if ((neighbor == NULL) ||
1469       (GNUNET_CONTAINER_multihashmap_get_multiple(ctx.extended_neighbors,
1470                                                   &peer->hashPubKey,
1471                                                   &update_matching_neighbors,
1472                                                   neighbor_update) != GNUNET_SYSERR))
1473     {
1474       /* new neighbor! */
1475       if (cost > ctx.fisheye_depth)
1476         {
1477           /* too costly */
1478           GNUNET_free(neighbor_update);
1479           return;
1480         }
1481       if (ctx.max_table_size <=
1482           GNUNET_CONTAINER_multihashmap_size (ctx.extended_neighbors))
1483         {
1484           /* remove most expensive entry */
1485           max = GNUNET_CONTAINER_heap_peek (ctx.neighbor_max_heap);
1486           if (cost > max->cost)
1487             {
1488               /* new entry most expensive, don't create */
1489               GNUNET_free(neighbor_update);
1490               return;
1491             }
1492           if (max->cost > 0)
1493             {
1494               /* only free if this is not a direct connection;
1495                  we could theoretically have more direct
1496                  connections than DV entries allowed total! */
1497               distant_neighbor_free (max);
1498             }
1499         }
1500
1501       neighbor = GNUNET_malloc (sizeof (struct DistantNeighbor));
1502       GNUNET_CONTAINER_DLL_insert (referrer->referee_head,
1503                          referrer->referee_tail, neighbor);
1504       neighbor->max_loc = GNUNET_CONTAINER_heap_insert (ctx.neighbor_max_heap,
1505                                                         neighbor, cost);
1506       neighbor->min_loc = GNUNET_CONTAINER_heap_insert (ctx.neighbor_min_heap,
1507                                                         neighbor, cost);
1508       neighbor->referrer = referrer;
1509       memcpy (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity));
1510       if (pkey != NULL) /* pkey will be null on direct neighbor addition */
1511       {
1512         neighbor->pkey = GNUNET_malloc(sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1513         memcpy (neighbor->pkey, pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1514       }
1515       else
1516         neighbor->pkey = pkey;
1517
1518       neighbor->last_activity = now;
1519       neighbor->cost = cost;
1520       neighbor->referrer_id = referrer_peer_id;
1521       neighbor->our_id = our_id;
1522       neighbor->hidden =
1523         (cost == 0) ? (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 4) ==
1524                        0) : GNUNET_NO;
1525       GNUNET_CONTAINER_multihashmap_put (ctx.extended_neighbors, &peer->hashPubKey,
1526                                  neighbor,
1527                                  GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1528     }
1529   else
1530     {
1531 #if DEBUG_DV_GOSSIP
1532       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1533                   "%s: Already know peer %s distance %d, referrer id %d!\n", "dv", GNUNET_i2s(peer), cost, referrer_peer_id);
1534 #endif
1535     }
1536 #if DEBUG_DV_GOSSIP
1537     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1538                 "%s: Size of extended_neighbors is %d\n", "dv", GNUNET_CONTAINER_multihashmap_size(ctx.extended_neighbors));
1539     GNUNET_CONTAINER_multihashmap_iterate(ctx.extended_neighbors, &print_neighbors, NULL);
1540 #endif
1541   GNUNET_free(neighbor_update);
1542   /* Old logic to remove entry and replace, not needed now as we only want to remove when full
1543    * or when the referring peer disconnects from us.
1544    *
1545    * FIXME: add new functionality, or check if it already exists (i forget)
1546    */
1547   /*
1548   GNUNET_DLL_remove (neighbor->referrer->referee_head,
1549                      neighbor->referrer->referee_tail, neighbor);
1550   neighbor->referrer = referrer;
1551   GNUNET_DLL_insert (referrer->referee_head,
1552                      referrer->referee_tail, neighbor);
1553   GNUNET_CONTAINER_heap_update_cost (ctx.neighbor_max_heap,
1554                                      neighbor->max_loc, cost);
1555   GNUNET_CONTAINER_heap_update_cost (ctx.neighbor_min_heap,
1556                                      neighbor->min_loc, cost);
1557   neighbor->referrer_id = referrer_peer_id;
1558   neighbor->last_activity = now;
1559   neighbor->cost = cost;
1560   */
1561 }
1562
1563
1564 static size_t
1565 generate_hello_address (void *cls, size_t max, void *buf)
1566 {
1567   struct HelloContext *hello_context = cls;
1568   char *addr_buffer;
1569   size_t offset;
1570   size_t size;
1571   size_t ret;
1572
1573   if (hello_context->addresses_to_add == 0)
1574     return 0;
1575
1576   /* Hello "address" will be concatenation of distant peer and direct peer identities */
1577   size = 2 * sizeof(struct GNUNET_PeerIdentity);
1578   GNUNET_assert(max >= size);
1579
1580   addr_buffer = GNUNET_malloc(size);
1581   offset = 0;
1582   /* Copy the distant peer identity to buffer */
1583   memcpy(addr_buffer, &hello_context->distant_peer, sizeof(struct GNUNET_PeerIdentity));
1584   offset += sizeof(struct GNUNET_PeerIdentity);
1585   /* Copy the direct peer identity to buffer */
1586   memcpy(&addr_buffer[offset], hello_context->direct_peer, sizeof(struct GNUNET_PeerIdentity));
1587   ret = GNUNET_HELLO_add_address ("dv",
1588                                   GNUNET_TIME_relative_to_absolute
1589                                   (GNUNET_TIME_UNIT_HOURS), addr_buffer, size,
1590                                   buf, max);
1591
1592   hello_context->addresses_to_add--;
1593
1594   GNUNET_free(addr_buffer);
1595   return ret;
1596 }
1597
1598
1599 /**
1600  * Core handler for dv gossip messages.  These will be used
1601  * by us to create a HELLO message for the newly peer containing
1602  * which direct peer we can connect through, and what the cost
1603  * is.  This HELLO will then be scheduled for validation by the
1604  * transport service so that it can be used by all others.
1605  *
1606  * @param cls closure
1607  * @param peer peer which sent the message (immediate sender)
1608  * @param message the message
1609  * @param latency the latency of the connection we received the message from
1610  * @param distance the distance to the immediate peer
1611  */
1612 static int handle_dv_gossip_message (void *cls,
1613                                      const struct GNUNET_PeerIdentity *peer,
1614                                      const struct GNUNET_MessageHeader *message,
1615                                      struct GNUNET_TIME_Relative latency,
1616                                      uint32_t distance)
1617 {
1618   struct HelloContext *hello_context;
1619   struct GNUNET_HELLO_Message *hello_msg;
1620   struct DirectNeighbor *referrer;
1621   p2p_dv_MESSAGE_NeighborInfo *enc_message = (p2p_dv_MESSAGE_NeighborInfo *)message;
1622
1623   if (ntohs (message->size) < sizeof (p2p_dv_MESSAGE_NeighborInfo))
1624     {
1625       return GNUNET_SYSERR;     /* invalid message */
1626     }
1627
1628 #if DEBUG_DV_GOSSIP
1629   char * encPeerAbout;
1630   char * encPeerFrom;
1631
1632   encPeerAbout = GNUNET_strdup(GNUNET_i2s(&enc_message->neighbor));
1633   encPeerFrom = GNUNET_strdup(GNUNET_i2s(peer));
1634   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1635               "%s: Receives %s message from peer %s about peer %s!\n", "dv", "DV GOSSIP", encPeerFrom, encPeerAbout);
1636   GNUNET_free(encPeerAbout);
1637   GNUNET_free(encPeerFrom);
1638 #endif
1639
1640   referrer = GNUNET_CONTAINER_multihashmap_get (ctx.direct_neighbors,
1641                                                 &peer->hashPubKey);
1642   if (referrer == NULL)
1643     return GNUNET_OK;
1644
1645   addUpdateNeighbor (&enc_message->neighbor, &enc_message->pkey,
1646                      ntohl (enc_message->neighbor_id),
1647                      referrer, ntohl (enc_message->cost) + 1);
1648
1649   hello_context = GNUNET_malloc(sizeof(struct HelloContext));
1650   hello_context->direct_peer = peer;
1651   memcpy(&hello_context->distant_peer, &enc_message->neighbor, sizeof(struct GNUNET_PeerIdentity));
1652   hello_context->addresses_to_add = 1;
1653   hello_msg = GNUNET_HELLO_create(&enc_message->pkey, &generate_hello_address, hello_context);
1654 #if DEBUG_DV_GOSSIP
1655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1656               "%s: Sending %s message to plugin, type is %d, size %d!\n", "dv", "HELLO", ntohs(hello_hdr->type), ntohs(hello_hdr->size));
1657 #endif
1658
1659   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);
1660   GNUNET_free(hello_context);
1661   GNUNET_free(hello_msg);
1662   return GNUNET_OK;
1663 }
1664
1665 static void
1666 process_peerinfo (void *cls,
1667          const struct GNUNET_PeerIdentity *peer,
1668          const struct GNUNET_HELLO_Message *hello, uint32_t trust)
1669 {
1670   struct PeerIteratorContext *peerinfo_iterator = cls;
1671   struct DirectNeighbor *neighbor = peerinfo_iterator->neighbor;
1672
1673   if ((peer == NULL))/* && (neighbor->pkey == NULL))*/
1674     {
1675       /* FIXME: Remove peer! */
1676       GNUNET_free(peerinfo_iterator);
1677       return;
1678     }
1679
1680   if (memcmp(&neighbor->identity, peer, sizeof(struct GNUNET_PeerIdentity) != 0))
1681     return;
1682
1683   if ((hello != NULL) && (GNUNET_HELLO_get_key (hello, &neighbor->pkey) == GNUNET_OK))
1684     {
1685       GNUNET_CONTAINER_multihashmap_get_multiple(ctx.extended_neighbors,
1686                                                  &peer->hashPubKey,
1687                                                  &add_pkey_to_extended,
1688                                                  &neighbor->pkey);
1689       neighbor->send_context->task = GNUNET_SCHEDULER_add_now(sched, &neighbor_send_task, neighbor->send_context);
1690     }
1691 }
1692
1693 /**
1694  * Method called whenever a peer connects.
1695  *
1696  * @param cls closure
1697  * @param peer peer identity this notification is about
1698  * @param latency reported latency of the connection with peer
1699  * @param distance reported distance (DV) to peer
1700  */
1701 void handle_core_connect (void *cls,
1702                           const struct GNUNET_PeerIdentity * peer,
1703                           struct GNUNET_TIME_Relative latency,
1704                           uint32_t distance)
1705 {
1706   struct DirectNeighbor *neighbor;
1707   struct PeerIteratorContext *peerinfo_iterator;
1708 #if DEBUG_DV
1709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1710               "%s: Receives core connect message for peer %s distance %d!\n", "dv", GNUNET_i2s(peer), distance);
1711 #endif
1712
1713   if ((distance == 0) && (GNUNET_CONTAINER_multihashmap_get(ctx.direct_neighbors, &peer->hashPubKey) == NULL))
1714   {
1715     peerinfo_iterator = GNUNET_malloc(sizeof(struct PeerIteratorContext));
1716     neighbor = GNUNET_malloc (sizeof (struct DirectNeighbor));
1717     neighbor->send_context = GNUNET_malloc(sizeof(struct NeighborSendContext));
1718     neighbor->send_context->toNeighbor = neighbor;
1719     neighbor->send_context->timeout = default_dv_delay; /* FIXME: base this on total gossip tasks, or bandwidth */
1720     memcpy (&neighbor->identity, peer, sizeof (struct GNUNET_PeerIdentity));
1721     /*memcpy (&neighbor->pkey, ,sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));*/
1722     GNUNET_CONTAINER_multihashmap_put (ctx.direct_neighbors,
1723                                &peer->hashPubKey,
1724                                neighbor, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1725     addUpdateNeighbor (peer, NULL, 0, neighbor, 0);
1726     peerinfo_iterator->neighbor = neighbor;
1727     peerinfo_iterator->ic = GNUNET_PEERINFO_iterate (cfg,
1728                                             sched,
1729                                             peer,
1730                                             0,
1731                                             GNUNET_TIME_relative_multiply
1732                                             (GNUNET_TIME_UNIT_SECONDS, 15),
1733                                             &process_peerinfo, peerinfo_iterator);
1734     /* Only add once we get the publicKey of this guy
1735      *
1736      * neighbor->send_context->task = GNUNET_SCHEDULER_add_now(sched, &neighbor_send_task, neighbor->send_context);
1737      */
1738   }
1739   else
1740   {
1741 #if DEBUG_DV
1742   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1743               "%s: Distance (%d) greater than 0 or already know about peer (%s), not re-adding!\n", "dv", distance, GNUNET_i2s(peer));
1744 #endif
1745     return;
1746   }
1747 }
1748
1749 /**
1750  * Method called whenever a given peer disconnects.
1751  *
1752  * @param cls closure
1753  * @param peer peer identity this notification is about
1754  */
1755 void handle_core_disconnect (void *cls,
1756                              const struct GNUNET_PeerIdentity * peer)
1757 {
1758   struct DirectNeighbor *neighbor;
1759   struct DistantNeighbor *referee;
1760
1761 #if DEBUG_DV
1762   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1763               "%s: Receives core peer disconnect message!\n", "dv");
1764 #endif
1765
1766   neighbor =
1767     GNUNET_CONTAINER_multihashmap_get (ctx.direct_neighbors, &peer->hashPubKey);
1768   if (neighbor == NULL)
1769     {
1770       return;
1771     }
1772   while (NULL != (referee = neighbor->referee_head))
1773     distant_neighbor_free (referee);
1774   GNUNET_assert (neighbor->referee_tail == NULL);
1775   GNUNET_CONTAINER_multihashmap_remove (ctx.direct_neighbors,
1776                                 &peer->hashPubKey, neighbor);
1777   if ((neighbor->send_context != NULL) && (neighbor->send_context->task != GNUNET_SCHEDULER_NO_TASK))
1778     GNUNET_SCHEDULER_cancel(sched, neighbor->send_context->task);
1779   GNUNET_free (neighbor);
1780 }
1781
1782
1783 /**
1784  * Process dv requests.
1785  *
1786  * @param cls closure
1787  * @param scheduler scheduler to use
1788  * @param server the initialized server
1789  * @param c configuration to use
1790  */
1791 static void
1792 run (void *cls,
1793      struct GNUNET_SCHEDULER_Handle *scheduler,
1794      struct GNUNET_SERVER_Handle *server,
1795      const struct GNUNET_CONFIGURATION_Handle *c)
1796 {
1797   struct GNUNET_TIME_Relative timeout;
1798   unsigned long long max_hosts;
1799   timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5);
1800   sched = scheduler;
1801   cfg = c;
1802
1803   /* FIXME: Read from config, or calculate, or something other than this! */
1804   max_hosts = 50;
1805   ctx.max_table_size = 100;
1806   ctx.fisheye_depth = 3;
1807
1808   ctx.neighbor_min_heap =
1809     GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1810   ctx.neighbor_max_heap =
1811     GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MAX);
1812
1813   ctx.direct_neighbors = GNUNET_CONTAINER_multihashmap_create (max_hosts);
1814   ctx.extended_neighbors =
1815     GNUNET_CONTAINER_multihashmap_create (ctx.max_table_size * 3);
1816
1817   client_transmit_timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5);
1818   default_dv_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5);
1819   GNUNET_SERVER_add_handlers (server, plugin_handlers);
1820   coreAPI =
1821   GNUNET_CORE_connect (sched,
1822                        cfg,
1823                        timeout,
1824                        NULL, /* FIXME: anything we want to pass around? */
1825                        &core_init,
1826                        &handle_core_connect,
1827                        &handle_core_disconnect,
1828                        NULL,
1829                        GNUNET_NO,
1830                        NULL,
1831                        GNUNET_NO,
1832                        core_handlers);
1833
1834   if (coreAPI == NULL)
1835     return;
1836   /* load (server); Huh? */
1837
1838   /* Scheduled the task to clean up when shutdown is called */
1839   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
1840                                 GNUNET_TIME_UNIT_FOREVER_REL,
1841                                 &shutdown_task,
1842                                 NULL);
1843 }
1844
1845
1846 /**
1847  * The main function for the dv service.
1848  *
1849  * @param argc number of arguments from the command line
1850  * @param argv command line arguments
1851  * @return 0 ok, 1 on error
1852  */
1853 int
1854 main (int argc, char *const *argv)
1855 {
1856   return (GNUNET_OK ==
1857           GNUNET_SERVICE_run (argc,
1858                               argv,
1859                               "dv",
1860                               GNUNET_SERVICE_OPTION_NONE,
1861                               &run, NULL)) ? 0 : 1;
1862 }