32af90568909f328c9b5c9881eaf4141e6a6b882
[asterisk/asterisk.git] / main / db.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief ASTdb Management
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \note DB3 is licensed under Sleepycat Public License and is thus incompatible
26  * with GPL.  To avoid having to make another exception (and complicate
27  * licensing even further) we elect to use DB1 which is BSD licensed
28  */
29
30 /*** MODULEINFO
31         <support_level>core</support_level>
32  ***/
33
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include "asterisk/_private.h"
39 #include "asterisk/paths.h"     /* use ast_config_AST_DB */
40 #include <sys/time.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <unistd.h>
44 #include <signal.h>
45 #include <dirent.h>
46 #include <sqlite3.h>
47
48 #include "asterisk/channel.h"
49 #include "asterisk/file.h"
50 #include "asterisk/app.h"
51 #include "asterisk/dsp.h"
52 #include "asterisk/astdb.h"
53 #include "asterisk/cli.h"
54 #include "asterisk/utils.h"
55 #include "asterisk/manager.h"
56
57 /*** DOCUMENTATION
58         <manager name="DBGet" language="en_US">
59                 <synopsis>
60                         Get DB Entry.
61                 </synopsis>
62                 <syntax>
63                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
64                         <parameter name="Family" required="true" />
65                         <parameter name="Key" required="true" />
66                 </syntax>
67                 <description>
68                 </description>
69         </manager>
70         <manager name="DBPut" language="en_US">
71                 <synopsis>
72                         Put DB entry.
73                 </synopsis>
74                 <syntax>
75                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
76                         <parameter name="Family" required="true" />
77                         <parameter name="Key" required="true" />
78                         <parameter name="Val" />
79                 </syntax>
80                 <description>
81                 </description>
82         </manager>
83         <manager name="DBDel" language="en_US">
84                 <synopsis>
85                         Delete DB entry.
86                 </synopsis>
87                 <syntax>
88                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
89                         <parameter name="Family" required="true" />
90                         <parameter name="Key" required="true" />
91                 </syntax>
92                 <description>
93                 </description>
94         </manager>
95         <manager name="DBDelTree" language="en_US">
96                 <synopsis>
97                         Delete DB Tree.
98                 </synopsis>
99                 <syntax>
100                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
101                         <parameter name="Family" required="true" />
102                         <parameter name="Key" />
103                 </syntax>
104                 <description>
105                 </description>
106         </manager>
107  ***/
108
109 #define MAX_DB_FIELD 256
110 AST_MUTEX_DEFINE_STATIC(dblock);
111 static ast_cond_t dbcond;
112 static sqlite3 *astdb;
113 static pthread_t syncthread;
114 static int doexit;
115
116 static void db_sync(void);
117
118 #define DEFINE_SQL_STATEMENT(stmt,sql) static sqlite3_stmt *stmt; \
119         const char stmt##_sql[] = sql;
120
121 DEFINE_SQL_STATEMENT(put_stmt, "INSERT OR REPLACE INTO astdb (key, value) VALUES (?, ?)")
122 DEFINE_SQL_STATEMENT(get_stmt, "SELECT value FROM astdb WHERE key=?")
123 DEFINE_SQL_STATEMENT(del_stmt, "DELETE FROM astdb WHERE key=?")
124 DEFINE_SQL_STATEMENT(deltree_stmt, "DELETE FROM astdb WHERE key || '/' LIKE ? || '/' || '%'")
125 DEFINE_SQL_STATEMENT(deltree_all_stmt, "DELETE FROM astdb")
126 DEFINE_SQL_STATEMENT(gettree_stmt, "SELECT key, value FROM astdb WHERE key || '/' LIKE ? || '/' || '%' ORDER BY key")
127 DEFINE_SQL_STATEMENT(gettree_all_stmt, "SELECT key, value FROM astdb ORDER BY key")
128 DEFINE_SQL_STATEMENT(showkey_stmt, "SELECT key, value FROM astdb WHERE key LIKE '%' || '/' || ? ORDER BY key")
129 DEFINE_SQL_STATEMENT(create_astdb_stmt, "CREATE TABLE IF NOT EXISTS astdb(key VARCHAR(256), value VARCHAR(256), PRIMARY KEY(key))")
130
131 static int init_stmt(sqlite3_stmt **stmt, const char *sql, size_t len)
132 {
133         ast_mutex_lock(&dblock);
134         if (sqlite3_prepare(astdb, sql, len, stmt, NULL) != SQLITE_OK) {
135                 ast_log(LOG_WARNING, "Couldn't prepare statement '%s': %s\n", sql, sqlite3_errmsg(astdb));
136                 ast_mutex_unlock(&dblock);
137                 return -1;
138         }
139         ast_mutex_unlock(&dblock);
140
141         return 0;
142 }
143
144 static int init_statements(void)
145 {
146         /* Don't initialize create_astdb_statment here as the astdb table needs to exist
147          * brefore these statments can be initialized */
148         return init_stmt(&get_stmt, get_stmt_sql, sizeof(get_stmt_sql))
149         || init_stmt(&del_stmt, del_stmt_sql, sizeof(del_stmt_sql))
150         || init_stmt(&deltree_stmt, deltree_stmt_sql, sizeof(deltree_stmt_sql))
151         || init_stmt(&deltree_all_stmt, deltree_all_stmt_sql, sizeof(deltree_all_stmt_sql))
152         || init_stmt(&gettree_stmt, gettree_stmt_sql, sizeof(gettree_stmt_sql))
153         || init_stmt(&gettree_all_stmt, gettree_all_stmt_sql, sizeof(gettree_all_stmt_sql))
154         || init_stmt(&showkey_stmt, showkey_stmt_sql, sizeof(showkey_stmt_sql))
155         || init_stmt(&put_stmt, put_stmt_sql, sizeof(put_stmt_sql));
156 }
157
158 static int convert_bdb_to_sqlite3(void)
159 {
160         char *cmd;
161         int res;
162
163         ast_asprintf(&cmd, "%s/astdb2sqlite3 '%s'\n", ast_config_AST_SBIN_DIR, ast_config_AST_DB);
164         res = ast_safe_system(cmd);
165         ast_free(cmd);
166
167         return res;
168 }
169
170 static int db_create_astdb(void)
171 {
172         int res = 0;
173
174         if (!create_astdb_stmt) {
175                 init_stmt(&create_astdb_stmt, create_astdb_stmt_sql, sizeof(create_astdb_stmt_sql));
176         }
177
178         ast_mutex_lock(&dblock);
179         if (sqlite3_step(create_astdb_stmt) != SQLITE_DONE) {
180                 ast_log(LOG_WARNING, "Couldn't create astdb table: %s\n", sqlite3_errmsg(astdb));
181                 res = -1;
182         }
183         sqlite3_reset(create_astdb_stmt);
184         db_sync();
185         ast_mutex_unlock(&dblock);
186
187         return res;
188 }
189
190 static int db_open(void)
191 {
192         char *dbname;
193         struct stat dont_care;
194
195         if (!(dbname = ast_alloca(strlen(ast_config_AST_DB) + sizeof(".sqlite3")))) {
196                 return -1;
197         }
198         strcpy(dbname, ast_config_AST_DB);
199         strcat(dbname, ".sqlite3");
200
201         if (stat(dbname, &dont_care) && !stat(ast_config_AST_DB, &dont_care)) {
202                 if (convert_bdb_to_sqlite3()) {
203                         ast_log(LOG_ERROR, "*** Database conversion failed!\n");
204                         ast_log(LOG_ERROR, "*** Asterisk now uses SQLite3 for its internal\n");
205                         ast_log(LOG_ERROR, "*** database. Conversion from the old astdb\n");
206                         ast_log(LOG_ERROR, "*** failed. Most likely the astdb2sqlite3 utility\n");
207                         ast_log(LOG_ERROR, "*** was not selected for build. To convert the\n");
208                         ast_log(LOG_ERROR, "*** old astdb, please delete '%s'\n", dbname);
209                         ast_log(LOG_ERROR, "*** and re-run 'make menuselect' and select astdb2sqlite3\n");
210                         ast_log(LOG_ERROR, "*** in the Utilities section, then 'make && make install'.\n");
211                         ast_log(LOG_ERROR, "*** It is also imperative that the user under which\n");
212                         ast_log(LOG_ERROR, "*** Asterisk runs have write permission to the directory\n");
213                         ast_log(LOG_ERROR, "*** where the database resides.\n");
214                         sleep(5);
215                 } else {
216                         ast_log(LOG_NOTICE, "Database conversion succeeded!\n");
217                 }
218         }
219
220         ast_mutex_lock(&dblock);
221         if (sqlite3_open(dbname, &astdb) != SQLITE_OK) {
222                 ast_log(LOG_WARNING, "Unable to open Asterisk database '%s': %s\n", dbname, sqlite3_errmsg(astdb));
223                 sqlite3_close(astdb);
224                 ast_mutex_unlock(&dblock);
225                 return -1;
226         }
227         ast_mutex_unlock(&dblock);
228
229         return 0;
230 }
231
232 static int db_init(void)
233 {
234         if (astdb) {
235                 return 0;
236         }
237
238         if (db_open() || db_create_astdb() || init_statements()) {
239                 return -1;
240         }
241
242         return 0;
243 }
244
245 /* We purposely don't lock around the sqlite3 call because the transaction
246  * calls will be called with the database lock held. For any other use, make
247  * sure to take the dblock yourself. */
248 static int db_execute_sql(const char *sql, int (*callback)(void *, int, char **, char **), void *arg)
249 {
250         char *errmsg = NULL;
251         int res =0;
252
253         sqlite3_exec(astdb, sql, callback, arg, &errmsg);
254         if (errmsg) {
255                 ast_log(LOG_WARNING, "Error executing SQL: %s\n", errmsg);
256                 sqlite3_free(errmsg);
257                 res = -1;
258         }
259
260         return res;
261 }
262
263 static int ast_db_begin_transaction(void)
264 {
265         return db_execute_sql("BEGIN TRANSACTION", NULL, NULL);
266 }
267
268 static int ast_db_commit_transaction(void)
269 {
270         return db_execute_sql("COMMIT", NULL, NULL);
271 }
272
273 static int ast_db_rollback_transaction(void)
274 {
275         return db_execute_sql("ROLLBACK", NULL, NULL);
276 }
277
278 int ast_db_put(const char *family, const char *key, const char *value)
279 {
280         char fullkey[MAX_DB_FIELD];
281         size_t fullkey_len;
282         int res = 0;
283
284         if (strlen(family) + strlen(key) + 2 > sizeof(fullkey) - 1) {
285                 ast_log(LOG_WARNING, "Family and key length must be less than %zu bytes\n", sizeof(fullkey) - 3);
286                 return -1;
287         }
288
289         fullkey_len = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, key);
290
291         ast_mutex_lock(&dblock);
292         if (sqlite3_bind_text(put_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
293                 ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
294                 res = -1;
295         } else if (sqlite3_bind_text(put_stmt, 2, value, -1, SQLITE_STATIC) != SQLITE_OK) {
296                 ast_log(LOG_WARNING, "Couldn't bind value to stmt: %s\n", sqlite3_errmsg(astdb));
297                 res = -1;
298         } else if (sqlite3_step(put_stmt) != SQLITE_DONE) {
299                 ast_log(LOG_WARNING, "Couldn't execute statment: %s\n", sqlite3_errmsg(astdb));
300                 res = -1;
301         }
302
303         sqlite3_reset(put_stmt);
304         db_sync();
305         ast_mutex_unlock(&dblock);
306
307         return res;
308 }
309
310 int ast_db_get(const char *family, const char *key, char *value, int valuelen)
311 {
312         const unsigned char *result;
313         char fullkey[MAX_DB_FIELD];
314         size_t fullkey_len;
315         int res = 0;
316
317         if (strlen(family) + strlen(key) + 2 > sizeof(fullkey) - 1) {
318                 ast_log(LOG_WARNING, "Family and key length must be less than %zu bytes\n", sizeof(fullkey) - 3);
319                 return -1;
320         }
321
322         fullkey_len = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, key);
323
324         ast_mutex_lock(&dblock);
325         if (sqlite3_bind_text(get_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
326                 ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
327                 res = -1;
328         } else if (sqlite3_step(get_stmt) != SQLITE_ROW) {
329                 ast_debug(1, "Unable to find key '%s' in family '%s'\n", key, family);
330                 res = -1;
331         } else if (!(result = sqlite3_column_text(get_stmt, 0))) {
332                 ast_log(LOG_WARNING, "Couldn't get value\n");
333                 res = -1;
334         } else {
335                 ast_copy_string(value, (const char *) result, valuelen);
336         }
337         sqlite3_reset(get_stmt);
338         ast_mutex_unlock(&dblock);
339
340         return res;
341 }
342
343 int ast_db_del(const char *family, const char *key)
344 {
345         char fullkey[MAX_DB_FIELD];
346         size_t fullkey_len;
347         int res = 0;
348
349         if (strlen(family) + strlen(key) + 2 > sizeof(fullkey) - 1) {
350                 ast_log(LOG_WARNING, "Family and key length must be less than %zu bytes\n", sizeof(fullkey) - 3);
351                 return -1;
352         }
353
354         fullkey_len = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, key);
355
356         ast_mutex_lock(&dblock);
357         if (sqlite3_bind_text(del_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
358                 ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
359                 res = -1;
360         } else if (sqlite3_step(del_stmt) != SQLITE_DONE) {
361                 ast_debug(1, "Unable to find key '%s' in family '%s'\n", key, family);
362                 res = -1;
363         }
364         sqlite3_reset(del_stmt);
365         db_sync();
366         ast_mutex_unlock(&dblock);
367
368         return res;
369 }
370
371 int ast_db_deltree(const char *family, const char *keytree)
372 {
373         sqlite3_stmt *stmt = deltree_stmt;
374         char prefix[MAX_DB_FIELD];
375         int res = 0;
376
377         if (!ast_strlen_zero(family)) {
378                 if (!ast_strlen_zero(keytree)) {
379                         /* Family and key tree */
380                         snprintf(prefix, sizeof(prefix), "/%s/%s", family, keytree);
381                 } else {
382                         /* Family only */
383                         snprintf(prefix, sizeof(prefix), "/%s", family);
384                 }
385         } else {
386                 prefix[0] = '\0';
387                 stmt = deltree_all_stmt;
388         }
389
390         ast_mutex_lock(&dblock);
391         if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, -1, SQLITE_STATIC) != SQLITE_OK)) {
392                 ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
393                 res = -1;
394         } else if (sqlite3_step(stmt) != SQLITE_DONE) {
395                 ast_log(LOG_WARNING, "Couldn't execute stmt: %s\n", sqlite3_errmsg(astdb));
396                 res = -1;
397         }
398         res = sqlite3_changes(astdb);
399         sqlite3_reset(stmt);
400         db_sync();
401         ast_mutex_unlock(&dblock);
402
403         return res;
404 }
405
406 struct ast_db_entry *ast_db_gettree(const char *family, const char *keytree)
407 {
408         char prefix[MAX_DB_FIELD];
409         sqlite3_stmt *stmt = gettree_stmt;
410         struct ast_db_entry *cur, *last = NULL, *ret = NULL;
411
412         if (!ast_strlen_zero(family)) {
413                 if (!ast_strlen_zero(keytree)) {
414                         /* Family and key tree */
415                         snprintf(prefix, sizeof(prefix), "/%s/%s", family, keytree);
416                 } else {
417                         /* Family only */
418                         snprintf(prefix, sizeof(prefix), "/%s", family);
419                 }
420         } else {
421                 prefix[0] = '\0';
422                 stmt = gettree_all_stmt;
423         }
424
425         ast_mutex_lock(&dblock);
426         if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, -1, SQLITE_STATIC) != SQLITE_OK)) {
427                 ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
428                 sqlite3_reset(stmt);
429                 ast_mutex_unlock(&dblock);
430                 return NULL;
431         }
432
433         while (sqlite3_step(stmt) == SQLITE_ROW) {
434                 const char *key_s, *value_s;
435                 if (!(key_s = (const char *) sqlite3_column_text(stmt, 0))) {
436                         break;
437                 }
438                 if (!(value_s = (const char *) sqlite3_column_text(stmt, 1))) {
439                         break;
440                 }
441                 if (!(cur = ast_malloc(sizeof(*cur) + strlen(key_s) + strlen(value_s) + 2))) {
442                         break;
443                 }
444                 cur->next = NULL;
445                 cur->key = cur->data + strlen(value_s) + 1;
446                 strcpy(cur->data, value_s);
447                 strcpy(cur->key, key_s);
448                 if (last) {
449                         last->next = cur;
450                 } else {
451                         ret = cur;
452                 }
453                 last = cur;
454         }
455         sqlite3_reset(stmt);
456         ast_mutex_unlock(&dblock);
457
458         return ret;
459 }
460
461 void ast_db_freetree(struct ast_db_entry *dbe)
462 {
463         struct ast_db_entry *last;
464         while (dbe) {
465                 last = dbe;
466                 dbe = dbe->next;
467                 ast_free(last);
468         }
469 }
470
471 static char *handle_cli_database_put(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
472 {
473         int res;
474
475         switch (cmd) {
476         case CLI_INIT:
477                 e->command = "database put";
478                 e->usage =
479                         "Usage: database put <family> <key> <value>\n"
480                         "       Adds or updates an entry in the Asterisk database for\n"
481                         "       a given family, key, and value.\n";
482                 return NULL;
483         case CLI_GENERATE:
484                 return NULL;
485         }
486
487         if (a->argc != 5)
488                 return CLI_SHOWUSAGE;
489         res = ast_db_put(a->argv[2], a->argv[3], a->argv[4]);
490         if (res)  {
491                 ast_cli(a->fd, "Failed to update entry\n");
492         } else {
493                 ast_cli(a->fd, "Updated database successfully\n");
494         }
495         return CLI_SUCCESS;
496 }
497
498 static char *handle_cli_database_get(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
499 {
500         int res;
501         char tmp[MAX_DB_FIELD];
502
503         switch (cmd) {
504         case CLI_INIT:
505                 e->command = "database get";
506                 e->usage =
507                         "Usage: database get <family> <key>\n"
508                         "       Retrieves an entry in the Asterisk database for a given\n"
509                         "       family and key.\n";
510                 return NULL;
511         case CLI_GENERATE:
512                 return NULL;
513         }
514
515         if (a->argc != 4)
516                 return CLI_SHOWUSAGE;
517         res = ast_db_get(a->argv[2], a->argv[3], tmp, sizeof(tmp));
518         if (res) {
519                 ast_cli(a->fd, "Database entry not found.\n");
520         } else {
521                 ast_cli(a->fd, "Value: %s\n", tmp);
522         }
523         return CLI_SUCCESS;
524 }
525
526 static char *handle_cli_database_del(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
527 {
528         int res;
529
530         switch (cmd) {
531         case CLI_INIT:
532                 e->command = "database del";
533                 e->usage =
534                         "Usage: database del <family> <key>\n"
535                         "       Deletes an entry in the Asterisk database for a given\n"
536                         "       family and key.\n";
537                 return NULL;
538         case CLI_GENERATE:
539                 return NULL;
540         }
541
542         if (a->argc != 4)
543                 return CLI_SHOWUSAGE;
544         res = ast_db_del(a->argv[2], a->argv[3]);
545         if (res) {
546                 ast_cli(a->fd, "Database entry does not exist.\n");
547         } else {
548                 ast_cli(a->fd, "Database entry removed.\n");
549         }
550         return CLI_SUCCESS;
551 }
552
553 static char *handle_cli_database_deltree(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
554 {
555         int res;
556
557         switch (cmd) {
558         case CLI_INIT:
559                 e->command = "database deltree";
560                 e->usage =
561                         "Usage: database deltree <family> [keytree]\n"
562                         "   OR: database deltree <family>[/keytree]\n"
563                         "       Deletes a family or specific keytree within a family\n"
564                         "       in the Asterisk database.  The two arguments may be\n"
565                         "       separated by either a space or a slash.\n";
566                 return NULL;
567         case CLI_GENERATE:
568                 return NULL;
569         }
570
571         if ((a->argc < 3) || (a->argc > 4))
572                 return CLI_SHOWUSAGE;
573         if (a->argc == 4) {
574                 res = ast_db_deltree(a->argv[2], a->argv[3]);
575         } else {
576                 res = ast_db_deltree(a->argv[2], NULL);
577         }
578         if (res < 0) {
579                 ast_cli(a->fd, "Database entries do not exist.\n");
580         } else {
581                 ast_cli(a->fd, "%d database entries removed.\n",res);
582         }
583         return CLI_SUCCESS;
584 }
585
586 static char *handle_cli_database_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
587 {
588         char prefix[MAX_DB_FIELD];
589         int counter = 0;
590         sqlite3_stmt *stmt = gettree_stmt;
591
592         switch (cmd) {
593         case CLI_INIT:
594                 e->command = "database show";
595                 e->usage =
596                         "Usage: database show [family [keytree]]\n"
597                         "   OR: database show [family[/keytree]]\n"
598                         "       Shows Asterisk database contents, optionally restricted\n"
599                         "       to a given family, or family and keytree. The two arguments\n"
600                         "       may be separated either by a space or by a slash.\n";
601                 return NULL;
602         case CLI_GENERATE:
603                 return NULL;
604         }
605
606         if (a->argc == 4) {
607                 /* Family and key tree */
608                 snprintf(prefix, sizeof(prefix), "/%s/%s", a->argv[2], a->argv[3]);
609         } else if (a->argc == 3) {
610                 /* Family only */
611                 snprintf(prefix, sizeof(prefix), "/%s", a->argv[2]);
612         } else if (a->argc == 2) {
613                 /* Neither */
614                 prefix[0] = '\0';
615                 stmt = gettree_all_stmt;
616
617         } else {
618                 return CLI_SHOWUSAGE;
619         }
620
621         ast_mutex_lock(&dblock);
622         if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, -1, SQLITE_STATIC) != SQLITE_OK)) {
623                 ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
624                 sqlite3_reset(stmt);
625                 ast_mutex_unlock(&dblock);
626                 return NULL;
627         }
628
629         while (sqlite3_step(stmt) == SQLITE_ROW) {
630                 const char *key_s, *value_s;
631                 if (!(key_s = (const char *) sqlite3_column_text(stmt, 0))) {
632                         ast_log(LOG_WARNING, "Skipping invalid key!\n");
633                         continue;
634                 }
635                 if (!(value_s = (const char *) sqlite3_column_text(stmt, 1))) {
636                         ast_log(LOG_WARNING, "Skipping invalid value!\n");
637                         continue;
638                 }
639                 ++counter;
640                 ast_cli(a->fd, "%-50s: %-25s\n", key_s, value_s);
641         }
642
643         sqlite3_reset(stmt);
644         ast_mutex_unlock(&dblock);
645
646         ast_cli(a->fd, "%d results found.\n", counter);
647         return CLI_SUCCESS;
648 }
649
650 static char *handle_cli_database_showkey(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
651 {
652         int counter = 0;
653
654         switch (cmd) {
655         case CLI_INIT:
656                 e->command = "database showkey";
657                 e->usage =
658                         "Usage: database showkey <keytree>\n"
659                         "       Shows Asterisk database contents, restricted to a given key.\n";
660                 return NULL;
661         case CLI_GENERATE:
662                 return NULL;
663         }
664
665         if (a->argc != 3) {
666                 return CLI_SHOWUSAGE;
667         }
668
669         ast_mutex_lock(&dblock);
670         if (!ast_strlen_zero(a->argv[2]) && (sqlite3_bind_text(showkey_stmt, 1, a->argv[2], -1, SQLITE_STATIC) != SQLITE_OK)) {
671                 ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", a->argv[2], sqlite3_errmsg(astdb));
672                 sqlite3_reset(showkey_stmt);
673                 ast_mutex_unlock(&dblock);
674                 return NULL;
675         }
676
677         while (sqlite3_step(showkey_stmt) == SQLITE_ROW) {
678                 const char *key_s, *value_s;
679                 if (!(key_s = (const char *) sqlite3_column_text(showkey_stmt, 0))) {
680                         break;
681                 }
682                 if (!(value_s = (const char *) sqlite3_column_text(showkey_stmt, 1))) {
683                         break;
684                 }
685                 ++counter;
686                 ast_cli(a->fd, "%-50s: %-25s\n", key_s, value_s);
687         }
688         sqlite3_reset(showkey_stmt);
689         ast_mutex_unlock(&dblock);
690
691         ast_cli(a->fd, "%d results found.\n", counter);
692         return CLI_SUCCESS;
693 }
694
695 static int display_results(void *arg, int columns, char **values, char **colnames)
696 {
697         struct ast_cli_args *a = arg;
698         size_t x;
699
700         for (x = 0; x < columns; x++) {
701                 ast_cli(a->fd, "%-5s: %-50s\n", colnames[x], values[x]);
702         }
703         ast_cli(a->fd, "\n");
704
705         return 0;
706 }
707
708 static char *handle_cli_database_query(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
709 {
710
711         switch (cmd) {
712         case CLI_INIT:
713                 e->command = "database query";
714                 e->usage =
715                         "Usage: database query \"<SQL Statement>\"\n"
716                         "       Run a user-specified SQL query on the database. Be careful.\n";
717                 return NULL;
718         case CLI_GENERATE:
719                 return NULL;
720         }
721
722         if (a->argc != 3) {
723                 return CLI_SHOWUSAGE;
724         }
725
726         ast_mutex_lock(&dblock);
727         db_execute_sql(a->argv[2], display_results, a);
728         db_sync(); /* Go ahead and sync the db in case they write */
729         ast_mutex_unlock(&dblock);
730
731         return CLI_SUCCESS;
732 }
733
734 static struct ast_cli_entry cli_database[] = {
735         AST_CLI_DEFINE(handle_cli_database_show,    "Shows database contents"),
736         AST_CLI_DEFINE(handle_cli_database_showkey, "Shows database contents"),
737         AST_CLI_DEFINE(handle_cli_database_get,     "Gets database value"),
738         AST_CLI_DEFINE(handle_cli_database_put,     "Adds/updates database value"),
739         AST_CLI_DEFINE(handle_cli_database_del,     "Removes database key/value"),
740         AST_CLI_DEFINE(handle_cli_database_deltree, "Removes database keytree/values"),
741         AST_CLI_DEFINE(handle_cli_database_query,   "Run a user-specified query on the astdb"),
742 };
743
744 static int manager_dbput(struct mansession *s, const struct message *m)
745 {
746         const char *family = astman_get_header(m, "Family");
747         const char *key = astman_get_header(m, "Key");
748         const char *val = astman_get_header(m, "Val");
749         int res;
750
751         if (ast_strlen_zero(family)) {
752                 astman_send_error(s, m, "No family specified");
753                 return 0;
754         }
755         if (ast_strlen_zero(key)) {
756                 astman_send_error(s, m, "No key specified");
757                 return 0;
758         }
759
760         res = ast_db_put(family, key, S_OR(val, ""));
761         if (res) {
762                 astman_send_error(s, m, "Failed to update entry");
763         } else {
764                 astman_send_ack(s, m, "Updated database successfully");
765         }
766         return 0;
767 }
768
769 static int manager_dbget(struct mansession *s, const struct message *m)
770 {
771         const char *id = astman_get_header(m,"ActionID");
772         char idText[256] = "";
773         const char *family = astman_get_header(m, "Family");
774         const char *key = astman_get_header(m, "Key");
775         char tmp[MAX_DB_FIELD];
776         int res;
777
778         if (ast_strlen_zero(family)) {
779                 astman_send_error(s, m, "No family specified.");
780                 return 0;
781         }
782         if (ast_strlen_zero(key)) {
783                 astman_send_error(s, m, "No key specified.");
784                 return 0;
785         }
786
787         if (!ast_strlen_zero(id))
788                 snprintf(idText, sizeof(idText) ,"ActionID: %s\r\n", id);
789
790         res = ast_db_get(family, key, tmp, sizeof(tmp));
791         if (res) {
792                 astman_send_error(s, m, "Database entry not found");
793         } else {
794                 astman_send_ack(s, m, "Result will follow");
795                 astman_append(s, "Event: DBGetResponse\r\n"
796                                 "Family: %s\r\n"
797                                 "Key: %s\r\n"
798                                 "Val: %s\r\n"
799                                 "%s"
800                                 "\r\n",
801                                 family, key, tmp, idText);
802                 astman_append(s, "Event: DBGetComplete\r\n"
803                                 "%s"
804                                 "\r\n",
805                                 idText);
806         }
807         return 0;
808 }
809
810 static int manager_dbdel(struct mansession *s, const struct message *m)
811 {
812         const char *family = astman_get_header(m, "Family");
813         const char *key = astman_get_header(m, "Key");
814         int res;
815
816         if (ast_strlen_zero(family)) {
817                 astman_send_error(s, m, "No family specified.");
818                 return 0;
819         }
820
821         if (ast_strlen_zero(key)) {
822                 astman_send_error(s, m, "No key specified.");
823                 return 0;
824         }
825
826         res = ast_db_del(family, key);
827         if (res)
828                 astman_send_error(s, m, "Database entry not found");
829         else
830                 astman_send_ack(s, m, "Key deleted successfully");
831
832         return 0;
833 }
834
835 static int manager_dbdeltree(struct mansession *s, const struct message *m)
836 {
837         const char *family = astman_get_header(m, "Family");
838         const char *key = astman_get_header(m, "Key");
839         int res;
840
841         if (ast_strlen_zero(family)) {
842                 astman_send_error(s, m, "No family specified.");
843                 return 0;
844         }
845
846         if (!ast_strlen_zero(key))
847                 res = ast_db_deltree(family, key);
848         else
849                 res = ast_db_deltree(family, NULL);
850
851         if (res <= 0)
852                 astman_send_error(s, m, "Database entry not found");
853         else
854                 astman_send_ack(s, m, "Key tree deleted successfully");
855
856         return 0;
857 }
858
859 /*!
860  * \internal
861  * \brief Signal the astdb sync thread to do its thing.
862  *
863  * \note dblock is assumed to be held when calling this function.
864  */
865 static void db_sync(void)
866 {
867         ast_cond_signal(&dbcond);
868 }
869
870 /*!
871  * \internal
872  * \brief astdb sync thread
873  *
874  * This thread is in charge of syncing astdb to disk after a change.
875  * By pushing it off to this thread to take care of, this I/O bound operation
876  * will not block other threads from performing other critical processing.
877  * If changes happen rapidly, this thread will also ensure that the sync
878  * operations are rate limited.
879  */
880 static void *db_sync_thread(void *data)
881 {
882         ast_mutex_lock(&dblock);
883         ast_db_begin_transaction();
884         for (;;) {
885                 /* We're ok with spurious wakeups, so we don't worry about a predicate */
886                 ast_cond_wait(&dbcond, &dblock);
887                 if (ast_db_commit_transaction()) {
888                         ast_db_rollback_transaction();
889                 }
890                 if (doexit) {
891                         ast_mutex_unlock(&dblock);
892                         break;
893                 }
894                 ast_db_begin_transaction();
895                 ast_mutex_unlock(&dblock);
896                 sleep(1);
897                 ast_mutex_lock(&dblock);
898                 /* Unfortunately, it is possible for signaling to happen
899                  * when we're not waiting: in the bit when we're unlocked
900                  * above. Do the do-exit check here again. (We could do
901                  * it once, but that would impose a forced delay of 1
902                  * second always.) */
903                 if (doexit) {
904                         ast_mutex_unlock(&dblock);
905                         break;
906                 }
907         }
908
909         return NULL;
910 }
911
912 static void astdb_atexit(void)
913 {
914         /* Set doexit to 1 to kill thread. db_sync must be called with
915          * mutex held. */
916         doexit = 1;
917         ast_mutex_lock(&dblock);
918         db_sync();
919         ast_mutex_unlock(&dblock);
920
921         pthread_join(syncthread, NULL);
922         ast_mutex_lock(&dblock);
923         sqlite3_close(astdb);
924         ast_mutex_unlock(&dblock);
925 }
926
927 int astdb_init(void)
928 {
929         if (db_init()) {
930                 return -1;
931         }
932
933         ast_cond_init(&dbcond, NULL);
934         if (ast_pthread_create_background(&syncthread, NULL, db_sync_thread, NULL)) {
935                 return -1;
936         }
937
938         ast_register_atexit(astdb_atexit);
939         ast_cli_register_multiple(cli_database, ARRAY_LEN(cli_database));
940         ast_manager_register_xml_core("DBGet", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_dbget);
941         ast_manager_register_xml_core("DBPut", EVENT_FLAG_SYSTEM, manager_dbput);
942         ast_manager_register_xml_core("DBDel", EVENT_FLAG_SYSTEM, manager_dbdel);
943         ast_manager_register_xml_core("DBDelTree", EVENT_FLAG_SYSTEM, manager_dbdeltree);
944         return 0;
945 }