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