ff0875ea6082c1c3e38ac6e798a7770ce0b520af
[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_record;
76
77   /**
78    * Precompiled SQL for put node
79    */
80   sqlite3_stmt *put_node;
81
82   /**
83    * Precompiled SQL for put signature
84    */
85   sqlite3_stmt *put_signature;
86
87   /**
88    * Precompiled SQL for iterate records
89    */
90   sqlite3_stmt *iterate_records;
91
92   /**
93    * Precompiled SQL for get node
94    */
95   sqlite3_stmt *get_node;
96
97   /**
98    * Precompiled SQL for get signature
99    */
100   sqlite3_stmt *get_signature;
101
102   /**
103    * Precompiled SQL for delete zone
104    */
105   sqlite3_stmt *delete_zone_records;
106
107   /**
108    * Precompiled SQL for delete zone
109    */
110   sqlite3_stmt *delete_zone_nodes;
111
112   /**
113    * Precompiled SQL for delete zone
114    */
115   sqlite3_stmt *delete_zone_signatures;
116
117 };
118
119
120 /**
121  * @brief Prepare a SQL statement
122  *
123  * @param dbh handle to the database
124  * @param zSql SQL statement, UTF-8 encoded
125  * @param ppStmt set to the prepared statement
126  * @return 0 on success
127  */
128 static int
129 sq_prepare (sqlite3 * dbh, const char *zSql, sqlite3_stmt ** ppStmt)
130 {
131   char *dummy;
132   int result;
133
134   result =
135       sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
136                           (const char **) &dummy);
137   LOG (GNUNET_ERROR_TYPE_DEBUG, 
138        "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
139   return result;
140 }
141
142
143 /**
144  * Create our database indices.
145  *
146  * @param dbh handle to the database
147  */
148 static void
149 create_indices (sqlite3 * dbh)
150 {
151   /* create indices */
152   if (SQLITE_OK !=
153       sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_zone_name_hash ON ns090records (zone_hash,record_name_hash)",
154                     NULL, NULL, NULL))
155     LOG (GNUNET_ERROR_TYPE_ERROR, 
156          "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
157
158
159   if (SQLITE_OK !=
160       sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS in_zone_location ON ns090nodes (zone_hash,zone_revision,node_location_depth,node_location_offset DESC)",
161                     NULL, NULL, NULL))
162     LOG (GNUNET_ERROR_TYPE_ERROR, 
163          "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
164
165
166   if (SQLITE_OK !=
167       sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS is_zone ON ns090signatures (zone_hash)",
168                     NULL, NULL, NULL))
169     LOG (GNUNET_ERROR_TYPE_ERROR, 
170          "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
171 }
172
173
174 #if 0
175 #define CHECK(a) GNUNET_break(a)
176 #define ENULL NULL
177 #else
178 #define ENULL &e
179 #define ENULL_DEFINED 1
180 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
181 #endif
182
183
184 /**
185  * Initialize the database connections and associated
186  * data structures (create tables and indices
187  * as needed as well).
188  *
189  * @param plugin the plugin context (state for this module)
190  * @return GNUNET_OK on success
191  */
192 static int
193 database_setup (struct Plugin *plugin)
194 {
195   sqlite3_stmt *stmt;
196   char *afsdir;
197 #if ENULL_DEFINED
198   char *e;
199 #endif
200
201   if (GNUNET_OK !=
202       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "namestore-sqlite",
203                                                "FILENAME", &afsdir))
204     {
205     LOG (GNUNET_ERROR_TYPE_ERROR, 
206          _ ("Option `%s' in section `%s' missing in configuration!\n"),
207          "FILENAME", "namestore-sqlite");
208     return GNUNET_SYSERR;
209   }
210   if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
211   {
212     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
213     {
214       GNUNET_break (0);
215       GNUNET_free (afsdir);
216       return GNUNET_SYSERR;
217     }
218   }
219 #ifdef ENABLE_NLS
220   plugin->fn =
221       GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), nl_langinfo (CODESET));
222 #else
223   plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), "UTF-8");       /* good luck */
224 #endif
225   GNUNET_free (afsdir);
226
227   /* Open database and precompile statements */
228   if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
229   {
230     LOG (GNUNET_ERROR_TYPE_ERROR,
231          _("Unable to initialize SQLite: %s.\n"),
232          sqlite3_errmsg (plugin->dbh));
233     return GNUNET_SYSERR;
234   }
235   CHECK (SQLITE_OK ==
236          sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
237                        ENULL));
238   CHECK (SQLITE_OK ==
239          sqlite3_exec (plugin->dbh, "PRAGMA synchronous=NORMAL", NULL, NULL,
240                        ENULL));
241   CHECK (SQLITE_OK ==
242          sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
243                        ENULL));
244   CHECK (SQLITE_OK ==
245          sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
246                        NULL, ENULL));
247   CHECK (SQLITE_OK ==
248          sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
249                        ENULL));
250   CHECK (SQLITE_OK ==
251          sqlite3_exec (plugin->dbh, "PRAGMA count_changes=OFF", NULL, NULL,
252                        ENULL));
253   CHECK (SQLITE_OK ==
254          sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
255                        ENULL));
256
257   CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
258
259
260   /* Create tables */
261   CHECK (SQLITE_OK ==
262          sq_prepare (plugin->dbh,
263                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns090records'",
264                      &stmt));
265   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
266       (sqlite3_exec
267        (plugin->dbh,
268         "CREATE TABLE ns090records (" 
269         " zone_hash TEXT NOT NULL DEFAULT ''," 
270         " zone_revision INT4 NOT NULL DEFAULT 0," 
271         " record_name_hash TEXT NOT NULL DEFAULT ''," 
272         " record_name TEXT NOT NULL DEFAULT ''," 
273         " record_type INT4 NOT NULL DEFAULT 0,"
274         " node_location_depth INT4 NOT NULL DEFAULT 0," 
275         " node_location_offset INT8 NOT NULL DEFAULT 0," 
276         " record_expiration_time INT8 NOT NULL DEFAULT 0," 
277         " record_flags INT4 NOT NULL DEFAULT 0,"
278         " record_value BLOB NOT NULL DEFAULT ''"
279         ")", 
280         NULL, NULL, NULL) != SQLITE_OK))
281   {
282     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
283     sqlite3_finalize (stmt);
284     return GNUNET_SYSERR;
285   }
286   sqlite3_finalize (stmt);
287
288   CHECK (SQLITE_OK ==
289          sq_prepare (plugin->dbh,
290                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns090nodes'",
291                      &stmt));
292   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
293       (sqlite3_exec
294        (plugin->dbh,
295         "CREATE TABLE ns090nodes (" 
296         " zone_hash TEXT NOT NULL DEFAULT ''," 
297         " zone_revision INT4 NOT NULL DEFAULT 0," 
298         " node_location_depth INT4 NOT NULL DEFAULT 0," 
299         " node_location_offset INT8 NOT NULL DEFAULT 0," 
300         " node_parent_offset INT8 NOT NULL DEFAULT 0," 
301         " node_hashcodes BLOB NOT NULL DEFAULT ''"
302         ")", 
303         NULL, NULL, NULL) != SQLITE_OK))
304   {
305     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
306     sqlite3_finalize (stmt);
307     return GNUNET_SYSERR;
308   }
309   sqlite3_finalize (stmt);
310
311
312   CHECK (SQLITE_OK ==
313          sq_prepare (plugin->dbh,
314                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns090signatures'",
315                      &stmt));
316   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
317       (sqlite3_exec
318        (plugin->dbh,
319         "CREATE TABLE ns090signatures (" 
320         " zone_hash TEXT NOT NULL DEFAULT ''," 
321         " zone_revision INT4 NOT NULL DEFAULT 0," 
322         " zone_time INT8 NOT NULL DEFAULT 0," 
323         " zone_root_hash TEXT NOT NULL DEFAULT 0," 
324         " zone_root_depth INT4 NOT NULL DEFAULT 0," 
325         " zone_public_key BLOB NOT NULL DEFAULT 0," 
326         " zone_signature BLOB NOT NULL DEFAULT 0" 
327         ")", 
328         NULL, NULL, NULL) != SQLITE_OK))
329   {
330     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
331     sqlite3_finalize (stmt);
332     return GNUNET_SYSERR;
333   }
334   sqlite3_finalize (stmt);
335
336
337   create_indices (plugin->dbh);
338
339   if ((sq_prepare
340        (plugin->dbh,
341         "INSERT INTO ns090records (zone_hash, zone_revision, record_name_hash, record_name, "
342         "record_type, node_location_depth, node_location_offset, "
343         "record_expiration_time, record_flags, record_value) VALUES "
344         "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
345         &plugin->put_record) != SQLITE_OK) ||
346       (sq_prepare
347        (plugin->dbh,
348         "INSERT INTO ns090nodes (zone_hash, zone_revision, "
349         "node_location_depth, node_location_offset, node_parent_offset, node_hashcodes) "
350         "VALUES (?, ?, ?, ?, ?, ?)",
351         &plugin->put_node) != SQLITE_OK) ||
352       (sq_prepare
353        (plugin->dbh,
354         "INSERT INTO ns090signatures (zone_hash, zone_revision, zone_time, zone_root_hash, "
355         "zone_root_depth, zone_public_key, zone_signature) "
356         "VALUES (?, ?, ?, ?, ?, ?)",
357         &plugin->put_signature) != SQLITE_OK) ||
358       (sq_prepare
359        (plugin->dbh,
360         "SELECT zone_revision,record_name,record_type,node_location_depth,node_location_offset,record_expiration_time,record_flags,record_value "
361         "FROM ns090records WHERE zone_hash=? AND record_name_hash=?",
362         &plugin->iterate_records) != SQLITE_OK) ||
363       (sq_prepare
364        (plugin->dbh,
365         "SELECT node_parent_offset,node_hashcodes FROM ns090nodes "
366         "WHERE zone_hash=? AND zone_revision=? AND node_location_depth=? AND node_location_offset<=? ORDER BY node_location_offset DESC LIMIT 1",
367         &plugin->get_node) != SQLITE_OK) ||
368       (sq_prepare
369        (plugin->dbh,
370         "SELECT zone_revision,zone_time,zone_root_hash,zone_root_depth,zone_public_key,zone_signature "
371         "FROM ns090signatures WHERE zone_hash=?",
372         &plugin->get_signature) != SQLITE_OK) ||
373       (sq_prepare
374        (plugin->dbh,
375         "DELETE FROM gn090records WHERE zone_hash=?",
376         &plugin->delete_zone_records) != SQLITE_OK) ||
377       (sq_prepare
378        (plugin->dbh,
379         "DELETE FROM gn090nodes WHERE zone_hash=?",
380         &plugin->delete_zone_nodes) != SQLITE_OK) ||
381       (sq_prepare
382        (plugin->dbh,
383         "DELETE FROM gn090signatures WHERE zone_hash=?",
384         &plugin->delete_zone_signatures) != SQLITE_OK) )
385   {
386     LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
387     return GNUNET_SYSERR;
388   }
389   return GNUNET_OK;
390 }
391
392
393 /**
394  * Shutdown database connection and associate data
395  * structures.
396  * @param plugin the plugin context (state for this module)
397  */
398 static void
399 database_shutdown (struct Plugin *plugin)
400 {
401   int result;
402   sqlite3_stmt *stmt;
403
404   if (NULL != plugin->put_record)
405     sqlite3_finalize (plugin->put_record);
406   if (NULL != plugin->put_node)
407     sqlite3_finalize (plugin->put_node);
408   if (NULL != plugin->put_signature)
409     sqlite3_finalize (plugin->put_signature);
410   if (NULL != plugin->iterate_records)
411     sqlite3_finalize (plugin->iterate_records);
412   if (NULL != plugin->get_node)
413     sqlite3_finalize (plugin->get_node);
414   if (NULL != plugin->get_signature)
415     sqlite3_finalize (plugin->get_signature);
416   if (NULL != plugin->delete_zone_records)
417     sqlite3_finalize (plugin->delete_zone_records);
418   if (NULL != plugin->delete_zone_nodes)
419     sqlite3_finalize (plugin->delete_zone_nodes);
420   if (NULL != plugin->delete_zone_signatures)
421     sqlite3_finalize (plugin->delete_zone_signatures);
422   result = sqlite3_close (plugin->dbh);
423   if (result == SQLITE_BUSY)
424   {
425     LOG (GNUNET_ERROR_TYPE_WARNING,
426          _("Tried to close sqlite without finalizing all prepared statements.\n"));
427     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
428     while (stmt != NULL)
429     {
430       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
431                        "Closing statement %p\n", stmt);
432       result = sqlite3_finalize (stmt);
433       if (result != SQLITE_OK)
434         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
435                          "Failed to close statement %p: %d\n", stmt, result);
436       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
437     }
438     result = sqlite3_close (plugin->dbh);
439   }
440   if (SQLITE_OK != result)
441     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
442
443   GNUNET_free_non_null (plugin->fn);
444 }
445
446
447 /**
448  * Store a record in the datastore.
449  *
450  * @param cls closure (internal context for the plugin)
451  * @param zone hash of the public key of the zone
452  * @param name name that is being mapped (at most 255 characters long)
453  * @param record_type type of the record (A, AAAA, PKEY, etc.)
454  * @param loc location of the signature for the record
455  * @param expiration expiration time for the content
456  * @param flags flags for the content
457  * @param data_size number of bytes in data
458  * @param data value, semantics depend on 'record_type' (see RFCs for DNS and 
459  *             GNS specification for GNS extensions)
460  * @return GNUNET_OK on success
461  */
462 static int 
463 namestore_sqlite_put_record (void *cls, 
464                              const GNUNET_HashCode *zone,
465                              const char *name,
466                              uint32_t record_type,
467                              const struct GNUNET_NAMESTORE_SignatureLocation *loc,
468                              struct GNUNET_TIME_Absolute expiration,
469                              enum GNUNET_NAMESTORE_RecordFlags flags,
470                              size_t data_size,
471                              const void *data)
472 {
473   struct Plugin *plugin = cls;
474   int n;
475   GNUNET_HashCode nh;
476   size_t name_len;
477
478   name_len = strlen (name);
479   GNUNET_CRYPTO_hash (name, name_len, &nh);
480   if ((SQLITE_OK != sqlite3_bind_blob (plugin->put_record, 1, zone, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
481       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_record, 2, loc->revision)) ||
482       (SQLITE_OK != sqlite3_bind_blob (plugin->put_record, 3, &nh, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
483       (SQLITE_OK != sqlite3_bind_text (plugin->put_record, 4, name, name_len, SQLITE_STATIC)) ||
484       (SQLITE_OK != sqlite3_bind_int (plugin->put_record, 5, record_type)) ||
485       (SQLITE_OK != sqlite3_bind_int (plugin->put_record, 6, loc->depth)) ||
486       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_record, 7, loc->offset)) ||
487       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_record, 8, expiration.abs_value)) ||
488       (SQLITE_OK != sqlite3_bind_int (plugin->put_record, 9, flags)) ||
489       (SQLITE_OK != sqlite3_bind_blob (plugin->put_record, 10, data, data_size, SQLITE_STATIC)) )
490   {
491     LOG_SQLITE (plugin, 
492                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
493                 "sqlite3_bind_XXXX");
494     if (SQLITE_OK != sqlite3_reset (plugin->put_record))
495       LOG_SQLITE (plugin, 
496                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
497                   "sqlite3_reset");
498     return GNUNET_SYSERR;
499
500   }
501   n = sqlite3_step (plugin->put_record);
502   if (SQLITE_OK != sqlite3_reset (plugin->put_record))
503     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
504                 "sqlite3_reset");
505   switch (n)
506   {
507   case SQLITE_DONE:
508     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
509     return GNUNET_OK;
510   case SQLITE_BUSY:
511     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
512                 "sqlite3_step");
513     return GNUNET_NO;
514   default:
515     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
516                 "sqlite3_step");
517     return GNUNET_SYSERR;
518   }
519 }
520
521
522 /**
523  * Store a Merkle tree node in the datastore.
524  *
525  * @param cls closure (internal context for the plugin)
526  * @param zone hash of public key of the zone
527  * @param loc location in the B-tree
528  * @param ploc parent's location in the B-tree (must have depth = loc.depth + 1), NULL for root
529  * @param num_entries number of entries at this node in the B-tree
530  * @param entries the 'num_entries' entries to store (hashes over the
531  *                records)
532  * @return GNUNET_OK on success
533  */
534 static int 
535 namestore_sqlite_put_node (void *cls, 
536                            const GNUNET_HashCode *zone,
537                            const struct GNUNET_NAMESTORE_SignatureLocation *loc,
538                            const struct GNUNET_NAMESTORE_SignatureLocation *ploc,
539                            unsigned int num_entries,
540                            const GNUNET_HashCode *entries)
541 {
542   struct Plugin *plugin = cls;
543   int n;
544
545   if ( (loc->revision != ploc->revision) ||
546        (loc->depth + 1 != ploc->depth) ||
547        (0 == num_entries))
548   {
549     GNUNET_break (0);
550     return GNUNET_SYSERR;
551   }
552   if ((SQLITE_OK != sqlite3_bind_blob (plugin->put_node, 1, zone, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
553       (SQLITE_OK != sqlite3_bind_int (plugin->put_node, 2, loc->revision)) ||
554       (SQLITE_OK != sqlite3_bind_int (plugin->put_node, 3, loc->depth)) ||
555       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_node, 4, loc->offset)) ||
556       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_node, 5, ploc->offset)) ||
557       (SQLITE_OK != sqlite3_bind_blob (plugin->put_node, 6, entries, num_entries * sizeof (GNUNET_HashCode), SQLITE_STATIC)) )
558   {
559     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
560                 "sqlite3_bind_XXXX");
561     if (SQLITE_OK != sqlite3_reset (plugin->put_node))
562       LOG_SQLITE (plugin,
563                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
564                   "sqlite3_reset");
565     return GNUNET_SYSERR;
566
567   }
568   n = sqlite3_step (plugin->put_node);
569   if (SQLITE_OK != sqlite3_reset (plugin->put_node))
570     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
571                 "sqlite3_reset");
572   switch (n)
573   {
574   case SQLITE_DONE:
575     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Node stored\n");
576     return GNUNET_OK;
577   case SQLITE_BUSY:
578     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
579                 "sqlite3_step");
580     return GNUNET_NO;
581   default:
582     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
583                 "sqlite3_step");
584     return GNUNET_SYSERR;
585   }
586 }
587   
588
589 /**
590  * Store a zone signature in the datastore.  If a signature for the zone with a
591  * lower depth exists, the old signature is removed.  If a signature for an
592  * older revision of the zone exists, this will delete all records, nodes
593  * and signatures for the older revision of the zone.
594  *
595  * @param cls closure (internal context for the plugin)
596  * @param zone_key public key of the zone
597  * @param loc location in the B-tree (top of the tree, offset 0, depth at 'maximum')
598  * @param top_sig signature at the top, NULL if 'loc.depth > 0'
599  * @param root_hash top level hash that is signed
600  * @param zone_time time the zone was signed
601  * @return GNUNET_OK on success
602  */
603 static int
604 namestore_sqlite_put_signature (void *cls, 
605                                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
606                                 const struct GNUNET_NAMESTORE_SignatureLocation *loc,
607                                 const struct GNUNET_CRYPTO_RsaSignature *top_sig,
608                                 const GNUNET_HashCode *root_hash,
609                                 struct GNUNET_TIME_Absolute zone_time)
610 {
611   struct Plugin *plugin = cls;
612   int n;
613   GNUNET_HashCode zone;
614
615   GNUNET_CRYPTO_hash (zone_key,
616                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
617                       &zone);
618   /* FIXME: get "old" signature, if older revision, delete all existing
619      records/nodes for the zone, if same revision, delete only the signature */
620
621
622   if ((SQLITE_OK != sqlite3_bind_blob (plugin->put_signature, 1, &zone, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
623       (SQLITE_OK != sqlite3_bind_int (plugin->put_signature, 2, loc->revision)) ||
624       (SQLITE_OK != sqlite3_bind_int64 (plugin->put_signature, 3, zone_time.abs_value)) ||
625       (SQLITE_OK != sqlite3_bind_blob (plugin->put_signature, 4, root_hash, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
626       (SQLITE_OK != sqlite3_bind_int (plugin->put_signature, 5, loc->depth)) ||
627       (SQLITE_OK != sqlite3_bind_blob (plugin->put_signature, 6, zone_key, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), SQLITE_STATIC))||
628       (SQLITE_OK != sqlite3_bind_blob (plugin->put_signature, 7, top_sig, sizeof (struct GNUNET_CRYPTO_RsaSignature), SQLITE_STATIC)) )
629   {
630     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
631                 "sqlite3_bind_XXXX");
632     if (SQLITE_OK != sqlite3_reset (plugin->put_signature))
633       LOG_SQLITE (plugin,
634                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
635                   "sqlite3_reset");
636     return GNUNET_SYSERR;
637
638   }
639   n = sqlite3_step (plugin->put_signature);
640   if (SQLITE_OK != sqlite3_reset (plugin->put_signature))
641     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
642                 "sqlite3_reset");
643   switch (n)
644   {
645   case SQLITE_DONE:
646     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Signature stored\n");
647     return GNUNET_OK;
648   case SQLITE_BUSY:
649     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
650                 "sqlite3_step");
651     return GNUNET_NO;
652   default:
653     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
654                 "sqlite3_step");
655     return GNUNET_SYSERR;
656   }
657 }
658   
659   
660 /**
661  * Iterate over the results for a particular key and zone in the
662  * datastore.  Will only query the latest revision known for the
663  * zone (as adding a new zone revision will cause the plugin to
664  * delete all records from previous revisions).
665  *
666  * @param cls closure (internal context for the plugin)
667  * @param zone hash of public key of the zone
668  * @param name_hash hash of name, NULL to iterate over all records of the zone
669  * @param iter maybe NULL (to just count)
670  * @param iter_cls closure for iter
671  * @return the number of results found
672  */
673 static unsigned int 
674 namestore_sqlite_iterate_records (void *cls, 
675                                   const GNUNET_HashCode *zone,
676                                   const GNUNET_HashCode *name_hash,
677                                   GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
678 {
679 #if 0
680   int n;
681   struct GNUNET_TIME_Absolute expiration;
682   unsigned long long rowid;
683   unsigned int size;
684   int ret;
685
686   n = sqlite3_step (stmt);
687   switch (n)
688   {
689   case SQLITE_ROW:
690     size = sqlite3_column_bytes (stmt, 5);
691     rowid = sqlite3_column_int64 (stmt, 6);
692     if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
693     {
694       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
695                        _
696                        ("Invalid data in database.  Trying to fix (by deletion).\n"));
697       if (SQLITE_OK != sqlite3_reset (stmt))
698         LOG_SQLITE (plugin,
699                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
700                     "sqlite3_reset");
701       if (GNUNET_OK == delete_by_rowid (plugin, rowid))
702         plugin->env->duc (plugin->env->cls,
703                           -(size + GNUNET_NAMESTORE_ENTRY_OVERHEAD));
704       break;
705     }
706     expiration.abs_value = sqlite3_column_int64 (stmt, 3);
707 #if DEBUG_SQLITE
708     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
709                      "Found reply in database with expiration %llu\n",
710                      (unsigned long long) expiration.abs_value);
711 #endif
712     ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
713                 size, sqlite3_column_blob (stmt, 5) /* data */ ,
714                 sqlite3_column_int (stmt, 0) /* type */ ,
715                 sqlite3_column_int (stmt, 1) /* priority */ ,
716                 sqlite3_column_int (stmt, 2) /* anonymity */ ,
717                 expiration, rowid);
718     if (SQLITE_OK != sqlite3_reset (stmt))
719       LOG_SQLITE (plugin,
720                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
721                   "sqlite3_reset");
722     if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
723       plugin->env->duc (plugin->env->cls,
724                         -(size + GNUNET_NAMESTORE_ENTRY_OVERHEAD));
725     return;
726   case SQLITE_DONE:
727     /* database must be empty */
728     if (SQLITE_OK != sqlite3_reset (stmt))
729       LOG_SQLITE (plugin,
730                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
731                   "sqlite3_reset");
732     break;
733   case SQLITE_BUSY:
734   case SQLITE_ERROR:
735   case SQLITE_MISUSE:
736   default:
737     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
738                 "sqlite3_step");
739     if (SQLITE_OK != sqlite3_reset (stmt))
740       LOG_SQLITE (plugin, 
741                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
742                   "sqlite3_reset");
743     GNUNET_break (0);
744     database_shutdown (plugin);
745     database_setup (plugin->env->cfg, plugin);
746     break;
747   }
748   if (SQLITE_OK != sqlite3_reset (stmt))
749     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
750                 "sqlite3_reset");
751   proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
752
753
754
755
756
757   const GNUNET_HashCode *key;
758   sqlite3_stmt *stmt;
759   int ret;
760
761   GNUNET_assert (proc != NULL);
762   if (sq_prepare (plugin->dbh, "SELECT hash FROM gn090", &stmt) != SQLITE_OK)
763   {
764     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
765                 "sqlite_prepare");
766     return;
767   }
768   while (SQLITE_ROW == (ret = sqlite3_step (stmt)))
769   {
770     key = sqlite3_column_blob (stmt, 1);
771     if (sizeof (GNUNET_HashCode) == sqlite3_column_bytes (stmt, 1))
772       proc (proc_cls, key, 1);
773   }
774   if (SQLITE_DONE != ret)
775     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
776   sqlite3_finalize (stmt);
777
778 #endif
779   return 0;
780 }
781
782  
783 /**
784  * Get a particular node from the signature tree.
785  *
786  * @param cls closure (internal context for the plugin)
787  * @param zone hash of public key of the zone
788  * @param loc location of the node in the signature tree
789  * @param cb function to call with the result
790  * @param cb_cls closure for cont
791  */
792 static void
793 namestore_sqlite_get_node (void *cls, 
794                            const GNUNET_HashCode *zone,
795                            const struct GNUNET_NAMESTORE_SignatureLocation *loc,
796                            GNUNET_NAMESTORE_NodeCallback cb, void *cb_cls)
797 {
798   // FIXME
799 }
800
801
802 /**
803  * Get the current signature for a zone.
804  *
805  * @param cls closure (internal context for the plugin)
806  * @param zone hash of public key of the zone
807  * @param cb function to call with the result
808  * @param cb_cls closure for cont
809  */
810 static void 
811 namestore_sqlite_get_signature (void *cls, 
812                                 const GNUNET_HashCode *zone,
813                                 GNUNET_NAMESTORE_SignatureCallback cb, void *cb_cls)
814 {
815   // FIXME
816 }
817
818
819 /**
820  * Delete an entire zone (all revisions, all records, all nodes,
821  * all signatures).  Not used in normal operation.
822  *
823  * @param cls closure (internal context for the plugin)
824  * @param zone zone to delete
825  */
826 static void 
827 namestore_sqlite_delete_zone (void *cls,
828                               const GNUNET_HashCode *zone)
829 {
830   // FIXME
831 }
832
833
834 /**
835  * Entry point for the plugin.
836  *
837  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
838  * @return NULL on error, othrewise the plugin context
839  */
840 void *
841 libgnunet_plugin_namestore_sqlite_init (void *cls)
842 {
843   static struct Plugin plugin;
844   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
845   struct GNUNET_NAMESTORE_PluginFunctions *api;
846
847   if (NULL != plugin.cfg)
848     return NULL;                /* can only initialize once! */
849   memset (&plugin, 0, sizeof (struct Plugin));
850   plugin.cfg = cfg;  
851   if (GNUNET_OK != database_setup (&plugin))
852   {
853     database_shutdown (&plugin);
854     return NULL;
855   }
856   api = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_PluginFunctions));
857   api->cls = &plugin;
858   api->put_record = &namestore_sqlite_put_record;
859   api->put_node = &namestore_sqlite_put_node;
860   api->put_signature = &namestore_sqlite_put_signature;
861   api->iterate_records = &namestore_sqlite_iterate_records;
862   api->get_node = &namestore_sqlite_get_node;
863   api->get_signature = &namestore_sqlite_get_signature;
864   api->delete_zone = &namestore_sqlite_delete_zone;
865   LOG (GNUNET_ERROR_TYPE_INFO, 
866        _("Sqlite database running\n"));
867   return api;
868 }
869
870
871 /**
872  * Exit point from the plugin.
873  *
874  * @param cls the plugin context (as returned by "init")
875  * @return always NULL
876  */
877 void *
878 libgnunet_plugin_namestore_sqlite_done (void *cls)
879 {
880   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
881   struct Plugin *plugin = api->cls;
882
883   LOG (GNUNET_ERROR_TYPE_DEBUG, 
884        "sqlite plugin is done\n");
885   database_shutdown (plugin);
886   plugin->cfg = NULL;
887   GNUNET_free (api);
888   LOG (GNUNET_ERROR_TYPE_DEBUG, 
889        "sqlite plugin is finished\n");
890   return NULL;
891 }
892
893 /* end of plugin_namestore_sqlite.c */