db.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. if (sqlite3_exec(astdb, sql, callback, arg, &errmsg) != SQLITE_OK) {
  254. ast_log(LOG_WARNING, "Error executing SQL (%s): %s\n", sql, errmsg);
  255. sqlite3_free(errmsg);
  256. res = -1;
  257. }
  258. return res;
  259. }
  260. static int ast_db_begin_transaction(void)
  261. {
  262. return db_execute_sql("BEGIN TRANSACTION", NULL, NULL);
  263. }
  264. static int ast_db_commit_transaction(void)
  265. {
  266. return db_execute_sql("COMMIT", NULL, NULL);
  267. }
  268. static int ast_db_rollback_transaction(void)
  269. {
  270. return db_execute_sql("ROLLBACK", NULL, NULL);
  271. }
  272. int ast_db_put(const char *family, const char *key, const char *value)
  273. {
  274. char fullkey[MAX_DB_FIELD];
  275. size_t fullkey_len;
  276. int res = 0;
  277. if (strlen(family) + strlen(key) + 2 > sizeof(fullkey) - 1) {
  278. ast_log(LOG_WARNING, "Family and key length must be less than %zu bytes\n", sizeof(fullkey) - 3);
  279. return -1;
  280. }
  281. fullkey_len = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, key);
  282. ast_mutex_lock(&dblock);
  283. if (sqlite3_bind_text(put_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
  284. ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
  285. res = -1;
  286. } else if (sqlite3_bind_text(put_stmt, 2, value, -1, SQLITE_STATIC) != SQLITE_OK) {
  287. ast_log(LOG_WARNING, "Couldn't bind value to stmt: %s\n", sqlite3_errmsg(astdb));
  288. res = -1;
  289. } else if (sqlite3_step(put_stmt) != SQLITE_DONE) {
  290. ast_log(LOG_WARNING, "Couldn't execute statment: %s\n", sqlite3_errmsg(astdb));
  291. res = -1;
  292. }
  293. sqlite3_reset(put_stmt);
  294. db_sync();
  295. ast_mutex_unlock(&dblock);
  296. return res;
  297. }
  298. /*!
  299. * \internal
  300. * \brief Get key value specified by family/key.
  301. *
  302. * Gets the value associated with the specified \a family and \a key, and
  303. * stores it, either into the fixed sized buffer specified by \a buffer
  304. * and \a bufferlen, or as a heap allocated string if \a bufferlen is -1.
  305. *
  306. * \note If \a bufferlen is -1, \a buffer points to heap allocated memory
  307. * and must be freed by calling ast_free().
  308. *
  309. * \retval -1 An error occurred
  310. * \retval 0 Success
  311. */
  312. static int db_get_common(const char *family, const char *key, char **buffer, int bufferlen)
  313. {
  314. const unsigned char *result;
  315. char fullkey[MAX_DB_FIELD];
  316. size_t fullkey_len;
  317. int res = 0;
  318. if (strlen(family) + strlen(key) + 2 > sizeof(fullkey) - 1) {
  319. ast_log(LOG_WARNING, "Family and key length must be less than %zu bytes\n", sizeof(fullkey) - 3);
  320. return -1;
  321. }
  322. fullkey_len = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, key);
  323. ast_mutex_lock(&dblock);
  324. if (sqlite3_bind_text(get_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
  325. ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
  326. res = -1;
  327. } else if (sqlite3_step(get_stmt) != SQLITE_ROW) {
  328. ast_debug(1, "Unable to find key '%s' in family '%s'\n", key, family);
  329. res = -1;
  330. } else if (!(result = sqlite3_column_text(get_stmt, 0))) {
  331. ast_log(LOG_WARNING, "Couldn't get value\n");
  332. res = -1;
  333. } else {
  334. const char *value = (const char *) result;
  335. if (bufferlen == -1) {
  336. *buffer = ast_strdup(value);
  337. } else {
  338. ast_copy_string(*buffer, value, bufferlen);
  339. }
  340. }
  341. sqlite3_reset(get_stmt);
  342. ast_mutex_unlock(&dblock);
  343. return res;
  344. }
  345. int ast_db_get(const char *family, const char *key, char *value, int valuelen)
  346. {
  347. ast_assert(value != NULL);
  348. /* Make sure we initialize */
  349. value[0] = 0;
  350. return db_get_common(family, key, &value, valuelen);
  351. }
  352. int ast_db_get_allocated(const char *family, const char *key, char **out)
  353. {
  354. *out = NULL;
  355. return db_get_common(family, key, out, -1);
  356. }
  357. int ast_db_del(const char *family, const char *key)
  358. {
  359. char fullkey[MAX_DB_FIELD];
  360. size_t fullkey_len;
  361. int res = 0;
  362. if (strlen(family) + strlen(key) + 2 > sizeof(fullkey) - 1) {
  363. ast_log(LOG_WARNING, "Family and key length must be less than %zu bytes\n", sizeof(fullkey) - 3);
  364. return -1;
  365. }
  366. fullkey_len = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, key);
  367. ast_mutex_lock(&dblock);
  368. if (sqlite3_bind_text(del_stmt, 1, fullkey, fullkey_len, SQLITE_STATIC) != SQLITE_OK) {
  369. ast_log(LOG_WARNING, "Couldn't bind key to stmt: %s\n", sqlite3_errmsg(astdb));
  370. res = -1;
  371. } else if (sqlite3_step(del_stmt) != SQLITE_DONE) {
  372. ast_debug(1, "Unable to find key '%s' in family '%s'\n", key, family);
  373. res = -1;
  374. }
  375. sqlite3_reset(del_stmt);
  376. db_sync();
  377. ast_mutex_unlock(&dblock);
  378. return res;
  379. }
  380. int ast_db_deltree(const char *family, const char *keytree)
  381. {
  382. sqlite3_stmt *stmt = deltree_stmt;
  383. char prefix[MAX_DB_FIELD];
  384. int res = 0;
  385. if (!ast_strlen_zero(family)) {
  386. if (!ast_strlen_zero(keytree)) {
  387. /* Family and key tree */
  388. snprintf(prefix, sizeof(prefix), "/%s/%s", family, keytree);
  389. } else {
  390. /* Family only */
  391. snprintf(prefix, sizeof(prefix), "/%s", family);
  392. }
  393. } else {
  394. prefix[0] = '\0';
  395. stmt = deltree_all_stmt;
  396. }
  397. ast_mutex_lock(&dblock);
  398. if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, -1, SQLITE_STATIC) != SQLITE_OK)) {
  399. ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
  400. res = -1;
  401. } else if (sqlite3_step(stmt) != SQLITE_DONE) {
  402. ast_log(LOG_WARNING, "Couldn't execute stmt: %s\n", sqlite3_errmsg(astdb));
  403. res = -1;
  404. }
  405. res = sqlite3_changes(astdb);
  406. sqlite3_reset(stmt);
  407. db_sync();
  408. ast_mutex_unlock(&dblock);
  409. return res;
  410. }
  411. struct ast_db_entry *ast_db_gettree(const char *family, const char *keytree)
  412. {
  413. char prefix[MAX_DB_FIELD];
  414. sqlite3_stmt *stmt = gettree_stmt;
  415. struct ast_db_entry *cur, *last = NULL, *ret = NULL;
  416. if (!ast_strlen_zero(family)) {
  417. if (!ast_strlen_zero(keytree)) {
  418. /* Family and key tree */
  419. snprintf(prefix, sizeof(prefix), "/%s/%s", family, keytree);
  420. } else {
  421. /* Family only */
  422. snprintf(prefix, sizeof(prefix), "/%s", family);
  423. }
  424. } else {
  425. prefix[0] = '\0';
  426. stmt = gettree_all_stmt;
  427. }
  428. ast_mutex_lock(&dblock);
  429. if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, -1, SQLITE_STATIC) != SQLITE_OK)) {
  430. ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
  431. sqlite3_reset(stmt);
  432. ast_mutex_unlock(&dblock);
  433. return NULL;
  434. }
  435. while (sqlite3_step(stmt) == SQLITE_ROW) {
  436. const char *key_s, *value_s;
  437. if (!(key_s = (const char *) sqlite3_column_text(stmt, 0))) {
  438. break;
  439. }
  440. if (!(value_s = (const char *) sqlite3_column_text(stmt, 1))) {
  441. break;
  442. }
  443. if (!(cur = ast_malloc(sizeof(*cur) + strlen(key_s) + strlen(value_s) + 2))) {
  444. break;
  445. }
  446. cur->next = NULL;
  447. cur->key = cur->data + strlen(value_s) + 1;
  448. strcpy(cur->data, value_s);
  449. strcpy(cur->key, key_s);
  450. if (last) {
  451. last->next = cur;
  452. } else {
  453. ret = cur;
  454. }
  455. last = cur;
  456. }
  457. sqlite3_reset(stmt);
  458. ast_mutex_unlock(&dblock);
  459. return ret;
  460. }
  461. void ast_db_freetree(struct ast_db_entry *dbe)
  462. {
  463. struct ast_db_entry *last;
  464. while (dbe) {
  465. last = dbe;
  466. dbe = dbe->next;
  467. ast_free(last);
  468. }
  469. }
  470. static char *handle_cli_database_put(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  471. {
  472. int res;
  473. switch (cmd) {
  474. case CLI_INIT:
  475. e->command = "database put";
  476. e->usage =
  477. "Usage: database put <family> <key> <value>\n"
  478. " Adds or updates an entry in the Asterisk database for\n"
  479. " a given family, key, and value.\n";
  480. return NULL;
  481. case CLI_GENERATE:
  482. return NULL;
  483. }
  484. if (a->argc != 5)
  485. return CLI_SHOWUSAGE;
  486. res = ast_db_put(a->argv[2], a->argv[3], a->argv[4]);
  487. if (res) {
  488. ast_cli(a->fd, "Failed to update entry\n");
  489. } else {
  490. ast_cli(a->fd, "Updated database successfully\n");
  491. }
  492. return CLI_SUCCESS;
  493. }
  494. static char *handle_cli_database_get(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  495. {
  496. int res;
  497. char tmp[MAX_DB_FIELD];
  498. switch (cmd) {
  499. case CLI_INIT:
  500. e->command = "database get";
  501. e->usage =
  502. "Usage: database get <family> <key>\n"
  503. " Retrieves an entry in the Asterisk database for a given\n"
  504. " family and key.\n";
  505. return NULL;
  506. case CLI_GENERATE:
  507. return NULL;
  508. }
  509. if (a->argc != 4)
  510. return CLI_SHOWUSAGE;
  511. res = ast_db_get(a->argv[2], a->argv[3], tmp, sizeof(tmp));
  512. if (res) {
  513. ast_cli(a->fd, "Database entry not found.\n");
  514. } else {
  515. ast_cli(a->fd, "Value: %s\n", tmp);
  516. }
  517. return CLI_SUCCESS;
  518. }
  519. static char *handle_cli_database_del(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  520. {
  521. int res;
  522. switch (cmd) {
  523. case CLI_INIT:
  524. e->command = "database del";
  525. e->usage =
  526. "Usage: database del <family> <key>\n"
  527. " Deletes an entry in the Asterisk database for a given\n"
  528. " family and key.\n";
  529. return NULL;
  530. case CLI_GENERATE:
  531. return NULL;
  532. }
  533. if (a->argc != 4)
  534. return CLI_SHOWUSAGE;
  535. res = ast_db_del(a->argv[2], a->argv[3]);
  536. if (res) {
  537. ast_cli(a->fd, "Database entry does not exist.\n");
  538. } else {
  539. ast_cli(a->fd, "Database entry removed.\n");
  540. }
  541. return CLI_SUCCESS;
  542. }
  543. static char *handle_cli_database_deltree(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  544. {
  545. int num_deleted;
  546. switch (cmd) {
  547. case CLI_INIT:
  548. e->command = "database deltree";
  549. e->usage =
  550. "Usage: database deltree <family> [keytree]\n"
  551. " OR: database deltree <family>[/keytree]\n"
  552. " Deletes a family or specific keytree within a family\n"
  553. " in the Asterisk database. The two arguments may be\n"
  554. " separated by either a space or a slash.\n";
  555. return NULL;
  556. case CLI_GENERATE:
  557. return NULL;
  558. }
  559. if ((a->argc < 3) || (a->argc > 4))
  560. return CLI_SHOWUSAGE;
  561. if (a->argc == 4) {
  562. num_deleted = ast_db_deltree(a->argv[2], a->argv[3]);
  563. } else {
  564. num_deleted = ast_db_deltree(a->argv[2], NULL);
  565. }
  566. if (num_deleted < 0) {
  567. ast_cli(a->fd, "Database unavailable.\n");
  568. } else if (num_deleted == 0) {
  569. ast_cli(a->fd, "Database entries do not exist.\n");
  570. } else {
  571. ast_cli(a->fd, "%d database entries removed.\n",num_deleted);
  572. }
  573. return CLI_SUCCESS;
  574. }
  575. static char *handle_cli_database_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  576. {
  577. char prefix[MAX_DB_FIELD];
  578. int counter = 0;
  579. sqlite3_stmt *stmt = gettree_stmt;
  580. switch (cmd) {
  581. case CLI_INIT:
  582. e->command = "database show";
  583. e->usage =
  584. "Usage: database show [family [keytree]]\n"
  585. " OR: database show [family[/keytree]]\n"
  586. " Shows Asterisk database contents, optionally restricted\n"
  587. " to a given family, or family and keytree. The two arguments\n"
  588. " may be separated either by a space or by a slash.\n";
  589. return NULL;
  590. case CLI_GENERATE:
  591. return NULL;
  592. }
  593. if (a->argc == 4) {
  594. /* Family and key tree */
  595. snprintf(prefix, sizeof(prefix), "/%s/%s", a->argv[2], a->argv[3]);
  596. } else if (a->argc == 3) {
  597. /* Family only */
  598. snprintf(prefix, sizeof(prefix), "/%s", a->argv[2]);
  599. } else if (a->argc == 2) {
  600. /* Neither */
  601. prefix[0] = '\0';
  602. stmt = gettree_all_stmt;
  603. } else {
  604. return CLI_SHOWUSAGE;
  605. }
  606. ast_mutex_lock(&dblock);
  607. if (!ast_strlen_zero(prefix) && (sqlite3_bind_text(stmt, 1, prefix, -1, SQLITE_STATIC) != SQLITE_OK)) {
  608. ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", prefix, sqlite3_errmsg(astdb));
  609. sqlite3_reset(stmt);
  610. ast_mutex_unlock(&dblock);
  611. return NULL;
  612. }
  613. while (sqlite3_step(stmt) == SQLITE_ROW) {
  614. const char *key_s, *value_s;
  615. if (!(key_s = (const char *) sqlite3_column_text(stmt, 0))) {
  616. ast_log(LOG_WARNING, "Skipping invalid key!\n");
  617. continue;
  618. }
  619. if (!(value_s = (const char *) sqlite3_column_text(stmt, 1))) {
  620. ast_log(LOG_WARNING, "Skipping invalid value!\n");
  621. continue;
  622. }
  623. ++counter;
  624. ast_cli(a->fd, "%-50s: %-25s\n", key_s, value_s);
  625. }
  626. sqlite3_reset(stmt);
  627. ast_mutex_unlock(&dblock);
  628. ast_cli(a->fd, "%d results found.\n", counter);
  629. return CLI_SUCCESS;
  630. }
  631. static char *handle_cli_database_showkey(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  632. {
  633. int counter = 0;
  634. switch (cmd) {
  635. case CLI_INIT:
  636. e->command = "database showkey";
  637. e->usage =
  638. "Usage: database showkey <keytree>\n"
  639. " Shows Asterisk database contents, restricted to a given key.\n";
  640. return NULL;
  641. case CLI_GENERATE:
  642. return NULL;
  643. }
  644. if (a->argc != 3) {
  645. return CLI_SHOWUSAGE;
  646. }
  647. ast_mutex_lock(&dblock);
  648. if (!ast_strlen_zero(a->argv[2]) && (sqlite3_bind_text(showkey_stmt, 1, a->argv[2], -1, SQLITE_STATIC) != SQLITE_OK)) {
  649. ast_log(LOG_WARNING, "Could bind %s to stmt: %s\n", a->argv[2], sqlite3_errmsg(astdb));
  650. sqlite3_reset(showkey_stmt);
  651. ast_mutex_unlock(&dblock);
  652. return NULL;
  653. }
  654. while (sqlite3_step(showkey_stmt) == SQLITE_ROW) {
  655. const char *key_s, *value_s;
  656. if (!(key_s = (const char *) sqlite3_column_text(showkey_stmt, 0))) {
  657. break;
  658. }
  659. if (!(value_s = (const char *) sqlite3_column_text(showkey_stmt, 1))) {
  660. break;
  661. }
  662. ++counter;
  663. ast_cli(a->fd, "%-50s: %-25s\n", key_s, value_s);
  664. }
  665. sqlite3_reset(showkey_stmt);
  666. ast_mutex_unlock(&dblock);
  667. ast_cli(a->fd, "%d results found.\n", counter);
  668. return CLI_SUCCESS;
  669. }
  670. static int display_results(void *arg, int columns, char **values, char **colnames)
  671. {
  672. struct ast_cli_args *a = arg;
  673. size_t x;
  674. for (x = 0; x < columns; x++) {
  675. ast_cli(a->fd, "%-5s: %-50s\n", colnames[x], values[x]);
  676. }
  677. ast_cli(a->fd, "\n");
  678. return 0;
  679. }
  680. static char *handle_cli_database_query(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  681. {
  682. switch (cmd) {
  683. case CLI_INIT:
  684. e->command = "database query";
  685. e->usage =
  686. "Usage: database query \"<SQL Statement>\"\n"
  687. " Run a user-specified SQL query on the database. Be careful.\n";
  688. return NULL;
  689. case CLI_GENERATE:
  690. return NULL;
  691. }
  692. if (a->argc != 3) {
  693. return CLI_SHOWUSAGE;
  694. }
  695. ast_mutex_lock(&dblock);
  696. db_execute_sql(a->argv[2], display_results, a);
  697. db_sync(); /* Go ahead and sync the db in case they write */
  698. ast_mutex_unlock(&dblock);
  699. return CLI_SUCCESS;
  700. }
  701. static struct ast_cli_entry cli_database[] = {
  702. AST_CLI_DEFINE(handle_cli_database_show, "Shows database contents"),
  703. AST_CLI_DEFINE(handle_cli_database_showkey, "Shows database contents"),
  704. AST_CLI_DEFINE(handle_cli_database_get, "Gets database value"),
  705. AST_CLI_DEFINE(handle_cli_database_put, "Adds/updates database value"),
  706. AST_CLI_DEFINE(handle_cli_database_del, "Removes database key/value"),
  707. AST_CLI_DEFINE(handle_cli_database_deltree, "Removes database keytree/values"),
  708. AST_CLI_DEFINE(handle_cli_database_query, "Run a user-specified query on the astdb"),
  709. };
  710. static int manager_dbput(struct mansession *s, const struct message *m)
  711. {
  712. const char *family = astman_get_header(m, "Family");
  713. const char *key = astman_get_header(m, "Key");
  714. const char *val = astman_get_header(m, "Val");
  715. int res;
  716. if (ast_strlen_zero(family)) {
  717. astman_send_error(s, m, "No family specified");
  718. return 0;
  719. }
  720. if (ast_strlen_zero(key)) {
  721. astman_send_error(s, m, "No key specified");
  722. return 0;
  723. }
  724. res = ast_db_put(family, key, S_OR(val, ""));
  725. if (res) {
  726. astman_send_error(s, m, "Failed to update entry");
  727. } else {
  728. astman_send_ack(s, m, "Updated database successfully");
  729. }
  730. return 0;
  731. }
  732. static int manager_dbget(struct mansession *s, const struct message *m)
  733. {
  734. const char *id = astman_get_header(m,"ActionID");
  735. char idText[256] = "";
  736. const char *family = astman_get_header(m, "Family");
  737. const char *key = astman_get_header(m, "Key");
  738. char tmp[MAX_DB_FIELD];
  739. int res;
  740. if (ast_strlen_zero(family)) {
  741. astman_send_error(s, m, "No family specified.");
  742. return 0;
  743. }
  744. if (ast_strlen_zero(key)) {
  745. astman_send_error(s, m, "No key specified.");
  746. return 0;
  747. }
  748. if (!ast_strlen_zero(id))
  749. snprintf(idText, sizeof(idText) ,"ActionID: %s\r\n", id);
  750. res = ast_db_get(family, key, tmp, sizeof(tmp));
  751. if (res) {
  752. astman_send_error(s, m, "Database entry not found");
  753. } else {
  754. astman_send_ack(s, m, "Result will follow");
  755. astman_append(s, "Event: DBGetResponse\r\n"
  756. "Family: %s\r\n"
  757. "Key: %s\r\n"
  758. "Val: %s\r\n"
  759. "%s"
  760. "\r\n",
  761. family, key, tmp, idText);
  762. astman_append(s, "Event: DBGetComplete\r\n"
  763. "%s"
  764. "\r\n",
  765. idText);
  766. }
  767. return 0;
  768. }
  769. static int manager_dbdel(struct mansession *s, const struct message *m)
  770. {
  771. const char *family = astman_get_header(m, "Family");
  772. const char *key = astman_get_header(m, "Key");
  773. int res;
  774. if (ast_strlen_zero(family)) {
  775. astman_send_error(s, m, "No family specified.");
  776. return 0;
  777. }
  778. if (ast_strlen_zero(key)) {
  779. astman_send_error(s, m, "No key specified.");
  780. return 0;
  781. }
  782. res = ast_db_del(family, key);
  783. if (res)
  784. astman_send_error(s, m, "Database entry not found");
  785. else
  786. astman_send_ack(s, m, "Key deleted successfully");
  787. return 0;
  788. }
  789. static int manager_dbdeltree(struct mansession *s, const struct message *m)
  790. {
  791. const char *family = astman_get_header(m, "Family");
  792. const char *key = astman_get_header(m, "Key");
  793. int num_deleted;
  794. if (ast_strlen_zero(family)) {
  795. astman_send_error(s, m, "No family specified.");
  796. return 0;
  797. }
  798. if (!ast_strlen_zero(key)) {
  799. num_deleted = ast_db_deltree(family, key);
  800. } else {
  801. num_deleted = ast_db_deltree(family, NULL);
  802. }
  803. if (num_deleted < 0) {
  804. astman_send_error(s, m, "Database unavailable");
  805. } else if (num_deleted == 0) {
  806. astman_send_error(s, m, "Database entry not found");
  807. } else {
  808. astman_send_ack(s, m, "Key tree deleted successfully");
  809. }
  810. return 0;
  811. }
  812. /*!
  813. * \internal
  814. * \brief Signal the astdb sync thread to do its thing.
  815. *
  816. * \note dblock is assumed to be held when calling this function.
  817. */
  818. static void db_sync(void)
  819. {
  820. dosync = 1;
  821. ast_cond_signal(&dbcond);
  822. }
  823. /*!
  824. * \internal
  825. * \brief astdb sync thread
  826. *
  827. * This thread is in charge of syncing astdb to disk after a change.
  828. * By pushing it off to this thread to take care of, this I/O bound operation
  829. * will not block other threads from performing other critical processing.
  830. * If changes happen rapidly, this thread will also ensure that the sync
  831. * operations are rate limited.
  832. */
  833. static void *db_sync_thread(void *data)
  834. {
  835. ast_mutex_lock(&dblock);
  836. ast_db_begin_transaction();
  837. for (;;) {
  838. /* If dosync is set, db_sync() was called during sleep(1),
  839. * and the pending transaction should be committed.
  840. * Otherwise, block until db_sync() is called.
  841. */
  842. while (!dosync) {
  843. ast_cond_wait(&dbcond, &dblock);
  844. }
  845. dosync = 0;
  846. if (ast_db_commit_transaction()) {
  847. ast_db_rollback_transaction();
  848. }
  849. if (doexit) {
  850. ast_mutex_unlock(&dblock);
  851. break;
  852. }
  853. ast_db_begin_transaction();
  854. ast_mutex_unlock(&dblock);
  855. sleep(1);
  856. ast_mutex_lock(&dblock);
  857. }
  858. return NULL;
  859. }
  860. /*! \internal \brief Clean up resources on Asterisk shutdown */
  861. static void astdb_atexit(void)
  862. {
  863. ast_cli_unregister_multiple(cli_database, ARRAY_LEN(cli_database));
  864. ast_manager_unregister("DBGet");
  865. ast_manager_unregister("DBPut");
  866. ast_manager_unregister("DBDel");
  867. ast_manager_unregister("DBDelTree");
  868. /* Set doexit to 1 to kill thread. db_sync must be called with
  869. * mutex held. */
  870. ast_mutex_lock(&dblock);
  871. doexit = 1;
  872. db_sync();
  873. ast_mutex_unlock(&dblock);
  874. pthread_join(syncthread, NULL);
  875. ast_mutex_lock(&dblock);
  876. clean_statements();
  877. if (sqlite3_close(astdb) == SQLITE_OK) {
  878. astdb = NULL;
  879. }
  880. ast_mutex_unlock(&dblock);
  881. }
  882. int astdb_init(void)
  883. {
  884. if (db_init()) {
  885. return -1;
  886. }
  887. ast_cond_init(&dbcond, NULL);
  888. if (ast_pthread_create_background(&syncthread, NULL, db_sync_thread, NULL)) {
  889. return -1;
  890. }
  891. ast_register_atexit(astdb_atexit);
  892. ast_cli_register_multiple(cli_database, ARRAY_LEN(cli_database));
  893. ast_manager_register_xml_core("DBGet", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_dbget);
  894. ast_manager_register_xml_core("DBPut", EVENT_FLAG_SYSTEM, manager_dbput);
  895. ast_manager_register_xml_core("DBDel", EVENT_FLAG_SYSTEM, manager_dbdel);
  896. ast_manager_register_xml_core("DBDelTree", EVENT_FLAG_SYSTEM, manager_dbdeltree);
  897. return 0;
  898. }