b0719b69bc1ce7d018498af2ab3125683d5152aa
[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 "plugin_datastore.h"
31 #include "datastore.h"
32
33 /**
34  * How many messages do we queue at most per client?
35  */
36 #define MAX_PENDING 1024
37
38 /**
39  * How long are we at most keeping "expired" content
40  * past the expiration date in the database?
41  */
42 #define MAX_EXPIRE_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
43
44
45
46 /**
47  * Our datastore plugin.
48  */
49 struct DatastorePlugin
50 {
51
52   /**
53    * API of the transport as returned by the plugin's
54    * initialization function.
55    */
56   struct GNUNET_DATASTORE_PluginFunctions *api;
57
58   /**
59    * Short name for the plugin (i.e. "sqlite").
60    */
61   char *short_name;
62
63   /**
64    * Name of the library (i.e. "gnunet_plugin_datastore_sqlite").
65    */
66   char *lib_name;
67
68   /**
69    * Environment this transport service is using
70    * for this plugin.
71    */
72   struct GNUNET_DATASTORE_PluginEnvironment env;
73
74 };
75
76
77 /**
78  * Linked list of active reservations.
79  */
80 struct ReservationList 
81 {
82
83   /**
84    * This is a linked list.
85    */
86   struct ReservationList *next;
87
88   /**
89    * Client that made the reservation.
90    */
91   struct GNUNET_SERVER_Client *client;
92
93   /**
94    * Number of bytes (still) reserved.
95    */
96   uint64_t amount;
97
98   /**
99    * Number of items (still) reserved.
100    */
101   uint64_t entries;
102
103   /**
104    * Reservation identifier.
105    */
106   int32_t rid;
107
108 };
109
110
111 /**
112  * Our datastore plugin (NULL if not available).
113  */
114 static struct DatastorePlugin *plugin;
115
116 /**
117  * Linked list of space reservations made by clients.
118  */
119 static struct ReservationList *reservations;
120
121 /**
122  * Bloomfilter to quickly tell if we don't have the content.
123  */
124 static struct GNUNET_CONTAINER_BloomFilter *filter;
125
126 /**
127  * Static counter to produce reservation identifiers.
128  */
129 static int reservation_gen;
130
131 /**
132  * How much space are we allowed to use?
133  */
134 static unsigned long long quota;
135
136 /**
137  * How much space are we using for the cache?
138  * (space available for insertions that will be
139  *  instantly reclaimed by discarding less 
140  *  important content --- or possibly whatever
141  *  we just inserted into 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 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                                         GNUNET_NO,
264                                         GNUNET_SCHEDULER_PRIORITY_IDLE,
265                                         GNUNET_SCHEDULER_NO_TASK,
266                                         MAX_EXPIRE_DELAY,
267                                         &delete_expired,
268                                         NULL);
269       return GNUNET_SYSERR;
270     }
271   now = GNUNET_TIME_absolute_get ();
272   if (expiration.value > now.value)
273     {
274       /* finished processing */
275       plugin->api->next_request (next_cls, GNUNET_YES);
276       return GNUNET_SYSERR;
277     }
278   plugin->api->next_request (next_cls, GNUNET_NO);
279 #if DEBUG_DATASTORE
280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
281               "Deleting content that expired %llu ms ago\n",
282               (unsigned long long) (now.value - expiration.value));
283 #endif
284   GNUNET_CONTAINER_bloomfilter_remove (filter,
285                                        key);
286   return GNUNET_NO; /* delete */
287 }
288
289
290 /**
291  * Task that is used to remove expired entries from
292  * the datastore.  This task will schedule itself
293  * again automatically to always delete all expired
294  * content quickly.
295  *
296  * @param cls not used
297  * @param tc task context
298  */ 
299 static void
300 delete_expired (void *cls,
301                 const struct GNUNET_SCHEDULER_TaskContext *tc)
302 {
303   plugin->api->iter_ascending_expiration (plugin->api->cls, 
304                                           0,
305                                           &expired_processor,
306                                           NULL);
307 }
308
309
310 /**
311  * An iterator over a set of items stored in the datastore.
312  *
313  * @param cls closure
314  * @param next_cls closure to pass to the "next" function.
315  * @param key key for the content
316  * @param size number of bytes in data
317  * @param data content stored
318  * @param type type of the content
319  * @param priority priority of the content
320  * @param anonymity anonymity-level for the content
321  * @param expiration expiration time for the content
322  * @param uid unique identifier for the datum;
323  *        maybe 0 if no unique identifier is available
324  *
325  * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
326  *         (continue on call to "next", of course),
327  *         GNUNET_NO to delete the item and continue (if supported)
328  */
329 static int 
330 manage (void *cls,
331         void *next_cls,
332         const GNUNET_HashCode * key,
333         uint32_t size,
334         const void *data,
335         uint32_t type,
336         uint32_t priority,
337         uint32_t anonymity,
338         struct GNUNET_TIME_Absolute
339         expiration, 
340         uint64_t uid)
341 {
342   unsigned long long *need = cls;
343
344   if (NULL == key)
345     {
346       GNUNET_free (need);
347       return GNUNET_SYSERR;
348     }
349   if (size + GNUNET_DATASTORE_ENTRY_OVERHEAD > *need)
350     *need = 0;
351   else
352     *need -= size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
353   plugin->api->next_request (next_cls, 
354                              (0 == *need) ? GNUNET_YES : GNUNET_NO);
355 #if DEBUG_DATASTORE
356   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
357               "Deleting %llu bytes of low-priority content (still trying to recover %llu bytes)\n",
358               size + GNUNET_DATASTORE_ENTRY_OVERHEAD,
359               *need);
360 #endif
361   GNUNET_CONTAINER_bloomfilter_remove (filter,
362                                        key);
363   return GNUNET_NO;
364 }
365
366
367 /**
368  * Manage available disk space by running tasks
369  * that will discard content if necessary.  This
370  * function will be run whenever a request for
371  * "need" bytes of storage could only be satisfied
372  * by eating into the "cache" (and we want our cache
373  * space back).
374  *
375  * @param need number of bytes of content that were
376  *        placed into the "cache" (and hence the
377  *        number of bytes that should be removed).
378  */
379 static void
380 manage_space (unsigned long long need)
381 {
382   unsigned long long *n;
383
384 #if DEBUG_DATASTORE
385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
386               "Asked to recover %llu bytes of cache space\n",
387               need);
388 #endif
389   n = GNUNET_malloc (sizeof(unsigned long long));
390   *n = need;
391   plugin->api->iter_low_priority (plugin->api->cls,
392                                   0,
393                                   &manage,
394                                   n);
395 }
396
397
398 /**
399  * Function called to notify a client about the socket
400  * begin ready to queue more data.  "buf" will be
401  * NULL and "size" zero if the socket was closed for
402  * writing in the meantime.
403  *
404  * @param cls closure
405  * @param size number of bytes available in buf
406  * @param buf where the callee should write the message
407  * @return number of bytes written to buf
408  */
409 static size_t
410 transmit_callback (void *cls,
411                    size_t size, void *buf)
412 {
413   struct TransmitCallbackContext *tcc = cls;
414   size_t msize;
415   
416   msize = ntohs(tcc->msg->size);
417   if (size == 0)
418     {
419 #if DEBUG_DATASTORE
420       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
421                   "Transmission failed.\n");
422 #endif
423       if (tcc->tc != NULL)
424         tcc->tc (tcc->tc_cls, GNUNET_SYSERR);
425       if (GNUNET_YES == tcc->end)
426         {
427           GNUNET_SERVER_receive_done (tcc->client, GNUNET_SYSERR);
428         }
429       GNUNET_free (tcc->msg);
430       GNUNET_free (tcc);
431       return 0;
432     }
433   GNUNET_assert (size >= msize);
434   memcpy (buf, tcc->msg, msize);
435   if (tcc->tc != NULL)
436     tcc->tc (tcc->tc_cls, GNUNET_OK);
437   if (GNUNET_YES == tcc->end)
438     {
439       GNUNET_SERVER_receive_done (tcc->client, GNUNET_OK);
440     }
441   else
442     {
443 #if DEBUG_DATASTORE
444       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
445                   "Response transmitted, more pending!\n");
446 #endif
447     }
448   GNUNET_free (tcc->msg);
449   GNUNET_free (tcc);
450   return msize;
451 }
452
453
454 /**
455  * Transmit the given message to the client.
456  *
457  * @param client target of the message
458  * @param msg message to transmit, will be freed!
459  * @param end is this the last response (and we should
460  *        signal the server completion accodingly after
461  *        transmitting this message)?
462  */
463 static void
464 transmit (struct GNUNET_SERVER_Client *client,
465           struct GNUNET_MessageHeader *msg,
466           TransmitContinuation tc,
467           void *tc_cls,
468           int end)
469 {
470   struct TransmitCallbackContext *tcc;
471
472   tcc = GNUNET_malloc (sizeof(struct TransmitCallbackContext));
473   tcc->msg = msg;
474   tcc->client = client;
475   tcc->tc = tc;
476   tcc->tc_cls = tc_cls;
477   tcc->end = end;
478
479   if (NULL ==
480       GNUNET_SERVER_notify_transmit_ready (client,
481                                            ntohs(msg->size),
482                                            GNUNET_TIME_UNIT_FOREVER_REL,
483                                            &transmit_callback,
484                                            tcc))
485     {
486       GNUNET_break (0);
487       if (GNUNET_YES == end)
488         {
489 #if DEBUG_DATASTORE
490           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
491                       "Disconnecting client.\n");
492 #endif    
493           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
494         }
495       if (NULL != tc)
496         tc (tc_cls, GNUNET_SYSERR);
497       GNUNET_free (msg);
498       GNUNET_free (tcc);
499     }
500 }
501
502
503 /**
504  * Transmit a status code to the client.
505  *
506  * @param client receiver of the response
507  * @param code status code
508  * @param msg optional error message (can be NULL)
509  */
510 static void
511 transmit_status (struct GNUNET_SERVER_Client *client,
512                  int code,
513                  const char *msg)
514 {
515   struct StatusMessage *sm;
516   size_t slen;
517
518 #if DEBUG_DATASTORE
519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
520               "Transmitting `%s' message with value %d and message `%s'\n",
521               "STATUS",
522               code,
523               msg != NULL ? msg : "(none)");
524 #endif
525   slen = (msg == NULL) ? 0 : strlen(msg) + 1;  
526   sm = GNUNET_malloc (sizeof(struct StatusMessage) + slen);
527   sm->header.size = htons(sizeof(struct StatusMessage) + slen);
528   sm->header.type = htons(GNUNET_MESSAGE_TYPE_DATASTORE_STATUS);
529   sm->status = htonl(code);
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 cls closure
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       pos = next;
751     }
752   GNUNET_break (0);
753   transmit_status (client, GNUNET_SYSERR, gettext_noop ("Could not find matching reservation"));
754 }
755
756
757 /**
758  * Check that the given message is a valid data message.
759  *
760  * @return NULL if the message is not well-formed, otherwise the message
761  */
762 static const struct DataMessage *
763 check_data (const struct GNUNET_MessageHeader *message)
764 {
765   uint16_t size;
766   uint32_t dsize;
767   const struct DataMessage *dm;
768
769   size = ntohs(message->size);
770   if (size < sizeof(struct DataMessage))
771     { 
772       GNUNET_break (0);
773       return NULL;
774     }
775   dm = (const struct DataMessage *) message;
776   dsize = ntohl(dm->size);
777   if (size != dsize + sizeof(struct DataMessage))
778     {
779       GNUNET_break (0);
780       return NULL;
781     }
782   return dm;
783 }
784
785
786 /**
787  * Handle PUT-message.
788  *
789  * @param cls closure
790  * @param client identification of the client
791  * @param message the actual message
792  */
793 static void
794 handle_put (void *cls,
795             struct GNUNET_SERVER_Client *client,
796             const struct GNUNET_MessageHeader *message)
797 {
798   const struct DataMessage *dm = check_data (message);
799   char *msg;
800   int ret;
801   int rid;
802   struct ReservationList *pos;
803   uint32_t size;
804
805 #if DEBUG_DATASTORE
806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
807               "Processing `%s' request\n",
808               "PUT");
809 #endif
810   if (ntohl(dm->type) == 0) 
811     {
812       GNUNET_break (0);
813       dm = NULL;
814     }
815   if (dm == NULL)
816     {
817       GNUNET_break (0);
818       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
819       return;
820     }
821   rid = ntohl(dm->rid);
822   size = ntohl(dm->size);
823   if (rid > 0)
824     {
825       pos = reservations;
826       while ( (NULL != pos) &&
827               (rid != pos->rid) )
828         pos = pos->next;
829       GNUNET_break (pos != NULL);
830       if (NULL != pos)
831         {
832           GNUNET_break (pos->entries > 0);
833           GNUNET_break (pos->amount > size);
834           pos->entries--;
835           pos->amount -= size;
836           reserved -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
837         }
838     }
839   msg = NULL;
840   ret = plugin->api->put (plugin->api->cls,
841                           &dm->key,
842                           size,
843                           &dm[1],
844                           ntohl(dm->type),
845                           ntohl(dm->priority),
846                           ntohl(dm->anonymity),
847                           GNUNET_TIME_absolute_ntoh(dm->expiration),
848                           &msg);
849   if (GNUNET_OK == ret)
850     GNUNET_CONTAINER_bloomfilter_add (filter,
851                                       &dm->key);
852   transmit_status (client, 
853                    (GNUNET_SYSERR == ret) ? GNUNET_SYSERR : GNUNET_OK, 
854                    msg);
855   GNUNET_free_non_null (msg);
856   if (quota - reserved - cache_size < plugin->api->get_size (plugin->api->cls))
857     manage_space (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
858 }
859
860
861 /**
862  * Handle GET-message.
863  *
864  * @param cls closure
865  * @param client identification of the client
866  * @param message the actual message
867  */
868 static void
869 handle_get (void *cls,
870              struct GNUNET_SERVER_Client *client,
871              const struct GNUNET_MessageHeader *message)
872 {
873   static struct GNUNET_TIME_Absolute zero;
874   const struct GetMessage *msg;
875   uint16_t size;
876
877 #if DEBUG_DATASTORE
878   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
879               "Processing `%s' request\n",
880               "GET");
881 #endif
882   size = ntohs(message->size);
883   if ( (size != sizeof(struct GetMessage)) &&
884        (size != sizeof(struct GetMessage) - sizeof(GNUNET_HashCode)) )
885     {
886       GNUNET_break (0);
887       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
888       return;
889     }
890   msg = (const struct GetMessage*) message;
891   if ( (size == sizeof(struct GetMessage)) &&
892        (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (filter,
893                                                          &msg->key)) )
894     {
895       /* don't bother database... */
896 #if DEBUG_DATASTORE
897       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898                   "Empty result set for `%s' request.\n",
899                   "GET");
900 #endif  
901       transmit_item (client,
902                      NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
903       return;
904     }
905   GNUNET_SERVER_client_keep (client);
906   plugin->api->get (plugin->api->cls,
907                     ((size == sizeof(struct GetMessage)) ? &msg->key : NULL),
908                     NULL,
909                     ntohl(msg->type),
910                     &transmit_item,
911                     client);    
912 }
913
914
915 /**
916  * Handle UPDATE-message.
917  *
918  * @param cls closure
919  * @param client identification of the client
920  * @param message the actual message
921  */
922 static void
923 handle_update (void *cls,
924                struct GNUNET_SERVER_Client *client,
925                const struct GNUNET_MessageHeader *message)
926 {
927   const struct UpdateMessage *msg;
928   int ret;
929   char *emsg;
930
931 #if DEBUG_DATASTORE
932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
933               "Processing `%s' request\n",
934               "UPDATE");
935 #endif
936   msg = (const struct UpdateMessage*) message;
937   emsg = NULL;
938   ret = plugin->api->update (plugin->api->cls,
939                              GNUNET_ntohll(msg->uid),
940                              (int32_t) ntohl(msg->priority),
941                              GNUNET_TIME_absolute_ntoh(msg->expiration),
942                              &emsg);
943   transmit_status (client, ret, emsg);
944   GNUNET_free_non_null (emsg);
945 }
946
947
948 /**
949  * Handle GET_RANDOM-message.
950  *
951  * @param cls closure
952  * @param client identification of the client
953  * @param message the actual message
954  */
955 static void
956 handle_get_random (void *cls,
957                    struct GNUNET_SERVER_Client *client,
958                    const struct GNUNET_MessageHeader *message)
959 {
960 #if DEBUG_DATASTORE
961   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
962               "Processing `%s' request\n",
963               "GET_RANDOM");
964 #endif
965   GNUNET_SERVER_client_keep (client);
966   plugin->api->iter_migration_order (plugin->api->cls,
967                                      0,
968                                      &transmit_item,
969                                      client);  
970 }
971
972
973 /**
974  * Context for the 'remove_callback'.
975  */
976 struct RemoveContext 
977 {
978   /**
979    * Client for whom we're doing the remvoing.
980    */
981   struct GNUNET_SERVER_Client *client;
982
983   /**
984    * GNUNET_YES if we managed to remove something.
985    */
986   int found;
987 };
988
989
990 /**
991  * Callback function that will cause the item that is passed
992  * in to be deleted (by returning GNUNET_NO).
993  */
994 static int
995 remove_callback (void *cls,
996                  void *next_cls,
997                  const GNUNET_HashCode * key,
998                  uint32_t size,
999                  const void *data,
1000                  uint32_t type,
1001                  uint32_t priority,
1002                  uint32_t anonymity,
1003                  struct GNUNET_TIME_Absolute
1004                  expiration, uint64_t uid)
1005 {
1006   struct RemoveContext *rc = cls;
1007
1008   if (key == NULL)
1009     {
1010 #if DEBUG_DATASTORE
1011       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1012                   "No further matches for `%s' request.\n",
1013                   "REMOVE");
1014 #endif  
1015       if (GNUNET_YES == rc->found)
1016         transmit_status (rc->client, GNUNET_OK, NULL);       
1017       else
1018         transmit_status (rc->client, GNUNET_SYSERR, _("Content not found"));            
1019       GNUNET_SERVER_client_drop (rc->client);
1020       GNUNET_free (rc);
1021       return GNUNET_OK; /* last item */
1022     }
1023   rc->found = GNUNET_YES;
1024 #if DEBUG_DATASTORE
1025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1026               "Item %llu matches `%s' request.\n",
1027               (unsigned long long) uid,
1028               "REMOVE");
1029 #endif  
1030   GNUNET_CONTAINER_bloomfilter_remove (filter,
1031                                        key);
1032   plugin->api->next_request (next_cls, GNUNET_YES);
1033   return GNUNET_NO;
1034 }
1035
1036
1037 /**
1038  * Handle REMOVE-message.
1039  *
1040  * @param cls closure
1041  * @param client identification of the client
1042  * @param message the actual message
1043  */
1044 static void
1045 handle_remove (void *cls,
1046              struct GNUNET_SERVER_Client *client,
1047              const struct GNUNET_MessageHeader *message)
1048 {
1049   const struct DataMessage *dm = check_data (message);
1050   GNUNET_HashCode vhash;
1051   struct RemoveContext *rc;
1052
1053 #if DEBUG_DATASTORE
1054   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1055               "Processing `%s' request\n",
1056               "REMOVE");
1057 #endif
1058   if (dm == NULL)
1059     {
1060       GNUNET_break (0);
1061       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1062       return;
1063     }
1064   rc = GNUNET_malloc (sizeof(struct RemoveContext));
1065   GNUNET_SERVER_client_keep (client);
1066   rc->client = client;
1067   GNUNET_CRYPTO_hash (&dm[1],
1068                       ntohl(dm->size),
1069                       &vhash);
1070   GNUNET_SERVER_client_keep (client);
1071   plugin->api->get (plugin->api->cls,
1072                     &dm->key,
1073                     &vhash,
1074                     ntohl(dm->type),
1075                     &remove_callback,
1076                     rc);
1077 }
1078
1079
1080 /**
1081  * Handle DROP-message.
1082  *
1083  * @param cls closure
1084  * @param client identification of the client
1085  * @param message the actual message
1086  */
1087 static void
1088 handle_drop (void *cls,
1089              struct GNUNET_SERVER_Client *client,
1090              const struct GNUNET_MessageHeader *message)
1091 {
1092 #if DEBUG_DATASTORE
1093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1094               "Processing `%s' request\n",
1095               "DROP");
1096 #endif
1097   plugin->api->drop (plugin->api->cls);
1098   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1099 }
1100
1101
1102 /**
1103  * List of handlers for the messages understood by this
1104  * service.
1105  */
1106 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1107   {&handle_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE, 
1108    sizeof(struct ReserveMessage) }, 
1109   {&handle_release_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE, 
1110    sizeof(struct ReleaseReserveMessage) }, 
1111   {&handle_put, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_PUT, 0 }, 
1112   {&handle_update, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE, 
1113    sizeof (struct UpdateMessage) }, 
1114   {&handle_get, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET, 0 }, 
1115   {&handle_get_random, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET_RANDOM, 
1116    sizeof(struct GNUNET_MessageHeader) }, 
1117   {&handle_remove, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, 0 }, 
1118   {&handle_drop, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_DROP, 
1119    sizeof(struct GNUNET_MessageHeader) }, 
1120   {NULL, NULL, 0, 0}
1121 };
1122
1123
1124
1125 /**
1126  * Load the datastore plugin.
1127  */
1128 static struct DatastorePlugin *
1129 load_plugin () 
1130 {
1131   struct DatastorePlugin *ret;
1132   char *libname;
1133   char *name;
1134
1135   if (GNUNET_OK !=
1136       GNUNET_CONFIGURATION_get_value_string (cfg,
1137                                              "DATASTORE", "DATABASE", &name))
1138     {
1139       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1140                   _("No `%s' specified for `%s' in configuration!\n"),
1141                   "DATABASE",
1142                   "DATASTORE");
1143       return NULL;
1144     }
1145   ret = GNUNET_malloc (sizeof(struct DatastorePlugin));
1146   ret->env.cfg = cfg;
1147   ret->env.sched = sched;  
1148   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1149               _("Loading `%s' datastore plugin\n"), name);
1150   GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", name);
1151   ret->short_name = name;
1152   ret->lib_name = libname;
1153   ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
1154   if (ret->api == NULL)
1155     {
1156       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1157                   _("Failed to load datastore plugin for `%s'\n"), name);
1158       GNUNET_free (ret->short_name);
1159       GNUNET_free (libname);
1160       GNUNET_free (ret);
1161       return NULL;
1162     }
1163   return ret;
1164 }
1165
1166
1167 /**
1168  * Function called when the service shuts
1169  * down.  Unloads our datastore plugin.
1170  *
1171  * @param plug plugin to unload
1172  */
1173 static void
1174 unload_plugin (struct DatastorePlugin *plug)
1175 {
1176 #if DEBUG_DATASTORE
1177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1178               "Datastore service is unloading plugin...\n");
1179 #endif
1180   GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
1181   GNUNET_free (plug->lib_name);
1182   GNUNET_free (plug->short_name);
1183   GNUNET_free (plug);
1184 }
1185
1186
1187 /**
1188  * Last task run during shutdown.  Disconnects us from
1189  * the transport and core.
1190  */
1191 static void
1192 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1193 {
1194   unload_plugin (plugin);
1195   plugin = NULL;
1196 }
1197
1198
1199 /**
1200  * Function that removes all active reservations made
1201  * by the given client and releases the space for other
1202  * requests.
1203  *
1204  * @param cls closure
1205  * @param client identification of the client
1206  */
1207 static void
1208 cleanup_reservations (void *cls,
1209                       struct GNUNET_SERVER_Client
1210                       * client)
1211 {
1212   struct ReservationList *pos;
1213   struct ReservationList *prev;
1214   struct ReservationList *next;
1215
1216   prev = NULL;
1217   pos = reservations;
1218   while (NULL != pos)
1219     {
1220       next = pos->next;
1221       if (pos->client == client)
1222         {
1223           if (prev == NULL)
1224             reservations = next;
1225           else
1226             prev->next = next;
1227           reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD;
1228           GNUNET_free (pos);
1229         }
1230       else
1231         {
1232           prev = pos;
1233         }
1234       pos = next;
1235     }
1236 }
1237
1238
1239 /**
1240  * Process datastore requests.
1241  *
1242  * @param cls closure
1243  * @param s scheduler to use
1244  * @param server the initialized server
1245  * @param c configuration to use
1246  */
1247 static void
1248 run (void *cls,
1249      struct GNUNET_SCHEDULER_Handle *s,
1250      struct GNUNET_SERVER_Handle *server,
1251      struct GNUNET_CONFIGURATION_Handle *c)
1252 {
1253   char *fn;
1254   unsigned int bf_size;
1255
1256   sched = s;
1257   cfg = c;
1258   if (GNUNET_OK !=
1259       GNUNET_CONFIGURATION_get_value_number (cfg,
1260                                              "DATASTORE", "QUOTA", &quota))
1261     {
1262       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1263                   _("No `%s' specified for `%s' in configuration!\n"),
1264                   "QUOTA",
1265                   "DATASTORE");
1266       return;
1267     }
1268   cache_size = quota / 8; /* Or should we make this an option? */
1269   bf_size = quota / 32; /* 8 bit per entry, 1 bit per 32 kb in DB */
1270   fn = NULL;
1271   if ( (GNUNET_OK !=
1272         GNUNET_CONFIGURATION_get_value_filename (cfg,
1273                                                  "DATASTORE",
1274                                                  "BLOOMFILTER",
1275                                                  &fn)) ||
1276        (GNUNET_OK !=
1277         GNUNET_DISK_directory_create_for_file (fn)) )
1278     {
1279       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1280                   _("Could not use specified filename `%s' for bloomfilter.\n"),
1281                   fn != NULL ? fn : "");
1282       GNUNET_free_non_null (fn);
1283       fn = NULL;
1284     }
1285   filter = GNUNET_CONTAINER_bloomfilter_load (fn, bf_size, 5);  /* approx. 3% false positives at max use */  
1286   GNUNET_free_non_null (fn);
1287   if (filter == NULL)
1288     {
1289       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1290                   _("Failed to initialize bloomfilter.\n"));
1291       return;
1292     }
1293   plugin = load_plugin ();
1294   if (NULL == plugin)
1295     {
1296       GNUNET_CONTAINER_bloomfilter_free (filter);
1297       return;
1298     }
1299   GNUNET_SERVER_disconnect_notify (server, &cleanup_reservations, NULL);
1300   GNUNET_SERVER_add_handlers (server, handlers);
1301   expired_kill_task
1302     = GNUNET_SCHEDULER_add_delayed (sched,
1303                                     GNUNET_NO,
1304                                     GNUNET_SCHEDULER_PRIORITY_IDLE,
1305                                     GNUNET_SCHEDULER_NO_TASK,
1306                                     GNUNET_TIME_UNIT_ZERO,
1307                                     &delete_expired, NULL);
1308   GNUNET_SCHEDULER_add_delayed (sched,
1309                                 GNUNET_YES,
1310                                 GNUNET_SCHEDULER_PRIORITY_IDLE,
1311                                 GNUNET_SCHEDULER_NO_TASK,
1312                                 GNUNET_TIME_UNIT_FOREVER_REL,
1313                                 &cleaning_task, NULL);
1314   
1315 }
1316
1317
1318 /**
1319  * The main function for the datastore service.
1320  *
1321  * @param argc number of arguments from the command line
1322  * @param argv command line arguments
1323  * @return 0 ok, 1 on error
1324  */
1325 int
1326 main (int argc, char *const *argv)
1327 {
1328   int ret;
1329
1330   ret = (GNUNET_OK ==
1331          GNUNET_SERVICE_run (argc,
1332                              argv,
1333                              "datastore", &run, NULL, NULL, NULL)) ? 0 : 1;
1334   return ret;
1335 }
1336
1337
1338 /* end of gnunet-service-datastore.c */