added ATS addresstype information to unix
[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    * Did we start our receive loop yet?
200    */
201   int in_receive;
202 };
203
204
205 /**
206  * Handler for messages received from the DHT service
207  * a demultiplexer which handles numerous message types
208  *
209  */
210 static void
211 service_message_handler (void *cls, const struct GNUNET_MessageHeader *msg);
212
213
214 /**
215  * Try to (re)connect to the DHT service.
216  *
217  * @return GNUNET_YES on success, GNUNET_NO on failure.
218  */
219 static int
220 try_connect (struct GNUNET_DHT_Handle *handle)
221 {
222   if (handle->client != NULL)
223     return GNUNET_OK;
224   handle->in_receive = GNUNET_NO;
225   handle->client = GNUNET_CLIENT_connect ("dht", handle->cfg);
226   if (handle->client == NULL)
227   {
228     LOG (GNUNET_ERROR_TYPE_WARNING,
229          _("Failed to connect to the DHT service!\n"));
230     return GNUNET_NO;
231   }
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 #if DEBUG_DHT
254     LOG (GNUNET_ERROR_TYPE_DEBUG,
255          "Retransmitting request related to %s to DHT %p\n", GNUNET_h2s (key),
256          handle);
257 #endif
258     GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
259                                  rh->message);
260     rh->message->in_pending_queue = GNUNET_YES;
261   }
262   return GNUNET_YES;
263 }
264
265
266 /**
267  * Try to send messages from list of messages to send
268  * @param handle DHT_Handle
269  */
270 static void
271 process_pending_messages (struct GNUNET_DHT_Handle *handle);
272
273
274 /**
275  * Try reconnecting to the dht service.
276  *
277  * @param cls GNUNET_DHT_Handle
278  * @param tc scheduler context
279  */
280 static void
281 try_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
282 {
283   struct GNUNET_DHT_Handle *handle = cls;
284
285 #if DEBUG_DHT
286   LOG (GNUNET_ERROR_TYPE_DEBUG, "Reconnecting with DHT %p\n", handle);
287 #endif
288   handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
289   if (handle->retry_time.rel_value < GNUNET_CONSTANTS_SERVICE_RETRY.rel_value)
290     handle->retry_time = GNUNET_CONSTANTS_SERVICE_RETRY;
291   else
292     handle->retry_time = GNUNET_TIME_relative_multiply (handle->retry_time, 2);
293   if (handle->retry_time.rel_value > GNUNET_CONSTANTS_SERVICE_TIMEOUT.rel_value)
294     handle->retry_time = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
295   handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
296   if (GNUNET_YES != try_connect (handle))
297   {
298 #if DEBUG_DHT
299     LOG (GNUNET_ERROR_TYPE_DEBUG, "dht reconnect failed(!)\n");
300 #endif
301     return;
302   }
303   GNUNET_CONTAINER_multihashmap_iterate (handle->active_requests,
304                                          &add_request_to_pending, handle);
305   process_pending_messages (handle);
306 }
307
308
309 /**
310  * Try reconnecting to the DHT service.
311  *
312  * @param handle handle to dht to (possibly) disconnect and reconnect
313  */
314 static void
315 do_disconnect (struct GNUNET_DHT_Handle *handle)
316 {
317   if (handle->client == NULL)
318     return;
319   GNUNET_assert (handle->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
320   if (NULL != handle->th)
321     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
322   handle->th = NULL;
323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
324               "Disconnecting from DHT service, will try to reconnect in %llu ms\n",
325               (unsigned long long) handle->retry_time.rel_value);
326   GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
327   handle->client = NULL;
328   handle->reconnect_task =
329       GNUNET_SCHEDULER_add_delayed (handle->retry_time, &try_reconnect, handle);
330 }
331
332
333 /**
334  * Transmit the next pending message, called by notify_transmit_ready
335  */
336 static size_t
337 transmit_pending (void *cls, size_t size, void *buf);
338
339
340 /**
341  * Try to send messages from list of messages to send
342  */
343 static void
344 process_pending_messages (struct GNUNET_DHT_Handle *handle)
345 {
346   struct PendingMessage *head;
347
348   if (handle->client == NULL)
349   {
350     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
351                 "process_pending_messages called, but client is null, reconnecting\n");
352     do_disconnect (handle);
353     return;
354   }
355   if (handle->th != NULL)
356     return;
357   if (NULL == (head = handle->pending_head))
358     return;
359   handle->th =
360       GNUNET_CLIENT_notify_transmit_ready (handle->client,
361                                            ntohs (head->msg->size),
362                                            GNUNET_TIME_UNIT_FOREVER_REL,
363                                            GNUNET_YES, &transmit_pending,
364                                            handle);
365   if (NULL != handle->th)
366     return;
367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
368               "notify_transmit_ready returned NULL, reconnecting\n");
369   do_disconnect (handle);
370 }
371
372
373 /**
374  * Transmit the next pending message, called by notify_transmit_ready
375  */
376 static size_t
377 transmit_pending (void *cls, size_t size, void *buf)
378 {
379   struct GNUNET_DHT_Handle *handle = cls;
380   struct PendingMessage *head;
381   size_t tsize;
382
383   handle->th = NULL;
384   if (buf == NULL)
385   {
386 #if DEBUG_DHT
387     LOG (GNUNET_ERROR_TYPE_DEBUG,
388          "Transmission to DHT service failed!  Reconnecting!\n");
389 #endif
390     do_disconnect (handle);
391     return 0;
392   }
393   if (NULL == (head = handle->pending_head))
394     return 0;
395
396   tsize = ntohs (head->msg->size);
397   if (size < tsize)
398   {
399     process_pending_messages (handle);
400     return 0;
401   }
402   memcpy (buf, head->msg, tsize);
403   GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
404                                head);
405   head->in_pending_queue = GNUNET_NO;
406   if (head->timeout_task != GNUNET_SCHEDULER_NO_TASK)
407   {
408     GNUNET_SCHEDULER_cancel (head->timeout_task);
409     head->timeout_task = GNUNET_SCHEDULER_NO_TASK;
410   }
411   if (NULL != head->cont)
412   {
413     GNUNET_SCHEDULER_add_continuation (head->cont, head->cont_cls,
414                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
415     head->cont = NULL;
416     head->cont_cls = NULL;
417   }
418   if (GNUNET_YES == head->free_on_send)
419     GNUNET_free (head);
420   process_pending_messages (handle);
421 #if DEBUG_DHT
422   LOG (GNUNET_ERROR_TYPE_DEBUG,
423        "Forwarded request of %u bytes to DHT service\n", (unsigned int) tsize);
424 #endif
425   if (GNUNET_NO == handle->in_receive)
426   {
427 #if DEBUG_DHT
428     LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting to process replies from DHT\n");
429 #endif
430     handle->in_receive = GNUNET_YES;
431     GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
432                            GNUNET_TIME_UNIT_FOREVER_REL);
433   }
434   return tsize;
435 }
436
437
438 /**
439  * Process a given reply that might match the given
440  * request.
441  *
442  * @param cls the 'struct GNUNET_DHT_ClientResultMessage'
443  * @param key query of the request
444  * @param value the 'struct GNUNET_DHT_RouteHandle' of a request matching the same key
445  * @return GNUNET_YES to continue to iterate over all results,
446  *         GNUNET_NO if the reply is malformed
447  */
448 static int
449 process_reply (void *cls, const GNUNET_HashCode * key, void *value)
450 {
451   const struct GNUNET_DHT_ClientResultMessage *dht_msg = cls;
452   struct GNUNET_DHT_GetHandle *get_handle = value;
453   const struct GNUNET_PeerIdentity *put_path;
454   const struct GNUNET_PeerIdentity *get_path;
455   uint32_t put_path_length;
456   uint32_t get_path_length;
457   size_t data_length;
458   size_t msize;
459   size_t meta_length;
460   const void *data;
461
462   if (dht_msg->unique_id != get_handle->unique_id)
463   {
464     /* UID mismatch */
465 #if DEBUG_DHT
466     LOG (GNUNET_ERROR_TYPE_DEBUG,
467          "Ignoring reply for %s: UID mismatch: %llu/%llu\n", GNUNET_h2s (key),
468          dht_msg->unique_id, get_handle->unique_id);
469 #endif
470     return GNUNET_YES;
471   }
472   msize = ntohs (dht_msg->header.size);
473   put_path_length = ntohl (dht_msg->put_path_length);
474   get_path_length = ntohl (dht_msg->get_path_length);
475   meta_length =
476       sizeof (struct GNUNET_DHT_ClientResultMessage) +
477       sizeof (struct GNUNET_PeerIdentity) * (get_path_length + put_path_length);
478   if ((msize < meta_length) ||
479       (get_path_length >
480        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
481       (put_path_length >
482        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
483   {
484     GNUNET_break (0);
485     return GNUNET_NO;
486   }
487   data_length = msize - meta_length;
488 #if DEBUG_DHT
489   LOG (GNUNET_ERROR_TYPE_DEBUG, "Giving %u byte reply for %s to application\n",
490        (unsigned int) data_length, GNUNET_h2s (key));
491 #endif
492   put_path = (const struct GNUNET_PeerIdentity *) &dht_msg[1];
493   get_path = &put_path[put_path_length];
494   data = &get_path[get_path_length];
495   get_handle->iter (get_handle->iter_cls,
496                     GNUNET_TIME_absolute_ntoh (dht_msg->expiration), key,
497                     get_path, get_path_length, put_path, put_path_length,
498                     ntohl (dht_msg->type), data_length, data);
499   return GNUNET_YES;
500 }
501
502
503 /**
504  * Handler for messages received from the DHT service
505  * a demultiplexer which handles numerous message types
506  *
507  * @param cls the 'struct GNUNET_DHT_Handle'
508  * @param msg the incoming message
509  */
510 static void
511 service_message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
512 {
513   struct GNUNET_DHT_Handle *handle = cls;
514   const struct GNUNET_DHT_ClientResultMessage *dht_msg;
515
516   if (msg == NULL)
517   {
518 #if DEBUG_DHT
519     LOG (GNUNET_ERROR_TYPE_DEBUG,
520          "Error receiving data from DHT service, reconnecting\n");
521 #endif
522     do_disconnect (handle);
523     return;
524   }
525   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT)
526   {
527     GNUNET_break (0);
528     do_disconnect (handle);
529     return;
530   }
531   if (ntohs (msg->size) < sizeof (struct GNUNET_DHT_ClientResultMessage))
532   {
533     GNUNET_break (0);
534     do_disconnect (handle);
535     return;
536   }
537   dht_msg = (const struct GNUNET_DHT_ClientResultMessage *) msg;
538 #if DEBUG_DHT
539   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received reply for `%s' from DHT service %p\n",
540        GNUNET_h2s (&dht_msg->key), handle);
541 #endif
542   GNUNET_CONTAINER_multihashmap_get_multiple (handle->active_requests,
543                                               &dht_msg->key, &process_reply,
544                                               (void *) dht_msg);
545   GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
546                          GNUNET_TIME_UNIT_FOREVER_REL);
547 }
548
549
550 /**
551  * Initialize the connection with the DHT service.
552  *
553  * @param cfg configuration to use
554  * @param ht_len size of the internal hash table to use for
555  *               processing multiple GET/FIND requests in parallel
556  *
557  * @return handle to the DHT service, or NULL on error
558  */
559 struct GNUNET_DHT_Handle *
560 GNUNET_DHT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
561                     unsigned int ht_len)
562 {
563   struct GNUNET_DHT_Handle *handle;
564
565   handle = GNUNET_malloc (sizeof (struct GNUNET_DHT_Handle));
566   handle->cfg = cfg;
567   handle->uid_gen =
568       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
569   handle->active_requests = GNUNET_CONTAINER_multihashmap_create (ht_len);
570   if (GNUNET_NO == try_connect (handle))
571   {
572     GNUNET_DHT_disconnect (handle);
573     return NULL;
574   }
575   return handle;
576 }
577
578
579 /**
580  * Shutdown connection with the DHT service.
581  *
582  * @param handle handle of the DHT connection to stop
583  */
584 void
585 GNUNET_DHT_disconnect (struct GNUNET_DHT_Handle *handle)
586 {
587   struct PendingMessage *pm;
588
589   GNUNET_assert (handle != NULL);
590   GNUNET_assert (0 ==
591                  GNUNET_CONTAINER_multihashmap_size (handle->active_requests));
592   if (handle->th != NULL)
593   {
594     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
595     handle->th = NULL;
596   }
597   while (NULL != (pm = handle->pending_head))
598   {
599     GNUNET_assert (GNUNET_YES == pm->in_pending_queue);
600     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
601                                  pm);
602     pm->in_pending_queue = GNUNET_NO;
603     GNUNET_assert (GNUNET_YES == pm->free_on_send);
604     if (GNUNET_SCHEDULER_NO_TASK != pm->timeout_task)
605       GNUNET_SCHEDULER_cancel (pm->timeout_task);
606     if (NULL != pm->cont)
607       GNUNET_SCHEDULER_add_continuation (pm->cont, pm->cont_cls,
608                                          GNUNET_SCHEDULER_REASON_TIMEOUT);
609     GNUNET_free (pm);
610   }
611   if (handle->client != NULL)
612   {
613     GNUNET_CLIENT_disconnect (handle->client, GNUNET_YES);
614     handle->client = NULL;
615   }
616   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
617     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
618   GNUNET_CONTAINER_multihashmap_destroy (handle->active_requests);
619   GNUNET_free (handle);
620 }
621
622
623 /**
624  * Timeout for the transmission of a fire&forget-request.  Clean it up.
625  *
626  * @param cls the 'struct PendingMessage'
627  * @param tc scheduler context
628  */
629 static void
630 timeout_put_request (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
631 {
632   struct PendingMessage *pending = cls;
633   struct GNUNET_DHT_Handle *handle;
634
635   handle = pending->handle;
636   GNUNET_assert (GNUNET_YES == pending->in_pending_queue);
637   GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
638                                pending);
639   pending->in_pending_queue = GNUNET_NO;
640   if (pending->cont != NULL)
641     pending->cont (pending->cont_cls, tc);
642   GNUNET_free (pending);
643 }
644
645
646 /**
647  * Perform a PUT operation storing data in the DHT.
648  *
649  * @param handle handle to DHT service
650  * @param key the key to store under
651  * @param desired_replication_level estimate of how many
652  *                nearest peers this request should reach
653  * @param options routing options for this message
654  * @param type type of the value
655  * @param size number of bytes in data; must be less than 64k
656  * @param data the data to store
657  * @param exp desired expiration time for the value
658  * @param timeout how long to wait for transmission of this request
659  * @param cont continuation to call when done (transmitting request to service)
660  * @param cont_cls closure for cont
661  */
662 void
663 GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle, const GNUNET_HashCode * key,
664                 uint32_t desired_replication_level,
665                 enum GNUNET_DHT_RouteOption options,
666                 enum GNUNET_BLOCK_Type type, size_t size, const char *data,
667                 struct GNUNET_TIME_Absolute exp,
668                 struct GNUNET_TIME_Relative timeout, GNUNET_SCHEDULER_Task cont,
669                 void *cont_cls)
670 {
671   struct GNUNET_DHT_ClientPutMessage *put_msg;
672   size_t msize;
673   struct PendingMessage *pending;
674
675   msize = sizeof (struct GNUNET_DHT_ClientPutMessage) + size;
676   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
677       (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
678   {
679     GNUNET_break (0);
680     if (NULL != cont)
681       cont (cont_cls, NULL);
682     return;
683   }
684   pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
685   put_msg = (struct GNUNET_DHT_ClientPutMessage *) &pending[1];
686   pending->msg = &put_msg->header;
687   pending->handle = handle;
688   pending->cont = cont;
689   pending->cont_cls = cont_cls;
690   pending->free_on_send = GNUNET_YES;
691   pending->timeout_task =
692       GNUNET_SCHEDULER_add_delayed (timeout, &timeout_put_request, pending);
693   put_msg->header.size = htons (msize);
694   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT);
695   put_msg->type = htonl (type);
696   put_msg->options = htonl ((uint32_t) options);
697   put_msg->desired_replication_level = htonl (desired_replication_level);
698   put_msg->expiration = GNUNET_TIME_absolute_hton (exp);
699   put_msg->key = *key;
700   memcpy (&put_msg[1], data, size);
701   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
702                                pending);
703   pending->in_pending_queue = GNUNET_YES;
704   process_pending_messages (handle);
705 }
706
707
708 /**
709  * Perform an asynchronous GET operation on the DHT identified. See
710  * also "GNUNET_BLOCK_evaluate".
711  *
712  * @param handle handle to the DHT service
713  * @param timeout how long to wait for transmission of this request to the service
714  * @param type expected type of the response object
715  * @param key the key to look up
716  * @param desired_replication_level estimate of how many
717                   nearest peers this request should reach
718  * @param options routing options for this message
719  * @param xquery extended query data (can be NULL, depending on type)
720  * @param xquery_size number of bytes in xquery
721  * @param iter function to call on each result
722  * @param iter_cls closure for iter
723  * @return handle to stop the async get
724  */
725 struct GNUNET_DHT_GetHandle *
726 GNUNET_DHT_get_start (struct GNUNET_DHT_Handle *handle,
727                       struct GNUNET_TIME_Relative timeout,
728                       enum GNUNET_BLOCK_Type type, const GNUNET_HashCode * key,
729                       uint32_t desired_replication_level,
730                       enum GNUNET_DHT_RouteOption options, const void *xquery,
731                       size_t xquery_size, GNUNET_DHT_GetIterator iter,
732                       void *iter_cls)
733 {
734   struct GNUNET_DHT_ClientGetMessage *get_msg;
735   struct GNUNET_DHT_GetHandle *get_handle;
736   size_t msize;
737   struct PendingMessage *pending;
738
739   msize = sizeof (struct GNUNET_DHT_ClientGetMessage) + xquery_size;
740   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
741       (xquery_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
742   {
743     GNUNET_break (0);
744     return NULL;
745   }
746 #if DEBUG_DHT
747   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending query for %s to DHT %p\n",
748        GNUNET_h2s (key), handle);
749 #endif
750   pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
751   get_msg = (struct GNUNET_DHT_ClientGetMessage *) &pending[1];
752   pending->msg = &get_msg->header;
753   pending->handle = handle;
754   pending->free_on_send = GNUNET_NO;
755   get_msg->header.size = htons (msize);
756   get_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET);
757   get_msg->options = htonl ((uint32_t) options);
758   get_msg->desired_replication_level = htonl (desired_replication_level);
759   get_msg->type = htonl (type);
760   get_msg->key = *key;
761   handle->uid_gen++;
762   get_msg->unique_id = handle->uid_gen;
763   memcpy (&get_msg[1], xquery, xquery_size);
764   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
765                                pending);
766   pending->in_pending_queue = GNUNET_YES;
767   get_handle = GNUNET_malloc (sizeof (struct GNUNET_DHT_GetHandle));
768   get_handle->iter = iter;
769   get_handle->iter_cls = iter_cls;
770   get_handle->message = pending;
771   get_handle->unique_id = get_msg->unique_id;
772   GNUNET_CONTAINER_multihashmap_put (handle->active_requests, key, get_handle,
773                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
774   process_pending_messages (handle);
775   return get_handle;
776 }
777
778
779 /**
780  * Stop async DHT-get.
781  *
782  * @param get_handle handle to the GET operation to stop
783  */
784 void
785 GNUNET_DHT_get_stop (struct GNUNET_DHT_GetHandle *get_handle)
786 {
787   struct GNUNET_DHT_Handle *handle;
788   const struct GNUNET_DHT_ClientGetMessage *get_msg;
789   struct GNUNET_DHT_ClientGetStopMessage *stop_msg;
790   struct PendingMessage *pending;
791
792   handle = get_handle->message->handle;
793   get_msg =
794       (const struct GNUNET_DHT_ClientGetMessage *) get_handle->message->msg;
795 #if DEBUG_DHT
796   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending STOP for %s to DHT via %p\n",
797        GNUNET_h2s (&get_msg->key), handle);
798 #endif
799   /* generate STOP */
800   pending =
801       GNUNET_malloc (sizeof (struct PendingMessage) +
802                      sizeof (struct GNUNET_DHT_ClientGetStopMessage));
803   stop_msg = (struct GNUNET_DHT_ClientGetStopMessage *) &pending[1];
804   pending->msg = &stop_msg->header;
805   pending->handle = handle;
806   pending->free_on_send = GNUNET_YES;
807   stop_msg->header.size =
808       htons (sizeof (struct GNUNET_DHT_ClientGetStopMessage));
809   stop_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP);
810   stop_msg->reserved = htonl (0);
811   stop_msg->unique_id = get_msg->unique_id;
812   stop_msg->key = get_msg->key;
813   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
814                                pending);
815   pending->in_pending_queue = GNUNET_YES;
816
817   /* remove 'GET' from active status */
818   GNUNET_assert (GNUNET_YES ==
819                  GNUNET_CONTAINER_multihashmap_remove (handle->active_requests,
820                                                        &get_msg->key,
821                                                        get_handle));
822   if (GNUNET_YES == get_handle->message->in_pending_queue)
823   {
824     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
825                                  get_handle->message);
826     get_handle->message->in_pending_queue = GNUNET_NO;
827   }
828   GNUNET_free (get_handle->message);
829   GNUNET_free (get_handle);
830
831   process_pending_messages (handle);
832 }
833
834
835 /* end of dht_api.c */