integrate dnsparser and dnsstub and tun with libgnunetutil
[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 _rowid_ >= ?"
156                             " ORDER BY _rowid_ 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 _rowid_ >= ?"
162                             " ORDER BY _rowid_ 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         zone_key = &zk;
507         ret = GNUNET_SQ_extract_result (stmt,
508                                         rsx);
509       }
510       else
511       {
512         ret = GNUNET_SQ_extract_result (stmt,
513                                         rs);
514       }
515       if ( (GNUNET_OK != ret) ||
516            (record_count > 64 * 1024) )
517       {
518         /* sanity check, don't stack allocate far too much just
519            because database might contain a large value here */
520         GNUNET_break (0);
521         ret = GNUNET_SYSERR;
522         break;
523       }
524       else
525       {
526         struct GNUNET_GNSRECORD_Data rd[record_count];
527
528         if (GNUNET_OK !=
529             GNUNET_GNSRECORD_records_deserialize (data_size,
530                                                   data,
531                                                   record_count,
532                                                   rd))
533         {
534           GNUNET_break (0);
535           ret = GNUNET_SYSERR;
536           break;
537         }
538         else
539         {
540           if (NULL != iter)
541             iter (iter_cls,
542                   seq + 1,
543                   zone_key,
544                   label,
545                   record_count,
546                   rd);
547         }
548       }
549       GNUNET_SQ_cleanup_result (rs);
550     }
551   }
552   GNUNET_SQ_reset (plugin->dbh,
553                    stmt);
554   return ret;
555 }
556
557
558 /**
559  * Lookup records in the datastore for which we are the authority.
560  *
561  * @param cls closure (internal context for the plugin)
562  * @param zone private key of the zone
563  * @param label name of the record in the zone
564  * @param iter function to call with the result
565  * @param iter_cls closure for @a iter
566  * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR
567  */
568 static int
569 namestore_sqlite_lookup_records (void *cls,
570                                  const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
571                                  const char *label,
572                                  GNUNET_NAMESTORE_RecordIterator iter,
573                                  void *iter_cls)
574 {
575   struct Plugin *plugin = cls;
576   struct GNUNET_SQ_QueryParam params[] = {
577     GNUNET_SQ_query_param_auto_from_type (zone),
578     GNUNET_SQ_query_param_string (label),
579     GNUNET_SQ_query_param_end
580   };
581
582   if (NULL == zone)
583   {
584     GNUNET_break (0);
585     return GNUNET_SYSERR;
586   }
587   if (GNUNET_OK !=
588       GNUNET_SQ_bind (plugin->lookup_label,
589                       params))
590   {
591     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
592                 "sqlite3_bind_XXXX");
593     GNUNET_SQ_reset (plugin->dbh,
594                      plugin->lookup_label);
595     return GNUNET_SYSERR;
596   }
597   return get_records_and_call_iterator (plugin,
598                                         plugin->lookup_label,
599                                         zone,
600                                         1,
601                                         iter,
602                                         iter_cls);
603 }
604
605
606 /**
607  * Iterate over the results for a particular key and zone in the
608  * datastore.  Will return at most one result to the iterator.
609  *
610  * @param cls closure (internal context for the plugin)
611  * @param zone hash of public key of the zone, NULL to iterate over all zones
612  * @param serial serial number to exclude in the list of all matching records
613  * @param limit maximum number of results to return
614  * @param iter function to call with the result
615  * @param iter_cls closure for @a iter
616  * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error
617  */
618 static int
619 namestore_sqlite_iterate_records (void *cls,
620                                   const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
621                                   uint64_t serial,
622                                   uint64_t limit,
623                                   GNUNET_NAMESTORE_RecordIterator iter,
624                                   void *iter_cls)
625 {
626   struct Plugin *plugin = cls;
627   sqlite3_stmt *stmt;
628   int err;
629
630   if (NULL == zone)
631   {
632     struct GNUNET_SQ_QueryParam params[] = {
633       GNUNET_SQ_query_param_uint64 (&serial),
634       GNUNET_SQ_query_param_uint64 (&limit),
635       GNUNET_SQ_query_param_end
636     };
637
638     stmt = plugin->iterate_all_zones;
639     err = GNUNET_SQ_bind (stmt,
640                           params);
641   }
642   else
643   {
644     struct GNUNET_SQ_QueryParam params[] = {
645       GNUNET_SQ_query_param_auto_from_type (zone),
646       GNUNET_SQ_query_param_uint64 (&serial),
647       GNUNET_SQ_query_param_uint64 (&limit),
648       GNUNET_SQ_query_param_end
649     };
650
651     stmt = plugin->iterate_zone;
652     err = GNUNET_SQ_bind (stmt,
653                           params);
654   }
655   if (GNUNET_OK != err)
656   {
657     LOG_SQLITE (plugin,
658                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
659                 "sqlite3_bind_XXXX");
660     GNUNET_SQ_reset (plugin->dbh,
661                      stmt);
662     return GNUNET_SYSERR;
663   }
664   return get_records_and_call_iterator (plugin,
665                                         stmt,
666                                         zone,
667                                         limit,
668                                         iter,
669                                         iter_cls);
670 }
671
672
673 /**
674  * Look for an existing PKEY delegation record for a given public key.
675  * Returns at most one result to the iterator.
676  *
677  * @param cls closure (internal context for the plugin)
678  * @param zone private key of the zone to look up in, never NULL
679  * @param value_zone public key of the target zone (value), never NULL
680  * @param iter function to call with the result
681  * @param iter_cls closure for @a iter
682  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
683  */
684 static int
685 namestore_sqlite_zone_to_name (void *cls,
686                                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
687                                const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
688                                GNUNET_NAMESTORE_RecordIterator iter,
689                                void *iter_cls)
690 {
691   struct Plugin *plugin = cls;
692   struct GNUNET_SQ_QueryParam params[] = {
693     GNUNET_SQ_query_param_auto_from_type (zone),
694     GNUNET_SQ_query_param_auto_from_type (value_zone),
695     GNUNET_SQ_query_param_end
696   };
697
698   if (GNUNET_OK !=
699       GNUNET_SQ_bind (plugin->zone_to_name,
700                       params))
701   {
702     LOG_SQLITE (plugin,
703                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
704                 "sqlite3_bind_XXXX");
705     GNUNET_SQ_reset (plugin->dbh,
706                      plugin->zone_to_name);
707     return GNUNET_SYSERR;
708   }
709   LOG (GNUNET_ERROR_TYPE_DEBUG,
710        "Performing reverse lookup for `%s'\n",
711        GNUNET_GNSRECORD_z2s (value_zone));
712   return get_records_and_call_iterator (plugin,
713                                         plugin->zone_to_name,
714                                         zone,
715                                         1,
716                                         iter,
717                                         iter_cls);
718 }
719
720
721 /**
722  * Entry point for the plugin.
723  *
724  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
725  * @return NULL on error, otherwise the plugin context
726  */
727 void *
728 libgnunet_plugin_namestore_sqlite_init (void *cls)
729 {
730   static struct Plugin plugin;
731   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
732   struct GNUNET_NAMESTORE_PluginFunctions *api;
733
734   if (NULL != plugin.cfg)
735     return NULL;                /* can only initialize once! */
736   memset (&plugin,
737           0,
738           sizeof (struct Plugin));
739   plugin.cfg = cfg;
740   if (GNUNET_OK != database_setup (&plugin))
741   {
742     database_shutdown (&plugin);
743     return NULL;
744   }
745   api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
746   api->cls = &plugin;
747   api->store_records = &namestore_sqlite_store_records;
748   api->iterate_records = &namestore_sqlite_iterate_records;
749   api->zone_to_name = &namestore_sqlite_zone_to_name;
750   api->lookup_records = &namestore_sqlite_lookup_records;
751   LOG (GNUNET_ERROR_TYPE_INFO,
752        _("Sqlite database running\n"));
753   return api;
754 }
755
756
757 /**
758  * Exit point from the plugin.
759  *
760  * @param cls the plugin context (as returned by "init")
761  * @return always NULL
762  */
763 void *
764 libgnunet_plugin_namestore_sqlite_done (void *cls)
765 {
766   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
767   struct Plugin *plugin = api->cls;
768
769   database_shutdown (plugin);
770   plugin->cfg = NULL;
771   GNUNET_free (api);
772   LOG (GNUNET_ERROR_TYPE_DEBUG,
773        "sqlite plugin is finished\n");
774   return NULL;
775 }
776
777 /* end of plugin_namestore_sqlite.c */