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