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