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