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