- Tests did not clean up: TEST_HOME with namestore db was not removed after test
[oweals/gnunet.git] / src / namestore / plugin_namestore_sqlite.c
1  /*
2   * This file is part of GNUnet
3   * (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., 59 Temple Place - Suite 330,
18   * Boston, MA 02111-1307, 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 count_changes=OFF", NULL, NULL,
228                        ENULL));
229   CHECK (SQLITE_OK ==
230          sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
231                        ENULL));
232
233   CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
234
235
236   /* Create table */
237   CHECK (SQLITE_OK ==
238          sq_prepare (plugin->dbh,
239                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns097records'",
240                      &stmt));
241   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
242       (sqlite3_exec
243        (plugin->dbh,
244         "CREATE TABLE ns097records ("
245         " zone_private_key BLOB NOT NULL DEFAULT '',"
246         " pkey BLOB,"
247         " rvalue INT8 NOT NULL DEFAULT '',"
248         " record_count INT NOT NULL DEFAULT 0,"
249         " record_data BLOB NOT NULL DEFAULT '',"
250         " label TEXT NOT NULL DEFAULT ''"
251         ")",
252         NULL, NULL, NULL) != SQLITE_OK))
253   {
254     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
255     sqlite3_finalize (stmt);
256     return GNUNET_SYSERR;
257   }
258   sqlite3_finalize (stmt);
259
260   create_indices (plugin->dbh);
261
262   if ((sq_prepare
263        (plugin->dbh,
264         "INSERT INTO ns097records (zone_private_key, pkey, rvalue, record_count, record_data, label)"
265         " VALUES (?, ?, ?, ?, ?, ?)",
266         &plugin->store_records) != SQLITE_OK) ||
267       (sq_prepare
268        (plugin->dbh,
269         "DELETE FROM ns097records WHERE zone_private_key=? AND label=?",
270         &plugin->delete_records) != SQLITE_OK) ||
271       (sq_prepare
272        (plugin->dbh,
273         "SELECT record_count,record_data,label"
274         " FROM ns097records WHERE zone_private_key=? AND pkey=?",
275         &plugin->zone_to_name) != SQLITE_OK) ||
276       (sq_prepare
277        (plugin->dbh,
278         "SELECT record_count,record_data,label"
279         " FROM ns097records WHERE zone_private_key=? ORDER BY rvalue LIMIT 1 OFFSET ?",
280         &plugin->iterate_zone) != SQLITE_OK) ||
281       (sq_prepare
282        (plugin->dbh,
283         "SELECT record_count,record_data,label,zone_private_key"
284         " FROM ns097records ORDER BY rvalue LIMIT 1 OFFSET ?",
285         &plugin->iterate_all_zones) != SQLITE_OK)  ||
286       (sq_prepare
287        (plugin->dbh,
288         "SELECT record_count,record_data,label,zone_private_key"
289         " FROM ns097records WHERE zone_private_key=? AND label=?",
290         &plugin->lookup_label) != SQLITE_OK)
291       )
292   {
293     LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
294     return GNUNET_SYSERR;
295   }
296   return GNUNET_OK;
297 }
298
299
300 /**
301  * Shutdown database connection and associate data
302  * structures.
303  * @param plugin the plugin context (state for this module)
304  */
305 static void
306 database_shutdown (struct Plugin *plugin)
307 {
308   int result;
309   sqlite3_stmt *stmt;
310
311   if (NULL != plugin->store_records)
312     sqlite3_finalize (plugin->store_records);
313   if (NULL != plugin->delete_records)
314     sqlite3_finalize (plugin->delete_records);
315   if (NULL != plugin->iterate_zone)
316     sqlite3_finalize (plugin->iterate_zone);
317   if (NULL != plugin->iterate_all_zones)
318     sqlite3_finalize (plugin->iterate_all_zones);
319   if (NULL != plugin->zone_to_name)
320     sqlite3_finalize (plugin->zone_to_name);
321   if (NULL != plugin->zone_to_name)
322     sqlite3_finalize (plugin->lookup_label);
323   result = sqlite3_close (plugin->dbh);
324   if (result == SQLITE_BUSY)
325   {
326     LOG (GNUNET_ERROR_TYPE_WARNING,
327          _("Tried to close sqlite without finalizing all prepared statements.\n"));
328     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
329     while (stmt != NULL)
330     {
331       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
332                        "Closing statement %p\n", stmt);
333       result = sqlite3_finalize (stmt);
334       if (result != SQLITE_OK)
335         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
336                          "Failed to close statement %p: %d\n", stmt, result);
337       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
338     }
339     result = sqlite3_close (plugin->dbh);
340   }
341   if (SQLITE_OK != result)
342     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
343
344   GNUNET_free_non_null (plugin->fn);
345 }
346
347
348 /**
349  * Store a record in the datastore.  Removes any existing record in the
350  * same zone with the same name.
351  *
352  * @param cls closure (internal context for the plugin)
353  * @param zone_key private key of the zone
354  * @param label name that is being mapped (at most 255 characters long)
355  * @param rd_count number of entries in @a rd array
356  * @param rd array of records with data to store
357  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
358  */
359 static int
360 namestore_sqlite_store_records (void *cls,
361                                 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
362                                 const char *label,
363                                 unsigned int rd_count,
364                                 const struct GNUNET_GNSRECORD_Data *rd)
365 {
366   struct Plugin *plugin = cls;
367   int n;
368   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
369   uint64_t rvalue;
370   size_t data_size;
371   unsigned int i;
372
373   memset (&pkey, 0, sizeof (pkey));
374   for (i=0;i<rd_count;i++)
375     if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
376     {
377       GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) == rd[i].data_size);
378       memcpy (&pkey,
379               rd[i].data,
380               rd[i].data_size);
381       break;
382     }
383   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
384   data_size = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
385   if (data_size > 64 * 65536)
386   {
387     GNUNET_break (0);
388     return GNUNET_SYSERR;
389   }
390   {
391     char data[data_size];
392
393     if (data_size != GNUNET_GNSRECORD_records_serialize (rd_count, rd,
394                                                          data_size, data))
395     {
396       GNUNET_break (0);
397       return GNUNET_SYSERR;
398     }
399
400     /* First delete 'old' records */
401     if ((SQLITE_OK != sqlite3_bind_blob (plugin->delete_records, 1,
402                                          zone_key, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey), SQLITE_STATIC)) ||
403         (SQLITE_OK != sqlite3_bind_text (plugin->delete_records, 2, label, -1, SQLITE_STATIC)))
404     {
405       LOG_SQLITE (plugin,
406                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
407                   "sqlite3_bind_XXXX");
408       if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
409         LOG_SQLITE (plugin,
410                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
411                     "sqlite3_reset");
412       return GNUNET_SYSERR;
413
414     }
415     n = sqlite3_step (plugin->delete_records);
416     if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
417       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
418                   "sqlite3_reset");
419
420     if (0 != rd_count)
421     {
422       if ((SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 1,
423                                            zone_key, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey), SQLITE_STATIC)) ||
424           (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 2,
425                                            &pkey, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), SQLITE_STATIC)) ||
426           (SQLITE_OK != sqlite3_bind_int64 (plugin->store_records, 3, rvalue)) ||
427           (SQLITE_OK != sqlite3_bind_int (plugin->store_records, 4, rd_count)) ||
428           (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 5, data, data_size, SQLITE_STATIC)) ||
429           (SQLITE_OK != sqlite3_bind_text (plugin->store_records, 6, label, -1, SQLITE_STATIC)))
430       {
431         LOG_SQLITE (plugin,
432                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
433                     "sqlite3_bind_XXXX");
434         if (SQLITE_OK != sqlite3_reset (plugin->store_records))
435           LOG_SQLITE (plugin,
436                       GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
437                       "sqlite3_reset");
438         return GNUNET_SYSERR;
439       }
440       n = sqlite3_step (plugin->store_records);
441       if (SQLITE_OK != sqlite3_reset (plugin->store_records))
442         LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
443                     "sqlite3_reset");
444     }
445   }
446   switch (n)
447   {
448   case SQLITE_DONE:
449     if (0 != rd_count)
450       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
451     else
452       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record deleted\n");
453     return GNUNET_OK;
454   case SQLITE_BUSY:
455     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
456                 "sqlite3_step");
457     return GNUNET_NO;
458   default:
459     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
460                 "sqlite3_step");
461     return GNUNET_SYSERR;
462   }
463 }
464
465
466 /**
467  * The given 'sqlite' statement has been prepared to be run.
468  * It will return a record which should be given to the iterator.
469  * Runs the statement and parses the returned record.
470  *
471  * @param plugin plugin context
472  * @param stmt to run (and then clean up)
473  * @param zone_key private key of the zone
474  * @param iter iterator to call with the result
475  * @param iter_cls closure for @a iter
476  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
477  */
478 static int
479 get_record_and_call_iterator (struct Plugin *plugin,
480                               sqlite3_stmt *stmt,
481                               const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
482                               GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
483 {
484   unsigned int record_count;
485   size_t data_size;
486   const char *data;
487   const char *label;
488   int ret;
489   int sret;
490
491   ret = GNUNET_NO;
492   if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
493   {
494     record_count = sqlite3_column_int (stmt, 0);
495     data_size = sqlite3_column_bytes (stmt, 1);
496     data = sqlite3_column_blob (stmt, 1);
497     label = (const char*) sqlite3_column_text (stmt, 2);
498     if (NULL == zone_key)
499     {
500       /* must be "iterate_all_zones", got one extra return value */
501       if (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey) !=
502           sqlite3_column_bytes (stmt, 3))
503       {
504         GNUNET_break (0);
505         ret = GNUNET_SYSERR;
506       }
507       else
508       {
509         zone_key = sqlite3_column_blob (stmt, 3);
510       }
511     }
512     if (record_count > 64 * 1024)
513     {
514       /* sanity check, don't stack allocate far too much just
515          because database might contain a large value here */
516       GNUNET_break (0);
517       ret = GNUNET_SYSERR;
518     }
519     else
520     {
521       struct GNUNET_GNSRECORD_Data rd[record_count];
522
523       if (GNUNET_OK !=
524           GNUNET_GNSRECORD_records_deserialize (data_size, data,
525                                                 record_count, rd))
526       {
527         GNUNET_break (0);
528         ret = GNUNET_SYSERR;
529       }
530       else if (NULL != zone_key)
531       {
532         if (NULL != iter)
533                 iter (iter_cls, zone_key, label, record_count, rd);
534         ret = GNUNET_YES;
535       }
536     }
537   }
538   else
539   {
540     if (SQLITE_DONE != sret)
541       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
542   }
543   if (SQLITE_OK != sqlite3_reset (stmt))
544     LOG_SQLITE (plugin,
545                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
546                 "sqlite3_reset");
547   return ret;
548 }
549
550 /**
551  * Lookup records in the datastore for which we are the authority.
552  *
553  * @param cls closure (internal context for the plugin)
554  * @param zone private key of the zone
555  * @param label name of the record in the zone
556  * @param iter function to call with the result
557  * @param iter_cls closure for @a iter
558  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
559  */
560 static int
561 namestore_sqlite_lookup_records (void *cls,
562     const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, const char *label,
563     GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
564 {
565   struct Plugin *plugin = cls;
566   sqlite3_stmt *stmt;
567   int err;
568
569   if (NULL == zone)
570   {
571     return GNUNET_SYSERR;
572   }
573   else
574   {
575     stmt = plugin->lookup_label;
576     err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
577                                              zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
578                                              SQLITE_STATIC)) ||
579             (SQLITE_OK != sqlite3_bind_text (stmt, 2,
580                                               label, -1, SQLITE_STATIC)) );
581   }
582   if (err)
583   {
584     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
585                 "sqlite3_bind_XXXX");
586     if (SQLITE_OK != sqlite3_reset (stmt))
587       LOG_SQLITE (plugin,
588                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
589                   "sqlite3_reset");
590     return GNUNET_SYSERR;
591   }
592   return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
593 }
594
595
596 /**
597  * Iterate over the results for a particular key and zone in the
598  * datastore.  Will return at most one result to the iterator.
599  *
600  * @param cls closure (internal context for the plugin)
601  * @param zone hash of public key of the zone, NULL to iterate over all zones
602  * @param offset offset in the list of all matching records
603  * @param iter function to call with the result
604  * @param iter_cls closure for @a iter
605  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
606  */
607 static int
608 namestore_sqlite_iterate_records (void *cls,
609                                   const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
610                                   uint64_t offset,
611                                   GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
612 {
613   struct Plugin *plugin = cls;
614   sqlite3_stmt *stmt;
615   int err;
616
617   if (NULL == zone)
618   {
619     stmt = plugin->iterate_all_zones;
620     err = (SQLITE_OK != sqlite3_bind_int64 (stmt, 1,
621                                             offset));
622   }
623   else
624   {
625     stmt = plugin->iterate_zone;
626     err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
627                                              zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
628                                              SQLITE_STATIC)) ||
629             (SQLITE_OK != sqlite3_bind_int64 (stmt, 2,
630                                               offset)) );
631   }
632   if (err)
633   {
634     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
635                 "sqlite3_bind_XXXX");
636     if (SQLITE_OK != sqlite3_reset (stmt))
637       LOG_SQLITE (plugin,
638                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
639                   "sqlite3_reset");
640     return GNUNET_SYSERR;
641   }
642   return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
643 }
644
645
646 /**
647  * Look for an existing PKEY delegation record for a given public key.
648  * Returns at most one result to the iterator.
649  *
650  * @param cls closure (internal context for the plugin)
651  * @param zone private key of the zone to look up in, never NULL
652  * @param value_zone public key of the target zone (value), never NULL
653  * @param iter function to call with the result
654  * @param iter_cls closure for @a iter
655  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
656  */
657 static int
658 namestore_sqlite_zone_to_name (void *cls,
659                                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
660                                const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
661                                GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
662 {
663   struct Plugin *plugin = cls;
664   sqlite3_stmt *stmt;
665
666   stmt = plugin->zone_to_name;
667   if ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
668                                         zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
669                                         SQLITE_STATIC)) ||
670        (SQLITE_OK != sqlite3_bind_blob (stmt, 2,
671                                         value_zone, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
672                                         SQLITE_STATIC)) )
673   {
674     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
675                 "sqlite3_bind_XXXX");
676     if (SQLITE_OK != sqlite3_reset (stmt))
677       LOG_SQLITE (plugin,
678                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
679                   "sqlite3_reset");
680     return GNUNET_SYSERR;
681   }
682   LOG (GNUNET_ERROR_TYPE_DEBUG,
683        "Performing reverse lookup for `%s'\n",
684        GNUNET_GNSRECORD_z2s (value_zone));
685
686   return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
687 }
688
689
690 /**
691  * Entry point for the plugin.
692  *
693  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
694  * @return NULL on error, otherwise the plugin context
695  */
696 void *
697 libgnunet_plugin_namestore_sqlite_init (void *cls)
698 {
699   static struct Plugin plugin;
700   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
701   struct GNUNET_NAMESTORE_PluginFunctions *api;
702
703   if (NULL != plugin.cfg)
704     return NULL;                /* can only initialize once! */
705   memset (&plugin, 0, sizeof (struct Plugin));
706   plugin.cfg = cfg;
707   if (GNUNET_OK != database_setup (&plugin))
708   {
709     database_shutdown (&plugin);
710     return NULL;
711   }
712   api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
713   api->cls = &plugin;
714   api->store_records = &namestore_sqlite_store_records;
715   api->iterate_records = &namestore_sqlite_iterate_records;
716   api->zone_to_name = &namestore_sqlite_zone_to_name;
717   api->lookup_records = &namestore_sqlite_lookup_records;
718   LOG (GNUNET_ERROR_TYPE_INFO,
719        _("Sqlite database running\n"));
720   return api;
721 }
722
723
724 /**
725  * Exit point from the plugin.
726  *
727  * @param cls the plugin context (as returned by "init")
728  * @return always NULL
729  */
730 void *
731 libgnunet_plugin_namestore_sqlite_done (void *cls)
732 {
733   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
734   struct Plugin *plugin = api->cls;
735
736   database_shutdown (plugin);
737   plugin->cfg = NULL;
738   GNUNET_free (api);
739   LOG (GNUNET_ERROR_TYPE_DEBUG,
740        "sqlite plugin is finished\n");
741   return NULL;
742 }
743
744 /* end of plugin_namestore_sqlite.c */