Debian Codegraph @

main/db.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2005, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
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 <[email protected]>
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 #include "asterisk/_private.h"
37 #include "asterisk/paths.h" /* use ast_config_AST_DB */
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
42 #include <signal.h>
43 #include <dirent.h>
44 #include <sqlite3.h>
45
46 #include "asterisk/channel.h"
47 #include "asterisk/file.h"
48 #include "asterisk/app.h"
49 #include "asterisk/dsp.h"
50 #include "asterisk/astdb.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/utils.h"
53 #include "asterisk/manager.h"
54
55 /*** DOCUMENTATION
56 <manager name="DBGet" language="en_US">
57 <since>
58 <version>1.2.0</version>
59 </since>
60 <synopsis>
61 Get DB Entry.
62 </synopsis>
63 <syntax>
64 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
65 <parameter name="Family" required="true" />
66 <parameter name="Key" required="true" />
67 </syntax>
68 <description>
69 </description>
70 </manager>
71 <manager name="DBGetTree" language="en_US">
72 <since>
73 <version>19.6.0</version>
74 <version>18.14.0</version>
75 <version>16.28.0</version>
76 </since>
77 <synopsis>
78 Get DB entries, optionally at a particular family/key
79 </synopsis>
80 <syntax>
81 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
82 <parameter name="Family" required="false" />
83 <parameter name="Key" required="false" />
84 </syntax>
85 <description>
86 </description>
87 </manager>
88 <manager name="DBPut" language="en_US">
89 <since>
90 <version>1.2.0</version>
91 </since>
92 <synopsis>
93 Put DB entry.
94 </synopsis>
95 <syntax>
96 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
97 <parameter name="Family" required="true" />
98 <parameter name="Key" required="true" />
99 <parameter name="Val" />
100 </syntax>
101 <description>
102 </description>
103 </manager>
104 <manager name="DBDel" language="en_US">
105 <since>
106 <version>1.6.0</version>
107 </since>
108 <synopsis>
109 Delete DB entry.
110 </synopsis>
111 <syntax>
112 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
113 <parameter name="Family" required="true" />
114 <parameter name="Key" required="true" />
115 </syntax>
116 <description>
117 </description>
118 </manager>
119 <manager name="DBDelTree" language="en_US">
120 <since>
121 <version>1.6.0</version>
122 </since>
123 <synopsis>
124 Delete DB Tree.
125 </synopsis>
126 <syntax>
127 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
128 <parameter name="Family" required="true" />
129 <parameter name="Key" />
130 </syntax>
131 <description>
132 </description>
133 </manager>
134 ***/
135
136 AST_MUTEX_DEFINE_STATIC(dblock);
137 static ast_cond_t dbcond;
138 static sqlite3 *astdb;
139 static pthread_t syncthread;
140 static int doexit;
141 static int dosync;
142
143 static void db_sync(void);
144
145 #define DEFINE_SQL_STATEMENT(stmt,sql) static sqlite3_stmt *stmt; \
146 const char stmt##_sql[] = sql;
147
148 DEFINE_SQL_STATEMENT(put_stmt, "INSERT OR REPLACE INTO astdb (key, value) VALUES (?, ?)")
149 DEFINE_SQL_STATEMENT(get_stmt, "SELECT value FROM astdb WHERE key=?")
150 DEFINE_SQL_STATEMENT(exists_stmt, "SELECT CAST(COUNT(1) AS INTEGER) AS 'exists' FROM astdb WHERE key=?")
151 DEFINE_SQL_STATEMENT(del_stmt, "DELETE FROM astdb WHERE key=?")
152 DEFINE_SQL_STATEMENT(deltree_stmt, "DELETE FROM astdb WHERE key || '/' LIKE ? || '/' || '%'")
153 DEFINE_SQL_STATEMENT(deltree_all_stmt, "DELETE FROM astdb")
154 DEFINE_SQL_STATEMENT(gettree_stmt, "SELECT key, value FROM astdb WHERE key || '/' LIKE ? || '/' || '%' ORDER BY key")
155 DEFINE_SQL_STATEMENT(gettree_all_stmt, "SELECT key, value FROM astdb ORDER BY key")
156 DEFINE_SQL_STATEMENT(showkey_stmt, "SELECT key, value FROM astdb WHERE key LIKE '%' || '/' || ? ORDER BY key")
157 DEFINE_SQL_STATEMENT(create_astdb_stmt, "CREATE TABLE IF NOT EXISTS astdb(key TEXT, value TEXT, PRIMARY KEY(key))")
158
159 /* This query begs an explanation:
160 *
161 * First, the parameter binding syntax used here is slightly different than the other
162 * queries in that we use a numbered parameter so that we can bind once and get the same
163 * value substituted multiple times within the executed query.
164 *
165 * Second, the key comparison is being used to find all keys that are lexicographically
166 * greater than the provided key, but less than the provided key with a high (but
167 * invalid) Unicode codepoint appended to it. This will give us all keys in the database
168 * that have 'key' as a prefix and performs much better than the equivalent "LIKE key ||
169 * '%'" operation.
170 */
171 DEFINE_SQL_STATEMENT(gettree_prefix_stmt, "SELECT key, value FROM astdb WHERE key > ?1 AND key <= ?1 || X'ffff'")
172
173 static int init_stmt(sqlite3_stmt **stmt, const char *sql, size_t len)
174 {
175 ast_mutex_lock(&dblock);
176 if (sqlite3_prepare(astdb, sql, len, stmt, NULL) != SQLITE_OK) {
177 ast_log(LOG_WARNING, "Couldn't prepare statement '%s': %s\n", sql, sqlite3_errmsg(astdb));
178 ast_mutex_unlock(&dblock);
179 return -1;
180 }
181 ast_mutex_unlock(&dblock);
182
183 return 0;
184 }
185
186 /*! \internal
187 * \brief Clean up the prepared SQLite3 statement
188 * \note dblock should already be locked prior to calling this method
189 */
190 static int clean_stmt(sqlite3_stmt **stmt, const char *sql)
191 {
192 if (sqlite3_finalize(*stmt) != SQLITE_OK) {
193 ast_log(LOG_WARNING, "Couldn't finalize statement '%s': %s\n", sql, sqlite3_errmsg(astdb));
194 *stmt = NULL;
195 return -1;
196 }
197 *stmt = NULL;
198 return 0;
199 }
200
201 /*! \internal
202 * \brief Clean up all prepared SQLite3 statements
203 * \note dblock should already be locked prior to calling this method
204 */
205 static void clean_statements(void)
206 {
207 clean_stmt(&get_stmt, get_stmt_sql);
208 clean_stmt(&exists_stmt, exists_stmt_sql);
209 clean_stmt(&del_stmt, del_stmt_sql);
210 clean_stmt(&deltree_stmt, deltree_stmt_sql);
211 clean_stmt(&deltree_all_stmt, deltree_all_stmt_sql);
212 clean_stmt(&gettree_stmt, gettree_stmt_sql);
213 clean_stmt(&gettree_all_stmt, gettree_all_stmt_sql);
214 clean_stmt(&gettree_prefix_stmt, gettree_prefix_stmt_sql);
215 clean_stmt(&showkey_stmt, showkey_stmt_sql);
216 clean_stmt(&put_stmt, put_stmt_sql);
217 clean_stmt(&create_astdb_stmt, create_astdb_stmt_sql);
218 }
219
220 static int init_statements(void)
221 {
222 /* Don't initialize create_astdb_statement here as the astdb table needs to exist
223 * before these statements can be initialized */
224 return init_stmt(&get_stmt, get_stmt_sql, sizeof(get_stmt_sql))
225 || init_stmt(&exists_stmt, exists_stmt_sql, sizeof(exists_stmt_sql))
226 || init_stmt(&del_stmt, del_stmt_sql, sizeof(del_stmt_sql))
227 || init_stmt(&deltree_stmt, deltree_stmt_sql, sizeof(deltree_stmt_sql))
228 || init_stmt(&deltree_all_stmt, deltree_all_stmt_sql, sizeof(deltree_all_stmt_sql))
229 || init_stmt(&gettree_stmt, gettree_stmt_sql, sizeof(gettree_stmt_sql))
230 || init_stmt(&gettree_all_stmt, gettree_all_stmt_sql, sizeof(gettree_all_stmt_sql))
231 || init_stmt(&gettree_prefix_stmt, gettree_prefix_stmt_sql, sizeof(gettree_prefix_stmt_sql))
232 || init_stmt(&showkey_stmt, showkey_stmt_sql, sizeof(showkey_stmt_sql))
233 || init_stmt(&put_stmt, put_stmt_sql, sizeof(put_stmt_sql));
234 }
235
236 static int convert_bdb_to_sqlite3(void)
237 {
238 char *cmd;
239 int res;
240
241 res = ast_asprintf(&cmd, "%s/astdb2sqlite3 '%s'\n", ast_config_AST_SBIN_DIR, ast_config_AST_DB);
242 if (0 <= res) {
243 res = ast_safe_system(cmd);
244 ast_free(cmd);
245 }
246
247 return res;
248 }
249
250 static int db_create_astdb(void)
251 {
252 int res = 0;
253
254 if (!create_astdb_stmt) {
255 init_stmt(&create_astdb_stmt, create_astdb_stmt_sql, sizeof(create_astdb_stmt_sql));
256 }
257
258 ast_mutex_lock(&dblock);
259 if (sqlite3_step(create_astdb_stmt) != SQLITE_DONE) {
260 ast_log(LOG_WARNING, "Couldn't create astdb table: %s\n", sqlite3_errmsg(astdb));
261 res = -1;
262 }
263 sqlite3_reset(create_astdb_stmt);
264 db_sync();
265 ast_mutex_unlock(&dblock);
266
267 return res;
268 }
269
270 static int db_open(void)
271 {
272 char *dbname;
273 struct stat dont_care;
274
275 if (!(dbname = ast_alloca(strlen(ast_config_AST_DB) + sizeof(".sqlite3")))) {
276 return -1;
277 }
278 strcpy(dbname, ast_config_AST_DB);
279 strcat(dbname, ".sqlite3");
280
281 if (stat(dbname, &dont_care) && !stat(ast_config_AST_DB, &dont_care)) {
282 if (convert_bdb_to_sqlite3()) {
283 ast_log(LOG_ERROR, "*** Database conversion failed!\n");
284 ast_log(LOG_ERROR, "*** Asterisk now uses SQLite3 for its internal\n");
285 ast_log(LOG_ERROR, "*** database. Conversion from the old astdb\n");
286 ast_log(LOG_ERROR, "*** failed. Most likely the astdb2sqlite3 utility\n");
287 ast_log(LOG_ERROR, "*** was not selected for build. To convert the\n");
288 ast_log(LOG_ERROR, "*** old astdb, please delete '%s'\n", dbname);
289 ast_log(LOG_ERROR, "*** and re-run 'make menuselect' and select astdb2sqlite3\n");
290 ast_log(LOG_ERROR, "*** in the Utilities section, then 'make && make install'.\n");
291 ast_log(LOG_ERROR, "*** It is also imperative that the user under which\n");
292 ast_log(LOG_ERROR, "*** Asterisk runs have write permission to the directory\n");
293 ast_log(LOG_ERROR, "*** where the database resides.\n");
294 sleep(5);
295 } else {
296 ast_log(LOG_NOTICE, "Database conversion succeeded!\n");
297 }
298 }
299
300 ast_mutex_lock(&dblock);
301 if (sqlite3_open(dbname, &astdb) != SQLITE_OK) {
302 ast_log(LOG_WARNING, "Unable to open Asterisk database '%s': %s\n", dbname, sqlite3_errmsg(astdb));
303 sqlite3_close(astdb);
304 ast_mutex_unlock(&dblock);
305 return -1;
306 }
307
308 ast_mutex_unlock(&dblock);
309
310 return 0;
311 }
312
313 static int db_init(void)
314 {
315 if (astdb) {
316 return 0;
317 }
318
319 if (db_open() || db_create_astdb() || init_statements()) {
320 return -1;
321 }
322
323 return 0;
324 }
325
326 /* We purposely don't lock around the sqlite3 call because the transaction
327 * calls will be called with the database lock held. For any other use, make
328 * sure to take the dblock yourself. */
329 static int db_execute_sql(const char *sql, int (*callback)(void *, int, char **, char **), void *arg)
330 {
331 char *errmsg = NULL;
332 int res =0;
333
334 if (sqlite3_exec(astdb, sql, callback, arg, &errmsg) != SQLITE_OK) {
335 ast_log(LOG_WARNING, "Error executing SQL (%s): %s\n", sql, errmsg);
336 sqlite3_free(errmsg);
337 res = -1;
338 }
339
340 return res;
341 }
342
343 static int ast_db_begin_transaction(void)
344 {
345 return db_execute_sql("BEGIN TRANSACTION", NULL, NULL);
346 }
347
348 static int ast_db_commit_transaction(void)
349 {
350 return db_execute_sql("COMMIT", NULL, NULL);
351 }
352
353 static int ast_db_rollback_transaction(void)
354 {
355 return db_execute_sql("ROLLBACK", NULL, NULL);
356 }
357
358 int ast_db_put(const char *family, const char *key, const char *value)
359 {
360 char *fullkey;
361 int fullkey_len;
362 int res = 0;
363
364 fullkey_len = ast_asprintf(&fullkey, "/%s/%s", family, key);
365 if (fullkey_len < 0) {
366 ast_log(LOG_WARNING, "Unable to allocate memory for family/key '/%s/%s'\n",
367 family, key);
368 return -1;
369 }
370
371 ast_mutex_lock(&dblock);
372 if (sqlite3_bind_text(put_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
373 ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
374 res = -1;
375 } else if (sqlite3_bind_text(put_stmt, 2, value, -1, SQLITE_STATIC) != SQLITE_OK) {
376 ast_log(LOG_WARNING, "Couldn't bind value to stmt: %s\n", sqlite3_errmsg(astdb));
377 res = -1;
378 } else if (sqlite3_step(put_stmt) != SQLITE_DONE) {
379 ast_log(LOG_WARNING, "Couldn't execute statement: %s\n", sqlite3_errmsg(astdb));
380 res = -1;
381 }
382 sqlite3_reset(put_stmt);
383 db_sync();
384 ast_mutex_unlock(&dblock);
385 ast_free(fullkey);
386
387 return res;
388 }
389
390 /*!
391 * \internal
392 * \brief Get key value specified by family/key.
393 *
394 * Gets the value associated with the specified \a family and \a key, and
395 * stores it, either into the fixed sized buffer specified by \a buffer
396 * and \a bufferlen, or as a heap allocated string if \a bufferlen is -1.
397 *
398 * \note If \a bufferlen is -1, \a buffer points to heap allocated memory
399 * and must be freed by calling ast_free().
400 *
401 * \retval -1 An error occurred
402 * \retval 0 Success
403 */
404 static int db_get_common(const char *family, const char *key, char **buffer, int bufferlen)
405 {
406 const unsigned char *result;
407 char *fullkey;
408 int fullkey_len;
409 int res = 0;
410
411 fullkey_len = ast_asprintf(&fullkey, "/%s/%s", family, key);
412 if (fullkey_len < 0) {
413 ast_log(LOG_WARNING, "Unable to allocate memory for family/key '/%s/%s'\n",
414 family, key);
415 return -1;
416 }
417
418 ast_mutex_lock(&dblock);
419 if (sqlite3_bind_text(get_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
420 ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
421 res = -1;
422 } else if (sqlite3_step(get_stmt) != SQLITE_ROW) {
423 ast_debug(1, "Unable to find key '%s' in family '%s'\n", key, family);
424 res = -1;
425 } else if (!(result = sqlite3_column_text(get_stmt, 0))) {
426 ast_log(LOG_WARNING, "Couldn't get value\n");
427 res = -1;
428 } else {
429 const char *value = (const char *) result;
430
431 if (bufferlen == -1) {
432 *buffer = ast_strdup(value);
433 } else {
434 ast_copy_string(*buffer, value, bufferlen);
435 }
436 }
437 sqlite3_reset(get_stmt);
438 ast_mutex_unlock(&dblock);
439 ast_free(fullkey);
440
441 return res;
442 }
443
444 int ast_db_get(const char *family, const char *key, char *value, int valuelen)
445 {
446 ast_assert(value != NULL);
447
448 /* Make sure we initialize */
449 value[0] = 0;
450
451 return db_get_common(family, key, &value, valuelen);
452 }
453
454 int ast_db_get_allocated(const char *family, const char *key, char **out)
455 {
456 *out = NULL;
457
458 return db_get_common(family, key, out, -1);
459 }
460
461 int ast_db_exists(const char *family, const char *key)
462 {
463 int result;
464 char *fullkey;
465 int fullkey_len;
466 int res = 0;
467
468 fullkey_len = ast_asprintf(&fullkey, "/%s/%s", family, key);
469 if (fullkey_len < 0) {
470 ast_log(LOG_WARNING, "Unable to allocate memory for family/key '/%s/%s'\n",
471 family, key);
472 return -1;
473 }
474
475 ast_mutex_lock(&dblock);
476 res = sqlite3_bind_text(exists_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC);
477 if (res != SQLITE_OK) {
478 ast_log(LOG_WARNING, "Couldn't bind key to stmt: %d:%s\n", res, sqlite3_errmsg(astdb));
479 res = 0;
480 } else if (sqlite3_step(exists_stmt) != SQLITE_ROW) {
481 res = 0;
482 } else if (!(result = sqlite3_column_int(exists_stmt, 0))) {
483 res = 0;
484 } else {
485 res = result;
486 }
487 sqlite3_reset(exists_stmt);
488 ast_mutex_unlock(&dblock);
489 ast_free(fullkey);
490
491 return res;
492 }
493
494
495 int ast_db_del(const char *family, const char *key)
496 {
497 char *fullkey;
498 int fullkey_len;
499 int res = 0;
500
501 fullkey_len = ast_asprintf(&fullkey, "/%s/%s", family, key);
502 if (fullkey_len < 0) {
503 ast_log(LOG_WARNING, "Unable to allocate memory for family/key '/%s/%s'\n",
504 family, key);
505 return -1;
506 }
507
508 ast_mutex_lock(&dblock);
509 if (sqlite3_bind_text(del_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
510 ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
511 res = -1;
512 } else if (sqlite3_step(del_stmt) != SQLITE_DONE) {
513 ast_debug(1, "Unable to find key '%s' in family '%s'\n", key, family);
514 res = -1;
515 }
516 sqlite3_reset(del_stmt);
517 db_sync();
518 ast_mutex_unlock(&dblock);
519 ast_free(fullkey);
520
521 return res;
522 }
523
524 int ast_db_del2(const char *family, const char *key)
525 {
526 char *fullkey;
527 char tmp[1];
528 int fullkey_len;
529 int mres, res = 0;
530
531 fullkey_len = ast_asprintf(&fullkey, "/%s/%s", family, key);
532 if (fullkey_len < 0) {
533 ast_log(LOG_WARNING, "Unable to allocate memory for family/key '/%s/%s'\n",
534 family, key);
535 return -1;
536 }
537
538 ast_mutex_lock(&dblock);
539 if (ast_db_get(family, key, tmp, sizeof(tmp))) {
540 ast_log(LOG_WARNING, "AstDB key %s does not exist\n", fullkey);
541 res = -1;
542 } else if (sqlite3_bind_text(del_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
543 ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
544 res = -1;
545 } else if ((mres = sqlite3_step(del_stmt) != SQLITE_DONE)) {
546 ast_log(LOG_WARNING, "AstDB error (%s): %s\n", fullkey, sqlite3_errstr(mres));
547 res = -1;
548 }
549 sqlite3_reset(del_stmt);
550 db_sync();
551 ast_mutex_unlock(&dblock);
552 ast_free(fullkey);
553
554 return res;
555 }
556
557 static char *create_prefix(const char *family, const char *keytree,
558 int *prefix_len)
559 {
560 char *prefix = NULL;
561 *prefix_len = 0;
562
563 if (!ast_strlen_zero(family)) {
564 if (!ast_strlen_zero(keytree)) {
565 /* Family and key tree */
566 *prefix_len = ast_asprintf(&prefix, "/%s/%s", family, keytree);
567 } else {
568 /* Family only */
569 *prefix_len = ast_asprintf(&prefix, "/%s", family);
570 }
571 if (*prefix_len < 0) {
572 ast_log(LOG_WARNING, "Unable to allocate memory for family/keytree '/%s%s%s'\n",
573 S_OR(family, ""), S_COR(keytree, "/", ""), S_OR(keytree, ""));
574 return NULL;
575 }
576 } else {
577 prefix = ast_strdup("");
578 }
579 return prefix;
580 }
581
582 int ast_db_deltree(const char *family, const char *keytree)
583 {
584 sqlite3_stmt *stmt = deltree_stmt;
585 char *prefix = NULL;
586 int prefix_len = 0;
587 int res = 0;
588
589 if (ast_strlen_zero(family) && !ast_strlen_zero(keytree)) {
590 ast_log(LOG_WARNING, "Key tree '%s' specified without family\n", keytree);
591 return -1;
592 }
593
594 prefix = create_prefix(family, keytree, &prefix_len);
595 if (!prefix) {
596 return -1;
597 }
598 if (prefix_len == 0) {
599 stmt = deltree_all_stmt;
600 }
601
602 ast_mutex_lock(&dblock);
603 if (prefix_len && (sqlite3_bind_text(stmt, 1, prefix, prefix_len, SQLITE_STATIC) != SQLITE_OK)) {
604 ast_log(LOG_WARNING, "Couldn't bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
605 res = -1;
606 } else if (sqlite3_step(stmt) != SQLITE_DONE) {
607 ast_log(LOG_WARNING, "Couldn't execute stmt: %s\n", sqlite3_errmsg(astdb));
608 res = -1;
609 }
610 res = sqlite3_changes(astdb);
611 sqlite3_reset(stmt);
612 db_sync();
613 ast_mutex_unlock(&dblock);
614 ast_free(prefix);
615
616 return res;
617 }
618
619 static struct ast_db_entry *db_gettree_common(sqlite3_stmt *stmt)
620 {
621 struct ast_db_entry *head = NULL, *prev = NULL, *cur;
622
623 while (sqlite3_step(stmt) == SQLITE_ROW) {
624 const char *key, *value;
625 size_t key_len, value_len;
626
627 key = (const char *) sqlite3_column_text(stmt, 0);
628 value = (const char *) sqlite3_column_text(stmt, 1);
629
630 if (!key || !value) {
631 break;
632 }
633
634 key_len = strlen(key);
635 value_len = strlen(value);
636
637 cur = ast_malloc(sizeof(*cur) + key_len + value_len + 2);
638 if (!cur) {
639 break;
640 }
641
642 cur->next = NULL;
643 cur->key = cur->data + value_len + 1;
644 memcpy(cur->data, value, value_len + 1);
645 memcpy(cur->key, key, key_len + 1);
646
647 if (prev) {
648 prev->next = cur;
649 } else {
650 head = cur;
651 }
652 prev = cur;
653 }
654
655 return head;
656 }
657
658 struct ast_db_entry *ast_db_gettree(const char *family, const char *keytree)
659 {
660 char *prefix = NULL;
661 int prefix_len = 0;
662 sqlite3_stmt *stmt = gettree_stmt;
663 struct ast_db_entry *ret;
664
665 prefix = create_prefix(family, keytree, &prefix_len);
666 if (!prefix) {
667 return NULL;
668 }
669 if (prefix_len == 0) {
670 stmt = gettree_all_stmt;
671 }
672
673 ast_mutex_lock(&dblock);
674 if (prefix_len && (sqlite3_bind_text(stmt, 1, prefix, prefix_len, SQLITE_STATIC) != SQLITE_OK)) {
675 ast_log(LOG_WARNING, "Could not bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
676 sqlite3_reset(stmt);
677 ast_mutex_unlock(&dblock);
678 ast_free(prefix);
679 return NULL;
680 }
681
682 ret = db_gettree_common(stmt);
683 sqlite3_reset(stmt);
684 ast_mutex_unlock(&dblock);
685 ast_free(prefix);
686
687 return ret;
688 }
689
690 struct ast_db_entry *ast_db_gettree_by_prefix(const char *family, const char *key_prefix)
691 {
692 char *prefix = NULL;
693 int prefix_len = 0;
694 struct ast_db_entry *ret;
695
696 prefix = create_prefix(family, key_prefix, &prefix_len);
697 if (!prefix) {
698 return NULL;
699 }
700
701 ast_mutex_lock(&dblock);
702 if (sqlite3_bind_text(gettree_prefix_stmt, 1, prefix, prefix_len, SQLITE_STATIC) != SQLITE_OK) {
703 ast_log(LOG_WARNING, "Could not bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
704 sqlite3_reset(gettree_prefix_stmt);
705 ast_mutex_unlock(&dblock);
706 ast_free(prefix);
707 return NULL;
708 }
709
710 ret = db_gettree_common(gettree_prefix_stmt);
711 sqlite3_reset(gettree_prefix_stmt);
712 ast_mutex_unlock(&dblock);
713 ast_free(prefix);
714
715 return ret;
716 }
717
718 void ast_db_freetree(struct ast_db_entry *dbe)
719 {
720 struct ast_db_entry *last;
721 while (dbe) {
722 last = dbe;
723 dbe = dbe->next;
724 ast_free(last);
725 }
726 }
727
728 static char *handle_cli_database_put(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
729 {
730 int res;
731
732 switch (cmd) {
733 case CLI_INIT:
734 e->command = "database put";
735 e->usage =
736 "Usage: database put <family> <key> <value>\n"
737 " Adds or updates an entry in the Asterisk database for\n"
738 " a given family, key, and value.\n";
739 return NULL;
740 case CLI_GENERATE:
741 return NULL;
742 }
743
744 if (a->argc != 5)
745 return CLI_SHOWUSAGE;
746 res = ast_db_put(a->argv[2], a->argv[3], a->argv[4]);
747 if (res) {
748 ast_cli(a->fd, "Failed to update entry\n");
749 } else {
750 ast_cli(a->fd, "Updated database successfully\n");
751 }
752 return CLI_SUCCESS;
753 }
754
755 static char *handle_cli_database_get(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
756 {
757 int res;
758 char *tmp = NULL;
759
760 switch (cmd) {
761 case CLI_INIT:
762 e->command = "database get";
763 e->usage =
764 "Usage: database get <family> <key>\n"
765 " Retrieves an entry in the Asterisk database for a given\n"
766 " family and key.\n";
767 return NULL;
768 case CLI_GENERATE:
769 return NULL;
770 }
771
772 if (a->argc != 4)
773 return CLI_SHOWUSAGE;
774 res = ast_db_get_allocated(a->argv[2], a->argv[3], &tmp);
775 if (res) {
776 ast_cli(a->fd, "Database entry not found.\n");
777 } else {
778 ast_cli(a->fd, "Value: %s\n", tmp);
779 ast_free(tmp);
780 }
781
782 return CLI_SUCCESS;
783 }
784
785 static char *handle_cli_database_del(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
786 {
787 int res;
788
789 switch (cmd) {
790 case CLI_INIT:
791 e->command = "database del";
792 e->usage =
793 "Usage: database del <family> <key>\n"
794 " Deletes an entry in the Asterisk database for a given\n"
795 " family and key.\n";
796 return NULL;
797 case CLI_GENERATE:
798 return NULL;
799 }
800
801 if (a->argc != 4)
802 return CLI_SHOWUSAGE;
803 res = ast_db_del2(a->argv[2], a->argv[3]);
804 if (res) {
805 ast_cli(a->fd, "Database entry could not be removed.\n");
806 } else {
807 ast_cli(a->fd, "Database entry removed.\n");
808 }
809 return CLI_SUCCESS;
810 }
811
812 static char *handle_cli_database_deltree(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
813 {
814 int num_deleted;
815
816 switch (cmd) {
817 case CLI_INIT:
818 e->command = "database deltree";
819 e->usage =
820 "Usage: database deltree <family> [keytree]\n"
821 " OR: database deltree <family>[/keytree]\n"
822 " Deletes a family or specific keytree within a family\n"
823 " in the Asterisk database. The two arguments may be\n"
824 " separated by either a space or a slash.\n";
825 return NULL;
826 case CLI_GENERATE:
827 return NULL;
828 }
829
830 if ((a->argc < 3) || (a->argc > 4))
831 return CLI_SHOWUSAGE;
832 if (a->argc == 4) {
833 num_deleted = ast_db_deltree(a->argv[2], a->argv[3]);
834 } else {
835 num_deleted = ast_db_deltree(a->argv[2], NULL);
836 }
837 if (num_deleted < 0) {
838 ast_cli(a->fd, "Database unavailable.\n");
839 } else if (num_deleted == 0) {
840 ast_cli(a->fd, "Database entries do not exist.\n");
841 } else {
842 ast_cli(a->fd, "%d database entries removed.\n",num_deleted);
843 }
844 return CLI_SUCCESS;
845 }
846
847 static char *handle_cli_database_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
848 {
849 char *prefix = NULL;
850 int prefix_len = 0;
851 const char *family = a->argc > 2 ? a->argv[2] : "";
852 const char *keytree = a->argc > 3 ? a->argv[3] : "";
853 int counter = 0;
854 sqlite3_stmt *stmt = gettree_stmt;
855
856 switch (cmd) {
857 case CLI_INIT:
858 e->command = "database show";
859 e->usage =
860 "Usage: database show [family [keytree]]\n"
861 " OR: database show [family[/keytree]]\n"
862 " Shows Asterisk database contents, optionally restricted\n"
863 " to a given family, or family and keytree. The two arguments\n"
864 " may be separated either by a space or by a slash.\n";
865 return NULL;
866 case CLI_GENERATE:
867 return NULL;
868 }
869
870 if (a->argc > 4) {
871 return CLI_SHOWUSAGE;
872 }
873
874 prefix = create_prefix(family, keytree, &prefix_len);
875 if (!prefix) {
876 return NULL;
877 }
878 if (prefix_len == 0) {
879 stmt = gettree_all_stmt;
880 }
881
882 ast_mutex_lock(&dblock);
883 if (prefix_len && (sqlite3_bind_text(stmt, 1, prefix, prefix_len, SQLITE_STATIC) != SQLITE_OK)) {
884 ast_log(LOG_WARNING, "Couldn't bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
885 sqlite3_reset(stmt);
886 ast_mutex_unlock(&dblock);
887 ast_free(prefix);
888 return NULL;
889 }
890
891 while (sqlite3_step(stmt) == SQLITE_ROW) {
892 const char *key_s, *value_s;
893 if (!(key_s = (const char *) sqlite3_column_text(stmt, 0))) {
894 ast_log(LOG_WARNING, "Skipping invalid key!\n");
895 continue;
896 }
897 if (!(value_s = (const char *) sqlite3_column_text(stmt, 1))) {
898 ast_log(LOG_WARNING, "Skipping invalid value!\n");
899 continue;
900 }
901 ++counter;
902 ast_cli(a->fd, "%-50s: %-25s\n", key_s, value_s);
903 }
904
905 sqlite3_reset(stmt);
906 ast_mutex_unlock(&dblock);
907 ast_free(prefix);
908
909 ast_cli(a->fd, "%d results found.\n", counter);
910 return CLI_SUCCESS;
911 }
912
913 static char *handle_cli_database_showkey(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
914 {
915 int counter = 0;
916
917 switch (cmd) {
918 case CLI_INIT:
919 e->command = "database showkey";
920 e->usage =
921 "Usage: database showkey <keytree>\n"
922 " Shows Asterisk database contents, restricted to a given key.\n";
923 return NULL;
924 case CLI_GENERATE:
925 return NULL;
926 }
927
928 if (a->argc != 3) {
929 return CLI_SHOWUSAGE;
930 }
931
932 ast_mutex_lock(&dblock);
933 if (!ast_strlen_zero(a->argv[2]) && (sqlite3_bind_text(showkey_stmt, 1, a->argv[2], -1, SQLITE_STATIC) != SQLITE_OK)) {
934 ast_log(LOG_WARNING, "Couldn't bind %s to stmt: %s\n", a->argv[2], sqlite3_errmsg(astdb));
935 sqlite3_reset(showkey_stmt);
936 ast_mutex_unlock(&dblock);
937 return NULL;
938 }
939
940 while (sqlite3_step(showkey_stmt) == SQLITE_ROW) {
941 const char *key_s, *value_s;
942 if (!(key_s = (const char *) sqlite3_column_text(showkey_stmt, 0))) {
943 break;
944 }
945 if (!(value_s = (const char *) sqlite3_column_text(showkey_stmt, 1))) {
946 break;
947 }
948 ++counter;
949 ast_cli(a->fd, "%-50s: %-25s\n", key_s, value_s);
950 }
951 sqlite3_reset(showkey_stmt);
952 ast_mutex_unlock(&dblock);
953
954 ast_cli(a->fd, "%d results found.\n", counter);
955 return CLI_SUCCESS;
956 }
957
958 static int display_results(void *arg, int columns, char **values, char **colnames)
959 {
960 struct ast_cli_args *a = arg;
961 size_t x;
962
963 for (x = 0; x < columns; x++) {
964 ast_cli(a->fd, "%-5s: %-50s\n", colnames[x], values[x]);
965 }
966 ast_cli(a->fd, "\n");
967
968 return 0;
969 }
970
971 static char *handle_cli_database_query(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
972 {
973
974 switch (cmd) {
975 case CLI_INIT:
976 e->command = "database query";
977 e->usage =
978 "Usage: database query \"<SQL Statement>\"\n"
979 " Run a user-specified SQL query on the database. Be careful.\n";
980 return NULL;
981 case CLI_GENERATE:
982 return NULL;
983 }
984
985 if (a->argc != 3) {
986 return CLI_SHOWUSAGE;
987 }
988
989 ast_mutex_lock(&dblock);
990 db_execute_sql(a->argv[2], display_results, a);
991 db_sync(); /* Go ahead and sync the db in case they write */
992 ast_mutex_unlock(&dblock);
993
994 return CLI_SUCCESS;
995 }
996
997 static struct ast_cli_entry cli_database[] = {
998 AST_CLI_DEFINE(handle_cli_database_show, "Shows database contents"),
999 AST_CLI_DEFINE(handle_cli_database_showkey, "Shows database contents"),
1000 AST_CLI_DEFINE(handle_cli_database_get, "Gets database value"),
1001 AST_CLI_DEFINE(handle_cli_database_put, "Adds/updates database value"),
1002 AST_CLI_DEFINE(handle_cli_database_del, "Removes database key/value"),
1003 AST_CLI_DEFINE(handle_cli_database_deltree, "Removes database keytree/values"),
1004 AST_CLI_DEFINE(handle_cli_database_query, "Run a user-specified query on the astdb"),
1005 };
1006
1007 static int manager_dbput(struct mansession *s, const struct message *m)
1008 {
1009 const char *family = astman_get_header(m, "Family");
1010 const char *key = astman_get_header(m, "Key");
1011 const char *val = astman_get_header(m, "Val");
1012 int res;
1013
1014 if (ast_strlen_zero(family)) {
1015 astman_send_error(s, m, "No family specified");
1016 return 0;
1017 }
1018 if (ast_strlen_zero(key)) {
1019 astman_send_error(s, m, "No key specified");
1020 return 0;
1021 }
1022
1023 res = ast_db_put(family, key, S_OR(val, ""));
1024 if (res) {
1025 astman_send_error(s, m, "Failed to update entry");
1026 } else {
1027 astman_send_ack(s, m, "Updated database successfully");
1028 }
1029 return 0;
1030 }
1031
1032 static int manager_dbget(struct mansession *s, const struct message *m)
1033 {
1034 const char *id = astman_get_header(m,"ActionID");
1035 char idText[256];
1036 const char *family = astman_get_header(m, "Family");
1037 const char *key = astman_get_header(m, "Key");
1038 char *tmp = NULL;
1039 int res;
1040
1041 if (ast_strlen_zero(family)) {
1042 astman_send_error(s, m, "No family specified.");
1043 return 0;
1044 }
1045 if (ast_strlen_zero(key)) {
1046 astman_send_error(s, m, "No key specified.");
1047 return 0;
1048 }
1049
1050 idText[0] = '\0';
1051 if (!ast_strlen_zero(id))
1052 snprintf(idText, sizeof(idText) ,"ActionID: %s\r\n", id);
1053
1054 res = ast_db_get_allocated(family, key, &tmp);
1055 if (res) {
1056 astman_send_error(s, m, "Database entry not found");
1057 } else {
1058 astman_send_listack(s, m, "Result will follow", "start");
1059
1060 astman_append(s, "Event: DBGetResponse\r\n"
1061 "Family: %s\r\n"
1062 "Key: %s\r\n"
1063 "Val: %s\r\n"
1064 "%s"
1065 "\r\n",
1066 family, key, tmp, idText);
1067 ast_free(tmp);
1068 astman_send_list_complete_start(s, m, "DBGetComplete", 1);
1069 astman_send_list_complete_end(s);
1070 }
1071 return 0;
1072 }
1073
1074 static int manager_db_tree_get(struct mansession *s, const struct message *m)
1075 {
1076 char *prefix;
1077 int prefix_len = 0;
1078 char idText[256];
1079 const char *id = astman_get_header(m,"ActionID");
1080 const char *family = astman_get_header(m, "Family");
1081 const char *key = astman_get_header(m, "Key");
1082 sqlite3_stmt *stmt = gettree_stmt;
1083 int count = 0;
1084
1085 prefix = create_prefix(family, key, &prefix_len);
1086 if (!prefix) {
1087 astman_send_error(s, m, "Unable to allocate memory for Family/Key");
1088 return 0;
1089 }
1090 if (prefix_len == 0) {
1091 stmt = gettree_all_stmt;
1092 }
1093
1094 idText[0] = '\0';
1095 if (!ast_strlen_zero(id)) {
1096 snprintf(idText, sizeof(idText) ,"ActionID: %s\r\n", id);
1097 }
1098
1099 ast_mutex_lock(&dblock);
1100 if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, prefix_len, SQLITE_STATIC) != SQLITE_OK)) {
1101 ast_log(LOG_WARNING, "Couldn't bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
1102 sqlite3_reset(stmt);
1103 ast_mutex_unlock(&dblock);
1104 ast_free(prefix);
1105 astman_send_error(s, m, "Unable to search database");
1106 return 0;
1107 }
1108
1109 astman_send_listack(s, m, "Result will follow", "start");
1110
1111 while (sqlite3_step(stmt) == SQLITE_ROW) {
1112 const char *key_s, *value_s;
1113 if (!(key_s = (const char *) sqlite3_column_text(stmt, 0))) {
1114 ast_log(LOG_WARNING, "Skipping invalid key!\n");
1115 continue;
1116 }
1117 if (!(value_s = (const char *) sqlite3_column_text(stmt, 1))) {
1118 ast_log(LOG_WARNING, "Skipping invalid value!\n");
1119 continue;
1120 }
1121 astman_append(s, "Event: DBGetTreeResponse\r\n"
1122 "Key: %s\r\n"
1123 "Val: %s\r\n"
1124 "%s"
1125 "\r\n",
1126 key_s, value_s, idText);
1127 count++;
1128 }
1129
1130 sqlite3_reset(stmt);
1131 ast_mutex_unlock(&dblock);
1132 ast_free(prefix);
1133
1134 astman_send_list_complete_start(s, m, "DBGetTreeComplete", count);
1135 astman_send_list_complete_end(s);
1136
1137 return 0;
1138 }
1139
1140 static int manager_dbdel(struct mansession *s, const struct message *m)
1141 {
1142 const char *family = astman_get_header(m, "Family");
1143 const char *key = astman_get_header(m, "Key");
1144 int res;
1145
1146 if (ast_strlen_zero(family)) {
1147 astman_send_error(s, m, "No family specified.");
1148 return 0;
1149 }
1150
1151 if (ast_strlen_zero(key)) {
1152 astman_send_error(s, m, "No key specified.");
1153 return 0;
1154 }
1155
1156 res = ast_db_del2(family, key);
1157 if (res)
1158 astman_send_error(s, m, "Database entry could not be deleted");
1159 else
1160 astman_send_ack(s, m, "Key deleted successfully");
1161
1162 return 0;
1163 }
1164
1165 static int manager_dbdeltree(struct mansession *s, const struct message *m)
1166 {
1167 const char *family = astman_get_header(m, "Family");
1168 const char *key = astman_get_header(m, "Key");
1169 int num_deleted;
1170
1171 if (ast_strlen_zero(family)) {
1172 astman_send_error(s, m, "No family specified.");
1173 return 0;
1174 }
1175
1176 if (!ast_strlen_zero(key)) {
1177 num_deleted = ast_db_deltree(family, key);
1178 } else {
1179 num_deleted = ast_db_deltree(family, NULL);
1180 }
1181
1182 if (num_deleted < 0) {
1183 astman_send_error(s, m, "Database unavailable");
1184 } else if (num_deleted == 0) {
1185 astman_send_error(s, m, "Database entry not found");
1186 } else {
1187 astman_send_ack(s, m, "Key tree deleted successfully");
1188 }
1189
1190 return 0;
1191 }
1192
1193 /*!
1194 * \internal
1195 * \brief Signal the astdb sync thread to do its thing.
1196 *
1197 * \note dblock is assumed to be held when calling this function.
1198 */
1199 static void db_sync(void)
1200 {
1201 dosync = 1;
1202 ast_cond_signal(&dbcond);
1203 }
1204
1205 /*!
1206 * \internal
1207 * \brief astdb sync thread
1208 *
1209 * This thread is in charge of syncing astdb to disk after a change.
1210 * By pushing it off to this thread to take care of, this I/O bound operation
1211 * will not block other threads from performing other critical processing.
1212 * If changes happen rapidly, this thread will also ensure that the sync
1213 * operations are rate limited.
1214 */
1215 static void *db_sync_thread(void *data)
1216 {
1217 ast_mutex_lock(&dblock);
1218 ast_db_begin_transaction();
1219 for (;;) {
1220 /* If dosync is set, db_sync() was called during sleep(1),
1221 * and the pending transaction should be committed.
1222 * Otherwise, block until db_sync() is called.
1223 */
1224 while (!dosync) {
1225 ast_cond_wait(&dbcond, &dblock);
1226 }
1227 dosync = 0;
1228 if (ast_db_commit_transaction()) {
1229 ast_db_rollback_transaction();
1230 }
1231 if (doexit) {
1232 ast_mutex_unlock(&dblock);
1233 break;
1234 }
1235 ast_db_begin_transaction();
1236 ast_mutex_unlock(&dblock);
1237 sleep(1);
1238 ast_mutex_lock(&dblock);
1239 }
1240
1241 return NULL;
1242 }
1243
1244 /*!
1245 * \internal
1246 * \brief Clean up resources on Asterisk shutdown
1247 */
1248 static void astdb_atexit(void)
1249 {
1250 ast_cli_unregister_multiple(cli_database, ARRAY_LEN(cli_database));
1251 ast_manager_unregister("DBGet");
1252 ast_manager_unregister("DBGetTree");
1253 ast_manager_unregister("DBPut");
1254 ast_manager_unregister("DBDel");
1255 ast_manager_unregister("DBDelTree");
1256
1257 /* Set doexit to 1 to kill thread. db_sync must be called with
1258 * mutex held. */
1259 ast_mutex_lock(&dblock);
1260 doexit = 1;
1261 db_sync();
1262 ast_mutex_unlock(&dblock);
1263
1264 pthread_join(syncthread, NULL);
1265 ast_mutex_lock(&dblock);
1266 clean_statements();
1267 if (sqlite3_close(astdb) == SQLITE_OK) {
1268 astdb = NULL;
1269 }
1270 ast_mutex_unlock(&dblock);
1271 }
1272
1273 int astdb_init(void)
1274 {
1275 ast_cond_init(&dbcond, NULL);
1276
1277 if (db_init()) {
1278 return -1;
1279 }
1280
1281 if (ast_pthread_create_background(&syncthread, NULL, db_sync_thread, NULL)) {
1282 return -1;
1283 }
1284
1285 ast_register_atexit(astdb_atexit);
1286 ast_cli_register_multiple(cli_database, ARRAY_LEN(cli_database));
1287 ast_manager_register_xml_core("DBGet", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_dbget);
1288 ast_manager_register_xml_core("DBGetTree", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_db_tree_get);
1289 ast_manager_register_xml_core("DBPut", EVENT_FLAG_SYSTEM, manager_dbput);
1290 ast_manager_register_xml_core("DBDel", EVENT_FLAG_SYSTEM, manager_dbdel);
1291 ast_manager_register_xml_core("DBDelTree", EVENT_FLAG_SYSTEM, manager_dbdeltree);
1292 return 0;
1293 }