fix #4546
[oweals/gnunet.git] / src / namecache / plugin_namecache_flat.c
1  /*
2   * This file is part of GNUnet
3   * Copyright (C) 2009-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 /**
22  * @file namecache/plugin_namecache_flat.c
23  * @brief flat file-based namecache backend
24  * @author Martin Schanzenbach
25  */
26
27 #include "platform.h"
28 #include "gnunet_namecache_plugin.h"
29 #include "gnunet_namecache_service.h"
30 #include "gnunet_gnsrecord_lib.h"
31 #include "namecache.h"
32
33 /**
34  * Context for all functions in this plugin.
35  */
36 struct Plugin
37 {
38
39   const struct GNUNET_CONFIGURATION_Handle *cfg;
40
41   /**
42    * Database filename.
43    */
44   char *fn;
45   
46   /**
47    * HashMap
48    */
49   struct GNUNET_CONTAINER_MultiHashMap *hm;
50
51 };
52
53 struct FlatFileEntry
54 {
55   /**
56    * Block
57    */
58   struct GNUNET_GNSRECORD_Block *block;
59
60   /**
61    * query
62    */
63   struct GNUNET_HashCode query;
64
65 };
66
67 /**
68  * Initialize the database connections and associated
69  * data structures (create tables and indices
70  * as needed as well).
71  *
72  * @param plugin the plugin context (state for this module)
73  * @return #GNUNET_OK on success
74  */
75 static int
76 database_setup (struct Plugin *plugin)
77 {
78   char *afsdir;
79   char* block_buffer;
80   char* buffer;
81   char* line;
82   char* query;
83   char* block;
84   size_t size;
85   struct FlatFileEntry *entry;
86   struct GNUNET_DISK_FileHandle *fh;
87
88   if (GNUNET_OK !=
89       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "namecache-flat",
90                                                "FILENAME", &afsdir))
91   {
92     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
93                                "namecache-flat", "FILENAME");
94     return GNUNET_SYSERR;
95   }
96   if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
97   {
98     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
99     {
100       GNUNET_break (0);
101       GNUNET_free (afsdir);
102       return GNUNET_SYSERR;
103     }
104   }
105   /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
106   plugin->fn = afsdir;
107
108   /* Load data from file into hashmap */
109   plugin->hm = GNUNET_CONTAINER_multihashmap_create (10,
110                                                      GNUNET_NO);
111   fh = GNUNET_DISK_file_open (afsdir,
112                               GNUNET_DISK_OPEN_CREATE |
113                               GNUNET_DISK_OPEN_READWRITE,
114                               GNUNET_DISK_PERM_USER_WRITE |
115                               GNUNET_DISK_PERM_USER_READ);
116   if (NULL == fh)
117   {
118     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
119                 _("Unable to initialize file: %s.\n"),
120                 afsdir);
121     return GNUNET_SYSERR;
122   }
123
124   if (GNUNET_SYSERR == GNUNET_DISK_file_size (afsdir,
125                                               &size,
126                                               GNUNET_YES,
127                                               GNUNET_YES))
128   {
129     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
130                 _("Unable to get filesize: %s.\n"),
131                 afsdir);
132     return GNUNET_SYSERR;
133   }
134
135   if (0 == size)
136     return GNUNET_OK;
137
138   buffer = GNUNET_malloc (size);
139
140   if (GNUNET_SYSERR == GNUNET_DISK_file_read (fh,
141                                               buffer,
142                                               size))
143   {
144     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
145                 _("Unable to read file: %s.\n"),
146                 afsdir);
147     return GNUNET_SYSERR;
148   }
149
150   GNUNET_DISK_file_close (fh);
151   if (0 < size) {
152     line = strtok (buffer, "\n");
153     while (line != NULL) {
154       query = strtok (line, ",");
155       if (NULL == query)
156         break;
157       block = strtok (NULL, ",");
158       if (NULL == block)
159         break;
160       line = strtok (NULL, "\n");
161       entry = GNUNET_malloc (sizeof (struct FlatFileEntry));
162       GNUNET_CRYPTO_hash_from_string (query,
163                                       &entry->query);
164       GNUNET_STRINGS_base64_decode (block,
165                                     strlen (block),
166                                     &block_buffer);
167       entry->block = (struct GNUNET_GNSRECORD_Block *) block_buffer;
168       if (GNUNET_OK != 
169           GNUNET_CONTAINER_multihashmap_put (plugin->hm,
170                                              &entry->query,
171                                              entry,
172                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
173       {
174         GNUNET_free (entry);
175         GNUNET_break (0);
176       }
177     }
178   }
179   GNUNET_free (buffer);
180   return GNUNET_OK;
181 }
182
183 /**
184  * Store values in hashmap in file and free data
185  *
186  * @param plugin the plugin context
187  */
188 static int
189 store_and_free_entries (void *cls,
190                         const struct GNUNET_HashCode *key,
191                         void *value)
192 {
193   struct GNUNET_DISK_FileHandle *fh = cls;
194   struct FlatFileEntry *entry = value;
195
196   char *line;
197   char *block_b64;
198   struct GNUNET_CRYPTO_HashAsciiEncoded query;
199   size_t block_size;
200
201   block_size = ntohl (entry->block->purpose.size) +
202     sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
203     sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
204
205   GNUNET_STRINGS_base64_encode ((char*)entry->block,
206                                 block_size,
207                                 &block_b64);
208   GNUNET_CRYPTO_hash_to_enc (&entry->query,
209                              &query);
210   GNUNET_asprintf (&line,
211                    "%s,%s\n",
212                    (char*)&query,
213                    block_b64);
214
215   GNUNET_free (block_b64);
216
217   GNUNET_DISK_file_write (fh,
218                           line,
219                           strlen (line));
220
221   GNUNET_free (entry->block);
222   GNUNET_free (entry);
223   return GNUNET_YES;
224 }
225
226 /**
227  * Shutdown database connection and associate data
228  * structures.
229  * @param plugin the plugin context (state for this module)
230  */
231 static void
232 database_shutdown (struct Plugin *plugin)
233 {
234   struct GNUNET_DISK_FileHandle *fh;
235   fh = GNUNET_DISK_file_open (plugin->fn,
236                               GNUNET_DISK_OPEN_CREATE |
237                               GNUNET_DISK_OPEN_TRUNCATE |
238                               GNUNET_DISK_OPEN_READWRITE,
239                               GNUNET_DISK_PERM_USER_WRITE |
240                               GNUNET_DISK_PERM_USER_READ);
241   if (NULL == fh)
242   {
243     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
244                 _("Unable to initialize file: %s.\n"),
245                 plugin->fn);
246     return;
247   }
248
249   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
250                                          &store_and_free_entries,
251                                          fh);
252   GNUNET_CONTAINER_multihashmap_destroy (plugin->hm);
253   GNUNET_DISK_file_close (fh);
254
255 }
256
257 static int
258 expire_blocks (void *cls,
259                const struct GNUNET_HashCode *key,
260                void *value)
261 {
262   struct Plugin *plugin = cls;
263   struct FlatFileEntry *entry = value;
264   struct GNUNET_TIME_Absolute now;
265   struct GNUNET_TIME_Absolute expiration;
266
267   now = GNUNET_TIME_absolute_get ();
268   expiration = GNUNET_TIME_absolute_ntoh (entry->block->expiration_time);
269
270   if (0 == GNUNET_TIME_absolute_get_difference (now,
271                                                 expiration).rel_value_us)
272   {
273     GNUNET_CONTAINER_multihashmap_remove_all (plugin->hm, key);
274   }
275   return GNUNET_YES;
276 }
277
278
279
280 /**
281  * Removes any expired block.
282  *
283  * @param plugin the plugin
284  */
285 static void
286 namecache_expire_blocks (struct Plugin *plugin)
287 {
288   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
289                                          &expire_blocks,
290                                          plugin);
291 }
292
293
294 /**
295  * Cache a block in the datastore.
296  *
297  * @param cls closure (internal context for the plugin)
298  * @param block block to cache
299  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
300  */
301 static int
302 namecache_cache_block (void *cls,
303                        const struct GNUNET_GNSRECORD_Block *block)
304 {
305   struct Plugin *plugin = cls;
306   struct GNUNET_HashCode query;
307   struct FlatFileEntry *entry;
308   size_t block_size;
309
310   namecache_expire_blocks (plugin);
311   GNUNET_CRYPTO_hash (&block->derived_key,
312                       sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
313                       &query);
314   block_size = ntohl (block->purpose.size) +
315     sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
316     sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
317   if (block_size > 64 * 65536)
318   {
319     GNUNET_break (0);
320     return GNUNET_SYSERR;
321   }
322   entry = GNUNET_malloc (sizeof (struct FlatFileEntry));
323   entry->block = GNUNET_malloc (block_size);
324   memcpy (entry->block, block, block_size);
325   GNUNET_CONTAINER_multihashmap_remove_all (plugin->hm, &query);
326   if (GNUNET_OK != 
327       GNUNET_CONTAINER_multihashmap_put (plugin->hm,
328                                          &query,
329                                          entry,
330                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
331   {
332     GNUNET_free (entry);
333     GNUNET_break (0);
334     return GNUNET_SYSERR;
335   }
336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
337               "Caching block under derived key `%s'\n",
338               GNUNET_h2s_full (&query));
339   return GNUNET_OK;
340 }
341
342
343 /**
344  * Get the block for a particular zone and label in the
345  * datastore.  Will return at most one result to the iterator.
346  *
347  * @param cls closure (internal context for the plugin)
348  * @param query hash of public key derived from the zone and the label
349  * @param iter function to call with the result
350  * @param iter_cls closure for @a iter
351  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
352  */
353 static int
354 namecache_lookup_block (void *cls,
355                         const struct GNUNET_HashCode *query,
356                         GNUNET_NAMECACHE_BlockCallback iter, void *iter_cls)
357 {
358   struct Plugin *plugin = cls;
359   const struct GNUNET_GNSRECORD_Block *block;
360
361   block = GNUNET_CONTAINER_multihashmap_get (plugin->hm, query);
362   if (NULL == block)
363     return GNUNET_NO;
364   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
365               "Found block under derived key `%s'\n",
366               GNUNET_h2s_full (query));
367   iter (iter_cls, block);
368   return GNUNET_YES;
369 }
370
371
372 /**
373  * Entry point for the plugin.
374  *
375  * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
376  * @return NULL on error, otherwise the plugin context
377  */
378 void *
379 libgnunet_plugin_namecache_flat_init (void *cls)
380 {
381   static struct Plugin plugin;
382   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
383   struct GNUNET_NAMECACHE_PluginFunctions *api;
384
385   if (NULL != plugin.cfg)
386     return NULL;                /* can only initialize once! */
387   memset (&plugin, 0, sizeof (struct Plugin));
388   plugin.cfg = cfg;
389   if (GNUNET_OK != database_setup (&plugin))
390   {
391     database_shutdown (&plugin);
392     return NULL;
393   }
394   api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
395   api->cls = &plugin;
396   api->cache_block = &namecache_cache_block;
397   api->lookup_block = &namecache_lookup_block;
398   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
399               _("flat plugin running\n"));
400   return api;
401 }
402
403
404 /**
405  * Exit point from the plugin.
406  *
407  * @param cls the plugin context (as returned by "init")
408  * @return always NULL
409  */
410 void *
411 libgnunet_plugin_namecache_flat_done (void *cls)
412 {
413   struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
414   struct Plugin *plugin = api->cls;
415
416   database_shutdown (plugin);
417   plugin->cfg = NULL;
418   GNUNET_free (api);
419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
420               "flat plugin is finished\n");
421   return NULL;
422 }
423
424 /* end of plugin_namecache_sqlite.c */