add nick name for cached records
[oweals/gnunet.git] / src / datastore / datastore_api.c
1 /*
2      This file is part of GNUnet
3      (C) 2004-2013 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 @a buf
298  * @param buf where to copy the drop message
299  * @return number of bytes written to @a 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   struct GNUNET_DATASTORE_Handle *h = qe->h;
392
393   GNUNET_STATISTICS_update (h->stats,
394                             gettext_noop ("# queue entry timeouts"), 1,
395                             GNUNET_NO);
396   qe->task = GNUNET_SCHEDULER_NO_TASK;
397   GNUNET_assert (GNUNET_NO == qe->was_transmitted);
398   LOG (GNUNET_ERROR_TYPE_DEBUG,
399        "Timeout of request in datastore queue\n");
400   /* response_proc's expect request at the head of the queue! */
401   GNUNET_CONTAINER_DLL_remove (h->queue_head, h->queue_tail, qe);
402   GNUNET_CONTAINER_DLL_insert (h->queue_head, h->queue_tail, qe);
403   GNUNET_assert (h->queue_head == qe);
404   qe->response_proc (qe->h, NULL);
405 }
406
407
408 /**
409  * Create a new entry for our priority queue (and possibly discard other entires if
410  * the queue is getting too long).
411  *
412  * @param h handle to the datastore
413  * @param msize size of the message to queue
414  * @param queue_priority priority of the entry
415  * @param max_queue_size at what queue size should this request be dropped
416  *        (if other requests of higher priority are in the queue)
417  * @param timeout timeout for the operation
418  * @param response_proc function to call with replies (can be NULL)
419  * @param qc client context (NOT a closure for @a response_proc)
420  * @return NULL if the queue is full
421  */
422 static struct GNUNET_DATASTORE_QueueEntry *
423 make_queue_entry (struct GNUNET_DATASTORE_Handle *h, size_t msize,
424                   unsigned int queue_priority, unsigned int max_queue_size,
425                   struct GNUNET_TIME_Relative timeout,
426                   GNUNET_CLIENT_MessageHandler response_proc,
427                   const union QueueContext *qc)
428 {
429   struct GNUNET_DATASTORE_QueueEntry *ret;
430   struct GNUNET_DATASTORE_QueueEntry *pos;
431   unsigned int c;
432
433   c = 0;
434   pos = h->queue_head;
435   while ((pos != NULL) && (c < max_queue_size) &&
436          (pos->priority >= queue_priority))
437   {
438     c++;
439     pos = pos->next;
440   }
441   if (c >= max_queue_size)
442   {
443     GNUNET_STATISTICS_update (h->stats, gettext_noop ("# queue overflows"), 1,
444                               GNUNET_NO);
445     return NULL;
446   }
447   ret = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_QueueEntry) + msize);
448   ret->h = h;
449   ret->response_proc = response_proc;
450   ret->qc = *qc;
451   ret->timeout = GNUNET_TIME_relative_to_absolute (timeout);
452   ret->priority = queue_priority;
453   ret->max_queue = max_queue_size;
454   ret->message_size = msize;
455   ret->was_transmitted = GNUNET_NO;
456   if (pos == NULL)
457   {
458     /* append at the tail */
459     pos = h->queue_tail;
460   }
461   else
462   {
463     pos = pos->prev;
464     /* do not insert at HEAD if HEAD query was already
465      * transmitted and we are still receiving replies! */
466     if ((pos == NULL) && (h->queue_head->was_transmitted))
467       pos = h->queue_head;
468   }
469   c++;
470 #if INSANE_STATISTICS
471   GNUNET_STATISTICS_update (h->stats, gettext_noop ("# queue entries created"),
472                             1, GNUNET_NO);
473 #endif
474   GNUNET_CONTAINER_DLL_insert_after (h->queue_head, h->queue_tail, pos, ret);
475   h->queue_size++;
476   ret->task = GNUNET_SCHEDULER_add_delayed (timeout, &timeout_queue_entry, ret);
477   for (pos = ret->next; NULL != pos; pos = pos->next)
478   {
479     if ((pos->max_queue < h->queue_size) && (pos->was_transmitted == GNUNET_NO))
480     {
481       GNUNET_assert (NULL != pos->response_proc);
482       /* move 'pos' element to head so that it will be
483        * killed on 'NULL' call below */
484       LOG (GNUNET_ERROR_TYPE_DEBUG,
485            "Dropping request from datastore queue\n");
486       /* response_proc's expect request at the head of the queue! */
487       GNUNET_CONTAINER_DLL_remove (h->queue_head, h->queue_tail, pos);
488       GNUNET_CONTAINER_DLL_insert (h->queue_head, h->queue_tail, pos);
489       GNUNET_STATISTICS_update (h->stats,
490                                 gettext_noop
491                                 ("# Requests dropped from datastore queue"), 1,
492                                 GNUNET_NO);
493       GNUNET_assert (h->queue_head == pos);
494       pos->response_proc (h, NULL);
495       break;
496     }
497   }
498   return ret;
499 }
500
501
502 /**
503  * Process entries in the queue (or do nothing if we are already
504  * doing so).
505  *
506  * @param h handle to the datastore
507  */
508 static void
509 process_queue (struct GNUNET_DATASTORE_Handle *h);
510
511
512 /**
513  * Try reconnecting to the datastore service.
514  *
515  * @param cls the `struct GNUNET_DATASTORE_Handle`
516  * @param tc scheduler context
517  */
518 static void
519 try_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
520 {
521   struct GNUNET_DATASTORE_Handle *h = cls;
522
523   h->retry_time = GNUNET_TIME_STD_BACKOFF (h->retry_time);
524   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
525   h->client = GNUNET_CLIENT_connect ("datastore", h->cfg);
526   if (h->client == NULL)
527   {
528     LOG (GNUNET_ERROR_TYPE_ERROR, "DATASTORE reconnect failed (fatally)\n");
529     return;
530   }
531   GNUNET_STATISTICS_update (h->stats,
532                             gettext_noop
533                             ("# datastore connections (re)created"), 1,
534                             GNUNET_NO);
535   LOG (GNUNET_ERROR_TYPE_DEBUG, "Reconnected to DATASTORE\n");
536   process_queue (h);
537 }
538
539
540 /**
541  * Disconnect from the service and then try reconnecting to the datastore service
542  * after some delay.
543  *
544  * @param h handle to datastore to disconnect and reconnect
545  */
546 static void
547 do_disconnect (struct GNUNET_DATASTORE_Handle *h)
548 {
549   if (h->client == NULL)
550   {
551     LOG (GNUNET_ERROR_TYPE_DEBUG,
552          "client NULL in disconnect, will not try to reconnect\n");
553     return;
554   }
555   GNUNET_CLIENT_disconnect (h->client);
556   h->skip_next_messages = 0;
557   h->client = NULL;
558   h->reconnect_task =
559       GNUNET_SCHEDULER_add_delayed (h->retry_time, &try_reconnect, h);
560 }
561
562
563 /**
564  * Function called whenever we receive a message from
565  * the service.  Calls the appropriate handler.
566  *
567  * @param cls the 'struct GNUNET_DATASTORE_Handle'
568  * @param msg the received message
569  */
570 static void
571 receive_cb (void *cls, const struct GNUNET_MessageHeader *msg)
572 {
573   struct GNUNET_DATASTORE_Handle *h = cls;
574   struct GNUNET_DATASTORE_QueueEntry *qe;
575
576   h->in_receive = GNUNET_NO;
577   LOG (GNUNET_ERROR_TYPE_DEBUG, "Receiving reply from datastore\n");
578   if (h->skip_next_messages > 0)
579   {
580     h->skip_next_messages--;
581     process_queue (h);
582     return;
583   }
584   if (NULL == (qe = h->queue_head))
585   {
586     GNUNET_break (0);
587     process_queue (h);
588     return;
589   }
590   qe->response_proc (h, msg);
591 }
592
593
594 /**
595  * Transmit request from queue to datastore service.
596  *
597  * @param cls the `struct GNUNET_DATASTORE_Handle`
598  * @param size number of bytes that can be copied to @a buf
599  * @param buf where to copy the drop message
600  * @return number of bytes written to @a buf
601  */
602 static size_t
603 transmit_request (void *cls, size_t size, void *buf)
604 {
605   struct GNUNET_DATASTORE_Handle *h = cls;
606   struct GNUNET_DATASTORE_QueueEntry *qe;
607   size_t msize;
608
609   h->th = NULL;
610   if (NULL == (qe = h->queue_head))
611     return 0;                   /* no entry in queue */
612   if (buf == NULL)
613   {
614     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to transmit request to DATASTORE.\n");
615     GNUNET_STATISTICS_update (h->stats,
616                               gettext_noop ("# transmission request failures"),
617                               1, GNUNET_NO);
618     do_disconnect (h);
619     return 0;
620   }
621   if (size < (msize = qe->message_size))
622   {
623     process_queue (h);
624     return 0;
625   }
626   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u byte request to DATASTORE\n",
627        msize);
628   memcpy (buf, &qe[1], msize);
629   qe->was_transmitted = GNUNET_YES;
630   GNUNET_SCHEDULER_cancel (qe->task);
631   qe->task = GNUNET_SCHEDULER_NO_TASK;
632   GNUNET_assert (GNUNET_NO == h->in_receive);
633   h->in_receive = GNUNET_YES;
634   GNUNET_CLIENT_receive (h->client, &receive_cb, h,
635                          GNUNET_TIME_absolute_get_remaining (qe->timeout));
636 #if INSANE_STATISTICS
637   GNUNET_STATISTICS_update (h->stats,
638                             gettext_noop ("# bytes sent to datastore"), 1,
639                             GNUNET_NO);
640 #endif
641   return msize;
642 }
643
644
645 /**
646  * Process entries in the queue (or do nothing if we are already
647  * doing so).
648  *
649  * @param h handle to the datastore
650  */
651 static void
652 process_queue (struct GNUNET_DATASTORE_Handle *h)
653 {
654   struct GNUNET_DATASTORE_QueueEntry *qe;
655
656   if (NULL == (qe = h->queue_head))
657   {
658     LOG (GNUNET_ERROR_TYPE_DEBUG, "Queue empty\n");
659     return;                     /* no entry in queue */
660   }
661   if (qe->was_transmitted == GNUNET_YES)
662   {
663     LOG (GNUNET_ERROR_TYPE_DEBUG, "Head request already transmitted\n");
664     return;                     /* waiting for replies */
665   }
666   if (h->th != NULL)
667   {
668     LOG (GNUNET_ERROR_TYPE_DEBUG, "Pending transmission request\n");
669     return;                     /* request pending */
670   }
671   if (h->client == NULL)
672   {
673     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not connected\n");
674     return;                     /* waiting for reconnect */
675   }
676   if (GNUNET_YES == h->in_receive)
677   {
678     /* wait for response to previous query */
679     return;
680   }
681   LOG (GNUNET_ERROR_TYPE_DEBUG, "Queueing %u byte request to DATASTORE\n",
682        qe->message_size);
683   h->th =
684       GNUNET_CLIENT_notify_transmit_ready (h->client, qe->message_size,
685                                            GNUNET_TIME_absolute_get_remaining
686                                            (qe->timeout), GNUNET_YES,
687                                            &transmit_request, h);
688   GNUNET_assert (GNUNET_NO == h->in_receive);
689   GNUNET_break (NULL != h->th);
690 }
691
692
693 /**
694  * Dummy continuation used to do nothing (but be non-zero).
695  *
696  * @param cls closure
697  * @param result result
698  * @param min_expiration expiration time
699  * @param emsg error message
700  */
701 static void
702 drop_status_cont (void *cls, int32_t result,
703                   struct GNUNET_TIME_Absolute min_expiration,
704                   const char *emsg)
705 {
706   /* do nothing */
707 }
708
709
710 /**
711  * Free a queue entry.  Removes the given entry from the
712  * queue and releases associated resources.  Does NOT
713  * call the callback.
714  *
715  * @param qe entry to free.
716  */
717 static void
718 free_queue_entry (struct GNUNET_DATASTORE_QueueEntry *qe)
719 {
720   struct GNUNET_DATASTORE_Handle *h = qe->h;
721
722   GNUNET_CONTAINER_DLL_remove (h->queue_head, h->queue_tail, qe);
723   if (qe->task != GNUNET_SCHEDULER_NO_TASK)
724   {
725     GNUNET_SCHEDULER_cancel (qe->task);
726     qe->task = GNUNET_SCHEDULER_NO_TASK;
727   }
728   h->queue_size--;
729   qe->was_transmitted = GNUNET_SYSERR;  /* use-after-free warning */
730   GNUNET_free (qe);
731 }
732
733
734 /**
735  * Type of a function to call when we receive a message
736  * from the service.
737  *
738  * @param cls closure
739  * @param msg message received, NULL on timeout or fatal error
740  */
741 static void
742 process_status_message (void *cls, const struct GNUNET_MessageHeader *msg)
743 {
744   struct GNUNET_DATASTORE_Handle *h = cls;
745   struct GNUNET_DATASTORE_QueueEntry *qe;
746   struct StatusContext rc;
747   const struct StatusMessage *sm;
748   const char *emsg;
749   int32_t status;
750   int was_transmitted;
751
752   if (NULL == (qe = h->queue_head))
753   {
754     GNUNET_break (0);
755     do_disconnect (h);
756     return;
757   }
758   rc = qe->qc.sc;
759   if (msg == NULL)
760   {
761     was_transmitted = qe->was_transmitted;
762     free_queue_entry (qe);
763     if (was_transmitted == GNUNET_YES)
764       do_disconnect (h);
765     else
766       process_queue (h);
767     if (rc.cont != NULL)
768       rc.cont (rc.cont_cls, GNUNET_SYSERR,
769                GNUNET_TIME_UNIT_ZERO_ABS,
770                _("Failed to receive status response from database."));
771     return;
772   }
773   GNUNET_assert (GNUNET_YES == qe->was_transmitted);
774   free_queue_entry (qe);
775   if ((ntohs (msg->size) < sizeof (struct StatusMessage)) ||
776       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DATASTORE_STATUS))
777   {
778     GNUNET_break (0);
779     h->retry_time = GNUNET_TIME_UNIT_ZERO;
780     do_disconnect (h);
781     if (rc.cont != NULL)
782       rc.cont (rc.cont_cls, GNUNET_SYSERR,
783                GNUNET_TIME_UNIT_ZERO_ABS,
784                _("Error reading response from datastore service"));
785     return;
786   }
787   sm = (const struct StatusMessage *) msg;
788   status = ntohl (sm->status);
789   emsg = NULL;
790   if (ntohs (msg->size) > sizeof (struct StatusMessage))
791   {
792     emsg = (const char *) &sm[1];
793     if (emsg[ntohs (msg->size) - sizeof (struct StatusMessage) - 1] != '\0')
794     {
795       GNUNET_break (0);
796       emsg = _("Invalid error message received from datastore service");
797     }
798   }
799   if ((status == GNUNET_SYSERR) && (emsg == NULL))
800   {
801     GNUNET_break (0);
802     emsg = _("Invalid error message received from datastore service");
803   }
804   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received status %d/%s\n", (int) status, emsg);
805   GNUNET_STATISTICS_update (h->stats,
806                             gettext_noop ("# status messages received"), 1,
807                             GNUNET_NO);
808   h->retry_time = GNUNET_TIME_UNIT_ZERO;
809   process_queue (h);
810   if (rc.cont != NULL)
811     rc.cont (rc.cont_cls, status,
812              GNUNET_TIME_absolute_ntoh (sm->min_expiration),
813              emsg);
814 }
815
816
817 /**
818  * Store an item in the datastore.  If the item is already present,
819  * the priorities are summed up and the higher expiration time and
820  * lower anonymity level is used.
821  *
822  * @param h handle to the datastore
823  * @param rid reservation ID to use (from "reserve"); use 0 if no
824  *            prior reservation was made
825  * @param key key for the value
826  * @param size number of bytes in data
827  * @param data content stored
828  * @param type type of the content
829  * @param priority priority of the content
830  * @param anonymity anonymity-level for the content
831  * @param replication how often should the content be replicated to other peers?
832  * @param expiration expiration time for the content
833  * @param queue_priority ranking of this request in the priority queue
834  * @param max_queue_size at what queue size should this request be dropped
835  *        (if other requests of higher priority are in the queue)
836  * @param timeout timeout for the operation
837  * @param cont continuation to call when done
838  * @param cont_cls closure for @a cont
839  * @return NULL if the entry was not queued, otherwise a handle that can be used to
840  *         cancel; note that even if NULL is returned, the callback will be invoked
841  *         (or rather, will already have been invoked)
842  */
843 struct GNUNET_DATASTORE_QueueEntry *
844 GNUNET_DATASTORE_put (struct GNUNET_DATASTORE_Handle *h, uint32_t rid,
845                       const struct GNUNET_HashCode * key, size_t size,
846                       const void *data, enum GNUNET_BLOCK_Type type,
847                       uint32_t priority, uint32_t anonymity,
848                       uint32_t replication,
849                       struct GNUNET_TIME_Absolute expiration,
850                       unsigned int queue_priority, unsigned int max_queue_size,
851                       struct GNUNET_TIME_Relative timeout,
852                       GNUNET_DATASTORE_ContinuationWithStatus cont,
853                       void *cont_cls)
854 {
855   struct GNUNET_DATASTORE_QueueEntry *qe;
856   struct DataMessage *dm;
857   size_t msize;
858   union QueueContext qc;
859
860   LOG (GNUNET_ERROR_TYPE_DEBUG,
861        "Asked to put %u bytes of data under key `%s' for %s\n", size,
862        GNUNET_h2s (key),
863        GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
864                                                GNUNET_YES));
865   msize = sizeof (struct DataMessage) + size;
866   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
867   qc.sc.cont = cont;
868   qc.sc.cont_cls = cont_cls;
869   qe = make_queue_entry (h, msize, queue_priority, max_queue_size, timeout,
870                          &process_status_message, &qc);
871   if (qe == NULL)
872   {
873     LOG (GNUNET_ERROR_TYPE_DEBUG, "Could not create queue entry for PUT\n");
874     return NULL;
875   }
876   GNUNET_STATISTICS_update (h->stats, gettext_noop ("# PUT requests executed"),
877                             1, GNUNET_NO);
878   dm = (struct DataMessage *) &qe[1];
879   dm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_PUT);
880   dm->header.size = htons (msize);
881   dm->rid = htonl (rid);
882   dm->size = htonl ((uint32_t) size);
883   dm->type = htonl (type);
884   dm->priority = htonl (priority);
885   dm->anonymity = htonl (anonymity);
886   dm->replication = htonl (replication);
887   dm->reserved = htonl (0);
888   dm->uid = GNUNET_htonll (0);
889   dm->expiration = GNUNET_TIME_absolute_hton (expiration);
890   dm->key = *key;
891   memcpy (&dm[1], data, size);
892   process_queue (h);
893   return qe;
894 }
895
896
897 /**
898  * Reserve space in the datastore.  This function should be used
899  * to avoid "out of space" failures during a longer sequence of "put"
900  * operations (for example, when a file is being inserted).
901  *
902  * @param h handle to the datastore
903  * @param amount how much space (in bytes) should be reserved (for content only)
904  * @param entries how many entries will be created (to calculate per-entry overhead)
905  * @param queue_priority ranking of this request in the priority queue
906  * @param max_queue_size at what queue size should this request be dropped
907  *        (if other requests of higher priority are in the queue)
908  * @param timeout how long to wait at most for a response (or before dying in queue)
909  * @param cont continuation to call when done; "success" will be set to
910  *             a positive reservation value if space could be reserved.
911  * @param cont_cls closure for @a cont
912  * @return NULL if the entry was not queued, otherwise a handle that can be used to
913  *         cancel; note that even if NULL is returned, the callback will be invoked
914  *         (or rather, will already have been invoked)
915  */
916 struct GNUNET_DATASTORE_QueueEntry *
917 GNUNET_DATASTORE_reserve (struct GNUNET_DATASTORE_Handle *h, uint64_t amount,
918                           uint32_t entries, unsigned int queue_priority,
919                           unsigned int max_queue_size,
920                           struct GNUNET_TIME_Relative timeout,
921                           GNUNET_DATASTORE_ContinuationWithStatus cont,
922                           void *cont_cls)
923 {
924   struct GNUNET_DATASTORE_QueueEntry *qe;
925   struct ReserveMessage *rm;
926   union QueueContext qc;
927
928   if (cont == NULL)
929     cont = &drop_status_cont;
930   LOG (GNUNET_ERROR_TYPE_DEBUG,
931        "Asked to reserve %llu bytes of data and %u entries\n",
932        (unsigned long long) amount, (unsigned int) entries);
933   qc.sc.cont = cont;
934   qc.sc.cont_cls = cont_cls;
935   qe = make_queue_entry (h, sizeof (struct ReserveMessage), queue_priority,
936                          max_queue_size, timeout, &process_status_message, &qc);
937   if (qe == NULL)
938   {
939     LOG (GNUNET_ERROR_TYPE_DEBUG,
940          "Could not create queue entry to reserve\n");
941     return NULL;
942   }
943   GNUNET_STATISTICS_update (h->stats,
944                             gettext_noop ("# RESERVE requests executed"), 1,
945                             GNUNET_NO);
946   rm = (struct ReserveMessage *) &qe[1];
947   rm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE);
948   rm->header.size = htons (sizeof (struct ReserveMessage));
949   rm->entries = htonl (entries);
950   rm->amount = GNUNET_htonll (amount);
951   process_queue (h);
952   return qe;
953 }
954
955
956 /**
957  * Signal that all of the data for which a reservation was made has
958  * been stored and that whatever excess space might have been reserved
959  * can now be released.
960  *
961  * @param h handle to the datastore
962  * @param rid reservation ID (value of "success" in original continuation
963  *        from the "reserve" function).
964  * @param queue_priority ranking of this request in the priority queue
965  * @param max_queue_size at what queue size should this request be dropped
966  *        (if other requests of higher priority are in the queue)
967  * @param queue_priority ranking of this request in the priority queue
968  * @param max_queue_size at what queue size should this request be dropped
969  *        (if other requests of higher priority are in the queue)
970  * @param timeout how long to wait at most for a response
971  * @param cont continuation to call when done
972  * @param cont_cls closure for @a cont
973  * @return NULL if the entry was not queued, otherwise a handle that can be used to
974  *         cancel; note that even if NULL is returned, the callback will be invoked
975  *         (or rather, will already have been invoked)
976  */
977 struct GNUNET_DATASTORE_QueueEntry *
978 GNUNET_DATASTORE_release_reserve (struct GNUNET_DATASTORE_Handle *h,
979                                   uint32_t rid, unsigned int queue_priority,
980                                   unsigned int max_queue_size,
981                                   struct GNUNET_TIME_Relative timeout,
982                                   GNUNET_DATASTORE_ContinuationWithStatus cont,
983                                   void *cont_cls)
984 {
985   struct GNUNET_DATASTORE_QueueEntry *qe;
986   struct ReleaseReserveMessage *rrm;
987   union QueueContext qc;
988
989   if (cont == NULL)
990     cont = &drop_status_cont;
991   LOG (GNUNET_ERROR_TYPE_DEBUG, "Asked to release reserve %d\n", rid);
992   qc.sc.cont = cont;
993   qc.sc.cont_cls = cont_cls;
994   qe = make_queue_entry (h, sizeof (struct ReleaseReserveMessage),
995                          queue_priority, max_queue_size, timeout,
996                          &process_status_message, &qc);
997   if (qe == NULL)
998   {
999     LOG (GNUNET_ERROR_TYPE_DEBUG,
1000          "Could not create queue entry to release reserve\n");
1001     return NULL;
1002   }
1003   GNUNET_STATISTICS_update (h->stats,
1004                             gettext_noop
1005                             ("# RELEASE RESERVE requests executed"), 1,
1006                             GNUNET_NO);
1007   rrm = (struct ReleaseReserveMessage *) &qe[1];
1008   rrm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE);
1009   rrm->header.size = htons (sizeof (struct ReleaseReserveMessage));
1010   rrm->rid = htonl (rid);
1011   process_queue (h);
1012   return qe;
1013 }
1014
1015
1016 /**
1017  * Update a value in the datastore.
1018  *
1019  * @param h handle to the datastore
1020  * @param uid identifier for the value
1021  * @param priority how much to increase the priority of the value
1022  * @param expiration new expiration value should be MAX of existing and this argument
1023  * @param queue_priority ranking of this request in the priority queue
1024  * @param max_queue_size at what queue size should this request be dropped
1025  *        (if other requests of higher priority are in the queue)
1026  * @param timeout how long to wait at most for a response
1027  * @param cont continuation to call when done
1028  * @param cont_cls closure for @a cont
1029  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1030  *         cancel; note that even if NULL is returned, the callback will be invoked
1031  *         (or rather, will already have been invoked)
1032  */
1033 struct GNUNET_DATASTORE_QueueEntry *
1034 GNUNET_DATASTORE_update (struct GNUNET_DATASTORE_Handle *h, uint64_t uid,
1035                          uint32_t priority,
1036                          struct GNUNET_TIME_Absolute expiration,
1037                          unsigned int queue_priority,
1038                          unsigned int max_queue_size,
1039                          struct GNUNET_TIME_Relative timeout,
1040                          GNUNET_DATASTORE_ContinuationWithStatus cont,
1041                          void *cont_cls)
1042 {
1043   struct GNUNET_DATASTORE_QueueEntry *qe;
1044   struct UpdateMessage *um;
1045   union QueueContext qc;
1046
1047   if (cont == NULL)
1048     cont = &drop_status_cont;
1049   LOG (GNUNET_ERROR_TYPE_DEBUG,
1050        "Asked to update entry %llu raising priority by %u and expiration to %s\n",
1051        uid,
1052        (unsigned int) priority,
1053        GNUNET_STRINGS_absolute_time_to_string (expiration));
1054   qc.sc.cont = cont;
1055   qc.sc.cont_cls = cont_cls;
1056   qe = make_queue_entry (h, sizeof (struct UpdateMessage), queue_priority,
1057                          max_queue_size, timeout, &process_status_message, &qc);
1058   if (qe == NULL)
1059   {
1060     LOG (GNUNET_ERROR_TYPE_DEBUG,
1061          "Could not create queue entry for UPDATE\n");
1062     return NULL;
1063   }
1064   GNUNET_STATISTICS_update (h->stats,
1065                             gettext_noop ("# UPDATE requests executed"), 1,
1066                             GNUNET_NO);
1067   um = (struct UpdateMessage *) &qe[1];
1068   um->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE);
1069   um->header.size = htons (sizeof (struct UpdateMessage));
1070   um->priority = htonl (priority);
1071   um->expiration = GNUNET_TIME_absolute_hton (expiration);
1072   um->uid = GNUNET_htonll (uid);
1073   process_queue (h);
1074   return qe;
1075 }
1076
1077
1078 /**
1079  * Explicitly remove some content from the database.
1080  * The @a cont continuation will be called with `status`
1081  * #GNUNET_OK" if content was removed, #GNUNET_NO
1082  * if no matching entry was found and #GNUNET_SYSERR
1083  * on all other types of errors.
1084  *
1085  * @param h handle to the datastore
1086  * @param key key for the value
1087  * @param size number of bytes in data
1088  * @param data content stored
1089  * @param queue_priority ranking of this request in the priority queue
1090  * @param max_queue_size at what queue size should this request be dropped
1091  *        (if other requests of higher priority are in the queue)
1092  * @param timeout how long to wait at most for a response
1093  * @param cont continuation to call when done
1094  * @param cont_cls closure for @a cont
1095  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1096  *         cancel; note that even if NULL is returned, the callback will be invoked
1097  *         (or rather, will already have been invoked)
1098  */
1099 struct GNUNET_DATASTORE_QueueEntry *
1100 GNUNET_DATASTORE_remove (struct GNUNET_DATASTORE_Handle *h,
1101                          const struct GNUNET_HashCode * key, size_t size,
1102                          const void *data, unsigned int queue_priority,
1103                          unsigned int max_queue_size,
1104                          struct GNUNET_TIME_Relative timeout,
1105                          GNUNET_DATASTORE_ContinuationWithStatus cont,
1106                          void *cont_cls)
1107 {
1108   struct GNUNET_DATASTORE_QueueEntry *qe;
1109   struct DataMessage *dm;
1110   size_t msize;
1111   union QueueContext qc;
1112
1113   if (cont == NULL)
1114     cont = &drop_status_cont;
1115   LOG (GNUNET_ERROR_TYPE_DEBUG, "Asked to remove %u bytes under key `%s'\n",
1116        size, GNUNET_h2s (key));
1117   qc.sc.cont = cont;
1118   qc.sc.cont_cls = cont_cls;
1119   msize = sizeof (struct DataMessage) + size;
1120   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1121   qe = make_queue_entry (h, msize, queue_priority, max_queue_size, timeout,
1122                          &process_status_message, &qc);
1123   if (qe == NULL)
1124   {
1125     LOG (GNUNET_ERROR_TYPE_DEBUG, "Could not create queue entry for REMOVE\n");
1126     return NULL;
1127   }
1128   GNUNET_STATISTICS_update (h->stats,
1129                             gettext_noop ("# REMOVE requests executed"), 1,
1130                             GNUNET_NO);
1131   dm = (struct DataMessage *) &qe[1];
1132   dm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE);
1133   dm->header.size = htons (msize);
1134   dm->rid = htonl (0);
1135   dm->size = htonl (size);
1136   dm->type = htonl (0);
1137   dm->priority = htonl (0);
1138   dm->anonymity = htonl (0);
1139   dm->uid = GNUNET_htonll (0);
1140   dm->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_ZERO_ABS);
1141   dm->key = *key;
1142   memcpy (&dm[1], data, size);
1143   process_queue (h);
1144   return qe;
1145 }
1146
1147
1148 /**
1149  * Type of a function to call when we receive a message
1150  * from the service.
1151  *
1152  * @param cls closure with the `struct GNUNET_DATASTORE_Handle *`
1153  * @param msg message received, NULL on timeout or fatal error
1154  */
1155 static void
1156 process_result_message (void *cls, const struct GNUNET_MessageHeader *msg)
1157 {
1158   struct GNUNET_DATASTORE_Handle *h = cls;
1159   struct GNUNET_DATASTORE_QueueEntry *qe;
1160   struct ResultContext rc;
1161   const struct DataMessage *dm;
1162   int was_transmitted;
1163
1164   if (NULL == msg)
1165   {
1166     qe = h->queue_head;
1167     GNUNET_assert (NULL != qe);
1168     rc = qe->qc.rc;
1169     was_transmitted = qe->was_transmitted;
1170     free_queue_entry (qe);
1171     if (GNUNET_YES == was_transmitted)
1172     {
1173       LOG (GNUNET_ERROR_TYPE_WARNING,
1174            _("Failed to receive response from database.\n"));
1175       do_disconnect (h);
1176     }
1177     else
1178     {
1179       process_queue (h);
1180     }
1181     if (NULL != rc.proc)
1182       rc.proc (rc.proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1183                0);
1184     return;
1185   }
1186   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END)
1187   {
1188     GNUNET_break (ntohs (msg->size) == sizeof (struct GNUNET_MessageHeader));
1189     qe = h->queue_head;
1190     rc = qe->qc.rc;
1191     GNUNET_assert (GNUNET_YES == qe->was_transmitted);
1192     free_queue_entry (qe);
1193     LOG (GNUNET_ERROR_TYPE_DEBUG,
1194          "Received end of result set, new queue size is %u\n", h->queue_size);
1195     h->retry_time = GNUNET_TIME_UNIT_ZERO;
1196     h->result_count = 0;
1197     process_queue (h);
1198     if (NULL != rc.proc)
1199       rc.proc (rc.proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1200                0);
1201     return;
1202   }
1203   qe = h->queue_head;
1204   GNUNET_assert (NULL != qe);
1205   rc = qe->qc.rc;
1206   if (GNUNET_YES != qe->was_transmitted)
1207   {
1208     GNUNET_break (0);
1209     free_queue_entry (qe);
1210     h->retry_time = GNUNET_TIME_UNIT_ZERO;
1211     do_disconnect (h);
1212     if (rc.proc != NULL)
1213       rc.proc (rc.proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1214                0);
1215     return;
1216   }
1217   if ((ntohs (msg->size) < sizeof (struct DataMessage)) ||
1218       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DATASTORE_DATA) ||
1219       (ntohs (msg->size) !=
1220        sizeof (struct DataMessage) +
1221        ntohl (((const struct DataMessage *) msg)->size)))
1222   {
1223     GNUNET_break (0);
1224     free_queue_entry (qe);
1225     h->retry_time = GNUNET_TIME_UNIT_ZERO;
1226     do_disconnect (h);
1227     if (rc.proc != NULL)
1228       rc.proc (rc.proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1229                0);
1230     return;
1231   }
1232 #if INSANE_STATISTICS
1233   GNUNET_STATISTICS_update (h->stats, gettext_noop ("# Results received"), 1,
1234                             GNUNET_NO);
1235 #endif
1236   dm = (const struct DataMessage *) msg;
1237   LOG (GNUNET_ERROR_TYPE_DEBUG,
1238        "Received result %llu with type %u and size %u with key %s\n",
1239        (unsigned long long) GNUNET_ntohll (dm->uid), ntohl (dm->type),
1240        ntohl (dm->size), GNUNET_h2s (&dm->key));
1241   free_queue_entry (qe);
1242   h->retry_time = GNUNET_TIME_UNIT_ZERO;
1243   process_queue (h);
1244   if (rc.proc != NULL)
1245     rc.proc (rc.proc_cls, &dm->key, ntohl (dm->size), &dm[1], ntohl (dm->type),
1246              ntohl (dm->priority), ntohl (dm->anonymity),
1247              GNUNET_TIME_absolute_ntoh (dm->expiration),
1248              GNUNET_ntohll (dm->uid));
1249 }
1250
1251
1252 /**
1253  * Get a random value from the datastore for content replication.
1254  * Returns a single, random value among those with the highest
1255  * replication score, lowering positive replication scores by one for
1256  * the chosen value (if only content with a replication score exists,
1257  * a random value is returned and replication scores are not changed).
1258  *
1259  * @param h handle to the datastore
1260  * @param queue_priority ranking of this request in the priority queue
1261  * @param max_queue_size at what queue size should this request be dropped
1262  *        (if other requests of higher priority are in the queue)
1263  * @param timeout how long to wait at most for a response
1264  * @param proc function to call on a random value; it
1265  *        will be called once with a value (if available)
1266  *        and always once with a value of NULL.
1267  * @param proc_cls closure for @a proc
1268  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1269  *         cancel
1270  */
1271 struct GNUNET_DATASTORE_QueueEntry *
1272 GNUNET_DATASTORE_get_for_replication (struct GNUNET_DATASTORE_Handle *h,
1273                                       unsigned int queue_priority,
1274                                       unsigned int max_queue_size,
1275                                       struct GNUNET_TIME_Relative timeout,
1276                                       GNUNET_DATASTORE_DatumProcessor proc,
1277                                       void *proc_cls)
1278 {
1279   struct GNUNET_DATASTORE_QueueEntry *qe;
1280   struct GNUNET_MessageHeader *m;
1281   union QueueContext qc;
1282
1283   GNUNET_assert (NULL != proc);
1284   LOG (GNUNET_ERROR_TYPE_DEBUG,
1285        "Asked to get replication entry in %s\n",
1286        GNUNET_STRINGS_relative_time_to_string (timeout, GNUNET_YES));
1287   qc.rc.proc = proc;
1288   qc.rc.proc_cls = proc_cls;
1289   qe = make_queue_entry (h, sizeof (struct GNUNET_MessageHeader),
1290                          queue_priority, max_queue_size, timeout,
1291                          &process_result_message, &qc);
1292   if (NULL == qe)
1293   {
1294     LOG (GNUNET_ERROR_TYPE_DEBUG,
1295          "Could not create queue entry for GET REPLICATION\n");
1296     return NULL;
1297   }
1298   GNUNET_STATISTICS_update (h->stats,
1299                             gettext_noop
1300                             ("# GET REPLICATION requests executed"), 1,
1301                             GNUNET_NO);
1302   m = (struct GNUNET_MessageHeader *) &qe[1];
1303   m->type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION);
1304   m->size = htons (sizeof (struct GNUNET_MessageHeader));
1305   process_queue (h);
1306   return qe;
1307 }
1308
1309
1310 /**
1311  * Get a single zero-anonymity value from the datastore.
1312  *
1313  * @param h handle to the datastore
1314  * @param offset offset of the result (modulo num-results); set to
1315  *               a random 64-bit value initially; then increment by
1316  *               one each time; detect that all results have been found by uid
1317  *               being again the first uid ever returned.
1318  * @param queue_priority ranking of this request in the priority queue
1319  * @param max_queue_size at what queue size should this request be dropped
1320  *        (if other requests of higher priority are in the queue)
1321  * @param timeout how long to wait at most for a response
1322  * @param type allowed type for the operation (never zero)
1323  * @param proc function to call on a random value; it
1324  *        will be called once with a value (if available)
1325  *        or with NULL if none value exists.
1326  * @param proc_cls closure for @a proc
1327  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1328  *         cancel
1329  */
1330 struct GNUNET_DATASTORE_QueueEntry *
1331 GNUNET_DATASTORE_get_zero_anonymity (struct GNUNET_DATASTORE_Handle *h,
1332                                      uint64_t offset,
1333                                      unsigned int queue_priority,
1334                                      unsigned int max_queue_size,
1335                                      struct GNUNET_TIME_Relative timeout,
1336                                      enum GNUNET_BLOCK_Type type,
1337                                      GNUNET_DATASTORE_DatumProcessor proc,
1338                                      void *proc_cls)
1339 {
1340   struct GNUNET_DATASTORE_QueueEntry *qe;
1341   struct GetZeroAnonymityMessage *m;
1342   union QueueContext qc;
1343
1344   GNUNET_assert (NULL != proc);
1345   GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
1346   LOG (GNUNET_ERROR_TYPE_DEBUG,
1347        "Asked to get %llu-th zero-anonymity entry of type %d in %s\n",
1348        (unsigned long long) offset, type,
1349        GNUNET_STRINGS_relative_time_to_string (timeout, GNUNET_YES));
1350   qc.rc.proc = proc;
1351   qc.rc.proc_cls = proc_cls;
1352   qe = make_queue_entry (h, sizeof (struct GetZeroAnonymityMessage),
1353                          queue_priority, max_queue_size, timeout,
1354                          &process_result_message, &qc);
1355   if (NULL == qe)
1356   {
1357     LOG (GNUNET_ERROR_TYPE_DEBUG,
1358          "Could not create queue entry for zero-anonymity procation\n");
1359     return NULL;
1360   }
1361   GNUNET_STATISTICS_update (h->stats,
1362                             gettext_noop
1363                             ("# GET ZERO ANONYMITY requests executed"), 1,
1364                             GNUNET_NO);
1365   m = (struct GetZeroAnonymityMessage *) &qe[1];
1366   m->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY);
1367   m->header.size = htons (sizeof (struct GetZeroAnonymityMessage));
1368   m->type = htonl ((uint32_t) type);
1369   m->offset = GNUNET_htonll (offset);
1370   process_queue (h);
1371   return qe;
1372 }
1373
1374
1375 /**
1376  * Get a result for a particular key from the datastore.  The processor
1377  * will only be called once.
1378  *
1379  * @param h handle to the datastore
1380  * @param offset offset of the result (modulo num-results); set to
1381  *               a random 64-bit value initially; then increment by
1382  *               one each time; detect that all results have been found by uid
1383  *               being again the first uid ever returned.
1384  * @param key maybe NULL (to match all entries)
1385  * @param type desired type, 0 for any
1386  * @param queue_priority ranking of this request in the priority queue
1387  * @param max_queue_size at what queue size should this request be dropped
1388  *        (if other requests of higher priority are in the queue)
1389  * @param timeout how long to wait at most for a response
1390  * @param proc function to call on each matching value;
1391  *        will be called once with a NULL value at the end
1392  * @param proc_cls closure for @a proc
1393  * @return NULL if the entry was not queued, otherwise a handle that can be used to
1394  *         cancel
1395  */
1396 struct GNUNET_DATASTORE_QueueEntry *
1397 GNUNET_DATASTORE_get_key (struct GNUNET_DATASTORE_Handle *h, uint64_t offset,
1398                           const struct GNUNET_HashCode * key,
1399                           enum GNUNET_BLOCK_Type type,
1400                           unsigned int queue_priority,
1401                           unsigned int max_queue_size,
1402                           struct GNUNET_TIME_Relative timeout,
1403                           GNUNET_DATASTORE_DatumProcessor proc, void *proc_cls)
1404 {
1405   struct GNUNET_DATASTORE_QueueEntry *qe;
1406   struct GetMessage *gm;
1407   union QueueContext qc;
1408
1409   GNUNET_assert (NULL != proc);
1410   LOG (GNUNET_ERROR_TYPE_DEBUG,
1411        "Asked to look for data of type %u under key `%s'\n",
1412        (unsigned int) type, GNUNET_h2s (key));
1413   qc.rc.proc = proc;
1414   qc.rc.proc_cls = proc_cls;
1415   qe = make_queue_entry (h, sizeof (struct GetMessage), queue_priority,
1416                          max_queue_size, timeout, &process_result_message, &qc);
1417   if (qe == NULL)
1418   {
1419     LOG (GNUNET_ERROR_TYPE_DEBUG, "Could not queue request for `%s'\n",
1420          GNUNET_h2s (key));
1421     return NULL;
1422   }
1423 #if INSANE_STATISTICS
1424   GNUNET_STATISTICS_update (h->stats, gettext_noop ("# GET requests executed"),
1425                             1, GNUNET_NO);
1426 #endif
1427   gm = (struct GetMessage *) &qe[1];
1428   gm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_GET);
1429   gm->type = htonl (type);
1430   gm->offset = GNUNET_htonll (offset);
1431   if (key != NULL)
1432   {
1433     gm->header.size = htons (sizeof (struct GetMessage));
1434     gm->key = *key;
1435   }
1436   else
1437   {
1438     gm->header.size =
1439         htons (sizeof (struct GetMessage) - sizeof (struct GNUNET_HashCode));
1440   }
1441   process_queue (h);
1442   return qe;
1443 }
1444
1445
1446 /**
1447  * Cancel a datastore operation.  The final callback from the
1448  * operation must not have been done yet.
1449  *
1450  * @param qe operation to cancel
1451  */
1452 void
1453 GNUNET_DATASTORE_cancel (struct GNUNET_DATASTORE_QueueEntry *qe)
1454 {
1455   struct GNUNET_DATASTORE_Handle *h;
1456
1457   GNUNET_assert (GNUNET_SYSERR != qe->was_transmitted);
1458   h = qe->h;
1459   LOG (GNUNET_ERROR_TYPE_DEBUG,
1460        "Pending DATASTORE request %p cancelled (%d, %d)\n", qe,
1461        qe->was_transmitted, h->queue_head == qe);
1462   if (GNUNET_YES == qe->was_transmitted)
1463   {
1464     free_queue_entry (qe);
1465     h->skip_next_messages++;
1466     return;
1467   }
1468   free_queue_entry (qe);
1469   process_queue (h);
1470 }
1471
1472
1473 /* end of datastore_api.c */