d9bc5b212baf0a365393c95856f4fce54ded2f80
[oweals/gnunet.git] / src / namestore / plugin_namestore_sqlite.c
1 /*
2  * This file is part of GNUnet
3  * Copyright (C) 2009-2017 GNUnet e.V.
4  *
5  * GNUnet is free software: you can redistribute it and/or modify it
6  * under the terms of the GNU Affero General Public License as published
7  * by the Free Software Foundation, either version 3 of the License,
8  * or (at your 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  * Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 /**
20  * @file namestore/plugin_namestore_sqlite.c
21  * @brief sqlite-based namestore backend
22  * @author Christian Grothoff
23  */
24
25 #include "platform.h"
26 #include "gnunet_namestore_plugin.h"
27 #include "gnunet_namestore_service.h"
28 #include "gnunet_gnsrecord_lib.h"
29 #include "gnunet_sq_lib.h"
30 #include "namestore.h"
31 #include <sqlite3.h>
32
33 /**
34  * After how many ms "busy" should a DB operation fail for good?  A
35  * low value makes sure that we are more responsive to requests
36  * (especially PUTs).  A high value guarantees a higher success rate
37  * (SELECTs in iterate can take several seconds despite LIMIT=1).
38  *
39  * The default value of 1s should ensure that users do not experience
40  * huge latencies while at the same time allowing operations to
41  * succeed with reasonable probability.
42  */
43 #define BUSY_TIMEOUT_MS 1000
44
45
46 /**
47  * Log an error message at log-level 'level' that indicates
48  * a failure of the command 'cmd' on file 'filename'
49  * with the message given by strerror(errno).
50  */
51 #define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from (level, "namestore-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
52
53 #define LOG(kind,...) GNUNET_log_from (kind, "namestore-sqlite", __VA_ARGS__)
54
55
56 /**
57  * Context for all functions in this plugin.
58  */
59 struct Plugin
60 {
61
62   const struct GNUNET_CONFIGURATION_Handle *cfg;
63
64   /**
65    * Database filename.
66    */
67   char *fn;
68
69   /**
70    * Native SQLite database handle.
71    */
72   sqlite3 *dbh;
73
74   /**
75    * Precompiled SQL to store records.
76    */
77   sqlite3_stmt *store_records;
78
79   /**
80    * Precompiled SQL to deltete existing records.
81    */
82   sqlite3_stmt *delete_records;
83
84   /**
85    * Precompiled SQL for iterate records within a zone.
86    */
87   sqlite3_stmt *iterate_zone;
88
89   /**
90    * Precompiled SQL for iterate all records within all zones.
91    */
92   sqlite3_stmt *iterate_all_zones;
93
94   /**
95    * Precompiled SQL to for reverse lookup based on PKEY.
96    */
97   sqlite3_stmt *zone_to_name;
98
99   /**
100    * Precompiled SQL to lookup records based on label.
101    */
102   sqlite3_stmt *lookup_label;
103 };
104
105
106 /**
107  * Initialize the database connections and associated
108  * data structures (create tables and indices
109  * as needed as well).
110  *
111  * @param plugin the plugin context (state for this module)
112  * @return #GNUNET_OK on success
113  */
114 static int
115 database_setup (struct Plugin *plugin)
116 {
117   char *sqlite_filename;
118   struct GNUNET_SQ_ExecuteStatement es[] = {
119     GNUNET_SQ_make_try_execute ("PRAGMA temp_store=MEMORY"),
120     GNUNET_SQ_make_try_execute ("PRAGMA synchronous=NORMAL"),
121     GNUNET_SQ_make_try_execute ("PRAGMA legacy_file_format=OFF"),
122     GNUNET_SQ_make_try_execute ("PRAGMA auto_vacuum=INCREMENTAL"),
123     GNUNET_SQ_make_try_execute ("PRAGMA encoding=\"UTF-8\""),
124     GNUNET_SQ_make_try_execute ("PRAGMA locking_mode=EXCLUSIVE"),
125     GNUNET_SQ_make_try_execute ("PRAGMA page_size=4092"),
126     GNUNET_SQ_make_execute ("CREATE TABLE IF NOT EXISTS ns098records ("
127                             " uid INTEGER PRIMARY KEY,"
128                             " zone_private_key BLOB NOT NULL,"
129                             " pkey BLOB,"
130                             " rvalue INT8 NOT NULL,"
131                             " record_count INT NOT NULL,"
132                             " record_data BLOB NOT NULL,"
133                             " label TEXT NOT NULL"
134                             ")"),
135     GNUNET_SQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_reverse "
136                                 "ON ns098records (zone_private_key,pkey)"),
137     GNUNET_SQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_iter "
138                                 "ON ns098records (zone_private_key,uid)"),
139     GNUNET_SQ_EXECUTE_STATEMENT_END
140   };
141   struct GNUNET_SQ_PrepareStatement ps[] = {
142     GNUNET_SQ_make_prepare ("INSERT INTO ns098records "
143                             "(zone_private_key,pkey,rvalue,record_count,record_data,label)"
144                             " VALUES (?, ?, ?, ?, ?, ?)",
145                             &plugin->store_records),
146     GNUNET_SQ_make_prepare ("DELETE FROM ns098records "
147                             "WHERE zone_private_key=? AND label=?",
148                             &plugin->delete_records),
149     GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label"
150                             " FROM ns098records"
151                             " WHERE zone_private_key=? AND pkey=?",
152                             &plugin->zone_to_name),
153     GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label"
154                             " FROM ns098records"
155                             " WHERE zone_private_key=? AND uid > ?"
156                             " ORDER BY uid ASC"
157                             " LIMIT ?",
158                             &plugin->iterate_zone),
159     GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label,zone_private_key"
160                             " FROM ns098records"
161                             " WHERE uid > ?"
162                             " ORDER BY uid ASC"
163                             " LIMIT ?",
164                             &plugin->iterate_all_zones),
165     GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label,zone_private_key"
166                             " FROM ns098records"
167                             " WHERE zone_private_key=? AND label=?",
168                             &plugin->lookup_label),
169     GNUNET_SQ_PREPARE_END
170   };
171
172   if (GNUNET_OK !=
173       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
174                                                "namestore-sqlite",
175                                                "FILENAME",
176                                                &sqlite_filename))
177   {
178     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
179                                "namestore-sqlite",
180                                "FILENAME");
181     return GNUNET_SYSERR;
182   }
183   if (GNUNET_OK !=
184       GNUNET_DISK_file_test (sqlite_filename))
185   {
186     if (GNUNET_OK !=
187         GNUNET_DISK_directory_create_for_file (sqlite_filename))
188     {
189       GNUNET_break (0);
190       GNUNET_free (sqlite_filename);
191       return GNUNET_SYSERR;
192     }
193   }
194   /* sqlite_filename should be UTF-8-encoded. If it isn't, it's a bug */
195   plugin->fn = sqlite_filename;
196
197   /* Open database and precompile statements */
198   if (SQLITE_OK !=
199       sqlite3_open (plugin->fn,
200                     &plugin->dbh))
201   {
202     LOG (GNUNET_ERROR_TYPE_ERROR,
203          _("Unable to initialize SQLite: %s.\n"),
204          sqlite3_errmsg (plugin->dbh));
205     return GNUNET_SYSERR;
206   }
207   GNUNET_break (SQLITE_OK ==
208                 sqlite3_busy_timeout (plugin->dbh,
209                                       BUSY_TIMEOUT_MS));
210   if (GNUNET_OK !=
211       GNUNET_SQ_exec_statements (plugin->dbh,
212                                  es))
213   {
214     GNUNET_break (0);
215     LOG (GNUNET_ERROR_TYPE_ERROR,
216          _("Failed to setup database at `%s'\n"),
217          plugin->fn);
218     return GNUNET_SYSERR;
219   }
220
221   if (GNUNET_OK !=
222       GNUNET_SQ_prepare (plugin->dbh,
223                          ps))
224   {
225     GNUNET_break (0);
226     LOG (GNUNET_ERROR_TYPE_ERROR,
227          _("Failed to setup database at `%s'\n"),
228          plugin->fn);
229     return GNUNET_SYSERR;
230   }
231   return GNUNET_OK;
232 }
233
234
235 /**
236  * Shutdown database connection and associate data
237  * structures.
238  * @param plugin the plugin context (state for this module)
239  */
240 static void
241 database_shutdown (struct Plugin *plugin)
242 {
243   int result;
244   sqlite3_stmt *stmt;
245
246   if (NULL != plugin->store_records)
247     sqlite3_finalize (plugin->store_records);
248   if (NULL != plugin->delete_records)
249     sqlite3_finalize (plugin->delete_records);
250   if (NULL != plugin->iterate_zone)
251     sqlite3_finalize (plugin->iterate_zone);
252   if (NULL != plugin->iterate_all_zones)
253     sqlite3_finalize (plugin->iterate_all_zones);
254   if (NULL != plugin->zone_to_name)
255     sqlite3_finalize (plugin->zone_to_name);
256   if (NULL != plugin->lookup_label)
257     sqlite3_finalize (plugin->lookup_label);
258   result = sqlite3_close (plugin->dbh);
259   if (result == SQLITE_BUSY)
260   {
261     LOG (GNUNET_ERROR_TYPE_WARNING,
262          _("Tried to close sqlite without finalizing all prepared statements.\n"));
263     stmt = sqlite3_next_stmt (plugin->dbh,
264                               NULL);
265     while (NULL != stmt)
266     {
267       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
268                        "sqlite",
269                        "Closing statement %p\n",
270                        stmt);
271       result = sqlite3_finalize (stmt);
272       if (result != SQLITE_OK)
273         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
274                          "sqlite",
275                          "Failed to close statement %p: %d\n",
276                          stmt,
277                          result);
278       stmt = sqlite3_next_stmt (plugin->dbh,
279                                 NULL);
280     }
281     result = sqlite3_close (plugin->dbh);
282   }
283   if (SQLITE_OK != result)
284     LOG_SQLITE (plugin,
285                 GNUNET_ERROR_TYPE_ERROR,
286                 "sqlite3_close");
287
288   GNUNET_free_non_null (plugin->fn);
289 }
290
291
292 /**
293  * Store a record in the datastore.  Removes any existing record in the
294  * same zone with the same name.
295  *
296  * @param cls closure (internal context for the plugin)
297  * @param zone_key private key of the zone
298  * @param label name that is being mapped (at most 255 characters long)
299  * @param rd_count number of entries in @a rd array
300  * @param rd array of records with data to store
301  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
302  */
303 static int
304 namestore_sqlite_store_records (void *cls,
305                                 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
306                                 const char *label,
307                                 unsigned int rd_count,
308                                 const struct GNUNET_GNSRECORD_Data *rd)
309 {
310   struct Plugin *plugin = cls;
311   int n;
312   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
313   uint64_t rvalue;
314   ssize_t data_size;
315
316   memset (&pkey,
317           0,
318           sizeof (pkey));
319   for (unsigned int i=0;i<rd_count;i++)
320     if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
321     {
322       GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) ==
323                     rd[i].data_size);
324       GNUNET_memcpy (&pkey,
325                      rd[i].data,
326                      rd[i].data_size);
327       break;
328     }
329   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
330                                      UINT64_MAX);
331   data_size = GNUNET_GNSRECORD_records_get_size (rd_count,
332                                                  rd);
333   if (data_size < 0)
334   {
335     GNUNET_break (0);
336     return GNUNET_SYSERR;
337   }
338   if (data_size > 64 * 65536)
339   {
340     GNUNET_break (0);
341     return GNUNET_SYSERR;
342   }
343   {
344     /* First delete 'old' records */
345     char data[data_size];
346     struct GNUNET_SQ_QueryParam dparams[] = {
347       GNUNET_SQ_query_param_auto_from_type (zone_key),
348       GNUNET_SQ_query_param_string (label),
349       GNUNET_SQ_query_param_end
350     };
351     ssize_t ret;
352
353     ret = GNUNET_GNSRECORD_records_serialize (rd_count,
354                                               rd,
355                                               data_size,
356                                               data);
357     if ( (ret < 0) ||
358          (data_size != ret) )
359     {
360       GNUNET_break (0);
361       return GNUNET_SYSERR;
362     }
363     if (GNUNET_OK !=
364         GNUNET_SQ_bind (plugin->delete_records,
365                         dparams))
366     {
367       LOG_SQLITE (plugin,
368                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
369                   "sqlite3_bind_XXXX");
370       GNUNET_SQ_reset (plugin->dbh,
371                        plugin->delete_records);
372       return GNUNET_SYSERR;
373
374     }
375     n = sqlite3_step (plugin->delete_records);
376     GNUNET_SQ_reset (plugin->dbh,
377                      plugin->delete_records);
378
379     if (0 != rd_count)
380     {
381       uint32_t rd_count32 = (uint32_t) rd_count;
382       struct GNUNET_SQ_QueryParam sparams[] = {
383         GNUNET_SQ_query_param_auto_from_type (zone_key),
384         GNUNET_SQ_query_param_auto_from_type (&pkey),
385         GNUNET_SQ_query_param_uint64 (&rvalue),
386         GNUNET_SQ_query_param_uint32 (&rd_count32),
387         GNUNET_SQ_query_param_fixed_size (data, data_size),
388         GNUNET_SQ_query_param_string (label),
389         GNUNET_SQ_query_param_end
390       };
391
392       if (GNUNET_OK !=
393           GNUNET_SQ_bind (plugin->store_records,
394                           sparams))
395       {
396         LOG_SQLITE (plugin,
397                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
398                     "sqlite3_bind_XXXX");
399         GNUNET_SQ_reset (plugin->dbh,
400                          plugin->store_records);
401         return GNUNET_SYSERR;
402       }
403       n = sqlite3_step (plugin->store_records);
404       GNUNET_SQ_reset (plugin->dbh,
405                        plugin->store_records);
406     }
407   }
408   switch (n)
409   {
410     case SQLITE_DONE:
411       if (0 != rd_count)
412         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
413                          "sqlite",
414                          "Record stored\n");
415       else
416         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
417                          "sqlite",
418                          "Record deleted\n");
419       return GNUNET_OK;
420     case SQLITE_BUSY:
421       LOG_SQLITE (plugin,
422                   GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
423                   "sqlite3_step");
424       return GNUNET_NO;
425     default:
426       LOG_SQLITE (plugin,
427                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
428                   "sqlite3_step");
429       return GNUNET_SYSERR;
430   }
431 }
432
433
434 /**
435  * The given 'sqlite' statement has been prepared to be run.
436  * It will return a record which should be given to the iterator.
437  * Runs the statement and parses the returned record.
438  *
439  * @param plugin plugin context
440  * @param stmt to run (and then clean up)
441  * @param zone_key private key of the zone
442  * @param limit maximum number of results to fetch
443  * @param iter iterator to call with the result
444  * @param iter_cls closure for @a iter
445  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
446  */
447 static int
448 get_records_and_call_iterator (struct Plugin *plugin,
449                                sqlite3_stmt *stmt,
450                                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
451                                uint64_t limit,
452                                GNUNET_NAMESTORE_RecordIterator iter,
453                                void *iter_cls)
454 {
455   int ret;
456   int sret;
457
458   ret = GNUNET_OK;
459   for (uint64_t i = 0;i<limit;i++)
460   {
461     sret = sqlite3_step (stmt);
462
463     if (SQLITE_DONE == sret)
464     {
465       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
466                   "Iteration done (no results)\n");
467       ret = GNUNET_NO;
468       break;
469     }
470     if (SQLITE_ROW != sret)
471     {
472       LOG_SQLITE (plugin,
473                   GNUNET_ERROR_TYPE_ERROR,
474                   "sqlite_step");
475       ret = GNUNET_SYSERR;
476       break;
477     }
478
479     {
480       uint64_t seq;
481       uint32_t record_count;
482       size_t data_size;
483       void *data;
484       char *label;
485       struct GNUNET_CRYPTO_EcdsaPrivateKey zk;
486       struct GNUNET_SQ_ResultSpec rs[] = {
487         GNUNET_SQ_result_spec_uint64 (&seq),
488         GNUNET_SQ_result_spec_uint32 (&record_count),
489         GNUNET_SQ_result_spec_variable_size (&data,
490                                              &data_size),
491         GNUNET_SQ_result_spec_string (&label),
492         GNUNET_SQ_result_spec_end
493       };
494       struct GNUNET_SQ_ResultSpec rsx[] = {
495         GNUNET_SQ_result_spec_uint64 (&seq),
496         GNUNET_SQ_result_spec_uint32 (&record_count),
497         GNUNET_SQ_result_spec_variable_size (&data,
498                                              &data_size),
499         GNUNET_SQ_result_spec_string (&label),
500         GNUNET_SQ_result_spec_auto_from_type (&zk),
501         GNUNET_SQ_result_spec_end
502       };
503
504       if (NULL == zone_key)
505       {
506         ret = GNUNET_SQ_extract_result (stmt,
507                                         rsx);
508       }
509       else
510       {
511         ret = GNUNET_SQ_extract_result (stmt,
512                                         rs);
513       }
514       if ( (GNUNET_OK != ret) ||
515            (record_count > 64 * 1024) )
516       {
517         /* sanity check, don't stack allocate far too much just
518            because database might contain a large value here */
519         GNUNET_break (0);
520         ret = GNUNET_SYSERR;
521         break;
522       }
523       else
524       {
525         struct GNUNET_GNSRECORD_Data rd[record_count];
526
527         if (GNUNET_OK !=
528             GNUNET_GNSRECORD_records_deserialize (data_size,
529                                                   data,
530                                                   record_count,
531                                                   rd))
532         {
533           GNUNET_break (0);
534           ret = GNUNET_SYSERR;
535           break;
536         }
537         else
538         {
539           if (NULL != zone_key)
540             zk = *zone_key;
541           if (NULL != iter)
542             iter (iter_cls,
543                   seq,
544                   &zk,
545                   label,
546                   record_count,
547                   rd);
548         }
549       }
550       GNUNET_SQ_cleanup_result (rs);
551     }
552   }
553   GNUNET_SQ_reset (plugin->dbh,
554                    stmt);
555   return ret;
556 }
557
558
559 /**
560  * Lookup records in the datastore for which we are the authority.
561  *
562  * @param cls closure (internal context for the plugin)
563  * @param zone private key of the zone
564  * @param label name of the record in the zone
565  * @param iter function to call with the result
566  * @param iter_cls closure for @a iter
567  * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR
568  */
569 static int
570 namestore_sqlite_lookup_records (void *cls,
571                                  const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
572                                  const char *label,
573                                  GNUNET_NAMESTORE_RecordIterator iter,
574                                  void *iter_cls)
575 {
576   struct Plugin *plugin = cls;
577   struct GNUNET_SQ_QueryParam params[] = {
578     GNUNET_SQ_query_param_auto_from_type (zone),
579     GNUNET_SQ_query_param_string (label),
580     GNUNET_SQ_query_param_end
581   };
582
583   if (NULL == zone)
584   {
585     GNUNET_break (0);
586     return GNUNET_SYSERR;
587   }
588   if (GNUNET_OK !=
589       GNUNET_SQ_bind (plugin->lookup_label,
590                       params))
591   {
592     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
593                 "sqlite3_bind_XXXX");
594     GNUNET_SQ_reset (plugin->dbh,
595                      plugin->lookup_label);
596     return GNUNET_SYSERR;
597   }
598   return get_records_and_call_iterator (plugin,
599                                         plugin->lookup_label,
600                                         zone,
601                                         1,
602                                         iter,
603                                         iter_cls);
604 }
605
606
607 /**
608  * Iterate over the results for a particular key and zone in the
609  * datastore.  Will return at most one result to the iterator.
610  *
611  * @param cls closure (internal context for the plugin)
612  * @param zone hash of public key of the zone, NULL to iterate over all zones
613  * @param serial serial number to exclude in the list of all matching records
614  * @param limit maximum number of results to return
615  * @param iter function to call with the result
616  * @param iter_cls closure for @a iter
617  * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error
618  */
619 static int
620 namestore_sqlite_iterate_records (void *cls,
621                                   const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
622                                   uint64_t serial,
623                                   uint64_t limit,
624                                   GNUNET_NAMESTORE_RecordIterator iter,
625                                   void *iter_cls)
626 {
627   struct Plugin *plugin = cls;
628   sqlite3_stmt *stmt;
629   int err;
630
631   if (NULL == zone)
632   {
633     struct GNUNET_SQ_QueryParam params[] = {
634       GNUNET_SQ_query_param_uint64 (&serial),
635       GNUNET_SQ_query_param_uint64 (&limit),
636       GNUNET_SQ_query_param_end
637     };
638
639     stmt = plugin->iterate_all_zones;
640     err = GNUNET_SQ_bind (stmt,
641                           params);
642   }
643   else
644   {
645     struct GNUNET_SQ_QueryParam params[] = {
646       GNUNET_SQ_query_param_auto_from_type (zone),
647       GNUNET_SQ_query_param_uint64 (&serial),
648       GNUNET_SQ_query_param_uint64 (&limit),
649       GNUNET_SQ_query_param_end
650     };
651
652     stmt = plugin->iterate_zone;
653     err = GNUNET_SQ_bind (stmt,
654                           params);
655   }
656   if (GNUNET_OK != err)
657   {
658     LOG_SQLITE (plugin,
659                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
660                 "sqlite3_bind_XXXX");
661     GNUNET_SQ_reset (plugin->dbh,
662                      stmt);
663     return GNUNET_SYSERR;
664   }
665   return get_records_and_call_iterator (plugin,
666                                         stmt,
667                                         zone,
668                                         limit,
669                                         iter,
670                                         iter_cls);
671 }
672
673
674 /**
675  * Look for an existing PKEY delegation record for a given public key.
676  * Returns at most one result to the iterator.
677  *
678  * @param cls closure (internal context for the plugin)
679  * @param zone private key of the zone to look up in, never NULL
680  * @param value_zone public key of the target zone (value), never NULL
681  * @param iter function to call with the result
682  * @param iter_cls closure for @a iter
683  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
684  */
685 static int
686 namestore_sqlite_zone_to_name (void *cls,
687                                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
688                                const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
689                                GNUNET_NAMESTORE_RecordIterator iter,
690                                void *iter_cls)
691 {
692   struct Plugin *plugin = cls;
693   struct GNUNET_SQ_QueryParam params[] = {
694     GNUNET_SQ_query_param_auto_from_type (zone),
695     GNUNET_SQ_query_param_auto_from_type (value_zone),
696     GNUNET_SQ_query_param_end
697   };
698
699   if (GNUNET_OK !=
700       GNUNET_SQ_bind (plugin->zone_to_name,
701                       params))
702   {
703     LOG_SQLITE (plugin,
704                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
705                 "sqlite3_bind_XXXX");
706     GNUNET_SQ_reset (plugin->dbh,
707                      plugin->zone_to_name);
708     return GNUNET_SYSERR;
709   }
710   LOG (GNUNET_ERROR_TYPE_DEBUG,
711        "Performing reverse lookup for `%s'\n",
712        GNUNET_GNSRECORD_z2s (value_zone));
713   return get_records_and_call_iterator (plugin,
714                                         plugin->zone_to_name,
715                                         zone,
716                                         1,
717                                         iter,
718                                         iter_cls);
719 }
720
721
722 /**
723  * Entry point for the plugin.
724  *
725  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
726  * @return NULL on error, otherwise the plugin context
727  */
728 void *
729 libgnunet_plugin_namestore_sqlite_init (void *cls)
730 {
731   static struct Plugin plugin;
732   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
733   struct GNUNET_NAMESTORE_PluginFunctions *api;
734
735   if (NULL != plugin.cfg)
736     return NULL;                /* can only initialize once! */
737   memset (&plugin,
738           0,
739           sizeof (struct Plugin));
740   plugin.cfg = cfg;
741   if (GNUNET_OK != database_setup (&plugin))
742   {
743     database_shutdown (&plugin);
744     return NULL;
745   }
746   api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
747   api->cls = &plugin;
748   api->store_records = &namestore_sqlite_store_records;
749   api->iterate_records = &namestore_sqlite_iterate_records;
750   api->zone_to_name = &namestore_sqlite_zone_to_name;
751   api->lookup_records = &namestore_sqlite_lookup_records;
752   LOG (GNUNET_ERROR_TYPE_INFO,
753        _("Sqlite database running\n"));
754   return api;
755 }
756
757
758 /**
759  * Exit point from the plugin.
760  *
761  * @param cls the plugin context (as returned by "init")
762  * @return always NULL
763  */
764 void *
765 libgnunet_plugin_namestore_sqlite_done (void *cls)
766 {
767   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
768   struct Plugin *plugin = api->cls;
769
770   database_shutdown (plugin);
771   plugin->cfg = NULL;
772   GNUNET_free (api);
773   LOG (GNUNET_ERROR_TYPE_DEBUG,
774        "sqlite plugin is finished\n");
775   return NULL;
776 }
777
778 /* end of plugin_namestore_sqlite.c */