-preparations for replacement of try_connect call
[oweals/gnunet.git] / src / namecache / plugin_namecache_flat.c
1  /*
2   * This file is part of GNUnet
3   * Copyright (C) 2009-2015 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 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   buffer = GNUNET_malloc (size);
136
137   if (GNUNET_SYSERR == GNUNET_DISK_file_read (fh,
138                                               buffer,
139                                               size))
140   {
141     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
142                 _("Unable to read file: %s.\n"),
143                 afsdir);
144     return GNUNET_SYSERR;
145   }
146
147   GNUNET_DISK_file_close (fh);
148
149   line = strtok ("\n", buffer);
150   while (line != NULL) {
151     query = strtok (",", line);
152     block = strtok (NULL, line);
153     line = strtok ("\n", buffer);
154     entry = GNUNET_malloc (sizeof (struct FlatFileEntry));
155     GNUNET_CRYPTO_hash_from_string (query,
156                                     &entry->query);
157     GNUNET_STRINGS_base64_decode (block,
158                                   strlen (block),
159                                   &block_buffer);
160     entry->block = (struct GNUNET_GNSRECORD_Block *) block_buffer;
161     if (GNUNET_OK != 
162         GNUNET_CONTAINER_multihashmap_put (plugin->hm,
163                                            &entry->query,
164                                            entry,
165                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
166     {
167       GNUNET_free (entry);
168       GNUNET_break (0);
169     }
170   }
171   GNUNET_free (buffer);
172   return GNUNET_OK;
173 }
174
175 /**
176  * Store values in hashmap in file and free data
177  *
178  * @param plugin the plugin context
179  */
180 static int
181 store_and_free_entries (void *cls,
182                         const struct GNUNET_HashCode *key,
183                         void *value)
184 {
185   struct GNUNET_DISK_FileHandle *fh = cls;
186   struct FlatFileEntry *entry = value;
187
188   char *line;
189   char *block_b64;
190   struct GNUNET_CRYPTO_HashAsciiEncoded query;
191   size_t block_size;
192
193   block_size = ntohl (entry->block->purpose.size) +
194     sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
195     sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
196
197   GNUNET_STRINGS_base64_encode ((char*)entry->block,
198                                 block_size,
199                                 &block_b64);
200   GNUNET_CRYPTO_hash_to_enc (&entry->query,
201                              &query);
202   GNUNET_asprintf (&line,
203                    "%s,%s\n",
204                    (char*)&query,
205                    block_b64);
206
207   GNUNET_free (block_b64);
208
209   GNUNET_DISK_file_write (fh,
210                           line,
211                           strlen (line));
212
213   GNUNET_free (entry->block);
214   GNUNET_free (entry);
215   return GNUNET_YES;
216 }
217
218 /**
219  * Shutdown database connection and associate data
220  * structures.
221  * @param plugin the plugin context (state for this module)
222  */
223 static void
224 database_shutdown (struct Plugin *plugin)
225 {
226   struct GNUNET_DISK_FileHandle *fh;
227   fh = GNUNET_DISK_file_open (plugin->fn,
228                               GNUNET_DISK_OPEN_CREATE |
229                               GNUNET_DISK_OPEN_TRUNCATE |
230                               GNUNET_DISK_OPEN_READWRITE,
231                               GNUNET_DISK_PERM_USER_WRITE |
232                               GNUNET_DISK_PERM_USER_READ);
233   if (NULL == fh)
234   {
235     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
236                 _("Unable to initialize file: %s.\n"),
237                 plugin->fn);
238     return;
239   }
240
241   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
242                                          &store_and_free_entries,
243                                          fh);
244   GNUNET_CONTAINER_multihashmap_destroy (plugin->hm);
245   GNUNET_DISK_file_close (fh);
246
247 }
248
249 static int
250 expire_blocks (void *cls,
251                const struct GNUNET_HashCode *key,
252                void *value)
253 {
254   struct Plugin *plugin = cls;
255   struct FlatFileEntry *entry = value;
256   struct GNUNET_TIME_Absolute now;
257   struct GNUNET_TIME_Absolute expiration;
258
259   now = GNUNET_TIME_absolute_get ();
260   expiration = GNUNET_TIME_absolute_ntoh (entry->block->expiration_time);
261
262   if (0 == GNUNET_TIME_absolute_get_difference (now,
263                                                 expiration).rel_value_us)
264   {
265     GNUNET_CONTAINER_multihashmap_remove_all (plugin->hm, key);
266   }
267   return GNUNET_YES;
268 }
269
270
271
272 /**
273  * Removes any expired block.
274  *
275  * @param plugin the plugin
276  */
277 static void
278 namecache_expire_blocks (struct Plugin *plugin)
279 {
280   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
281                                          &expire_blocks,
282                                          plugin);
283 }
284
285
286 /**
287  * Cache a block in the datastore.
288  *
289  * @param cls closure (internal context for the plugin)
290  * @param block block to cache
291  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
292  */
293 static int
294 namecache_cache_block (void *cls,
295                               const struct GNUNET_GNSRECORD_Block *block)
296 {
297   struct Plugin *plugin = cls;
298   struct GNUNET_HashCode query;
299   struct FlatFileEntry *entry;
300   size_t block_size;
301
302   namecache_expire_blocks (plugin);
303   GNUNET_CRYPTO_hash (&block->derived_key,
304                       sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
305                       &query);
306   block_size = ntohl (block->purpose.size) +
307     sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
308     sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
309   if (block_size > 64 * 65536)
310   {
311     GNUNET_break (0);
312     return GNUNET_SYSERR;
313   }
314   entry = GNUNET_malloc (sizeof (struct FlatFileEntry));
315   entry->block = GNUNET_malloc (block_size);
316   memcpy (entry->block, block, block_size);
317   GNUNET_CONTAINER_multihashmap_remove_all (plugin->hm, &query);
318   if (GNUNET_OK != 
319       GNUNET_CONTAINER_multihashmap_put (plugin->hm,
320                                          &query,
321                                          entry,
322                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
323   {
324     GNUNET_free (entry);
325     GNUNET_break (0);
326     return GNUNET_SYSERR;
327   }
328   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
329               "Caching block under derived key `%s'\n",
330               GNUNET_h2s_full (&query));
331   return GNUNET_OK;
332 }
333
334
335 /**
336  * Get the block for a particular zone and label in the
337  * datastore.  Will return at most one result to the iterator.
338  *
339  * @param cls closure (internal context for the plugin)
340  * @param query hash of public key derived from the zone and the label
341  * @param iter function to call with the result
342  * @param iter_cls closure for @a iter
343  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
344  */
345 static int
346 namecache_lookup_block (void *cls,
347                         const struct GNUNET_HashCode *query,
348                         GNUNET_NAMECACHE_BlockCallback iter, void *iter_cls)
349 {
350   struct Plugin *plugin = cls;
351   const struct GNUNET_GNSRECORD_Block *block;
352
353   block = GNUNET_CONTAINER_multihashmap_get (plugin->hm, query);
354   if (NULL == block)
355     return GNUNET_NO;
356   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
357               "Found block under derived key `%s'\n",
358               GNUNET_h2s_full (query));
359   iter (iter_cls, block);
360   return GNUNET_YES;
361 }
362
363
364 /**
365  * Entry point for the plugin.
366  *
367  * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
368  * @return NULL on error, otherwise the plugin context
369  */
370 void *
371 libgnunet_plugin_namecache_flat_init (void *cls)
372 {
373   static struct Plugin plugin;
374   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
375   struct GNUNET_NAMECACHE_PluginFunctions *api;
376
377   if (NULL != plugin.cfg)
378     return NULL;                /* can only initialize once! */
379   memset (&plugin, 0, sizeof (struct Plugin));
380   plugin.cfg = cfg;
381   if (GNUNET_OK != database_setup (&plugin))
382   {
383     database_shutdown (&plugin);
384     return NULL;
385   }
386   api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
387   api->cls = &plugin;
388   api->cache_block = &namecache_cache_block;
389   api->lookup_block = &namecache_lookup_block;
390   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
391        _("flat plugin running\n"));
392   return api;
393 }
394
395
396 /**
397  * Exit point from the plugin.
398  *
399  * @param cls the plugin context (as returned by "init")
400  * @return always NULL
401  */
402 void *
403 libgnunet_plugin_namecache_flat_done (void *cls)
404 {
405   struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
406   struct Plugin *plugin = api->cls;
407
408   database_shutdown (plugin);
409   plugin->cfg = NULL;
410   GNUNET_free (api);
411   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
412        "flat plugin is finished\n");
413   return NULL;
414 }
415
416 /* end of plugin_namecache_sqlite.c */