7dcd54fcfecf87f5ba0c8303e8df3cf1347fe8be
[oweals/gnunet.git] / src / datacache / datacache.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2004, 2005, 2006, 2007, 2009, 2010, 2015 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20 /**
21  * @file datacache/datacache.c
22  * @brief datacache API implementation
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "gnunet_datacache_lib.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_datacache_plugin.h"
30
31
32 #define LOG(kind,...) GNUNET_log_from (kind, "datacache", __VA_ARGS__)
33
34 #define LOG_STRERROR_FILE(kind,op,fn) GNUNET_log_from_strerror_file (kind, "datacache", op, fn)
35
36 /**
37  * Internal state of the datacache library.
38  */
39 struct GNUNET_DATACACHE_Handle
40 {
41
42   /**
43    * Bloomfilter to quickly tell if we don't have the content.
44    */
45   struct GNUNET_CONTAINER_BloomFilter *filter;
46
47   /**
48    * Our configuration.
49    */
50   const struct GNUNET_CONFIGURATION_Handle *cfg;
51
52   /**
53    * Opaque handle for the statistics service.
54    */
55   struct GNUNET_STATISTICS_Handle *stats;
56
57   /**
58    * Configuration section to use.
59    */
60   char *section;
61
62   /**
63    * API of the transport as returned by the plugin's
64    * initialization function.
65    */
66   struct GNUNET_DATACACHE_PluginFunctions *api;
67
68   /**
69    * Short name for the plugin (i.e. "sqlite").
70    */
71   char *short_name;
72
73   /**
74    * Name of the library (i.e. "gnunet_plugin_datacache_sqlite").
75    */
76   char *lib_name;
77
78   /**
79    * Name for the bloom filter file.
80    */
81   char *bloom_name;
82
83   /**
84    * Environment provided to our plugin.
85    */
86   struct GNUNET_DATACACHE_PluginEnvironment env;
87
88   /**
89    * How much space is in use right now?
90    */
91   unsigned long long utilization;
92
93 };
94
95
96 /**
97  * Function called by plugins to notify the datacache
98  * about content deletions.
99  *
100  * @param cls closure
101  * @param key key of the content that was deleted
102  * @param size number of bytes that were made available
103  */
104 static void
105 env_delete_notify (void *cls,
106                    const struct GNUNET_HashCode *key,
107                    size_t size)
108 {
109   struct GNUNET_DATACACHE_Handle *h = cls;
110
111   LOG (GNUNET_ERROR_TYPE_DEBUG,
112        "Content under key `%s' discarded\n",
113        GNUNET_h2s (key));
114   GNUNET_assert (h->utilization >= size);
115   h->utilization -= size;
116   GNUNET_CONTAINER_bloomfilter_remove (h->filter,
117                                        key);
118   GNUNET_STATISTICS_update (h->stats,
119                             gettext_noop ("# bytes stored"),
120                             - (long long) size,
121                             GNUNET_NO);
122   GNUNET_STATISTICS_update (h->stats,
123                             gettext_noop ("# items stored"),
124                             -1,
125                             GNUNET_NO);
126 }
127
128
129 /**
130  * Create a data cache.
131  *
132  * @param cfg configuration to use
133  * @param section section in the configuration that contains our options
134  * @return handle to use to access the service
135  */
136 struct GNUNET_DATACACHE_Handle *
137 GNUNET_DATACACHE_create (const struct GNUNET_CONFIGURATION_Handle *cfg,
138                          const char *section)
139 {
140   unsigned int bf_size;
141   unsigned long long quota;
142   struct GNUNET_DATACACHE_Handle *ret;
143   char *libname;
144   char *name;
145
146   if (GNUNET_OK !=
147       GNUNET_CONFIGURATION_get_value_size (cfg,
148                                            section,
149                                            "QUOTA",
150                                            &quota))
151   {
152     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
153                                section,
154                                "QUOTA");
155     return NULL;
156   }
157   if (GNUNET_OK !=
158       GNUNET_CONFIGURATION_get_value_string (cfg,
159                                              section,
160                                              "DATABASE",
161                                              &name))
162   {
163     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
164                                section,
165                                "DATABASE");
166     return NULL;
167   }
168   bf_size = quota / 32;         /* 8 bit per entry, 1 bit per 32 kb in DB */
169
170   ret = GNUNET_new (struct GNUNET_DATACACHE_Handle);
171
172   if (GNUNET_YES !=
173       GNUNET_CONFIGURATION_get_value_yesno (cfg,
174                                             section,
175                                             "DISABLE_BF"))
176   {
177     if (GNUNET_YES !=
178         GNUNET_CONFIGURATION_get_value_yesno (cfg,
179                                               section,
180                                               "DISABLE_BF_RC"))
181     {
182       ret->bloom_name = GNUNET_DISK_mktemp ("gnunet-datacachebloom");
183     }
184     if (NULL != ret->bloom_name)
185     {
186       ret->filter = GNUNET_CONTAINER_bloomfilter_load (ret->bloom_name,
187                                                        quota / 1024,     /* 8 bit per entry in DB, expect 1k entries */
188                                                        5);
189     }
190     if (NULL == ret->filter)
191     {
192       ret->filter = GNUNET_CONTAINER_bloomfilter_init (NULL,
193                                                        bf_size,
194                                                        5); /* approx. 3% false positives at max use */
195     }
196   }
197   ret->stats = GNUNET_STATISTICS_create ("datacache", cfg);
198   ret->section = GNUNET_strdup (section);
199   ret->env.cfg = cfg;
200   ret->env.delete_notify = &env_delete_notify;
201   ret->env.section = ret->section;
202   ret->env.cls = ret;
203   ret->env.delete_notify = &env_delete_notify;
204   ret->env.quota = quota;
205   LOG (GNUNET_ERROR_TYPE_INFO,
206        _("Loading `%s' datacache plugin\n"),
207        name);
208   GNUNET_asprintf (&libname,
209                    "libgnunet_plugin_datacache_%s",
210                    name);
211   ret->short_name = name;
212   ret->lib_name = libname;
213   ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
214   if (ret->api == NULL)
215   {
216     LOG (GNUNET_ERROR_TYPE_ERROR,
217          _("Failed to load datacache plugin for `%s'\n"),
218          name);
219     GNUNET_DATACACHE_destroy (ret);
220     return NULL;
221   }
222   return ret;
223 }
224
225
226 /**
227  * Destroy a data cache (and free associated resources).
228  *
229  * @param h handle to the datastore
230  */
231 void
232 GNUNET_DATACACHE_destroy (struct GNUNET_DATACACHE_Handle *h)
233 {
234   if (NULL != h->filter)
235     GNUNET_CONTAINER_bloomfilter_free (h->filter);
236   if (NULL != h->api)
237     GNUNET_break (NULL ==
238                   GNUNET_PLUGIN_unload (h->lib_name,
239                                         h->api));
240   GNUNET_free (h->lib_name);
241   GNUNET_free (h->short_name);
242   GNUNET_free (h->section);
243   if (NULL != h->bloom_name)
244   {
245     if (0 != UNLINK (h->bloom_name))
246       GNUNET_log_from_strerror_file (GNUNET_ERROR_TYPE_WARNING,
247                                      "datacache",
248                                      "unlink",
249                                      h->bloom_name);
250     GNUNET_free (h->bloom_name);
251   }
252   GNUNET_STATISTICS_destroy (h->stats,
253                              GNUNET_NO);
254   GNUNET_free (h);
255 }
256
257
258 /**
259  * Store an item in the datastore.
260  *
261  * @param h handle to the datacache
262  * @param key key to store data under
263  * @param xor_distance distance of @a key to our PID
264  * @param data_size number of bytes in @a data
265  * @param data data to store
266  * @param type type of the value
267  * @param discard_time when to discard the value in any case
268  * @param path_info_len number of entries in @a path_info
269  * @param path_info a path through the network
270  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error, #GNUNET_NO if duplicate
271  */
272 int
273 GNUNET_DATACACHE_put (struct GNUNET_DATACACHE_Handle *h,
274                       const struct GNUNET_HashCode *key,
275                       uint32_t xor_distance,
276                       size_t data_size,
277                       const char *data,
278                       enum GNUNET_BLOCK_Type type,
279                       struct GNUNET_TIME_Absolute discard_time,
280                       unsigned int path_info_len,
281                       const struct GNUNET_PeerIdentity *path_info)
282 {
283   ssize_t used;
284
285   used = h->api->put (h->api->cls,
286                       key,
287                       xor_distance,
288                       data_size,
289                       data,
290                       type,
291                       discard_time,
292                       path_info_len,
293                       path_info);
294   if (-1 == used)
295   {
296     GNUNET_break (0);
297     return GNUNET_SYSERR;
298   }
299   if (0 == used)
300   {
301     /* duplicate */
302     return GNUNET_NO;
303   }
304   LOG (GNUNET_ERROR_TYPE_DEBUG,
305        "Stored data under key `%s' in cache\n",
306        GNUNET_h2s (key));
307   if (NULL != h->filter)
308     GNUNET_CONTAINER_bloomfilter_add (h->filter,
309                                       key);
310   GNUNET_STATISTICS_update (h->stats,
311                             gettext_noop ("# bytes stored"),
312                             used,
313                             GNUNET_NO);
314   GNUNET_STATISTICS_update (h->stats,
315                             gettext_noop ("# items stored"),
316                             1,
317                             GNUNET_NO);
318   while (h->utilization + used > h->env.quota)
319     GNUNET_assert (GNUNET_OK ==
320                    h->api->del (h->api->cls));
321   h->utilization += used;
322   return GNUNET_OK;
323 }
324
325
326 /**
327  * Iterate over the results for a particular key
328  * in the datacache.
329  *
330  * @param h handle to the datacache
331  * @param key what to look up
332  * @param type entries of which type are relevant?
333  * @param iter maybe NULL (to just count)
334  * @param iter_cls closure for @a iter
335  * @return the number of results found
336  */
337 unsigned int
338 GNUNET_DATACACHE_get (struct GNUNET_DATACACHE_Handle *h,
339                       const struct GNUNET_HashCode *key,
340                       enum GNUNET_BLOCK_Type type,
341                       GNUNET_DATACACHE_Iterator iter,
342                       void *iter_cls)
343 {
344   GNUNET_STATISTICS_update (h->stats,
345                             gettext_noop ("# requests received"),
346                             1,
347                             GNUNET_NO);
348   LOG (GNUNET_ERROR_TYPE_DEBUG,
349        "Processing request for key `%s'\n",
350        GNUNET_h2s (key));
351   if ( (NULL != h->filter) &&
352        (GNUNET_OK != GNUNET_CONTAINER_bloomfilter_test (h->filter, key)) )
353   {
354     GNUNET_STATISTICS_update (h->stats,
355                               gettext_noop ("# requests filtered by bloom filter"),
356                               1,
357                               GNUNET_NO);
358     LOG (GNUNET_ERROR_TYPE_DEBUG,
359          "Bloomfilter filters request for key `%s'\n",
360          GNUNET_h2s (key));
361     return 0;                   /* can not be present */
362   }
363   return h->api->get (h->api->cls,
364                       key,
365                       type,
366                       iter,
367                       iter_cls);
368 }
369
370
371 /**
372  * Obtain a random element from the datacache.
373  *
374  * @param h handle to the datacache
375  * @param iter maybe NULL (to just count)
376  * @param iter_cls closure for @a iter
377  * @return the number of results found (zero or 1)
378  */
379 unsigned int
380 GNUNET_DATACACHE_get_random (struct GNUNET_DATACACHE_Handle *h,
381                              GNUNET_DATACACHE_Iterator iter,
382                              void *iter_cls)
383 {
384   GNUNET_STATISTICS_update (h->stats,
385                             gettext_noop ("# requests for random value received"),
386                             1,
387                             GNUNET_NO);
388   LOG (GNUNET_ERROR_TYPE_DEBUG,
389        "Processing request for random value\n");
390   return h->api->get_random (h->api->cls,
391                              iter,
392                              iter_cls);
393 }
394
395
396 /**
397  * Iterate over the results that are "close" to a particular key in
398  * the datacache.  "close" is defined as numerically larger than @a
399  * key (when interpreted as a circular address space), with small
400  * distance.
401  *
402  * @param h handle to the datacache
403  * @param key area of the keyspace to look into
404  * @param num_results number of results that should be returned to @a iter
405  * @param iter maybe NULL (to just count)
406  * @param iter_cls closure for @a iter
407  * @return the number of results found
408  */
409 unsigned int
410 GNUNET_DATACACHE_get_closest (struct GNUNET_DATACACHE_Handle *h,
411                               const struct GNUNET_HashCode *key,
412                               unsigned int num_results,
413                               GNUNET_DATACACHE_Iterator iter,
414                               void *iter_cls)
415 {
416   GNUNET_STATISTICS_update (h->stats,
417                             gettext_noop ("# proximity search requests received"),
418                             1,
419                             GNUNET_NO);
420   LOG (GNUNET_ERROR_TYPE_DEBUG,
421        "Processing proximity search at `%s'\n",
422        GNUNET_h2s (key));
423   return h->api->get_closest (h->api->cls,
424                               key,
425                               num_results,
426                               iter,
427                               iter_cls);
428 }
429
430
431 /* end of datacache.c */