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