fix memory leak and unnecessary allocations
[oweals/gnunet.git] / src / namestore / plugin_namestore_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 namestore/plugin_namestore_flat.c
23  * @brief file-based namestore backend
24  * @author Martin Schanzenbach
25  */
26
27 #include "platform.h"
28 #include "gnunet_namestore_plugin.h"
29 #include "gnunet_namestore_service.h"
30 #include "gnunet_gnsrecord_lib.h"
31 #include "namestore.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    * Offset
53    */
54   uint32_t offset;
55
56   /**
57    * Target Offset
58    */
59   uint32_t target_offset;
60
61   /**
62    * Iterator closure
63    */
64   void *iter_cls;
65
66   /**
67    * Iterator
68    */
69   GNUNET_NAMESTORE_RecordIterator iter;
70
71   /**
72    * Zone to iterate
73    */
74   const struct GNUNET_CRYPTO_EcdsaPrivateKey *iter_zone;
75
76   /**
77    * PKEY to look for in zone to name
78    */
79   struct GNUNET_CRYPTO_EcdsaPublicKey *iter_pkey;
80
81   /**
82    * Iteration result found
83    */
84   int iter_result_found;
85
86 };
87
88 struct FlatFileEntry
89 {
90   /**
91    * Entry zone
92    */
93   struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key;
94
95   /**
96    * Record cound
97    */
98   uint32_t record_count;
99
100   /**
101    * Rvalue
102    */
103   uint64_t rvalue;
104
105   /**
106    * Record data
107    */
108   struct GNUNET_GNSRECORD_Data *record_data;
109
110   /**
111    * Label
112    */
113   char *label;
114
115
116 };
117
118
119 /**
120  * Initialize the database connections and associated
121  * data structures (create tables and indices
122  * as needed as well).
123  *
124  * @param plugin the plugin context (state for this module)
125  * @return #GNUNET_OK on success
126  */
127 static int
128 database_setup (struct Plugin *plugin)
129 {
130   char *afsdir;
131   char *key;
132   char *record_data;
133   char *zone_private_key;
134   char *record_data_b64;
135   char *buffer;
136   char *line;
137   char *label;
138   char *rvalue;
139   char *record_count;
140   size_t record_data_size;
141   size_t size;
142   size_t key_len;
143   struct GNUNET_HashCode hkey;
144   struct GNUNET_DISK_FileHandle *fh;
145   struct FlatFileEntry *entry;
146
147   if (GNUNET_OK !=
148       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
149                                                "namestore-flat",
150                                                "FILENAME", &afsdir))
151   {
152     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
153                                "namestore-flat", "FILENAME");
154     return GNUNET_SYSERR;
155   }
156   if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
157   {
158     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
159     {
160       GNUNET_break (0);
161       GNUNET_free (afsdir);
162       return GNUNET_SYSERR;
163     }
164   }
165   /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
166   plugin->fn = afsdir;
167
168   /* Load data from file into hashmap */
169   plugin->hm = GNUNET_CONTAINER_multihashmap_create (10,
170                                                      GNUNET_NO);
171   fh = GNUNET_DISK_file_open (afsdir,
172                               GNUNET_DISK_OPEN_CREATE |
173                               GNUNET_DISK_OPEN_READWRITE,
174                               GNUNET_DISK_PERM_USER_WRITE |
175                               GNUNET_DISK_PERM_USER_READ);
176   if (NULL == fh)
177   {
178     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
179          _("Unable to initialize file: %s.\n"),
180          afsdir);
181     return GNUNET_SYSERR;
182   }
183
184   if (GNUNET_SYSERR == GNUNET_DISK_file_size (afsdir,
185                                               &size,
186                                               GNUNET_YES,
187                                               GNUNET_YES))
188   {
189     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
190          _("Unable to get filesize: %s.\n"),
191          afsdir);
192     return GNUNET_SYSERR;
193   }
194
195   buffer = GNUNET_malloc (size);
196
197   if (GNUNET_SYSERR == GNUNET_DISK_file_read (fh,
198                                               buffer,
199                                               size))
200   {
201     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
202          _("Unable to read file: %s.\n"),
203          afsdir);
204     return GNUNET_SYSERR;
205   }
206
207   GNUNET_DISK_file_close (fh);
208   if (0 < size) {
209     line = strtok (buffer, "\n");
210     while (line != NULL) {
211       zone_private_key = strtok (line, ",");
212       if (NULL == zone_private_key)
213         break;
214       rvalue = strtok (NULL, ",");
215       if (NULL == rvalue)
216         break;
217       record_count = strtok (NULL, ",");
218       if (NULL == record_count)
219         break;
220       record_data_b64 = strtok (NULL, ",");
221       if (NULL == record_data_b64)
222         break;
223       label = strtok (NULL, ",");
224       if (NULL == label)
225         break;
226       line = strtok (NULL, "\n");
227       entry = GNUNET_malloc (sizeof (struct FlatFileEntry));
228       if (1 != sscanf (rvalue, "%lu", &entry->rvalue))
229       {
230         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
231                     "Error parsing entry\n");
232         GNUNET_free (entry);
233         break;
234       }
235       if (1 != sscanf (record_count, "%u", &entry->record_count))
236       {
237         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
238                     "Error parsing entry\n");
239         GNUNET_free (entry);
240         break;
241       }
242       entry->label = GNUNET_strdup (label);
243       record_data_size = GNUNET_STRINGS_base64_decode (record_data_b64,
244                                                        strlen (record_data_b64),
245                                                        &record_data);
246       entry->record_data =
247         GNUNET_malloc (sizeof (struct GNUNET_GNSRECORD_Data) * entry->record_count);
248       if (GNUNET_OK != GNUNET_GNSRECORD_records_deserialize (record_data_size,
249                                                              record_data,
250                                                              entry->record_count,
251                                                              entry->record_data))
252       {
253         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
254                     "Unable to deserialize record %s\n", label);
255         GNUNET_free (entry->label);
256         GNUNET_free (entry);
257         GNUNET_free (record_data);
258         break;
259       }
260       GNUNET_free (record_data);
261       GNUNET_STRINGS_base64_decode (zone_private_key,
262                                     strlen (zone_private_key),
263                                     (char**)&entry->private_key);
264       key_len = strlen (label) + sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey);
265       key = GNUNET_malloc (strlen (label) + sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
266       GNUNET_memcpy (key, label, strlen (label));
267       GNUNET_memcpy (key+strlen(label),
268               entry->private_key,
269               sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
270       GNUNET_CRYPTO_hash (key,
271                           key_len,
272                           &hkey);
273       GNUNET_free (key);
274       if (GNUNET_OK !=
275           GNUNET_CONTAINER_multihashmap_put (plugin->hm,
276                                              &hkey,
277                                              entry,
278                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
279       {
280         GNUNET_free (entry);
281         GNUNET_break (0);
282       }
283     }
284   }
285   GNUNET_free (buffer);
286   return GNUNET_OK;
287 }
288
289
290 /**
291  * Store values in hashmap in file and free data
292  *
293  * @param plugin the plugin context
294  */
295 static int
296 store_and_free_entries (void *cls,
297                         const struct GNUNET_HashCode *key,
298                         void *value)
299 {
300   struct GNUNET_DISK_FileHandle *fh = cls;
301   struct FlatFileEntry *entry = value;
302   char *line;
303   char *zone_private_key;
304   char *record_data_b64;
305   size_t data_size;
306
307   GNUNET_STRINGS_base64_encode ((char*)entry->private_key,
308                                 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
309                                 &zone_private_key);
310   data_size = GNUNET_GNSRECORD_records_get_size (entry->record_count,
311                                                  entry->record_data);
312   {
313     char data[data_size];
314
315     if (data_size !=
316         GNUNET_GNSRECORD_records_serialize (entry->record_count,
317                                             entry->record_data,
318                                             data_size,
319                                             data))
320     {
321       GNUNET_break (0);
322       GNUNET_free (zone_private_key);
323       return GNUNET_SYSERR;
324     }
325     GNUNET_STRINGS_base64_encode (data,
326                                   data_size,
327                                   &record_data_b64);
328   }
329   GNUNET_asprintf (&line,
330                    "%s,%lu,%u,%s,%s\n",
331                    zone_private_key,
332                    entry->rvalue,
333                    entry->record_count,
334                    record_data_b64,
335                    entry->label);
336   GNUNET_free (record_data_b64);
337   GNUNET_free (zone_private_key);
338
339   GNUNET_DISK_file_write (fh,
340                           line,
341                           strlen (line));
342
343   GNUNET_free (entry->private_key);
344   GNUNET_free (entry->label);
345   GNUNET_free (entry->record_data);
346   GNUNET_free (entry);
347   return GNUNET_YES;
348 }
349
350 /**
351  * Shutdown database connection and associate data
352  * structures.
353  * @param plugin the plugin context (state for this module)
354  */
355 static void
356 database_shutdown (struct Plugin *plugin)
357 {
358   struct GNUNET_DISK_FileHandle *fh;
359   fh = GNUNET_DISK_file_open (plugin->fn,
360                               GNUNET_DISK_OPEN_CREATE |
361                               GNUNET_DISK_OPEN_TRUNCATE |
362                               GNUNET_DISK_OPEN_READWRITE,
363                               GNUNET_DISK_PERM_USER_WRITE |
364                               GNUNET_DISK_PERM_USER_READ);
365   if (NULL == fh)
366   {
367     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
368                 _("Unable to initialize file: %s.\n"),
369                 plugin->fn);
370     return;
371   }
372
373   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
374                                          &store_and_free_entries,
375                                          fh);
376   GNUNET_CONTAINER_multihashmap_destroy (plugin->hm);
377   GNUNET_DISK_file_close (fh);
378 }
379
380
381 /**
382  * Store a record in the datastore.  Removes any existing record in the
383  * same zone with the same name.
384  *
385  * @param cls closure (internal context for the plugin)
386  * @param zone_key private key of the zone
387  * @param label name that is being mapped (at most 255 characters long)
388  * @param rd_count number of entries in @a rd array
389  * @param rd array of records with data to store
390  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
391  */
392 static int
393 namestore_store_records (void *cls,
394                          const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
395                          const char *label,
396                          unsigned int rd_count,
397                          const struct GNUNET_GNSRECORD_Data *rd)
398 {
399   struct Plugin *plugin = cls;
400   uint64_t rvalue;
401   size_t key_len;
402   char *key;
403   struct GNUNET_HashCode hkey;
404   struct FlatFileEntry *entry;
405   int i;
406
407   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
408   key_len = strlen (label) + sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey);
409   key = GNUNET_malloc (key_len);
410   GNUNET_memcpy (key, label, strlen (label));
411   GNUNET_memcpy (key+strlen(label),
412           zone_key,
413           sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
414   GNUNET_CRYPTO_hash (key,
415                       key_len,
416                       &hkey);
417
418   GNUNET_CONTAINER_multihashmap_remove_all (plugin->hm, &hkey);
419
420   if (0 < rd_count)
421   {
422     entry = GNUNET_malloc (sizeof (struct FlatFileEntry));
423     entry->private_key = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
424     GNUNET_asprintf (&entry->label,
425                      label,
426                      strlen (label));
427     GNUNET_memcpy (entry->private_key,
428             zone_key,
429             sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
430     entry->rvalue = rvalue;
431     entry->record_count = rd_count;
432     entry->record_data = GNUNET_malloc (sizeof (struct GNUNET_GNSRECORD_Data) * rd_count);
433     for (i = 0; i < rd_count; i++)
434     {
435       entry->record_data[i].expiration_time = rd[i].expiration_time;
436       entry->record_data[i].record_type = rd[i].record_type;
437       entry->record_data[i].flags = rd[i].flags;
438       entry->record_data[i].data_size = rd[i].data_size;
439       entry->record_data[i].data = GNUNET_malloc (rd[i].data_size);
440       GNUNET_memcpy ((char*)entry->record_data[i].data, rd[i].data, rd[i].data_size);
441     }
442     return GNUNET_CONTAINER_multihashmap_put (plugin->hm,
443                                               &hkey,
444                                               entry,
445                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
446   }
447   return GNUNET_NO;
448 }
449
450
451 /**
452  * Lookup records in the datastore for which we are the authority.
453  *
454  * @param cls closure (internal context for the plugin)
455  * @param zone private key of the zone
456  * @param label name of the record in the zone
457  * @param iter function to call with the result
458  * @param iter_cls closure for @a iter
459  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
460  */
461 static int
462 namestore_lookup_records (void *cls,
463                           const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
464                           const char *label,
465                           GNUNET_NAMESTORE_RecordIterator iter,
466                           void *iter_cls)
467 {
468   struct Plugin *plugin = cls;
469   struct FlatFileEntry *entry;
470   struct GNUNET_HashCode hkey;
471   char *key;
472   size_t key_len;
473
474   if (NULL == zone)
475   {
476     return GNUNET_SYSERR;
477   }
478   key_len = strlen (label) + sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey);
479   key = GNUNET_malloc (key_len);
480   GNUNET_memcpy (key, label, strlen (label));
481   GNUNET_memcpy (key+strlen(label),
482           zone,
483           sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
484   GNUNET_CRYPTO_hash (key,
485                       key_len,
486                       &hkey);
487   GNUNET_free (key);
488
489   entry = GNUNET_CONTAINER_multihashmap_get (plugin->hm, &hkey);
490
491   if (NULL == entry)
492     return GNUNET_NO;
493   if (NULL != iter)
494     iter (iter_cls, entry->private_key, entry->label, entry->record_count, entry->record_data);
495   return GNUNET_YES;
496 }
497
498
499 static int
500 iterate_zones (void *cls,
501                const struct GNUNET_HashCode *key,
502                void *value)
503 {
504   struct Plugin *plugin = cls;
505   struct FlatFileEntry *entry = value;
506
507   if ((plugin->target_offset > plugin->offset) ||
508       ( (NULL != plugin->iter_zone) &&
509         (0 != memcmp (entry->private_key,
510                       plugin->iter_zone,
511                       sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))))) {
512     plugin->offset++;
513     return GNUNET_YES;
514   }
515   plugin->iter (plugin->iter_cls,
516                 entry->private_key,
517                 entry->label,
518                 entry->record_count,
519                 entry->record_data);
520   plugin->iter_result_found = GNUNET_YES;
521   return GNUNET_NO;
522 }
523
524 /**
525  * Iterate over the results for a particular key and zone in the
526  * datastore.  Will return at most one result to the iterator.
527  *
528  * @param cls closure (internal context for the plugin)
529  * @param zone hash of public key of the zone, NULL to iterate over all zones
530  * @param offset offset in the list of all matching records
531  * @param iter function to call with the result
532  * @param iter_cls closure for @a iter
533  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
534  */
535 static int
536 namestore_iterate_records (void *cls,
537                            const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
538                            uint64_t offset,
539                            GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
540 {
541   struct Plugin *plugin = cls;
542   plugin->target_offset = offset;
543   plugin->offset = 0;
544   plugin->iter = iter;
545   plugin->iter_cls = iter_cls;
546   plugin->iter_zone = zone;
547   plugin->iter_result_found = GNUNET_NO;
548   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
549                                          &iterate_zones,
550                                          plugin);
551   return plugin->iter_result_found;
552 }
553
554 static int
555 zone_to_name (void *cls,
556               const struct GNUNET_HashCode *key,
557               void *value)
558 {
559   struct Plugin *plugin = cls;
560   struct FlatFileEntry *entry = value;
561   int i;
562
563   if (0 != memcmp (entry->private_key,
564                    plugin->iter_zone,
565                    sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
566     return GNUNET_YES;
567
568   for (i = 0; i < entry->record_count; i++) {
569     if (GNUNET_GNSRECORD_TYPE_PKEY != entry->record_data[i].record_type)
570       continue;
571     if (0 == memcmp (plugin->iter_pkey,
572                      entry->record_data[i].data,
573                      sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)))
574     {
575       plugin->iter (plugin->iter_cls,
576                     entry->private_key,
577                     entry->label,
578                     entry->record_count,
579                     entry->record_data);
580       plugin->iter_result_found = GNUNET_YES;
581
582     }
583   }
584
585   return GNUNET_YES;
586 }
587
588 /**
589  * Look for an existing PKEY delegation record for a given public key.
590  * Returns at most one result to the iterator.
591  *
592  * @param cls closure (internal context for the plugin)
593  * @param zone private key of the zone to look up in, never NULL
594  * @param value_zone public key of the target zone (value), never NULL
595  * @param iter function to call with the result
596  * @param iter_cls closure for @a iter
597  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
598  */
599 static int
600 namestore_zone_to_name (void *cls,
601                         const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
602                         const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
603                         GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
604 {
605   struct Plugin *plugin = cls;
606
607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
608               "Performing reverse lookup for `%s'\n",
609               GNUNET_GNSRECORD_z2s (value_zone));
610
611   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
612                                          &zone_to_name,
613                                          plugin);
614
615
616   return plugin->iter_result_found;
617 }
618
619
620 /**
621  * Entry point for the plugin.
622  *
623  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
624  * @return NULL on error, otherwise the plugin context
625  */
626 void *
627 libgnunet_plugin_namestore_flat_init (void *cls)
628 {
629   static struct Plugin plugin;
630   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
631   struct GNUNET_NAMESTORE_PluginFunctions *api;
632
633   if (NULL != plugin.cfg)
634     return NULL;                /* can only initialize once! */
635   memset (&plugin, 0, sizeof (struct Plugin));
636   plugin.cfg = cfg;
637   if (GNUNET_OK != database_setup (&plugin))
638   {
639     database_shutdown (&plugin);
640     return NULL;
641   }
642   api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
643   api->cls = &plugin;
644   api->store_records = &namestore_store_records;
645   api->iterate_records = &namestore_iterate_records;
646   api->zone_to_name = &namestore_zone_to_name;
647   api->lookup_records = &namestore_lookup_records;
648   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
649               _("flat file database running\n"));
650   return api;
651 }
652
653
654 /**
655  * Exit point from the plugin.
656  *
657  * @param cls the plugin context (as returned by "init")
658  * @return always NULL
659  */
660 void *
661 libgnunet_plugin_namestore_flat_done (void *cls)
662 {
663   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
664   struct Plugin *plugin = api->cls;
665
666   database_shutdown (plugin);
667   plugin->cfg = NULL;
668   GNUNET_free (api);
669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
670               "flat file plugin is finished\n");
671   return NULL;
672 }
673
674 /* end of plugin_namestore_flat.c */