db.c 34 KB

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