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