Merge remote-tracking branch 'origin/master' into credentials
[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
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
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, section, "DISABLE_BF"))
174   {
175     if (GNUNET_YES !=
176         GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "DISABLE_BF_RC"))
177     {
178       ret->bloom_name = GNUNET_DISK_mktemp ("gnunet-datacachebloom");
179     }
180     if (NULL != ret->bloom_name)
181     {
182       ret->filter = GNUNET_CONTAINER_bloomfilter_load (ret->bloom_name,
183                                                        quota / 1024,     /* 8 bit per entry in DB, expect 1k entries */
184                                                        5);
185     }
186     if (NULL == ret->filter)
187     {
188       ret->filter = GNUNET_CONTAINER_bloomfilter_init (NULL,
189                                                        bf_size,
190                                                        5); /* approx. 3% false positives at max use */
191     }
192   }
193   ret->stats = GNUNET_STATISTICS_create ("datacache", cfg);
194   ret->section = GNUNET_strdup (section);
195   ret->env.cfg = cfg;
196   ret->env.delete_notify = &env_delete_notify;
197   ret->env.section = ret->section;
198   ret->env.cls = ret;
199   ret->env.delete_notify = &env_delete_notify;
200   ret->env.quota = quota;
201   LOG (GNUNET_ERROR_TYPE_INFO,
202        _("Loading `%s' datacache plugin\n"),
203        name);
204   GNUNET_asprintf (&libname,
205                    "libgnunet_plugin_datacache_%s",
206                    name);
207   ret->short_name = name;
208   ret->lib_name = libname;
209   ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
210   if (ret->api == NULL)
211   {
212     LOG (GNUNET_ERROR_TYPE_ERROR,
213          _("Failed to load datacache plugin for `%s'\n"),
214          name);
215     GNUNET_DATACACHE_destroy (ret);
216     return NULL;
217   }
218   return ret;
219 }
220
221
222 /**
223  * Destroy a data cache (and free associated resources).
224  *
225  * @param h handle to the datastore
226  */
227 void
228 GNUNET_DATACACHE_destroy (struct GNUNET_DATACACHE_Handle *h)
229 {
230   if (NULL != h->filter)
231     GNUNET_CONTAINER_bloomfilter_free (h->filter);
232   if (NULL != h->api)
233     GNUNET_break (NULL == GNUNET_PLUGIN_unload (h->lib_name, h->api));
234   GNUNET_free (h->lib_name);
235   GNUNET_free (h->short_name);
236   GNUNET_free (h->section);
237   if (NULL != h->bloom_name)
238   {
239     if (0 != UNLINK (h->bloom_name))
240       GNUNET_log_from_strerror_file (GNUNET_ERROR_TYPE_WARNING,
241                                      "datacache",
242                                      "unlink",
243                                      h->bloom_name);
244     GNUNET_free (h->bloom_name);
245   }
246   GNUNET_STATISTICS_destroy (h->stats, GNUNET_NO);
247   GNUNET_free (h);
248 }
249
250
251 /**
252  * Store an item in the datastore.
253  *
254  * @param h handle to the datacache
255  * @param key key to store data under
256  * @param data_size number of bytes in @a data
257  * @param data data to store
258  * @param type type of the value
259  * @param discard_time when to discard the value in any case
260  * @param path_info_len number of entries in @a path_info
261  * @param path_info a path through the network
262  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error, #GNUNET_NO if duplicate
263  */
264 int
265 GNUNET_DATACACHE_put (struct GNUNET_DATACACHE_Handle *h,
266                       const struct GNUNET_HashCode *key,
267                       size_t data_size,
268                       const char *data,
269                       enum GNUNET_BLOCK_Type type,
270                       struct GNUNET_TIME_Absolute discard_time,
271                       unsigned int path_info_len,
272                       const struct GNUNET_PeerIdentity *path_info)
273 {
274   ssize_t used;
275
276   used = h->api->put (h->api->cls, key,
277                       data_size, data,
278                       type, discard_time,
279                       path_info_len, path_info);
280   if (-1 == used)
281   {
282     GNUNET_break (0);
283     return GNUNET_SYSERR;
284   }
285   if (0 == used)
286   {
287     /* duplicate */
288     return GNUNET_NO;
289   }
290   LOG (GNUNET_ERROR_TYPE_DEBUG,
291        "Stored data under key `%s' in cache\n",
292        GNUNET_h2s (key));
293   GNUNET_STATISTICS_update (h->stats,
294                             gettext_noop ("# bytes stored"),
295                             data_size,
296                             GNUNET_NO);
297   GNUNET_STATISTICS_update (h->stats,
298                             gettext_noop ("# items stored"),
299                             1,
300                             GNUNET_NO);
301   if (NULL != h->filter)
302     GNUNET_CONTAINER_bloomfilter_add (h->filter, key);
303   while (h->utilization + used > h->env.quota)
304     GNUNET_assert (GNUNET_OK == h->api->del (h->api->cls));
305   h->utilization += used;
306   return GNUNET_OK;
307 }
308
309
310 /**
311  * Iterate over the results for a particular key
312  * in the datacache.
313  *
314  * @param h handle to the datacache
315  * @param key what to look up
316  * @param type entries of which type are relevant?
317  * @param iter maybe NULL (to just count)
318  * @param iter_cls closure for @a iter
319  * @return the number of results found
320  */
321 unsigned int
322 GNUNET_DATACACHE_get (struct GNUNET_DATACACHE_Handle *h,
323                       const struct GNUNET_HashCode *key,
324                       enum GNUNET_BLOCK_Type type,
325                       GNUNET_DATACACHE_Iterator iter,
326                       void *iter_cls)
327 {
328   GNUNET_STATISTICS_update (h->stats,
329                             gettext_noop ("# requests received"),
330                             1,
331                             GNUNET_NO);
332   LOG (GNUNET_ERROR_TYPE_DEBUG,
333        "Processing request for key `%s'\n",
334        GNUNET_h2s (key));
335   if ( (NULL != h->filter) &&
336        (GNUNET_OK != GNUNET_CONTAINER_bloomfilter_test (h->filter, key)) )
337   {
338     GNUNET_STATISTICS_update (h->stats,
339                               gettext_noop ("# requests filtered by bloom filter"),
340                               1,
341                               GNUNET_NO);
342     LOG (GNUNET_ERROR_TYPE_DEBUG,
343          "Bloomfilter filters request for key `%s'\n",
344          GNUNET_h2s (key));
345     return 0;                   /* can not be present */
346   }
347   return h->api->get (h->api->cls,
348                       key, type,
349                       iter, iter_cls);
350 }
351
352
353 /**
354  * Obtain a random element from the datacache.
355  *
356  * @param h handle to the datacache
357  * @param iter maybe NULL (to just count)
358  * @param iter_cls closure for @a iter
359  * @return the number of results found (zero or 1)
360  */
361 unsigned int
362 GNUNET_DATACACHE_get_random (struct GNUNET_DATACACHE_Handle *h,
363                              GNUNET_DATACACHE_Iterator iter,
364                              void *iter_cls)
365 {
366   GNUNET_STATISTICS_update (h->stats,
367                             gettext_noop ("# requests for random value received"),
368                             1,
369                             GNUNET_NO);
370   LOG (GNUNET_ERROR_TYPE_DEBUG,
371        "Processing request for random value\n");
372   return h->api->get_random (h->api->cls,
373                              iter,
374                              iter_cls);
375 }
376
377
378 /**
379  * Iterate over the results that are "close" to a particular key in
380  * the datacache.  "close" is defined as numerically larger than @a
381  * key (when interpreted as a circular address space), with small
382  * distance.
383  *
384  * @param h handle to the datacache
385  * @param key area of the keyspace to look into
386  * @param num_results number of results that should be returned to @a iter
387  * @param iter maybe NULL (to just count)
388  * @param iter_cls closure for @a iter
389  * @return the number of results found
390  */
391 unsigned int
392 GNUNET_DATACACHE_get_closest (struct GNUNET_DATACACHE_Handle *h,
393                               const struct GNUNET_HashCode *key,
394                               unsigned int num_results,
395                               GNUNET_DATACACHE_Iterator iter,
396                               void *iter_cls)
397 {
398   GNUNET_STATISTICS_update (h->stats,
399                             gettext_noop ("# proximity search requests received"),
400                             1,
401                             GNUNET_NO);
402   LOG (GNUNET_ERROR_TYPE_DEBUG,
403        "Processing proximity search at `%s'\n",
404        GNUNET_h2s (key));
405   return h->api->get_closest (h->api->cls,
406                               key,
407                               num_results,
408                               iter,
409                               iter_cls);
410 }
411
412
413 /* end of datacache.c */