4a40b3db1d37fcb8d0205b2f2300364857d43264
[oweals/gnunet.git] / src / namestore / plugin_namestore_sqlite.c
1  /*
2   * This file is part of GNUnet
3   * (C) 2009, 2011, 2012 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 <sqlite3.h>
30
31 /**
32  * After how many ms "busy" should a DB operation fail for good?
33  * A low value makes sure that we are more responsive to requests
34  * (especially PUTs).  A high value guarantees a higher success
35  * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
36  *
37  * The default value of 1s should ensure that users do not experience
38  * huge latencies while at the same time allowing operations to succeed
39  * with reasonable probability.
40  */
41 #define BUSY_TIMEOUT_MS 1000
42
43
44 /**
45  * Log an error message at log-level 'level' that indicates
46  * a failure of the command 'cmd' on file 'filename'
47  * with the message given by strerror(errno).
48  */
49 #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)
50
51 #define LOG(kind,...) GNUNET_log_from (kind, "namestore-sqlite", __VA_ARGS__)
52
53
54 /**
55  * Context for all functions in this plugin.
56  */
57 struct Plugin
58 {
59
60   const struct GNUNET_CONFIGURATION_Handle *cfg;
61
62   /**
63    * Database filename.
64    */
65   char *fn;
66
67   /**
68    * Native SQLite database handle.
69    */
70   sqlite3 *dbh;
71
72   /**
73    * Precompiled SQL for put record
74    */
75   sqlite3_stmt *put_records;
76
77   /**
78    * Precompiled SQL for remove record
79    */
80   sqlite3_stmt *remove_records;
81
82   /**
83    * Precompiled SQL for iterate over all records.
84    */
85   sqlite3_stmt *iterate_all;
86
87   /**
88    * Precompiled SQL for iterate records with same name.
89    */
90   sqlite3_stmt *iterate_by_name;
91
92   /**
93    * Precompiled SQL for iterate records with same zone.
94    */
95   sqlite3_stmt *iterate_by_zone;
96
97   /**
98    * Precompiled SQL for iterate records with same name and zone.
99    */
100   sqlite3_stmt *iterate_records;
101
102   /**
103    * Precompiled SQL for delete zone
104    */
105   sqlite3_stmt *delete_zone;
106
107 };
108
109
110 /**
111  * @brief Prepare a SQL statement
112  *
113  * @param dbh handle to the database
114  * @param zSql SQL statement, UTF-8 encoded
115  * @param ppStmt set to the prepared statement
116  * @return 0 on success
117  */
118 static int
119 sq_prepare (sqlite3 * dbh, const char *zSql, sqlite3_stmt ** ppStmt)
120 {
121   char *dummy;
122   int result;
123
124   result =
125       sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
126                           (const char **) &dummy);
127   LOG (GNUNET_ERROR_TYPE_DEBUG, 
128        "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
129   return result;
130 }
131
132
133 /**
134  * Create our database indices.
135  *
136  * @param dbh handle to the database
137  */
138 static void
139 create_indices (sqlite3 * dbh)
140 {
141   /* create indices */
142   if ( (SQLITE_OK !=
143         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_zone_name_rv ON ns090records (zone_hash,record_name_hash,rvalue)",
144                       NULL, NULL, NULL)) ||
145        (SQLITE_OK !=
146         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_zone_rv ON ns090records (zone_hash,rvalue)",
147                       NULL, NULL, NULL)) ||
148        (SQLITE_OK !=
149         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_zone ON ns090records (zone_hash)",
150                       NULL, NULL, NULL)) ||
151        (SQLITE_OK !=
152         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_name_rv ON ns090records (record_name_hash,rvalue)",
153                       NULL, NULL, NULL)) ||
154        (SQLITE_OK !=
155         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_rv ON ns090records (rvalue)",
156                       NULL, NULL, NULL)) )    
157     LOG (GNUNET_ERROR_TYPE_ERROR, 
158          "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
159 }
160
161
162 #if 0
163 #define CHECK(a) GNUNET_break(a)
164 #define ENULL NULL
165 #else
166 #define ENULL &e
167 #define ENULL_DEFINED 1
168 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
169 #endif
170
171
172 /**
173  * Initialize the database connections and associated
174  * data structures (create tables and indices
175  * as needed as well).
176  *
177  * @param plugin the plugin context (state for this module)
178  * @return GNUNET_OK on success
179  */
180 static int
181 database_setup (struct Plugin *plugin)
182 {
183   sqlite3_stmt *stmt;
184   char *afsdir;
185 #if ENULL_DEFINED
186   char *e;
187 #endif
188
189   if (GNUNET_OK !=
190       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "namestore-sqlite",
191                                                "FILENAME", &afsdir))
192     {
193     LOG (GNUNET_ERROR_TYPE_ERROR, 
194          _ ("Option `%s' in section `%s' missing in configuration!\n"),
195          "FILENAME", "namestore-sqlite");
196     return GNUNET_SYSERR;
197   }
198   if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
199   {
200     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
201     {
202       GNUNET_break (0);
203       GNUNET_free (afsdir);
204       return GNUNET_SYSERR;
205     }
206   }
207 #ifdef ENABLE_NLS
208   plugin->fn =
209       GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), nl_langinfo (CODESET));
210 #else
211   plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), "UTF-8");       /* good luck */
212 #endif
213   GNUNET_free (afsdir);
214
215   /* Open database and precompile statements */
216   if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
217   {
218     LOG (GNUNET_ERROR_TYPE_ERROR,
219          _("Unable to initialize SQLite: %s.\n"),
220          sqlite3_errmsg (plugin->dbh));
221     return GNUNET_SYSERR;
222   }
223   CHECK (SQLITE_OK ==
224          sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
225                        ENULL));
226   CHECK (SQLITE_OK ==
227          sqlite3_exec (plugin->dbh, "PRAGMA synchronous=NORMAL", NULL, NULL,
228                        ENULL));
229   CHECK (SQLITE_OK ==
230          sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
231                        ENULL));
232   CHECK (SQLITE_OK ==
233          sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
234                        NULL, ENULL));
235   CHECK (SQLITE_OK ==
236          sqlite3_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"", NULL,
237                        NULL, ENULL));
238   CHECK (SQLITE_OK ==
239          sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
240                        ENULL));
241   CHECK (SQLITE_OK ==
242          sqlite3_exec (plugin->dbh, "PRAGMA count_changes=OFF", NULL, NULL,
243                        ENULL));
244   CHECK (SQLITE_OK ==
245          sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
246                        ENULL));
247
248   CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
249
250
251   /* Create tables */
252   CHECK (SQLITE_OK ==
253          sq_prepare (plugin->dbh,
254                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns090records'",
255                      &stmt));
256   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
257       (sqlite3_exec
258        (plugin->dbh,
259         "CREATE TABLE ns090records (" 
260         " zone_hash BLOB NOT NULL DEFAULT ''," 
261         " record_data BLOB NOT NULL DEFAULT ''"
262         " block_expiration_time INT8 NOT NULL DEFAULT 0," 
263         " record_name TEXT NOT NULL DEFAULT ''," 
264         " record_name_hash BLOB NOT NULL DEFAULT ''," 
265         " rvalue INT8 NOT NULL DEFAULT ''"
266         ")", 
267         NULL, NULL, NULL) != SQLITE_OK))
268   {
269     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
270     sqlite3_finalize (stmt);
271     return GNUNET_SYSERR;
272   }
273   sqlite3_finalize (stmt);
274
275   create_indices (plugin->dbh);
276
277 #define ALL "zone_hash, record_name, record_data, block_expiration_time"
278   if ((sq_prepare
279        (plugin->dbh,
280         "INSERT INTO ns090records (" ALL ", record_name_hash, rvalue) VALUES "
281         "(?, ?, ?, ?, ?, ?)",
282         &plugin->put_records) != SQLITE_OK) ||
283       (sq_prepare
284        (plugin->dbh,
285         "DELETE FROM ns090records WHERE zone_hash=? AND record_name_hash=?",
286         &plugin->remove_records) != SQLITE_OK) ||
287       (sq_prepare
288        (plugin->dbh,
289         "SELECT " ALL
290         "FROM ns090records WHERE zone_hash=? AND record_name_hash=? ORDER BY rvalue OFFSET ? LIMIT 1",
291         &plugin->iterate_records) != SQLITE_OK) ||
292       (sq_prepare
293        (plugin->dbh,
294         "SELECT " ALL
295         "FROM ns090records WHERE zone_hash=? ORDER BY rvalue OFFSET ? LIMIT 1",
296         &plugin->iterate_by_zone) != SQLITE_OK) ||
297       (sq_prepare
298        (plugin->dbh,
299         "SELECT " ALL 
300         "FROM ns090records WHERE record_name_hash=? ORDER BY rvalue OFFSET ? LIMIT 1",
301         &plugin->iterate_by_name) != SQLITE_OK) ||
302       (sq_prepare
303         (plugin->dbh,
304         "SELECT " ALL
305         "FROM ns090records ORDER BY rvalue OFFSET ? LIMIT 1",
306         &plugin->iterate_all) != SQLITE_OK) ||
307       (sq_prepare
308        (plugin->dbh,
309         "DELETE FROM ns090records WHERE zone_hash=?",
310         &plugin->delete_zone) != SQLITE_OK) )
311   {
312     LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
313     return GNUNET_SYSERR;
314   }
315 #undef ALL
316   return GNUNET_OK;
317 }
318
319
320 /**
321  * Shutdown database connection and associate data
322  * structures.
323  * @param plugin the plugin context (state for this module)
324  */
325 static void
326 database_shutdown (struct Plugin *plugin)
327 {
328   int result;
329   sqlite3_stmt *stmt;
330
331   if (NULL != plugin->put_records)
332     sqlite3_finalize (plugin->put_records);
333   if (NULL != plugin->remove_records)
334     sqlite3_finalize (plugin->remove_records);
335   if (NULL != plugin->iterate_records)
336     sqlite3_finalize (plugin->iterate_records);
337   if (NULL != plugin->iterate_records)
338     sqlite3_finalize (plugin->iterate_by_zone);
339   if (NULL != plugin->iterate_records)
340     sqlite3_finalize (plugin->iterate_by_name);
341   if (NULL != plugin->iterate_records)
342     sqlite3_finalize (plugin->iterate_all);
343   if (NULL != plugin->delete_zone)
344     sqlite3_finalize (plugin->delete_zone);
345   result = sqlite3_close (plugin->dbh);
346   if (result == SQLITE_BUSY)
347   {
348     LOG (GNUNET_ERROR_TYPE_WARNING,
349          _("Tried to close sqlite without finalizing all prepared statements.\n"));
350     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
351     while (stmt != NULL)
352     {
353       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
354                        "Closing statement %p\n", stmt);
355       result = sqlite3_finalize (stmt);
356       if (result != SQLITE_OK)
357         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
358                          "Failed to close statement %p: %d\n", stmt, result);
359       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
360     }
361     result = sqlite3_close (plugin->dbh);
362   }
363   if (SQLITE_OK != result)
364     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
365
366   GNUNET_free_non_null (plugin->fn);
367 }
368
369
370 /**
371  * Store a record in the datastore.
372  *
373  * @param cls closure (internal context for the plugin)
374  * @param zone hash of the public key of the zone
375  * @param name name that is being mapped (at most 255 characters long)
376  * @param record_type type of the record (A, AAAA, PKEY, etc.)
377  * @param loc location of the signature for the record
378  * @param expiration expiration time for the content
379  * @param flags flags for the content
380  * @param data_size number of bytes in data
381  * @param data value, semantics depend on 'record_type' (see RFCs for DNS and 
382  *             GNS specification for GNS extensions)
383  * @return GNUNET_OK on success
384  */
385 static int 
386 namestore_sqlite_put_records (void *cls, 
387                               const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
388                               struct GNUNET_TIME_Absolute expire,
389                               const char *name,
390                               unsigned int rd_count,
391                               const struct GNUNET_NAMESTORE_RecordData *rd,
392                               const struct GNUNET_CRYPTO_RsaSignature *signature)
393 {
394 #if 0
395   struct Plugin *plugin = cls;
396   int n;
397   GNUNET_HashCode nh;
398   size_t name_len;
399
400   name_len = strlen (name);
401   GNUNET_CRYPTO_hash (name, name_len, &nh);
402   if ((SQLITE_OK != sqlite3_bind_blob (plugin->put_record, 1, zone, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
403       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_record, 2, loc->revision)) ||
404       (SQLITE_OK != sqlite3_bind_blob (plugin->put_record, 3, &nh, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
405       (SQLITE_OK != sqlite3_bind_text (plugin->put_record, 4, name, -1, SQLITE_STATIC)) ||
406       (SQLITE_OK != sqlite3_bind_int (plugin->put_record, 5, record_type)) ||
407       (SQLITE_OK != sqlite3_bind_int (plugin->put_record, 6, loc->depth)) ||
408       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_record, 7, loc->offset)) ||
409       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_record, 8, expiration.abs_value)) ||
410       (SQLITE_OK != sqlite3_bind_int (plugin->put_record, 9, flags)) ||
411       (SQLITE_OK != sqlite3_bind_blob (plugin->put_record, 10, data, data_size, SQLITE_STATIC)) )
412   {
413     LOG_SQLITE (plugin, 
414                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
415                 "sqlite3_bind_XXXX");
416     if (SQLITE_OK != sqlite3_reset (plugin->put_record))
417       LOG_SQLITE (plugin, 
418                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
419                   "sqlite3_reset");
420     return GNUNET_SYSERR;
421
422   }
423   n = sqlite3_step (plugin->put_record);
424   if (SQLITE_OK != sqlite3_reset (plugin->put_record))
425     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
426                 "sqlite3_reset");
427   switch (n)
428   {
429   case SQLITE_DONE:
430     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
431     return GNUNET_OK;
432   case SQLITE_BUSY:
433     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
434                 "sqlite3_step");
435     return GNUNET_NO;
436   default:
437     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
438                 "sqlite3_step");
439     return GNUNET_SYSERR;
440   }
441 #endif
442   return GNUNET_SYSERR;
443 }
444
445
446 /**
447  * Store a Merkle tree node in the datastore.
448  *
449  * @param cls closure (internal context for the plugin)
450  * @param zone hash of public key of the zone
451  * @param loc location in the B-tree
452  * @param ploc parent's location in the B-tree (must have depth = loc.depth + 1), NULL for root
453  * @param num_entries number of entries at this node in the B-tree
454  * @param entries the 'num_entries' entries to store (hashes over the
455  *                records)
456  * @return GNUNET_OK on success
457  */
458 static int 
459 namestore_sqlite_remove_records (void *cls, 
460                                  const GNUNET_HashCode *zone,
461                                  const char *name)
462 {
463 #if 0
464   struct Plugin *plugin = cls;
465   int n;
466
467   if ( (loc->revision != ploc->revision) ||
468        (loc->depth + 1 != ploc->depth) ||
469        (0 == num_entries))
470   {
471     GNUNET_break (0);
472     return GNUNET_SYSERR;
473   }
474   if ((SQLITE_OK != sqlite3_bind_blob (plugin->put_node, 1, zone, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
475       (SQLITE_OK != sqlite3_bind_int (plugin->put_node, 2, loc->revision)) ||
476       (SQLITE_OK != sqlite3_bind_int (plugin->put_node, 3, loc->depth)) ||
477       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_node, 4, loc->offset)) ||
478       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_node, 5, ploc->offset)) ||
479       (SQLITE_OK != sqlite3_bind_blob (plugin->put_node, 6, entries, num_entries * sizeof (GNUNET_HashCode), SQLITE_STATIC)) )
480   {
481     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
482                 "sqlite3_bind_XXXX");
483     if (SQLITE_OK != sqlite3_reset (plugin->put_node))
484       LOG_SQLITE (plugin,
485                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
486                   "sqlite3_reset");
487     return GNUNET_SYSERR;
488
489   }
490   n = sqlite3_step (plugin->put_node);
491   if (SQLITE_OK != sqlite3_reset (plugin->put_node))
492     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
493                 "sqlite3_reset");
494   switch (n)
495   {
496   case SQLITE_DONE:
497     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Node stored\n");
498     return GNUNET_OK;
499   case SQLITE_BUSY:
500     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
501                 "sqlite3_step");
502     return GNUNET_NO;
503   default:
504     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
505                 "sqlite3_step");
506     return GNUNET_SYSERR;
507   }
508 #endif
509   return GNUNET_SYSERR;
510 }
511   
512   
513 /**
514  * Iterate over the results for a particular key and zone in the
515  * datastore.  Will only query the latest revision known for the
516  * zone (as adding a new zone revision will cause the plugin to
517  * delete all records from previous revisions).
518  *
519  * @param cls closure (internal context for the plugin)
520  * @param zone hash of public key of the zone, NULL to iterate over all zones
521  * @param name_hash hash of name, NULL to iterate over all records of the zone
522  * @param offset offset in the list of all matching records
523  * @param iter maybe NULL (to just count)
524  * @param iter_cls closure for iter
525  * @return GNUNET_OK on success, GNUNET_NO if there were no results, GNUNET_SYSERR on error
526  */
527 static int 
528 namestore_sqlite_iterate_records (void *cls, 
529                                   const GNUNET_HashCode *zone,
530                                   const GNUNET_HashCode *name_hash,
531                                   uint64_t offset,
532                                   GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
533 {
534 #if 0
535   struct Plugin *plugin = cls;
536   unsigned int ret;
537   int sret;
538   struct GNUNET_TIME_Absolute expiration;
539   uint32_t record_type;
540   enum GNUNET_NAMESTORE_RecordFlags flags;
541   size_t data_size;
542   const void *data;
543   struct GNUNET_NAMESTORE_SignatureLocation loc;
544   const char *name;
545
546   if ((SQLITE_OK != sqlite3_bind_blob (plugin->iterate_records, 1, 
547                                        zone, sizeof (GNUNET_HashCode), 
548                                        SQLITE_STATIC)) ||
549       (SQLITE_OK != sqlite3_bind_blob (plugin->iterate_records, 2, 
550                                        name_hash, sizeof (GNUNET_HashCode), 
551                                        SQLITE_STATIC)) )
552   {
553     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
554                 "sqlite3_bind_XXXX");
555     if (SQLITE_OK != sqlite3_reset (plugin->iterate_records))
556       LOG_SQLITE (plugin,
557                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
558                   "sqlite3_reset");
559     return GNUNET_SYSERR;
560   }
561   ret = 0;
562   while (SQLITE_ROW == (sret = sqlite3_step (plugin->iterate_records)))
563   {
564     ret++;
565     if (NULL == iter)
566       continue; /* FIXME: just counting can be done more cheaply... */
567     loc.revision = sqlite3_column_int (plugin->iterate_records, 0);
568     name = (const char*) sqlite3_column_text (plugin->iterate_records, 1);
569     record_type = sqlite3_column_int (plugin->iterate_records, 2);
570     loc.depth = sqlite3_column_int (plugin->iterate_records, 3);
571     loc.offset = sqlite3_column_int64 (plugin->iterate_records, 4);
572     expiration.abs_value = (uint64_t) sqlite3_column_int64 (plugin->iterate_records, 5);
573     flags = (enum GNUNET_NAMESTORE_RecordFlags) sqlite3_column_int (plugin->iterate_records, 6);
574     data = sqlite3_column_blob (plugin->iterate_records, 7);
575     data_size = sqlite3_column_bytes (plugin->iterate_records, 7);
576     iter (iter_cls, zone,
577           &loc, name, record_type,
578           expiration, flags, data_size, data);
579   }
580   if (SQLITE_DONE != sret)
581     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
582   if (SQLITE_OK != sqlite3_reset (plugin->iterate_records))
583     LOG_SQLITE (plugin,
584                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
585                 "sqlite3_reset");
586   return ret;
587 #endif
588   return GNUNET_SYSERR;
589 }
590
591
592 /**
593  * Delete an entire zone (all records).  Not used in normal operation.
594  *
595  * @param cls closure (internal context for the plugin)
596  * @param zone zone to delete
597  */
598 static void 
599 namestore_sqlite_delete_zone (void *cls,
600                               const GNUNET_HashCode *zone)
601 {
602   struct Plugin *plugin = cls;
603   sqlite3_stmt *stmt = plugin->delete_zone;
604   int n;
605
606   if (SQLITE_OK != sqlite3_bind_blob (stmt, 1, zone, sizeof (GNUNET_HashCode), SQLITE_STATIC))
607   {
608     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
609                 "sqlite3_bind_XXXX");
610     if (SQLITE_OK != sqlite3_reset (stmt))
611       LOG_SQLITE (plugin,
612                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
613                   "sqlite3_reset");
614     return;
615   }
616   n = sqlite3_step (stmt);
617   if (SQLITE_OK != sqlite3_reset (stmt))
618     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
619                 "sqlite3_reset");
620   switch (n)
621   {
622   case SQLITE_DONE:
623     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Values deleted\n");
624     break;
625   case SQLITE_BUSY:
626     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
627                 "sqlite3_step");
628     break;
629   default:
630     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
631                 "sqlite3_step");
632     break;
633   }
634 }
635
636
637 /**
638  * Entry point for the plugin.
639  *
640  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
641  * @return NULL on error, othrewise the plugin context
642  */
643 void *
644 libgnunet_plugin_namestore_sqlite_init (void *cls)
645 {
646   static struct Plugin plugin;
647   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
648   struct GNUNET_NAMESTORE_PluginFunctions *api;
649
650   if (NULL != plugin.cfg)
651     return NULL;                /* can only initialize once! */
652   memset (&plugin, 0, sizeof (struct Plugin));
653   plugin.cfg = cfg;  
654   if (GNUNET_OK != database_setup (&plugin))
655   {
656     database_shutdown (&plugin);
657     return NULL;
658   }
659   api = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_PluginFunctions));
660   api->cls = &plugin;
661   api->put_records = &namestore_sqlite_put_records;
662   api->remove_records = &namestore_sqlite_remove_records;
663   api->iterate_records = &namestore_sqlite_iterate_records;
664   api->delete_zone = &namestore_sqlite_delete_zone;
665   LOG (GNUNET_ERROR_TYPE_INFO, 
666        _("Sqlite database running\n"));
667   return api;
668 }
669
670
671 /**
672  * Exit point from the plugin.
673  *
674  * @param cls the plugin context (as returned by "init")
675  * @return always NULL
676  */
677 void *
678 libgnunet_plugin_namestore_sqlite_done (void *cls)
679 {
680   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
681   struct Plugin *plugin = api->cls;
682
683   LOG (GNUNET_ERROR_TYPE_DEBUG, 
684        "sqlite plugin is done\n");
685   database_shutdown (plugin);
686   plugin->cfg = NULL;
687   GNUNET_free (api);
688   LOG (GNUNET_ERROR_TYPE_DEBUG, 
689        "sqlite plugin is finished\n");
690   return NULL;
691 }
692
693 /* end of plugin_namestore_sqlite.c */