-logging
[oweals/gnunet.git] / src / datastore / gnunet-service-datastore.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2004-2014 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/gnunet-service-datastore.c
23  * @brief Management for the datastore for files stored on a GNUnet node
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_statistics_service.h"
31 #include "gnunet_datastore_plugin.h"
32 #include "datastore.h"
33
34 /**
35  * How many messages do we queue at most per client?
36  */
37 #define MAX_PENDING 1024
38
39 /**
40  * How long are we at most keeping "expired" content
41  * past the expiration date in the database?
42  */
43 #define MAX_EXPIRE_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
44
45 /**
46  * How fast are we allowed to query the database for deleting
47  * expired content? (1 item per second).
48  */
49 #define MIN_EXPIRE_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
50
51 /**
52  * Name under which we store current space consumption.
53  */
54 static char *quota_stat_name;
55
56 /**
57  * After how many payload-changing operations
58  * do we sync our statistics?
59  */
60 #define MAX_STAT_SYNC_LAG 50
61
62
63 /**
64  * Our datastore plugin.
65  */
66 struct DatastorePlugin
67 {
68
69   /**
70    * API of the transport as returned by the plugin's
71    * initialization function.
72    */
73   struct GNUNET_DATASTORE_PluginFunctions *api;
74
75   /**
76    * Short name for the plugin (i.e. "sqlite").
77    */
78   char *short_name;
79
80   /**
81    * Name of the library (i.e. "gnunet_plugin_datastore_sqlite").
82    */
83   char *lib_name;
84
85   /**
86    * Environment this transport service is using
87    * for this plugin.
88    */
89   struct GNUNET_DATASTORE_PluginEnvironment env;
90
91 };
92
93
94 /**
95  * Linked list of active reservations.
96  */
97 struct ReservationList
98 {
99
100   /**
101    * This is a linked list.
102    */
103   struct ReservationList *next;
104
105   /**
106    * Client that made the reservation.
107    */
108   struct GNUNET_SERVER_Client *client;
109
110   /**
111    * Number of bytes (still) reserved.
112    */
113   uint64_t amount;
114
115   /**
116    * Number of items (still) reserved.
117    */
118   uint64_t entries;
119
120   /**
121    * Reservation identifier.
122    */
123   int32_t rid;
124
125 };
126
127
128
129 /**
130  * Our datastore plugin (NULL if not available).
131  */
132 static struct DatastorePlugin *plugin;
133
134 /**
135  * Linked list of space reservations made by clients.
136  */
137 static struct ReservationList *reservations;
138
139 /**
140  * Bloomfilter to quickly tell if we don't have the content.
141  */
142 static struct GNUNET_CONTAINER_BloomFilter *filter;
143
144 /**
145  * Name of our plugin.
146  */
147 static char *plugin_name;
148
149 /**
150  * Our configuration.
151  */
152 static const struct GNUNET_CONFIGURATION_Handle *cfg;
153
154 /**
155  * Handle for reporting statistics.
156  */
157 static struct GNUNET_STATISTICS_Handle *stats;
158
159 /**
160  * How much space are we using for the cache?  (space available for
161  * insertions that will be instantly reclaimed by discarding less
162  * important content --- or possibly whatever we just inserted into
163  * the "cache").
164  */
165 static unsigned long long cache_size;
166
167 /**
168  * How much space have we currently reserved?
169  */
170 static unsigned long long reserved;
171
172 /**
173  * How much data are we currently storing
174  * in the database?
175  */
176 static unsigned long long payload;
177
178 /**
179  * Identity of the task that is used to delete
180  * expired content.
181  */
182 static struct GNUNET_SCHEDULER_Task * expired_kill_task;
183
184 /**
185  * Minimum time that content should have to not be discarded instantly
186  * (time stamp of any content that we've been discarding recently to
187  * stay below the quota).  FOREVER if we had to expire content with
188  * non-zero priority.
189  */
190 static struct GNUNET_TIME_Absolute min_expiration;
191
192 /**
193  * How much space are we allowed to use?
194  */
195 static unsigned long long quota;
196
197 /**
198  * Should the database be dropped on exit?
199  */
200 static int do_drop;
201
202 /**
203  * Should we refresh the BF when the DB is loaded?
204  */
205 static int refresh_bf;
206
207 /**
208  * Number of updates that were made to the
209  * payload value since we last synchronized
210  * it with the statistics service.
211  */
212 static unsigned int last_sync;
213
214 /**
215  * Did we get an answer from statistics?
216  */
217 static int stats_worked;
218
219
220 /**
221  * Synchronize our utilization statistics with the
222  * statistics service.
223  */
224 static void
225 sync_stats ()
226 {
227   GNUNET_STATISTICS_set (stats, quota_stat_name, payload, GNUNET_YES);
228   GNUNET_STATISTICS_set (stats, "# utilization by current datastore", payload, GNUNET_NO);
229   last_sync = 0;
230 }
231
232
233 /**
234  * Context for transmitting replies to clients.
235  */
236 struct TransmitCallbackContext
237 {
238
239   /**
240    * We keep these in a doubly-linked list (for cleanup).
241    */
242   struct TransmitCallbackContext *next;
243
244   /**
245    * We keep these in a doubly-linked list (for cleanup).
246    */
247   struct TransmitCallbackContext *prev;
248
249   /**
250    * The message that we're asked to transmit.
251    */
252   struct GNUNET_MessageHeader *msg;
253
254   /**
255    * Handle for the transmission request.
256    */
257   struct GNUNET_SERVER_TransmitHandle *th;
258
259   /**
260    * Client that we are transmitting to.
261    */
262   struct GNUNET_SERVER_Client *client;
263
264 };
265
266
267 /**
268  * Head of the doubly-linked list (for cleanup).
269  */
270 static struct TransmitCallbackContext *tcc_head;
271
272 /**
273  * Tail of the doubly-linked list (for cleanup).
274  */
275 static struct TransmitCallbackContext *tcc_tail;
276
277 /**
278  * Have we already cleaned up the TCCs and are hence no longer
279  * willing (or able) to transmit anything to anyone?
280  */
281 static int cleaning_done;
282
283 /**
284  * Handle for pending get request.
285  */
286 static struct GNUNET_STATISTICS_GetHandle *stat_get;
287
288 /**
289  * Handle to our server.
290  */
291 static struct GNUNET_SERVER_Handle *server;
292
293 /**
294  * Task that is used to remove expired entries from
295  * the datastore.  This task will schedule itself
296  * again automatically to always delete all expired
297  * content quickly.
298  *
299  * @param cls not used
300  * @param tc task context
301  */
302 static void
303 delete_expired (void *cls,
304                 const struct GNUNET_SCHEDULER_TaskContext *tc);
305
306
307 /**
308  * Iterate over the expired items stored in the datastore.
309  * Delete all expired items; once we have processed all
310  * expired items, re-schedule the "delete_expired" task.
311  *
312  * @param cls not used
313  * @param key key for the content
314  * @param size number of bytes in data
315  * @param data content stored
316  * @param type type of the content
317  * @param priority priority of the content
318  * @param anonymity anonymity-level for the content
319  * @param expiration expiration time for the content
320  * @param uid unique identifier for the datum;
321  *        maybe 0 if no unique identifier is available
322  *
323  * @return #GNUNET_SYSERR to abort the iteration, #GNUNET_OK to continue
324  *         (continue on call to "next", of course),
325  *         #GNUNET_NO to delete the item and continue (if supported)
326  */
327 static int
328 expired_processor (void *cls,
329                    const struct GNUNET_HashCode *key,
330                    uint32_t size,
331                    const void *data,
332                    enum GNUNET_BLOCK_Type type,
333                    uint32_t priority,
334                    uint32_t anonymity,
335                    struct GNUNET_TIME_Absolute expiration,
336                    uint64_t uid)
337 {
338   struct GNUNET_TIME_Absolute now;
339
340   if (key == NULL)
341   {
342     expired_kill_task =
343         GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY,
344                                                     GNUNET_SCHEDULER_PRIORITY_IDLE,
345                                                     &delete_expired, NULL);
346     return GNUNET_SYSERR;
347   }
348   now = GNUNET_TIME_absolute_get ();
349   if (expiration.abs_value_us > now.abs_value_us)
350   {
351     /* finished processing */
352     expired_kill_task =
353         GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY,
354                                                     GNUNET_SCHEDULER_PRIORITY_IDLE,
355                                                     &delete_expired, NULL);
356     return GNUNET_SYSERR;
357   }
358   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
359               "Deleting content `%s' of type %u that expired %s ago\n",
360               GNUNET_h2s (key), type,
361               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (expiration,
362                                                                                            now),
363                                                       GNUNET_YES));
364   min_expiration = now;
365   GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes expired"), size,
366                             GNUNET_YES);
367   GNUNET_CONTAINER_bloomfilter_remove (filter, key);
368   expired_kill_task =
369       GNUNET_SCHEDULER_add_delayed_with_priority (MIN_EXPIRE_DELAY,
370                                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
371                                                   &delete_expired, NULL);
372   return GNUNET_NO;
373 }
374
375
376 /**
377  * Task that is used to remove expired entries from
378  * the datastore.  This task will schedule itself
379  * again automatically to always delete all expired
380  * content quickly.
381  *
382  * @param cls not used
383  * @param tc task context
384  */
385 static void
386 delete_expired (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
387 {
388   expired_kill_task = NULL;
389   plugin->api->get_expiration (plugin->api->cls, &expired_processor, NULL);
390 }
391
392
393 /**
394  * An iterator over a set of items stored in the datastore
395  * that deletes until we're happy with respect to our quota.
396  *
397  * @param cls closure
398  * @param key key for the content
399  * @param size number of bytes in data
400  * @param data content stored
401  * @param type type of the content
402  * @param priority priority of the content
403  * @param anonymity anonymity-level for the content
404  * @param expiration expiration time for the content
405  * @param uid unique identifier for the datum;
406  *        maybe 0 if no unique identifier is available
407  *
408  * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
409  *         (continue on call to "next", of course),
410  *         GNUNET_NO to delete the item and continue (if supported)
411  */
412 static int
413 quota_processor (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
414                  const void *data, enum GNUNET_BLOCK_Type type,
415                  uint32_t priority, uint32_t anonymity,
416                  struct GNUNET_TIME_Absolute expiration, uint64_t uid)
417 {
418   unsigned long long *need = cls;
419
420   if (NULL == key)
421     return GNUNET_SYSERR;
422   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
423               "Deleting %llu bytes of low-priority (%u) content `%s' of type %u at %s prior to expiration (still trying to free another %llu bytes)\n",
424               (unsigned long long) (size + GNUNET_DATASTORE_ENTRY_OVERHEAD),
425               (unsigned int) priority,
426               GNUNET_h2s (key), type,
427               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
428                                                       GNUNET_YES),
429               *need);
430   if (size + GNUNET_DATASTORE_ENTRY_OVERHEAD > *need)
431     *need = 0;
432   else
433     *need -= size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
434   if (priority > 0)
435     min_expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
436   else
437     min_expiration = expiration;
438   GNUNET_STATISTICS_update (stats,
439                             gettext_noop ("# bytes purged (low-priority)"),
440                             size, GNUNET_YES);
441   GNUNET_CONTAINER_bloomfilter_remove (filter, key);
442   return GNUNET_NO;
443 }
444
445
446 /**
447  * Manage available disk space by running tasks
448  * that will discard content if necessary.  This
449  * function will be run whenever a request for
450  * "need" bytes of storage could only be satisfied
451  * by eating into the "cache" (and we want our cache
452  * space back).
453  *
454  * @param need number of bytes of content that were
455  *        placed into the "cache" (and hence the
456  *        number of bytes that should be removed).
457  */
458 static void
459 manage_space (unsigned long long need)
460 {
461   unsigned long long last;
462
463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
464               "Asked to free up %llu bytes of cache space\n", need);
465   last = 0;
466   while ((need > 0) && (last != need))
467   {
468     last = need;
469     plugin->api->get_expiration (plugin->api->cls, &quota_processor, &need);
470   }
471 }
472
473
474 /**
475  * Function called to notify a client about the socket
476  * begin ready to queue more data.  "buf" will be
477  * NULL and "size" zero if the socket was closed for
478  * writing in the meantime.
479  *
480  * @param cls closure
481  * @param size number of bytes available in buf
482  * @param buf where the callee should write the message
483  * @return number of bytes written to buf
484  */
485 static size_t
486 transmit_callback (void *cls, size_t size, void *buf)
487 {
488   struct TransmitCallbackContext *tcc = cls;
489   size_t msize;
490
491   tcc->th = NULL;
492   GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
493   msize = ntohs (tcc->msg->size);
494   if (size == 0)
495   {
496     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
497                 _("Transmission to client failed!\n"));
498     GNUNET_SERVER_receive_done (tcc->client, GNUNET_SYSERR);
499     GNUNET_SERVER_client_drop (tcc->client);
500     GNUNET_free (tcc->msg);
501     GNUNET_free (tcc);
502     return 0;
503   }
504   GNUNET_assert (size >= msize);
505   memcpy (buf, tcc->msg, msize);
506   GNUNET_SERVER_receive_done (tcc->client, GNUNET_OK);
507   GNUNET_SERVER_client_drop (tcc->client);
508   GNUNET_free (tcc->msg);
509   GNUNET_free (tcc);
510   return msize;
511 }
512
513
514 /**
515  * Transmit the given message to the client.
516  *
517  * @param client target of the message
518  * @param msg message to transmit, will be freed!
519  */
520 static void
521 transmit (struct GNUNET_SERVER_Client *client, struct GNUNET_MessageHeader *msg)
522 {
523   struct TransmitCallbackContext *tcc;
524
525   if (GNUNET_YES == cleaning_done)
526   {
527     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
528                 _("Shutdown in progress, aborting transmission.\n"));
529     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
530     GNUNET_free (msg);
531     return;
532   }
533   tcc = GNUNET_new (struct TransmitCallbackContext);
534   tcc->msg = msg;
535   tcc->client = client;
536   if (NULL ==
537       (tcc->th =
538        GNUNET_SERVER_notify_transmit_ready (client, ntohs (msg->size),
539                                             GNUNET_TIME_UNIT_FOREVER_REL,
540                                             &transmit_callback, tcc)))
541   {
542     GNUNET_break (0);
543     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
544     GNUNET_free (msg);
545     GNUNET_free (tcc);
546     return;
547   }
548   GNUNET_SERVER_client_keep (client);
549   GNUNET_CONTAINER_DLL_insert (tcc_head, tcc_tail, tcc);
550 }
551
552
553 /**
554  * Transmit a status code to the client.
555  *
556  * @param client receiver of the response
557  * @param code status code
558  * @param msg optional error message (can be NULL)
559  */
560 static void
561 transmit_status (struct GNUNET_SERVER_Client *client, int code, const char *msg)
562 {
563   struct StatusMessage *sm;
564   size_t slen;
565
566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567               "Transmitting `%s' message with value %d and message `%s'\n",
568               "STATUS", code, msg != NULL ? msg : "(none)");
569   slen = (msg == NULL) ? 0 : strlen (msg) + 1;
570   sm = GNUNET_malloc (sizeof (struct StatusMessage) + slen);
571   sm->header.size = htons (sizeof (struct StatusMessage) + slen);
572   sm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_STATUS);
573   sm->status = htonl (code);
574   sm->min_expiration = GNUNET_TIME_absolute_hton (min_expiration);
575   if (slen > 0)
576     memcpy (&sm[1], msg, slen);
577   transmit (client, &sm->header);
578 }
579
580
581 /**
582  * Function that will transmit the given datastore entry
583  * to the client.
584  *
585  * @param cls closure, pointer to the client (of type GNUNET_SERVER_Client).
586  * @param key key for the content
587  * @param size number of bytes in data
588  * @param data content stored
589  * @param type type of the content
590  * @param priority priority of the content
591  * @param anonymity anonymity-level for the content
592  * @param expiration expiration time for the content
593  * @param uid unique identifier for the datum;
594  *        maybe 0 if no unique identifier is available
595  *
596  * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue,
597  *         GNUNET_NO to delete the item and continue (if supported)
598  */
599 static int
600 transmit_item (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
601                const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
602                uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
603                uint64_t uid)
604 {
605   struct GNUNET_SERVER_Client *client = cls;
606   struct GNUNET_MessageHeader *end;
607   struct DataMessage *dm;
608
609   if (key == NULL)
610   {
611     /* transmit 'DATA_END' */
612     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' message\n",
613                 "DATA_END");
614     end = GNUNET_new (struct GNUNET_MessageHeader);
615     end->size = htons (sizeof (struct GNUNET_MessageHeader));
616     end->type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END);
617     transmit (client, end);
618     GNUNET_SERVER_client_drop (client);
619     return GNUNET_OK;
620   }
621   GNUNET_assert (sizeof (struct DataMessage) + size <
622                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
623   dm = GNUNET_malloc (sizeof (struct DataMessage) + size);
624   dm->header.size = htons (sizeof (struct DataMessage) + size);
625   dm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA);
626   dm->rid = htonl (0);
627   dm->size = htonl (size);
628   dm->type = htonl (type);
629   dm->priority = htonl (priority);
630   dm->anonymity = htonl (anonymity);
631   dm->replication = htonl (0);
632   dm->reserved = htonl (0);
633   dm->expiration = GNUNET_TIME_absolute_hton (expiration);
634   dm->uid = GNUNET_htonll (uid);
635   dm->key = *key;
636   memcpy (&dm[1], data, size);
637   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
638               "Transmitting `%s' message for `%s' of type %u with expiration %s (in: %s)\n",
639               "DATA", GNUNET_h2s (key), type,
640               GNUNET_STRINGS_absolute_time_to_string (expiration),
641               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
642                                                       GNUNET_YES));
643   GNUNET_STATISTICS_update (stats, gettext_noop ("# results found"), 1,
644                             GNUNET_NO);
645   transmit (client, &dm->header);
646   GNUNET_SERVER_client_drop (client);
647   return GNUNET_OK;
648 }
649
650
651 /**
652  * Handle RESERVE-message.
653  *
654  * @param cls closure
655  * @param client identification of the client
656  * @param message the actual message
657  */
658 static void
659 handle_reserve (void *cls, struct GNUNET_SERVER_Client *client,
660                 const struct GNUNET_MessageHeader *message)
661 {
662   /**
663    * Static counter to produce reservation identifiers.
664    */
665   static int reservation_gen;
666
667   const struct ReserveMessage *msg = (const struct ReserveMessage *) message;
668   struct ReservationList *e;
669   unsigned long long used;
670   unsigned long long req;
671   uint64_t amount;
672   uint32_t entries;
673
674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n", "RESERVE");
675   amount = GNUNET_ntohll (msg->amount);
676   entries = ntohl (msg->entries);
677   used = payload + reserved;
678   req =
679       amount + ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * entries;
680   if (used + req > quota)
681   {
682     if (quota < used)
683       used = quota;             /* cheat a bit for error message (to avoid negative numbers) */
684     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
685                 _
686                 ("Insufficient space (%llu bytes are available) to satisfy `%s' request for %llu bytes\n"),
687                 quota - used, "RESERVE", req);
688     if (cache_size < req)
689     {
690       /* TODO: document this in the FAQ; essentially, if this
691        * message happens, the insertion request could be blocked
692        * by less-important content from migration because it is
693        * larger than 1/8th of the overall available space, and
694        * we only reserve 1/8th for "fresh" insertions */
695       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
696                   _
697                   ("The requested amount (%llu bytes) is larger than the cache size (%llu bytes)\n"),
698                   req, cache_size);
699       transmit_status (client, 0,
700                        gettext_noop
701                        ("Insufficient space to satisfy request and "
702                         "requested amount is larger than cache size"));
703     }
704     else
705     {
706       transmit_status (client, 0,
707                        gettext_noop ("Insufficient space to satisfy request"));
708     }
709     return;
710   }
711   reserved += req;
712   GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
713                          GNUNET_NO);
714   e = GNUNET_new (struct ReservationList);
715   e->next = reservations;
716   reservations = e;
717   e->client = client;
718   e->amount = amount;
719   e->entries = entries;
720   e->rid = ++reservation_gen;
721   if (reservation_gen < 0)
722     reservation_gen = 0;        /* wrap around */
723   transmit_status (client, e->rid, NULL);
724 }
725
726
727 /**
728  * Handle RELEASE_RESERVE-message.
729  *
730  * @param cls closure
731  * @param client identification of the client
732  * @param message the actual message
733  */
734 static void
735 handle_release_reserve (void *cls,
736                         struct GNUNET_SERVER_Client *client,
737                         const struct GNUNET_MessageHeader *message)
738 {
739   const struct ReleaseReserveMessage *msg =
740       (const struct ReleaseReserveMessage *) message;
741   struct ReservationList *pos;
742   struct ReservationList *prev;
743   struct ReservationList *next;
744   int rid = ntohl (msg->rid);
745   unsigned long long rem;
746
747   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
748               "Processing `%s' request\n",
749               "RELEASE_RESERVE");
750   next = reservations;
751   prev = NULL;
752   while (NULL != (pos = next))
753   {
754     next = pos->next;
755     if (rid == pos->rid)
756     {
757       if (prev == NULL)
758         reservations = next;
759       else
760         prev->next = next;
761       rem =
762           pos->amount +
763           ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * pos->entries;
764       GNUNET_assert (reserved >= rem);
765       reserved -= rem;
766       GNUNET_STATISTICS_set (stats,
767                              gettext_noop ("# reserved"), reserved,
768                              GNUNET_NO);
769       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
770                   "Returning %llu remaining reserved bytes to storage pool\n",
771                   rem);
772       GNUNET_free (pos);
773       transmit_status (client, GNUNET_OK, NULL);
774       return;
775     }
776     prev = pos;
777   }
778   GNUNET_break (0);
779   transmit_status (client, GNUNET_SYSERR,
780                    gettext_noop ("Could not find matching reservation"));
781 }
782
783
784 /**
785  * Check that the given message is a valid data message.
786  *
787  * @return NULL if the message is not well-formed, otherwise the message
788  */
789 static const struct DataMessage *
790 check_data (const struct GNUNET_MessageHeader *message)
791 {
792   uint16_t size;
793   uint32_t dsize;
794   const struct DataMessage *dm;
795
796   size = ntohs (message->size);
797   if (size < sizeof (struct DataMessage))
798   {
799     GNUNET_break (0);
800     return NULL;
801   }
802   dm = (const struct DataMessage *) message;
803   dsize = ntohl (dm->size);
804   if (size != dsize + sizeof (struct DataMessage))
805   {
806     GNUNET_break (0);
807     return NULL;
808   }
809   return dm;
810 }
811
812
813 /**
814  * Context for a PUT request used to see if the content is
815  * already present.
816  */
817 struct PutContext
818 {
819   /**
820    * Client to notify on completion.
821    */
822   struct GNUNET_SERVER_Client *client;
823
824 #if ! HAVE_UNALIGNED_64_ACCESS
825   void *reserved;
826 #endif
827
828   /* followed by the 'struct DataMessage' */
829 };
830
831
832 /**
833  * Put continuation.
834  *
835  * @param cls closure
836  * @param key key for the item stored
837  * @param size size of the item stored
838  * @param status #GNUNET_OK or #GNUNET_SYSERROR
839  * @param msg error message on error
840  */
841 static void
842 put_continuation (void *cls, 
843                   const struct GNUNET_HashCode *key, 
844                   uint32_t size,
845                   int status,
846                   const char *msg)
847 {
848   struct GNUNET_SERVER_Client *client = cls;
849
850   if (GNUNET_OK == status)
851   {
852     GNUNET_STATISTICS_update (stats,
853                               gettext_noop ("# bytes stored"), size,
854                               GNUNET_YES);
855     GNUNET_CONTAINER_bloomfilter_add (filter, key);
856     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
857                 "Successfully stored %u bytes under key `%s'\n",
858                 size, GNUNET_h2s (key));
859   }
860   transmit_status (client, status, msg);
861   GNUNET_SERVER_client_drop (client);
862   if (quota - reserved - cache_size < payload)
863   {
864     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
865                 _("Need %llu bytes more space (%llu allowed, using %llu)\n"),
866                 (unsigned long long) size + GNUNET_DATASTORE_ENTRY_OVERHEAD,
867                 (unsigned long long) (quota - reserved - cache_size),
868                 (unsigned long long) payload);
869     manage_space (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
870   }
871 }
872
873 /**
874  * Actually put the data message.
875  *
876  * @param client sender of the message
877  * @param dm message with the data to store
878  */
879 static void
880 execute_put (struct GNUNET_SERVER_Client *client, const struct DataMessage *dm)
881 {
882   GNUNET_SERVER_client_keep (client);
883   plugin->api->put (plugin->api->cls, &dm->key, ntohl (dm->size), &dm[1],
884                     ntohl (dm->type), ntohl (dm->priority),
885                     ntohl (dm->anonymity), ntohl (dm->replication),
886                     GNUNET_TIME_absolute_ntoh (dm->expiration),
887                     &put_continuation, client);
888 }
889
890
891 static void
892 check_present_continuation (void *cls, 
893                             int status, 
894                             const char *msg)
895 {
896   struct GNUNET_SERVER_Client *client = cls;
897
898   transmit_status (client, GNUNET_NO, NULL);
899   GNUNET_SERVER_client_drop (client);
900 }
901
902
903 /**
904  * Function that will check if the given datastore entry
905  * matches the put and if none match executes the put.
906  *
907  * @param cls closure, pointer to the client (of type `struct PutContext`).
908  * @param key key for the content
909  * @param size number of bytes in data
910  * @param data content stored
911  * @param type type of the content
912  * @param priority priority of the content
913  * @param anonymity anonymity-level for the content
914  * @param expiration expiration time for the content
915  * @param uid unique identifier for the datum;
916  *        maybe 0 if no unique identifier is available
917  * @return #GNUNET_OK usually
918  *         #GNUNET_NO to delete the item
919  */
920 static int
921 check_present (void *cls, 
922                const struct GNUNET_HashCode *key,
923                uint32_t size,
924                const void *data, 
925                enum GNUNET_BLOCK_Type type, 
926                uint32_t priority,
927                uint32_t anonymity, 
928                struct GNUNET_TIME_Absolute expiration,
929                uint64_t uid)
930 {
931   struct PutContext *pc = cls;
932   const struct DataMessage *dm;
933
934   dm = (const struct DataMessage *) &pc[1];
935   if (key == NULL)
936   {
937     execute_put (pc->client, dm);
938     GNUNET_SERVER_client_drop (pc->client);
939     GNUNET_free (pc);
940     return GNUNET_OK;
941   }
942   if ((GNUNET_BLOCK_TYPE_FS_DBLOCK == type) ||
943       (GNUNET_BLOCK_TYPE_FS_IBLOCK == type) || ((size == ntohl (dm->size)) &&
944                                                 (0 ==
945                                                  memcmp (&dm[1], data, size))))
946   {
947     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
948                 "Result already present in datastore\n");
949     /* FIXME: change API to allow increasing 'replication' counter */
950     if ((ntohl (dm->priority) > 0) ||
951         (GNUNET_TIME_absolute_ntoh (dm->expiration).abs_value_us >
952          expiration.abs_value_us))
953       plugin->api->update (plugin->api->cls, 
954                            uid,
955                            (int32_t) ntohl (dm->priority),
956                            GNUNET_TIME_absolute_ntoh (dm->expiration),
957                            &check_present_continuation,
958                            pc->client);
959     else
960     {
961       transmit_status (pc->client, GNUNET_NO, NULL);
962       GNUNET_SERVER_client_drop (pc->client);
963     }
964     GNUNET_free (pc);
965   }
966   else
967   {
968     execute_put (pc->client, dm);
969     GNUNET_SERVER_client_drop (pc->client);
970     GNUNET_free (pc);
971   }
972   return GNUNET_OK;
973 }
974
975
976 /**
977  * Handle PUT-message.
978  *
979  * @param cls closure
980  * @param client identification of the client
981  * @param message the actual message
982  */
983 static void
984 handle_put (void *cls, struct GNUNET_SERVER_Client *client,
985             const struct GNUNET_MessageHeader *message)
986 {
987   const struct DataMessage *dm = check_data (message);
988   int rid;
989   struct ReservationList *pos;
990   struct PutContext *pc;
991   struct GNUNET_HashCode vhash;
992   uint32_t size;
993
994   if ((dm == NULL) || (ntohl (dm->type) == 0))
995   {
996     GNUNET_break (0);
997     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
998     return;
999   }
1000   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1001               "Processing `%s' request for `%s' of type %u\n", "PUT",
1002               GNUNET_h2s (&dm->key), ntohl (dm->type));
1003   rid = ntohl (dm->rid);
1004   size = ntohl (dm->size);
1005   if (rid > 0)
1006   {
1007     pos = reservations;
1008     while ((NULL != pos) && (rid != pos->rid))
1009       pos = pos->next;
1010     GNUNET_break (pos != NULL);
1011     if (NULL != pos)
1012     {
1013       GNUNET_break (pos->entries > 0);
1014       GNUNET_break (pos->amount >= size);
1015       pos->entries--;
1016       pos->amount -= size;
1017       reserved -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
1018       GNUNET_STATISTICS_set (stats,
1019                              gettext_noop ("# reserved"), reserved,
1020                              GNUNET_NO);
1021     }
1022   }
1023   if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (filter, &dm->key))
1024   {
1025     GNUNET_CRYPTO_hash (&dm[1], size, &vhash);
1026     pc = GNUNET_malloc (sizeof (struct PutContext) + size +
1027                         sizeof (struct DataMessage));
1028     pc->client = client;
1029     GNUNET_SERVER_client_keep (client);
1030     memcpy (&pc[1], dm, size + sizeof (struct DataMessage));
1031     plugin->api->get_key (plugin->api->cls,
1032                           0, 
1033                           &dm->key, 
1034                           &vhash,
1035                           ntohl (dm->type),
1036                           &check_present, 
1037                           pc);
1038     return;
1039   }
1040   execute_put (client, dm);
1041 }
1042
1043
1044 /**
1045  * Handle GET-message.
1046  *
1047  * @param cls closure
1048  * @param client identification of the client
1049  * @param message the actual message
1050  */
1051 static void
1052 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
1053             const struct GNUNET_MessageHeader *message)
1054 {
1055   const struct GetMessage *msg;
1056   uint16_t size;
1057
1058   size = ntohs (message->size);
1059   if ((size != sizeof (struct GetMessage)) &&
1060       (size != sizeof (struct GetMessage) - sizeof (struct GNUNET_HashCode)))
1061   {
1062     GNUNET_break (0);
1063     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1064     return;
1065   }
1066   msg = (const struct GetMessage *) message;
1067   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1068               "Processing `%s' request for `%s' of type %u\n", "GET",
1069               GNUNET_h2s (&msg->key), ntohl (msg->type));
1070   GNUNET_STATISTICS_update (stats,
1071                             gettext_noop ("# GET requests received"), 1,
1072                             GNUNET_NO);
1073   GNUNET_SERVER_client_keep (client);
1074   if ((size == sizeof (struct GetMessage)) &&
1075       (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (filter, &msg->key)))
1076   {
1077     /* don't bother database... */
1078     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1079                 "Empty result set for `%s' request for `%s' (bloomfilter).\n",
1080                 "GET", GNUNET_h2s (&msg->key));
1081     GNUNET_STATISTICS_update (stats,
1082                               gettext_noop
1083                               ("# requests filtered by bloomfilter"), 1,
1084                               GNUNET_NO);
1085     transmit_item (client, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1086                    0);
1087     return;
1088   }
1089   plugin->api->get_key (plugin->api->cls, GNUNET_ntohll (msg->offset),
1090                         ((size ==
1091                           sizeof (struct GetMessage)) ? &msg->key : NULL), NULL,
1092                         ntohl (msg->type), &transmit_item, client);
1093 }
1094
1095
1096 static void
1097 update_continuation (void *cls, 
1098                      int status, 
1099                      const char *msg)
1100 {
1101   struct GNUNET_SERVER_Client *client = cls;
1102
1103   transmit_status (client, status, msg);
1104   GNUNET_SERVER_client_drop (client);
1105 }
1106
1107
1108 /**
1109  * Handle UPDATE-message.
1110  *
1111  * @param cls closure
1112  * @param client identification of the client
1113  * @param message the actual message
1114  */
1115 static void
1116 handle_update (void *cls, struct GNUNET_SERVER_Client *client,
1117                const struct GNUNET_MessageHeader *message)
1118 {
1119   const struct UpdateMessage *msg;
1120
1121   GNUNET_STATISTICS_update (stats, gettext_noop ("# UPDATE requests received"),
1122                             1, GNUNET_NO);
1123   msg = (const struct UpdateMessage *) message;
1124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request for %llu\n",
1125               "UPDATE", (unsigned long long) GNUNET_ntohll (msg->uid));
1126   GNUNET_SERVER_client_keep (client);
1127   plugin->api->update (plugin->api->cls, GNUNET_ntohll (msg->uid),
1128                        (int32_t) ntohl (msg->priority),
1129                        GNUNET_TIME_absolute_ntoh (msg->expiration),
1130                        update_continuation, client);
1131 }
1132
1133
1134 /**
1135  * Handle GET_REPLICATION-message.
1136  *
1137  * @param cls closure
1138  * @param client identification of the client
1139  * @param message the actual message
1140  */
1141 static void
1142 handle_get_replication (void *cls, struct GNUNET_SERVER_Client *client,
1143                         const struct GNUNET_MessageHeader *message)
1144 {
1145   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
1146               "GET_REPLICATION");
1147   GNUNET_STATISTICS_update (stats,
1148                             gettext_noop
1149                             ("# GET REPLICATION requests received"), 1,
1150                             GNUNET_NO);
1151   GNUNET_SERVER_client_keep (client);
1152   plugin->api->get_replication (plugin->api->cls, &transmit_item, client);
1153 }
1154
1155
1156 /**
1157  * Handle GET_ZERO_ANONYMITY-message.
1158  *
1159  * @param cls closure
1160  * @param client identification of the client
1161  * @param message the actual message
1162  */
1163 static void
1164 handle_get_zero_anonymity (void *cls, struct GNUNET_SERVER_Client *client,
1165                            const struct GNUNET_MessageHeader *message)
1166 {
1167   const struct GetZeroAnonymityMessage *msg =
1168       (const struct GetZeroAnonymityMessage *) message;
1169   enum GNUNET_BLOCK_Type type;
1170
1171   type = (enum GNUNET_BLOCK_Type) ntohl (msg->type);
1172   if (type == GNUNET_BLOCK_TYPE_ANY)
1173   {
1174     GNUNET_break (0);
1175     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1176     return;
1177   }
1178   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
1179               "GET_ZERO_ANONYMITY");
1180   GNUNET_STATISTICS_update (stats,
1181                             gettext_noop
1182                             ("# GET ZERO ANONYMITY requests received"), 1,
1183                             GNUNET_NO);
1184   GNUNET_SERVER_client_keep (client);
1185   plugin->api->get_zero_anonymity (plugin->api->cls,
1186                                    GNUNET_ntohll (msg->offset), type,
1187                                    &transmit_item, client);
1188 }
1189
1190
1191 /**
1192  * Callback function that will cause the item that is passed
1193  * in to be deleted (by returning GNUNET_NO).
1194  */
1195 static int
1196 remove_callback (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
1197                  const void *data, enum GNUNET_BLOCK_Type type,
1198                  uint32_t priority, uint32_t anonymity,
1199                  struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1200 {
1201   struct GNUNET_SERVER_Client *client = cls;
1202
1203   if (key == NULL)
1204   {
1205     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1206                 "No further matches for `%s' request.\n", "REMOVE");
1207     transmit_status (client, GNUNET_NO, _("Content not found"));
1208     GNUNET_SERVER_client_drop (client);
1209     return GNUNET_OK;           /* last item */
1210   }
1211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1212               "Item %llu matches `%s' request for key `%s' and type %u.\n",
1213               (unsigned long long) uid, "REMOVE", GNUNET_h2s (key), type);
1214   GNUNET_STATISTICS_update (stats,
1215                             gettext_noop ("# bytes removed (explicit request)"),
1216                             size, GNUNET_YES);
1217   GNUNET_CONTAINER_bloomfilter_remove (filter, key);
1218   transmit_status (client, GNUNET_OK, NULL);
1219   GNUNET_SERVER_client_drop (client);
1220   return GNUNET_NO;
1221 }
1222
1223
1224 /**
1225  * Handle REMOVE-message.
1226  *
1227  * @param cls closure
1228  * @param client identification of the client
1229  * @param message the actual message
1230  */
1231 static void
1232 handle_remove (void *cls, struct GNUNET_SERVER_Client *client,
1233                const struct GNUNET_MessageHeader *message)
1234 {
1235   const struct DataMessage *dm = check_data (message);
1236   struct GNUNET_HashCode vhash;
1237
1238   if (dm == NULL)
1239   {
1240     GNUNET_break (0);
1241     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1242     return;
1243   }
1244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1245               "Processing `%s' request for `%s' of type %u\n", "REMOVE",
1246               GNUNET_h2s (&dm->key), ntohl (dm->type));
1247   GNUNET_STATISTICS_update (stats, gettext_noop ("# REMOVE requests received"),
1248                             1, GNUNET_NO);
1249   GNUNET_SERVER_client_keep (client);
1250   GNUNET_CRYPTO_hash (&dm[1], ntohl (dm->size), &vhash);
1251   plugin->api->get_key (plugin->api->cls, 0, &dm->key, &vhash,
1252                         (enum GNUNET_BLOCK_Type) ntohl (dm->type),
1253                         &remove_callback, client);
1254 }
1255
1256
1257 /**
1258  * Handle DROP-message.
1259  *
1260  * @param cls closure
1261  * @param client identification of the client
1262  * @param message the actual message
1263  */
1264 static void
1265 handle_drop (void *cls, struct GNUNET_SERVER_Client *client,
1266              const struct GNUNET_MessageHeader *message)
1267 {
1268   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1269               "Processing `%s' request\n",
1270               "DROP");
1271   do_drop = GNUNET_YES;
1272   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1273 }
1274
1275
1276 /**
1277  * Function called by plugins to notify us about a
1278  * change in their disk utilization.
1279  *
1280  * @param cls closure (NULL)
1281  * @param delta change in disk utilization,
1282  *        0 for "reset to empty"
1283  */
1284 static void
1285 disk_utilization_change_cb (void *cls,
1286                             int delta)
1287 {
1288   if ((delta < 0) && (payload < -delta))
1289   {
1290     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1291                 _("Datastore payload must have been inaccurate (%lld < %lld). Recomputing it.\n"),
1292                 (long long) payload,
1293                 (long long) -delta);
1294     plugin->api->estimate_size (plugin->api->cls, &payload);
1295     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1296                 _("New payload: %lld\n"),
1297                 (long long) payload);
1298      sync_stats ();
1299     return;
1300   }
1301   payload += delta;
1302   last_sync++;
1303   if (last_sync >= MAX_STAT_SYNC_LAG)
1304     sync_stats ();
1305 }
1306
1307
1308 /**
1309  * Callback function to process statistic values.
1310  *
1311  * @param cls closure (struct Plugin*)
1312  * @param subsystem name of subsystem that created the statistic
1313  * @param name the name of the datum
1314  * @param value the current value
1315  * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
1316  * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
1317  */
1318 static int
1319 process_stat_in (void *cls,
1320                  const char *subsystem,
1321                  const char *name,
1322                  uint64_t value,
1323                  int is_persistent)
1324 {
1325   GNUNET_assert (GNUNET_NO == stats_worked);
1326   stats_worked = GNUNET_YES;
1327   payload += value;
1328   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1329               "Notification from statistics about existing payload (%llu), new payload is %llu\n",
1330               value, payload);
1331   return GNUNET_OK;
1332 }
1333
1334
1335 /**
1336  * Load the datastore plugin.
1337  */
1338 static struct DatastorePlugin *
1339 load_plugin ()
1340 {
1341   struct DatastorePlugin *ret;
1342   char *libname;
1343
1344   ret = GNUNET_new (struct DatastorePlugin);
1345   ret->env.cfg = cfg;
1346   ret->env.duc = &disk_utilization_change_cb;
1347   ret->env.cls = NULL;
1348   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1349               _("Loading `%s' datastore plugin\n"),
1350               plugin_name);
1351   GNUNET_asprintf (&libname,
1352                    "libgnunet_plugin_datastore_%s",
1353                    plugin_name);
1354   ret->short_name = GNUNET_strdup (plugin_name);
1355   ret->lib_name = libname;
1356   ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
1357   if (NULL == ret->api)
1358   {
1359     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1360                 _("Failed to load datastore plugin for `%s'\n"),
1361                 plugin_name);
1362     GNUNET_free (ret->short_name);
1363     GNUNET_free (libname);
1364     GNUNET_free (ret);
1365     return NULL;
1366   }
1367   return ret;
1368 }
1369
1370
1371 /**
1372  * Function called when the service shuts
1373  * down.  Unloads our datastore plugin.
1374  *
1375  * @param plug plugin to unload
1376  */
1377 static void
1378 unload_plugin (struct DatastorePlugin *plug)
1379 {
1380   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1381               "Datastore service is unloading plugin...\n");
1382   GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
1383   GNUNET_free (plug->lib_name);
1384   GNUNET_free (plug->short_name);
1385   GNUNET_free (plug);
1386 }
1387
1388
1389 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1390   {&handle_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE,
1391    sizeof (struct ReserveMessage)},
1392   {&handle_release_reserve, NULL,
1393    GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE,
1394    sizeof (struct ReleaseReserveMessage)},
1395   {&handle_put, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_PUT, 0},
1396   {&handle_update, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE,
1397    sizeof (struct UpdateMessage)},
1398   {&handle_get, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET, 0},
1399   {&handle_get_replication, NULL,
1400    GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION,
1401    sizeof (struct GNUNET_MessageHeader)},
1402   {&handle_get_zero_anonymity, NULL,
1403    GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY,
1404    sizeof (struct GetZeroAnonymityMessage)},
1405   {&handle_remove, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, 0},
1406   {&handle_drop, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_DROP,
1407    sizeof (struct GNUNET_MessageHeader)},
1408   {NULL, NULL, 0, 0}
1409 };
1410
1411
1412 /**
1413  * Adds a given @a key to the bloomfilter in @a cls @a count times.
1414  *
1415  * @param cls the bloomfilter
1416  * @param key key to add
1417  * @param count number of times to add key
1418  */
1419 static void
1420 add_key_to_bloomfilter (void *cls,
1421                         const struct GNUNET_HashCode *key,
1422                         unsigned int count)
1423 {
1424   struct GNUNET_CONTAINER_BloomFilter *bf = cls;
1425
1426   if (NULL == key)
1427   {
1428     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1429                 _("Bloomfilter construction complete.\n"));
1430     GNUNET_SERVER_add_handlers (server, handlers);
1431     GNUNET_SERVER_resume (server);
1432     expired_kill_task
1433       = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1434                                             &delete_expired,
1435                                             NULL);
1436     return;
1437   }
1438
1439   while (0 < count--)
1440     GNUNET_CONTAINER_bloomfilter_add (bf, key);
1441 }
1442
1443
1444 /**
1445  * We finished receiving the statistic.  Initialize the plugin; if
1446  * loading the statistic failed, run the estimator.
1447  *
1448  * @param cls NULL
1449  * @param success #GNUNET_NO if we failed to read the stat
1450  */
1451 static void
1452 process_stat_done (void *cls, int success)
1453 {
1454
1455   stat_get = NULL;
1456   plugin = load_plugin ();
1457   if (NULL == plugin)
1458   {
1459     GNUNET_CONTAINER_bloomfilter_free (filter);
1460     filter = NULL;
1461     if (NULL != stats)
1462     {
1463       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1464       stats = NULL;
1465     }
1466     return;
1467   }
1468   if (GNUNET_NO == stats_worked)
1469   {
1470     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1471                 "Failed to obtain value from statistics service, recomputing it\n");
1472     plugin->api->estimate_size (plugin->api->cls, &payload);
1473   }
1474   if (GNUNET_YES == refresh_bf)
1475   {
1476     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1477                 _("Rebuilding bloomfilter.  Please be patient.\n"));
1478     if (NULL != plugin->api->get_keys)
1479     {
1480       plugin->api->get_keys (plugin->api->cls,
1481                              &add_key_to_bloomfilter,
1482                              filter);
1483       return;
1484     }
1485     else
1486       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1487                   _("Plugin does not support get_keys function. Please fix!\n"));
1488
1489     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1490                 _("Bloomfilter construction complete.\n"));
1491   }
1492
1493   GNUNET_SERVER_add_handlers (server, handlers);
1494   GNUNET_SERVER_resume (server);
1495   expired_kill_task
1496     = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1497                                           &delete_expired,
1498                                           NULL);
1499 }
1500
1501
1502 /**
1503  * Task run during shutdown.
1504  */
1505 static void
1506 cleaning_task (void *cls,
1507                const struct GNUNET_SCHEDULER_TaskContext *tc)
1508 {
1509   struct TransmitCallbackContext *tcc;
1510
1511   cleaning_done = GNUNET_YES;
1512   while (NULL != (tcc = tcc_head))
1513   {
1514     GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
1515     if (tcc->th != NULL)
1516     {
1517       GNUNET_SERVER_notify_transmit_ready_cancel (tcc->th);
1518       GNUNET_SERVER_client_drop (tcc->client);
1519     }
1520     GNUNET_free (tcc->msg);
1521     GNUNET_free (tcc);
1522   }
1523   if (NULL != expired_kill_task)
1524   {
1525     GNUNET_SCHEDULER_cancel (expired_kill_task);
1526     expired_kill_task = NULL;
1527   }
1528   if (GNUNET_YES == do_drop)
1529     plugin->api->drop (plugin->api->cls);
1530   if (NULL != plugin)
1531   {
1532     unload_plugin (plugin);
1533     plugin = NULL;
1534   }
1535   if (NULL != filter)
1536   {
1537     GNUNET_CONTAINER_bloomfilter_free (filter);
1538     filter = NULL;
1539   }
1540   if (NULL != stat_get)
1541   {
1542     GNUNET_STATISTICS_get_cancel (stat_get);
1543     stat_get = NULL;
1544   }
1545   GNUNET_free_non_null (plugin_name);
1546   plugin_name = NULL;
1547   if (last_sync > 0)
1548     sync_stats ();
1549   if (NULL != stats)
1550   {
1551     GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1552     stats = NULL;
1553   }
1554   GNUNET_free (quota_stat_name);
1555   quota_stat_name = NULL;
1556 }
1557
1558
1559 /**
1560  * Function that removes all active reservations made
1561  * by the given client and releases the space for other
1562  * requests.
1563  *
1564  * @param cls closure
1565  * @param client identification of the client
1566  */
1567 static void
1568 cleanup_reservations (void *cls,
1569                       struct GNUNET_SERVER_Client *client)
1570 {
1571   struct ReservationList *pos;
1572   struct ReservationList *prev;
1573   struct ReservationList *next;
1574
1575   if (NULL == client)
1576     return;
1577   prev = NULL;
1578   pos = reservations;
1579   while (NULL != pos)
1580   {
1581     next = pos->next;
1582     if (pos->client == client)
1583     {
1584       if (NULL == prev)
1585         reservations = next;
1586       else
1587         prev->next = next;
1588       reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD;
1589       GNUNET_free (pos);
1590     }
1591     else
1592     {
1593       prev = pos;
1594     }
1595     pos = next;
1596   }
1597   GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
1598                          GNUNET_NO);
1599 }
1600
1601
1602 /**
1603  * Process datastore requests.
1604  *
1605  * @param cls closure
1606  * @param serv the initialized server
1607  * @param c configuration to use
1608  */
1609 static void
1610 run (void *cls,
1611      struct GNUNET_SERVER_Handle *serv,
1612      const struct GNUNET_CONFIGURATION_Handle *c)
1613 {
1614   char *fn;
1615   char *pfn;
1616   unsigned int bf_size;
1617
1618   server = serv;
1619   cfg = c;
1620   if (GNUNET_OK !=
1621       GNUNET_CONFIGURATION_get_value_string (cfg, "DATASTORE", "DATABASE",
1622                                              &plugin_name))
1623   {
1624     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1625                 _("No `%s' specified for `%s' in configuration!\n"), "DATABASE",
1626                 "DATASTORE");
1627     return;
1628   }
1629   GNUNET_asprintf (&quota_stat_name,
1630                    _("# bytes used in file-sharing datastore `%s'"),
1631                    plugin_name);
1632   if (GNUNET_OK !=
1633       GNUNET_CONFIGURATION_get_value_size (cfg, "DATASTORE", "QUOTA", &quota))
1634   {
1635     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1636                 _("No `%s' specified for `%s' in configuration!\n"), "QUOTA",
1637                 "DATASTORE");
1638     return;
1639   }
1640   stats = GNUNET_STATISTICS_create ("datastore", cfg);
1641   GNUNET_STATISTICS_set (stats, gettext_noop ("# quota"), quota, GNUNET_NO);
1642   cache_size = quota / 8;       /* Or should we make this an option? */
1643   GNUNET_STATISTICS_set (stats, gettext_noop ("# cache size"), cache_size,
1644                          GNUNET_NO);
1645   if (quota / (32 * 1024LL) > (1 << 31))
1646     bf_size = (1 << 31);          /* absolute limit: ~2 GB, beyond that BF just won't help anyway */
1647   else
1648     bf_size = quota / (32 * 1024LL);         /* 8 bit per entry, 1 bit per 32 kb in DB */
1649   fn = NULL;
1650   if ((GNUNET_OK !=
1651        GNUNET_CONFIGURATION_get_value_filename (cfg, "DATASTORE", "BLOOMFILTER",
1652                                                 &fn)) ||
1653       (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn)))
1654   {
1655     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1656                 _("Could not use specified filename `%s' for bloomfilter.\n"),
1657                 NULL != fn ? fn : "");
1658     GNUNET_free_non_null (fn);
1659     fn = NULL;
1660   }
1661   if (NULL != fn)
1662   {
1663     GNUNET_asprintf (&pfn, "%s.%s", fn, plugin_name);
1664     if (GNUNET_YES == GNUNET_DISK_file_test (pfn))
1665     {
1666       filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5);        /* approx. 3% false positives at max use */
1667       if (NULL == filter)
1668       {
1669         /* file exists but not valid, remove and try again, but refresh */
1670         if (0 != UNLINK (pfn))
1671         {
1672           /* failed to remove, run without file */
1673           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1674                       _("Failed to remove bogus bloomfilter file `%s'\n"),
1675                       pfn);
1676           GNUNET_free (pfn);
1677           pfn = NULL;
1678           filter = GNUNET_CONTAINER_bloomfilter_load (NULL, bf_size, 5);        /* approx. 3% false positives at max use */
1679           refresh_bf = GNUNET_YES;
1680         }
1681         else
1682         {
1683           /* try again after remove */
1684           filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5);        /* approx. 3% false positives at max use */
1685           refresh_bf = GNUNET_YES;
1686           if (NULL == filter)
1687           {
1688             /* failed yet again, give up on using file */
1689             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1690                         _("Failed to remove bogus bloomfilter file `%s'\n"),
1691                         pfn);
1692             GNUNET_free (pfn);
1693             pfn = NULL;
1694             filter = GNUNET_CONTAINER_bloomfilter_init (NULL, bf_size, 5);        /* approx. 3% false positives at max use */
1695           }
1696         }
1697       }
1698       else
1699       {
1700         /* normal case: have an existing valid bf file, no need to refresh */
1701         refresh_bf = GNUNET_NO;
1702       }
1703     }
1704     else
1705     {
1706       filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5);        /* approx. 3% false positives at max use */
1707       refresh_bf = GNUNET_YES;
1708     }
1709     GNUNET_free (pfn);
1710   }
1711   else
1712   {
1713     filter = GNUNET_CONTAINER_bloomfilter_init (NULL, bf_size, 5);      /* approx. 3% false positives at max use */
1714     refresh_bf = GNUNET_YES;
1715   }
1716   GNUNET_free_non_null (fn);
1717   if (NULL == filter)
1718   {
1719     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1720                 _("Failed to initialize bloomfilter.\n"));
1721     if (NULL != stats)
1722     {
1723       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1724       stats = NULL;
1725     }
1726     return;
1727   }
1728   GNUNET_SERVER_suspend (server);
1729   stat_get =
1730       GNUNET_STATISTICS_get (stats,
1731                              "datastore",
1732                              quota_stat_name,
1733                              GNUNET_TIME_UNIT_SECONDS,
1734                              &process_stat_done,
1735                              &process_stat_in,
1736                              NULL);
1737   if (NULL == stat_get)
1738     process_stat_done (NULL, GNUNET_SYSERR);
1739   GNUNET_SERVER_disconnect_notify (server,
1740                                    &cleanup_reservations,
1741                                    NULL);
1742   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1743                                 &cleaning_task,
1744                                 NULL);
1745 }
1746
1747
1748 /**
1749  * The main function for the datastore service.
1750  *
1751  * @param argc number of arguments from the command line
1752  * @param argv command line arguments
1753  * @return 0 ok, 1 on error
1754  */
1755 int
1756 main (int argc,
1757       char *const *argv)
1758 {
1759   int ret;
1760
1761   ret =
1762       (GNUNET_OK ==
1763        GNUNET_SERVICE_run (argc, argv, "datastore",
1764                            GNUNET_SERVICE_OPTION_NONE,
1765                            &run, NULL)) ? 0 : 1;
1766   return ret;
1767 }
1768
1769
1770 /* end of gnunet-service-datastore.c */