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