db.c 30 KB

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