-fix (C) notices
[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  * @param tc scheduler context
500  */
501 static void
502 try_reconnect (void *cls,
503                const struct GNUNET_SCHEDULER_TaskContext *tc)
504 {
505   struct GNUNET_DHT_Handle *handle = cls;
506
507   LOG (GNUNET_ERROR_TYPE_DEBUG, "Reconnecting with DHT %p\n", handle);
508   handle->retry_time = GNUNET_TIME_STD_BACKOFF (handle->retry_time);
509   handle->reconnect_task = NULL;
510   if (GNUNET_YES != try_connect (handle))
511   {
512     LOG (GNUNET_ERROR_TYPE_DEBUG, "dht reconnect failed(!)\n");
513     return;
514   }
515   GNUNET_CONTAINER_multihashmap_iterate (handle->active_requests,
516                                          &add_request_to_pending, handle);
517   process_pending_messages (handle);
518 }
519
520
521 /**
522  * Try reconnecting to the DHT service.
523  *
524  * @param handle handle to dht to (possibly) disconnect and reconnect
525  */
526 static void
527 do_disconnect (struct GNUNET_DHT_Handle *handle)
528 {
529   struct GNUNET_DHT_PutHandle *ph;
530   struct GNUNET_DHT_PutHandle *next;
531
532   if (NULL == handle->client)
533     return;
534   GNUNET_assert (NULL == handle->reconnect_task);
535   if (NULL != handle->th)
536     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
537   handle->th = NULL;
538   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
539               "Disconnecting from DHT service, will try to reconnect in %s\n",
540               GNUNET_STRINGS_relative_time_to_string (handle->retry_time,
541                                                       GNUNET_YES));
542   GNUNET_CLIENT_disconnect (handle->client);
543   handle->client = NULL;
544
545   /* signal disconnect to all PUT requests that were transmitted but waiting
546      for the put confirmation */
547   next = handle->put_head;
548   while (NULL != (ph = next))
549   {
550     next = ph->next;
551     if (NULL == ph->pending)
552     {
553       if (NULL != ph->cont)
554         ph->cont (ph->cont_cls, GNUNET_SYSERR);
555       GNUNET_DHT_put_cancel (ph);
556     }
557   }
558   handle->reconnect_task =
559       GNUNET_SCHEDULER_add_delayed (handle->retry_time, &try_reconnect, handle);
560 }
561
562
563 /**
564  * Transmit the next pending message, called by notify_transmit_ready
565  *
566  * @param cls the DHT handle
567  * @param size number of bytes available in @a buf for transmission
568  * @param buf where to copy messages for the service
569  * @return number of bytes written to @a buf
570  */
571 static size_t
572 transmit_pending (void *cls,
573                   size_t size,
574                   void *buf);
575
576
577 /**
578  * Try to send messages from list of messages to send
579  *
580  * @param handle handle to DHT
581  */
582 static void
583 process_pending_messages (struct GNUNET_DHT_Handle *handle)
584 {
585   struct PendingMessage *head;
586
587   if (NULL == handle->client)
588   {
589     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
590                 "process_pending_messages called, but client is NULL, reconnecting\n");
591     do_disconnect (handle);
592     return;
593   }
594   if (NULL != handle->th)
595     return;
596   if (NULL == (head = handle->pending_head))
597     return;
598   handle->th =
599       GNUNET_CLIENT_notify_transmit_ready (handle->client,
600                                            ntohs (head->msg->size),
601                                            GNUNET_TIME_UNIT_FOREVER_REL,
602                                            GNUNET_YES, &transmit_pending,
603                                            handle);
604   if (NULL != handle->th)
605     return;
606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
607               "notify_transmit_ready returned NULL, reconnecting\n");
608   do_disconnect (handle);
609 }
610
611
612 /**
613  * Transmit the next pending message, called by notify_transmit_ready
614  *
615  * @param cls the DHT handle
616  * @param size number of bytes available in @a buf for transmission
617  * @param buf where to copy messages for the service
618  * @return number of bytes written to @a buf
619  */
620 static size_t
621 transmit_pending (void *cls,
622                   size_t size,
623                   void *buf)
624 {
625   struct GNUNET_DHT_Handle *handle = cls;
626   struct PendingMessage *head;
627   size_t tsize;
628
629
630   handle->th = NULL;
631   if (NULL == buf)
632   {
633     LOG (GNUNET_ERROR_TYPE_DEBUG,
634          "Transmission to DHT service failed!  Reconnecting!\n");
635     do_disconnect (handle);
636     return 0;
637   }
638   if (NULL == (head = handle->pending_head))
639     return 0;
640
641   tsize = ntohs (head->msg->size);
642   if (size < tsize)
643   {
644     process_pending_messages (handle);
645     return 0;
646   }
647   memcpy (buf, head->msg, tsize);
648   GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
649                                head);
650   head->in_pending_queue = GNUNET_NO;
651   if (NULL != head->cont)
652   {
653     head->cont (head->cont_cls, NULL);
654     head->cont = NULL;
655     head->cont_cls = NULL;
656   }
657   if (GNUNET_YES == head->free_on_send)
658     GNUNET_free (head);
659   process_pending_messages (handle);
660   LOG (GNUNET_ERROR_TYPE_DEBUG,
661        "Forwarded request of %u bytes to DHT service\n", (unsigned int) tsize);
662   if (GNUNET_NO == handle->in_receive)
663   {
664     LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting to process replies from DHT\n");
665     handle->in_receive = GNUNET_YES;
666     
667     GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
668                            GNUNET_TIME_UNIT_FOREVER_REL);
669   }
670   return tsize;
671 }
672
673
674 /**
675  * Process a given reply that might match the given
676  * request.
677  *
678  * @param cls the `struct GNUNET_DHT_ClientResultMessage`
679  * @param key query of the request
680  * @param value the `struct GNUNET_DHT_RouteHandle` of a request matching the same key
681  * @return #GNUNET_YES to continue to iterate over all results,
682  *         #GNUNET_NO if the reply is malformed or we found a matching request
683  */
684 static int
685 process_reply (void *cls,
686                const struct GNUNET_HashCode *key,
687                void *value)
688 {
689   const struct GNUNET_DHT_ClientResultMessage *dht_msg = cls;
690   struct GNUNET_DHT_GetHandle *get_handle = value;
691   const struct GNUNET_PeerIdentity *put_path;
692   const struct GNUNET_PeerIdentity *get_path;
693   struct GNUNET_HashCode hc;
694   uint32_t put_path_length;
695   uint32_t get_path_length;
696   size_t data_length;
697   size_t msize;
698   size_t meta_length;
699   const void *data;
700
701   if (dht_msg->unique_id != get_handle->unique_id)
702   {
703     /* UID mismatch */
704     LOG (GNUNET_ERROR_TYPE_DEBUG,
705          "Ignoring reply for %s: UID mismatch: %llu/%llu\n", GNUNET_h2s (key),
706          dht_msg->unique_id, get_handle->unique_id);
707     return GNUNET_YES;
708   }
709   msize = ntohs (dht_msg->header.size);
710   put_path_length = ntohl (dht_msg->put_path_length);
711   get_path_length = ntohl (dht_msg->get_path_length);
712   meta_length =
713       sizeof (struct GNUNET_DHT_ClientResultMessage) +
714       sizeof (struct GNUNET_PeerIdentity) * (get_path_length + put_path_length);
715   if ((msize < meta_length) ||
716       (get_path_length >
717        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
718       (put_path_length >
719        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
720   {
721     GNUNET_break (0);
722     return GNUNET_NO;
723   }
724   data_length = msize - meta_length;
725   LOG (GNUNET_ERROR_TYPE_DEBUG, "Giving %u byte reply for %s to application\n",
726        (unsigned int) data_length, GNUNET_h2s (key));
727   put_path = (const struct GNUNET_PeerIdentity *) &dht_msg[1];
728   get_path = &put_path[put_path_length];
729   data = &get_path[get_path_length];
730   /* remember that we've seen this result */
731   GNUNET_CRYPTO_hash (data, data_length, &hc);
732   if (get_handle->seen_results_size == get_handle->seen_results_end)
733     GNUNET_array_grow (get_handle->seen_results,
734                        get_handle->seen_results_size,
735                        get_handle->seen_results_size * 2 + 1);
736   GNUNET_assert (get_handle->seen_results_end == get_handle->seen_results_transmission_offset);
737   get_handle->seen_results[get_handle->seen_results_end++] = hc;
738   /* no need to block it explicitly, service already knows about it! */
739   get_handle->seen_results_transmission_offset++;
740   get_handle->iter (get_handle->iter_cls,
741                     GNUNET_TIME_absolute_ntoh (dht_msg->expiration), key,
742                     get_path, get_path_length, put_path, put_path_length,
743                     ntohl (dht_msg->type), data_length, data);
744   return GNUNET_NO;
745 }
746
747
748 /**
749  * Process a get monitor message from the service.
750  *
751  * @param handle The DHT handle.
752  * @param msg Monitor get message from the service.
753  * @return #GNUNET_OK if everything went fine,
754  *         #GNUNET_SYSERR if the message is malformed.
755  */
756 static int
757 process_monitor_get_message (struct GNUNET_DHT_Handle *handle,
758                              const struct GNUNET_DHT_MonitorGetMessage *msg)
759 {
760   struct GNUNET_DHT_MonitorHandle *h;
761
762   for (h = handle->monitor_head; NULL != h; h = h->next)
763   {
764     int type_ok;
765     int key_ok;
766
767     type_ok = (GNUNET_BLOCK_TYPE_ANY == h->type) || (h->type == ntohl(msg->type));
768     key_ok = (NULL == h->key) || (0 == memcmp (h->key, &msg->key,
769                                                sizeof (struct GNUNET_HashCode)));
770     if (type_ok && key_ok && (NULL != h->get_cb))
771       h->get_cb (h->cb_cls,
772                  ntohl (msg->options),
773                  (enum GNUNET_BLOCK_Type) ntohl(msg->type),
774                  ntohl (msg->hop_count),
775                  ntohl (msg->desired_replication_level),
776                  ntohl (msg->get_path_length),
777                  (struct GNUNET_PeerIdentity *) &msg[1],
778                  &msg->key);
779   }
780   return GNUNET_OK;
781 }
782
783
784 /**
785  * Process a get response monitor message from the service.
786  *
787  * @param handle The DHT handle.
788  * @param msg monitor get response message from the service
789  * @return #GNUNET_OK if everything went fine,
790  *         #GNUNET_SYSERR if the message is malformed.
791  */
792 static int
793 process_monitor_get_resp_message (struct GNUNET_DHT_Handle *handle,
794                                   const struct GNUNET_DHT_MonitorGetRespMessage *msg)
795 {
796   struct GNUNET_DHT_MonitorHandle *h;
797   struct GNUNET_PeerIdentity *path;
798   uint32_t getl;
799   uint32_t putl;
800   size_t msize;
801
802   msize = ntohs (msg->header.size);
803   path = (struct GNUNET_PeerIdentity *) &msg[1];
804   getl = ntohl (msg->get_path_length);
805   putl = ntohl (msg->put_path_length);
806   if ( (getl + putl < getl) ||
807        ( ((msize - sizeof (struct GNUNET_DHT_MonitorGetRespMessage)) / sizeof (struct GNUNET_PeerIdentity)) < getl + putl) )
808   {
809     GNUNET_break (0);
810     return GNUNET_SYSERR;
811   }
812   for (h = handle->monitor_head; NULL != h; h = h->next)
813   {
814     int type_ok;
815     int key_ok;
816
817     type_ok = (GNUNET_BLOCK_TYPE_ANY == h->type) || (h->type == ntohl(msg->type));
818     key_ok = (NULL == h->key) || (0 == memcmp (h->key, &msg->key,
819                                                sizeof (struct GNUNET_HashCode)));
820     if (type_ok && key_ok && (NULL != h->get_resp_cb))
821       h->get_resp_cb (h->cb_cls,
822                       (enum GNUNET_BLOCK_Type) ntohl(msg->type),
823                       path, getl,
824                       &path[getl], putl,
825                       GNUNET_TIME_absolute_ntoh(msg->expiration_time),
826                       &msg->key,
827                       (void *) &path[getl + putl],
828                       msize -
829                       sizeof (struct GNUNET_DHT_MonitorGetRespMessage) -
830                       sizeof (struct GNUNET_PeerIdentity) * (putl + getl));
831   }
832   return GNUNET_OK;
833 }
834
835
836 /**
837  * Process a put monitor message from the service.
838  *
839  * @param handle The DHT handle.
840  * @param msg Monitor put message from the service.
841  * @return #GNUNET_OK if everything went fine,
842  *         #GNUNET_SYSERR if the message is malformed.
843  */
844 static int
845 process_monitor_put_message (struct GNUNET_DHT_Handle *handle,
846                              const struct GNUNET_DHT_MonitorPutMessage *msg)
847 {
848   struct GNUNET_DHT_MonitorHandle *h;
849   size_t msize;
850   struct GNUNET_PeerIdentity *path;
851   uint32_t putl;
852
853   msize = ntohs (msg->header.size);
854   path = (struct GNUNET_PeerIdentity *) &msg[1];
855   putl = ntohl (msg->put_path_length);
856   if (((msize - sizeof (struct GNUNET_DHT_MonitorGetRespMessage)) / sizeof (struct GNUNET_PeerIdentity)) < putl)
857   {
858     GNUNET_break (0);
859     return GNUNET_SYSERR;
860   }
861   for (h = handle->monitor_head; NULL != h; h = h->next)
862   {
863     int type_ok;
864     int key_ok;
865
866     type_ok = (GNUNET_BLOCK_TYPE_ANY == h->type) || (h->type == ntohl(msg->type));
867     key_ok = (NULL == h->key) || (0 == memcmp (h->key, &msg->key,
868                                                sizeof (struct GNUNET_HashCode)));
869     if (type_ok && key_ok && (NULL != h->put_cb))
870       h->put_cb (h->cb_cls,
871                  ntohl (msg->options),
872                  (enum GNUNET_BLOCK_Type) ntohl(msg->type),
873                  ntohl (msg->hop_count),
874                  ntohl (msg->desired_replication_level),
875                  putl, path,
876                  GNUNET_TIME_absolute_ntoh(msg->expiration_time),
877                  &msg->key,
878                  (void *) &path[putl],
879                  msize -
880                  sizeof (struct GNUNET_DHT_MonitorPutMessage) -
881                  sizeof (struct GNUNET_PeerIdentity) * putl);
882   }
883   return GNUNET_OK;
884 }
885
886
887 #if ENABLE_MALICIOUS
888 /**
889  * Process a act malicious confirmation from service.
890  * @param handle The DHT handle.
891  * @param msg confirmation message from the service.
892  * @return #GNUNET_OK if everything went fine,
893  *         #GNUNET_SYSERR if the message is malformed.
894  */
895 static int
896 process_act_malicious_confirmation_message (struct GNUNET_DHT_Handle *handle,
897            const struct GNUNET_DHT_ClientActMaliciousConfirmationMessage *msg)
898 {
899    struct GNUNET_DHT_ActMaliciousHandle *mh;
900    GNUNET_DHT_PutContinuation cont;
901    void *cont_cls;
902    
903    mh = handle->mh;
904    if (NULL == mh)
905     return GNUNET_OK;
906   cont = mh->cont;
907   cont_cls = mh->cont_cls;
908   if (NULL != cont)
909     cont (cont_cls, GNUNET_OK);
910   
911   return GNUNET_OK;
912 }
913 #endif
914
915
916 /**
917  * Process a put confirmation message from the service.
918  *
919  * @param handle The DHT handle.
920  * @param msg confirmation message from the service.
921  * @return #GNUNET_OK if everything went fine,
922  *         #GNUNET_SYSERR if the message is malformed.
923  */
924 static int
925 process_put_confirmation_message (struct GNUNET_DHT_Handle *handle,
926                                   const struct GNUNET_DHT_ClientPutConfirmationMessage *msg)
927 {
928   struct GNUNET_DHT_PutHandle *ph;
929   GNUNET_DHT_PutContinuation cont;
930   void *cont_cls;
931
932   for (ph = handle->put_head; NULL != ph; ph = ph->next)
933     if (ph->unique_id == msg->unique_id)
934       break;
935   if (NULL == ph)
936     return GNUNET_OK;
937   cont = ph->cont;
938   cont_cls = ph->cont_cls;
939   GNUNET_DHT_put_cancel (ph);
940   if (NULL != cont)
941     cont (cont_cls, GNUNET_OK);
942   return GNUNET_OK;
943 }
944
945
946 /**
947  * Handler for messages received from the DHT service
948  * a demultiplexer which handles numerous message types
949  *
950  * @param cls the `struct GNUNET_DHT_Handle`
951  * @param msg the incoming message
952  */
953 static void
954 service_message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
955 {
956   struct GNUNET_DHT_Handle *handle = cls;
957   const struct GNUNET_DHT_ClientResultMessage *dht_msg;
958   uint16_t msize;
959   int ret;
960
961
962   if (NULL == msg)
963   {
964     LOG (GNUNET_ERROR_TYPE_DEBUG,
965          "Error receiving data from DHT service, reconnecting\n");
966     do_disconnect (handle);
967     return;
968   }
969   GNUNET_CLIENT_receive (handle->client, &service_message_handler, handle,
970                          GNUNET_TIME_UNIT_FOREVER_REL);
971   ret = GNUNET_SYSERR;
972   msize = ntohs (msg->size);
973   switch (ntohs (msg->type))
974   {
975   case GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET:
976     if (msize < sizeof (struct GNUNET_DHT_MonitorGetMessage))
977     {
978       GNUNET_break (0);
979       break;
980     }
981     ret = process_monitor_get_message(handle,
982                                       (const struct GNUNET_DHT_MonitorGetMessage *) msg);
983     break;
984   case GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP:
985     if (msize < sizeof (struct GNUNET_DHT_MonitorGetRespMessage))
986     {
987       GNUNET_break (0);
988       break;
989     }
990     ret = process_monitor_get_resp_message(handle,
991                                            (const struct GNUNET_DHT_MonitorGetRespMessage *) msg);
992     break;
993   case GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT:
994     if (msize < sizeof (struct GNUNET_DHT_MonitorPutMessage))
995     {
996       GNUNET_break (0);
997       break;
998     }
999     ret = process_monitor_put_message(handle,
1000                                       (const struct GNUNET_DHT_MonitorPutMessage *) msg);
1001     break;
1002   case GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT_RESP:
1003     /* Not implemented yet */
1004     GNUNET_break(0);
1005     break;
1006   case GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT:
1007     if (ntohs (msg->size) < sizeof (struct GNUNET_DHT_ClientResultMessage))
1008     {
1009       GNUNET_break (0);
1010       break;
1011     }
1012     dht_msg = (const struct GNUNET_DHT_ClientResultMessage *) msg;
1013     LOG (GNUNET_ERROR_TYPE_DEBUG,
1014          "Received reply for `%s' from DHT service %p\n",
1015          GNUNET_h2s (&dht_msg->key), handle);
1016     GNUNET_CONTAINER_multihashmap_get_multiple (handle->active_requests,
1017                                                 &dht_msg->key,
1018                                                 &process_reply,
1019                                                 (void *) dht_msg);
1020     ret = GNUNET_OK;
1021     break;
1022   case GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT_OK:
1023     if (ntohs (msg->size) != sizeof (struct GNUNET_DHT_ClientPutConfirmationMessage))
1024     {
1025       GNUNET_break (0);
1026       break;
1027     }
1028     ret = process_put_confirmation_message (handle,
1029                                             (const struct GNUNET_DHT_ClientPutConfirmationMessage*) msg);
1030     break;
1031 #if ENABLE_MALICIOUS
1032     case GNUNET_MESSAGE_TYPE_DHT_CLIENT_ACT_MALICIOUS_OK:
1033        if(msize != sizeof (struct GNUNET_DHT_ClientActMaliciousConfirmationMessage))
1034        {
1035          GNUNET_break (0);
1036          break;
1037        }
1038        ret = process_act_malicious_confirmation_message (handle,
1039                                             (const struct GNUNET_DHT_ClientActMaliciousConfirmationMessage*) msg);
1040       break;
1041 #endif
1042   default:
1043     GNUNET_break(0);
1044     LOG (GNUNET_ERROR_TYPE_WARNING,
1045          "Unknown DHT message type: %hu (%hu) size: %hu\n",
1046          ntohs (msg->type), msg->type, msize);
1047     break;
1048   }
1049   if (GNUNET_OK != ret)
1050   {
1051     GNUNET_break (0);
1052     do_disconnect (handle);
1053     return;
1054   }
1055 }
1056
1057
1058 /**
1059  * Initialize the connection with the DHT service.
1060  *
1061  * @param cfg configuration to use
1062  * @param ht_len size of the internal hash table to use for
1063  *               processing multiple GET/FIND requests in parallel
1064  * @return handle to the DHT service, or NULL on error
1065  */
1066 struct GNUNET_DHT_Handle *
1067 GNUNET_DHT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1068                     unsigned int ht_len)
1069 {
1070   struct GNUNET_DHT_Handle *handle;
1071
1072   handle = GNUNET_new (struct GNUNET_DHT_Handle);
1073   handle->cfg = cfg;
1074   handle->uid_gen =
1075       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1076   handle->active_requests = GNUNET_CONTAINER_multihashmap_create (ht_len, GNUNET_YES);
1077   if (GNUNET_NO == try_connect (handle))
1078   {
1079     GNUNET_DHT_disconnect (handle);
1080     return NULL;
1081   }
1082   return handle;
1083 }
1084
1085
1086 /**
1087  * Shutdown connection with the DHT service.
1088  *
1089  * @param handle handle of the DHT connection to stop
1090  */
1091 void
1092 GNUNET_DHT_disconnect (struct GNUNET_DHT_Handle *handle)
1093 {
1094   struct PendingMessage *pm;
1095   struct GNUNET_DHT_PutHandle *ph;
1096
1097   GNUNET_assert (NULL != handle);
1098   GNUNET_assert (0 ==
1099                  GNUNET_CONTAINER_multihashmap_size (handle->active_requests));
1100   if (NULL != handle->th)
1101   {
1102     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1103     handle->th = NULL;
1104   }
1105   while (NULL != (pm = handle->pending_head))
1106   {
1107     GNUNET_assert (GNUNET_YES == pm->in_pending_queue);
1108     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
1109                                  pm);
1110     pm->in_pending_queue = GNUNET_NO;
1111     GNUNET_assert (GNUNET_YES == pm->free_on_send);
1112     if (NULL != pm->cont)
1113       pm->cont (pm->cont_cls, NULL);
1114     GNUNET_free (pm);
1115   }
1116   while (NULL != (ph = handle->put_head))
1117   {
1118     GNUNET_break (NULL == ph->pending);
1119     if (NULL != ph->cont)
1120       ph->cont (ph->cont_cls, GNUNET_SYSERR);
1121     GNUNET_DHT_put_cancel (ph);
1122   }
1123
1124   if (NULL != handle->client)
1125   {
1126     GNUNET_CLIENT_disconnect (handle->client);
1127     handle->client = NULL;
1128   }
1129   if (NULL != handle->reconnect_task)
1130     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1131   GNUNET_CONTAINER_multihashmap_destroy (handle->active_requests);
1132   GNUNET_free (handle);
1133 }
1134
1135
1136 /**
1137  * Timeout for the transmission of a fire&forget-request.  Clean it up.
1138  *
1139  * @param cls the `struct GNUNET_DHT_PutHandle *`
1140  * @param tc scheduler context
1141  */
1142 static void
1143 timeout_put_request (void *cls,
1144                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1145 {
1146   struct GNUNET_DHT_PutHandle *ph = cls;
1147   struct GNUNET_DHT_Handle *handle = ph->dht_handle;
1148
1149   ph->timeout_task = NULL;
1150   if (NULL != ph->pending)
1151   {
1152     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
1153                                  ph->pending);
1154     ph->pending->in_pending_queue = GNUNET_NO;
1155     GNUNET_free (ph->pending);
1156   }
1157   if (NULL != ph->cont)
1158     ph->cont (ph->cont_cls, GNUNET_NO);
1159   GNUNET_CONTAINER_DLL_remove (handle->put_head,
1160                                handle->put_tail,
1161                                ph);
1162   GNUNET_free (ph);
1163 }
1164
1165
1166 /**
1167  * Function called whenever the PUT message leaves the queue.  Sets
1168  * the message pointer in the put handle to NULL.
1169  *
1170  * @param cls the `struct GNUNET_DHT_PutHandle`
1171  * @param tc unused
1172  */
1173 static void
1174 mark_put_message_gone (void *cls,
1175                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1176 {
1177   struct GNUNET_DHT_PutHandle *ph = cls;
1178
1179   ph->pending = NULL;
1180 }
1181
1182
1183 /**
1184  * Perform a PUT operation storing data in the DHT.  FIXME: we should
1185  * change the protocol to get a confirmation for the PUT from the DHT
1186  * and call 'cont' only after getting the confirmation; otherwise, the
1187  * client has no good way of telling if the 'PUT' message actually got
1188  * to the DHT service!
1189  *
1190  * @param handle handle to DHT service
1191  * @param key the key to store under
1192  * @param desired_replication_level estimate of how many
1193  *                nearest peers this request should reach
1194  * @param options routing options for this message
1195  * @param type type of the value
1196  * @param size number of bytes in data; must be less than 64k
1197  * @param data the data to store
1198  * @param exp desired expiration time for the value
1199  * @param timeout how long to wait for transmission of this request
1200  * @param cont continuation to call when done (transmitting request to service)
1201  *        You must not call #GNUNET_DHT_disconnect in this continuation
1202  * @param cont_cls closure for @a cont
1203  */
1204 struct GNUNET_DHT_PutHandle *
1205 GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle,
1206                         const struct GNUNET_HashCode * key,
1207                 uint32_t desired_replication_level,
1208                 enum GNUNET_DHT_RouteOption options,
1209                 enum GNUNET_BLOCK_Type type, size_t size,
1210                             const void *data,
1211                 struct GNUNET_TIME_Absolute exp,
1212                 struct GNUNET_TIME_Relative timeout,
1213                             GNUNET_DHT_PutContinuation cont,
1214                 void *cont_cls)
1215 {
1216   struct GNUNET_DHT_ClientPutMessage *put_msg;
1217   size_t msize;
1218   struct PendingMessage *pending;
1219   struct GNUNET_DHT_PutHandle *ph;
1220
1221   msize = sizeof (struct GNUNET_DHT_ClientPutMessage) + size;
1222   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1223       (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
1224   {
1225     GNUNET_break (0);
1226     return NULL;
1227   }
1228   ph = GNUNET_new (struct GNUNET_DHT_PutHandle);
1229   ph->dht_handle = handle;
1230   ph->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout, &timeout_put_request, ph);
1231   ph->cont = cont;
1232   ph->cont_cls = cont_cls;
1233   ph->unique_id = ++handle->uid_gen;
1234   pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1235   ph->pending = pending;
1236   put_msg = (struct GNUNET_DHT_ClientPutMessage *) &pending[1];
1237   pending->msg = &put_msg->header;
1238   pending->handle = handle;
1239   pending->cont = &mark_put_message_gone;
1240   pending->cont_cls = ph;
1241   pending->free_on_send = GNUNET_YES;
1242   put_msg->header.size = htons (msize);
1243   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT);
1244   put_msg->type = htonl (type);
1245   put_msg->options = htonl ((uint32_t) options);
1246   put_msg->desired_replication_level = htonl (desired_replication_level);
1247   put_msg->unique_id = ph->unique_id;
1248   put_msg->expiration = GNUNET_TIME_absolute_hton (exp);
1249   put_msg->key = *key;
1250   memcpy (&put_msg[1], data, size);
1251   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1252                                pending);
1253   pending->in_pending_queue = GNUNET_YES;
1254   GNUNET_CONTAINER_DLL_insert_tail (handle->put_head,
1255                                     handle->put_tail,
1256                                     ph);
1257   process_pending_messages (handle);
1258   return ph;
1259 }
1260
1261
1262 /**
1263  * Cancels a DHT PUT operation.  Note that the PUT request may still
1264  * go out over the network (we can't stop that); However, if the PUT
1265  * has not yet been sent to the service, cancelling the PUT will stop
1266  * this from happening (but there is no way for the user of this API
1267  * to tell if that is the case).  The only use for this API is to
1268  * prevent a later call to 'cont' from #GNUNET_DHT_put (i.e. because
1269  * the system is shutting down).
1270  *
1271  * @param ph put operation to cancel ('cont' will no longer be called)
1272  */
1273 void
1274 GNUNET_DHT_put_cancel (struct GNUNET_DHT_PutHandle *ph)
1275 {
1276   struct GNUNET_DHT_Handle *handle = ph->dht_handle;
1277
1278   if (NULL != ph->pending)
1279   {
1280     GNUNET_CONTAINER_DLL_remove (handle->pending_head,
1281                                  handle->pending_tail,
1282                                  ph->pending);
1283     GNUNET_free (ph->pending);
1284     ph->pending = NULL;
1285   }
1286   if (ph->timeout_task != NULL)
1287   {
1288     GNUNET_SCHEDULER_cancel (ph->timeout_task);
1289     ph->timeout_task = NULL;
1290   }
1291   GNUNET_CONTAINER_DLL_remove (handle->put_head,
1292                                handle->put_tail,
1293                                ph);
1294   GNUNET_free (ph);
1295 }
1296
1297
1298 /**
1299  * Perform an asynchronous GET operation on the DHT identified. See
1300  * also #GNUNET_BLOCK_evaluate.
1301  *
1302  * @param handle handle to the DHT service
1303  * @param type expected type of the response object
1304  * @param key the key to look up
1305  * @param desired_replication_level estimate of how many
1306                   nearest peers this request should reach
1307  * @param options routing options for this message
1308  * @param xquery extended query data (can be NULL, depending on type)
1309  * @param xquery_size number of bytes in @a xquery
1310  * @param iter function to call on each result
1311  * @param iter_cls closure for iter
1312  * @return handle to stop the async get
1313  */
1314 struct GNUNET_DHT_GetHandle *
1315 GNUNET_DHT_get_start (struct GNUNET_DHT_Handle *handle,
1316                       enum GNUNET_BLOCK_Type type, const struct GNUNET_HashCode * key,
1317                       uint32_t desired_replication_level,
1318                       enum GNUNET_DHT_RouteOption options, const void *xquery,
1319                       size_t xquery_size, GNUNET_DHT_GetIterator iter,
1320                       void *iter_cls)
1321 {
1322   struct GNUNET_DHT_ClientGetMessage *get_msg;
1323   struct GNUNET_DHT_GetHandle *get_handle;
1324   size_t msize;
1325   struct PendingMessage *pending;
1326
1327   msize = sizeof (struct GNUNET_DHT_ClientGetMessage) + xquery_size;
1328   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1329       (xquery_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
1330   {
1331     GNUNET_break (0);
1332     return NULL;
1333   }
1334   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending query for %s to DHT %p\n",
1335        GNUNET_h2s (key), handle);
1336   pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1337   get_msg = (struct GNUNET_DHT_ClientGetMessage *) &pending[1];
1338   pending->msg = &get_msg->header;
1339   pending->handle = handle;
1340   pending->free_on_send = GNUNET_NO;
1341   get_msg->header.size = htons (msize);
1342   get_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET);
1343   get_msg->options = htonl ((uint32_t) options);
1344   get_msg->desired_replication_level = htonl (desired_replication_level);
1345   get_msg->type = htonl (type);
1346   get_msg->key = *key;
1347   get_msg->unique_id = ++handle->uid_gen;
1348   memcpy (&get_msg[1], xquery, xquery_size);
1349   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1350                                pending);
1351   pending->in_pending_queue = GNUNET_YES;
1352   get_handle = GNUNET_new (struct GNUNET_DHT_GetHandle);
1353   get_handle->key = *key;
1354   get_handle->dht_handle = handle;
1355   get_handle->iter = iter;
1356   get_handle->iter_cls = iter_cls;
1357   get_handle->message = pending;
1358   get_handle->unique_id = get_msg->unique_id;
1359   GNUNET_CONTAINER_multihashmap_put (handle->active_requests,
1360                                      &get_handle->key,
1361                                      get_handle,
1362                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1363   process_pending_messages (handle);
1364   return get_handle;
1365 }
1366
1367
1368 /**
1369  * Tell the DHT not to return any of the following known results
1370  * to this client.
1371  *
1372  * @param get_handle get operation for which results should be filtered
1373  * @param num_results number of results to be blocked that are
1374  *        provided in this call (size of the @a results array)
1375  * @param results array of hash codes over the 'data' of the results
1376  *        to be blocked
1377  */
1378 void
1379 GNUNET_DHT_get_filter_known_results (struct GNUNET_DHT_GetHandle *get_handle,
1380                                      unsigned int num_results,
1381                                      const struct GNUNET_HashCode *results)
1382 {
1383   unsigned int needed;
1384
1385   needed = get_handle->seen_results_end + num_results;
1386   if (needed > get_handle->seen_results_size)
1387     GNUNET_array_grow (get_handle->seen_results,
1388                        get_handle->seen_results_size,
1389                        needed);
1390   memcpy (&get_handle->seen_results[get_handle->seen_results_end],
1391           results,
1392           num_results * sizeof (struct GNUNET_HashCode));
1393   get_handle->seen_results_end += num_results;
1394   queue_filter_messages (get_handle);
1395   process_pending_messages (get_handle->dht_handle);
1396 }
1397
1398
1399 /**
1400  * Stop async DHT-get.
1401  *
1402  * @param get_handle handle to the GET operation to stop
1403  */
1404 void
1405 GNUNET_DHT_get_stop (struct GNUNET_DHT_GetHandle *get_handle)
1406 {
1407   struct GNUNET_DHT_Handle *handle;
1408   const struct GNUNET_DHT_ClientGetMessage *get_msg;
1409   struct GNUNET_DHT_ClientGetStopMessage *stop_msg;
1410   struct PendingMessage *pending;
1411
1412   handle = get_handle->message->handle;
1413   get_msg =
1414       (const struct GNUNET_DHT_ClientGetMessage *) get_handle->message->msg;
1415   LOG (GNUNET_ERROR_TYPE_DEBUG,
1416        "Sending STOP for %s to DHT via %p\n",
1417        GNUNET_h2s (&get_msg->key), handle);
1418   /* generate STOP */
1419   pending =
1420       GNUNET_malloc (sizeof (struct PendingMessage) +
1421                      sizeof (struct GNUNET_DHT_ClientGetStopMessage));
1422   stop_msg = (struct GNUNET_DHT_ClientGetStopMessage *) &pending[1];
1423   pending->msg = &stop_msg->header;
1424   pending->handle = handle;
1425   pending->free_on_send = GNUNET_YES;
1426   stop_msg->header.size =
1427       htons (sizeof (struct GNUNET_DHT_ClientGetStopMessage));
1428   stop_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP);
1429   stop_msg->reserved = htonl (0);
1430   stop_msg->unique_id = get_msg->unique_id;
1431   stop_msg->key = get_msg->key;
1432   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1433                                pending);
1434   pending->in_pending_queue = GNUNET_YES;
1435
1436   /* remove 'GET' from active status */
1437   GNUNET_assert (GNUNET_YES ==
1438                  GNUNET_CONTAINER_multihashmap_remove (handle->active_requests,
1439                                                        &get_handle->key,
1440                                                        get_handle));
1441   if (GNUNET_YES == get_handle->message->in_pending_queue)
1442   {
1443     GNUNET_CONTAINER_DLL_remove (handle->pending_head, handle->pending_tail,
1444                                  get_handle->message);
1445     get_handle->message->in_pending_queue = GNUNET_NO;
1446   }
1447   GNUNET_free (get_handle->message);
1448   GNUNET_array_grow (get_handle->seen_results,
1449                      get_handle->seen_results_end,
1450                      0);
1451   GNUNET_free (get_handle);
1452   process_pending_messages (handle);
1453 }
1454
1455
1456 /**
1457  * Start monitoring the local DHT service.
1458  *
1459  * @param handle Handle to the DHT service.
1460  * @param type Type of blocks that are of interest.
1461  * @param key Key of data of interest, NULL for all.
1462  * @param get_cb Callback to process monitored get messages.
1463  * @param get_resp_cb Callback to process monitored get response messages.
1464  * @param put_cb Callback to process monitored put messages.
1465  * @param cb_cls Closure for callbacks.
1466  * @return Handle to stop monitoring.
1467  */
1468 struct GNUNET_DHT_MonitorHandle *
1469 GNUNET_DHT_monitor_start (struct GNUNET_DHT_Handle *handle,
1470                           enum GNUNET_BLOCK_Type type,
1471                           const struct GNUNET_HashCode *key,
1472                           GNUNET_DHT_MonitorGetCB get_cb,
1473                           GNUNET_DHT_MonitorGetRespCB get_resp_cb,
1474                           GNUNET_DHT_MonitorPutCB put_cb,
1475                           void *cb_cls)
1476 {
1477   struct GNUNET_DHT_MonitorHandle *h;
1478   struct GNUNET_DHT_MonitorStartStopMessage *m;
1479   struct PendingMessage *pending;
1480
1481   h = GNUNET_new (struct GNUNET_DHT_MonitorHandle);
1482   GNUNET_CONTAINER_DLL_insert(handle->monitor_head, handle->monitor_tail, h);
1483
1484   h->get_cb = get_cb;
1485   h->get_resp_cb = get_resp_cb;
1486   h->put_cb = put_cb;
1487   h->cb_cls = cb_cls;
1488   h->type = type;
1489   h->dht_handle = handle;
1490   if (NULL != key)
1491   {
1492     h->key = GNUNET_new (struct GNUNET_HashCode);
1493     *h->key = *key;
1494   }
1495
1496   pending = GNUNET_malloc (sizeof (struct GNUNET_DHT_MonitorStartStopMessage) +
1497                            sizeof (struct PendingMessage));
1498   m = (struct GNUNET_DHT_MonitorStartStopMessage *) &pending[1];
1499   pending->msg = &m->header;
1500   pending->handle = handle;
1501   pending->free_on_send = GNUNET_YES;
1502   m->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_START);
1503   m->header.size = htons (sizeof (struct GNUNET_DHT_MonitorStartStopMessage));
1504   m->type = htonl(type);
1505   m->get = htons(NULL != get_cb);
1506   m->get_resp = htons(NULL != get_resp_cb);
1507   m->put = htons(NULL != put_cb);
1508   if (NULL != key) {
1509     m->filter_key = htons(1);
1510     memcpy (&m->key, key, sizeof(struct GNUNET_HashCode));
1511   }
1512   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1513                                pending);
1514   pending->in_pending_queue = GNUNET_YES;
1515   process_pending_messages (handle);
1516
1517   return h;
1518 }
1519
1520
1521 /**
1522  * Stop monitoring.
1523  *
1524  * @param handle The handle to the monitor request returned by monitor_start.
1525  *
1526  * On return get_handle will no longer be valid, caller must not use again!!!
1527  */
1528 void
1529 GNUNET_DHT_monitor_stop (struct GNUNET_DHT_MonitorHandle *handle)
1530 {
1531   struct GNUNET_DHT_MonitorStartStopMessage *m;
1532   struct PendingMessage *pending;
1533
1534   GNUNET_CONTAINER_DLL_remove (handle->dht_handle->monitor_head,
1535                                handle->dht_handle->monitor_tail,
1536                                handle);
1537
1538   pending = GNUNET_malloc (sizeof (struct GNUNET_DHT_MonitorStartStopMessage) +
1539                            sizeof (struct PendingMessage));
1540   m = (struct GNUNET_DHT_MonitorStartStopMessage *) &pending[1];
1541   pending->msg = &m->header;
1542   pending->handle = handle->dht_handle;
1543   pending->free_on_send = GNUNET_YES;
1544   m->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP);
1545   m->header.size = htons (sizeof (struct GNUNET_DHT_MonitorStartStopMessage));
1546   m->type = htonl(handle->type);
1547   m->get = htons (NULL != handle->get_cb);
1548   m->get_resp = htons(NULL != handle->get_resp_cb);
1549   m->put = htons (NULL != handle->put_cb);
1550   if (NULL != handle->key)
1551   {
1552     m->filter_key = htons (1);
1553     m->key = *handle->key;
1554   }
1555   GNUNET_CONTAINER_DLL_insert (handle->dht_handle->pending_head,
1556                                handle->dht_handle->pending_tail,
1557                                pending);
1558   pending->in_pending_queue = GNUNET_YES;
1559   process_pending_messages (handle->dht_handle);
1560
1561   GNUNET_free_non_null (handle->key);
1562   GNUNET_free (handle);
1563 }
1564
1565
1566 #if ENABLE_MALICIOUS
1567 /**
1568  * Turn the DHT service to act malicious.
1569  *
1570  * @param handle the DHT handle
1571  * @param action 1 to make the service malicious; 0 to make it benign
1572  * @param cont continuation to call when done (transmitting request to service)
1573  * @param cont_cls closure for @a cont        
1574  */
1575 struct GNUNET_DHT_ActMaliciousHandle *
1576 GNUNET_DHT_act_malicious (struct GNUNET_DHT_Handle *handle, 
1577                           unsigned int action,
1578                           GNUNET_DHT_PutContinuation cont,
1579                           void *cont_cls)
1580 {
1581   struct GNUNET_DHT_ActMaliciousMessage *amm;
1582   struct GNUNET_DHT_ActMaliciousHandle *mh;
1583   struct PendingMessage *pending;
1584   size_t msize;
1585   
1586   msize = sizeof(struct GNUNET_DHT_ActMaliciousMessage);
1587   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1588   {
1589     GNUNET_break(0);
1590     return NULL;
1591   }
1592   mh = GNUNET_new (struct GNUNET_DHT_ActMaliciousHandle);
1593   mh->dht_handle = handle;
1594   mh->cont = cont;
1595   mh->cont_cls = cont_cls;
1596   pending = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1597   amm = (struct GNUNET_DHT_ActMaliciousMessage *)&pending[1];
1598   pending->msg = &amm->header;
1599   pending->handle = handle;
1600   pending->free_on_send = GNUNET_YES;
1601   amm->header.size = htons (msize);
1602   amm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_ACT_MALICIOUS);
1603   amm->action = action;
1604   handle->mh = mh;
1605   GNUNET_CONTAINER_DLL_insert (handle->pending_head, handle->pending_tail,
1606                                pending);
1607   pending->in_pending_queue = GNUNET_YES;
1608   process_pending_messages (handle);
1609   return mh;
1610 }
1611 #endif
1612
1613
1614 /* end of dht_api.c */