fcfc076d276b5694eead27c4cf7ba580e3e14f4a
[oweals/gnunet.git] / src / datastore / datastore_api.c
1 /*
2      This file is part of GNUnet
3      (C) 2004, 2005, 2006, 2007, 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file datastore/datastore_api.c
23  * @brief Management for the datastore for files stored on a GNUnet node.  Implements
24  *        a priority queue for requests (with timeouts).
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_arm_service.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_datastore_service.h"
31 #include "gnunet_statistics_service.h"
32 #include "datastore.h"
33
34 #define LOG(kind,...) GNUNET_log_from (kind, "datastore-api",__VA_ARGS__)
35
36 /**
37  * Collect an instane number of statistics?  May cause excessive IPC.
38  */
39 #define INSANE_STATISTICS GNUNET_NO
40
41 /**
42  * If a client stopped asking for more results, how many more do
43  * we receive from the DB before killing the connection?  Trade-off
44  * between re-doing TCP handshakes and (needlessly) receiving
45  * useless results.
46  */
47 #define MAX_EXCESS_RESULTS 8
48
49 /**
50  * Context for processing status messages.
51  */
52 struct StatusContext
53 {
54   /**
55    * Continuation to call with the status.
56    */
57   GNUNET_DATASTORE_ContinuationWithStatus cont;
58
59   /**
60    * Closure for cont.
61    */
62   void *cont_cls;
63
64 };
65
66
67 /**
68  * Context for processing result messages.
69  */
70 struct ResultContext
71 {
72   /**
73    * Function to call with the result.
74    */
75   GNUNET_DATASTORE_DatumProcessor proc;
76
77   /**
78    * Closure for proc.
79    */
80   void *proc_cls;
81
82 };
83
84
85 /**
86  *  Context for a queue operation.
87  */
88 union QueueContext
89 {
90
91   struct StatusContext sc;
92
93   struct ResultContext rc;
94
95 };
96
97
98
99 /**
100  * Entry in our priority queue.
101  */
102 struct GNUNET_DATASTORE_QueueEntry
103 {
104
105   /**
106    * This is a linked list.
107    */
108   struct GNUNET_DATASTORE_QueueEntry *next;
109
110   /**
111    * This is a linked list.
112    */
113   struct GNUNET_DATASTORE_QueueEntry *prev;
114
115   /**
116    * Handle to the master context.
117    */
118   struct GNUNET_DATASTORE_Handle *h;
119
120   /**
121    * Response processor (NULL if we are not waiting for a response).
122    * This struct should be used for the closure, function-specific
123    * arguments can be passed via 'qc'.
124    */
125   GNUNET_CLIENT_MessageHandler response_proc;
126
127   /**
128    * Function to call after transmission of the request.
129    */
130   GNUNET_DATASTORE_ContinuationWithStatus cont;
131
132   /**
133    * Closure for 'cont'.
134    */
135   void *cont_cls;
136
137   /**
138    * Context for the operation.
139    */
140   union QueueContext qc;
141
142   /**
143    * Task for timeout signalling.
144    */
145   GNUNET_SCHEDULER_TaskIdentifier task;
146
147   /**
148    * Timeout for the current operation.
149    */
150   struct GNUNET_TIME_Absolute timeout;
151
152   /**
153    * Priority in the queue.
154    */
155   unsigned int priority;
156
157   /**
158    * Maximum allowed length of queue (otherwise
159    * this request should be discarded).
160    */
161   unsigned int max_queue;
162
163   /**
164    * Number of bytes in the request message following
165    * this struct.  32-bit value for nicer memory
166    * access (and overall struct alignment).
167    */
168   uint32_t message_size;
169
170   /**
171    * Has this message been transmitted to the service?
172    * Only ever GNUNET_YES for the head of the queue.
173    * Note that the overall struct should end at a
174    * multiple of 64 bits.
175    */
176   int was_transmitted;
177
178 };
179
180 /**
181  * Handle to the datastore service.
182  */
183 struct GNUNET_DATASTORE_Handle
184 {
185
186   /**
187    * Our configuration.
188    */
189   const struct GNUNET_CONFIGURATION_Handle *cfg;
190
191   /**
192    * Current connection to the datastore service.
193    */
194   struct GNUNET_CLIENT_Connection *client;
195
196   /**
197    * Handle for statistics.
198    */
199   struct GNUNET_STATISTICS_Handle *stats;
200
201   /**
202    * Current transmit handle.
203    */
204   struct GNUNET_CLIENT_TransmitHandle *th;
205
206   /**
207    * Current head of priority queue.
208    */
209   struct GNUNET_DATASTORE_QueueEntry *queue_head;
210
211   /**
212    * Current tail of priority queue.
213    */
214   struct GNUNET_DATASTORE_QueueEntry *queue_tail;
215
216   /**
217    * Task for trying to reconnect.
218    */
219   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
220
221   /**
222    * How quickly should we retry?  Used for exponential back-off on
223    * connect-errors.
224    */
225   struct GNUNET_TIME_Relative retry_time;
226
227   /**
228    * Number of entries in the queue.
229    */
230   unsigned int queue_size;
231
232   /**
233    * Number of results we're receiving for the current query
234    * after application stopped to care.  Used to determine when
235    * to reset the connection.
236    */
237   unsigned int result_count;
238
239   /**
240    * Are we currently trying to receive from the service?
241    */
242   int in_receive;
243
244   /**
245    * We should ignore the next message(s) from the service.
246    */
247   unsigned int skip_next_messages;
248
249 };
250
251
252
253 /**
254  * Connect to the datastore service.
255  *
256  * @param cfg configuration to use
257  * @return handle to use to access the service
258  */
259 struct GNUNET_DATASTORE_Handle *
260 GNUNET_DATASTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
261 {
262   struct GNUNET_CLIENT_Connection *c;
263   struct GNUNET_DATASTORE_Handle *h;
264
265   c = GNUNET_CLIENT_connect ("datastore", cfg);
266   if (c == NULL)
267     return NULL;                /* oops */
268   h = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_Handle) +
269                      GNUNET_SERVER_MAX_MESSAGE_SIZE - 1);
270   h->client = c;
271   h->cfg = cfg;
272   h->stats = GNUNET_STATISTICS_create ("datastore-api", cfg);
273   return h;
274 }
275
276
277 /**
278  * Task used by 'transmit_drop' to disconnect the datastore.
279  *
280  * @param cls the datastore handle
281  * @param tc scheduler context
282  */
283 static void
284 disconnect_after_drop (void *cls,
285                        const struct GNUNET_SCHEDULER_TaskContext *tc)
286 {
287   struct GNUNET_DATASTORE_Handle *h = cls;
288
289   GNUNET_DATASTORE_disconnect (h, GNUNET_NO);
290 }
291
292
293 /**
294  * Transmit DROP message to datastore service.
295  *
296  * @param cls the 'struct GNUNET_DATASTORE_Handle'
297  * @param size number of bytes that can be copied to buf
298  * @param buf where to copy the drop message
299  * @return number of bytes written to buf
300  */
301 static size_t
302 transmit_drop (void *cls, size_t size, void *buf)
303 {
304   struct GNUNET_DATASTORE_Handle *h = cls;
305   struct GNUNET_MessageHeader *hdr;
306
307   if (buf == NULL)
308   {
309     LOG (GNUNET_ERROR_TYPE_WARNING,
310          _("Failed to transmit request to drop database.\n"));
311     GNUNET_SCHEDULER_add_continuation (&disconnect_after_drop, h,
312                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
313     return 0;
314   }
315   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
316   hdr = buf;
317   hdr->size = htons (sizeof (struct GNUNET_MessageHeader));
318   hdr->type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DROP);
319   GNUNET_SCHEDULER_add_continuation (&disconnect_after_drop, h,
320                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
321   return sizeof (struct GNUNET_MessageHeader);
322 }
323
324
325 /**
326  * Disconnect from the datastore service (and free
327  * associated resources).
328  *
329  * @param h handle to the datastore
330  * @param drop set to GNUNET_YES to delete all data in datastore (!)
331  */
332 void
333 GNUNET_DATASTORE_disconnect (struct GNUNET_DATASTORE_Handle *h, int drop)
334 {
335   struct GNUNET_DATASTORE_QueueEntry *qe;
336
337   LOG (GNUNET_ERROR_TYPE_DEBUG, "Datastore disconnect\n");
338   if (NULL != h->th)
339   {
340     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
341     h->th = NULL;
342   }
343   if (h->client != NULL)
344   {
345     GNUNET_CLIENT_disconnect (h->client);
346     h->client = NULL;
347   }
348   if (h->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
349   {
350     GNUNET_SCHEDULER_cancel (h->reconnect_task);
351     h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
352   }
353   while (NULL != (qe = h->queue_head))
354   {
355     GNUNET_assert (NULL != qe->response_proc);
356     qe->response_proc (h, NULL);
357   }
358   if (GNUNET_YES == drop)
359   {
360     h->client = GNUNET_CLIENT_connect ("datastore", h->cfg);
361     if (h->client != NULL)
362     {
363       if (NULL !=
364           GNUNET_CLIENT_notify_transmit_ready (h->client,
365                                                sizeof (struct
366                                                        GNUNET_MessageHeader),
367                                                GNUNET_TIME_UNIT_MINUTES,
368                                                GNUNET_YES, &transmit_drop, h))
369         return;
370       GNUNET_CLIENT_disconnect (h->client);
371       h->client = NULL;
372     }
373     GNUNET_break (0);
374   }
375   GNUNET_STATISTICS_destroy (h->stats, GNUNET_NO);
376   h->stats = NULL;
377   GNUNET_free (h);
378 }
379
380
381 /**
382  * A request has timed out (before being transmitted to the service).
383  *
384  * @param cls the 'struct GNUNET_DATASTORE_QueueEntry'
385  * @param tc scheduler context
386  */
387 static void
388 timeout_queue_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
389 {
390   struct GNUNET_DATASTORE_QueueEntry *qe = cls;
391
392   GNUNET_STATISTICS_update (qe->h->stats,
393                             gettext_noop ("# queue entry timeouts"), 1,
394                             GNUNET_NO);
395   qe->task = GNUNET_SCHEDULER_NO_TASK;
396   GNUNET_assert (qe->was_transmitted == GNUNET_NO);
397   LOG (GNUNET_ERROR_TYPE_DEBUG, "Timeout of request in datastore queue\n");
398   qe->response_proc (qe->h, NULL);
399 }
400
401
402 /**
403  * Create a new entry for our priority queue (and possibly discard other entires if
404  * the queue is getting too long).
405  *
406  * @param h handle to the datastore
407  * @param msize size of the message to queue
408  * @param queue_priority priority of the entry
409  * @param max_queue_size at what queue size should this request be dropped
410  *        (if other requests of higher priority are in the queue)
411  * @param timeout timeout for the operation
412  * @param response_proc function to call with replies (can be NULL)
413  * @param qc client context (NOT a closure for response_proc)
414  * @return NULL if the queue is full
415  */
416 static struct GNUNET_DATASTORE_QueueEntry *
417 make_queue_entry (struct GNUNET_DATASTORE_Handle *h, size_t msize,
418                   unsigned int queue_priority, unsigned int max_queue_size,
419                   struct GNUNET_TIME_Relative timeout,
420                   GNUNET_CLIENT_MessageHandler response_proc,
421                   const union QueueContext *qc)
422 {
423   struct GNUNET_DATASTORE_QueueEntry *ret;
424   struct GNUNET_DATASTORE_QueueEntry *pos;
425   unsigned int c;
426
427   c = 0;
428   pos = h->queue_head;
429   while ((pos != NULL) && (c < max_queue_size) &&
430          (pos->priority >= queue_priority))
431   {
432     c++;
433     pos = pos->next;
434   }
435   if (c >= max_queue_size)
436   {
437     GNUNET_STATISTICS_update (h->stats, gettext_noop ("# queue overflows"), 1,
438                               GNUNET_NO);
439     return NULL;
440   }
441   ret = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_QueueEntry) + msize);
442   ret->h = h;
443   ret->response_proc = response_proc;
444   ret->qc = *qc;
445   ret->timeout = GNUNET_TIME_relative_to_absolute (timeout);
446   ret->priority = queue_priority;
447   ret->max_queue = max_queue_size;
448   ret->message_size = msize;
449   ret->was_transmitted = GNUNET_NO;
450   if (pos == NULL)
451   {
452     /* append at the tail */
453     pos = h->queue_tail;
454   }
455   else
456   {
457     pos = pos->prev;
458     /* do not insert at HEAD if HEAD query was already
459      * transmitted and we are still receiving replies! */
460     if ((pos == NULL) && (h->queue_head->was_transmitted))
461       pos = h->queue_head;
462   }
463   c++;
464 #if INSANE_STATISTICS
465   GNUNET_STATISTICS_update (h->stats, gettext_noop ("# queue entries created"),
466                             1, GNUNET_NO);
467 #endif
468   GNUNET_CONTAINER_DLL_insert_after (h->queue_head, h->queue_tail, pos, ret);
469   h->queue_size++;
470   ret->task = GNUNET_SCHEDULER_add_delayed (timeout, &timeout_queue_entry, ret);
471   for (pos = ret->next; NULL != pos; pos = pos->next)
472   {
473     if ((pos->max_queue < h->queue_size) && (pos->was_transmitted == GNUNET_NO))
474     {
475       GNUNET_assert (pos->response_proc != NULL);
476       /* move 'pos' element to head so that it will be
477        * killed on 'NULL' call below */
478       LOG (GNUNET_ERROR_TYPE_DEBUG, "Dropping request from datastore queue\n");
479       GNUNET_CONTAINER_DLL_remove (h->queue_head, h->queue_tail, pos);
480       GNUNET_CONTAINER_DLL_insert (h->queue_head, h->queue_tail, pos);
481       GNUNET_STATISTICS_update (h->stats,
482                                 gettext_noop
483                                 ("# Requests dropped from datastore queue"), 1,
484                                 GNUNET_NO);
485       GNUNET_assert (h->queue_head == pos);
486       pos->response_proc (h, NULL);
487       break;
488     }
489   }
490   return ret;
491 }
492
493
494 /**
495  * Process entries in the queue (or do nothing if we are already
496  * doing so).
497  *
498  * @param h handle to the datastore
499  */
500 static void
501 process_queue (struct GNUNET_DATASTORE_Handle *h);
502
503
504 /**
505  * Try reconnecting to the datastore service.
506  *
507  * @param cls the 'struct GNUNET_DATASTORE_Handle'
508  * @param tc scheduler context
509  */
510 static void
511 try_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
512 {
513   struct GNUNET_DATASTORE_Handle *h = cls;
514
515   if (h->retry_time.rel_value < GNUNET_CONSTANTS_SERVICE_RETRY.rel_value)
516     h->retry_time = GNUNET_CONSTANTS_SERVICE_RETRY;
517   else
518     h->retry_time = GNUNET_TIME_relative_multiply (h->retry_time, 2);
519   if (h->retry_time.rel_value > GNUNET_CONSTANTS_SERVICE_TIMEOUT.rel_value)
520     h->retry_time = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
521   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
522   h->client = GNUNET_CLIENT_connect ("datastore", h->cfg);
523   if (h->client == NULL)
524   {
525     LOG (GNUNET_ERROR_TYPE_ERROR, "DATASTORE reconnect failed (fatally)\n");
526     return;
527   }
528   GNUNET_STATISTICS_update (h->stats,
529                             gettext_noop
530                             ("# datastore connections (re)created"), 1,
531                             GNUNET_NO);
532   LOG (GNUNET_ERROR_TYPE_DEBUG, "Reconnected to DATASTORE\n");
533   process_queue (h);
534 }
535
536
537 /**
538  * Disconnect from the service and then try reconnecting to the datastore service
539  * after some delay.
540  *
541  * @param h handle to datastore to disconnect and reconnect
542  */
543 static void
544 do_disconnect (struct GNUNET_DATASTORE_Handle *h)
545 {
546   if (h->client == NULL)
547   {
548     LOG (GNUNET_ERROR_TYPE_DEBUG,
549          "client NULL in disconnect, will not try to reconnect\n");
550     return;
551   }
552   GNUNET_CLIENT_disconnect (h->client);
553   h->skip_next_messages = 0;
554   h->client = NULL;
555   h->reconnect_task =
556       GNUNET_SCHEDULER_add_delayed (h->retry_time, &try_reconnect, h);
557 }
558
559
560 /**
561  * Function called whenever we receive a message from
562  * the service.  Calls the appropriate handler.
563  *
564  * @param cls the 'struct GNUNET_DATASTORE_Handle'
565  * @param msg the received message
566  */
567 static void
568 receive_cb (void *cls, const struct GNUNET_MessageHeader *msg)
569 {
570   struct GNUNET_DATASTORE_Handle *h = cls;
571   struct GNUNET_DATASTORE_QueueEntry *qe;
572
573   h->in_receive = GNUNET_NO;
574   LOG (GNUNET_ERROR_TYPE_DEBUG, "Receiving reply from datastore\n");
575   if (h->skip_next_messages > 0)
576   {
577     h->skip_next_messages--;
578     process_queue (h);
579     return;
580   }
581   if (NULL == (qe = h->queue_head))
582   {
583     GNUNET_break (0);
584     process_queue (h);
585     return;
586   }
587   qe->response_proc (h, msg);
588 }
589
590
591 /**
592  * Transmit request from queue to datastore service.
593  *
594  * @param cls the 'struct GNUNET_DATASTORE_Handle'
595  * @param size number of bytes that can be copied to buf
596  * @param buf where to copy the drop message
597  * @return number of bytes written to buf
598  */
599 static size_t
600 transmit_request (void *cls, size_t size, void *buf)
601 {
602   struct GNUNET_DATASTORE_Handle *h = cls;
603   struct GNUNET_DATASTORE_QueueEntry *qe;
604   size_t msize;
605
606   h->th = NULL;
607   if (NULL == (qe = h->queue_head))
608     return 0;                   /* no entry in queue */
609   if (buf == NULL)
610   {
611     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to transmit request to DATASTORE.\n");
612     GNUNET_STATISTICS_update (h->stats,
613                               gettext_noop ("# transmission request failures"),
614                               1, GNUNET_NO);
615     do_disconnect (h);
616     return 0;
617   }
618   if (size < (msize = qe->message_size))
619   {
620     process_queue (h);
621     return 0;
622   }
623   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u byte request to DATASTORE\n",
624        msize);
625   memcpy (buf, &qe[1], msize);
626   qe->was_transmitted = GNUNET_YES;
627   GNUNET_SCHEDULER_cancel (qe->task);
628   qe->task = GNUNET_SCHEDULER_NO_TASK;
629   GNUNET_assert (GNUNET_NO == h->in_receive);
630   h->in_receive = GNUNET_YES;
631   GNUNET_CLIENT_receive (h->client, &receive_cb, h,
632                          GNUNET_TIME_absolute_get_remaining (qe->timeout));
633 #if INSANE_STATISTICS
634   GNUNET_STATISTICS_update (h->stats,
635                             gettext_noop ("# bytes sent to datastore"), 1,
636                             GNUNET_NO);
637 #endif
638   return msize;
639 }
640
641
642 /**
643  * Process entries in the queue (or do nothing if we are already
644  * doing so).
645  *
646  * @param h handle to the datastore
647  */
648 static void
649 process_queue (struct GNUNET_DATASTORE_Handle *h)
650 {
651   struct GNUNET_DATASTORE_QueueEntry *qe;
652
653   if (NULL == (qe = h->queue_head))
654   {
655     LOG (GNUNET_ERROR_TYPE_DEBUG, "Queue empty\n");
656     return;                     /* no entry in queue */
657   }
658   if (qe->was_transmitted == GNUNET_YES)
659   {
660     LOG (GNUNET_ERROR_TYPE_DEBUG, "Head request already transmitted\n");
661     return;                     /* waiting for replies */
662   }
663   if (h->th != NULL)
664   {
665     LOG (GNUNET_ERROR_TYPE_DEBUG, "Pending transmission request\n");
666     return;                     /* request pending */
667   }
668   if (h->client == NULL)
669   {
670     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not connected\n");
671     return;                     /* waiting for reconnect */
672   }
673   if (GNUNET_YES == h->in_receive)
674   {
675     /* wait for response to previous query */
676     return;
677   }
678   LOG (GNUNET_ERROR_TYPE_DEBUG, "Queueing %u byte request to DATASTORE\n",
679        qe->message_size);
680   h->th =
681       GNUNET_CLIENT_notify_transmit_ready (h->client, qe->message_size,
682                                            GNUNET_TIME_absolute_get_remaining
683                                            (qe->timeout), GNUNET_YES,
684                                            &transmit_request, h);
685   GNUNET_assert (GNUNET_NO == h->in_receive);
686   GNUNET_break (NULL != h->th);
687 }
688
689
690 /**
691  * Dummy continuation used to do nothing (but be non-zero).
692  *
693  * @param cls closure
694  * @param result result
695  * @param min_expiration expiration time
696  * @param emsg error message
697  */
698 static void
699 drop_status_cont (void *cls, int32_t result, 
700                   struct GNUNET_TIME_Absolute min_expiration,
701                   const char *emsg)
702 {
703   /* do nothing */
704 }
705
706
707 /**
708  * Free a queue entry.  Removes the given entry from the
709  * queue and releases associated resources.  Does NOT
710  * call the callback.
711  *
712  * @param qe entry to free.
713  */
714 static void
715 free_queue_entry (struct GNUNET_DATASTORE_QueueEntry *qe)
716 {
717   struct GNUNET_DATASTORE_Handle *h = qe->h;
718
719   GNUNET_CONTAINER_DLL_remove (h->queue_head, h->queue_tail, qe);
720   if (qe->task != GNUNET_SCHEDULER_NO_TASK)
721   {
722     GNUNET_SCHEDULER_cancel (qe->task);
723     qe->task = GNUNET_SCHEDULER_NO_TASK;
724   }
725   h->queue_size--;
726   qe->was_transmitted = GNUNET_SYSERR;  /* use-after-free warning */
727   GNUNET_free (qe);
728 }
729
730
731 /**
732  * Type of a function to call when we receive a message
733  * from the service.
734  *
735  * @param cls closure
736  * @param msg message received, NULL on timeout or fatal error
737  */
738 static void
739 process_status_message (void *cls, const struct GNUNET_MessageHeader *msg)
740 {
741   struct GNUNET_DATASTORE_Handle *h = cls;
742   struct GNUNET_DATASTORE_QueueEntry *qe;
743   struct StatusContext rc;
744   const struct StatusMessage *sm;
745   const char *emsg;
746   int32_t status;
747   int was_transmitted;
748
749   if (NULL == (qe = h->queue_head))
750   {
751     GNUNET_break (0);
752     do_disconnect (h);
753     return;
754   }
755   rc = qe->qc.sc;
756   if (msg == NULL)
757   {
758     was_transmitted = qe->was_transmitted;
759     free_queue_entry (qe);
760     if (was_transmitted == GNUNET_YES)
761       do_disconnect (h);
762     else
763       process_queue (h);
764     if (rc.cont != NULL)
765       rc.cont (rc.cont_cls, GNUNET_SYSERR,
766                GNUNET_TIME_UNIT_ZERO_ABS,
767                _("Failed to receive status response from database."));
768     return;
769   }
770   GNUNET_assert (GNUNET_YES == qe->was_transmitted);
771   free_queue_entry (qe);
772   if ((ntohs (msg->size) < sizeof (struct StatusMessage)) ||
773       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DATASTORE_STATUS))
774   {
775     GNUNET_break (0);
776     h->retry_time = GNUNET_TIME_UNIT_ZERO;
777     do_disconnect (h);
778     if (rc.cont != NULL)
779       rc.cont (rc.cont_cls, GNUNET_SYSERR,
780                GNUNET_TIME_UNIT_ZERO_ABS,
781                _("Error reading response from datastore service"));
782     return;
783   }
784   sm = (const struct StatusMessage *) msg;
785   status = ntohl (sm->status);
786   emsg = NULL;
787   if (ntohs (msg->size) > sizeof (struct StatusMessage))
788   {
789     emsg = (const char *) &sm[1];
790     if (emsg[ntohs (msg->size) - sizeof (struct StatusMessage) - 1] != '\0')
791     {
792       GNUNET_break (0);
793       emsg = _("Invalid error message received from datastore service");
794     }
795   }
796   if ((status == GNUNET_SYSERR) && (emsg == NULL))
797   {
798     GNUNET_break (0);
799     emsg = _("Invalid error message received from datastore service");
800   }
801   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received status %d/%s\n", (int) status, emsg);
802   GNUNET_STATISTICS_update (h->stats,
803                             gettext_noop ("# status messages received"), 1,
804                             GNUNET_NO);
805   h->retry_time.rel_value = 0;
806   process_queue (h);
807   if (rc.cont != NULL)
808     rc.cont (rc.cont_cls, status, 
809              GNUNET_TIME_absolute_ntoh (sm->min_expiration),
810              emsg);
811 }
812
813
814 /**
815  * Store an item in the datastore.  If the item is already present,
816  * the priorities are summed up and the higher expiration time and
817  * lower anonymity level is used.
818  *
819  * @param h handle to the datastore
820  * @param rid reservation ID to use (from "reserve"); use 0 if no
821  *            prior reservation was made
822  * @param key key for the value
823  * @param size number of bytes in data
824  * @param data content stored
825  * @param type type of the content
826  * @param priority priority of the content
827  * @param anonymity anonymity-level for the content
828  * @param replication how often should the content be replicated to other peers?
829  * @param expiration expiration time for the content
830  * @param queue_priority ranking of this request in the priority queue
831  * @param max_queue_size at what queue size should this request be dropped
832  *        (if other requests of higher priority are in the queue)
833  * @param timeout timeout for the operation
834  * @param cont continuation to call when done
835  * @param cont_cls closure for cont
836  * @return NULL if the entry was not queued, otherwise a handle that can be used to
837  *         cancel; note that even if NULL is returned, the callback will be invoked
838  *         (or rather, will already have been invoked)
839  */
840 struct GNUNET_DATASTORE_QueueEntry *
841 GNUNET_DATASTORE_put (struct GNUNET_DATASTORE_Handle *h, uint32_t rid,
842                       const struct GNUNET_HashCode * key, size_t size,
843                       const void *data, enum GNUNET_BLOCK_Type type,
844                       uint32_t priority, uint32_t anonymity,
845                       uint32_t replication,
846                       struct GNUNET_TIME_Absolute expiration,
847                       unsigned int queue_priority, unsigned int max_queue_size,
848                       struct GNUNET_TIME_Relative timeout,
849                       GNUNET_DATASTORE_ContinuationWithStatus cont,
850                       void *cont_cls)
851 {
852   struct GNUNET_DATASTORE_QueueEntry *qe;
853   struct DataMessage *dm;
854   size_t msize;
855   union QueueContext qc;
856
857   LOG (GNUNET_ERROR_TYPE_DEBUG,
858        "Asked to put %u bytes of data under key `%s' for %llu ms\n", size,
859        GNUNET_h2s (key),
860        GNUNET_TIME_absolute_get_remaining (expiration).rel_value);
861   msize = sizeof (struct DataMessage) + size;
862   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
863   qc.sc.cont = cont;
864   qc.sc.cont_cls = cont_cls;
865   qe = make_queue_entry (h, msize, queue_priority, max_queue_size, timeout,
866                          &process_status_message, &qc);
867   if (qe == NULL)
868   {
869     LOG (GNUNET_ERROR_TYPE_DEBUG, "Could not create queue entry for PUT\n");
870     return NULL;
871   }
872   GNUNET_STATISTICS_update (h->stats, gettext_noop ("# PUT requests executed"),
873                             1, GNUNET_NO);
874   dm = (struct DataMessage *) &qe[1];
875   dm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_PUT);
876   dm->header.size = htons (msize);
877   dm->rid = htonl (rid);
878   dm->size = htonl ((uint32_t) size);
879   dm->type = htonl (type);
880   dm->priority = htonl (priority);
881   dm->anonymity = htonl (anonymity);
882   dm->replication = htonl (replication);
883   dm->reserved = htonl (0);
884   dm->uid = GNUNET_htonll (0);
885   dm->expiration = GNUNET_TIME_absolute_hton (expiration);
886   dm->key = *key;
887   memcpy (&dm[1], data, size);
888   process_queue (h);
889   return qe;
890 }
891
892
893 /**
894  * Reserve space in the datastore.  This function should be used
895  * to avoid "out of space" failures during a longer sequence of "put"
896  * operations (for example, when a file is being inserted).
897  *
898  * @param h handle to the datastore
899  * @param amount how much space (in bytes) should be reserved (for content only)
900  * @param entries how many entries will be created (to calculate per-entry overhead)
901  * @param queue_priority ranking of this request in the priority queue
902  * @param max_queue_size at what queue size should this request be dropped
903  *        (if other requests of higher priority are in the queue)
904  * @param timeout how long to wait at most for a response (or before dying in queue)
905  * @param cont continuation to call when done; "success" will be set to
906  *             a positive reservation value if space could be reserved.
907  * @param cont_cls closure for cont
908  * @return NULL if the entry was not queued, otherwise a handle that can be used to
909  *         cancel; note that even if NULL is returned, the callback will be invoked
910  *         (or rather, will already have been invoked)
911  */
912 struct GNUNET_DATASTORE_QueueEntry *
913 GNUNET_DATASTORE_reserve (struct GNUNET_DATASTORE_Handle *h, uint64_t amount,
914                           uint32_t entries, unsigned int queue_priority,
915                           unsigned int max_queue_size,
916                           struct GNUNET_TIME_Relative timeout,
917                           GNUNET_DATASTORE_ContinuationWithStatus cont,
918                           void *cont_cls)
919 {
920   struct GNUNET_DATASTORE_QueueEntry *qe;
921   struct ReserveMessage *rm;
922   union QueueContext qc;
923
924   if (cont == NULL)
925     cont = &drop_status_cont;
926   LOG (GNUNET_ERROR_TYPE_DEBUG,
927        "Asked to reserve %llu bytes of data and %u entries\n",
928        (unsigned long long) amount, (unsigned int) entries);
929   qc.sc.cont = cont;
930   qc.sc.cont_cls = cont_cls;
931   qe = make_queue_entry (h, sizeof (struct ReserveMessage), queue_priority,
932                          max_queue_size, timeout, &process_status_message, &qc);
933   if (qe == NULL)
934   {
935     LOG (GNUNET_ERROR_TYPE_DEBUG, "Could not create queue entry to reserve\n");
936     return NULL;
937   }
938   GNUNET_STATISTICS_update (h->stats,
939                             gettext_noop ("# RESERVE requests executed"), 1,
940                             GNUNET_NO);
941   rm = (struct ReserveMessage *) &qe[1];
942   rm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE);
943   rm->header.size = htons (sizeof (struct ReserveMessage));
944   rm->entries = htonl (entries);
945   rm->amount = GNUNET_htonll (amount);
946   process_queue (h);
947   return qe;
948 }
949
950
951 /**
952  * Signal that all of the data for which a reservation was made has
953  * been stored and that whatever excess space might have been reserved
954  * can now be released.
955  *
956  * @param h handle to the datastore
957  * @param rid reservation ID (value of "success" in original continuation
958  *        from the "reserve" function).
959  * @param queue_priority ranking of this request in the priority queue
960  * @param max_queue_size at what queue size should this request be dropped
961  *        (if other requests of higher priority are in the queue)
962  * @param queue_priority ranking of this request in the priority queue
963  * @param max_queue_size at what queue size should this request be dropped
964  *        (if other requests of higher priority are in the queue)
965  * @param timeout how long to wait at most for a response
966  * @param cont continuation to call when done
967  * @param cont_cls closure for cont
968  * @return NULL if the entry was not queued, otherwise a handle that can be used to
969  *         cancel; note that even if NULL is returned, the callback will be invoked
970  *         (or rather, will already have been invoked)
971  */
972 struct GNUNET_DATASTORE_QueueEntry *
973 GNUNET_DATASTORE_release_reserve (struct GNUNET_DATASTORE_Handle *h,
974                                   uint32_t rid, unsigned int queue_priority,
975                                   unsigned int max_queue_size,
976                                   struct GNUNET_TIME_Relative timeout,
977                                   GNUNET_DATASTORE_ContinuationWithStatus cont,
978                                   void *cont_cls)
979 {
980   struct GNUNET_DATASTORE_QueueEntry *qe;
981   struct ReleaseReserveMessage *rrm;
982   union QueueContext qc;
983
984   if (cont == NULL)
985     cont = &drop_status_cont;
986   LOG (GNUNET_ERROR_TYPE_DEBUG, "Asked to release reserve %d\n", rid);
987   qc.sc.cont = cont;
988   qc.sc.cont_cls = cont_cls;
989   qe = make_queue_entry (h, sizeof (struct ReleaseReserveMessage),
990                          queue_priority, max_queue_size, timeout,
991                          &process_status_message, &qc);
992   if (qe == NULL)
993   {
994     LOG (GNUNET_ERROR_TYPE_DEBUG,
995          "Could not create queue entry to release reserve\n");
996     return NULL;
997   }
998   GNUNET_STATISTICS_update (h->stats,
999                             gettext_noop
1000                             ("# RELEASE RESERVE requests executed"), 1,
1001                             GNUNET_NO);
1002   rrm = (struct ReleaseReserveMessage *) &qe[1];
1003   rrm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE);
1004   rrm->header.size = htons (sizeof (struct ReleaseReserveMessage));
1005   rrm->rid = htonl (rid);
1006   process_queue (h);
1007   return qe;
1008 }
1009
1010
1011 /**
1012  * Update a value in the datastore.
1013  *
1014  * @param h handle to the datastore
1015  * @param uid identifier for the value
1016  * @param priority how much to increase the priority of the value
1017  * @param expiration new expiration value should be MAX of existing and this argument
1018  * @param queue_priority ranking of this request in the priority queue
1019  * @param max_queue_size at what queue size should this request be dropped
1020  *        (if other requests of higher priority are in the queue)
1021  * @param timeout how long to wait at most for a response
1022  * @param cont continuation to call when done
1023  * @param cont_cls closure for cont
1024  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1025  *         cancel; note that even if NULL is returned, the callback will be invoked
1026  *         (or rather, will already have been invoked)
1027  */
1028 struct GNUNET_DATASTORE_QueueEntry *
1029 GNUNET_DATASTORE_update (struct GNUNET_DATASTORE_Handle *h, uint64_t uid,
1030                          uint32_t priority,
1031                          struct GNUNET_TIME_Absolute expiration,
1032                          unsigned int queue_priority,
1033                          unsigned int max_queue_size,
1034                          struct GNUNET_TIME_Relative timeout,
1035                          GNUNET_DATASTORE_ContinuationWithStatus cont,
1036                          void *cont_cls)
1037 {
1038   struct GNUNET_DATASTORE_QueueEntry *qe;
1039   struct UpdateMessage *um;
1040   union QueueContext qc;
1041
1042   if (cont == NULL)
1043     cont = &drop_status_cont;
1044   LOG (GNUNET_ERROR_TYPE_DEBUG,
1045        "Asked to update entry %llu raising priority by %u and expiration to %llu\n",
1046        uid, (unsigned int) priority, (unsigned long long) expiration.abs_value);
1047   qc.sc.cont = cont;
1048   qc.sc.cont_cls = cont_cls;
1049   qe = make_queue_entry (h, sizeof (struct UpdateMessage), queue_priority,
1050                          max_queue_size, timeout, &process_status_message, &qc);
1051   if (qe == NULL)
1052   {
1053     LOG (GNUNET_ERROR_TYPE_DEBUG, "Could not create queue entry for UPDATE\n");
1054     return NULL;
1055   }
1056   GNUNET_STATISTICS_update (h->stats,
1057                             gettext_noop ("# UPDATE requests executed"), 1,
1058                             GNUNET_NO);
1059   um = (struct UpdateMessage *) &qe[1];
1060   um->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE);
1061   um->header.size = htons (sizeof (struct UpdateMessage));
1062   um->priority = htonl (priority);
1063   um->expiration = GNUNET_TIME_absolute_hton (expiration);
1064   um->uid = GNUNET_htonll (uid);
1065   process_queue (h);
1066   return qe;
1067 }
1068
1069
1070 /**
1071  * Explicitly remove some content from the database.
1072  * The "cont"inuation will be called with status
1073  * "GNUNET_OK" if content was removed, "GNUNET_NO"
1074  * if no matching entry was found and "GNUNET_SYSERR"
1075  * on all other types of errors.
1076  *
1077  * @param h handle to the datastore
1078  * @param key key for the value
1079  * @param size number of bytes in data
1080  * @param data content stored
1081  * @param queue_priority ranking of this request in the priority queue
1082  * @param max_queue_size at what queue size should this request be dropped
1083  *        (if other requests of higher priority are in the queue)
1084  * @param timeout how long to wait at most for a response
1085  * @param cont continuation to call when done
1086  * @param cont_cls closure for cont
1087  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1088  *         cancel; note that even if NULL is returned, the callback will be invoked
1089  *         (or rather, will already have been invoked)
1090  */
1091 struct GNUNET_DATASTORE_QueueEntry *
1092 GNUNET_DATASTORE_remove (struct GNUNET_DATASTORE_Handle *h,
1093                          const struct GNUNET_HashCode * key, size_t size,
1094                          const void *data, unsigned int queue_priority,
1095                          unsigned int max_queue_size,
1096                          struct GNUNET_TIME_Relative timeout,
1097                          GNUNET_DATASTORE_ContinuationWithStatus cont,
1098                          void *cont_cls)
1099 {
1100   struct GNUNET_DATASTORE_QueueEntry *qe;
1101   struct DataMessage *dm;
1102   size_t msize;
1103   union QueueContext qc;
1104
1105   if (cont == NULL)
1106     cont = &drop_status_cont;
1107   LOG (GNUNET_ERROR_TYPE_DEBUG, "Asked to remove %u bytes under key `%s'\n",
1108        size, GNUNET_h2s (key));
1109   qc.sc.cont = cont;
1110   qc.sc.cont_cls = cont_cls;
1111   msize = sizeof (struct DataMessage) + size;
1112   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1113   qe = make_queue_entry (h, msize, queue_priority, max_queue_size, timeout,
1114                          &process_status_message, &qc);
1115   if (qe == NULL)
1116   {
1117     LOG (GNUNET_ERROR_TYPE_DEBUG, "Could not create queue entry for REMOVE\n");
1118     return NULL;
1119   }
1120   GNUNET_STATISTICS_update (h->stats,
1121                             gettext_noop ("# REMOVE requests executed"), 1,
1122                             GNUNET_NO);
1123   dm = (struct DataMessage *) &qe[1];
1124   dm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE);
1125   dm->header.size = htons (msize);
1126   dm->rid = htonl (0);
1127   dm->size = htonl (size);
1128   dm->type = htonl (0);
1129   dm->priority = htonl (0);
1130   dm->anonymity = htonl (0);
1131   dm->uid = GNUNET_htonll (0);
1132   dm->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_ZERO_ABS);
1133   dm->key = *key;
1134   memcpy (&dm[1], data, size);
1135   process_queue (h);
1136   return qe;
1137 }
1138
1139
1140 /**
1141  * Type of a function to call when we receive a message
1142  * from the service.
1143  *
1144  * @param cls closure
1145  * @param msg message received, NULL on timeout or fatal error
1146  */
1147 static void
1148 process_result_message (void *cls, const struct GNUNET_MessageHeader *msg)
1149 {
1150   struct GNUNET_DATASTORE_Handle *h = cls;
1151   struct GNUNET_DATASTORE_QueueEntry *qe;
1152   struct ResultContext rc;
1153   const struct DataMessage *dm;
1154   int was_transmitted;
1155
1156   if (msg == NULL)
1157   {
1158     qe = h->queue_head;
1159     GNUNET_assert (NULL != qe);
1160     rc = qe->qc.rc;
1161     was_transmitted = qe->was_transmitted;
1162     free_queue_entry (qe);
1163     if (was_transmitted == GNUNET_YES)
1164     {
1165       LOG (GNUNET_ERROR_TYPE_WARNING,
1166            _("Failed to receive response from database.\n"));
1167       do_disconnect (h);
1168     }
1169     else
1170     {
1171       process_queue (h);
1172     }
1173     if (rc.proc != NULL)
1174       rc.proc (rc.proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1175                0);
1176     return;
1177   }
1178   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END)
1179   {
1180     GNUNET_break (ntohs (msg->size) == sizeof (struct GNUNET_MessageHeader));
1181     qe = h->queue_head;
1182     rc = qe->qc.rc;
1183     GNUNET_assert (GNUNET_YES == qe->was_transmitted);
1184     free_queue_entry (qe);
1185     LOG (GNUNET_ERROR_TYPE_DEBUG,
1186          "Received end of result set, new queue size is %u\n", h->queue_size);
1187     h->retry_time.rel_value = 0;
1188     h->result_count = 0;
1189     process_queue (h);
1190     if (rc.proc != NULL)
1191       rc.proc (rc.proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1192                0);
1193     return;
1194   }
1195   qe = h->queue_head;
1196   GNUNET_assert (NULL != qe);
1197   rc = qe->qc.rc;
1198   if (GNUNET_YES != qe->was_transmitted)
1199   {
1200     GNUNET_break (0);
1201     free_queue_entry (qe);
1202     h->retry_time = GNUNET_TIME_UNIT_ZERO;
1203     do_disconnect (h);
1204     if (rc.proc != NULL)
1205       rc.proc (rc.proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1206                0);
1207     return;
1208   }
1209   if ((ntohs (msg->size) < sizeof (struct DataMessage)) ||
1210       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DATASTORE_DATA) ||
1211       (ntohs (msg->size) !=
1212        sizeof (struct DataMessage) +
1213        ntohl (((const struct DataMessage *) msg)->size)))
1214   {
1215     GNUNET_break (0);
1216     free_queue_entry (qe);
1217     h->retry_time = GNUNET_TIME_UNIT_ZERO;
1218     do_disconnect (h);
1219     if (rc.proc != NULL)
1220       rc.proc (rc.proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1221                0);
1222     return;
1223   }
1224 #if INSANE_STATISTICS
1225   GNUNET_STATISTICS_update (h->stats, gettext_noop ("# Results received"), 1,
1226                             GNUNET_NO);
1227 #endif
1228   dm = (const struct DataMessage *) msg;
1229   LOG (GNUNET_ERROR_TYPE_DEBUG,
1230        "Received result %llu with type %u and size %u with key %s\n",
1231        (unsigned long long) GNUNET_ntohll (dm->uid), ntohl (dm->type),
1232        ntohl (dm->size), GNUNET_h2s (&dm->key));
1233   free_queue_entry (qe);
1234   h->retry_time.rel_value = 0;
1235   process_queue (h);
1236   if (rc.proc != NULL)
1237     rc.proc (rc.proc_cls, &dm->key, ntohl (dm->size), &dm[1], ntohl (dm->type),
1238              ntohl (dm->priority), ntohl (dm->anonymity),
1239              GNUNET_TIME_absolute_ntoh (dm->expiration),
1240              GNUNET_ntohll (dm->uid));
1241 }
1242
1243
1244 /**
1245  * Get a random value from the datastore for content replication.
1246  * Returns a single, random value among those with the highest
1247  * replication score, lowering positive replication scores by one for
1248  * the chosen value (if only content with a replication score exists,
1249  * a random value is returned and replication scores are not changed).
1250  *
1251  * @param h handle to the datastore
1252  * @param queue_priority ranking of this request in the priority queue
1253  * @param max_queue_size at what queue size should this request be dropped
1254  *        (if other requests of higher priority are in the queue)
1255  * @param timeout how long to wait at most for a response
1256  * @param proc function to call on a random value; it
1257  *        will be called once with a value (if available)
1258  *        and always once with a value of NULL.
1259  * @param proc_cls closure for proc
1260  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1261  *         cancel
1262  */
1263 struct GNUNET_DATASTORE_QueueEntry *
1264 GNUNET_DATASTORE_get_for_replication (struct GNUNET_DATASTORE_Handle *h,
1265                                       unsigned int queue_priority,
1266                                       unsigned int max_queue_size,
1267                                       struct GNUNET_TIME_Relative timeout,
1268                                       GNUNET_DATASTORE_DatumProcessor proc,
1269                                       void *proc_cls)
1270 {
1271   struct GNUNET_DATASTORE_QueueEntry *qe;
1272   struct GNUNET_MessageHeader *m;
1273   union QueueContext qc;
1274
1275   GNUNET_assert (NULL != proc);
1276   LOG (GNUNET_ERROR_TYPE_DEBUG, "Asked to get replication entry in %llu ms\n",
1277        (unsigned long long) timeout.rel_value);
1278   qc.rc.proc = proc;
1279   qc.rc.proc_cls = proc_cls;
1280   qe = make_queue_entry (h, sizeof (struct GNUNET_MessageHeader),
1281                          queue_priority, max_queue_size, timeout,
1282                          &process_result_message, &qc);
1283   if (qe == NULL)
1284   {
1285     LOG (GNUNET_ERROR_TYPE_DEBUG,
1286          "Could not create queue entry for GET REPLICATION\n");
1287     return NULL;
1288   }
1289   GNUNET_STATISTICS_update (h->stats,
1290                             gettext_noop
1291                             ("# GET REPLICATION requests executed"), 1,
1292                             GNUNET_NO);
1293   m = (struct GNUNET_MessageHeader *) &qe[1];
1294   m->type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION);
1295   m->size = htons (sizeof (struct GNUNET_MessageHeader));
1296   process_queue (h);
1297   return qe;
1298 }
1299
1300
1301 /**
1302  * Get a single zero-anonymity value from the datastore.
1303  *
1304  * @param h handle to the datastore
1305  * @param offset offset of the result (modulo num-results); set to
1306  *               a random 64-bit value initially; then increment by
1307  *               one each time; detect that all results have been found by uid
1308  *               being again the first uid ever returned.
1309  * @param queue_priority ranking of this request in the priority queue
1310  * @param max_queue_size at what queue size should this request be dropped
1311  *        (if other requests of higher priority are in the queue)
1312  * @param timeout how long to wait at most for a response
1313  * @param type allowed type for the operation (never zero)
1314  * @param proc function to call on a random value; it
1315  *        will be called once with a value (if available)
1316  *        or with NULL if none value exists.
1317  * @param proc_cls closure for proc
1318  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1319  *         cancel
1320  */
1321 struct GNUNET_DATASTORE_QueueEntry *
1322 GNUNET_DATASTORE_get_zero_anonymity (struct GNUNET_DATASTORE_Handle *h,
1323                                      uint64_t offset,
1324                                      unsigned int queue_priority,
1325                                      unsigned int max_queue_size,
1326                                      struct GNUNET_TIME_Relative timeout,
1327                                      enum GNUNET_BLOCK_Type type,
1328                                      GNUNET_DATASTORE_DatumProcessor proc,
1329                                      void *proc_cls)
1330 {
1331   struct GNUNET_DATASTORE_QueueEntry *qe;
1332   struct GetZeroAnonymityMessage *m;
1333   union QueueContext qc;
1334
1335   GNUNET_assert (NULL != proc);
1336   GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
1337   LOG (GNUNET_ERROR_TYPE_DEBUG,
1338        "Asked to get %llu-th zero-anonymity entry of type %d in %llu ms\n",
1339        (unsigned long long) offset, type,
1340        (unsigned long long) timeout.rel_value);
1341   qc.rc.proc = proc;
1342   qc.rc.proc_cls = proc_cls;
1343   qe = make_queue_entry (h, sizeof (struct GetZeroAnonymityMessage),
1344                          queue_priority, max_queue_size, timeout,
1345                          &process_result_message, &qc);
1346   if (qe == NULL)
1347   {
1348     LOG (GNUNET_ERROR_TYPE_DEBUG,
1349          "Could not create queue entry for zero-anonymity procation\n");
1350     return NULL;
1351   }
1352   GNUNET_STATISTICS_update (h->stats,
1353                             gettext_noop
1354                             ("# GET ZERO ANONYMITY requests executed"), 1,
1355                             GNUNET_NO);
1356   m = (struct GetZeroAnonymityMessage *) &qe[1];
1357   m->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY);
1358   m->header.size = htons (sizeof (struct GetZeroAnonymityMessage));
1359   m->type = htonl ((uint32_t) type);
1360   m->offset = GNUNET_htonll (offset);
1361   process_queue (h);
1362   return qe;
1363 }
1364
1365
1366 /**
1367  * Get a result for a particular key from the datastore.  The processor
1368  * will only be called once.
1369  *
1370  * @param h handle to the datastore
1371  * @param offset offset of the result (modulo num-results); set to
1372  *               a random 64-bit value initially; then increment by
1373  *               one each time; detect that all results have been found by uid
1374  *               being again the first uid ever returned.
1375  * @param key maybe NULL (to match all entries)
1376  * @param type desired type, 0 for any
1377  * @param queue_priority ranking of this request in the priority queue
1378  * @param max_queue_size at what queue size should this request be dropped
1379  *        (if other requests of higher priority are in the queue)
1380  * @param timeout how long to wait at most for a response
1381  * @param proc function to call on each matching value;
1382  *        will be called once with a NULL value at the end
1383  * @param proc_cls closure for proc
1384  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1385  *         cancel
1386  */
1387 struct GNUNET_DATASTORE_QueueEntry *
1388 GNUNET_DATASTORE_get_key (struct GNUNET_DATASTORE_Handle *h, uint64_t offset,
1389                           const struct GNUNET_HashCode * key,
1390                           enum GNUNET_BLOCK_Type type,
1391                           unsigned int queue_priority,
1392                           unsigned int max_queue_size,
1393                           struct GNUNET_TIME_Relative timeout,
1394                           GNUNET_DATASTORE_DatumProcessor proc, void *proc_cls)
1395 {
1396   struct GNUNET_DATASTORE_QueueEntry *qe;
1397   struct GetMessage *gm;
1398   union QueueContext qc;
1399
1400   GNUNET_assert (NULL != proc);
1401   LOG (GNUNET_ERROR_TYPE_DEBUG,
1402        "Asked to look for data of type %u under key `%s'\n",
1403        (unsigned int) type, GNUNET_h2s (key));
1404   qc.rc.proc = proc;
1405   qc.rc.proc_cls = proc_cls;
1406   qe = make_queue_entry (h, sizeof (struct GetMessage), queue_priority,
1407                          max_queue_size, timeout, &process_result_message, &qc);
1408   if (qe == NULL)
1409   {
1410     LOG (GNUNET_ERROR_TYPE_DEBUG, "Could not queue request for `%s'\n",
1411          GNUNET_h2s (key));
1412     return NULL;
1413   }
1414 #if INSANE_STATISTICS
1415   GNUNET_STATISTICS_update (h->stats, gettext_noop ("# GET requests executed"),
1416                             1, GNUNET_NO);
1417 #endif
1418   gm = (struct GetMessage *) &qe[1];
1419   gm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_GET);
1420   gm->type = htonl (type);
1421   gm->offset = GNUNET_htonll (offset);
1422   if (key != NULL)
1423   {
1424     gm->header.size = htons (sizeof (struct GetMessage));
1425     gm->key = *key;
1426   }
1427   else
1428   {
1429     gm->header.size =
1430         htons (sizeof (struct GetMessage) - sizeof (struct GNUNET_HashCode));
1431   }
1432   process_queue (h);
1433   return qe;
1434 }
1435
1436
1437 /**
1438  * Cancel a datastore operation.  The final callback from the
1439  * operation must not have been done yet.
1440  *
1441  * @param qe operation to cancel
1442  */
1443 void
1444 GNUNET_DATASTORE_cancel (struct GNUNET_DATASTORE_QueueEntry *qe)
1445 {
1446   struct GNUNET_DATASTORE_Handle *h;
1447
1448   GNUNET_assert (GNUNET_SYSERR != qe->was_transmitted);
1449   h = qe->h;
1450   LOG (GNUNET_ERROR_TYPE_DEBUG,
1451        "Pending DATASTORE request %p cancelled (%d, %d)\n", qe,
1452        qe->was_transmitted, h->queue_head == qe);
1453   if (GNUNET_YES == qe->was_transmitted)
1454   {
1455     free_queue_entry (qe);
1456     h->skip_next_messages++;
1457     return;
1458   }
1459   free_queue_entry (qe);
1460   process_queue (h);
1461 }
1462
1463
1464 /* end of datastore_api.c */