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