e0b97b4577404315749e7ff614f78fd95ba13181
[oweals/gnunet.git] / src / dht / dht_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file dht/dht_api.c
23  * @brief library to access the DHT service
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  */
27
28 #include "platform.h"
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"
35 #include "dht.h"
36
37 #define DEBUG_DHT_API GNUNET_EXTRA_LOGGING
38
39 #define LOG(kind,...) GNUNET_log_from (kind, "dht-api",__VA_ARGS__)
40
41 /**
42  * Entry in our list of messages to be (re-)transmitted.
43  */
44 struct PendingMessage
45 {
46   /**
47    * This is a doubly-linked list.
48    */
49   struct PendingMessage *prev;
50
51   /**
52    * This is a doubly-linked list.
53    */
54   struct PendingMessage *next;
55
56   /**
57    * Message that is pending, allocated at the end
58    * of this struct.
59    */
60   const struct GNUNET_MessageHeader *msg;
61
62   /**
63    * Handle to the DHT API context.
64    */
65   struct GNUNET_DHT_Handle *handle;
66
67   /**
68    * Continuation to call when the request has been
69    * transmitted (for the first time) to the service; can be NULL.
70    */
71   GNUNET_SCHEDULER_Task cont;
72
73   /**
74    * Closure for 'cont'.
75    */
76   void *cont_cls;
77
78   /**
79    * Timeout task for this message
80    */
81   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
82
83   /**
84    * Unique ID for this request
85    */
86   uint64_t unique_id;
87
88   /**
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
92    * from there.
93    */
94   int free_on_send;
95
96   /**
97    * GNUNET_YES if this message is in our pending queue right now.
98    */
99   int in_pending_queue;
100
101 };
102
103
104 /**
105  * Handle to a GET request
106  */
107 struct GNUNET_DHT_GetHandle
108 {
109
110   /**
111    * Iterator to call on data receipt
112    */
113   GNUNET_DHT_GetIterator iter;
114
115   /**
116    * Closure for the iterator callback
117    */
118   void *iter_cls;
119
120   /**
121    * Main handle to this DHT api
122    */
123   struct GNUNET_DHT_Handle *dht_handle;
124
125   /**
126    * The actual message sent for this request,
127    * used for retransmitting requests on service
128    * failure/reconnect.  Freed on route_stop.
129    */
130   struct PendingMessage *message;
131
132   /**
133    * Key that this get request is for
134    */
135   GNUNET_HashCode key;
136
137   /**
138    * Unique identifier for this request (for key collisions).
139    */
140   uint64_t unique_id;
141
142 };
143
144
145 /**
146  * Connection to the DHT service.
147  */
148 struct GNUNET_DHT_Handle
149 {
150
151   /**
152    * Configuration to use.
153    */
154   const struct GNUNET_CONFIGURATION_Handle *cfg;
155
156   /**
157    * Socket (if available).
158    */
159   struct GNUNET_CLIENT_Connection *client;
160
161   /**
162    * Currently pending transmission request (or NULL).
163    */
164   struct GNUNET_CLIENT_TransmitHandle *th;
165
166   /**
167    * Head of linked list of messages we would like to transmit.
168    */
169   struct PendingMessage *pending_head;
170
171   /**
172    * Tail of linked list of messages we would like to transmit.
173    */
174   struct PendingMessage *pending_tail;
175
176   /**
177    * Hash map containing the current outstanding unique requests
178    * (values are of type 'struct GNUNET_DHT_RouteHandle').
179    */
180   struct GNUNET_CONTAINER_MultiHashMap *active_requests;
181
182   /**
183    * Task for trying to reconnect.
184    */
185   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
186
187   /**
188    * How quickly should we retry?  Used for exponential back-off on
189    * connect-errors.
190    */
191   struct GNUNET_TIME_Relative retry_time;
192
193   /**
194    * Generator for unique ids.
195    */
196   uint64_t uid_gen;
197
198 };
199
200
201 /**
202  * Handler for messages received from the DHT service
203  * a demultiplexer which handles numerous message types
204  *
205  */
206 static void
207 service_message_handler (void *cls, const struct GNUNET_MessageHeader *msg);
208
209
210 /**
211  * Try to (re)connect to the DHT service.
212  *
213  * @return GNUNET_YES on success, GNUNET_NO on failure.
214  */
215 static int
216 try_connect (struct GNUNET_DHT_Handle *handle)
217 {
218   if (handle->client != NULL)
219     return GNUNET_OK;
220   handle->client = GNUNET_CLIENT_connect ("dht", handle->cfg);
221   if (handle->client == NULL)
222   {
223     LOG (GNUNET_ERROR_TYPE_WARNING,
224          _("Failed to connect to the DHT service!\n"));
225     return GNUNET_NO;
226   }
227 #if DEBUG_DHT
228   LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting to process replies from DHT\n");
229 #endif
230   GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
231                          GNUNET_TIME_UNIT_FOREVER_REL);
232   return GNUNET_YES;
233 }
234
235
236 /**
237  * Add the request corresponding to the given route handle
238  * to the pending queue (if it is not already in there).
239  *
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)
244  */
245 static int
246 add_request_to_pending (void *cls, const GNUNET_HashCode * key, void *value)
247 {
248   struct GNUNET_DHT_Handle *handle = cls;
249   struct GNUNET_DHT_GetHandle *rh = value;
250
251   if (GNUNET_NO == rh->message->in_pending_queue)
252   {
253     GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
254                                  rh->message);
255     rh->message->in_pending_queue = GNUNET_YES;
256   }
257   return GNUNET_YES;
258 }
259
260
261 /**
262  * Try to send messages from list of messages to send
263  * @param handle DHT_Handle
264  */
265 static void
266 process_pending_messages (struct GNUNET_DHT_Handle *handle);
267
268
269 /**
270  * Try reconnecting to the dht service.
271  *
272  * @param cls GNUNET_DHT_Handle
273  * @param tc scheduler context
274  */
275 static void
276 try_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
277 {
278   struct GNUNET_DHT_Handle *handle = cls;
279
280   LOG (GNUNET_ERROR_TYPE_DEBUG,
281        "Reconnedting with DHT %p\n",
282        handle);
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;
286   else
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)
293   {
294     LOG (GNUNET_ERROR_TYPE_DEBUG, "dht reconnect failed(!)\n");
295     return;
296   }
297   GNUNET_CONTAINER_multihashmap_iterate (handle->active_requests,
298                                          &add_request_to_pending, handle);
299   process_pending_messages (handle);
300 }
301
302
303 /**
304  * Try reconnecting to the DHT service.
305  *
306  * @param handle handle to dht to (possibly) disconnect and reconnect
307  */
308 static void
309 do_disconnect (struct GNUNET_DHT_Handle *handle)
310 {
311   if (handle->client == NULL)
312     return;
313   GNUNET_assert (handle->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
314   if (NULL != handle->th)
315     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
316   handle->th = NULL;
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);
324 }
325
326
327 /**
328  * Transmit the next pending message, called by notify_transmit_ready
329  */
330 static size_t
331 transmit_pending (void *cls, size_t size, void *buf);
332
333
334 /**
335  * Try to send messages from list of messages to send
336  */
337 static void
338 process_pending_messages (struct GNUNET_DHT_Handle *handle)
339 {
340   struct PendingMessage *head;
341
342   if (handle->client == NULL)
343   {
344     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
345                 "process_pending_messages called, but client is null, reconnecting\n");
346     do_disconnect (handle);
347     return;
348   }
349   if (handle->th != NULL)
350     return;
351   if (NULL == (head = handle->pending_head))
352     return;
353   handle->th =
354       GNUNET_CLIENT_notify_transmit_ready (handle->client,
355                                            ntohs (head->msg->size),
356                                            GNUNET_TIME_UNIT_FOREVER_REL,
357                                            GNUNET_YES, &transmit_pending,
358                                            handle);
359   if (NULL != handle->th)
360     return;
361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
362               "notify_transmit_ready returned NULL, reconnecting\n");
363   do_disconnect (handle);
364 }
365
366
367 /**
368  * Transmit the next pending message, called by notify_transmit_ready
369  */
370 static size_t
371 transmit_pending (void *cls, size_t size, void *buf)
372 {
373   struct GNUNET_DHT_Handle *handle = cls;
374   struct PendingMessage *head;
375   size_t tsize;
376
377   handle->th = NULL;
378   if (buf == NULL)
379   {
380     LOG (GNUNET_ERROR_TYPE_DEBUG,
381          "Transmission to DHT service failed!  Reconnecting!\n");
382     do_disconnect (handle);
383     return 0;
384   }
385   if (NULL == (head = handle->pending_head))
386     return 0;
387
388   tsize = ntohs (head->msg->size);
389   if (size < tsize)
390   {
391     process_pending_messages (handle);
392     return 0;
393   }
394   memcpy (buf, head->msg, tsize);
395   GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
396                                head);
397   if (head->timeout_task != GNUNET_SCHEDULER_NO_TASK)
398   {
399     GNUNET_SCHEDULER_cancel (head->timeout_task);
400     head->timeout_task = GNUNET_SCHEDULER_NO_TASK;
401   }
402   if (NULL != head->cont)
403   {
404     GNUNET_SCHEDULER_add_continuation (head->cont, head->cont_cls,
405                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
406     head->cont = NULL;
407     head->cont_cls = NULL;
408   }
409   head->in_pending_queue = GNUNET_NO;
410   if (GNUNET_YES == head->free_on_send)
411     GNUNET_free (head);
412   process_pending_messages (handle);
413 #if DEBUG_DHT
414   LOG (GNUNET_ERROR_TYPE_DEBUG,
415        "Forwarded request of %u bytes to DHT service\n", (unsigned int) tsize);
416 #endif
417   return tsize;
418 }
419
420
421 /**
422  * Process a given reply that might match the given
423  * request.
424  *
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
430  */
431 static int
432 process_reply (void *cls, const GNUNET_HashCode * key, void *value)
433 {
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;
440   size_t data_length;
441   size_t msize;
442   size_t meta_length;
443   const void *data;
444
445   if (dht_msg->unique_id != get_handle->unique_id)
446   {
447     /* UID mismatch */
448     LOG (GNUNET_ERROR_TYPE_DEBUG, 
449          "Ignoring reply for %s: UID mismatch: %llu/%llu\n",
450          GNUNET_h2s (key),
451          dht_msg->unique_id, get_handle->unique_id);
452     return GNUNET_YES;
453   }
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);
457   meta_length =
458       sizeof (struct GNUNET_DHT_ClientResultMessage) +
459       sizeof (struct GNUNET_PeerIdentity) * (get_path_length + put_path_length);
460   if ((msize < meta_length) ||
461       (get_path_length >
462        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
463       (put_path_length >
464        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
465   {
466     GNUNET_break (0);
467     return GNUNET_NO;
468   }
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,
473        GNUNET_h2s (key));
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);
481   return GNUNET_YES;
482 }
483
484
485 /**
486  * Handler for messages received from the DHT service
487  * a demultiplexer which handles numerous message types
488  *
489  * @param cls the 'struct GNUNET_DHT_Handle'
490  * @param msg the incoming message
491  */
492 static void
493 service_message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
494 {
495   struct GNUNET_DHT_Handle *handle = cls;
496   const struct GNUNET_DHT_ClientResultMessage *dht_msg;
497
498   if (msg == NULL)
499   {
500     LOG (GNUNET_ERROR_TYPE_DEBUG,
501          "Error receiving data from DHT service, reconnecting\n");
502     do_disconnect (handle);
503     return;
504   }
505   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT)
506   {
507     GNUNET_break (0);
508     do_disconnect (handle);
509     return;
510   }
511   if (ntohs (msg->size) < sizeof (struct GNUNET_DHT_ClientResultMessage))
512   {
513     GNUNET_break (0);
514     do_disconnect (handle);
515     return;
516   }
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),
521        handle);
522   GNUNET_CONTAINER_multihashmap_get_multiple (handle->active_requests,
523                                               &dht_msg->key, &process_reply,
524                                               (void *) dht_msg);
525   GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
526                          GNUNET_TIME_UNIT_FOREVER_REL);
527 }
528
529
530 /**
531  * Initialize the connection with the DHT service.
532  *
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
536  *
537  * @return handle to the DHT service, or NULL on error
538  */
539 struct GNUNET_DHT_Handle *
540 GNUNET_DHT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
541                     unsigned int ht_len)
542 {
543   struct GNUNET_DHT_Handle *handle;
544
545   handle = GNUNET_malloc (sizeof (struct GNUNET_DHT_Handle));
546   handle->cfg = cfg;
547   handle->uid_gen =
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))
551   {
552     GNUNET_DHT_disconnect (handle);
553     return NULL;
554   }
555   return handle;
556 }
557
558
559 /**
560  * Shutdown connection with the DHT service.
561  *
562  * @param handle handle of the DHT connection to stop
563  */
564 void
565 GNUNET_DHT_disconnect (struct GNUNET_DHT_Handle *handle)
566 {
567   struct PendingMessage *pm;
568
569   GNUNET_assert (handle != NULL);
570   GNUNET_assert (0 ==
571                  GNUNET_CONTAINER_multihashmap_size (handle->active_requests));
572   if (handle->th != NULL)
573   {
574     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
575     handle->th = NULL;
576   }
577   while (NULL != (pm = handle->pending_head))
578   {
579     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
580                                  pm);
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;
588     GNUNET_free (pm);
589   }
590   if (handle->client != NULL)
591   {
592     GNUNET_CLIENT_disconnect (handle->client, GNUNET_YES);
593     handle->client = NULL;
594   }
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);
599 }
600
601
602 /**
603  * Timeout for the transmission of a fire&forget-request.  Clean it up.
604  *
605  * @param cls the 'struct PendingMessage'
606  * @param tc scheduler context
607  */
608 static void
609 timeout_put_request (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
610 {
611   struct PendingMessage *pending = cls;
612   struct GNUNET_DHT_Handle *handle;
613
614   handle = pending->handle;
615   GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
616                                pending);
617   if (pending->cont != NULL)
618     pending->cont (pending->cont_cls, tc);
619   GNUNET_free (pending);
620 }
621
622
623 /**
624  * Perform a PUT operation storing data in the DHT.
625  *
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
638  */
639 void
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,
646                 void *cont_cls)
647 {
648   struct GNUNET_DHT_ClientPutMessage *put_msg;
649   size_t msize;
650   struct PendingMessage *pending;
651
652   msize = sizeof (struct GNUNET_DHT_ClientPutMessage) + size;
653   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
654       (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
655   {
656     GNUNET_break (0);
657     if (NULL != cont)
658       cont (cont_cls, NULL);
659     return;
660   }
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);
676   put_msg->key = *key;
677   memcpy (&put_msg[1], data, size);
678   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
679                                pending);
680   pending->in_pending_queue = GNUNET_YES;
681   process_pending_messages (handle);
682 }
683
684
685 /**
686  * Perform an asynchronous GET operation on the DHT identified. See
687  * also "GNUNET_BLOCK_evaluate".
688  *
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
701  */
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,
709                       void *iter_cls)
710 {
711   struct GNUNET_DHT_ClientGetMessage *get_msg;
712   struct GNUNET_DHT_GetHandle *get_handle;
713   size_t msize;
714   struct PendingMessage *pending;
715
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))
719   {
720     GNUNET_break (0);
721     return NULL;
722   }
723   LOG (GNUNET_ERROR_TYPE_DEBUG,
724        "Sending query for %s to DHT %p\n",
725        GNUNET_h2s (key),
726        handle);
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);
737   get_msg->key = *key;
738   handle->uid_gen++;
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,
742                                pending);
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);
752   return get_handle;
753 }
754
755
756 /**
757  * Stop async DHT-get.
758  *
759  * @param get_handle handle to the GET operation to stop
760  */
761 void
762 GNUNET_DHT_get_stop (struct GNUNET_DHT_GetHandle *get_handle)
763 {
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;
768
769   handle = get_handle->message->handle;
770   get_msg =
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),
775        handle);
776   /* generate STOP */
777   pending =
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,
791                                pending);
792   pending->in_pending_queue = GNUNET_YES;
793
794   /* remove 'GET' from active status */
795   GNUNET_assert (GNUNET_YES ==
796                  GNUNET_CONTAINER_multihashmap_remove (handle->active_requests,
797                                                        &get_msg->key,
798                                                        get_handle));
799   if (GNUNET_YES == get_handle->message->in_pending_queue)
800   {
801     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
802                                  get_handle->message);
803     get_handle->message->in_pending_queue = GNUNET_NO;
804   }
805   GNUNET_free (get_handle->message);
806   GNUNET_free (get_handle);
807
808   process_pending_messages (handle);
809 }
810
811
812 /* end of dht_api.c */