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