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