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