-fix FTBFS
[oweals/gnunet.git] / src / namestore / plugin_namestore_sqlite.c
1  /*
2   * This file is part of GNUnet
3   * (C) 2009-2013 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?  A
35  * low value makes sure that we are more responsive to requests
36  * (especially PUTs).  A high value guarantees a higher success rate
37  * (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
41  * succeed 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 caching a block
76    */
77   sqlite3_stmt *cache_block;
78
79   /**
80    * Precompiled SQL for looking up a block
81    */
82   sqlite3_stmt *lookup_block;
83
84   /**
85    * Precompiled SQL for removing expired blocks
86    */
87   sqlite3_stmt *expire_blocks;
88
89   /**
90    * Precompiled SQL to store records.
91    */
92   sqlite3_stmt *store_records;
93
94   /**
95    * Precompiled SQL to deltete existing records.
96    */
97   sqlite3_stmt *delete_records;
98
99   /**
100    * Precompiled SQL for iterate records within a zone.
101    */
102   sqlite3_stmt *iterate_zone;
103
104   /**
105    * Precompiled SQL for iterate all records within all zones.
106    */
107   sqlite3_stmt *iterate_all_zones;
108
109   /**
110    * Precompiled SQL to for reverse lookup based on PKEY.
111    */
112   sqlite3_stmt *zone_to_name;
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_query_hash ON ns096blocks (query,expiration_time)",
151                       NULL, NULL, NULL)) ||
152        (SQLITE_OK !=
153         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_block_expiration ON ns096blocks (expiration_time)",
154                       NULL, NULL, NULL)) ||
155        (SQLITE_OK !=
156         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_pkey_reverse ON ns096records (zone_private_key,pkey_hash)",
157                       NULL, NULL, NULL)) ||
158        (SQLITE_OK !=
159         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_pkey_iter ON ns096records (zone_private_key,rvalue)",
160                       NULL, NULL, NULL)) ||
161        (SQLITE_OK !=
162         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS it_iter ON ns096records (rvalue)",
163                       NULL, NULL, NULL)) )
164     LOG (GNUNET_ERROR_TYPE_ERROR, 
165          "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
166 }
167
168
169 #if 0
170 #define CHECK(a) GNUNET_break(a)
171 #define ENULL NULL
172 #else
173 #define ENULL &e
174 #define ENULL_DEFINED 1
175 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
176 #endif
177
178
179 /**
180  * Initialize the database connections and associated
181  * data structures (create tables and indices
182  * as needed as well).
183  *
184  * @param plugin the plugin context (state for this module)
185  * @return #GNUNET_OK on success
186  */
187 static int
188 database_setup (struct Plugin *plugin)
189 {
190   sqlite3_stmt *stmt;
191   char *afsdir;
192 #if ENULL_DEFINED
193   char *e;
194 #endif
195
196   if (GNUNET_OK !=
197       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "namestore-sqlite",
198                                                "FILENAME", &afsdir))
199   {
200     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
201                                "namestore-sqlite", "FILENAME");
202     return GNUNET_SYSERR;
203   }
204   if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
205   {
206     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
207     {
208       GNUNET_break (0);
209       GNUNET_free (afsdir);
210       return GNUNET_SYSERR;
211     }
212   }
213   /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
214   plugin->fn = 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 = 'ns096blocks'",
256                      &stmt));
257   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
258       (sqlite3_exec
259        (plugin->dbh,
260         "CREATE TABLE ns096blocks (" 
261         " query BLOB NOT NULL DEFAULT ''," 
262         " block BLOB NOT NULL DEFAULT ''," 
263         " expiration_time INT8 NOT NULL DEFAULT 0" 
264         ")", 
265         NULL, NULL, NULL) != SQLITE_OK))
266   {
267     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
268     sqlite3_finalize (stmt);
269     return GNUNET_SYSERR;
270   }
271   sqlite3_finalize (stmt);
272
273   CHECK (SQLITE_OK ==
274          sq_prepare (plugin->dbh,
275                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns096records'",
276                      &stmt));
277   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
278       (sqlite3_exec
279        (plugin->dbh,
280         "CREATE TABLE ns096records (" 
281         " zone_private_key BLOB NOT NULL DEFAULT ''," 
282         " pkey_hash BLOB," 
283         " rvalue INT8 NOT NULL DEFAULT '',"
284         " record_count INT NOT NULL DEFAULT 0,"
285         " record_data BLOB NOT NULL DEFAULT '',"
286         " label TEXT NOT NULL DEFAULT ''" 
287         ")", 
288         NULL, NULL, NULL) != SQLITE_OK))
289   {
290     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
291     sqlite3_finalize (stmt);
292     return GNUNET_SYSERR;
293   }
294   sqlite3_finalize (stmt);
295
296   create_indices (plugin->dbh);
297
298   if ((sq_prepare
299        (plugin->dbh,
300         "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
301         &plugin->cache_block) != SQLITE_OK) ||
302       (sq_prepare
303        (plugin->dbh,
304         "DELETE FROM ns096blocks WHERE expiration_time<?",
305         &plugin->expire_blocks) != SQLITE_OK) ||
306       (sq_prepare
307        (plugin->dbh,
308         "SELECT block FROM ns096blocks WHERE query=? ORDER BY expiration_time DESC LIMIT 1",
309         &plugin->lookup_block) != SQLITE_OK) ||
310       (sq_prepare
311        (plugin->dbh,
312         "INSERT INTO ns096records (zone_private_key, pkey_hash, rvalue, record_count, record_data, label)"
313         " VALUES (?, ?, ?, ?, ?, ?)",
314         &plugin->store_records) != SQLITE_OK) ||
315       (sq_prepare
316        (plugin->dbh,
317         "DELETE FROM ns096records WHERE zone_private_key=? AND label=?",
318         &plugin->delete_records) != SQLITE_OK) ||
319       (sq_prepare
320        (plugin->dbh,
321         "SELECT record_count,record_data,label"
322         " FROM ns096records WHERE zone_private_key=? AND pkey_hash=?",
323         &plugin->zone_to_name) != SQLITE_OK) ||
324       (sq_prepare
325        (plugin->dbh,
326         "SELECT record_count,record_data,label" 
327         " FROM ns096records WHERE zone_private_key=? ORDER BY rvalue LIMIT 1 OFFSET ?",
328         &plugin->iterate_zone) != SQLITE_OK) ||
329       (sq_prepare
330        (plugin->dbh,
331         "SELECT record_count,record_data,label" 
332         " FROM ns096records ORDER BY rvalue LIMIT 1 OFFSET ?",
333         &plugin->iterate_all_zones) != SQLITE_OK) 
334       )
335   {
336     LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
337     return GNUNET_SYSERR;
338   }
339   return GNUNET_OK;
340 }
341
342
343 /**
344  * Shutdown database connection and associate data
345  * structures.
346  * @param plugin the plugin context (state for this module)
347  */
348 static void
349 database_shutdown (struct Plugin *plugin)
350 {
351   int result;
352   sqlite3_stmt *stmt;
353
354   if (NULL != plugin->cache_block)
355     sqlite3_finalize (plugin->cache_block);
356   if (NULL != plugin->expire_blocks)
357     sqlite3_finalize (plugin->expire_blocks);
358   if (NULL != plugin->lookup_block)
359     sqlite3_finalize (plugin->lookup_block);
360   if (NULL != plugin->store_records)
361     sqlite3_finalize (plugin->store_records);
362   if (NULL != plugin->delete_records)
363     sqlite3_finalize (plugin->delete_records);
364   if (NULL != plugin->iterate_zone)
365     sqlite3_finalize (plugin->iterate_zone);
366   if (NULL != plugin->zone_to_name)
367     sqlite3_finalize (plugin->zone_to_name);
368   result = sqlite3_close (plugin->dbh);
369   if (result == SQLITE_BUSY)
370   {
371     LOG (GNUNET_ERROR_TYPE_WARNING,
372          _("Tried to close sqlite without finalizing all prepared statements.\n"));
373     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
374     while (stmt != NULL)
375     {
376       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
377                        "Closing statement %p\n", stmt);
378       result = sqlite3_finalize (stmt);
379       if (result != SQLITE_OK)
380         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
381                          "Failed to close statement %p: %d\n", stmt, result);
382       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
383     }
384     result = sqlite3_close (plugin->dbh);
385   }
386   if (SQLITE_OK != result)
387     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
388
389   GNUNET_free_non_null (plugin->fn);
390 }
391
392
393 /**
394  * Removes any expired block.
395  *
396  * @param plugin the plugin
397  */
398 static void
399 namestore_sqlite_expire_blocks (struct Plugin *plugin)
400 {
401   struct GNUNET_TIME_Absolute now;
402   int n;
403
404   now = GNUNET_TIME_absolute_get ();
405   if (SQLITE_OK != sqlite3_bind_int64 (plugin->expire_blocks, 
406                                        1, now.abs_value_us))
407   {
408     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
409                 "sqlite3_bind_XXXX");
410     if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
411       LOG_SQLITE (plugin,
412                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
413                   "sqlite3_reset");
414     return;
415   }
416   n = sqlite3_step (plugin->expire_blocks);
417   if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
418     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
419                 "sqlite3_reset");
420   switch (n)
421   {
422   case SQLITE_DONE:
423     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Records expired\n");
424     return;
425   case SQLITE_BUSY:
426     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
427                 "sqlite3_step");
428     return;
429   default:
430     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
431                 "sqlite3_step");
432     return;
433   }
434 }
435
436
437 /**
438  * Cache a block in the datastore.
439  *
440  * @param cls closure (internal context for the plugin)
441  * @param block block to cache
442  * @return GNUNET_OK on success, else GNUNET_SYSERR
443  */
444 static int 
445 namestore_sqlite_cache_block (void *cls, 
446                               const struct GNUNET_NAMESTORE_Block *block)
447 {
448   struct Plugin *plugin = cls;
449   struct GNUNET_HashCode query;
450   struct GNUNET_TIME_Absolute expiration;
451   size_t block_size;
452   int n;
453
454   namestore_sqlite_expire_blocks (plugin);
455   GNUNET_CRYPTO_hash (&block->derived_key, 
456                       sizeof (struct GNUNET_CRYPTO_EccPublicKey), 
457                       &query);
458   expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
459   block_size = ntohl (block->purpose.size) + 
460     sizeof (struct GNUNET_CRYPTO_EccPublicKey) + 
461     sizeof (struct GNUNET_CRYPTO_EccSignature); 
462   if (block_size > 64 * 65536)
463   {
464     GNUNET_break (0);
465     return GNUNET_SYSERR;
466   }
467   if ((SQLITE_OK != sqlite3_bind_blob (plugin->cache_block, 1, &query, sizeof (struct GNUNET_HashCode), SQLITE_STATIC)) ||
468       (SQLITE_OK != sqlite3_bind_blob (plugin->cache_block, 2, block, block_size, SQLITE_STATIC)) ||
469       (SQLITE_OK != sqlite3_bind_int64 (plugin->cache_block, 3, expiration.abs_value_us)))
470   {
471     LOG_SQLITE (plugin, 
472                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
473                 "sqlite3_bind_XXXX");
474     if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
475       LOG_SQLITE (plugin, 
476                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
477                   "sqlite3_reset");
478     return GNUNET_SYSERR;
479     
480   }
481   n = sqlite3_step (plugin->cache_block);
482   if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
483     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
484                 "sqlite3_reset");
485   switch (n)
486   {
487   case SQLITE_DONE:
488     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
489     return GNUNET_OK;
490   case SQLITE_BUSY:
491     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
492                 "sqlite3_step");
493     return GNUNET_NO;
494   default:
495     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
496                 "sqlite3_step");
497     return GNUNET_SYSERR;  
498   }
499 }
500
501
502 /**
503  * Get the block for a particular zone and label in the
504  * datastore.  Will return at most one result to the iterator.
505  *
506  * @param cls closure (internal context for the plugin)
507  * @param query hash of public key derived from the zone and the label
508  * @param iter function to call with the result
509  * @param iter_cls closure for iter
510  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
511  */
512 static int
513 namestore_sqlite_lookup_block (void *cls, 
514                                const struct GNUNET_HashCode *query,
515                                GNUNET_NAMESTORE_BlockCallback iter, void *iter_cls)
516 {
517   struct Plugin *plugin = cls;
518   int ret;
519   int sret;
520   size_t block_size;
521   const struct GNUNET_NAMESTORE_Block *block;
522
523   if (SQLITE_OK != sqlite3_bind_blob (plugin->lookup_block, 1,
524                                       query, sizeof (struct GNUNET_HashCode),
525                                       SQLITE_STATIC))
526   {
527     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
528                 "sqlite3_bind_XXXX");
529     if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
530       LOG_SQLITE (plugin,
531                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
532                   "sqlite3_reset");
533     return GNUNET_SYSERR;
534   }      
535
536   ret = GNUNET_NO;
537   if (SQLITE_ROW == (sret = sqlite3_step (plugin->lookup_block)))
538   {     
539     block = sqlite3_column_blob (plugin->lookup_block, 0);
540     block_size = sqlite3_column_bytes (plugin->lookup_block, 0);
541     if ( (block_size < sizeof (struct GNUNET_NAMESTORE_Block)) ||
542          (ntohl (block->purpose.size) + 
543           sizeof (struct GNUNET_CRYPTO_EccPublicKey) + 
544           sizeof (struct GNUNET_CRYPTO_EccSignature) != block_size) )
545     {
546       GNUNET_break (0);
547       ret = GNUNET_SYSERR;     
548     }
549     else
550     {
551       iter (iter_cls, block);    
552       ret = GNUNET_YES;
553     }
554   }
555   else
556   {
557     if (SQLITE_DONE != sret)
558     {
559       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");    
560       ret = GNUNET_SYSERR;
561     }
562   }
563   if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
564     LOG_SQLITE (plugin,
565                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
566                 "sqlite3_reset");
567   return ret;
568 }
569
570
571 /**
572  * Store a record in the datastore.  Removes any existing record in the
573  * same zone with the same name.
574  *
575  * @param cls closure (internal context for the plugin)
576  * @param zone_key private key of the zone
577  * @param label name that is being mapped (at most 255 characters long)
578  * @param rd_count number of entries in 'rd' array
579  * @param rd array of records with data to store
580  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
581  */
582 static int 
583 namestore_sqlite_store_records (void *cls, 
584                                 const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
585                                 const char *label,
586                                 unsigned int rd_count,
587                                 const struct GNUNET_NAMESTORE_RecordData *rd)
588 {
589   struct Plugin *plugin = cls;
590   int n;
591   struct GNUNET_HashCode pkey_hash;
592   uint64_t rvalue;
593   size_t data_size;
594   unsigned int i;
595
596   memset (&pkey_hash, 0, sizeof (pkey_hash));
597   for (i=0;i<rd_count;i++)
598     if (GNUNET_NAMESTORE_TYPE_PKEY == rd[i].record_type)
599     {
600       GNUNET_break (sizeof (struct GNUNET_CRYPTO_EccPublicKey) == rd[i].data_size);
601       GNUNET_CRYPTO_hash (rd[i].data,
602                           rd[i].data_size,
603                           &pkey_hash);
604       break;
605     }
606   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
607   data_size = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
608   if (data_size > 64 * 65536)
609   {
610     GNUNET_break (0);
611     return GNUNET_SYSERR;
612   }
613   {
614     char data[data_size];
615
616     if (data_size != GNUNET_NAMESTORE_records_serialize (rd_count, rd,
617                                                          data_size, data))
618     {
619       GNUNET_break (0);
620       return GNUNET_SYSERR;
621     }
622
623     /* First delete 'old' records */
624     if ((SQLITE_OK != sqlite3_bind_blob (plugin->delete_records, 1, 
625                                          zone_key, sizeof (struct GNUNET_CRYPTO_EccPrivateKey), SQLITE_STATIC)) ||
626         (SQLITE_OK != sqlite3_bind_text (plugin->delete_records, 2, label, -1, SQLITE_STATIC)))
627     {
628       LOG_SQLITE (plugin, 
629                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
630                   "sqlite3_bind_XXXX");
631       if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
632         LOG_SQLITE (plugin, 
633                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
634                     "sqlite3_reset");
635       return GNUNET_SYSERR;
636       
637     }
638     n = sqlite3_step (plugin->delete_records);
639     if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
640       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
641                   "sqlite3_reset");
642
643     if (0 != rd_count)
644     {
645       if ((SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 1, 
646                                            zone_key, sizeof (struct GNUNET_CRYPTO_EccPrivateKey), SQLITE_STATIC)) ||
647           (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 2,
648                                            &pkey_hash, sizeof (struct GNUNET_HashCode), SQLITE_STATIC)) ||
649           (SQLITE_OK != sqlite3_bind_int64 (plugin->store_records, 3, rvalue)) ||
650           (SQLITE_OK != sqlite3_bind_int (plugin->store_records, 4, rd_count)) ||
651           (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 5, data, data_size, SQLITE_STATIC)) ||
652           (SQLITE_OK != sqlite3_bind_text (plugin->store_records, 6, label, -1, SQLITE_STATIC)))
653       {
654         LOG_SQLITE (plugin, 
655                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
656                     "sqlite3_bind_XXXX");
657         if (SQLITE_OK != sqlite3_reset (plugin->store_records))
658           LOG_SQLITE (plugin, 
659                       GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
660                       "sqlite3_reset");
661         return GNUNET_SYSERR;   
662       }
663       n = sqlite3_step (plugin->store_records);
664       if (SQLITE_OK != sqlite3_reset (plugin->store_records))
665         LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
666                     "sqlite3_reset");
667     }
668   }
669   switch (n)
670   {
671   case SQLITE_DONE:
672     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
673     return GNUNET_OK;
674   case SQLITE_BUSY:
675     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
676                 "sqlite3_step");
677     return GNUNET_NO;
678   default:
679     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
680                 "sqlite3_step");
681     return GNUNET_SYSERR;  
682   }
683 }
684
685
686 /**
687  * The given 'sqlite' statement has been prepared to be run.
688  * It will return a record which should be given to the iterator.
689  * Runs the statement and parses the returned record.
690  *
691  * @param plugin plugin context
692  * @param stmt to run (and then clean up)
693  * @param zone_key private key of the zone
694  * @param iter iterator to call with the result
695  * @param iter_cls closure for @a iter
696  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
697  */
698 static int
699 get_record_and_call_iterator (struct Plugin *plugin,
700                               sqlite3_stmt *stmt,                             
701                               const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
702                               GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
703 {
704   unsigned int record_count;
705   size_t data_size;
706   const char *data;
707   const char *label;
708   int ret;
709   int sret;
710
711   ret = GNUNET_NO;
712   if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
713   {     
714     record_count = sqlite3_column_int (stmt, 0);
715     data_size = sqlite3_column_bytes (stmt, 1);
716     data = sqlite3_column_blob (stmt, 1);
717     label = (const char*) sqlite3_column_text (stmt, 2);
718
719     if (record_count > 64 * 1024)
720     {
721       /* sanity check, don't stack allocate far too much just
722          because database might contain a large value here */
723       GNUNET_break (0);
724       ret = GNUNET_SYSERR;
725     } 
726     else
727     {
728       struct GNUNET_NAMESTORE_RecordData rd[record_count];
729
730       if (GNUNET_OK !=
731           GNUNET_NAMESTORE_records_deserialize (data_size, data,
732                                                 record_count, rd))
733       {
734         GNUNET_break (0);
735         ret = GNUNET_SYSERR;
736       }
737       else
738       {
739         iter (iter_cls, zone_key, label, 
740               record_count, rd);
741         ret = GNUNET_YES;
742       }
743     }
744   }
745   else
746   {
747     if (SQLITE_DONE != sret)
748       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
749   }
750   if (SQLITE_OK != sqlite3_reset (stmt))
751     LOG_SQLITE (plugin,
752                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
753                 "sqlite3_reset");
754   return ret;
755 }
756
757
758 /**
759  * Iterate over the results for a particular key and zone in the
760  * datastore.  Will return at most one result to the iterator.
761  *
762  * @param cls closure (internal context for the plugin)
763  * @param zone hash of public key of the zone, NULL to iterate over all zones
764  * @param offset offset in the list of all matching records
765  * @param iter function to call with the result
766  * @param iter_cls closure for @a iter
767  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
768  */
769 static int 
770 namestore_sqlite_iterate_records (void *cls, 
771                                   const struct GNUNET_CRYPTO_EccPrivateKey *zone,
772                                   uint64_t offset,
773                                   GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
774 {
775   struct Plugin *plugin = cls;
776   sqlite3_stmt *stmt;
777   int err;
778
779   if (NULL == zone)
780   {
781     stmt = plugin->iterate_all_zones;
782     err = (SQLITE_OK != sqlite3_bind_int64 (stmt, 1,
783                                             offset));
784   }
785   else
786   {
787     stmt = plugin->iterate_zone;
788     err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1, 
789                                              zone, sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
790                                              SQLITE_STATIC)) ||
791             (SQLITE_OK != sqlite3_bind_int64 (stmt, 2,
792                                               offset)) );
793   }
794   if (err)
795   {
796     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
797                 "sqlite3_bind_XXXX");
798     if (SQLITE_OK != sqlite3_reset (stmt))
799       LOG_SQLITE (plugin,
800                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
801                   "sqlite3_reset");
802     return GNUNET_SYSERR;
803   }      
804   return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
805 }
806
807
808 /**
809  * Look for an existing PKEY delegation record for a given public key.
810  * Returns at most one result to the iterator.
811  *
812  * @param cls closure (internal context for the plugin)
813  * @param zone private key of the zone to look up in, never NULL
814  * @param value_zone public key of the target zone (value), never NULL
815  * @param iter function to call with the result
816  * @param iter_cls closure for @a iter
817  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
818  */
819 static int
820 namestore_sqlite_zone_to_name (void *cls, 
821                                const struct GNUNET_CRYPTO_EccPrivateKey *zone,
822                                const struct GNUNET_CRYPTO_EccPublicKey *value_zone,
823                                GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
824 {
825   struct Plugin *plugin = cls;
826   sqlite3_stmt *stmt;
827
828   stmt = plugin->zone_to_name;
829   if ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1, 
830                                         zone, sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
831                                         SQLITE_STATIC)) ||
832        (SQLITE_OK != sqlite3_bind_blob (stmt, 2, 
833                                         value_zone, sizeof (struct GNUNET_CRYPTO_EccPublicKey),
834                                         SQLITE_STATIC)) )
835   {
836     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
837                 "sqlite3_bind_XXXX");
838     if (SQLITE_OK != sqlite3_reset (stmt))
839       LOG_SQLITE (plugin,
840                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
841                   "sqlite3_reset");
842     return GNUNET_SYSERR;
843   }      
844   return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
845 }
846
847
848 /**
849  * Entry point for the plugin.
850  *
851  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
852  * @return NULL on error, otherwise the plugin context
853  */
854 void *
855 libgnunet_plugin_namestore_sqlite_init (void *cls)
856 {
857   static struct Plugin plugin;
858   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
859   struct GNUNET_NAMESTORE_PluginFunctions *api;
860
861   if (NULL != plugin.cfg)
862     return NULL;                /* can only initialize once! */
863   memset (&plugin, 0, sizeof (struct Plugin));
864   plugin.cfg = cfg;  
865   if (GNUNET_OK != database_setup (&plugin))
866   {
867     database_shutdown (&plugin);
868     return NULL;
869   }
870   api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
871   api->cls = &plugin;
872   api->cache_block = &namestore_sqlite_cache_block;
873   api->lookup_block = &namestore_sqlite_lookup_block;
874   api->store_records = &namestore_sqlite_store_records;
875   api->iterate_records = &namestore_sqlite_iterate_records;
876   api->zone_to_name = &namestore_sqlite_zone_to_name;
877   LOG (GNUNET_ERROR_TYPE_INFO, 
878        _("Sqlite database running\n"));
879   return api;
880 }
881
882
883 /**
884  * Exit point from the plugin.
885  *
886  * @param cls the plugin context (as returned by "init")
887  * @return always NULL
888  */
889 void *
890 libgnunet_plugin_namestore_sqlite_done (void *cls)
891 {
892   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
893   struct Plugin *plugin = api->cls;
894
895   database_shutdown (plugin);
896   plugin->cfg = NULL;
897   GNUNET_free (api);
898   LOG (GNUNET_ERROR_TYPE_DEBUG, 
899        "sqlite plugin is finished\n");
900   return NULL;
901 }
902
903 /* end of plugin_namestore_sqlite.c */