fix related to #4909/12605: force desirability of path if path is in use
[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   if (GNUNET_SYSERR ==
184       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     GNUNET_DISK_file_close (fh);
193     return GNUNET_SYSERR;
194   }
195
196   buffer = GNUNET_malloc (size + 1);
197   if (GNUNET_SYSERR ==
198       GNUNET_DISK_file_read (fh,
199                              buffer,
200                              size))
201   {
202     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
203          _("Unable to read file: %s.\n"),
204          afsdir);
205     GNUNET_free (buffer);
206     GNUNET_DISK_file_close (fh);
207     return GNUNET_SYSERR;
208   }
209   buffer[size] = '\0';
210   GNUNET_DISK_file_close (fh);
211
212   if (0 < size)
213   {
214     line = strtok (buffer, "\n");
215     while (line != NULL) {
216       zone_private_key = strtok (line, ",");
217       if (NULL == zone_private_key)
218         break;
219       rvalue = strtok (NULL, ",");
220       if (NULL == rvalue)
221         break;
222       record_count = strtok (NULL, ",");
223       if (NULL == record_count)
224         break;
225       record_data_b64 = strtok (NULL, ",");
226       if (NULL == record_data_b64)
227         break;
228       label = strtok (NULL, ",");
229       if (NULL == label)
230         break;
231       line = strtok (NULL, "\n");
232       entry = GNUNET_malloc (sizeof (struct FlatFileEntry));
233       if (1 != sscanf (rvalue, "%lu", &entry->rvalue))
234       {
235         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
236                     "Error parsing entry\n");
237         GNUNET_free (entry);
238         break;
239       }
240       if (1 != sscanf (record_count, "%u", &entry->record_count))
241       {
242         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
243                     "Error parsing entry\n");
244         GNUNET_free (entry);
245         break;
246       }
247       entry->label = GNUNET_strdup (label);
248       record_data_size = GNUNET_STRINGS_base64_decode (record_data_b64,
249                                                        strlen (record_data_b64),
250                                                        &record_data);
251       entry->record_data =
252         GNUNET_malloc (sizeof (struct GNUNET_GNSRECORD_Data) * entry->record_count);
253       if (GNUNET_OK != GNUNET_GNSRECORD_records_deserialize (record_data_size,
254                                                              record_data,
255                                                              entry->record_count,
256                                                              entry->record_data))
257       {
258         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
259                     "Unable to deserialize record %s\n", label);
260         GNUNET_free (entry->label);
261         GNUNET_free (entry);
262         GNUNET_free (record_data);
263         break;
264       }
265       GNUNET_free (record_data);
266       GNUNET_STRINGS_base64_decode (zone_private_key,
267                                     strlen (zone_private_key),
268                                     (char**)&entry->private_key);
269       key_len = strlen (label) + sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey);
270       key = GNUNET_malloc (strlen (label) + sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
271       GNUNET_memcpy (key, label, strlen (label));
272       GNUNET_memcpy (key+strlen(label),
273               entry->private_key,
274               sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
275       GNUNET_CRYPTO_hash (key,
276                           key_len,
277                           &hkey);
278       GNUNET_free (key);
279       if (GNUNET_OK !=
280           GNUNET_CONTAINER_multihashmap_put (plugin->hm,
281                                              &hkey,
282                                              entry,
283                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
284       {
285         GNUNET_free (entry);
286         GNUNET_break (0);
287       }
288     }
289   }
290   GNUNET_free (buffer);
291   return GNUNET_OK;
292 }
293
294
295 /**
296  * Store values in hashmap in file and free data
297  *
298  * @param plugin the plugin context
299  */
300 static int
301 store_and_free_entries (void *cls,
302                         const struct GNUNET_HashCode *key,
303                         void *value)
304 {
305   struct GNUNET_DISK_FileHandle *fh = cls;
306   struct FlatFileEntry *entry = value;
307   char *line;
308   char *zone_private_key;
309   char *record_data_b64;
310   size_t data_size;
311
312   GNUNET_STRINGS_base64_encode ((char*)entry->private_key,
313                                 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
314                                 &zone_private_key);
315   data_size = GNUNET_GNSRECORD_records_get_size (entry->record_count,
316                                                  entry->record_data);
317   {
318     char data[data_size];
319
320     if (data_size !=
321         GNUNET_GNSRECORD_records_serialize (entry->record_count,
322                                             entry->record_data,
323                                             data_size,
324                                             data))
325     {
326       GNUNET_break (0);
327       GNUNET_free (zone_private_key);
328       return GNUNET_SYSERR;
329     }
330     GNUNET_STRINGS_base64_encode (data,
331                                   data_size,
332                                   &record_data_b64);
333   }
334   GNUNET_asprintf (&line,
335                    "%s,%lu,%u,%s,%s\n",
336                    zone_private_key,
337                    entry->rvalue,
338                    entry->record_count,
339                    record_data_b64,
340                    entry->label);
341   GNUNET_free (record_data_b64);
342   GNUNET_free (zone_private_key);
343
344   GNUNET_DISK_file_write (fh,
345                           line,
346                           strlen (line));
347
348   GNUNET_free (line);
349   GNUNET_free (entry->private_key);
350   GNUNET_free (entry->label);
351   GNUNET_free (entry->record_data);
352   GNUNET_free (entry);
353   return GNUNET_YES;
354 }
355
356
357 /**
358  * Shutdown database connection and associate data
359  * structures.
360  * @param plugin the plugin context (state for this module)
361  */
362 static void
363 database_shutdown (struct Plugin *plugin)
364 {
365   struct GNUNET_DISK_FileHandle *fh;
366   fh = GNUNET_DISK_file_open (plugin->fn,
367                               GNUNET_DISK_OPEN_CREATE |
368                               GNUNET_DISK_OPEN_TRUNCATE |
369                               GNUNET_DISK_OPEN_READWRITE,
370                               GNUNET_DISK_PERM_USER_WRITE |
371                               GNUNET_DISK_PERM_USER_READ);
372   if (NULL == fh)
373   {
374     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
375                 _("Unable to initialize file: %s.\n"),
376                 plugin->fn);
377     return;
378   }
379
380   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
381                                          &store_and_free_entries,
382                                          fh);
383   GNUNET_CONTAINER_multihashmap_destroy (plugin->hm);
384   GNUNET_DISK_file_close (fh);
385 }
386
387
388 /**
389  * Store a record in the datastore.  Removes any existing record in the
390  * same zone with the same name.
391  *
392  * @param cls closure (internal context for the plugin)
393  * @param zone_key private key of the zone
394  * @param label name that is being mapped (at most 255 characters long)
395  * @param rd_count number of entries in @a rd array
396  * @param rd array of records with data to store
397  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
398  */
399 static int
400 namestore_store_records (void *cls,
401                          const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
402                          const char *label,
403                          unsigned int rd_count,
404                          const struct GNUNET_GNSRECORD_Data *rd)
405 {
406   struct Plugin *plugin = cls;
407   uint64_t rvalue;
408   size_t key_len;
409   char *key;
410   struct GNUNET_HashCode hkey;
411   struct FlatFileEntry *entry;
412   int i;
413
414   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
415   key_len = strlen (label) + sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey);
416   key = GNUNET_malloc (key_len);
417   GNUNET_memcpy (key, label, strlen (label));
418   GNUNET_memcpy (key+strlen(label),
419           zone_key,
420           sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
421   GNUNET_CRYPTO_hash (key,
422                       key_len,
423                       &hkey);
424
425   GNUNET_CONTAINER_multihashmap_remove_all (plugin->hm, &hkey);
426
427   if (0 < rd_count)
428   {
429     entry = GNUNET_malloc (sizeof (struct FlatFileEntry));
430     entry->private_key = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
431     GNUNET_asprintf (&entry->label,
432                      label,
433                      strlen (label));
434     GNUNET_memcpy (entry->private_key,
435             zone_key,
436             sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
437     entry->rvalue = rvalue;
438     entry->record_count = rd_count;
439     entry->record_data = GNUNET_malloc (sizeof (struct GNUNET_GNSRECORD_Data) * rd_count);
440     for (i = 0; i < rd_count; i++)
441     {
442       entry->record_data[i].expiration_time = rd[i].expiration_time;
443       entry->record_data[i].record_type = rd[i].record_type;
444       entry->record_data[i].flags = rd[i].flags;
445       entry->record_data[i].data_size = rd[i].data_size;
446       entry->record_data[i].data = GNUNET_malloc (rd[i].data_size);
447       GNUNET_memcpy ((char*)entry->record_data[i].data, rd[i].data, rd[i].data_size);
448     }
449     return GNUNET_CONTAINER_multihashmap_put (plugin->hm,
450                                               &hkey,
451                                               entry,
452                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
453   }
454   return GNUNET_NO;
455 }
456
457
458 /**
459  * Lookup records in the datastore for which we are the authority.
460  *
461  * @param cls closure (internal context for the plugin)
462  * @param zone private key of the zone
463  * @param label name of the record in the zone
464  * @param iter function to call with the result
465  * @param iter_cls closure for @a iter
466  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
467  */
468 static int
469 namestore_lookup_records (void *cls,
470                           const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
471                           const char *label,
472                           GNUNET_NAMESTORE_RecordIterator iter,
473                           void *iter_cls)
474 {
475   struct Plugin *plugin = cls;
476   struct FlatFileEntry *entry;
477   struct GNUNET_HashCode hkey;
478   char *key;
479   size_t key_len;
480
481   if (NULL == zone)
482   {
483     return GNUNET_SYSERR;
484   }
485   key_len = strlen (label) + sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey);
486   key = GNUNET_malloc (key_len);
487   GNUNET_memcpy (key, label, strlen (label));
488   GNUNET_memcpy (key+strlen(label),
489           zone,
490           sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
491   GNUNET_CRYPTO_hash (key,
492                       key_len,
493                       &hkey);
494   GNUNET_free (key);
495
496   entry = GNUNET_CONTAINER_multihashmap_get (plugin->hm, &hkey);
497
498   if (NULL == entry)
499     return GNUNET_NO;
500   if (NULL != iter)
501     iter (iter_cls, entry->private_key, entry->label, entry->record_count, entry->record_data);
502   return GNUNET_YES;
503 }
504
505
506 static int
507 iterate_zones (void *cls,
508                const struct GNUNET_HashCode *key,
509                void *value)
510 {
511   struct Plugin *plugin = cls;
512   struct FlatFileEntry *entry = value;
513
514   if ((plugin->target_offset > plugin->offset) ||
515       ( (NULL != plugin->iter_zone) &&
516         (0 != memcmp (entry->private_key,
517                       plugin->iter_zone,
518                       sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))))) {
519     plugin->offset++;
520     return GNUNET_YES;
521   }
522   plugin->iter (plugin->iter_cls,
523                 entry->private_key,
524                 entry->label,
525                 entry->record_count,
526                 entry->record_data);
527   plugin->iter_result_found = GNUNET_YES;
528   return GNUNET_NO;
529 }
530
531 /**
532  * Iterate over the results for a particular key and zone in the
533  * datastore.  Will return at most one result to the iterator.
534  *
535  * @param cls closure (internal context for the plugin)
536  * @param zone hash of public key of the zone, NULL to iterate over all zones
537  * @param offset offset in the list of all matching records
538  * @param iter function to call with the result
539  * @param iter_cls closure for @a iter
540  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
541  */
542 static int
543 namestore_iterate_records (void *cls,
544                            const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
545                            uint64_t offset,
546                            GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
547 {
548   struct Plugin *plugin = cls;
549   plugin->target_offset = offset;
550   plugin->offset = 0;
551   plugin->iter = iter;
552   plugin->iter_cls = iter_cls;
553   plugin->iter_zone = zone;
554   plugin->iter_result_found = GNUNET_NO;
555   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
556                                          &iterate_zones,
557                                          plugin);
558   return plugin->iter_result_found;
559 }
560
561 static int
562 zone_to_name (void *cls,
563               const struct GNUNET_HashCode *key,
564               void *value)
565 {
566   struct Plugin *plugin = cls;
567   struct FlatFileEntry *entry = value;
568   int i;
569
570   if (0 != memcmp (entry->private_key,
571                    plugin->iter_zone,
572                    sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
573     return GNUNET_YES;
574
575   for (i = 0; i < entry->record_count; i++) {
576     if (GNUNET_GNSRECORD_TYPE_PKEY != entry->record_data[i].record_type)
577       continue;
578     if (0 == memcmp (plugin->iter_pkey,
579                      entry->record_data[i].data,
580                      sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)))
581     {
582       plugin->iter (plugin->iter_cls,
583                     entry->private_key,
584                     entry->label,
585                     entry->record_count,
586                     entry->record_data);
587       plugin->iter_result_found = GNUNET_YES;
588
589     }
590   }
591
592   return GNUNET_YES;
593 }
594
595 /**
596  * Look for an existing PKEY delegation record for a given public key.
597  * Returns at most one result to the iterator.
598  *
599  * @param cls closure (internal context for the plugin)
600  * @param zone private key of the zone to look up in, never NULL
601  * @param value_zone public key of the target zone (value), never NULL
602  * @param iter function to call with the result
603  * @param iter_cls closure for @a iter
604  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
605  */
606 static int
607 namestore_zone_to_name (void *cls,
608                         const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
609                         const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
610                         GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
611 {
612   struct Plugin *plugin = cls;
613
614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
615               "Performing reverse lookup for `%s'\n",
616               GNUNET_GNSRECORD_z2s (value_zone));
617
618   GNUNET_CONTAINER_multihashmap_iterate (plugin->hm,
619                                          &zone_to_name,
620                                          plugin);
621
622
623   return plugin->iter_result_found;
624 }
625
626
627 /**
628  * Entry point for the plugin.
629  *
630  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
631  * @return NULL on error, otherwise the plugin context
632  */
633 void *
634 libgnunet_plugin_namestore_flat_init (void *cls)
635 {
636   static struct Plugin plugin;
637   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
638   struct GNUNET_NAMESTORE_PluginFunctions *api;
639
640   if (NULL != plugin.cfg)
641     return NULL;                /* can only initialize once! */
642   memset (&plugin, 0, sizeof (struct Plugin));
643   plugin.cfg = cfg;
644   if (GNUNET_OK != database_setup (&plugin))
645   {
646     database_shutdown (&plugin);
647     return NULL;
648   }
649   api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
650   api->cls = &plugin;
651   api->store_records = &namestore_store_records;
652   api->iterate_records = &namestore_iterate_records;
653   api->zone_to_name = &namestore_zone_to_name;
654   api->lookup_records = &namestore_lookup_records;
655   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
656               _("flat file database running\n"));
657   return api;
658 }
659
660
661 /**
662  * Exit point from the plugin.
663  *
664  * @param cls the plugin context (as returned by "init")
665  * @return always NULL
666  */
667 void *
668 libgnunet_plugin_namestore_flat_done (void *cls)
669 {
670   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
671   struct Plugin *plugin = api->cls;
672
673   database_shutdown (plugin);
674   plugin->cfg = NULL;
675   GNUNET_free (api);
676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
677               "flat file plugin is finished\n");
678   return NULL;
679 }
680
681 /* end of plugin_namestore_flat.c */