db.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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. static int init_stmt(sqlite3_stmt **stmt, const char *sql, size_t len)
  121. {
  122. ast_mutex_lock(&dblock);
  123. if (sqlite3_prepare(astdb, sql, len, stmt, NULL) != SQLITE_OK) {
  124. ast_log(LOG_WARNING, "Couldn't prepare statement '%s': %s\n", sql, sqlite3_errmsg(astdb));
  125. ast_mutex_unlock(&dblock);
  126. return -1;
  127. }
  128. ast_mutex_unlock(&dblock);
  129. return 0;
  130. }
  131. /*! \internal
  132. * \brief Clean up the prepared SQLite3 statement
  133. * \note dblock should already be locked prior to calling this method
  134. */
  135. static int clean_stmt(sqlite3_stmt **stmt, const char *sql)
  136. {
  137. if (sqlite3_finalize(*stmt) != SQLITE_OK) {
  138. ast_log(LOG_WARNING, "Couldn't finalize statement '%s': %s\n", sql, sqlite3_errmsg(astdb));
  139. *stmt = NULL;
  140. return -1;
  141. }
  142. *stmt = NULL;
  143. return 0;
  144. }
  145. /*! \internal
  146. * \brief Clean up all prepared SQLite3 statements
  147. * \note dblock should already be locked prior to calling this method
  148. */
  149. static void clean_statements(void)
  150. {
  151. clean_stmt(&get_stmt, get_stmt_sql);
  152. clean_stmt(&del_stmt, del_stmt_sql);
  153. clean_stmt(&deltree_stmt, deltree_stmt_sql);
  154. clean_stmt(&deltree_all_stmt, deltree_all_stmt_sql);
  155. clean_stmt(&gettree_stmt, gettree_stmt_sql);
  156. clean_stmt(&gettree_all_stmt, gettree_all_stmt_sql);
  157. clean_stmt(&showkey_stmt, showkey_stmt_sql);
  158. clean_stmt(&put_stmt, put_stmt_sql);
  159. clean_stmt(&create_astdb_stmt, create_astdb_stmt_sql);
  160. }
  161. static int init_statements(void)
  162. {
  163. /* Don't initialize create_astdb_statment here as the astdb table needs to exist
  164. * brefore these statments can be initialized */
  165. return init_stmt(&get_stmt, get_stmt_sql, sizeof(get_stmt_sql))
  166. || init_stmt(&del_stmt, del_stmt_sql, sizeof(del_stmt_sql))
  167. || init_stmt(&deltree_stmt, deltree_stmt_sql, sizeof(deltree_stmt_sql))
  168. || init_stmt(&deltree_all_stmt, deltree_all_stmt_sql, sizeof(deltree_all_stmt_sql))
  169. || init_stmt(&gettree_stmt, gettree_stmt_sql, sizeof(gettree_stmt_sql))
  170. || init_stmt(&gettree_all_stmt, gettree_all_stmt_sql, sizeof(gettree_all_stmt_sql))
  171. || init_stmt(&showkey_stmt, showkey_stmt_sql, sizeof(showkey_stmt_sql))
  172. || init_stmt(&put_stmt, put_stmt_sql, sizeof(put_stmt_sql));
  173. }
  174. static int convert_bdb_to_sqlite3(void)
  175. {
  176. char *cmd;
  177. int res;
  178. ast_asprintf(&cmd, "%s/astdb2sqlite3 '%s'\n", ast_config_AST_SBIN_DIR, ast_config_AST_DB);
  179. res = ast_safe_system(cmd);
  180. ast_free(cmd);
  181. return res;
  182. }
  183. static int db_create_astdb(void)
  184. {
  185. int res = 0;
  186. if (!create_astdb_stmt) {
  187. init_stmt(&create_astdb_stmt, create_astdb_stmt_sql, sizeof(create_astdb_stmt_sql));
  188. }
  189. ast_mutex_lock(&dblock);
  190. if (sqlite3_step(create_astdb_stmt) != SQLITE_DONE) {
  191. ast_log(LOG_WARNING, "Couldn't create astdb table: %s\n", sqlite3_errmsg(astdb));
  192. res = -1;
  193. }
  194. sqlite3_reset(create_astdb_stmt);
  195. db_sync();
  196. ast_mutex_unlock(&dblock);
  197. return res;
  198. }
  199. static int db_open(void)
  200. {
  201. char *dbname;
  202. struct stat dont_care;
  203. if (!(dbname = ast_alloca(strlen(ast_config_AST_DB) + sizeof(".sqlite3")))) {
  204. return -1;
  205. }
  206. strcpy(dbname, ast_config_AST_DB);
  207. strcat(dbname, ".sqlite3");
  208. if (stat(dbname, &dont_care) && !stat(ast_config_AST_DB, &dont_care)) {
  209. if (convert_bdb_to_sqlite3()) {
  210. ast_log(LOG_ERROR, "*** Database conversion failed!\n");
  211. ast_log(LOG_ERROR, "*** Asterisk now uses SQLite3 for its internal\n");
  212. ast_log(LOG_ERROR, "*** database. Conversion from the old astdb\n");
  213. ast_log(LOG_ERROR, "*** failed. Most likely the astdb2sqlite3 utility\n");
  214. ast_log(LOG_ERROR, "*** was not selected for build. To convert the\n");
  215. ast_log(LOG_ERROR, "*** old astdb, please delete '%s'\n", dbname);
  216. ast_log(LOG_ERROR, "*** and re-run 'make menuselect' and select astdb2sqlite3\n");
  217. ast_log(LOG_ERROR, "*** in the Utilities section, then 'make && make install'.\n");
  218. ast_log(LOG_ERROR, "*** It is also imperative that the user under which\n");
  219. ast_log(LOG_ERROR, "*** Asterisk runs have write permission to the directory\n");
  220. ast_log(LOG_ERROR, "*** where the database resides.\n");
  221. sleep(5);
  222. } else {
  223. ast_log(LOG_NOTICE, "Database conversion succeeded!\n");
  224. }
  225. }
  226. ast_mutex_lock(&dblock);
  227. if (sqlite3_open(dbname, &astdb) != SQLITE_OK) {
  228. ast_log(LOG_WARNING, "Unable to open Asterisk database '%s': %s\n", dbname, sqlite3_errmsg(astdb));
  229. sqlite3_close(astdb);
  230. ast_mutex_unlock(&dblock);
  231. return -1;
  232. }
  233. ast_mutex_unlock(&dblock);
  234. return 0;
  235. }
  236. static int db_init(void)
  237. {
  238. if (astdb) {
  239. return 0;
  240. }
  241. if (db_open() || db_create_astdb() || init_statements()) {
  242. return -1;
  243. }
  244. return 0;
  245. }
  246. /* We purposely don't lock around the sqlite3 call because the transaction
  247. * calls will be called with the database lock held. For any other use, make
  248. * sure to take the dblock yourself. */
  249. static int db_execute_sql(const char *sql, int (*callback)(void *, int, char **, char **), void *arg)
  250. {
  251. char *errmsg = NULL;
  252. int res =0;
  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. return res;
  260. }
  261. static int ast_db_begin_transaction(void)
  262. {
  263. return db_execute_sql("BEGIN TRANSACTION", NULL, NULL);
  264. }
  265. static int ast_db_commit_transaction(void)
  266. {
  267. return db_execute_sql("COMMIT", NULL, NULL);
  268. }
  269. static int ast_db_rollback_transaction(void)
  270. {
  271. return db_execute_sql("ROLLBACK", NULL, NULL);
  272. }
  273. int ast_db_put(const char *family, const char *key, const char *value)
  274. {
  275. char fullkey[MAX_DB_FIELD];
  276. size_t fullkey_len;
  277. int res = 0;
  278. if (strlen(family) + strlen(key) + 2 > sizeof(fullkey) - 1) {
  279. ast_log(LOG_WARNING, "Family and key length must be less than %zu bytes\n", sizeof(fullkey) - 3);
  280. return -1;
  281. }
  282. fullkey_len = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, key);
  283. ast_mutex_lock(&dblock);
  284. if (sqlite3_bind_text(put_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
  285. ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
  286. res = -1;
  287. } else if (sqlite3_bind_text(put_stmt, 2, value, -1, SQLITE_STATIC) != SQLITE_OK) {
  288. ast_log(LOG_WARNING, "Couldn't bind value to stmt: %s\n", sqlite3_errmsg(astdb));
  289. res = -1;
  290. } else if (sqlite3_step(put_stmt) != SQLITE_DONE) {
  291. ast_log(LOG_WARNING, "Couldn't execute statment: %s\n", sqlite3_errmsg(astdb));
  292. res = -1;
  293. }
  294. sqlite3_reset(put_stmt);
  295. db_sync();
  296. ast_mutex_unlock(&dblock);
  297. return res;
  298. }
  299. /*!
  300. * \internal
  301. * \brief Get key value specified by family/key.
  302. *
  303. * Gets the value associated with the specified \a family and \a key, and
  304. * stores it, either into the fixed sized buffer specified by \a buffer
  305. * and \a bufferlen, or as a heap allocated string if \a bufferlen is -1.
  306. *
  307. * \note If \a bufferlen is -1, \a buffer points to heap allocated memory
  308. * and must be freed by calling ast_free().
  309. *
  310. * \retval -1 An error occurred
  311. * \retval 0 Success
  312. */
  313. static int db_get_common(const char *family, const char *key, char **buffer, int bufferlen)
  314. {
  315. const unsigned char *result;
  316. char fullkey[MAX_DB_FIELD];
  317. size_t fullkey_len;
  318. int res = 0;
  319. if (strlen(family) + strlen(key) + 2 > sizeof(fullkey) - 1) {
  320. ast_log(LOG_WARNING, "Family and key length must be less than %zu bytes\n", sizeof(fullkey) - 3);
  321. return -1;
  322. }
  323. fullkey_len = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, key);
  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. const char *value = (const char *) result;
  336. if (bufferlen == -1) {
  337. *buffer = ast_strdup(value);
  338. } else {
  339. ast_copy_string(*buffer, value, bufferlen);
  340. }
  341. }
  342. sqlite3_reset(get_stmt);
  343. ast_mutex_unlock(&dblock);
  344. return res;
  345. }
  346. int ast_db_get(const char *family, const char *key, char *value, int valuelen)
  347. {
  348. ast_assert(value != NULL);
  349. /* Make sure we initialize */
  350. value[0] = 0;
  351. return db_get_common(family, key, &value, valuelen);
  352. }
  353. int ast_db_get_allocated(const char *family, const char *key, char **out)
  354. {
  355. *out = NULL;
  356. return db_get_common(family, key, out, -1);
  357. }
  358. int ast_db_del(const char *family, const char *key)
  359. {
  360. char fullkey[MAX_DB_FIELD];
  361. size_t fullkey_len;
  362. int res = 0;
  363. if (strlen(family) + strlen(key) + 2 > sizeof(fullkey) - 1) {
  364. ast_log(LOG_WARNING, "Family and key length must be less than %zu bytes\n", sizeof(fullkey) - 3);
  365. return -1;
  366. }
  367. fullkey_len = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, key);
  368. ast_mutex_lock(&dblock);
  369. if (sqlite3_bind_text(del_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
  370. ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
  371. res = -1;
  372. } else if (sqlite3_step(del_stmt) != SQLITE_DONE) {
  373. ast_debug(1, "Unable to find key '%s' in family '%s'\n", key, family);
  374. res = -1;
  375. }
  376. sqlite3_reset(del_stmt);
  377. db_sync();
  378. ast_mutex_unlock(&dblock);
  379. return res;
  380. }
  381. int ast_db_deltree(const char *family, const char *keytree)
  382. {
  383. sqlite3_stmt *stmt = deltree_stmt;
  384. char prefix[MAX_DB_FIELD];
  385. int res = 0;
  386. if (!ast_strlen_zero(family)) {
  387. if (!ast_strlen_zero(keytree)) {
  388. /* Family and key tree */
  389. snprintf(prefix, sizeof(prefix), "/%s/%s", family, keytree);
  390. } else {
  391. /* Family only */
  392. snprintf(prefix, sizeof(prefix), "/%s", family);
  393. }
  394. } else {
  395. prefix[0] = '\0';
  396. stmt = deltree_all_stmt;
  397. }
  398. ast_mutex_lock(&dblock);
  399. if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, -1, SQLITE_STATIC) != SQLITE_OK)) {
  400. ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
  401. res = -1;
  402. } else if (sqlite3_step(stmt) != SQLITE_DONE) {
  403. ast_log(LOG_WARNING, "Couldn't execute stmt: %s\n", sqlite3_errmsg(astdb));
  404. res = -1;
  405. }
  406. res = sqlite3_changes(astdb);
  407. sqlite3_reset(stmt);
  408. db_sync();
  409. ast_mutex_unlock(&dblock);
  410. return res;
  411. }
  412. struct ast_db_entry *ast_db_gettree(const char *family, const char *keytree)
  413. {
  414. char prefix[MAX_DB_FIELD];
  415. sqlite3_stmt *stmt = gettree_stmt;
  416. struct ast_db_entry *cur, *last = NULL, *ret = NULL;
  417. if (!ast_strlen_zero(family)) {
  418. if (!ast_strlen_zero(keytree)) {
  419. /* Family and key tree */
  420. snprintf(prefix, sizeof(prefix), "/%s/%s", family, keytree);
  421. } else {
  422. /* Family only */
  423. snprintf(prefix, sizeof(prefix), "/%s", family);
  424. }
  425. } else {
  426. prefix[0] = '\0';
  427. stmt = gettree_all_stmt;
  428. }
  429. ast_mutex_lock(&dblock);
  430. if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, -1, SQLITE_STATIC) != SQLITE_OK)) {
  431. ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
  432. sqlite3_reset(stmt);
  433. ast_mutex_unlock(&dblock);
  434. return NULL;
  435. }
  436. while (sqlite3_step(stmt) == SQLITE_ROW) {
  437. const char *key_s, *value_s;
  438. if (!(key_s = (const char *) sqlite3_column_text(stmt, 0))) {
  439. break;
  440. }
  441. if (!(value_s = (const char *) sqlite3_column_text(stmt, 1))) {
  442. break;
  443. }
  444. if (!(cur = ast_malloc(sizeof(*cur) + strlen(key_s) + strlen(value_s) + 2))) {
  445. break;
  446. }
  447. cur->next = NULL;
  448. cur->key = cur->data + strlen(value_s) + 1;
  449. strcpy(cur->data, value_s);
  450. strcpy(cur->key, key_s);
  451. if (last) {
  452. last->next = cur;
  453. } else {
  454. ret = cur;
  455. }
  456. last = cur;
  457. }
  458. sqlite3_reset(stmt);
  459. ast_mutex_unlock(&dblock);
  460. return ret;
  461. }
  462. void ast_db_freetree(struct ast_db_entry *dbe)
  463. {
  464. struct ast_db_entry *last;
  465. while (dbe) {
  466. last = dbe;
  467. dbe = dbe->next;
  468. ast_free(last);
  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. switch (cmd) {
  475. case CLI_INIT:
  476. e->command = "database put";
  477. e->usage =
  478. "Usage: database put <family> <key> <value>\n"
  479. " Adds or updates an entry in the Asterisk database for\n"
  480. " a given family, key, and value.\n";
  481. return NULL;
  482. case CLI_GENERATE:
  483. return NULL;
  484. }
  485. if (a->argc != 5)
  486. return CLI_SHOWUSAGE;
  487. res = ast_db_put(a->argv[2], a->argv[3], a->argv[4]);
  488. if (res) {
  489. ast_cli(a->fd, "Failed to update entry\n");
  490. } else {
  491. ast_cli(a->fd, "Updated database successfully\n");
  492. }
  493. return CLI_SUCCESS;
  494. }
  495. static char *handle_cli_database_get(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  496. {
  497. int res;
  498. char tmp[MAX_DB_FIELD];
  499. switch (cmd) {
  500. case CLI_INIT:
  501. e->command = "database get";
  502. e->usage =
  503. "Usage: database get <family> <key>\n"
  504. " Retrieves an entry in the Asterisk database for a given\n"
  505. " family and key.\n";
  506. return NULL;
  507. case CLI_GENERATE:
  508. return NULL;
  509. }
  510. if (a->argc != 4)
  511. return CLI_SHOWUSAGE;
  512. res = ast_db_get(a->argv[2], a->argv[3], tmp, sizeof(tmp));
  513. if (res) {
  514. ast_cli(a->fd, "Database entry not found.\n");
  515. } else {
  516. ast_cli(a->fd, "Value: %s\n", tmp);
  517. }
  518. return CLI_SUCCESS;
  519. }
  520. static char *handle_cli_database_del(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  521. {
  522. int res;
  523. switch (cmd) {
  524. case CLI_INIT:
  525. e->command = "database del";
  526. e->usage =
  527. "Usage: database del <family> <key>\n"
  528. " Deletes an entry in the Asterisk database for a given\n"
  529. " family and key.\n";
  530. return NULL;
  531. case CLI_GENERATE:
  532. return NULL;
  533. }
  534. if (a->argc != 4)
  535. return CLI_SHOWUSAGE;
  536. res = ast_db_del(a->argv[2], a->argv[3]);
  537. if (res) {
  538. ast_cli(a->fd, "Database entry does not exist.\n");
  539. } else {
  540. ast_cli(a->fd, "Database entry removed.\n");
  541. }
  542. return CLI_SUCCESS;
  543. }
  544. static char *handle_cli_database_deltree(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  545. {
  546. int num_deleted;
  547. switch (cmd) {
  548. case CLI_INIT:
  549. e->command = "database deltree";
  550. e->usage =
  551. "Usage: database deltree <family> [keytree]\n"
  552. " OR: database deltree <family>[/keytree]\n"
  553. " Deletes a family or specific keytree within a family\n"
  554. " in the Asterisk database. The two arguments may be\n"
  555. " separated by either a space or a slash.\n";
  556. return NULL;
  557. case CLI_GENERATE:
  558. return NULL;
  559. }
  560. if ((a->argc < 3) || (a->argc > 4))
  561. return CLI_SHOWUSAGE;
  562. if (a->argc == 4) {
  563. num_deleted = ast_db_deltree(a->argv[2], a->argv[3]);
  564. } else {
  565. num_deleted = ast_db_deltree(a->argv[2], NULL);
  566. }
  567. if (num_deleted < 0) {
  568. ast_cli(a->fd, "Database unavailable.\n");
  569. } else if (num_deleted == 0) {
  570. ast_cli(a->fd, "Database entries do not exist.\n");
  571. } else {
  572. ast_cli(a->fd, "%d database entries removed.\n",num_deleted);
  573. }
  574. return CLI_SUCCESS;
  575. }
  576. static char *handle_cli_database_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  577. {
  578. char prefix[MAX_DB_FIELD];
  579. int counter = 0;
  580. sqlite3_stmt *stmt = gettree_stmt;
  581. switch (cmd) {
  582. case CLI_INIT:
  583. e->command = "database show";
  584. e->usage =
  585. "Usage: database show [family [keytree]]\n"
  586. " OR: database show [family[/keytree]]\n"
  587. " Shows Asterisk database contents, optionally restricted\n"
  588. " to a given family, or family and keytree. The two arguments\n"
  589. " may be separated either by a space or by a slash.\n";
  590. return NULL;
  591. case CLI_GENERATE:
  592. return NULL;
  593. }
  594. if (a->argc == 4) {
  595. /* Family and key tree */
  596. snprintf(prefix, sizeof(prefix), "/%s/%s", a->argv[2], a->argv[3]);
  597. } else if (a->argc == 3) {
  598. /* Family only */
  599. snprintf(prefix, sizeof(prefix), "/%s", a->argv[2]);
  600. } else if (a->argc == 2) {
  601. /* Neither */
  602. prefix[0] = '\0';
  603. stmt = gettree_all_stmt;
  604. } else {
  605. return CLI_SHOWUSAGE;
  606. }
  607. ast_mutex_lock(&dblock);
  608. if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, -1, SQLITE_STATIC) != SQLITE_OK)) {
  609. ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
  610. sqlite3_reset(stmt);
  611. ast_mutex_unlock(&dblock);
  612. return NULL;
  613. }
  614. while (sqlite3_step(stmt) == SQLITE_ROW) {
  615. const char *key_s, *value_s;
  616. if (!(key_s = (const char *) sqlite3_column_text(stmt, 0))) {
  617. ast_log(LOG_WARNING, "Skipping invalid key!\n");
  618. continue;
  619. }
  620. if (!(value_s = (const char *) sqlite3_column_text(stmt, 1))) {
  621. ast_log(LOG_WARNING, "Skipping invalid value!\n");
  622. continue;
  623. }
  624. ++counter;
  625. ast_cli(a->fd, "%-50s: %-25s\n", key_s, value_s);
  626. }
  627. sqlite3_reset(stmt);
  628. ast_mutex_unlock(&dblock);
  629. ast_cli(a->fd, "%d results found.\n", counter);
  630. return CLI_SUCCESS;
  631. }
  632. static char *handle_cli_database_showkey(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  633. {
  634. int counter = 0;
  635. switch (cmd) {
  636. case CLI_INIT:
  637. e->command = "database showkey";
  638. e->usage =
  639. "Usage: database showkey <keytree>\n"
  640. " Shows Asterisk database contents, restricted to a given key.\n";
  641. return NULL;
  642. case CLI_GENERATE:
  643. return NULL;
  644. }
  645. if (a->argc != 3) {
  646. return CLI_SHOWUSAGE;
  647. }
  648. ast_mutex_lock(&dblock);
  649. if (!ast_strlen_zero(a->argv[2]) && (sqlite3_bind_text(showkey_stmt, 1, a->argv[2], -1, SQLITE_STATIC) != SQLITE_OK)) {
  650. ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", a->argv[2], sqlite3_errmsg(astdb));
  651. sqlite3_reset(showkey_stmt);
  652. ast_mutex_unlock(&dblock);
  653. return NULL;
  654. }
  655. while (sqlite3_step(showkey_stmt) == SQLITE_ROW) {
  656. const char *key_s, *value_s;
  657. if (!(key_s = (const char *) sqlite3_column_text(showkey_stmt, 0))) {
  658. break;
  659. }
  660. if (!(value_s = (const char *) sqlite3_column_text(showkey_stmt, 1))) {
  661. break;
  662. }
  663. ++counter;
  664. ast_cli(a->fd, "%-50s: %-25s\n", key_s, value_s);
  665. }
  666. sqlite3_reset(showkey_stmt);
  667. ast_mutex_unlock(&dblock);
  668. ast_cli(a->fd, "%d results found.\n", counter);
  669. return CLI_SUCCESS;
  670. }
  671. static int display_results(void *arg, int columns, char **values, char **colnames)
  672. {
  673. struct ast_cli_args *a = arg;
  674. size_t x;
  675. for (x = 0; x < columns; x++) {
  676. ast_cli(a->fd, "%-5s: %-50s\n", colnames[x], values[x]);
  677. }
  678. ast_cli(a->fd, "\n");
  679. return 0;
  680. }
  681. static char *handle_cli_database_query(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  682. {
  683. switch (cmd) {
  684. case CLI_INIT:
  685. e->command = "database query";
  686. e->usage =
  687. "Usage: database query \"<SQL Statement>\"\n"
  688. " Run a user-specified SQL query on the database. Be careful.\n";
  689. return NULL;
  690. case CLI_GENERATE:
  691. return NULL;
  692. }
  693. if (a->argc != 3) {
  694. return CLI_SHOWUSAGE;
  695. }
  696. ast_mutex_lock(&dblock);
  697. db_execute_sql(a->argv[2], display_results, a);
  698. db_sync(); /* Go ahead and sync the db in case they write */
  699. ast_mutex_unlock(&dblock);
  700. return CLI_SUCCESS;
  701. }
  702. static struct ast_cli_entry cli_database[] = {
  703. AST_CLI_DEFINE(handle_cli_database_show, "Shows database contents"),
  704. AST_CLI_DEFINE(handle_cli_database_showkey, "Shows database contents"),
  705. AST_CLI_DEFINE(handle_cli_database_get, "Gets database value"),
  706. AST_CLI_DEFINE(handle_cli_database_put, "Adds/updates database value"),
  707. AST_CLI_DEFINE(handle_cli_database_del, "Removes database key/value"),
  708. AST_CLI_DEFINE(handle_cli_database_deltree, "Removes database keytree/values"),
  709. AST_CLI_DEFINE(handle_cli_database_query, "Run a user-specified query on the astdb"),
  710. };
  711. static int manager_dbput(struct mansession *s, const struct message *m)
  712. {
  713. const char *family = astman_get_header(m, "Family");
  714. const char *key = astman_get_header(m, "Key");
  715. const char *val = astman_get_header(m, "Val");
  716. int res;
  717. if (ast_strlen_zero(family)) {
  718. astman_send_error(s, m, "No family specified");
  719. return 0;
  720. }
  721. if (ast_strlen_zero(key)) {
  722. astman_send_error(s, m, "No key specified");
  723. return 0;
  724. }
  725. res = ast_db_put(family, key, S_OR(val, ""));
  726. if (res) {
  727. astman_send_error(s, m, "Failed to update entry");
  728. } else {
  729. astman_send_ack(s, m, "Updated database successfully");
  730. }
  731. return 0;
  732. }
  733. static int manager_dbget(struct mansession *s, const struct message *m)
  734. {
  735. const char *id = astman_get_header(m,"ActionID");
  736. char idText[256] = "";
  737. const char *family = astman_get_header(m, "Family");
  738. const char *key = astman_get_header(m, "Key");
  739. char tmp[MAX_DB_FIELD];
  740. int res;
  741. if (ast_strlen_zero(family)) {
  742. astman_send_error(s, m, "No family specified.");
  743. return 0;
  744. }
  745. if (ast_strlen_zero(key)) {
  746. astman_send_error(s, m, "No key specified.");
  747. return 0;
  748. }
  749. if (!ast_strlen_zero(id))
  750. snprintf(idText, sizeof(idText) ,"ActionID: %s\r\n", id);
  751. res = ast_db_get(family, key, tmp, sizeof(tmp));
  752. if (res) {
  753. astman_send_error(s, m, "Database entry not found");
  754. } else {
  755. astman_send_ack(s, m, "Result will follow");
  756. astman_append(s, "Event: DBGetResponse\r\n"
  757. "Family: %s\r\n"
  758. "Key: %s\r\n"
  759. "Val: %s\r\n"
  760. "%s"
  761. "\r\n",
  762. family, key, tmp, idText);
  763. astman_append(s, "Event: DBGetComplete\r\n"
  764. "%s"
  765. "\r\n",
  766. idText);
  767. }
  768. return 0;
  769. }
  770. static int manager_dbdel(struct mansession *s, const struct message *m)
  771. {
  772. const char *family = astman_get_header(m, "Family");
  773. const char *key = astman_get_header(m, "Key");
  774. int res;
  775. if (ast_strlen_zero(family)) {
  776. astman_send_error(s, m, "No family specified.");
  777. return 0;
  778. }
  779. if (ast_strlen_zero(key)) {
  780. astman_send_error(s, m, "No key specified.");
  781. return 0;
  782. }
  783. res = ast_db_del(family, key);
  784. if (res)
  785. astman_send_error(s, m, "Database entry not found");
  786. else
  787. astman_send_ack(s, m, "Key deleted successfully");
  788. return 0;
  789. }
  790. static int manager_dbdeltree(struct mansession *s, const struct message *m)
  791. {
  792. const char *family = astman_get_header(m, "Family");
  793. const char *key = astman_get_header(m, "Key");
  794. int num_deleted;
  795. if (ast_strlen_zero(family)) {
  796. astman_send_error(s, m, "No family specified.");
  797. return 0;
  798. }
  799. if (!ast_strlen_zero(key)) {
  800. num_deleted = ast_db_deltree(family, key);
  801. } else {
  802. num_deleted = ast_db_deltree(family, NULL);
  803. }
  804. if (num_deleted < 0) {
  805. astman_send_error(s, m, "Database unavailable");
  806. } else if (num_deleted == 0) {
  807. astman_send_error(s, m, "Database entry not found");
  808. } else {
  809. astman_send_ack(s, m, "Key tree deleted successfully");
  810. }
  811. return 0;
  812. }
  813. /*!
  814. * \internal
  815. * \brief Signal the astdb sync thread to do its thing.
  816. *
  817. * \note dblock is assumed to be held when calling this function.
  818. */
  819. static void db_sync(void)
  820. {
  821. dosync = 1;
  822. ast_cond_signal(&dbcond);
  823. }
  824. /*!
  825. * \internal
  826. * \brief astdb sync thread
  827. *
  828. * This thread is in charge of syncing astdb to disk after a change.
  829. * By pushing it off to this thread to take care of, this I/O bound operation
  830. * will not block other threads from performing other critical processing.
  831. * If changes happen rapidly, this thread will also ensure that the sync
  832. * operations are rate limited.
  833. */
  834. static void *db_sync_thread(void *data)
  835. {
  836. ast_mutex_lock(&dblock);
  837. ast_db_begin_transaction();
  838. for (;;) {
  839. /* If dosync is set, db_sync() was called during sleep(1),
  840. * and the pending transaction should be committed.
  841. * Otherwise, block until db_sync() is called.
  842. */
  843. while (!dosync) {
  844. ast_cond_wait(&dbcond, &dblock);
  845. }
  846. dosync = 0;
  847. if (ast_db_commit_transaction()) {
  848. ast_db_rollback_transaction();
  849. }
  850. if (doexit) {
  851. ast_mutex_unlock(&dblock);
  852. break;
  853. }
  854. ast_db_begin_transaction();
  855. ast_mutex_unlock(&dblock);
  856. sleep(1);
  857. ast_mutex_lock(&dblock);
  858. }
  859. return NULL;
  860. }
  861. /*!
  862. * \internal
  863. * \brief Clean up resources on Asterisk shutdown
  864. */
  865. static void astdb_atexit(void)
  866. {
  867. ast_cli_unregister_multiple(cli_database, ARRAY_LEN(cli_database));
  868. ast_manager_unregister("DBGet");
  869. ast_manager_unregister("DBPut");
  870. ast_manager_unregister("DBDel");
  871. ast_manager_unregister("DBDelTree");
  872. /* Set doexit to 1 to kill thread. db_sync must be called with
  873. * mutex held. */
  874. ast_mutex_lock(&dblock);
  875. doexit = 1;
  876. db_sync();
  877. ast_mutex_unlock(&dblock);
  878. pthread_join(syncthread, NULL);
  879. ast_mutex_lock(&dblock);
  880. clean_statements();
  881. if (sqlite3_close(astdb) == SQLITE_OK) {
  882. astdb = NULL;
  883. }
  884. ast_mutex_unlock(&dblock);
  885. }
  886. int astdb_init(void)
  887. {
  888. if (db_init()) {
  889. return -1;
  890. }
  891. ast_cond_init(&dbcond, NULL);
  892. if (ast_pthread_create_background(&syncthread, NULL, db_sync_thread, NULL)) {
  893. return -1;
  894. }
  895. ast_register_atexit(astdb_atexit);
  896. ast_cli_register_multiple(cli_database, ARRAY_LEN(cli_database));
  897. ast_manager_register_xml_core("DBGet", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_dbget);
  898. ast_manager_register_xml_core("DBPut", EVENT_FLAG_SYSTEM, manager_dbput);
  899. ast_manager_register_xml_core("DBDel", EVENT_FLAG_SYSTEM, manager_dbdel);
  900. ast_manager_register_xml_core("DBDelTree", EVENT_FLAG_SYSTEM, manager_dbdeltree);
  901. return 0;
  902. }