use new connecT API
[oweals/gnunet.git] / src / dht / dht_api.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2010, 2011, 2012 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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 LOG(kind,...) GNUNET_log_from (kind, "dht-api",__VA_ARGS__)
38
39 /**
40  * Entry in our list of messages to be (re-)transmitted.
41  */
42 struct PendingMessage
43 {
44   /**
45    * This is a doubly-linked list.
46    */
47   struct PendingMessage *prev;
48
49   /**
50    * This is a doubly-linked list.
51    */
52   struct PendingMessage *next;
53
54   /**
55    * Message that is pending, allocated at the end
56    * of this struct.
57    */
58   const struct GNUNET_MessageHeader *msg;
59
60   /**
61    * Handle to the DHT API context.
62    */
63   struct GNUNET_DHT_Handle *handle;
64
65   /**
66    * Continuation to call when the request has been
67    * transmitted (for the first time) to the service; can be NULL.
68    */
69   GNUNET_SCHEDULER_TaskCallback cont;
70
71   /**
72    * Closure for 'cont'.
73    */
74   void *cont_cls;
75
76   /**
77    * Unique ID for this request
78    */
79   uint64_t unique_id;
80
81   /**
82    * Free the saved message once sent, set to GNUNET_YES for messages
83    * that do not receive responses; GNUNET_NO if this pending message
84    * is aliased from a 'struct GNUNET_DHT_RouteHandle' and will be freed
85    * from there.
86    */
87   int free_on_send;
88
89   /**
90    * GNUNET_YES if this message is in our pending queue right now.
91    */
92   int in_pending_queue;
93
94 };
95
96 #if ENABLE_MALICIOUS
97 /**
98  * Handle to act malicious message
99  */
100 struct GNUNET_DHT_ActMaliciousHandle
101 {
102   /**
103    * Continuation to call when done.
104    */
105   GNUNET_DHT_ActMaliciousContinuation cont;
106
107   /**
108    * Main handle to this DHT api
109    */
110   struct GNUNET_DHT_Handle *dht_handle;
111
112   /**
113    * Closure for 'cont'.
114    */
115   void *cont_cls;
116 };
117 #endif
118
119 /**
120  * Handle to a PUT request.
121  */
122 struct GNUNET_DHT_PutHandle
123 {
124   /**
125    * Kept in a DLL.
126    */
127   struct GNUNET_DHT_PutHandle *next;
128
129   /**
130    * Kept in a DLL.
131    */
132   struct GNUNET_DHT_PutHandle *prev;
133
134   /**
135    * Continuation to call when done.
136    */
137   GNUNET_DHT_PutContinuation cont;
138
139   /**
140    * Pending message associated with this PUT operation,
141    * NULL after the message has been transmitted to the service.
142    */
143   struct PendingMessage *pending;
144
145   /**
146    * Main handle to this DHT api
147    */
148   struct GNUNET_DHT_Handle *dht_handle;
149
150   /**
151    * Closure for 'cont'.
152    */
153   void *cont_cls;
154
155   /**
156    * Timeout task for this operation.
157    */
158   struct GNUNET_SCHEDULER_Task * timeout_task;
159
160   /**
161    * Unique ID for the PUT operation.
162    */
163   uint64_t unique_id;
164
165 };
166
167 /**
168  * Handle to a GET request
169  */
170 struct GNUNET_DHT_GetHandle
171 {
172
173   /**
174    * Iterator to call on data receipt
175    */
176   GNUNET_DHT_GetIterator iter;
177
178   /**
179    * Closure for the iterator callback
180    */
181   void *iter_cls;
182
183   /**
184    * Main handle to this DHT api
185    */
186   struct GNUNET_DHT_Handle *dht_handle;
187
188   /**
189    * The actual message sent for this request,
190    * used for retransmitting requests on service
191    * failure/reconnect.  Freed on route_stop.
192    */
193   struct PendingMessage *message;
194
195   /**
196    * Array of hash codes over the results that we have already
197    * seen.
198    */
199   struct GNUNET_HashCode *seen_results;
200
201   /**
202    * Key that this get request is for
203    */
204   struct GNUNET_HashCode key;
205
206   /**
207    * Unique identifier for this request (for key collisions).
208    */
209   uint64_t unique_id;
210
211   /**
212    * Size of the 'seen_results' array.  Note that not
213    * all positions might be used (as we over-allocate).
214    */
215   unsigned int seen_results_size;
216
217   /**
218    * Offset into the 'seen_results' array marking the
219    * end of the positions that are actually used.
220    */
221   unsigned int seen_results_end;
222
223   /**
224    * Offset into the 'seen_results' array marking the
225    * position up to where we've send the hash codes to
226    * the DHT for blocking (needed as we might not be
227    * able to send all hash codes at once).
228    */
229   unsigned int seen_results_transmission_offset;
230
231
232 };
233
234
235 /**
236  * Handle to a monitoring request.
237  */
238 struct GNUNET_DHT_MonitorHandle
239 {
240   /**
241    * DLL.
242    */
243   struct GNUNET_DHT_MonitorHandle *next;
244
245   /**
246    * DLL.
247    */
248   struct GNUNET_DHT_MonitorHandle *prev;
249
250   /**
251    * Main handle to this DHT api.
252    */
253   struct GNUNET_DHT_Handle *dht_handle;
254
255   /**
256    * Type of block looked for.
257    */
258   enum GNUNET_BLOCK_Type type;
259
260   /**
261    * Key being looked for, NULL == all.
262    */
263   struct GNUNET_HashCode *key;
264
265   /**
266    * Callback for each received message of type get.
267    */
268   GNUNET_DHT_MonitorGetCB get_cb;
269
270   /**
271    * Callback for each received message of type get response.
272    */
273   GNUNET_DHT_MonitorGetRespCB get_resp_cb;
274
275   /**
276    * Callback for each received message of type put.
277    */
278   GNUNET_DHT_MonitorPutCB put_cb;
279
280   /**
281    * Closure for cb.
282    */
283   void *cb_cls;
284
285 };
286
287
288 /**
289  * Connection to the DHT service.
290  */
291 struct GNUNET_DHT_Handle
292 {
293
294   /**
295    * Configuration to use.
296    */
297   const struct GNUNET_CONFIGURATION_Handle *cfg;
298
299   /**
300    * Socket (if available).
301    */
302   struct GNUNET_CLIENT_Connection *client;
303
304   /**
305    * Currently pending transmission request (or NULL).
306    */
307   struct GNUNET_CLIENT_TransmitHandle *th;
308
309   /**
310    * Head of linked list of messages we would like to transmit.
311    */
312   struct PendingMessage *pending_head;
313
314   /**
315    * Tail of linked list of messages we would like to transmit.
316    */
317   struct PendingMessage *pending_tail;
318
319   /**
320    * Head of linked list of messages we would like to monitor.
321    */
322   struct GNUNET_DHT_MonitorHandle *monitor_head;
323
324   /**
325    * Tail of linked list of messages we would like to monitor.
326    */
327   struct GNUNET_DHT_MonitorHandle *monitor_tail;
328
329   /**
330    * Head of active PUT requests.
331    */
332   struct GNUNET_DHT_PutHandle *put_head;
333
334   /**
335    * Tail of active PUT requests.
336    */
337   struct GNUNET_DHT_PutHandle *put_tail;
338
339   /**
340    * Hash map containing the current outstanding unique GET requests
341    * (values are of type `struct GNUNET_DHT_GetHandle`).
342    */
343   struct GNUNET_CONTAINER_MultiHashMap *active_requests;
344
345   /**
346    * Task for trying to reconnect.
347    */
348   struct GNUNET_SCHEDULER_Task * reconnect_task;
349
350   /**
351    * How quickly should we retry?  Used for exponential back-off on
352    * connect-errors.
353    */
354   struct GNUNET_TIME_Relative retry_time;
355
356   /**
357    * Generator for unique ids.
358    */
359   uint64_t uid_gen;
360
361   /**
362    * Did we start our receive loop yet?
363    */
364   int in_receive;
365
366 #if ENABLE_MALICIOUS
367   /**
368    * Handle of act malicious request.
369    */
370   struct GNUNET_DHT_ActMaliciousHandle *mh;
371 #endif
372 };
373
374
375 /**
376  * Handler for messages received from the DHT service
377  * a demultiplexer which handles numerous message types
378  *
379  * @param cls the `struct GNUNET_DHT_Handle`
380  * @param msg the incoming message
381  */
382 static void
383 service_message_handler (void *cls,
384                          const struct GNUNET_MessageHeader *msg);
385
386
387 /**
388  * Try to (re)connect to the DHT service.
389  *
390  * @param handle DHT handle to reconnect
391  * @return #GNUNET_YES on success, #GNUNET_NO on failure.
392  */
393 static int
394 try_connect (struct GNUNET_DHT_Handle *handle)
395 {
396   if (NULL != handle->client)
397     return GNUNET_OK;
398   handle->in_receive = GNUNET_NO;
399   handle->client = GNUNET_CLIENT_connect ("dht", handle->cfg);
400   if (NULL == handle->client)
401   {
402     LOG (GNUNET_ERROR_TYPE_WARNING,
403          _("Failed to connect to the DHT service!\n"));
404     return GNUNET_NO;
405   }
406   return GNUNET_YES;
407 }
408
409
410 /**
411  * Queue messages to DHT to block certain results from the result set.
412  *
413  * @param get_handle GET to generate messages for.
414  */
415 static void
416 queue_filter_messages (struct GNUNET_DHT_GetHandle *get_handle)
417 {
418   struct PendingMessage *pm;
419   struct GNUNET_DHT_ClientGetResultSeenMessage *msg;
420   uint16_t msize;
421   unsigned int delta;
422   unsigned int max;
423
424   while (get_handle->seen_results_transmission_offset < get_handle->seen_results_end)
425   {
426     delta = get_handle->seen_results_end - get_handle->seen_results_transmission_offset;
427     max = (GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage)) / sizeof (struct GNUNET_HashCode);
428     if (delta > max)
429       delta = max;
430     msize = sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage) + delta * sizeof (struct GNUNET_HashCode);
431
432     pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
433     msg = (struct GNUNET_DHT_ClientGetResultSeenMessage *) &pm[1];
434     pm->msg = &msg->header;
435     pm->handle = get_handle->dht_handle;
436     pm->unique_id = get_handle->unique_id;
437     pm->free_on_send = GNUNET_YES;
438     pm->in_pending_queue = GNUNET_YES;
439     msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_RESULTS_KNOWN);
440     msg->header.size = htons (msize);
441     msg->key = get_handle->key;
442     msg->unique_id = get_handle->unique_id;
443     memcpy (&msg[1],
444             &get_handle->seen_results[get_handle->seen_results_transmission_offset],
445             sizeof (struct GNUNET_HashCode) * delta);
446     get_handle->seen_results_transmission_offset += delta;
447     GNUNET_CONTAINER_DLL_insert_tail (get_handle->dht_handle->pending_head,
448                                       get_handle->dht_handle->pending_tail,
449                                       pm);
450   }
451 }
452
453
454 /**
455  * Add the request corresponding to the given route handle
456  * to the pending queue (if it is not already in there).
457  *
458  * @param cls the `struct GNUNET_DHT_Handle *`
459  * @param key key for the request (not used)
460  * @param value the `struct GNUNET_DHT_GetHandle *`
461  * @return #GNUNET_YES (always)
462  */
463 static int
464 add_request_to_pending (void *cls,
465                         const struct GNUNET_HashCode *key,
466                         void *value)
467 {
468   struct GNUNET_DHT_Handle *handle = cls;
469   struct GNUNET_DHT_GetHandle *get_handle = value;
470
471   if (GNUNET_NO == get_handle->message->in_pending_queue)
472   {
473     LOG (GNUNET_ERROR_TYPE_DEBUG,
474          "Retransmitting request related to %s to DHT %p\n", GNUNET_h2s (key),
475          handle);
476     get_handle->seen_results_transmission_offset = 0;
477     GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
478                                  get_handle->message);
479     queue_filter_messages (get_handle);
480     get_handle->message->in_pending_queue = GNUNET_YES;
481   }
482   return GNUNET_YES;
483 }
484
485
486 /**
487  * Try to send messages from list of messages to send
488  *
489  * @param handle DHT_Handle
490  */
491 static void
492 process_pending_messages (struct GNUNET_DHT_Handle *handle);
493
494
495 /**
496  * Try reconnecting to the dht service.
497  *
498  * @param cls a `struct GNUNET_DHT_Handle`
499  */
500 static void
501 try_reconnect (void *cls)
502 {
503   struct GNUNET_DHT_Handle *handle = cls;
504
505   LOG (GNUNET_ERROR_TYPE_DEBUG, "Reconnecting with DHT %p\n", handle);
506   handle->retry_time = GNUNET_TIME_STD_BACKOFF (handle->retry_time);
507   handle->reconnect_task = NULL;
508   if (GNUNET_YES != try_connect (handle))
509   {
510     LOG (GNUNET_ERROR_TYPE_DEBUG, "dht reconnect failed(!)\n");
511     return;
512   }
513   GNUNET_CONTAINER_multihashmap_iterate (handle->active_requests,
514                                          &add_request_to_pending, handle);
515   process_pending_messages (handle);
516 }
517
518
519 /**
520  * Try reconnecting to the DHT service.
521  *
522  * @param handle handle to dht to (possibly) disconnect and reconnect
523  */
524 static void
525 do_disconnect (struct GNUNET_DHT_Handle *handle)
526 {
527   struct GNUNET_DHT_PutHandle *ph;
528   struct GNUNET_DHT_PutHandle *next;
529
530   if (NULL == handle->client)
531     return;
532   GNUNET_assert (NULL == handle->reconnect_task);
533   if (NULL != handle->th)
534     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
535   handle->th = NULL;
536   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
537               "Disconnecting from DHT service, will try to reconnect in %s\n",
538               GNUNET_STRINGS_relative_time_to_string (handle->retry_time,
539                                                       GNUNET_YES));
540   GNUNET_CLIENT_disconnect (handle->client);
541   handle->client = NULL;
542
543   /* signal disconnect to all PUT requests that were transmitted but waiting
544      for the put confirmation */
545   next = handle->put_head;
546   while (NULL != (ph = next))
547   {
548     next = ph->next;
549     if (NULL == ph->pending)
550     {
551       if (NULL != ph->cont)
552         ph->cont (ph->cont_cls, GNUNET_SYSERR);
553       GNUNET_DHT_put_cancel (ph);
554     }
555   }
556   handle->reconnect_task =
557       GNUNET_SCHEDULER_add_delayed (handle->retry_time, &try_reconnect, handle);
558 }
559
560
561 /**
562  * Transmit the next pending message, called by notify_transmit_ready
563  *
564  * @param cls the DHT handle
565  * @param size number of bytes available in @a buf for transmission
566  * @param buf where to copy messages for the service
567  * @return number of bytes written to @a buf
568  */
569 static size_t
570 transmit_pending (void *cls,
571                   size_t size,
572                   void *buf);
573
574
575 /**
576  * Try to send messages from list of messages to send
577  *
578  * @param handle handle to DHT
579  */
580 static void
581 process_pending_messages (struct GNUNET_DHT_Handle *handle)
582 {
583   struct PendingMessage *head;
584
585   if (NULL == handle->client)
586   {
587     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
588                 "process_pending_messages called, but client is NULL, reconnecting\n");
589     do_disconnect (handle);
590     return;
591   }
592   if (NULL != handle->th)
593     return;
594   if (NULL == (head = handle->pending_head))
595     return;
596   handle->th =
597       GNUNET_CLIENT_notify_transmit_ready (handle->client,
598                                            ntohs (head->msg->size),
599                                            GNUNET_TIME_UNIT_FOREVER_REL,
600                                            GNUNET_YES, &transmit_pending,
601                                            handle);
602   if (NULL != handle->th)
603     return;
604   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
605               "notify_transmit_ready returned NULL, reconnecting\n");
606   do_disconnect (handle);
607 }
608
609
610 /**
611  * Transmit the next pending message, called by notify_transmit_ready
612  *
613  * @param cls the DHT handle
614  * @param size number of bytes available in @a buf for transmission
615  * @param buf where to copy messages for the service
616  * @return number of bytes written to @a buf
617  */
618 static size_t
619 transmit_pending (void *cls,
620                   size_t size,
621                   void *buf)
622 {
623   struct GNUNET_DHT_Handle *handle = cls;
624   struct PendingMessage *head;
625   size_t tsize;
626
627
628   handle->th = NULL;
629   if (NULL == buf)
630   {
631     LOG (GNUNET_ERROR_TYPE_DEBUG,
632          "Transmission to DHT service failed!  Reconnecting!\n");
633     do_disconnect (handle);
634     return 0;
635   }
636   if (NULL == (head = handle->pending_head))
637     return 0;
638
639   tsize = ntohs (head->msg->size);
640   if (size < tsize)
641   {
642     process_pending_messages (handle);
643     return 0;
644   }
645   memcpy (buf, head->msg, tsize);
646   GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
647                                head);
648   head->in_pending_queue = GNUNET_NO;
649   if (NULL != head->cont)
650   {
651     head->cont (head->cont_cls);
652     head->cont = NULL;
653     head->cont_cls = NULL;
654   }
655   if (GNUNET_YES == head->free_on_send)
656     GNUNET_free (head);
657   process_pending_messages (handle);
658   LOG (GNUNET_ERROR_TYPE_DEBUG,
659        "Forwarded request of %u bytes to DHT service\n", (unsigned int) tsize);
660   if (GNUNET_NO == handle->in_receive)
661   {
662     LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting to process replies from DHT\n");
663     handle->in_receive = GNUNET_YES;
664
665     GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
666                            GNUNET_TIME_UNIT_FOREVER_REL);
667   }
668   return tsize;
669 }
670
671
672 /**
673  * Process a given reply that might match the given
674  * request.
675  *
676  * @param cls the `struct GNUNET_DHT_ClientResultMessage`
677  * @param key query of the request
678  * @param value the `struct GNUNET_DHT_RouteHandle` of a request matching the same key
679  * @return #GNUNET_YES to continue to iterate over all results,
680  *         #GNUNET_NO if the reply is malformed or we found a matching request
681  */
682 static int
683 process_reply (void *cls,
684                const struct GNUNET_HashCode *key,
685                void *value)
686 {
687   const struct GNUNET_DHT_ClientResultMessage *dht_msg = cls;
688   struct GNUNET_DHT_GetHandle *get_handle = value;
689   const struct GNUNET_PeerIdentity *put_path;
690   const struct GNUNET_PeerIdentity *get_path;
691   struct GNUNET_HashCode hc;
692   uint32_t put_path_length;
693   uint32_t get_path_length;
694   size_t data_length;
695   size_t msize;
696   size_t meta_length;
697   const void *data;
698
699   if (dht_msg->unique_id != get_handle->unique_id)
700   {
701     /* UID mismatch */
702     LOG (GNUNET_ERROR_TYPE_DEBUG,
703          "Ignoring reply for %s: UID mismatch: %llu/%llu\n", GNUNET_h2s (key),
704          dht_msg->unique_id, get_handle->unique_id);
705     return GNUNET_YES;
706   }
707   msize = ntohs (dht_msg->header.size);
708   put_path_length = ntohl (dht_msg->put_path_length);
709   get_path_length = ntohl (dht_msg->get_path_length);
710   meta_length =
711       sizeof (struct GNUNET_DHT_ClientResultMessage) +
712       sizeof (struct GNUNET_PeerIdentity) * (get_path_length + put_path_length);
713   if ((msize < meta_length) ||
714       (get_path_length >
715        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
716       (put_path_length >
717        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
718   {
719     GNUNET_break (0);
720     return GNUNET_NO;
721   }
722   data_length = msize - meta_length;
723   LOG (GNUNET_ERROR_TYPE_DEBUG, "Giving %u byte reply for %s to application\n",
724        (unsigned int) data_length, GNUNET_h2s (key));
725   put_path = (const struct GNUNET_PeerIdentity *) &dht_msg[1];
726   get_path = &put_path[put_path_length];
727   data = &get_path[get_path_length];
728   /* remember that we've seen this result */
729   GNUNET_CRYPTO_hash (data, data_length, &hc);
730   if (get_handle->seen_results_size == get_handle->seen_results_end)
731     GNUNET_array_grow (get_handle->seen_results,
732                        get_handle->seen_results_size,
733                        get_handle->seen_results_size * 2 + 1);
734   GNUNET_assert (get_handle->seen_results_end == get_handle->seen_results_transmission_offset);
735   get_handle->seen_results[get_handle->seen_results_end++] = hc;
736   /* no need to block it explicitly, service already knows about it! */
737   get_handle->seen_results_transmission_offset++;
738   get_handle->iter (get_handle->iter_cls,
739                     GNUNET_TIME_absolute_ntoh (dht_msg->expiration), key,
740                     get_path, get_path_length, put_path, put_path_length,
741                     ntohl (dht_msg->type), data_length, data);
742   return GNUNET_NO;
743 }
744
745
746 /**
747  * Process a get monitor message from the service.
748  *
749  * @param handle The DHT handle.
750  * @param msg Monitor get message from the service.
751  * @return #GNUNET_OK if everything went fine,
752  *         #GNUNET_SYSERR if the message is malformed.
753  */
754 static int
755 process_monitor_get_message (struct GNUNET_DHT_Handle *handle,
756                              const struct GNUNET_DHT_MonitorGetMessage *msg)
757 {
758   struct GNUNET_DHT_MonitorHandle *h;
759
760   for (h = handle->monitor_head; NULL != h; h = h->next)
761   {
762     int type_ok;
763     int key_ok;
764
765     type_ok = (GNUNET_BLOCK_TYPE_ANY == h->type) || (h->type == ntohl(msg->type));
766     key_ok = (NULL == h->key) || (0 == memcmp (h->key, &msg->key,
767                                                sizeof (struct GNUNET_HashCode)));
768     if (type_ok && key_ok && (NULL != h->get_cb))
769       h->get_cb (h->cb_cls,
770                  ntohl (msg->options),
771                  (enum GNUNET_BLOCK_Type) ntohl(msg->type),
772                  ntohl (msg->hop_count),
773                  ntohl (msg->desired_replication_level),
774                  ntohl (msg->get_path_length),
775                  (struct GNUNET_PeerIdentity *) &msg[1],
776                  &msg->key);
777   }
778   return GNUNET_OK;
779 }
780
781
782 /**
783  * Process a get response monitor message from the service.
784  *
785  * @param handle The DHT handle.
786  * @param msg monitor get response message from the service
787  * @return #GNUNET_OK if everything went fine,
788  *         #GNUNET_SYSERR if the message is malformed.
789  */
790 static int
791 process_monitor_get_resp_message (struct GNUNET_DHT_Handle *handle,
792                                   const struct GNUNET_DHT_MonitorGetRespMessage *msg)
793 {
794   struct GNUNET_DHT_MonitorHandle *h;
795   struct GNUNET_PeerIdentity *path;
796   uint32_t getl;
797   uint32_t putl;
798   size_t msize;
799
800   msize = ntohs (msg->header.size);
801   path = (struct GNUNET_PeerIdentity *) &msg[1];
802   getl = ntohl (msg->get_path_length);
803   putl = ntohl (msg->put_path_length);
804   if ( (getl + putl < getl) ||
805        ( ((msize - sizeof (struct GNUNET_DHT_MonitorGetRespMessage)) / sizeof (struct GNUNET_PeerIdentity)) < getl + putl) )
806   {
807     GNUNET_break (0);
808     return GNUNET_SYSERR;
809   }
810   for (h = handle->monitor_head; NULL != h; h = h->next)
811   {
812     int type_ok;
813     int key_ok;
814
815     type_ok = (GNUNET_BLOCK_TYPE_ANY == h->type) || (h->type == ntohl(msg->type));
816     key_ok = (NULL == h->key) || (0 == memcmp (h->key, &msg->key,
817                                                sizeof (struct GNUNET_HashCode)));
818     if (type_ok && key_ok && (NULL != h->get_resp_cb))
819       h->get_resp_cb (h->cb_cls,
820                       (enum GNUNET_BLOCK_Type) ntohl(msg->type),
821                       path, getl,
822                       &path[getl], putl,
823                       GNUNET_TIME_absolute_ntoh(msg->expiration_time),
824                       &msg->key,
825                       (void *) &path[getl + putl],
826                       msize -
827                       sizeof (struct GNUNET_DHT_MonitorGetRespMessage) -
828                       sizeof (struct GNUNET_PeerIdentity) * (putl + getl));
829   }
830   return GNUNET_OK;
831 }
832
833
834 /**
835  * Process a put monitor message from the service.
836  *
837  * @param handle The DHT handle.
838  * @param msg Monitor put message from the service.
839  * @return #GNUNET_OK if everything went fine,
840  *         #GNUNET_SYSERR if the message is malformed.
841  */
842 static int
843 process_monitor_put_message (struct GNUNET_DHT_Handle *handle,
844                              const struct GNUNET_DHT_MonitorPutMessage *msg)
845 {
846   struct GNUNET_DHT_MonitorHandle *h;
847   size_t msize;
848   struct GNUNET_PeerIdentity *path;
849   uint32_t putl;
850
851   msize = ntohs (msg->header.size);
852   path = (struct GNUNET_PeerIdentity *) &msg[1];
853   putl = ntohl (msg->put_path_length);
854   if (((msize - sizeof (struct GNUNET_DHT_MonitorGetRespMessage)) / sizeof (struct GNUNET_PeerIdentity)) < putl)
855   {
856     GNUNET_break (0);
857     return GNUNET_SYSERR;
858   }
859   for (h = handle->monitor_head; NULL != h; h = h->next)
860   {
861     int type_ok;
862     int key_ok;
863
864     type_ok = (GNUNET_BLOCK_TYPE_ANY == h->type) || (h->type == ntohl(msg->type));
865     key_ok = (NULL == h->key) || (0 == memcmp (h->key, &msg->key,
866                                                sizeof (struct GNUNET_HashCode)));
867     if (type_ok && key_ok && (NULL != h->put_cb))
868       h->put_cb (h->cb_cls,
869                  ntohl (msg->options),
870                  (enum GNUNET_BLOCK_Type) ntohl(msg->type),
871                  ntohl (msg->hop_count),
872                  ntohl (msg->desired_replication_level),
873                  putl, path,
874                  GNUNET_TIME_absolute_ntoh(msg->expiration_time),
875                  &msg->key,
876                  (void *) &path[putl],
877                  msize -
878                  sizeof (struct GNUNET_DHT_MonitorPutMessage) -
879                  sizeof (struct GNUNET_PeerIdentity) * putl);
880   }
881   return GNUNET_OK;
882 }
883
884
885 #if ENABLE_MALICIOUS
886 /**
887  * Process a act malicious confirmation from service.
888  * @param handle The DHT handle.
889  * @param msg confirmation message from the service.
890  * @return #GNUNET_OK if everything went fine,
891  *         #GNUNET_SYSERR if the message is malformed.
892  */
893 static int
894 process_act_malicious_confirmation_message (struct GNUNET_DHT_Handle *handle,
895            const struct GNUNET_DHT_ClientActMaliciousConfirmationMessage *msg)
896 {
897    struct GNUNET_DHT_ActMaliciousHandle *mh;
898    GNUNET_DHT_PutContinuation cont;
899    void *cont_cls;
900
901    mh = handle->mh;
902    if (NULL == mh)
903     return GNUNET_OK;
904   cont = mh->cont;
905   cont_cls = mh->cont_cls;
906   if (NULL != cont)
907     cont (cont_cls, GNUNET_OK);
908
909   return GNUNET_OK;
910 }
911 #endif
912
913
914 /**
915  * Process a put confirmation message from the service.
916  *
917  * @param handle The DHT handle.
918  * @param msg confirmation message from the service.
919  * @return #GNUNET_OK if everything went fine,
920  *         #GNUNET_SYSERR if the message is malformed.
921  */
922 static int
923 process_put_confirmation_message (struct GNUNET_DHT_Handle *handle,
924                                   const struct GNUNET_DHT_ClientPutConfirmationMessage *msg)
925 {
926   struct GNUNET_DHT_PutHandle *ph;
927   GNUNET_DHT_PutContinuation cont;
928   void *cont_cls;
929
930   for (ph = handle->put_head; NULL != ph; ph = ph->next)
931     if (ph->unique_id == msg->unique_id)
932       break;
933   if (NULL == ph)
934     return GNUNET_OK;
935   cont = ph->cont;
936   cont_cls = ph->cont_cls;
937   GNUNET_DHT_put_cancel (ph);
938   if (NULL != cont)
939     cont (cont_cls, GNUNET_OK);
940   return GNUNET_OK;
941 }
942
943
944 /**
945  * Handler for messages received from the DHT service
946  * a demultiplexer which handles numerous message types
947  *
948  * @param cls the `struct GNUNET_DHT_Handle`
949  * @param msg the incoming message
950  */
951 static void
952 service_message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
953 {
954   struct GNUNET_DHT_Handle *handle = cls;
955   const struct GNUNET_DHT_ClientResultMessage *dht_msg;
956   uint16_t msize;
957   int ret;
958
959
960   if (NULL == msg)
961   {
962     LOG (GNUNET_ERROR_TYPE_DEBUG,
963          "Error receiving data from DHT service, reconnecting\n");
964     do_disconnect (handle);
965     return;
966   }
967   GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
968                          GNUNET_TIME_UNIT_FOREVER_REL);
969   ret = GNUNET_SYSERR;
970   msize = ntohs (msg->size);
971   switch (ntohs (msg->type))
972   {
973   case GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET:
974     if (msize < sizeof (struct GNUNET_DHT_MonitorGetMessage))
975     {
976       GNUNET_break (0);
977       break;
978     }
979     ret = process_monitor_get_message(handle,
980                                       (const struct GNUNET_DHT_MonitorGetMessage *) msg);
981     break;
982   case GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP:
983     if (msize < sizeof (struct GNUNET_DHT_MonitorGetRespMessage))
984     {
985       GNUNET_break (0);
986       break;
987     }
988     ret = process_monitor_get_resp_message(handle,
989                                            (const struct GNUNET_DHT_MonitorGetRespMessage *) msg);
990     break;
991   case GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT:
992     if (msize < sizeof (struct GNUNET_DHT_MonitorPutMessage))
993     {
994       GNUNET_break (0);
995       break;
996     }
997     ret = process_monitor_put_message(handle,
998                                       (const struct GNUNET_DHT_MonitorPutMessage *) msg);
999     break;
1000   case GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT_RESP:
1001     /* Not implemented yet */
1002     GNUNET_break(0);
1003     break;
1004   case GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT:
1005     if (ntohs (msg->size) < sizeof (struct GNUNET_DHT_ClientResultMessage))
1006     {
1007       GNUNET_break (0);
1008       break;
1009     }
1010     dht_msg = (const struct GNUNET_DHT_ClientResultMessage *) msg;
1011     LOG (GNUNET_ERROR_TYPE_DEBUG,
1012          "Received reply for `%s' from DHT service %p\n",
1013          GNUNET_h2s (&dht_msg->key), handle);
1014     GNUNET_CONTAINER_multihashmap_get_multiple (handle->active_requests,
1015                                                 &dht_msg->key,
1016                                                 &process_reply,
1017                                                 (void *) dht_msg);
1018     ret = GNUNET_OK;
1019     break;
1020   case GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT_OK:
1021     if (ntohs (msg->size) != sizeof (struct GNUNET_DHT_ClientPutConfirmationMessage))
1022     {
1023       GNUNET_break (0);
1024       break;
1025     }
1026     ret = process_put_confirmation_message (handle,
1027                                             (const struct GNUNET_DHT_ClientPutConfirmationMessage*) msg);
1028     break;
1029 #if ENABLE_MALICIOUS
1030     case GNUNET_MESSAGE_TYPE_DHT_CLIENT_ACT_MALICIOUS_OK:
1031        if(msize != sizeof (struct GNUNET_DHT_ClientActMaliciousConfirmationMessage))
1032        {
1033          GNUNET_break (0);
1034          break;
1035        }
1036        ret = process_act_malicious_confirmation_message (handle,
1037                                             (const struct GNUNET_DHT_ClientActMaliciousConfirmationMessage*) msg);
1038       break;
1039 #endif
1040   default:
1041     GNUNET_break(0);
1042     LOG (GNUNET_ERROR_TYPE_WARNING,
1043          "Unknown DHT message type: %hu (%hu) size: %hu\n",
1044          ntohs (msg->type), msg->type, msize);
1045     break;
1046   }
1047   if (GNUNET_OK != ret)
1048   {
1049     GNUNET_break (0);
1050     do_disconnect (handle);
1051     return;
1052   }
1053 }
1054
1055
1056 /**
1057  * Initialize the connection with the DHT service.
1058  *
1059  * @param cfg configuration to use
1060  * @param ht_len size of the internal hash table to use for
1061  *               processing multiple GET/FIND requests in parallel
1062  * @return handle to the DHT service, or NULL on error
1063  */
1064 struct GNUNET_DHT_Handle *
1065 GNUNET_DHT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1066                     unsigned int ht_len)
1067 {
1068   struct GNUNET_DHT_Handle *handle;
1069
1070   handle = GNUNET_new (struct GNUNET_DHT_Handle);
1071   handle->cfg = cfg;
1072   handle->uid_gen =
1073       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1074   handle->active_requests = GNUNET_CONTAINER_multihashmap_create (ht_len, GNUNET_YES);
1075   if (GNUNET_NO == try_connect (handle))
1076   {
1077     GNUNET_DHT_disconnect (handle);
1078     return NULL;
1079   }
1080   return handle;
1081 }
1082
1083
1084 /**
1085  * Shutdown connection with the DHT service.
1086  *
1087  * @param handle handle of the DHT connection to stop
1088  */
1089 void
1090 GNUNET_DHT_disconnect (struct GNUNET_DHT_Handle *handle)
1091 {
1092   struct PendingMessage *pm;
1093   struct GNUNET_DHT_PutHandle *ph;
1094
1095   GNUNET_assert (NULL != handle);
1096   GNUNET_assert (0 ==
1097                  GNUNET_CONTAINER_multihashmap_size (handle->active_requests));
1098   if (NULL != handle->th)
1099   {
1100     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1101     handle->th = NULL;
1102   }
1103   while (NULL != (pm = handle->pending_head))
1104   {
1105     GNUNET_assert (GNUNET_YES == pm->in_pending_queue);
1106     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
1107                                  pm);
1108     pm->in_pending_queue = GNUNET_NO;
1109     GNUNET_assert (GNUNET_YES == pm->free_on_send);
1110     if (NULL != pm->cont)
1111       pm->cont (pm->cont_cls);
1112     GNUNET_free (pm);
1113   }
1114   while (NULL != (ph = handle->put_head))
1115   {
1116     GNUNET_break (NULL == ph->pending);
1117     if (NULL != ph->cont)
1118       ph->cont (ph->cont_cls, GNUNET_SYSERR);
1119     GNUNET_DHT_put_cancel (ph);
1120   }
1121
1122   if (NULL != handle->client)
1123   {
1124     GNUNET_CLIENT_disconnect (handle->client);
1125     handle->client = NULL;
1126   }
1127   if (NULL != handle->reconnect_task)
1128     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1129   GNUNET_CONTAINER_multihashmap_destroy (handle->active_requests);
1130   GNUNET_free (handle);
1131 }
1132
1133
1134 /**
1135  * Timeout for the transmission of a fire&forget-request.  Clean it up.
1136  *
1137  * @param cls the `struct GNUNET_DHT_PutHandle *`
1138  */
1139 static void
1140 timeout_put_request (void *cls)
1141 {
1142   struct GNUNET_DHT_PutHandle *ph = cls;
1143   struct GNUNET_DHT_Handle *handle = ph->dht_handle;
1144
1145   ph->timeout_task = NULL;
1146   if (NULL != ph->pending)
1147   {
1148     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
1149                                  ph->pending);
1150     ph->pending->in_pending_queue = GNUNET_NO;
1151     GNUNET_free (ph->pending);
1152   }
1153   if (NULL != ph->cont)
1154     ph->cont (ph->cont_cls, GNUNET_NO);
1155   GNUNET_CONTAINER_DLL_remove (handle->put_head,
1156                                handle->put_tail,
1157                                ph);
1158   GNUNET_free (ph);
1159 }
1160
1161
1162 /**
1163  * Function called whenever the PUT message leaves the queue.  Sets
1164  * the message pointer in the put handle to NULL.
1165  *
1166  * @param cls the `struct GNUNET_DHT_PutHandle`
1167  */
1168 static void
1169 mark_put_message_gone (void *cls)
1170 {
1171   struct GNUNET_DHT_PutHandle *ph = cls;
1172
1173   ph->pending = NULL;
1174 }
1175
1176
1177 /**
1178  * Perform a PUT operation storing data in the DHT.  FIXME: we should
1179  * change the protocol to get a confirmation for the PUT from the DHT
1180  * and call 'cont' only after getting the confirmation; otherwise, the
1181  * client has no good way of telling if the 'PUT' message actually got
1182  * to the DHT service!
1183  *
1184  * @param handle handle to DHT service
1185  * @param key the key to store under
1186  * @param desired_replication_level estimate of how many
1187  *                nearest peers this request should reach
1188  * @param options routing options for this message
1189  * @param type type of the value
1190  * @param size number of bytes in data; must be less than 64k
1191  * @param data the data to store
1192  * @param exp desired expiration time for the value
1193  * @param timeout how long to wait for transmission of this request
1194  * @param cont continuation to call when done (transmitting request to service)
1195  *        You must not call #GNUNET_DHT_disconnect in this continuation
1196  * @param cont_cls closure for @a cont
1197  */
1198 struct GNUNET_DHT_PutHandle *
1199 GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle,
1200                         const struct GNUNET_HashCode * key,
1201                 uint32_t desired_replication_level,
1202                 enum GNUNET_DHT_RouteOption options,
1203                 enum GNUNET_BLOCK_Type type, size_t size,
1204                             const void *data,
1205                 struct GNUNET_TIME_Absolute exp,
1206                 struct GNUNET_TIME_Relative timeout,
1207                             GNUNET_DHT_PutContinuation cont,
1208                 void *cont_cls)
1209 {
1210   struct GNUNET_DHT_ClientPutMessage *put_msg;
1211   size_t msize;
1212   struct PendingMessage *pending;
1213   struct GNUNET_DHT_PutHandle *ph;
1214
1215   msize = sizeof (struct GNUNET_DHT_ClientPutMessage) + size;
1216   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1217       (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
1218   {
1219     GNUNET_break (0);
1220     return NULL;
1221   }
1222   ph = GNUNET_new (struct GNUNET_DHT_PutHandle);
1223   ph->dht_handle = handle;
1224   ph->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout, &timeout_put_request, ph);
1225   ph->cont = cont;
1226   ph->cont_cls = cont_cls;
1227   ph->unique_id = ++handle->uid_gen;
1228   pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1229   ph->pending = pending;
1230   put_msg = (struct GNUNET_DHT_ClientPutMessage *) &pending[1];
1231   pending->msg = &put_msg->header;
1232   pending->handle = handle;
1233   pending->cont = &mark_put_message_gone;
1234   pending->cont_cls = ph;
1235   pending->free_on_send = GNUNET_YES;
1236   put_msg->header.size = htons (msize);
1237   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT);
1238   put_msg->type = htonl (type);
1239   put_msg->options = htonl ((uint32_t) options);
1240   put_msg->desired_replication_level = htonl (desired_replication_level);
1241   put_msg->unique_id = ph->unique_id;
1242   put_msg->expiration = GNUNET_TIME_absolute_hton (exp);
1243   put_msg->key = *key;
1244   memcpy (&put_msg[1], data, size);
1245   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1246                                pending);
1247   pending->in_pending_queue = GNUNET_YES;
1248   GNUNET_CONTAINER_DLL_insert_tail (handle->put_head,
1249                                     handle->put_tail,
1250                                     ph);
1251   process_pending_messages (handle);
1252   return ph;
1253 }
1254
1255
1256 /**
1257  * Cancels a DHT PUT operation.  Note that the PUT request may still
1258  * go out over the network (we can't stop that); However, if the PUT
1259  * has not yet been sent to the service, cancelling the PUT will stop
1260  * this from happening (but there is no way for the user of this API
1261  * to tell if that is the case).  The only use for this API is to
1262  * prevent a later call to 'cont' from #GNUNET_DHT_put (i.e. because
1263  * the system is shutting down).
1264  *
1265  * @param ph put operation to cancel ('cont' will no longer be called)
1266  */
1267 void
1268 GNUNET_DHT_put_cancel (struct GNUNET_DHT_PutHandle *ph)
1269 {
1270   struct GNUNET_DHT_Handle *handle = ph->dht_handle;
1271
1272   if (NULL != ph->pending)
1273   {
1274     GNUNET_CONTAINER_DLL_remove (handle->pending_head,
1275                                  handle->pending_tail,
1276                                  ph->pending);
1277     GNUNET_free (ph->pending);
1278     ph->pending = NULL;
1279   }
1280   if (ph->timeout_task != NULL)
1281   {
1282     GNUNET_SCHEDULER_cancel (ph->timeout_task);
1283     ph->timeout_task = NULL;
1284   }
1285   GNUNET_CONTAINER_DLL_remove (handle->put_head,
1286                                handle->put_tail,
1287                                ph);
1288   GNUNET_free (ph);
1289 }
1290
1291
1292 /**
1293  * Perform an asynchronous GET operation on the DHT identified. See
1294  * also #GNUNET_BLOCK_evaluate.
1295  *
1296  * @param handle handle to the DHT service
1297  * @param type expected type of the response object
1298  * @param key the key to look up
1299  * @param desired_replication_level estimate of how many
1300                   nearest peers this request should reach
1301  * @param options routing options for this message
1302  * @param xquery extended query data (can be NULL, depending on type)
1303  * @param xquery_size number of bytes in @a xquery
1304  * @param iter function to call on each result
1305  * @param iter_cls closure for iter
1306  * @return handle to stop the async get
1307  */
1308 struct GNUNET_DHT_GetHandle *
1309 GNUNET_DHT_get_start (struct GNUNET_DHT_Handle *handle,
1310                       enum GNUNET_BLOCK_Type type, const struct GNUNET_HashCode * key,
1311                       uint32_t desired_replication_level,
1312                       enum GNUNET_DHT_RouteOption options, const void *xquery,
1313                       size_t xquery_size, GNUNET_DHT_GetIterator iter,
1314                       void *iter_cls)
1315 {
1316   struct GNUNET_DHT_ClientGetMessage *get_msg;
1317   struct GNUNET_DHT_GetHandle *get_handle;
1318   size_t msize;
1319   struct PendingMessage *pending;
1320
1321   msize = sizeof (struct GNUNET_DHT_ClientGetMessage) + xquery_size;
1322   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1323       (xquery_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
1324   {
1325     GNUNET_break (0);
1326     return NULL;
1327   }
1328   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending query for %s to DHT %p\n",
1329        GNUNET_h2s (key), handle);
1330   pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1331   get_msg = (struct GNUNET_DHT_ClientGetMessage *) &pending[1];
1332   pending->msg = &get_msg->header;
1333   pending->handle = handle;
1334   pending->free_on_send = GNUNET_NO;
1335   get_msg->header.size = htons (msize);
1336   get_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET);
1337   get_msg->options = htonl ((uint32_t) options);
1338   get_msg->desired_replication_level = htonl (desired_replication_level);
1339   get_msg->type = htonl (type);
1340   get_msg->key = *key;
1341   get_msg->unique_id = ++handle->uid_gen;
1342   memcpy (&get_msg[1], xquery, xquery_size);
1343   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1344                                pending);
1345   pending->in_pending_queue = GNUNET_YES;
1346   get_handle = GNUNET_new (struct GNUNET_DHT_GetHandle);
1347   get_handle->key = *key;
1348   get_handle->dht_handle = handle;
1349   get_handle->iter = iter;
1350   get_handle->iter_cls = iter_cls;
1351   get_handle->message = pending;
1352   get_handle->unique_id = get_msg->unique_id;
1353   GNUNET_CONTAINER_multihashmap_put (handle->active_requests,
1354                                      &get_handle->key,
1355                                      get_handle,
1356                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1357   process_pending_messages (handle);
1358   return get_handle;
1359 }
1360
1361
1362 /**
1363  * Tell the DHT not to return any of the following known results
1364  * to this client.
1365  *
1366  * @param get_handle get operation for which results should be filtered
1367  * @param num_results number of results to be blocked that are
1368  *        provided in this call (size of the @a results array)
1369  * @param results array of hash codes over the 'data' of the results
1370  *        to be blocked
1371  */
1372 void
1373 GNUNET_DHT_get_filter_known_results (struct GNUNET_DHT_GetHandle *get_handle,
1374                                      unsigned int num_results,
1375                                      const struct GNUNET_HashCode *results)
1376 {
1377   unsigned int needed;
1378
1379   needed = get_handle->seen_results_end + num_results;
1380   if (needed > get_handle->seen_results_size)
1381     GNUNET_array_grow (get_handle->seen_results,
1382                        get_handle->seen_results_size,
1383                        needed);
1384   memcpy (&get_handle->seen_results[get_handle->seen_results_end],
1385           results,
1386           num_results * sizeof (struct GNUNET_HashCode));
1387   get_handle->seen_results_end += num_results;
1388   queue_filter_messages (get_handle);
1389   process_pending_messages (get_handle->dht_handle);
1390 }
1391
1392
1393 /**
1394  * Stop async DHT-get.
1395  *
1396  * @param get_handle handle to the GET operation to stop
1397  */
1398 void
1399 GNUNET_DHT_get_stop (struct GNUNET_DHT_GetHandle *get_handle)
1400 {
1401   struct GNUNET_DHT_Handle *handle;
1402   const struct GNUNET_DHT_ClientGetMessage *get_msg;
1403   struct GNUNET_DHT_ClientGetStopMessage *stop_msg;
1404   struct PendingMessage *pending;
1405
1406   handle = get_handle->message->handle;
1407   get_msg =
1408       (const struct GNUNET_DHT_ClientGetMessage *) get_handle->message->msg;
1409   LOG (GNUNET_ERROR_TYPE_DEBUG,
1410        "Sending STOP for %s to DHT via %p\n",
1411        GNUNET_h2s (&get_msg->key), handle);
1412   /* generate STOP */
1413   pending =
1414       GNUNET_malloc (sizeof (struct PendingMessage) +
1415                      sizeof (struct GNUNET_DHT_ClientGetStopMessage));
1416   stop_msg = (struct GNUNET_DHT_ClientGetStopMessage *) &pending[1];
1417   pending->msg = &stop_msg->header;
1418   pending->handle = handle;
1419   pending->free_on_send = GNUNET_YES;
1420   stop_msg->header.size =
1421       htons (sizeof (struct GNUNET_DHT_ClientGetStopMessage));
1422   stop_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP);
1423   stop_msg->reserved = htonl (0);
1424   stop_msg->unique_id = get_msg->unique_id;
1425   stop_msg->key = get_msg->key;
1426   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1427                                pending);
1428   pending->in_pending_queue = GNUNET_YES;
1429
1430   /* remove 'GET' from active status */
1431   GNUNET_assert (GNUNET_YES ==
1432                  GNUNET_CONTAINER_multihashmap_remove (handle->active_requests,
1433                                                        &get_handle->key,
1434                                                        get_handle));
1435   if (GNUNET_YES == get_handle->message->in_pending_queue)
1436   {
1437     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
1438                                  get_handle->message);
1439     get_handle->message->in_pending_queue = GNUNET_NO;
1440   }
1441   GNUNET_free (get_handle->message);
1442   GNUNET_array_grow (get_handle->seen_results,
1443                      get_handle->seen_results_end,
1444                      0);
1445   GNUNET_free (get_handle);
1446   process_pending_messages (handle);
1447 }
1448
1449
1450 /**
1451  * Start monitoring the local DHT service.
1452  *
1453  * @param handle Handle to the DHT service.
1454  * @param type Type of blocks that are of interest.
1455  * @param key Key of data of interest, NULL for all.
1456  * @param get_cb Callback to process monitored get messages.
1457  * @param get_resp_cb Callback to process monitored get response messages.
1458  * @param put_cb Callback to process monitored put messages.
1459  * @param cb_cls Closure for callbacks.
1460  * @return Handle to stop monitoring.
1461  */
1462 struct GNUNET_DHT_MonitorHandle *
1463 GNUNET_DHT_monitor_start (struct GNUNET_DHT_Handle *handle,
1464                           enum GNUNET_BLOCK_Type type,
1465                           const struct GNUNET_HashCode *key,
1466                           GNUNET_DHT_MonitorGetCB get_cb,
1467                           GNUNET_DHT_MonitorGetRespCB get_resp_cb,
1468                           GNUNET_DHT_MonitorPutCB put_cb,
1469                           void *cb_cls)
1470 {
1471   struct GNUNET_DHT_MonitorHandle *h;
1472   struct GNUNET_DHT_MonitorStartStopMessage *m;
1473   struct PendingMessage *pending;
1474
1475   h = GNUNET_new (struct GNUNET_DHT_MonitorHandle);
1476   GNUNET_CONTAINER_DLL_insert(handle->monitor_head, handle->monitor_tail, h);
1477
1478   h->get_cb = get_cb;
1479   h->get_resp_cb = get_resp_cb;
1480   h->put_cb = put_cb;
1481   h->cb_cls = cb_cls;
1482   h->type = type;
1483   h->dht_handle = handle;
1484   if (NULL != key)
1485   {
1486     h->key = GNUNET_new (struct GNUNET_HashCode);
1487     *h->key = *key;
1488   }
1489
1490   pending = GNUNET_malloc (sizeof (struct GNUNET_DHT_MonitorStartStopMessage) +
1491                            sizeof (struct PendingMessage));
1492   m = (struct GNUNET_DHT_MonitorStartStopMessage *) &pending[1];
1493   pending->msg = &m->header;
1494   pending->handle = handle;
1495   pending->free_on_send = GNUNET_YES;
1496   m->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_START);
1497   m->header.size = htons (sizeof (struct GNUNET_DHT_MonitorStartStopMessage));
1498   m->type = htonl(type);
1499   m->get = htons(NULL != get_cb);
1500   m->get_resp = htons(NULL != get_resp_cb);
1501   m->put = htons(NULL != put_cb);
1502   if (NULL != key) {
1503     m->filter_key = htons(1);
1504     memcpy (&m->key, key, sizeof(struct GNUNET_HashCode));
1505   }
1506   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1507                                pending);
1508   pending->in_pending_queue = GNUNET_YES;
1509   process_pending_messages (handle);
1510
1511   return h;
1512 }
1513
1514
1515 /**
1516  * Stop monitoring.
1517  *
1518  * @param handle The handle to the monitor request returned by monitor_start.
1519  *
1520  * On return get_handle will no longer be valid, caller must not use again!!!
1521  */
1522 void
1523 GNUNET_DHT_monitor_stop (struct GNUNET_DHT_MonitorHandle *handle)
1524 {
1525   struct GNUNET_DHT_MonitorStartStopMessage *m;
1526   struct PendingMessage *pending;
1527
1528   GNUNET_CONTAINER_DLL_remove (handle->dht_handle->monitor_head,
1529                                handle->dht_handle->monitor_tail,
1530                                handle);
1531
1532   pending = GNUNET_malloc (sizeof (struct GNUNET_DHT_MonitorStartStopMessage) +
1533                            sizeof (struct PendingMessage));
1534   m = (struct GNUNET_DHT_MonitorStartStopMessage *) &pending[1];
1535   pending->msg = &m->header;
1536   pending->handle = handle->dht_handle;
1537   pending->free_on_send = GNUNET_YES;
1538   m->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP);
1539   m->header.size = htons (sizeof (struct GNUNET_DHT_MonitorStartStopMessage));
1540   m->type = htonl(handle->type);
1541   m->get = htons (NULL != handle->get_cb);
1542   m->get_resp = htons(NULL != handle->get_resp_cb);
1543   m->put = htons (NULL != handle->put_cb);
1544   if (NULL != handle->key)
1545   {
1546     m->filter_key = htons (1);
1547     m->key = *handle->key;
1548   }
1549   GNUNET_CONTAINER_DLL_insert (handle->dht_handle->pending_head,
1550                                handle->dht_handle->pending_tail,
1551                                pending);
1552   pending->in_pending_queue = GNUNET_YES;
1553   process_pending_messages (handle->dht_handle);
1554
1555   GNUNET_free_non_null (handle->key);
1556   GNUNET_free (handle);
1557 }
1558
1559
1560 #if ENABLE_MALICIOUS
1561 /**
1562  * Turn the DHT service to act malicious.
1563  *
1564  * @param handle the DHT handle
1565  * @param action 1 to make the service malicious; 0 to make it benign
1566  * @param cont continuation to call when done (transmitting request to service)
1567  * @param cont_cls closure for @a cont
1568  */
1569 struct GNUNET_DHT_ActMaliciousHandle *
1570 GNUNET_DHT_act_malicious (struct GNUNET_DHT_Handle *handle,
1571                           unsigned int action,
1572                           GNUNET_DHT_PutContinuation cont,
1573                           void *cont_cls)
1574 {
1575   struct GNUNET_DHT_ActMaliciousMessage *amm;
1576   struct GNUNET_DHT_ActMaliciousHandle *mh;
1577   struct PendingMessage *pending;
1578   size_t msize;
1579
1580   msize = sizeof(struct GNUNET_DHT_ActMaliciousMessage);
1581   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1582   {
1583     GNUNET_break(0);
1584     return NULL;
1585   }
1586   mh = GNUNET_new (struct GNUNET_DHT_ActMaliciousHandle);
1587   mh->dht_handle = handle;
1588   mh->cont = cont;
1589   mh->cont_cls = cont_cls;
1590   pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1591   amm = (struct GNUNET_DHT_ActMaliciousMessage *)&pending[1];
1592   pending->msg = &amm->header;
1593   pending->handle = handle;
1594   pending->free_on_send = GNUNET_YES;
1595   amm->header.size = htons (msize);
1596   amm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_ACT_MALICIOUS);
1597   amm->action = action;
1598   handle->mh = mh;
1599   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1600                                pending);
1601   pending->in_pending_queue = GNUNET_YES;
1602   process_pending_messages (handle);
1603   return mh;
1604 }
1605 #endif
1606
1607
1608 /* end of dht_api.c */