note about performance issue, indentation fix
[oweals/gnunet.git] / src / namestore / plugin_namestore_sqlite.c
1  /*
2   * This file is part of GNUnet
3   * Copyright (C) 2009-2013 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 "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,
141                       "CREATE INDEX IF NOT EXISTS ir_pkey_reverse ON ns097records (zone_private_key,pkey)",
142                       NULL, NULL, NULL)) ||
143        (SQLITE_OK !=
144         sqlite3_exec (dbh,
145                       "CREATE INDEX IF NOT EXISTS ir_pkey_iter ON ns097records (zone_private_key,rvalue)",
146                       NULL, NULL, NULL)) ||
147        (SQLITE_OK !=
148         sqlite3_exec (dbh,
149                       "CREATE INDEX IF NOT EXISTS it_iter ON ns097records (rvalue)",
150                       NULL, NULL, NULL)) )
151     LOG (GNUNET_ERROR_TYPE_ERROR,
152          "Failed to create indices: %s\n",
153          sqlite3_errmsg (dbh));
154 }
155
156
157 #if 0
158 #define CHECK(a) GNUNET_break(a)
159 #define ENULL NULL
160 #else
161 #define ENULL &e
162 #define ENULL_DEFINED 1
163 #define CHECK(a) if (! (a)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
164 #endif
165
166
167 /**
168  * Initialize the database connections and associated
169  * data structures (create tables and indices
170  * as needed as well).
171  *
172  * @param plugin the plugin context (state for this module)
173  * @return #GNUNET_OK on success
174  */
175 static int
176 database_setup (struct Plugin *plugin)
177 {
178   sqlite3_stmt *stmt;
179   char *afsdir;
180 #if ENULL_DEFINED
181   char *e;
182 #endif
183
184   if (GNUNET_OK !=
185       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
186                                                "namestore-sqlite",
187                                                "FILENAME",
188                                                &afsdir))
189   {
190     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
191                                "namestore-sqlite",
192                                "FILENAME");
193     return GNUNET_SYSERR;
194   }
195   if (GNUNET_OK !=
196       GNUNET_DISK_file_test (afsdir))
197   {
198     if (GNUNET_OK !=
199         GNUNET_DISK_directory_create_for_file (afsdir))
200     {
201       GNUNET_break (0);
202       GNUNET_free (afsdir);
203       return GNUNET_SYSERR;
204     }
205   }
206   /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
207   plugin->fn = afsdir;
208
209   /* Open database and precompile statements */
210   if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
211   {
212     LOG (GNUNET_ERROR_TYPE_ERROR,
213          _("Unable to initialize SQLite: %s.\n"),
214          sqlite3_errmsg (plugin->dbh));
215     return GNUNET_SYSERR;
216   }
217   CHECK (SQLITE_OK ==
218          sqlite3_exec (plugin->dbh,
219                        "PRAGMA temp_store=MEMORY", NULL, NULL,
220                        ENULL));
221   CHECK (SQLITE_OK ==
222          sqlite3_exec (plugin->dbh,
223                        "PRAGMA synchronous=NORMAL", NULL, NULL,
224                        ENULL));
225   CHECK (SQLITE_OK ==
226          sqlite3_exec (plugin->dbh,
227                        "PRAGMA legacy_file_format=OFF", NULL, NULL,
228                        ENULL));
229   CHECK (SQLITE_OK ==
230          sqlite3_exec (plugin->dbh,
231                        "PRAGMA auto_vacuum=INCREMENTAL", NULL,
232                        NULL, ENULL));
233   CHECK (SQLITE_OK ==
234          sqlite3_exec (plugin->dbh,
235                        "PRAGMA encoding=\"UTF-8\"", NULL,
236                        NULL, ENULL));
237   CHECK (SQLITE_OK ==
238          sqlite3_exec (plugin->dbh,
239                        "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
240                        ENULL));
241   CHECK (SQLITE_OK ==
242          sqlite3_exec (plugin->dbh,
243                        "PRAGMA page_size=4092", NULL, NULL,
244                        ENULL));
245
246   CHECK (SQLITE_OK ==
247          sqlite3_busy_timeout (plugin->dbh,
248                                BUSY_TIMEOUT_MS));
249
250
251   /* Create table */
252   CHECK (SQLITE_OK ==
253          sq_prepare (plugin->dbh,
254                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns097records'",
255                      &stmt));
256   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
257       (sqlite3_exec
258        (plugin->dbh,
259         "CREATE TABLE ns097records ("
260         " zone_private_key BLOB NOT NULL DEFAULT '',"
261         " pkey BLOB,"
262         " rvalue INT8 NOT NULL DEFAULT '',"
263         " record_count INT NOT NULL DEFAULT 0,"
264         " record_data BLOB NOT NULL DEFAULT '',"
265         " label TEXT NOT NULL DEFAULT ''"
266         ")",
267         NULL, NULL, NULL) != SQLITE_OK))
268   {
269     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR,
270                 "sqlite3_exec");
271     sqlite3_finalize (stmt);
272     return GNUNET_SYSERR;
273   }
274   sqlite3_finalize (stmt);
275
276   create_indices (plugin->dbh);
277
278   if ((sq_prepare
279        (plugin->dbh,
280         "INSERT INTO ns097records (zone_private_key, pkey, rvalue, record_count, record_data, label)"
281         " VALUES (?, ?, ?, ?, ?, ?)",
282         &plugin->store_records) != SQLITE_OK) ||
283       (sq_prepare
284        (plugin->dbh,
285         "DELETE FROM ns097records WHERE zone_private_key=? AND label=?",
286         &plugin->delete_records) != SQLITE_OK) ||
287       (sq_prepare
288        (plugin->dbh,
289         "SELECT record_count,record_data,label"
290         " FROM ns097records WHERE zone_private_key=? AND pkey=?",
291         &plugin->zone_to_name) != SQLITE_OK) ||
292       (sq_prepare
293        (plugin->dbh,
294         "SELECT record_count,record_data,label"
295         " FROM ns097records WHERE zone_private_key=? ORDER BY rvalue LIMIT 1 OFFSET ?",
296         &plugin->iterate_zone) != SQLITE_OK) ||
297       (sq_prepare
298        (plugin->dbh,
299         "SELECT record_count,record_data,label,zone_private_key"
300         " FROM ns097records ORDER BY rvalue LIMIT 1 OFFSET ?",
301         &plugin->iterate_all_zones) != SQLITE_OK)  ||
302       (sq_prepare
303        (plugin->dbh,
304         "SELECT record_count,record_data,label,zone_private_key"
305         " FROM ns097records WHERE zone_private_key=? AND label=?",
306         &plugin->lookup_label) != SQLITE_OK)
307       )
308   {
309     LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
310     return GNUNET_SYSERR;
311   }
312   return GNUNET_OK;
313 }
314
315
316 /**
317  * Shutdown database connection and associate data
318  * structures.
319  * @param plugin the plugin context (state for this module)
320  */
321 static void
322 database_shutdown (struct Plugin *plugin)
323 {
324   int result;
325   sqlite3_stmt *stmt;
326
327   if (NULL != plugin->store_records)
328     sqlite3_finalize (plugin->store_records);
329   if (NULL != plugin->delete_records)
330     sqlite3_finalize (plugin->delete_records);
331   if (NULL != plugin->iterate_zone)
332     sqlite3_finalize (plugin->iterate_zone);
333   if (NULL != plugin->iterate_all_zones)
334     sqlite3_finalize (plugin->iterate_all_zones);
335   if (NULL != plugin->zone_to_name)
336     sqlite3_finalize (plugin->zone_to_name);
337   if (NULL != plugin->lookup_label)
338     sqlite3_finalize (plugin->lookup_label);
339   result = sqlite3_close (plugin->dbh);
340   if (result == SQLITE_BUSY)
341   {
342     LOG (GNUNET_ERROR_TYPE_WARNING,
343          _("Tried to close sqlite without finalizing all prepared statements.\n"));
344     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
345     while (stmt != NULL)
346     {
347       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
348                        "Closing statement %p\n", stmt);
349       result = sqlite3_finalize (stmt);
350       if (result != SQLITE_OK)
351         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
352                          "Failed to close statement %p: %d\n", stmt, result);
353       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
354     }
355     result = sqlite3_close (plugin->dbh);
356   }
357   if (SQLITE_OK != result)
358     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
359
360   GNUNET_free_non_null (plugin->fn);
361 }
362
363
364 /**
365  * Store a record in the datastore.  Removes any existing record in the
366  * same zone with the same name.
367  *
368  * @param cls closure (internal context for the plugin)
369  * @param zone_key private key of the zone
370  * @param label name that is being mapped (at most 255 characters long)
371  * @param rd_count number of entries in @a rd array
372  * @param rd array of records with data to store
373  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
374  */
375 static int
376 namestore_sqlite_store_records (void *cls,
377                                 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
378                                 const char *label,
379                                 unsigned int rd_count,
380                                 const struct GNUNET_GNSRECORD_Data *rd)
381 {
382   struct Plugin *plugin = cls;
383   int n;
384   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
385   uint64_t rvalue;
386   size_t data_size;
387   unsigned int i;
388
389   memset (&pkey, 0, sizeof (pkey));
390   for (i=0;i<rd_count;i++)
391     if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
392     {
393       GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) ==
394                     rd[i].data_size);
395       GNUNET_memcpy (&pkey,
396                      rd[i].data,
397                      rd[i].data_size);
398       break;
399     }
400   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
401                                      UINT64_MAX);
402   data_size = GNUNET_GNSRECORD_records_get_size (rd_count,
403                                                  rd);
404   if (data_size > 64 * 65536)
405   {
406     GNUNET_break (0);
407     return GNUNET_SYSERR;
408   }
409   {
410     char data[data_size];
411
412     if (data_size !=
413         GNUNET_GNSRECORD_records_serialize (rd_count,
414                                             rd,
415                                             data_size,
416                                             data))
417     {
418       GNUNET_break (0);
419       return GNUNET_SYSERR;
420     }
421
422     /* First delete 'old' records */
423     if ((SQLITE_OK !=
424          sqlite3_bind_blob (plugin->delete_records,
425                             1,
426                             zone_key,
427                             sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
428                             SQLITE_STATIC)) ||
429         (SQLITE_OK !=
430          sqlite3_bind_text (plugin->delete_records,
431                             2,
432                             label,
433                             -1,
434                             SQLITE_STATIC)))
435     {
436       LOG_SQLITE (plugin,
437                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
438                   "sqlite3_bind_XXXX");
439       if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
440         LOG_SQLITE (plugin,
441                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
442                     "sqlite3_reset");
443       return GNUNET_SYSERR;
444
445     }
446     n = sqlite3_step (plugin->delete_records);
447     if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
448       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
449                   "sqlite3_reset");
450
451     if (0 != rd_count)
452     {
453       if ((SQLITE_OK !=
454            sqlite3_bind_blob (plugin->store_records,
455                               1,
456                               zone_key,
457                               sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
458                               SQLITE_STATIC)) ||
459           (SQLITE_OK !=
460            sqlite3_bind_blob (plugin->store_records,
461                               2,
462                               &pkey,
463                               sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
464                               SQLITE_STATIC)) ||
465           (SQLITE_OK !=
466            sqlite3_bind_int64 (plugin->store_records, 3, rvalue)) ||
467           (SQLITE_OK !=
468            sqlite3_bind_int (plugin->store_records, 4, rd_count)) ||
469           (SQLITE_OK !=
470            sqlite3_bind_blob (plugin->store_records, 5,
471                               data, data_size,
472                               SQLITE_STATIC)) ||
473           (SQLITE_OK !=
474            sqlite3_bind_text (plugin->store_records, 6,
475                               label, -1,
476                               SQLITE_STATIC)))
477       {
478         LOG_SQLITE (plugin,
479                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
480                     "sqlite3_bind_XXXX");
481         if (SQLITE_OK != sqlite3_reset (plugin->store_records))
482           LOG_SQLITE (plugin,
483                       GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
484                       "sqlite3_reset");
485         return GNUNET_SYSERR;
486       }
487       n = sqlite3_step (plugin->store_records);
488       if (SQLITE_OK != sqlite3_reset (plugin->store_records))
489         LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
490                     "sqlite3_reset");
491     }
492   }
493   switch (n)
494   {
495   case SQLITE_DONE:
496     if (0 != rd_count)
497       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
498     else
499       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record deleted\n");
500     return GNUNET_OK;
501   case SQLITE_BUSY:
502     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
503                 "sqlite3_step");
504     return GNUNET_NO;
505   default:
506     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
507                 "sqlite3_step");
508     return GNUNET_SYSERR;
509   }
510 }
511
512
513 /**
514  * The given 'sqlite' statement has been prepared to be run.
515  * It will return a record which should be given to the iterator.
516  * Runs the statement and parses the returned record.
517  *
518  * @param plugin plugin context
519  * @param stmt to run (and then clean up)
520  * @param zone_key private key of the zone
521  * @param iter iterator to call with the result
522  * @param iter_cls closure for @a iter
523  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
524  */
525 static int
526 get_record_and_call_iterator (struct Plugin *plugin,
527                               sqlite3_stmt *stmt,
528                               const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
529                               GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
530 {
531   unsigned int record_count;
532   size_t data_size;
533   const char *data;
534   const char *label;
535   int ret;
536   int sret;
537
538   ret = GNUNET_NO;
539   if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
540   {
541     record_count = sqlite3_column_int (stmt, 0);
542     data_size = sqlite3_column_bytes (stmt, 1);
543     data = sqlite3_column_blob (stmt, 1);
544     label = (const char*) sqlite3_column_text (stmt, 2);
545     if (NULL == zone_key)
546     {
547       /* must be "iterate_all_zones", got one extra return value */
548       if (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey) !=
549           sqlite3_column_bytes (stmt, 3))
550       {
551         GNUNET_break (0);
552         ret = GNUNET_SYSERR;
553       }
554       else
555       {
556         zone_key = sqlite3_column_blob (stmt, 3);
557       }
558     }
559     if (record_count > 64 * 1024)
560     {
561       /* sanity check, don't stack allocate far too much just
562          because database might contain a large value here */
563       GNUNET_break (0);
564       ret = GNUNET_SYSERR;
565     }
566     else
567     {
568       struct GNUNET_GNSRECORD_Data rd[record_count];
569
570       if (GNUNET_OK !=
571           GNUNET_GNSRECORD_records_deserialize (data_size, data,
572                                                 record_count, rd))
573       {
574         GNUNET_break (0);
575         ret = GNUNET_SYSERR;
576       }
577       else if (NULL != zone_key)
578       {
579         if (NULL != iter)
580                 iter (iter_cls, zone_key, label, record_count, rd);
581         ret = GNUNET_YES;
582       }
583     }
584   }
585   else
586   {
587     if (SQLITE_DONE != sret)
588       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
589   }
590   if (SQLITE_OK != sqlite3_reset (stmt))
591     LOG_SQLITE (plugin,
592                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
593                 "sqlite3_reset");
594   return ret;
595 }
596
597 /**
598  * Lookup records in the datastore for which we are the authority.
599  *
600  * @param cls closure (internal context for the plugin)
601  * @param zone private key of the zone
602  * @param label name of the record in the zone
603  * @param iter function to call with the result
604  * @param iter_cls closure for @a iter
605  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
606  */
607 static int
608 namestore_sqlite_lookup_records (void *cls,
609     const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, const char *label,
610     GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
611 {
612   struct Plugin *plugin = cls;
613   sqlite3_stmt *stmt;
614   int err;
615
616   if (NULL == zone)
617   {
618     return GNUNET_SYSERR;
619   }
620   else
621   {
622     stmt = plugin->lookup_label;
623     err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
624                                              zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
625                                              SQLITE_STATIC)) ||
626             (SQLITE_OK != sqlite3_bind_text (stmt, 2,
627                                               label, -1, SQLITE_STATIC)) );
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  * Iterate over the results for a particular key and zone in the
645  * datastore.  Will return at most one result to the iterator.
646  *
647  * @param cls closure (internal context for the plugin)
648  * @param zone hash of public key of the zone, NULL to iterate over all zones
649  * @param offset offset in the list of all matching records
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_iterate_records (void *cls,
656                                   const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
657                                   uint64_t offset,
658                                   GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
659 {
660   struct Plugin *plugin = cls;
661   sqlite3_stmt *stmt;
662   int err;
663
664   if (NULL == zone)
665   {
666     stmt = plugin->iterate_all_zones;
667     err = (SQLITE_OK != sqlite3_bind_int64 (stmt, 1,
668                                             offset));
669   }
670   else
671   {
672     stmt = plugin->iterate_zone;
673     err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
674                                              zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
675                                              SQLITE_STATIC)) ||
676             (SQLITE_OK != sqlite3_bind_int64 (stmt, 2,
677                                               offset)) );
678   }
679   if (err)
680   {
681     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
682                 "sqlite3_bind_XXXX");
683     if (SQLITE_OK != sqlite3_reset (stmt))
684       LOG_SQLITE (plugin,
685                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
686                   "sqlite3_reset");
687     return GNUNET_SYSERR;
688   }
689   return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
690 }
691
692
693 /**
694  * Look for an existing PKEY delegation record for a given public key.
695  * Returns at most one result to the iterator.
696  *
697  * @param cls closure (internal context for the plugin)
698  * @param zone private key of the zone to look up in, never NULL
699  * @param value_zone public key of the target zone (value), never NULL
700  * @param iter function to call with the result
701  * @param iter_cls closure for @a iter
702  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
703  */
704 static int
705 namestore_sqlite_zone_to_name (void *cls,
706                                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
707                                const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
708                                GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
709 {
710   struct Plugin *plugin = cls;
711   sqlite3_stmt *stmt;
712
713   stmt = plugin->zone_to_name;
714   if ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
715                                         zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
716                                         SQLITE_STATIC)) ||
717        (SQLITE_OK != sqlite3_bind_blob (stmt, 2,
718                                         value_zone, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
719                                         SQLITE_STATIC)) )
720   {
721     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
722                 "sqlite3_bind_XXXX");
723     if (SQLITE_OK != sqlite3_reset (stmt))
724       LOG_SQLITE (plugin,
725                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
726                   "sqlite3_reset");
727     return GNUNET_SYSERR;
728   }
729   LOG (GNUNET_ERROR_TYPE_DEBUG,
730        "Performing reverse lookup for `%s'\n",
731        GNUNET_GNSRECORD_z2s (value_zone));
732
733   return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
734 }
735
736
737 /**
738  * Entry point for the plugin.
739  *
740  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
741  * @return NULL on error, otherwise the plugin context
742  */
743 void *
744 libgnunet_plugin_namestore_sqlite_init (void *cls)
745 {
746   static struct Plugin plugin;
747   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
748   struct GNUNET_NAMESTORE_PluginFunctions *api;
749
750   if (NULL != plugin.cfg)
751     return NULL;                /* can only initialize once! */
752   memset (&plugin, 0, sizeof (struct Plugin));
753   plugin.cfg = cfg;
754   if (GNUNET_OK != database_setup (&plugin))
755   {
756     database_shutdown (&plugin);
757     return NULL;
758   }
759   api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
760   api->cls = &plugin;
761   api->store_records = &namestore_sqlite_store_records;
762   api->iterate_records = &namestore_sqlite_iterate_records;
763   api->zone_to_name = &namestore_sqlite_zone_to_name;
764   api->lookup_records = &namestore_sqlite_lookup_records;
765   LOG (GNUNET_ERROR_TYPE_INFO,
766        _("Sqlite database running\n"));
767   return api;
768 }
769
770
771 /**
772  * Exit point from the plugin.
773  *
774  * @param cls the plugin context (as returned by "init")
775  * @return always NULL
776  */
777 void *
778 libgnunet_plugin_namestore_sqlite_done (void *cls)
779 {
780   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
781   struct Plugin *plugin = api->cls;
782
783   database_shutdown (plugin);
784   plugin->cfg = NULL;
785   GNUNET_free (api);
786   LOG (GNUNET_ERROR_TYPE_DEBUG,
787        "sqlite plugin is finished\n");
788   return NULL;
789 }
790
791 /* end of plugin_namestore_sqlite.c */