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