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