fix 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   GNUNET_SERVER_client_keep (client);
934   msg = (const struct GetMessage*) message;
935   if ( (size == sizeof(struct GetMessage)) &&
936        (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (filter,
937                                                          &msg->key)) )
938     {
939       /* don't bother database... */
940 #if DEBUG_DATASTORE
941       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
942                   "Empty result set for `%s' request for `%s'.\n",
943                   "GET",
944                   GNUNET_h2s (&msg->key));
945 #endif  
946       transmit_item (client,
947                      NULL, NULL, 0, NULL, 0, 0, 0, 
948                      GNUNET_TIME_UNIT_ZERO_ABS, 0);
949       return;
950     }
951   plugin->api->get (plugin->api->cls,
952                     ((size == sizeof(struct GetMessage)) ? &msg->key : NULL),
953                     NULL,
954                     ntohl(msg->type),
955                     &transmit_item,
956                     client);    
957 }
958
959
960 /**
961  * Handle UPDATE-message.
962  *
963  * @param cls closure
964  * @param client identification of the client
965  * @param message the actual message
966  */
967 static void
968 handle_update (void *cls,
969                struct GNUNET_SERVER_Client *client,
970                const struct GNUNET_MessageHeader *message)
971 {
972   const struct UpdateMessage *msg;
973   int ret;
974   char *emsg;
975
976 #if DEBUG_DATASTORE
977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
978               "Processing `%s' request\n",
979               "UPDATE");
980 #endif
981   msg = (const struct UpdateMessage*) message;
982   emsg = NULL;
983   ret = plugin->api->update (plugin->api->cls,
984                              GNUNET_ntohll(msg->uid),
985                              (int32_t) ntohl(msg->priority),
986                              GNUNET_TIME_absolute_ntoh(msg->expiration),
987                              &emsg);
988   transmit_status (client, ret, emsg);
989   GNUNET_free_non_null (emsg);
990 }
991
992
993 /**
994  * Handle GET_RANDOM-message.
995  *
996  * @param cls closure
997  * @param client identification of the client
998  * @param message the actual message
999  */
1000 static void
1001 handle_get_random (void *cls,
1002                    struct GNUNET_SERVER_Client *client,
1003                    const struct GNUNET_MessageHeader *message)
1004 {
1005 #if DEBUG_DATASTORE
1006   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1007               "Processing `%s' request\n",
1008               "GET_RANDOM");
1009 #endif
1010   GNUNET_SERVER_client_keep (client);
1011   plugin->api->iter_migration_order (plugin->api->cls,
1012                                      0,
1013                                      &transmit_item,
1014                                      client);  
1015 }
1016
1017
1018 /**
1019  * Context for the 'remove_callback'.
1020  */
1021 struct RemoveContext 
1022 {
1023   /**
1024    * Client for whom we're doing the remvoing.
1025    */
1026   struct GNUNET_SERVER_Client *client;
1027
1028   /**
1029    * GNUNET_YES if we managed to remove something.
1030    */
1031   int found;
1032 };
1033
1034
1035 /**
1036  * Callback function that will cause the item that is passed
1037  * in to be deleted (by returning GNUNET_NO).
1038  */
1039 static int
1040 remove_callback (void *cls,
1041                  void *next_cls,
1042                  const GNUNET_HashCode * key,
1043                  uint32_t size,
1044                  const void *data,
1045                  uint32_t type,
1046                  uint32_t priority,
1047                  uint32_t anonymity,
1048                  struct GNUNET_TIME_Absolute
1049                  expiration, uint64_t uid)
1050 {
1051   struct RemoveContext *rc = cls;
1052
1053   if (key == NULL)
1054     {
1055 #if DEBUG_DATASTORE
1056       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1057                   "No further matches for `%s' request.\n",
1058                   "REMOVE");
1059 #endif  
1060       if (GNUNET_YES == rc->found)
1061         transmit_status (rc->client, GNUNET_OK, NULL);       
1062       else
1063         transmit_status (rc->client, GNUNET_NO, _("Content not found"));        
1064       GNUNET_SERVER_client_drop (rc->client);
1065       GNUNET_free (rc);
1066       return GNUNET_OK; /* last item */
1067     }
1068   rc->found = GNUNET_YES;
1069 #if DEBUG_DATASTORE
1070   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1071               "Item %llu matches `%s' request.\n",
1072               (unsigned long long) uid,
1073               "REMOVE");
1074 #endif  
1075   GNUNET_CONTAINER_bloomfilter_remove (filter,
1076                                        key);
1077   plugin->api->next_request (next_cls, GNUNET_YES);
1078   return GNUNET_NO;
1079 }
1080
1081
1082 /**
1083  * Handle REMOVE-message.
1084  *
1085  * @param cls closure
1086  * @param client identification of the client
1087  * @param message the actual message
1088  */
1089 static void
1090 handle_remove (void *cls,
1091              struct GNUNET_SERVER_Client *client,
1092              const struct GNUNET_MessageHeader *message)
1093 {
1094   const struct DataMessage *dm = check_data (message);
1095   GNUNET_HashCode vhash;
1096   struct RemoveContext *rc;
1097
1098 #if DEBUG_DATASTORE
1099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100               "Processing `%s' request\n",
1101               "REMOVE");
1102 #endif
1103   if (dm == NULL)
1104     {
1105       GNUNET_break (0);
1106       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1107       return;
1108     }
1109   rc = GNUNET_malloc (sizeof(struct RemoveContext));
1110   GNUNET_SERVER_client_keep (client);
1111   rc->client = client;
1112   GNUNET_CRYPTO_hash (&dm[1],
1113                       ntohl(dm->size),
1114                       &vhash);
1115   plugin->api->get (plugin->api->cls,
1116                     &dm->key,
1117                     &vhash,
1118                     ntohl(dm->type),
1119                     &remove_callback,
1120                     rc);
1121 }
1122
1123
1124 /**
1125  * Handle DROP-message.
1126  *
1127  * @param cls closure
1128  * @param client identification of the client
1129  * @param message the actual message
1130  */
1131 static void
1132 handle_drop (void *cls,
1133              struct GNUNET_SERVER_Client *client,
1134              const struct GNUNET_MessageHeader *message)
1135 {
1136 #if DEBUG_DATASTORE
1137   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1138               "Processing `%s' request\n",
1139               "DROP");
1140 #endif
1141   plugin->api->drop (plugin->api->cls);
1142   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1143 }
1144
1145
1146 /**
1147  * List of handlers for the messages understood by this
1148  * service.
1149  */
1150 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1151   {&handle_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE, 
1152    sizeof(struct ReserveMessage) }, 
1153   {&handle_release_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE, 
1154    sizeof(struct ReleaseReserveMessage) }, 
1155   {&handle_put, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_PUT, 0 }, 
1156   {&handle_update, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE, 
1157    sizeof (struct UpdateMessage) }, 
1158   {&handle_get, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET, 0 }, 
1159   {&handle_get_random, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET_RANDOM, 
1160    sizeof(struct GNUNET_MessageHeader) }, 
1161   {&handle_remove, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, 0 }, 
1162   {&handle_drop, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_DROP, 
1163    sizeof(struct GNUNET_MessageHeader) }, 
1164   {NULL, NULL, 0, 0}
1165 };
1166
1167
1168
1169 /**
1170  * Load the datastore plugin.
1171  */
1172 static struct DatastorePlugin *
1173 load_plugin () 
1174 {
1175   struct DatastorePlugin *ret;
1176   char *libname;
1177   char *name;
1178
1179   if (GNUNET_OK !=
1180       GNUNET_CONFIGURATION_get_value_string (cfg,
1181                                              "DATASTORE", "DATABASE", &name))
1182     {
1183       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1184                   _("No `%s' specified for `%s' in configuration!\n"),
1185                   "DATABASE",
1186                   "DATASTORE");
1187       return NULL;
1188     }
1189   ret = GNUNET_malloc (sizeof(struct DatastorePlugin));
1190   ret->env.cfg = cfg;
1191   ret->env.sched = sched;  
1192   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1193               _("Loading `%s' datastore plugin\n"), name);
1194   GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", name);
1195   ret->short_name = name;
1196   ret->lib_name = libname;
1197   ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
1198   if (ret->api == NULL)
1199     {
1200       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1201                   _("Failed to load datastore plugin for `%s'\n"), name);
1202       GNUNET_free (ret->short_name);
1203       GNUNET_free (libname);
1204       GNUNET_free (ret);
1205       return NULL;
1206     }
1207   return ret;
1208 }
1209
1210
1211 /**
1212  * Function called when the service shuts
1213  * down.  Unloads our datastore plugin.
1214  *
1215  * @param plug plugin to unload
1216  */
1217 static void
1218 unload_plugin (struct DatastorePlugin *plug)
1219 {
1220 #if DEBUG_DATASTORE
1221   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1222               "Datastore service is unloading plugin...\n");
1223 #endif
1224   GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
1225   GNUNET_free (plug->lib_name);
1226   GNUNET_free (plug->short_name);
1227   GNUNET_free (plug);
1228 }
1229
1230
1231 /**
1232  * Last task run during shutdown.  Disconnects us from
1233  * the transport and core.
1234  */
1235 static void
1236 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1237 {
1238   struct TransmitCallbackContext *tcc;
1239
1240   while (NULL != (tcc = tcc_head))
1241     {
1242       GNUNET_CONTAINER_DLL_remove (tcc_head,
1243                                    tcc_tail,
1244                                    tcc);
1245       if (tcc->th != NULL)
1246         GNUNET_CONNECTION_notify_transmit_ready_cancel (tcc->th);
1247       if (NULL != tcc->tc)
1248         tcc->tc (tcc->tc_cls, GNUNET_SYSERR);
1249       GNUNET_free (tcc->msg);
1250       GNUNET_free (tcc);
1251     }
1252   if (expired_kill_task != GNUNET_SCHEDULER_NO_TASK)
1253     {
1254       GNUNET_SCHEDULER_cancel (sched,
1255                                expired_kill_task);
1256       expired_kill_task = GNUNET_SCHEDULER_NO_TASK;
1257     }
1258   unload_plugin (plugin);
1259   plugin = NULL;
1260   if (filter != NULL)
1261     {
1262       GNUNET_CONTAINER_bloomfilter_free (filter);
1263       filter = NULL;
1264     }
1265   GNUNET_ARM_stop_services (cfg, tc->sched, "statistics", NULL);
1266 }
1267
1268
1269 /**
1270  * Function that removes all active reservations made
1271  * by the given client and releases the space for other
1272  * requests.
1273  *
1274  * @param cls closure
1275  * @param client identification of the client
1276  */
1277 static void
1278 cleanup_reservations (void *cls,
1279                       struct GNUNET_SERVER_Client
1280                       * client)
1281 {
1282   struct ReservationList *pos;
1283   struct ReservationList *prev;
1284   struct ReservationList *next;
1285
1286   if (client == NULL)
1287     return;
1288   prev = NULL;
1289   pos = reservations;
1290   while (NULL != pos)
1291     {
1292       next = pos->next;
1293       if (pos->client == client)
1294         {
1295           if (prev == NULL)
1296             reservations = next;
1297           else
1298             prev->next = next;
1299           reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD;
1300           GNUNET_free (pos);
1301         }
1302       else
1303         {
1304           prev = pos;
1305         }
1306       pos = next;
1307     }
1308 }
1309
1310
1311 /**
1312  * Process datastore requests.
1313  *
1314  * @param cls closure
1315  * @param s scheduler to use
1316  * @param server the initialized server
1317  * @param c configuration to use
1318  */
1319 static void
1320 run (void *cls,
1321      struct GNUNET_SCHEDULER_Handle *s,
1322      struct GNUNET_SERVER_Handle *server,
1323      const struct GNUNET_CONFIGURATION_Handle *c)
1324 {
1325   char *fn;
1326   unsigned int bf_size;
1327
1328   sched = s;
1329   cfg = c;
1330   if (GNUNET_OK !=
1331       GNUNET_CONFIGURATION_get_value_number (cfg,
1332                                              "DATASTORE", "QUOTA", &quota))
1333     {
1334       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1335                   _("No `%s' specified for `%s' in configuration!\n"),
1336                   "QUOTA",
1337                   "DATASTORE");
1338       return;
1339     }
1340   cache_size = quota / 8; /* Or should we make this an option? */
1341   bf_size = quota / 32; /* 8 bit per entry, 1 bit per 32 kb in DB */
1342   fn = NULL;
1343   if ( (GNUNET_OK !=
1344         GNUNET_CONFIGURATION_get_value_filename (cfg,
1345                                                  "DATASTORE",
1346                                                  "BLOOMFILTER",
1347                                                  &fn)) ||
1348        (GNUNET_OK !=
1349         GNUNET_DISK_directory_create_for_file (fn)) )
1350     {
1351       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1352                   _("Could not use specified filename `%s' for bloomfilter.\n"),
1353                   fn != NULL ? fn : "");
1354       GNUNET_free_non_null (fn);
1355       fn = NULL;
1356     }
1357   filter = GNUNET_CONTAINER_bloomfilter_load (fn, bf_size, 5);  /* approx. 3% false positives at max use */  
1358   GNUNET_free_non_null (fn);
1359   if (filter == NULL)
1360     {
1361       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1362                   _("Failed to initialize bloomfilter.\n"));
1363       return;
1364     }
1365   GNUNET_ARM_start_services (cfg, sched, "statistics", NULL);
1366   plugin = load_plugin ();
1367   if (NULL == plugin)
1368     {
1369       GNUNET_CONTAINER_bloomfilter_free (filter);
1370       filter = NULL;
1371       GNUNET_ARM_stop_services (cfg, sched, "statistics", NULL);
1372       return;
1373     }
1374   GNUNET_SERVER_disconnect_notify (server, &cleanup_reservations, NULL);
1375   GNUNET_SERVER_add_handlers (server, handlers);
1376   expired_kill_task
1377     = GNUNET_SCHEDULER_add_with_priority (sched,
1378                                           GNUNET_SCHEDULER_PRIORITY_IDLE,
1379                                           &delete_expired, NULL);
1380   GNUNET_SCHEDULER_add_delayed (sched,
1381                                 GNUNET_TIME_UNIT_FOREVER_REL,
1382                                 &cleaning_task, NULL);
1383   
1384 }
1385
1386
1387 /**
1388  * The main function for the datastore service.
1389  *
1390  * @param argc number of arguments from the command line
1391  * @param argv command line arguments
1392  * @return 0 ok, 1 on error
1393  */
1394 int
1395 main (int argc, char *const *argv)
1396 {
1397   int ret;
1398
1399   ret = (GNUNET_OK ==
1400          GNUNET_SERVICE_run (argc,
1401                              argv,
1402                              "datastore",
1403                              GNUNET_SERVICE_OPTION_NONE,
1404                              &run, NULL)) ? 0 : 1;
1405   return ret;
1406 }
1407
1408
1409 /* end of gnunet-service-datastore.c */