ef1f9b8e34d507a592fa7bd0ae92ee6e3d9d3508
[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     LOG (GNUNET_ERROR_TYPE_ERROR, 
204          _ ("Option `%s' in section `%s' missing in configuration!\n"),
205          "FILENAME", "namestore-sqlite");
206     return GNUNET_SYSERR;
207   }
208   if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
209   {
210     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
211     {
212       GNUNET_break (0);
213       GNUNET_free (afsdir);
214       return GNUNET_SYSERR;
215     }
216   }
217 #ifdef ENABLE_NLS
218   plugin->fn =
219       GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), nl_langinfo (CODESET));
220 #else
221   plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), "UTF-8");       /* good luck */
222 #endif
223   GNUNET_free (afsdir);
224
225   /* Open database and precompile statements */
226   if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
227   {
228     LOG (GNUNET_ERROR_TYPE_ERROR,
229          _("Unable to initialize SQLite: %s.\n"),
230          sqlite3_errmsg (plugin->dbh));
231     return GNUNET_SYSERR;
232   }
233   CHECK (SQLITE_OK ==
234          sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
235                        ENULL));
236   CHECK (SQLITE_OK ==
237          sqlite3_exec (plugin->dbh, "PRAGMA synchronous=NORMAL", NULL, NULL,
238                        ENULL));
239   CHECK (SQLITE_OK ==
240          sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
241                        ENULL));
242   CHECK (SQLITE_OK ==
243          sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
244                        NULL, ENULL));
245   CHECK (SQLITE_OK ==
246          sqlite3_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"", NULL,
247                        NULL, ENULL));
248   CHECK (SQLITE_OK ==
249          sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
250                        ENULL));
251   CHECK (SQLITE_OK ==
252          sqlite3_exec (plugin->dbh, "PRAGMA count_changes=OFF", NULL, NULL,
253                        ENULL));
254   CHECK (SQLITE_OK ==
255          sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
256                        ENULL));
257
258   CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
259
260
261   /* Create tables */
262   CHECK (SQLITE_OK ==
263          sq_prepare (plugin->dbh,
264                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns091records'",
265                      &stmt));
266   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
267       (sqlite3_exec
268        (plugin->dbh,
269         "CREATE TABLE ns091records (" 
270         " zone_key BLOB NOT NULL DEFAULT ''," 
271         " zone_delegation BLOB NOT NULL DEFAULT ''," 
272         " zone_hash BLOB NOT NULL DEFAULT ''," 
273         " record_count INT NOT NULL DEFAULT 0,"
274         " record_data BLOB NOT NULL DEFAULT '',"
275         " block_expiration_time INT8 NOT NULL DEFAULT 0," 
276         " signature BLOB NOT NULL DEFAULT '',"
277         " record_name TEXT NOT NULL DEFAULT ''," 
278         " record_name_hash BLOB NOT NULL DEFAULT ''," 
279         " rvalue INT8 NOT NULL DEFAULT ''"
280         ")", 
281         NULL, NULL, NULL) != SQLITE_OK))
282   {
283     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
284     sqlite3_finalize (stmt);
285     return GNUNET_SYSERR;
286   }
287   sqlite3_finalize (stmt);
288
289   create_indices (plugin->dbh);
290
291 #define ALL "zone_key, record_name, record_count, record_data, block_expiration_time, signature"
292   if ((sq_prepare
293        (plugin->dbh,
294         "INSERT INTO ns091records (" ALL ", zone_delegation, zone_hash, record_name_hash, rvalue) VALUES "
295         "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
296         &plugin->put_records) != SQLITE_OK) ||
297       (sq_prepare
298        (plugin->dbh,
299         "DELETE FROM ns091records WHERE zone_hash=? AND record_name_hash=?",
300         &plugin->remove_records) != SQLITE_OK) ||
301       (sq_prepare
302        (plugin->dbh,
303         "SELECT " ALL
304         " FROM ns091records WHERE zone_hash=? AND record_name_hash=? ORDER BY rvalue LIMIT 1 OFFSET ?",
305         &plugin->iterate_records) != SQLITE_OK) ||
306       (sq_prepare
307        (plugin->dbh,
308         "SELECT " ALL
309         " FROM ns091records WHERE zone_hash=? ORDER BY rvalue  LIMIT 1 OFFSET ?",
310         &plugin->iterate_by_zone) != SQLITE_OK) ||
311       (sq_prepare
312        (plugin->dbh,
313         "SELECT " ALL 
314         " FROM ns091records WHERE record_name_hash=? ORDER BY rvalue LIMIT 1 OFFSET ?",
315         &plugin->iterate_by_name) != SQLITE_OK) ||
316       (sq_prepare
317         (plugin->dbh,
318         "SELECT " ALL
319         " FROM ns091records ORDER BY rvalue LIMIT 1 OFFSET ?",
320         &plugin->iterate_all) != SQLITE_OK) ||
321       (sq_prepare
322         (plugin->dbh,
323         "SELECT " ALL
324         " FROM ns091records WHERE zone_hash=? AND zone_delegation=?",
325         &plugin->zone_to_name) != SQLITE_OK) ||
326       (sq_prepare
327        (plugin->dbh,
328         "DELETE FROM ns091records WHERE zone_hash=?",
329         &plugin->delete_zone) != SQLITE_OK) )
330   {
331     LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
332     return GNUNET_SYSERR;
333   }
334 #undef ALL
335   return GNUNET_OK;
336 }
337
338
339 /**
340  * Shutdown database connection and associate data
341  * structures.
342  * @param plugin the plugin context (state for this module)
343  */
344 static void
345 database_shutdown (struct Plugin *plugin)
346 {
347   int result;
348   sqlite3_stmt *stmt;
349
350   if (NULL != plugin->put_records)
351     sqlite3_finalize (plugin->put_records);
352   if (NULL != plugin->remove_records)
353     sqlite3_finalize (plugin->remove_records);
354   if (NULL != plugin->iterate_records)
355     sqlite3_finalize (plugin->iterate_records);
356   if (NULL != plugin->iterate_by_zone)
357     sqlite3_finalize (plugin->iterate_by_zone);
358   if (NULL != plugin->iterate_by_name)
359     sqlite3_finalize (plugin->iterate_by_name);
360   if (NULL != plugin->iterate_all)
361     sqlite3_finalize (plugin->iterate_all);
362   if (NULL != plugin->zone_to_name)
363     sqlite3_finalize (plugin->zone_to_name);
364   if (NULL != plugin->delete_zone)
365     sqlite3_finalize (plugin->delete_zone);
366   result = sqlite3_close (plugin->dbh);
367   if (result == SQLITE_BUSY)
368   {
369     LOG (GNUNET_ERROR_TYPE_WARNING,
370          _("Tried to close sqlite without finalizing all prepared statements.\n"));
371     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
372     while (stmt != NULL)
373     {
374       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
375                        "Closing statement %p\n", stmt);
376       result = sqlite3_finalize (stmt);
377       if (result != SQLITE_OK)
378         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
379                          "Failed to close statement %p: %d\n", stmt, result);
380       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
381     }
382     result = sqlite3_close (plugin->dbh);
383   }
384   if (SQLITE_OK != result)
385     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
386
387   GNUNET_free_non_null (plugin->fn);
388 }
389
390
391 /**
392  * Removes any existing record in the given zone with the same name.
393  *
394  * @param cls closure (internal context for the plugin)
395  * @param zone hash of the public key of the zone
396  * @param name name to remove (at most 255 characters long)
397  * @return GNUNET_OK on success
398  */
399 static int 
400 namestore_sqlite_remove_records (void *cls, 
401                                  const struct GNUNET_CRYPTO_ShortHashCode *zone,
402                                  const char *name)
403 {
404   struct Plugin *plugin = cls;
405   struct GNUNET_CRYPTO_ShortHashCode nh;
406   size_t name_len;
407   int n;
408
409   name_len = strlen (name);
410   GNUNET_CRYPTO_short_hash (name, name_len, &nh);
411
412   if ((SQLITE_OK != sqlite3_bind_blob (plugin->remove_records, 1, zone, sizeof (struct GNUNET_CRYPTO_ShortHashCode), SQLITE_STATIC)) ||
413       (SQLITE_OK != sqlite3_bind_blob (plugin->remove_records, 2, &nh, sizeof (struct GNUNET_CRYPTO_ShortHashCode), SQLITE_STATIC)))
414   {
415     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
416                 "sqlite3_bind_XXXX");
417     if (SQLITE_OK != sqlite3_reset (plugin->remove_records))
418       LOG_SQLITE (plugin,
419                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
420                   "sqlite3_reset");
421     return GNUNET_SYSERR;
422   }
423   n = sqlite3_step (plugin->remove_records);
424   if (SQLITE_OK != sqlite3_reset (plugin->remove_records))
425     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
426                 "sqlite3_reset");
427   switch (n)
428   {
429   case SQLITE_DONE:
430     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record removed\n");
431     return GNUNET_OK;
432   case SQLITE_BUSY:
433     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
434                 "sqlite3_step");
435     return GNUNET_NO;
436   default:
437     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
438                 "sqlite3_step");
439     return GNUNET_SYSERR;
440   }
441 }
442
443
444 /**
445  * Store a record in the datastore.  Removes any existing record in the
446  * same zone with the same name.
447  *
448  * @param cls closure (internal context for the plugin)
449  * @param zone_key public key of the zone
450  * @param expire when does the corresponding block in the DHT expire (until
451  *               when should we never do a DHT lookup for the same name again)?
452  * @param name name that is being mapped (at most 255 characters long)
453  * @param rd_count number of entries in 'rd' array
454  * @param rd array of records with data to store
455  * @param signature signature of the record block, NULL if signature is unavailable (i.e. 
456  *        because the user queried for a particular record type only)
457  * @return GNUNET_OK on success, else GNUNET_SYSERR
458  */
459 static int 
460 namestore_sqlite_put_records (void *cls, 
461                               const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
462                               struct GNUNET_TIME_Absolute expire,
463                               const char *name,
464                               unsigned int rd_count,
465                               const struct GNUNET_NAMESTORE_RecordData *rd,
466                               const struct GNUNET_CRYPTO_RsaSignature *signature)
467 {
468   struct Plugin *plugin = cls;
469   int n;
470   struct GNUNET_CRYPTO_ShortHashCode zone;
471   struct GNUNET_CRYPTO_ShortHashCode zone_delegation;
472   struct GNUNET_CRYPTO_ShortHashCode nh;
473   size_t name_len;
474   uint64_t rvalue;
475   size_t data_size;
476   unsigned int i;
477
478   GNUNET_CRYPTO_short_hash (zone_key, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), &zone);
479   (void) namestore_sqlite_remove_records (plugin, &zone, name);
480   name_len = strlen (name);
481   GNUNET_CRYPTO_short_hash (name, name_len, &nh);
482   memset (&zone_delegation, 0, sizeof (zone_delegation));
483   for (i=0;i<rd_count;i++)
484     if (rd[i].record_type == GNUNET_NAMESTORE_TYPE_PKEY)
485     {
486       GNUNET_assert (sizeof (struct GNUNET_CRYPTO_ShortHashCode) == rd[i].data_size);
487       memcpy (&zone_delegation,
488               rd[i].data,
489               sizeof (struct GNUNET_CRYPTO_ShortHashCode));
490       break;
491     }
492   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
493   data_size = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
494   if (data_size > 64 * 65536)
495   {
496     GNUNET_break (0);
497     return GNUNET_SYSERR;
498   }
499   {
500     char data[data_size];
501
502     if (data_size != GNUNET_NAMESTORE_records_serialize (rd_count, rd,
503                                                          data_size, data))
504     {
505       GNUNET_break (0);
506       return GNUNET_SYSERR;
507     }
508     if ((SQLITE_OK != sqlite3_bind_blob (plugin->put_records, 1, zone_key, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), SQLITE_STATIC)) ||
509         (SQLITE_OK != sqlite3_bind_text (plugin->put_records, 2, name, -1, SQLITE_STATIC)) ||
510         (SQLITE_OK != sqlite3_bind_int (plugin->put_records, 3, rd_count)) ||
511         (SQLITE_OK != sqlite3_bind_blob (plugin->put_records, 4, data, data_size, SQLITE_STATIC)) ||
512         (SQLITE_OK != sqlite3_bind_int64 (plugin->put_records, 5, expire.abs_value)) ||
513         (SQLITE_OK != sqlite3_bind_blob (plugin->put_records, 6, signature, sizeof (struct GNUNET_CRYPTO_RsaSignature), SQLITE_STATIC)) ||
514         (SQLITE_OK != sqlite3_bind_blob (plugin->put_records, 7, &zone_delegation, sizeof (struct GNUNET_CRYPTO_ShortHashCode), SQLITE_STATIC)) ||
515         (SQLITE_OK != sqlite3_bind_blob (plugin->put_records, 8, &zone, sizeof (struct GNUNET_CRYPTO_ShortHashCode), SQLITE_STATIC)) ||
516         (SQLITE_OK != sqlite3_bind_blob (plugin->put_records, 9, &nh, sizeof (struct GNUNET_CRYPTO_ShortHashCode), SQLITE_STATIC)) ||
517         (SQLITE_OK != sqlite3_bind_int64 (plugin->put_records, 10, rvalue)) )
518     {
519       LOG_SQLITE (plugin, 
520                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
521                   "sqlite3_bind_XXXX");
522       if (SQLITE_OK != sqlite3_reset (plugin->put_records))
523         LOG_SQLITE (plugin, 
524                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
525                     "sqlite3_reset");
526       return GNUNET_SYSERR;
527       
528     }
529     n = sqlite3_step (plugin->put_records);
530     if (SQLITE_OK != sqlite3_reset (plugin->put_records))
531       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
532                   "sqlite3_reset");
533   }
534   switch (n)
535   {
536   case SQLITE_DONE:
537     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
538     return GNUNET_OK;
539   case SQLITE_BUSY:
540     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
541                 "sqlite3_step");
542     return GNUNET_NO;
543   default:
544     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
545                 "sqlite3_step");
546     return GNUNET_SYSERR;  
547   }
548 }
549
550
551 /**
552  * The given 'sqlite' statement has been prepared to be run.
553  * It will return a record which should be given to the iterator.
554  * Runs the statement and parses the returned record.
555  *
556  * @param plugin plugin context
557  * @param stmt to run (and then clean up)
558  * @param iter iterator to call with the result
559  * @param iter_cls closure for 'iter'
560  * @return GNUNET_OK on success, GNUNET_NO if there were no results, GNUNET_SYSERR on error
561  */
562 static int
563 get_record_and_call_iterator (struct Plugin *plugin,
564                               sqlite3_stmt *stmt,                             
565                               GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
566 {
567   int ret;
568   int sret;
569   unsigned int record_count;
570   size_t data_size;
571   const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key;
572   const struct GNUNET_CRYPTO_RsaSignature *sig;
573   struct GNUNET_TIME_Absolute expiration;
574   const char *data;
575   const char *name;
576
577   ret = GNUNET_NO;
578   if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
579   {     
580     ret = GNUNET_YES;
581     zone_key =  sqlite3_column_blob (stmt, 0);
582     name = (const char*) sqlite3_column_text (stmt, 1);
583     record_count = sqlite3_column_int (stmt, 2);
584     data_size = sqlite3_column_bytes (stmt, 3);
585     data = sqlite3_column_blob (stmt, 3);
586     expiration.abs_value = (uint64_t) sqlite3_column_int64 (stmt, 4);
587     sig = sqlite3_column_blob (stmt, 5);
588
589     if ( (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) != sqlite3_column_bytes (stmt, 0)) ||
590          (sizeof (struct GNUNET_CRYPTO_RsaSignature) != sqlite3_column_bytes (stmt, 5)) )
591     {
592       GNUNET_break (0);
593       ret = GNUNET_SYSERR;
594     }
595     else if (record_count > 64 * 1024)
596     {
597       /* sanity check, don't stack allocate far too much just
598          because database might contain a large value here */
599       GNUNET_break (0);
600       ret = GNUNET_SYSERR;
601     } 
602     else
603     {
604       struct GNUNET_NAMESTORE_RecordData rd[record_count];
605
606       if (GNUNET_OK !=
607           GNUNET_NAMESTORE_records_deserialize (data_size, data,
608                                                 record_count, rd))
609       {
610         GNUNET_break (0);
611         ret = GNUNET_SYSERR;
612       }
613       else
614       {
615         iter (iter_cls, zone_key, expiration, name, 
616               record_count, rd, sig);
617       }
618     }
619   }
620   else
621   {
622     if (SQLITE_DONE != sret)
623       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
624     iter (iter_cls, NULL, GNUNET_TIME_UNIT_ZERO_ABS, NULL, 0, NULL, NULL);
625   }
626   if (SQLITE_OK != sqlite3_reset (stmt))
627     LOG_SQLITE (plugin,
628                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
629                 "sqlite3_reset");
630   return ret;
631 }
632   
633   
634 /**
635  * Iterate over the results for a particular key and zone in the
636  * datastore.  Will return at most one result to the iterator.
637  *
638  * @param cls closure (internal context for the plugin)
639  * @param zone hash of public key of the zone, NULL to iterate over all zones
640  * @param name name as string, NULL to iterate over all records of the zone
641  * @param offset offset in the list of all matching records
642  * @param iter function to call with the result
643  * @param iter_cls closure for iter
644  * @return GNUNET_OK on success, GNUNET_NO if there were no results, GNUNET_SYSERR on error
645  */
646 static int 
647 namestore_sqlite_iterate_records (void *cls, 
648                                   const struct GNUNET_CRYPTO_ShortHashCode *zone,
649                                   const char *name,
650                                   uint64_t offset,
651                                   GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
652 {
653   struct Plugin *plugin = cls;
654   sqlite3_stmt *stmt;
655   struct GNUNET_CRYPTO_ShortHashCode name_hase;
656   unsigned int boff;
657
658   if (NULL == zone)
659     if (NULL == name)
660       stmt = plugin->iterate_all;
661     else
662     {
663       GNUNET_CRYPTO_short_hash (name, strlen(name), &name_hase);
664       stmt = plugin->iterate_by_name;
665     }
666   else
667     if (NULL == name)
668       stmt = plugin->iterate_by_zone;
669     else
670     {
671       GNUNET_CRYPTO_short_hash (name, strlen(name), &name_hase);
672       stmt = plugin->iterate_records;
673     }
674
675   boff = 0;
676   if ( (NULL != zone) &&
677        (SQLITE_OK != sqlite3_bind_blob (stmt, ++boff, 
678                                         zone, sizeof (struct GNUNET_CRYPTO_ShortHashCode),
679                                         SQLITE_STATIC)) )
680   {
681     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
682                 "sqlite3_bind_XXXX");
683     if (SQLITE_OK != sqlite3_reset (stmt))
684       LOG_SQLITE (plugin,
685                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
686                   "sqlite3_reset");
687     return GNUNET_SYSERR;
688   }      
689   if ( (NULL != name) &&
690        (SQLITE_OK != sqlite3_bind_blob (stmt, ++boff, 
691                                         &name_hase, sizeof (struct GNUNET_CRYPTO_ShortHashCode),
692                                         SQLITE_STATIC)) )
693   {
694     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ITERATE NAME HASH: `%8s'", GNUNET_short_h2s(&name_hase));
695     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
696                 "sqlite3_bind_XXXX");
697     if (SQLITE_OK != sqlite3_reset (stmt))
698       LOG_SQLITE (plugin,
699                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
700                   "sqlite3_reset");
701     return GNUNET_SYSERR;
702   }      
703
704   if (SQLITE_OK != sqlite3_bind_int64 (stmt, ++boff, 
705                                        offset)) 
706   {
707     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
708                 "sqlite3_bind_XXXX");
709     if (SQLITE_OK != sqlite3_reset (stmt))
710       LOG_SQLITE (plugin,
711                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
712                   "sqlite3_reset");
713     return GNUNET_SYSERR;
714   }
715
716   return get_record_and_call_iterator (plugin, stmt, iter, iter_cls);
717 }
718
719
720 /**
721  * Look for an existing PKEY delegation record for a given public key.
722  * Returns at most one result to the iterator.
723  *
724  * @param cls closure (internal context for the plugin)
725  * @param zone hash of public key of the zone to look up in, never NULL
726  * @param value_zone hash of the public key of the target zone (value), never NULL
727  * @param iter function to call with the result
728  * @param iter_cls closure for iter
729  * @return GNUNET_OK on success, GNUNET_NO if there were no results, GNUNET_SYSERR on error
730  */
731 static int
732 namestore_sqlite_zone_to_name (void *cls, 
733                                const struct GNUNET_CRYPTO_ShortHashCode *zone,
734                                const struct GNUNET_CRYPTO_ShortHashCode *value_zone,
735                                GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
736 {
737   struct Plugin *plugin = cls;
738   sqlite3_stmt *stmt;
739
740   stmt = plugin->zone_to_name;
741   if ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1, 
742                                         zone, sizeof (struct GNUNET_CRYPTO_ShortHashCode),
743                                         SQLITE_STATIC)) ||
744        (SQLITE_OK != sqlite3_bind_blob (stmt, 2, 
745                                         value_zone, sizeof (struct GNUNET_CRYPTO_ShortHashCode),
746                                         SQLITE_STATIC)) )
747   {
748     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
749                 "sqlite3_bind_XXXX");
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 GNUNET_SYSERR;
755   }      
756   return get_record_and_call_iterator (plugin, stmt, iter, iter_cls);
757 }
758
759
760 /**
761  * Delete an entire zone (all records).  Not used in normal operation.
762  *
763  * @param cls closure (internal context for the plugin)
764  * @param zone zone to delete
765  */
766 static void 
767 namestore_sqlite_delete_zone (void *cls,
768                               const struct GNUNET_CRYPTO_ShortHashCode *zone)
769 {
770   struct Plugin *plugin = cls;
771   sqlite3_stmt *stmt = plugin->delete_zone;
772   int n;
773
774   if (SQLITE_OK != sqlite3_bind_blob (stmt, 1, zone, sizeof (struct GNUNET_CRYPTO_ShortHashCode), SQLITE_STATIC))
775   {
776     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
777                 "sqlite3_bind_XXXX");
778     if (SQLITE_OK != sqlite3_reset (stmt))
779       LOG_SQLITE (plugin,
780                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
781                   "sqlite3_reset");
782     return;
783   }
784   n = sqlite3_step (stmt);
785   if (SQLITE_OK != sqlite3_reset (stmt))
786     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
787                 "sqlite3_reset");
788   switch (n)
789   {
790   case SQLITE_DONE:
791     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Values deleted\n");
792     break;
793   case SQLITE_BUSY:
794     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
795                 "sqlite3_step");
796     break;
797   default:
798     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
799                 "sqlite3_step");
800     break;
801   }
802 }
803
804
805 /**
806  * Entry point for the plugin.
807  *
808  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
809  * @return NULL on error, othrewise the plugin context
810  */
811 void *
812 libgnunet_plugin_namestore_sqlite_init (void *cls)
813 {
814   static struct Plugin plugin;
815   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
816   struct GNUNET_NAMESTORE_PluginFunctions *api;
817
818   if (NULL != plugin.cfg)
819     return NULL;                /* can only initialize once! */
820   memset (&plugin, 0, sizeof (struct Plugin));
821   plugin.cfg = cfg;  
822   if (GNUNET_OK != database_setup (&plugin))
823   {
824     database_shutdown (&plugin);
825     return NULL;
826   }
827   api = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_PluginFunctions));
828   api->cls = &plugin;
829   api->put_records = &namestore_sqlite_put_records;
830   api->remove_records = &namestore_sqlite_remove_records;
831   api->iterate_records = &namestore_sqlite_iterate_records;
832   api->zone_to_name = &namestore_sqlite_zone_to_name;
833   api->delete_zone = &namestore_sqlite_delete_zone;
834   LOG (GNUNET_ERROR_TYPE_INFO, 
835        _("Sqlite database running\n"));
836   return api;
837 }
838
839
840 /**
841  * Exit point from the plugin.
842  *
843  * @param cls the plugin context (as returned by "init")
844  * @return always NULL
845  */
846 void *
847 libgnunet_plugin_namestore_sqlite_done (void *cls)
848 {
849   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
850   struct Plugin *plugin = api->cls;
851
852   LOG (GNUNET_ERROR_TYPE_DEBUG, 
853        "sqlite plugin is done\n");
854   database_shutdown (plugin);
855   plugin->cfg = NULL;
856   GNUNET_free (api);
857   LOG (GNUNET_ERROR_TYPE_DEBUG, 
858        "sqlite plugin is finished\n");
859   return NULL;
860 }
861
862 /* end of plugin_namestore_sqlite.c */