missing function reference
[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_arm_service.h"
30 #include "gnunet_protocols.h"
31 #include "plugin_datastore.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
47 /**
48  * Our datastore plugin.
49  */
50 struct DatastorePlugin
51 {
52
53   /**
54    * API of the transport as returned by the plugin's
55    * initialization function.
56    */
57   struct GNUNET_DATASTORE_PluginFunctions *api;
58
59   /**
60    * Short name for the plugin (i.e. "sqlite").
61    */
62   char *short_name;
63
64   /**
65    * Name of the library (i.e. "gnunet_plugin_datastore_sqlite").
66    */
67   char *lib_name;
68
69   /**
70    * Environment this transport service is using
71    * for this plugin.
72    */
73   struct GNUNET_DATASTORE_PluginEnvironment env;
74
75 };
76
77
78 /**
79  * Linked list of active reservations.
80  */
81 struct ReservationList 
82 {
83
84   /**
85    * This is a linked list.
86    */
87   struct ReservationList *next;
88
89   /**
90    * Client that made the reservation.
91    */
92   struct GNUNET_SERVER_Client *client;
93
94   /**
95    * Number of bytes (still) reserved.
96    */
97   uint64_t amount;
98
99   /**
100    * Number of items (still) reserved.
101    */
102   uint64_t entries;
103
104   /**
105    * Reservation identifier.
106    */
107   int32_t rid;
108
109 };
110
111
112 /**
113  * Our datastore plugin (NULL if not available).
114  */
115 static struct DatastorePlugin *plugin;
116
117 /**
118  * Linked list of space reservations made by clients.
119  */
120 static struct ReservationList *reservations;
121
122 /**
123  * Bloomfilter to quickly tell if we don't have the content.
124  */
125 static struct GNUNET_CONTAINER_BloomFilter *filter;
126
127 /**
128  * Static counter to produce reservation identifiers.
129  */
130 static int reservation_gen;
131
132 /**
133  * How much space are we allowed to use?
134  */
135 static unsigned long long quota;
136
137 /**
138  * How much space are we using for the cache?  (space available for
139  * insertions that will be instantly reclaimed by discarding less
140  * important content --- or possibly whatever we just inserted into
141  * the "cache").
142  */
143 static unsigned long long cache_size;
144
145 /**
146  * How much space have we currently reserved?
147  */
148 static unsigned long long reserved;
149
150 /**
151  * Identity of the task that is used to delete
152  * expired content.
153  */
154 static GNUNET_SCHEDULER_TaskIdentifier expired_kill_task;
155
156 /**
157  * Our configuration.
158  */
159 const struct GNUNET_CONFIGURATION_Handle *cfg;
160
161 /**
162  * Our scheduler.
163  */
164 struct GNUNET_SCHEDULER_Handle *sched; 
165
166 /**
167  * Function called once the transmit operation has
168  * either failed or succeeded.
169  *
170  * @param cls closure
171  * @param status GNUNET_OK on success, GNUNET_SYSERR on error
172  */
173 typedef void (*TransmitContinuation)(void *cls,
174                                      int status);
175
176
177 struct TransmitCallbackContext 
178 {
179   /**
180    * The message that we're asked to transmit.
181    */
182   struct GNUNET_MessageHeader *msg;
183
184   /**
185    * Client that we are transmitting to.
186    */
187   struct GNUNET_SERVER_Client *client;
188
189   /**
190    * Function to call once msg has been transmitted
191    * (or at least added to the buffer).
192    */
193   TransmitContinuation tc;
194
195   /**
196    * Closure for tc.
197    */
198   void *tc_cls;
199
200   /**
201    * GNUNET_YES if we are supposed to signal the server
202    * completion of the client's request.
203    */
204   int end;
205 };
206
207
208 /**
209  * Task that is used to remove expired entries from
210  * the datastore.  This task will schedule itself
211  * again automatically to always delete all expired
212  * content quickly.
213  *
214  * @param cls not used
215  * @param tc task context
216  */ 
217 static void
218 delete_expired (void *cls,
219                 const struct GNUNET_SCHEDULER_TaskContext *tc);
220
221
222 /**
223  * Iterate over the expired items stored in the datastore.
224  * Delete all expired items; once we have processed all
225  * expired items, re-schedule the "delete_expired" task.
226  *
227  * @param cls not used
228  * @param next_cls closure to pass to the "next" function.
229  * @param key key for the content
230  * @param size number of bytes in data
231  * @param data content stored
232  * @param type type of the content
233  * @param priority priority of the content
234  * @param anonymity anonymity-level for the content
235  * @param expiration expiration time for the content
236  * @param uid unique identifier for the datum;
237  *        maybe 0 if no unique identifier is available
238  *
239  * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
240  *         (continue on call to "next", of course),
241  *         GNUNET_NO to delete the item and continue (if supported)
242  */
243 static int 
244 expired_processor (void *cls,
245                    void *next_cls,
246                    const GNUNET_HashCode * key,
247                    uint32_t size,
248                    const void *data,
249                    uint32_t type,
250                    uint32_t priority,
251                    uint32_t anonymity,
252                    struct GNUNET_TIME_Absolute
253                    expiration, 
254                    uint64_t uid)
255 {
256   struct GNUNET_TIME_Absolute now;
257
258   expired_kill_task = GNUNET_SCHEDULER_NO_TASK;
259   if (key == NULL) 
260     {
261       expired_kill_task 
262         = GNUNET_SCHEDULER_add_delayed (sched,
263                                         MAX_EXPIRE_DELAY,
264                                         &delete_expired,
265                                         NULL);
266       return GNUNET_SYSERR;
267     }
268   now = GNUNET_TIME_absolute_get ();
269   if (expiration.value > now.value)
270     {
271       /* finished processing */
272       plugin->api->next_request (next_cls, GNUNET_YES);
273       return GNUNET_SYSERR;
274     }
275   plugin->api->next_request (next_cls, GNUNET_NO);
276 #if DEBUG_DATASTORE
277   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
278               "Deleting content that expired %llu ms ago\n",
279               (unsigned long long) (now.value - expiration.value));
280 #endif
281   GNUNET_CONTAINER_bloomfilter_remove (filter,
282                                        key);
283   return GNUNET_NO; /* delete */
284 }
285
286
287 /**
288  * Task that is used to remove expired entries from
289  * the datastore.  This task will schedule itself
290  * again automatically to always delete all expired
291  * content quickly.
292  *
293  * @param cls not used
294  * @param tc task context
295  */ 
296 static void
297 delete_expired (void *cls,
298                 const struct GNUNET_SCHEDULER_TaskContext *tc)
299 {
300   plugin->api->iter_ascending_expiration (plugin->api->cls, 
301                                           0,
302                                           &expired_processor,
303                                           NULL);
304 }
305
306
307 /**
308  * An iterator over a set of items stored in the datastore.
309  *
310  * @param cls closure
311  * @param next_cls closure to pass to the "next" function.
312  * @param key key for the content
313  * @param size number of bytes in data
314  * @param data content stored
315  * @param type type of the content
316  * @param priority priority of the content
317  * @param anonymity anonymity-level for the content
318  * @param expiration expiration time for the content
319  * @param uid unique identifier for the datum;
320  *        maybe 0 if no unique identifier is available
321  *
322  * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
323  *         (continue on call to "next", of course),
324  *         GNUNET_NO to delete the item and continue (if supported)
325  */
326 static int 
327 manage (void *cls,
328         void *next_cls,
329         const GNUNET_HashCode * key,
330         uint32_t size,
331         const void *data,
332         uint32_t type,
333         uint32_t priority,
334         uint32_t anonymity,
335         struct GNUNET_TIME_Absolute
336         expiration, 
337         uint64_t uid)
338 {
339   unsigned long long *need = cls;
340
341   if (NULL == key)
342     {
343       GNUNET_free (need);
344       return GNUNET_SYSERR;
345     }
346   if (size + GNUNET_DATASTORE_ENTRY_OVERHEAD > *need)
347     *need = 0;
348   else
349     *need -= size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
350   plugin->api->next_request (next_cls, 
351                              (0 == *need) ? GNUNET_YES : GNUNET_NO);
352 #if DEBUG_DATASTORE
353   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
354               "Deleting %llu bytes of low-priority content (still trying to free another %llu bytes)\n",
355               size + GNUNET_DATASTORE_ENTRY_OVERHEAD,
356               *need);
357 #endif
358   GNUNET_CONTAINER_bloomfilter_remove (filter,
359                                        key);
360   return GNUNET_NO;
361 }
362
363
364 /**
365  * Manage available disk space by running tasks
366  * that will discard content if necessary.  This
367  * function will be run whenever a request for
368  * "need" bytes of storage could only be satisfied
369  * by eating into the "cache" (and we want our cache
370  * space back).
371  *
372  * @param need number of bytes of content that were
373  *        placed into the "cache" (and hence the
374  *        number of bytes that should be removed).
375  */
376 static void
377 manage_space (unsigned long long need)
378 {
379   unsigned long long *n;
380
381 #if DEBUG_DATASTORE
382   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
383               "Asked to free up %llu bytes of cache space\n",
384               need);
385 #endif
386   n = GNUNET_malloc (sizeof(unsigned long long));
387   *n = need;
388   plugin->api->iter_low_priority (plugin->api->cls,
389                                   0,
390                                   &manage,
391                                   n);
392 }
393
394
395 /**
396  * Function called to notify a client about the socket
397  * begin ready to queue more data.  "buf" will be
398  * NULL and "size" zero if the socket was closed for
399  * writing in the meantime.
400  *
401  * @param cls closure
402  * @param size number of bytes available in buf
403  * @param buf where the callee should write the message
404  * @return number of bytes written to buf
405  */
406 static size_t
407 transmit_callback (void *cls,
408                    size_t size, void *buf)
409 {
410   struct TransmitCallbackContext *tcc = cls;
411   size_t msize;
412   
413   msize = ntohs(tcc->msg->size);
414   if (size == 0)
415     {
416 #if DEBUG_DATASTORE
417       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
418                   "Transmission failed.\n");
419 #endif
420       if (tcc->tc != NULL)
421         tcc->tc (tcc->tc_cls, GNUNET_SYSERR);
422       if (GNUNET_YES == tcc->end)
423         {
424           GNUNET_SERVER_receive_done (tcc->client, GNUNET_SYSERR);
425         }
426       GNUNET_free (tcc->msg);
427       GNUNET_free (tcc);
428       return 0;
429     }
430   GNUNET_assert (size >= msize);
431   memcpy (buf, tcc->msg, msize);
432   if (tcc->tc != NULL)
433     tcc->tc (tcc->tc_cls, GNUNET_OK);
434   if (GNUNET_YES == tcc->end)
435     {
436       GNUNET_SERVER_receive_done (tcc->client, GNUNET_OK);
437     }
438   else
439     {
440 #if DEBUG_DATASTORE
441       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
442                   "Response transmitted, more pending!\n");
443 #endif
444     }
445   GNUNET_free (tcc->msg);
446   GNUNET_free (tcc);
447   return msize;
448 }
449
450
451 /**
452  * Transmit the given message to the client.
453  *
454  * @param client target of the message
455  * @param msg message to transmit, will be freed!
456  * @param tc function to call afterwards
457  * @param tc_cls closure for tc
458  * @param end is this the last response (and we should
459  *        signal the server completion accodingly after
460  *        transmitting this message)?
461  */
462 static void
463 transmit (struct GNUNET_SERVER_Client *client,
464           struct GNUNET_MessageHeader *msg,
465           TransmitContinuation tc,
466           void *tc_cls,
467           int end)
468 {
469   struct TransmitCallbackContext *tcc;
470
471   tcc = GNUNET_malloc (sizeof(struct TransmitCallbackContext));
472   tcc->msg = msg;
473   tcc->client = client;
474   tcc->tc = tc;
475   tcc->tc_cls = tc_cls;
476   tcc->end = end;
477
478   if (NULL ==
479       GNUNET_SERVER_notify_transmit_ready (client,
480                                            ntohs(msg->size),
481                                            GNUNET_TIME_UNIT_FOREVER_REL,
482                                            &transmit_callback,
483                                            tcc))
484     {
485       GNUNET_break (0);
486       if (GNUNET_YES == end)
487         {
488 #if DEBUG_DATASTORE
489           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
490                       "Disconnecting client.\n");
491 #endif    
492           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
493         }
494       if (NULL != tc)
495         tc (tc_cls, GNUNET_SYSERR);
496       GNUNET_free (msg);
497       GNUNET_free (tcc);
498     }
499 }
500
501
502 /**
503  * Transmit a status code to the client.
504  *
505  * @param client receiver of the response
506  * @param code status code
507  * @param msg optional error message (can be NULL)
508  */
509 static void
510 transmit_status (struct GNUNET_SERVER_Client *client,
511                  int code,
512                  const char *msg)
513 {
514   struct StatusMessage *sm;
515   size_t slen;
516
517 #if DEBUG_DATASTORE
518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
519               "Transmitting `%s' message with value %d and message `%s'\n",
520               "STATUS",
521               code,
522               msg != NULL ? msg : "(none)");
523 #endif
524   slen = (msg == NULL) ? 0 : strlen(msg) + 1;  
525   sm = GNUNET_malloc (sizeof(struct StatusMessage) + slen);
526   sm->header.size = htons(sizeof(struct StatusMessage) + slen);
527   sm->header.type = htons(GNUNET_MESSAGE_TYPE_DATASTORE_STATUS);
528   sm->status = htonl(code);
529   if (slen > 0)
530     memcpy (&sm[1], msg, slen);  
531   transmit (client, &sm->header, NULL, NULL, GNUNET_YES);
532 }
533
534
535 /**
536  * Function called once the transmit operation has
537  * either failed or succeeded.
538  *
539  * @param next_cls closure for calling "next_request" callback
540  * @param status GNUNET_OK on success, GNUNET_SYSERR on error
541  */
542 static void 
543 get_next(void *next_cls,
544          int status)
545 {
546   if (status != GNUNET_OK)
547     {
548       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
549                   _("Failed to transmit an item to the client; aborting iteration.\n"));    
550       plugin->api->next_request (next_cls, GNUNET_YES);
551       return;
552     }
553   plugin->api->next_request (next_cls, GNUNET_NO);
554 }
555
556
557 /**
558  * Function that will transmit the given datastore entry
559  * to the client.
560  *
561  * @param cls closure, pointer to the client (of type GNUNET_SERVER_Client).
562  * @param next_cls closure to use to ask for the next item
563  * @param key key for the content
564  * @param size number of bytes in data
565  * @param data content stored
566  * @param type type of the content
567  * @param priority priority of the content
568  * @param anonymity anonymity-level for the content
569  * @param expiration expiration time for the content
570  * @param uid unique identifier for the datum;
571  *        maybe 0 if no unique identifier is available
572  *
573  * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue,
574  *         GNUNET_NO to delete the item and continue (if supported)
575  */
576 static int
577 transmit_item (void *cls,
578                void *next_cls,
579                const GNUNET_HashCode * key,
580                uint32_t size,
581                const void *data,
582                uint32_t type,
583                uint32_t priority,
584                uint32_t anonymity,
585                struct GNUNET_TIME_Absolute
586                expiration, uint64_t uid)
587 {
588   struct GNUNET_SERVER_Client *client = cls;
589   struct GNUNET_MessageHeader *end;
590   struct DataMessage *dm;
591
592   if (key == NULL)
593     {
594       /* transmit 'DATA_END' */
595 #if DEBUG_DATASTORE
596       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
597                   "Transmitting `%s' message\n",
598                   "DATA_END");
599 #endif
600       end = GNUNET_malloc (sizeof(struct GNUNET_MessageHeader));
601       end->size = htons(sizeof(struct GNUNET_MessageHeader));
602       end->type = htons(GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END);
603       transmit (client, end, NULL, NULL, GNUNET_YES);
604       GNUNET_SERVER_client_drop (client);
605       return GNUNET_OK;
606     }
607   dm = GNUNET_malloc (sizeof(struct DataMessage) + size);
608   dm->header.size = htons(sizeof(struct DataMessage) + size);
609   dm->header.type = htons(GNUNET_MESSAGE_TYPE_DATASTORE_DATA);
610   dm->rid = htonl(0);
611   dm->size = htonl(size);
612   dm->type = htonl(type);
613   dm->priority = htonl(priority);
614   dm->anonymity = htonl(anonymity);
615   dm->expiration = GNUNET_TIME_absolute_hton(expiration);
616   dm->uid = GNUNET_htonll(uid);
617   dm->key = *key;
618   memcpy (&dm[1], data, size);
619 #if DEBUG_DATASTORE
620   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
621               "Transmitting `%s' message\n",
622               "DATA");
623 #endif
624   transmit (client, &dm->header, &get_next, next_cls, GNUNET_NO);
625   return GNUNET_OK;
626 }
627
628
629 /**
630  * Handle RESERVE-message.
631  *
632  * @param cls closure
633  * @param client identification of the client
634  * @param message the actual message
635  */
636 static void
637 handle_reserve (void *cls,
638                 struct GNUNET_SERVER_Client *client,
639                 const struct GNUNET_MessageHeader *message)
640 {
641   const struct ReserveMessage *msg = (const struct ReserveMessage*) message;
642   struct ReservationList *e;
643   unsigned long long used;
644   unsigned long long req;
645   uint64_t amount;
646   uint32_t entries;
647
648 #if DEBUG_DATASTORE
649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
650               "Processing `%s' request\n",
651               "RESERVE");
652 #endif
653   amount = GNUNET_ntohll(msg->amount);
654   entries = ntohl(msg->entries);
655   used = plugin->api->get_size (plugin->api->cls) + reserved;
656   req = 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                   _("Insufficient space (%llu bytes are available) to satisfy `%s' request for %llu bytes\n"),
663                   quota - used,
664                   "RESERVE",
665                   req);
666       if (cache_size < req)
667         {
668           /* TODO: document this in the FAQ; essentially, if this
669              message happens, the insertion request could be blocked
670              by less-important content from migration because it is
671              larger than 1/8th of the overall available space, and
672              we only reserve 1/8th for "fresh" insertions */
673           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
674                       _("The requested amount (%llu bytes) is larger than the cache size (%llu bytes)\n"),
675                       req,
676                       cache_size);
677           transmit_status (client, 0, 
678                            gettext_noop ("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   e = GNUNET_malloc (sizeof(struct ReservationList));
690   e->next = reservations;
691   reservations = e;
692   e->client = client;
693   e->amount = amount;
694   e->entries = entries;
695   e->rid = ++reservation_gen;
696   if (reservation_gen < 0)
697     reservation_gen = 0; /* wrap around */
698   transmit_status (client, e->rid, NULL);
699 }
700
701
702 /**
703  * Handle RELEASE_RESERVE-message.
704  *
705  * @param cls closure
706  * @param client identification of the client
707  * @param message the actual message
708  */
709 static void
710 handle_release_reserve (void *cls,
711                         struct GNUNET_SERVER_Client *client,
712                         const struct GNUNET_MessageHeader *message)
713 {
714   const struct ReleaseReserveMessage *msg = (const struct ReleaseReserveMessage*) message;
715   struct ReservationList *pos;
716   struct ReservationList *prev;
717   struct ReservationList *next;
718   int rid = ntohl(msg->rid);
719   unsigned long long rem;
720
721 #if DEBUG_DATASTORE
722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
723               "Processing `%s' request\n",
724               "RELEASE_RESERVE");
725 #endif
726   next = reservations;
727   prev = NULL;
728   while (NULL != (pos = next))
729     {
730       next = pos->next;
731       if (rid == pos->rid)
732         {
733           if (prev == NULL)
734             reservations = next;
735           else
736             prev->next = next;
737           rem = pos->amount + ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * pos->entries;
738           GNUNET_assert (reserved >= rem);
739           reserved -= rem;
740 #if DEBUG_DATASTORE
741           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
742                       "Returning %llu remaining reserved bytes to storage pool\n",
743                       rem);
744 #endif    
745           GNUNET_free (pos);
746           transmit_status (client, GNUNET_OK, NULL);
747           return;
748         }       
749       prev = pos;
750     }
751   GNUNET_break (0);
752   transmit_status (client, GNUNET_SYSERR, gettext_noop ("Could not find matching reservation"));
753 }
754
755
756 /**
757  * Check that the given message is a valid data message.
758  *
759  * @return NULL if the message is not well-formed, otherwise the message
760  */
761 static const struct DataMessage *
762 check_data (const struct GNUNET_MessageHeader *message)
763 {
764   uint16_t size;
765   uint32_t dsize;
766   const struct DataMessage *dm;
767
768   size = ntohs(message->size);
769   if (size < sizeof(struct DataMessage))
770     { 
771       GNUNET_break (0);
772       return NULL;
773     }
774   dm = (const struct DataMessage *) message;
775   dsize = ntohl(dm->size);
776   if (size != dsize + sizeof(struct DataMessage))
777     {
778       GNUNET_break (0);
779       return NULL;
780     }
781   return dm;
782 }
783
784
785 /**
786  * Handle PUT-message.
787  *
788  * @param cls closure
789  * @param client identification of the client
790  * @param message the actual message
791  */
792 static void
793 handle_put (void *cls,
794             struct GNUNET_SERVER_Client *client,
795             const struct GNUNET_MessageHeader *message)
796 {
797   const struct DataMessage *dm = check_data (message);
798   char *msg;
799   int ret;
800   int rid;
801   struct ReservationList *pos;
802   uint32_t size;
803
804 #if DEBUG_DATASTORE
805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
806               "Processing `%s' request\n",
807               "PUT");
808 #endif
809   if (ntohl(dm->type) == 0) 
810     {
811       GNUNET_break (0);
812       dm = NULL;
813     }
814   if (dm == NULL)
815     {
816       GNUNET_break (0);
817       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
818       return;
819     }
820   rid = ntohl(dm->rid);
821   size = ntohl(dm->size);
822   if (rid > 0)
823     {
824       pos = reservations;
825       while ( (NULL != pos) &&
826               (rid != pos->rid) )
827         pos = pos->next;
828       GNUNET_break (pos != NULL);
829       if (NULL != pos)
830         {
831           GNUNET_break (pos->entries > 0);
832           GNUNET_break (pos->amount > size);
833           pos->entries--;
834           pos->amount -= size;
835           reserved -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
836         }
837     }
838   msg = NULL;
839   ret = plugin->api->put (plugin->api->cls,
840                           &dm->key,
841                           size,
842                           &dm[1],
843                           ntohl(dm->type),
844                           ntohl(dm->priority),
845                           ntohl(dm->anonymity),
846                           GNUNET_TIME_absolute_ntoh(dm->expiration),
847                           &msg);
848   if (GNUNET_OK == ret)
849     {
850       GNUNET_CONTAINER_bloomfilter_add (filter,
851                                         &dm->key);
852 #if DEBUG_DATASTORE
853       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
854                   "Successfully stored %u bytes under key `%s'\n",
855                   size,
856                   GNUNET_h2s (&dm->key));
857 #endif
858     }
859   transmit_status (client, 
860                    (GNUNET_SYSERR == ret) ? GNUNET_SYSERR : GNUNET_OK, 
861                    msg);
862   GNUNET_free_non_null (msg);
863   if (quota - reserved - cache_size < plugin->api->get_size (plugin->api->cls))
864     manage_space (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
865 }
866
867
868 /**
869  * Handle GET-message.
870  *
871  * @param cls closure
872  * @param client identification of the client
873  * @param message the actual message
874  */
875 static void
876 handle_get (void *cls,
877              struct GNUNET_SERVER_Client *client,
878              const struct GNUNET_MessageHeader *message)
879 {
880   const struct GetMessage *msg;
881   uint16_t size;
882
883 #if DEBUG_DATASTORE
884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
885               "Processing `%s' request\n",
886               "GET");
887 #endif
888   size = ntohs(message->size);
889   if ( (size != sizeof(struct GetMessage)) &&
890        (size != sizeof(struct GetMessage) - sizeof(GNUNET_HashCode)) )
891     {
892       GNUNET_break (0);
893       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
894       return;
895     }
896   msg = (const struct GetMessage*) message;
897   if ( (size == sizeof(struct GetMessage)) &&
898        (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (filter,
899                                                          &msg->key)) )
900     {
901       /* don't bother database... */
902 #if DEBUG_DATASTORE
903       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
904                   "Empty result set for `%s' request for `%s'.\n",
905                   "GET",
906                   GNUNET_h2s (&msg->key));
907 #endif  
908       GNUNET_SERVER_client_keep (client);
909       transmit_item (client,
910                      NULL, NULL, 0, NULL, 0, 0, 0, 
911                      GNUNET_TIME_UNIT_ZERO_ABS, 0);
912       return;
913     }
914   GNUNET_SERVER_client_keep (client);
915   plugin->api->get (plugin->api->cls,
916                     ((size == sizeof(struct GetMessage)) ? &msg->key : NULL),
917                     NULL,
918                     ntohl(msg->type),
919                     &transmit_item,
920                     client);    
921 }
922
923
924 /**
925  * Handle UPDATE-message.
926  *
927  * @param cls closure
928  * @param client identification of the client
929  * @param message the actual message
930  */
931 static void
932 handle_update (void *cls,
933                struct GNUNET_SERVER_Client *client,
934                const struct GNUNET_MessageHeader *message)
935 {
936   const struct UpdateMessage *msg;
937   int ret;
938   char *emsg;
939
940 #if DEBUG_DATASTORE
941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
942               "Processing `%s' request\n",
943               "UPDATE");
944 #endif
945   msg = (const struct UpdateMessage*) message;
946   emsg = NULL;
947   ret = plugin->api->update (plugin->api->cls,
948                              GNUNET_ntohll(msg->uid),
949                              (int32_t) ntohl(msg->priority),
950                              GNUNET_TIME_absolute_ntoh(msg->expiration),
951                              &emsg);
952   transmit_status (client, ret, emsg);
953   GNUNET_free_non_null (emsg);
954 }
955
956
957 /**
958  * Handle GET_RANDOM-message.
959  *
960  * @param cls closure
961  * @param client identification of the client
962  * @param message the actual message
963  */
964 static void
965 handle_get_random (void *cls,
966                    struct GNUNET_SERVER_Client *client,
967                    const struct GNUNET_MessageHeader *message)
968 {
969 #if DEBUG_DATASTORE
970   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
971               "Processing `%s' request\n",
972               "GET_RANDOM");
973 #endif
974   GNUNET_SERVER_client_keep (client);
975   plugin->api->iter_migration_order (plugin->api->cls,
976                                      0,
977                                      &transmit_item,
978                                      client);  
979 }
980
981
982 /**
983  * Context for the 'remove_callback'.
984  */
985 struct RemoveContext 
986 {
987   /**
988    * Client for whom we're doing the remvoing.
989    */
990   struct GNUNET_SERVER_Client *client;
991
992   /**
993    * GNUNET_YES if we managed to remove something.
994    */
995   int found;
996 };
997
998
999 /**
1000  * Callback function that will cause the item that is passed
1001  * in to be deleted (by returning GNUNET_NO).
1002  */
1003 static int
1004 remove_callback (void *cls,
1005                  void *next_cls,
1006                  const GNUNET_HashCode * key,
1007                  uint32_t size,
1008                  const void *data,
1009                  uint32_t type,
1010                  uint32_t priority,
1011                  uint32_t anonymity,
1012                  struct GNUNET_TIME_Absolute
1013                  expiration, uint64_t uid)
1014 {
1015   struct RemoveContext *rc = cls;
1016
1017   if (key == NULL)
1018     {
1019 #if DEBUG_DATASTORE
1020       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1021                   "No further matches for `%s' request.\n",
1022                   "REMOVE");
1023 #endif  
1024       if (GNUNET_YES == rc->found)
1025         transmit_status (rc->client, GNUNET_OK, NULL);       
1026       else
1027         transmit_status (rc->client, GNUNET_NO, _("Content not found"));        
1028       GNUNET_SERVER_client_drop (rc->client);
1029       GNUNET_free (rc);
1030       return GNUNET_OK; /* last item */
1031     }
1032   rc->found = GNUNET_YES;
1033 #if DEBUG_DATASTORE
1034   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1035               "Item %llu matches `%s' request.\n",
1036               (unsigned long long) uid,
1037               "REMOVE");
1038 #endif  
1039   GNUNET_CONTAINER_bloomfilter_remove (filter,
1040                                        key);
1041   plugin->api->next_request (next_cls, GNUNET_YES);
1042   return GNUNET_NO;
1043 }
1044
1045
1046 /**
1047  * Handle REMOVE-message.
1048  *
1049  * @param cls closure
1050  * @param client identification of the client
1051  * @param message the actual message
1052  */
1053 static void
1054 handle_remove (void *cls,
1055              struct GNUNET_SERVER_Client *client,
1056              const struct GNUNET_MessageHeader *message)
1057 {
1058   const struct DataMessage *dm = check_data (message);
1059   GNUNET_HashCode vhash;
1060   struct RemoveContext *rc;
1061
1062 #if DEBUG_DATASTORE
1063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1064               "Processing `%s' request\n",
1065               "REMOVE");
1066 #endif
1067   if (dm == NULL)
1068     {
1069       GNUNET_break (0);
1070       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1071       return;
1072     }
1073   rc = GNUNET_malloc (sizeof(struct RemoveContext));
1074   GNUNET_SERVER_client_keep (client);
1075   rc->client = client;
1076   GNUNET_CRYPTO_hash (&dm[1],
1077                       ntohl(dm->size),
1078                       &vhash);
1079   plugin->api->get (plugin->api->cls,
1080                     &dm->key,
1081                     &vhash,
1082                     ntohl(dm->type),
1083                     &remove_callback,
1084                     rc);
1085 }
1086
1087
1088 /**
1089  * Handle DROP-message.
1090  *
1091  * @param cls closure
1092  * @param client identification of the client
1093  * @param message the actual message
1094  */
1095 static void
1096 handle_drop (void *cls,
1097              struct GNUNET_SERVER_Client *client,
1098              const struct GNUNET_MessageHeader *message)
1099 {
1100 #if DEBUG_DATASTORE
1101   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1102               "Processing `%s' request\n",
1103               "DROP");
1104 #endif
1105   plugin->api->drop (plugin->api->cls);
1106   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1107 }
1108
1109
1110 /**
1111  * List of handlers for the messages understood by this
1112  * service.
1113  */
1114 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1115   {&handle_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE, 
1116    sizeof(struct ReserveMessage) }, 
1117   {&handle_release_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE, 
1118    sizeof(struct ReleaseReserveMessage) }, 
1119   {&handle_put, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_PUT, 0 }, 
1120   {&handle_update, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE, 
1121    sizeof (struct UpdateMessage) }, 
1122   {&handle_get, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET, 0 }, 
1123   {&handle_get_random, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET_RANDOM, 
1124    sizeof(struct GNUNET_MessageHeader) }, 
1125   {&handle_remove, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, 0 }, 
1126   {&handle_drop, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_DROP, 
1127    sizeof(struct GNUNET_MessageHeader) }, 
1128   {NULL, NULL, 0, 0}
1129 };
1130
1131
1132
1133 /**
1134  * Load the datastore plugin.
1135  */
1136 static struct DatastorePlugin *
1137 load_plugin () 
1138 {
1139   struct DatastorePlugin *ret;
1140   char *libname;
1141   char *name;
1142
1143   if (GNUNET_OK !=
1144       GNUNET_CONFIGURATION_get_value_string (cfg,
1145                                              "DATASTORE", "DATABASE", &name))
1146     {
1147       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1148                   _("No `%s' specified for `%s' in configuration!\n"),
1149                   "DATABASE",
1150                   "DATASTORE");
1151       return NULL;
1152     }
1153   ret = GNUNET_malloc (sizeof(struct DatastorePlugin));
1154   ret->env.cfg = cfg;
1155   ret->env.sched = sched;  
1156   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1157               _("Loading `%s' datastore plugin\n"), name);
1158   GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", name);
1159   ret->short_name = name;
1160   ret->lib_name = libname;
1161   ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
1162   if (ret->api == NULL)
1163     {
1164       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1165                   _("Failed to load datastore plugin for `%s'\n"), name);
1166       GNUNET_free (ret->short_name);
1167       GNUNET_free (libname);
1168       GNUNET_free (ret);
1169       return NULL;
1170     }
1171   return ret;
1172 }
1173
1174
1175 /**
1176  * Function called when the service shuts
1177  * down.  Unloads our datastore plugin.
1178  *
1179  * @param plug plugin to unload
1180  */
1181 static void
1182 unload_plugin (struct DatastorePlugin *plug)
1183 {
1184 #if DEBUG_DATASTORE
1185   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1186               "Datastore service is unloading plugin...\n");
1187 #endif
1188   GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
1189   GNUNET_free (plug->lib_name);
1190   GNUNET_free (plug->short_name);
1191   GNUNET_free (plug);
1192 }
1193
1194
1195 /**
1196  * Last task run during shutdown.  Disconnects us from
1197  * the transport and core.
1198  */
1199 static void
1200 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1201 {
1202   if (expired_kill_task != GNUNET_SCHEDULER_NO_TASK)
1203     {
1204       GNUNET_SCHEDULER_cancel (sched,
1205                                expired_kill_task);
1206       expired_kill_task = GNUNET_SCHEDULER_NO_TASK;
1207     }
1208   unload_plugin (plugin);
1209   plugin = NULL;
1210   if (filter != NULL)
1211     {
1212       GNUNET_CONTAINER_bloomfilter_free (filter);
1213       filter = NULL;
1214     }
1215   GNUNET_ARM_stop_services (cfg, tc->sched, "statistics", NULL);
1216 }
1217
1218
1219 /**
1220  * Function that removes all active reservations made
1221  * by the given client and releases the space for other
1222  * requests.
1223  *
1224  * @param cls closure
1225  * @param client identification of the client
1226  */
1227 static void
1228 cleanup_reservations (void *cls,
1229                       struct GNUNET_SERVER_Client
1230                       * client)
1231 {
1232   struct ReservationList *pos;
1233   struct ReservationList *prev;
1234   struct ReservationList *next;
1235
1236   if (client == NULL)
1237     return;
1238   prev = NULL;
1239   pos = reservations;
1240   while (NULL != pos)
1241     {
1242       next = pos->next;
1243       if (pos->client == client)
1244         {
1245           if (prev == NULL)
1246             reservations = next;
1247           else
1248             prev->next = next;
1249           reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD;
1250           GNUNET_free (pos);
1251         }
1252       else
1253         {
1254           prev = pos;
1255         }
1256       pos = next;
1257     }
1258 }
1259
1260
1261 /**
1262  * Process datastore requests.
1263  *
1264  * @param cls closure
1265  * @param s scheduler to use
1266  * @param server the initialized server
1267  * @param c configuration to use
1268  */
1269 static void
1270 run (void *cls,
1271      struct GNUNET_SCHEDULER_Handle *s,
1272      struct GNUNET_SERVER_Handle *server,
1273      const struct GNUNET_CONFIGURATION_Handle *c)
1274 {
1275   char *fn;
1276   unsigned int bf_size;
1277
1278   sched = s;
1279   cfg = c;
1280   if (GNUNET_OK !=
1281       GNUNET_CONFIGURATION_get_value_number (cfg,
1282                                              "DATASTORE", "QUOTA", &quota))
1283     {
1284       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1285                   _("No `%s' specified for `%s' in configuration!\n"),
1286                   "QUOTA",
1287                   "DATASTORE");
1288       return;
1289     }
1290   cache_size = quota / 8; /* Or should we make this an option? */
1291   bf_size = quota / 32; /* 8 bit per entry, 1 bit per 32 kb in DB */
1292   fn = NULL;
1293   if ( (GNUNET_OK !=
1294         GNUNET_CONFIGURATION_get_value_filename (cfg,
1295                                                  "DATASTORE",
1296                                                  "BLOOMFILTER",
1297                                                  &fn)) ||
1298        (GNUNET_OK !=
1299         GNUNET_DISK_directory_create_for_file (fn)) )
1300     {
1301       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1302                   _("Could not use specified filename `%s' for bloomfilter.\n"),
1303                   fn != NULL ? fn : "");
1304       GNUNET_free_non_null (fn);
1305       fn = NULL;
1306     }
1307   filter = GNUNET_CONTAINER_bloomfilter_load (fn, bf_size, 5);  /* approx. 3% false positives at max use */  
1308   GNUNET_free_non_null (fn);
1309   if (filter == NULL)
1310     {
1311       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1312                   _("Failed to initialize bloomfilter.\n"));
1313       return;
1314     }
1315   GNUNET_ARM_start_services (cfg, sched, "statistics", NULL);
1316   plugin = load_plugin ();
1317   if (NULL == plugin)
1318     {
1319       GNUNET_CONTAINER_bloomfilter_free (filter);
1320       filter = NULL;
1321       GNUNET_ARM_stop_services (cfg, sched, "statistics", NULL);
1322       return;
1323     }
1324   GNUNET_SERVER_disconnect_notify (server, &cleanup_reservations, NULL);
1325   GNUNET_SERVER_add_handlers (server, handlers);
1326   expired_kill_task
1327     = GNUNET_SCHEDULER_add_with_priority (sched,
1328                                           GNUNET_SCHEDULER_PRIORITY_IDLE,
1329                                           &delete_expired, NULL);
1330   GNUNET_SCHEDULER_add_delayed (sched,
1331                                 GNUNET_TIME_UNIT_FOREVER_REL,
1332                                 &cleaning_task, NULL);
1333   
1334 }
1335
1336
1337 /**
1338  * The main function for the datastore service.
1339  *
1340  * @param argc number of arguments from the command line
1341  * @param argv command line arguments
1342  * @return 0 ok, 1 on error
1343  */
1344 int
1345 main (int argc, char *const *argv)
1346 {
1347   int ret;
1348
1349   ret = (GNUNET_OK ==
1350          GNUNET_SERVICE_run (argc,
1351                              argv,
1352                              "datastore",
1353                              GNUNET_SERVICE_OPTION_NONE,
1354                              &run, NULL)) ? 0 : 1;
1355   return ret;
1356 }
1357
1358
1359 /* end of gnunet-service-datastore.c */