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