2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
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.
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.
23 * @brief library to access the DHT service
24 * @author Christian Grothoff
25 * @author Nathan Evans
29 #include "gnunet_util_lib.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_arm_service.h"
32 #include "gnunet_hello_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_dht_service.h"
37 #define DEBUG_DHT_API GNUNET_EXTRA_LOGGING
39 #define LOG(kind,...) GNUNET_log_from (kind, "dht-api",__VA_ARGS__)
42 * Entry in our list of messages to be (re-)transmitted.
47 * This is a doubly-linked list.
49 struct PendingMessage *prev;
52 * This is a doubly-linked list.
54 struct PendingMessage *next;
57 * Message that is pending, allocated at the end
60 const struct GNUNET_MessageHeader *msg;
63 * Handle to the DHT API context.
65 struct GNUNET_DHT_Handle *handle;
68 * Continuation to call when the request has been
69 * transmitted (for the first time) to the service; can be NULL.
71 GNUNET_SCHEDULER_Task cont;
79 * Timeout task for this message
81 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
84 * Unique ID for this request
89 * Free the saved message once sent, set to GNUNET_YES for messages
90 * that do not receive responses; GNUNET_NO if this pending message
91 * is aliased from a 'struct GNUNET_DHT_RouteHandle' and will be freed
97 * GNUNET_YES if this message is in our pending queue right now.
105 * Handle to a GET request
107 struct GNUNET_DHT_GetHandle
111 * Iterator to call on data receipt
113 GNUNET_DHT_GetIterator iter;
116 * Closure for the iterator callback
121 * Main handle to this DHT api
123 struct GNUNET_DHT_Handle *dht_handle;
126 * The actual message sent for this request,
127 * used for retransmitting requests on service
128 * failure/reconnect. Freed on route_stop.
130 struct PendingMessage *message;
133 * Key that this get request is for
138 * Unique identifier for this request (for key collisions).
146 * Connection to the DHT service.
148 struct GNUNET_DHT_Handle
152 * Configuration to use.
154 const struct GNUNET_CONFIGURATION_Handle *cfg;
157 * Socket (if available).
159 struct GNUNET_CLIENT_Connection *client;
162 * Currently pending transmission request (or NULL).
164 struct GNUNET_CLIENT_TransmitHandle *th;
167 * Head of linked list of messages we would like to transmit.
169 struct PendingMessage *pending_head;
172 * Tail of linked list of messages we would like to transmit.
174 struct PendingMessage *pending_tail;
177 * Hash map containing the current outstanding unique requests
178 * (values are of type 'struct GNUNET_DHT_RouteHandle').
180 struct GNUNET_CONTAINER_MultiHashMap *active_requests;
183 * Task for trying to reconnect.
185 GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
188 * How quickly should we retry? Used for exponential back-off on
191 struct GNUNET_TIME_Relative retry_time;
194 * Generator for unique ids.
202 * Handler for messages received from the DHT service
203 * a demultiplexer which handles numerous message types
207 service_message_handler (void *cls, const struct GNUNET_MessageHeader *msg);
211 * Try to (re)connect to the DHT service.
213 * @return GNUNET_YES on success, GNUNET_NO on failure.
216 try_connect (struct GNUNET_DHT_Handle *handle)
218 if (handle->client != NULL)
220 handle->client = GNUNET_CLIENT_connect ("dht", handle->cfg);
221 if (handle->client == NULL)
223 LOG (GNUNET_ERROR_TYPE_WARNING,
224 _("Failed to connect to the DHT service!\n"));
228 LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting to process replies from DHT\n");
230 GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
231 GNUNET_TIME_UNIT_FOREVER_REL);
237 * Add the request corresponding to the given route handle
238 * to the pending queue (if it is not already in there).
240 * @param cls the 'struct GNUNET_DHT_Handle*'
241 * @param key key for the request (not used)
242 * @param value the 'struct GNUNET_DHT_GetHandle*'
243 * @return GNUNET_YES (always)
246 add_request_to_pending (void *cls, const GNUNET_HashCode * key, void *value)
248 struct GNUNET_DHT_Handle *handle = cls;
249 struct GNUNET_DHT_GetHandle *rh = value;
251 if (GNUNET_NO == rh->message->in_pending_queue)
253 GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
255 rh->message->in_pending_queue = GNUNET_YES;
262 * Try to send messages from list of messages to send
263 * @param handle DHT_Handle
266 process_pending_messages (struct GNUNET_DHT_Handle *handle);
270 * Try reconnecting to the dht service.
272 * @param cls GNUNET_DHT_Handle
273 * @param tc scheduler context
276 try_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
278 struct GNUNET_DHT_Handle *handle = cls;
280 LOG (GNUNET_ERROR_TYPE_DEBUG,
281 "Reconnedting with DHT %p\n",
283 handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
284 if (handle->retry_time.rel_value < GNUNET_CONSTANTS_SERVICE_RETRY.rel_value)
285 handle->retry_time = GNUNET_CONSTANTS_SERVICE_RETRY;
287 handle->retry_time = GNUNET_TIME_relative_multiply (handle->retry_time, 2);
288 if (handle->retry_time.rel_value > GNUNET_CONSTANTS_SERVICE_TIMEOUT.rel_value)
289 handle->retry_time = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
290 handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
291 handle->client = GNUNET_CLIENT_connect ("dht", handle->cfg);
292 if (handle->client == NULL)
294 LOG (GNUNET_ERROR_TYPE_DEBUG, "dht reconnect failed(!)\n");
297 GNUNET_CONTAINER_multihashmap_iterate (handle->active_requests,
298 &add_request_to_pending, handle);
299 process_pending_messages (handle);
304 * Try reconnecting to the DHT service.
306 * @param handle handle to dht to (possibly) disconnect and reconnect
309 do_disconnect (struct GNUNET_DHT_Handle *handle)
311 if (handle->client == NULL)
313 GNUNET_assert (handle->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
314 if (NULL != handle->th)
315 GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
318 "Disconnecting from DHT service, will try to reconnect in %llu ms\n",
319 (unsigned long long) handle->retry_time.rel_value);
320 GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
321 handle->client = NULL;
322 handle->reconnect_task =
323 GNUNET_SCHEDULER_add_delayed (handle->retry_time, &try_reconnect, handle);
328 * Transmit the next pending message, called by notify_transmit_ready
331 transmit_pending (void *cls, size_t size, void *buf);
335 * Try to send messages from list of messages to send
338 process_pending_messages (struct GNUNET_DHT_Handle *handle)
340 struct PendingMessage *head;
342 if (handle->client == NULL)
344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
345 "process_pending_messages called, but client is null, reconnecting\n");
346 do_disconnect (handle);
349 if (handle->th != NULL)
351 if (NULL == (head = handle->pending_head))
354 GNUNET_CLIENT_notify_transmit_ready (handle->client,
355 ntohs (head->msg->size),
356 GNUNET_TIME_UNIT_FOREVER_REL,
357 GNUNET_YES, &transmit_pending,
359 if (NULL != handle->th)
361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
362 "notify_transmit_ready returned NULL, reconnecting\n");
363 do_disconnect (handle);
368 * Transmit the next pending message, called by notify_transmit_ready
371 transmit_pending (void *cls, size_t size, void *buf)
373 struct GNUNET_DHT_Handle *handle = cls;
374 struct PendingMessage *head;
380 LOG (GNUNET_ERROR_TYPE_DEBUG,
381 "Transmission to DHT service failed! Reconnecting!\n");
382 do_disconnect (handle);
385 if (NULL == (head = handle->pending_head))
388 tsize = ntohs (head->msg->size);
391 process_pending_messages (handle);
394 memcpy (buf, head->msg, tsize);
395 GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
397 if (head->timeout_task != GNUNET_SCHEDULER_NO_TASK)
399 GNUNET_SCHEDULER_cancel (head->timeout_task);
400 head->timeout_task = GNUNET_SCHEDULER_NO_TASK;
402 if (NULL != head->cont)
404 GNUNET_SCHEDULER_add_continuation (head->cont, head->cont_cls,
405 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
407 head->cont_cls = NULL;
409 head->in_pending_queue = GNUNET_NO;
410 if (GNUNET_YES == head->free_on_send)
412 process_pending_messages (handle);
414 LOG (GNUNET_ERROR_TYPE_DEBUG,
415 "Forwarded request of %u bytes to DHT service\n", (unsigned int) tsize);
422 * Process a given reply that might match the given
425 * @param cls the 'struct GNUNET_DHT_ClientResultMessage'
426 * @param key query of the request
427 * @param value the 'struct GNUNET_DHT_RouteHandle' of a request matching the same key
428 * @return GNUNET_YES to continue to iterate over all results,
429 * GNUNET_NO if the reply is malformed
432 process_reply (void *cls, const GNUNET_HashCode * key, void *value)
434 const struct GNUNET_DHT_ClientResultMessage *dht_msg = cls;
435 struct GNUNET_DHT_GetHandle *get_handle = value;
436 const struct GNUNET_PeerIdentity *put_path;
437 const struct GNUNET_PeerIdentity *get_path;
438 uint32_t put_path_length;
439 uint32_t get_path_length;
445 if (dht_msg->unique_id != get_handle->unique_id)
448 LOG (GNUNET_ERROR_TYPE_DEBUG,
449 "Ignoring reply for %s: UID mismatch: %llu/%llu\n",
451 dht_msg->unique_id, get_handle->unique_id);
454 msize = ntohs (dht_msg->header.size);
455 put_path_length = ntohl (dht_msg->put_path_length);
456 get_path_length = ntohl (dht_msg->get_path_length);
458 sizeof (struct GNUNET_DHT_ClientResultMessage) +
459 sizeof (struct GNUNET_PeerIdentity) * (get_path_length + put_path_length);
460 if ((msize < meta_length) ||
462 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
464 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
469 data_length = msize - meta_length;
470 LOG (GNUNET_ERROR_TYPE_DEBUG,
471 "Giving %u byte reply for %s to application\n",
472 (unsigned int) data_length,
474 put_path = (const struct GNUNET_PeerIdentity *) &dht_msg[1];
475 get_path = &put_path[put_path_length];
476 data = &get_path[get_path_length];
477 get_handle->iter (get_handle->iter_cls,
478 GNUNET_TIME_absolute_ntoh (dht_msg->expiration), key,
479 get_path, get_path_length, put_path, put_path_length,
480 ntohl (dht_msg->type), data_length, data);
486 * Handler for messages received from the DHT service
487 * a demultiplexer which handles numerous message types
489 * @param cls the 'struct GNUNET_DHT_Handle'
490 * @param msg the incoming message
493 service_message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
495 struct GNUNET_DHT_Handle *handle = cls;
496 const struct GNUNET_DHT_ClientResultMessage *dht_msg;
500 LOG (GNUNET_ERROR_TYPE_DEBUG,
501 "Error receiving data from DHT service, reconnecting\n");
502 do_disconnect (handle);
505 if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT)
508 do_disconnect (handle);
511 if (ntohs (msg->size) < sizeof (struct GNUNET_DHT_ClientResultMessage))
514 do_disconnect (handle);
517 dht_msg = (const struct GNUNET_DHT_ClientResultMessage *) msg;
518 LOG (GNUNET_ERROR_TYPE_DEBUG,
519 "Received reply for `%s' from DHT service %p\n",
520 GNUNET_h2s (&dht_msg->key),
522 GNUNET_CONTAINER_multihashmap_get_multiple (handle->active_requests,
523 &dht_msg->key, &process_reply,
525 GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
526 GNUNET_TIME_UNIT_FOREVER_REL);
531 * Initialize the connection with the DHT service.
533 * @param cfg configuration to use
534 * @param ht_len size of the internal hash table to use for
535 * processing multiple GET/FIND requests in parallel
537 * @return handle to the DHT service, or NULL on error
539 struct GNUNET_DHT_Handle *
540 GNUNET_DHT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
543 struct GNUNET_DHT_Handle *handle;
545 handle = GNUNET_malloc (sizeof (struct GNUNET_DHT_Handle));
548 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
549 handle->active_requests = GNUNET_CONTAINER_multihashmap_create (ht_len);
550 if (GNUNET_NO == try_connect (handle))
552 GNUNET_DHT_disconnect (handle);
560 * Shutdown connection with the DHT service.
562 * @param handle handle of the DHT connection to stop
565 GNUNET_DHT_disconnect (struct GNUNET_DHT_Handle *handle)
567 struct PendingMessage *pm;
569 GNUNET_assert (handle != NULL);
571 GNUNET_CONTAINER_multihashmap_size (handle->active_requests));
572 if (handle->th != NULL)
574 GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
577 while (NULL != (pm = handle->pending_head))
579 GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
581 GNUNET_assert (GNUNET_YES == pm->free_on_send);
582 if (GNUNET_SCHEDULER_NO_TASK != pm->timeout_task)
583 GNUNET_SCHEDULER_cancel (pm->timeout_task);
584 if (NULL != pm->cont)
585 GNUNET_SCHEDULER_add_continuation (pm->cont, pm->cont_cls,
586 GNUNET_SCHEDULER_REASON_TIMEOUT);
587 pm->in_pending_queue = GNUNET_NO;
590 if (handle->client != NULL)
592 GNUNET_CLIENT_disconnect (handle->client, GNUNET_YES);
593 handle->client = NULL;
595 if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
596 GNUNET_SCHEDULER_cancel (handle->reconnect_task);
597 GNUNET_CONTAINER_multihashmap_destroy (handle->active_requests);
598 GNUNET_free (handle);
603 * Timeout for the transmission of a fire&forget-request. Clean it up.
605 * @param cls the 'struct PendingMessage'
606 * @param tc scheduler context
609 timeout_put_request (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
611 struct PendingMessage *pending = cls;
612 struct GNUNET_DHT_Handle *handle;
614 handle = pending->handle;
615 GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
617 if (pending->cont != NULL)
618 pending->cont (pending->cont_cls, tc);
619 GNUNET_free (pending);
624 * Perform a PUT operation storing data in the DHT.
626 * @param handle handle to DHT service
627 * @param key the key to store under
628 * @param desired_replication_level estimate of how many
629 * nearest peers this request should reach
630 * @param options routing options for this message
631 * @param type type of the value
632 * @param size number of bytes in data; must be less than 64k
633 * @param data the data to store
634 * @param exp desired expiration time for the value
635 * @param timeout how long to wait for transmission of this request
636 * @param cont continuation to call when done (transmitting request to service)
637 * @param cont_cls closure for cont
640 GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle, const GNUNET_HashCode * key,
641 uint32_t desired_replication_level,
642 enum GNUNET_DHT_RouteOption options,
643 enum GNUNET_BLOCK_Type type, size_t size, const char *data,
644 struct GNUNET_TIME_Absolute exp,
645 struct GNUNET_TIME_Relative timeout, GNUNET_SCHEDULER_Task cont,
648 struct GNUNET_DHT_ClientPutMessage *put_msg;
650 struct PendingMessage *pending;
652 msize = sizeof (struct GNUNET_DHT_ClientPutMessage) + size;
653 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
654 (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
658 cont (cont_cls, NULL);
661 pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
662 put_msg = (struct GNUNET_DHT_ClientPutMessage *) &pending[1];
663 pending->msg = &put_msg->header;
664 pending->handle = handle;
665 pending->cont = cont;
666 pending->cont_cls = cont_cls;
667 pending->free_on_send = GNUNET_YES;
668 pending->timeout_task =
669 GNUNET_SCHEDULER_add_delayed (timeout, &timeout_put_request, pending);
670 put_msg->header.size = htons (msize);
671 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT);
672 put_msg->type = htonl (type);
673 put_msg->options = htonl ((uint32_t) options);
674 put_msg->desired_replication_level = htonl (desired_replication_level);
675 put_msg->expiration = GNUNET_TIME_absolute_hton (exp);
677 memcpy (&put_msg[1], data, size);
678 GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
680 pending->in_pending_queue = GNUNET_YES;
681 process_pending_messages (handle);
686 * Perform an asynchronous GET operation on the DHT identified. See
687 * also "GNUNET_BLOCK_evaluate".
689 * @param handle handle to the DHT service
690 * @param timeout how long to wait for transmission of this request to the service
691 * @param type expected type of the response object
692 * @param key the key to look up
693 * @param desired_replication_level estimate of how many
694 nearest peers this request should reach
695 * @param options routing options for this message
696 * @param xquery extended query data (can be NULL, depending on type)
697 * @param xquery_size number of bytes in xquery
698 * @param iter function to call on each result
699 * @param iter_cls closure for iter
700 * @return handle to stop the async get
702 struct GNUNET_DHT_GetHandle *
703 GNUNET_DHT_get_start (struct GNUNET_DHT_Handle *handle,
704 struct GNUNET_TIME_Relative timeout,
705 enum GNUNET_BLOCK_Type type, const GNUNET_HashCode * key,
706 uint32_t desired_replication_level,
707 enum GNUNET_DHT_RouteOption options, const void *xquery,
708 size_t xquery_size, GNUNET_DHT_GetIterator iter,
711 struct GNUNET_DHT_ClientGetMessage *get_msg;
712 struct GNUNET_DHT_GetHandle *get_handle;
714 struct PendingMessage *pending;
716 msize = sizeof (struct GNUNET_DHT_ClientGetMessage) + xquery_size;
717 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
718 (xquery_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
723 LOG (GNUNET_ERROR_TYPE_DEBUG,
724 "Sending query for %s to DHT %p\n",
727 pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
728 get_msg = (struct GNUNET_DHT_ClientGetMessage *) &pending[1];
729 pending->msg = &get_msg->header;
730 pending->handle = handle;
731 pending->free_on_send = GNUNET_NO;
732 get_msg->header.size = htons (msize);
733 get_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET);
734 get_msg->options = htonl ((uint32_t) options);
735 get_msg->desired_replication_level = htonl (desired_replication_level);
736 get_msg->type = htonl (type);
739 get_msg->unique_id = handle->uid_gen;
740 memcpy (&get_msg[1], xquery, xquery_size);
741 GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
743 pending->in_pending_queue = GNUNET_YES;
744 get_handle = GNUNET_malloc (sizeof (struct GNUNET_DHT_GetHandle));
745 get_handle->iter = iter;
746 get_handle->iter_cls = iter_cls;
747 get_handle->message = pending;
748 get_handle->unique_id = get_msg->unique_id;
749 GNUNET_CONTAINER_multihashmap_put (handle->active_requests, key, get_handle,
750 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
751 process_pending_messages (handle);
757 * Stop async DHT-get.
759 * @param get_handle handle to the GET operation to stop
762 GNUNET_DHT_get_stop (struct GNUNET_DHT_GetHandle *get_handle)
764 struct GNUNET_DHT_Handle *handle;
765 const struct GNUNET_DHT_ClientGetMessage *get_msg;
766 struct GNUNET_DHT_ClientGetStopMessage *stop_msg;
767 struct PendingMessage *pending;
769 handle = get_handle->message->handle;
771 (const struct GNUNET_DHT_ClientGetMessage *) get_handle->message->msg;
772 LOG (GNUNET_ERROR_TYPE_DEBUG,
773 "Sending STOP for %s to DHT via %p\n",
774 GNUNET_h2s (&get_msg->key),
778 GNUNET_malloc (sizeof (struct PendingMessage) +
779 sizeof (struct GNUNET_DHT_ClientGetStopMessage));
780 stop_msg = (struct GNUNET_DHT_ClientGetStopMessage *) &pending[1];
781 pending->msg = &stop_msg->header;
782 pending->handle = handle;
783 pending->free_on_send = GNUNET_YES;
784 stop_msg->header.size =
785 htons (sizeof (struct GNUNET_DHT_ClientGetStopMessage));
786 stop_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP);
787 stop_msg->reserved = htonl (0);
788 stop_msg->unique_id = get_msg->unique_id;
789 stop_msg->key = get_msg->key;
790 GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
792 pending->in_pending_queue = GNUNET_YES;
794 /* remove 'GET' from active status */
795 GNUNET_assert (GNUNET_YES ==
796 GNUNET_CONTAINER_multihashmap_remove (handle->active_requests,
799 if (GNUNET_YES == get_handle->message->in_pending_queue)
801 GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
802 get_handle->message);
803 get_handle->message->in_pending_queue = GNUNET_NO;
805 GNUNET_free (get_handle->message);
806 GNUNET_free (get_handle);
808 process_pending_messages (handle);
812 /* end of dht_api.c */