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