res_config_sqlite3.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2011, Terry Wilson
  5. *
  6. * Terry Wilson <twilson@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. * Please follow coding guidelines
  19. * http://svn.digium.com/view/asterisk/trunk/doc/CODING-GUIDELINES
  20. */
  21. /*! \file
  22. *
  23. * \brief SQLite 3 configuration engine
  24. *
  25. * \author\verbatim Terry Wilson <twilson@digium.com> \endverbatim
  26. *
  27. * This is a realtime configuration engine for the SQLite 3 Database
  28. * \ingroup resources
  29. */
  30. /*! \li \ref res_config_sqlite3.c uses the configuration file \ref res_config_sqlite3.conf
  31. * \addtogroup configuration_file Configuration Files
  32. */
  33. /*!
  34. * \page res_config_sqlite3.conf res_config_sqlite3.conf
  35. * \verbinclude res_config_sqlite3.conf.sample
  36. */
  37. /*** MODULEINFO
  38. <depend>sqlite3</depend>
  39. <support_level>core</support_level>
  40. ***/
  41. #include "asterisk.h"
  42. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  43. #include <sqlite3.h>
  44. #include "asterisk/module.h"
  45. #include "asterisk/config.h"
  46. #include "asterisk/paths.h"
  47. #include "asterisk/astobj2.h"
  48. #include "asterisk/lock.h"
  49. #include "asterisk/utils.h"
  50. #include "asterisk/app.h"
  51. /*** DOCUMENTATION
  52. ***/
  53. static struct ast_config *realtime_sqlite3_load(const char *database, const char *table, const char *configfile, struct ast_config *config, struct ast_flags flags, const char *suggested_include_file, const char *who_asked);
  54. static struct ast_variable *realtime_sqlite3(const char *database, const char *table, const struct ast_variable *fields);
  55. static struct ast_config *realtime_sqlite3_multi(const char *database, const char *table, const struct ast_variable *fields);
  56. static int realtime_sqlite3_update(const char *database, const char *table, const char *keyfield, const char *entity, const struct ast_variable *fields);
  57. static int realtime_sqlite3_update2(const char *database, const char *table, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields);
  58. static int realtime_sqlite3_store(const char *database, const char *table, const struct ast_variable *fields);
  59. static int realtime_sqlite3_destroy(const char *database, const char *table, const char *keyfield, const char *entity, const struct ast_variable *fields);
  60. static int realtime_sqlite3_require(const char *database, const char *table, va_list ap);
  61. static int realtime_sqlite3_unload(const char *database, const char *table);
  62. struct ast_config_engine sqlite3_config_engine = {
  63. .name = "sqlite3",
  64. .load_func = realtime_sqlite3_load,
  65. .realtime_func = realtime_sqlite3,
  66. .realtime_multi_func = realtime_sqlite3_multi,
  67. .update_func = realtime_sqlite3_update,
  68. .update2_func = realtime_sqlite3_update2,
  69. .store_func = realtime_sqlite3_store,
  70. .destroy_func = realtime_sqlite3_destroy,
  71. .require_func = realtime_sqlite3_require,
  72. .unload_func = realtime_sqlite3_unload,
  73. };
  74. enum {
  75. REALTIME_SQLITE3_REQ_WARN,
  76. REALTIME_SQLITE3_REQ_CLOSE,
  77. REALTIME_SQLITE3_REQ_CHAR,
  78. };
  79. struct realtime_sqlite3_db {
  80. AST_DECLARE_STRING_FIELDS(
  81. AST_STRING_FIELD(name);
  82. AST_STRING_FIELD(filename);
  83. );
  84. sqlite3 *handle;
  85. pthread_t syncthread;
  86. ast_cond_t cond;
  87. unsigned int requirements:2;
  88. unsigned int dirty:1;
  89. unsigned int debug:1;
  90. unsigned int exiting:1;
  91. unsigned int wakeup:1;
  92. unsigned int batch;
  93. };
  94. struct ao2_container *databases;
  95. #define DB_BUCKETS 7
  96. AST_MUTEX_DEFINE_STATIC(config_lock);
  97. /* We need a separate buffer for each field we might use concurrently */
  98. AST_THREADSTORAGE(escape_table_buf);
  99. AST_THREADSTORAGE(escape_column_buf);
  100. AST_THREADSTORAGE(escape_value_buf);
  101. static int realtime_sqlite3_execute_handle(struct realtime_sqlite3_db *db, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync);
  102. void db_start_batch(struct realtime_sqlite3_db *db);
  103. void db_stop_batch(struct realtime_sqlite3_db *db);
  104. static inline const char *sqlite3_escape_string_helper(struct ast_threadstorage *ts, const char *param)
  105. {
  106. size_t maxlen = strlen(param) * 2 + sizeof("\"\"");
  107. /* It doesn't appear that sqlite3_snprintf will do more than double the
  108. * length of a string with %q as an option. %Q could double and possibly
  109. * add two quotes, and convert NULL pointers to the word "NULL", but we
  110. * don't allow those anyway. Just going to use %q for now. */
  111. struct ast_str *buf = ast_str_thread_get(ts, maxlen);
  112. char *tmp = ast_str_buffer(buf);
  113. char q = ts == &escape_value_buf ? '\'' : '"';
  114. ast_str_reset(buf);
  115. *tmp++ = q; /* Initial quote */
  116. while ((*tmp++ = *param++)) {
  117. /* Did we just copy a quote? Then double it. */
  118. if (*(tmp - 1) == q) {
  119. *tmp++ = q;
  120. }
  121. }
  122. *tmp = '\0'; /* Terminate past NULL from copy */
  123. *(tmp - 1) = q; /* Replace original NULL with the quote */
  124. ast_str_update(buf);
  125. return ast_str_buffer(buf);
  126. }
  127. static inline const char *sqlite3_escape_table(const char *param)
  128. {
  129. return sqlite3_escape_string_helper(&escape_table_buf, param);
  130. }
  131. static inline const char *sqlite3_escape_column(const char *param)
  132. {
  133. return sqlite3_escape_string_helper(&escape_column_buf, param);
  134. }
  135. /* Not inlining this function because it uses strdupa and I don't know if the compiler would be dumb */
  136. static const char *sqlite3_escape_column_op(const char *param)
  137. {
  138. size_t maxlen = strlen(param) * 2 + sizeof("\"\" =");
  139. struct ast_str *buf = ast_str_thread_get(&escape_column_buf, maxlen);
  140. char *tmp = ast_str_buffer(buf);
  141. int space = 0;
  142. ast_str_reset(buf);
  143. *tmp++ = '"';
  144. while ((*tmp++ = *param++)) {
  145. /* If we have seen a space, don't double quotes. XXX If we ever make the column/op field
  146. * available to users via an API, we will definitely need to avoid allowing special
  147. * characters like ';' in the data past the space as it will be unquoted data */
  148. if (space) {
  149. continue;
  150. }
  151. if (*(tmp - 1) == ' ') {
  152. *(tmp - 1) = '"';
  153. *tmp++ = ' ';
  154. space = 1;
  155. } else if (*(tmp - 1) == '"') {
  156. *tmp++ = '"';
  157. }
  158. }
  159. if (!space) {
  160. strcpy(tmp - 1, "\" =");
  161. }
  162. ast_str_update(buf);
  163. return ast_str_buffer(buf);
  164. }
  165. static inline const char *sqlite3_escape_value(const char *param)
  166. {
  167. return sqlite3_escape_string_helper(&escape_value_buf, param);
  168. }
  169. static int db_hash_fn(const void *obj, const int flags)
  170. {
  171. const struct realtime_sqlite3_db *db = obj;
  172. return ast_str_hash(flags & OBJ_KEY ? (const char *) obj : db->name);
  173. }
  174. static int db_cmp_fn(void *obj, void *arg, int flags) {
  175. struct realtime_sqlite3_db *db = obj, *other = arg;
  176. const char *name = arg;
  177. return !strcasecmp(db->name, flags & OBJ_KEY ? name : other->name) ? CMP_MATCH | CMP_STOP : 0;
  178. }
  179. static void db_destructor(void *obj)
  180. {
  181. struct realtime_sqlite3_db *db = obj;
  182. ast_debug(1, "Destroying db: %s\n", db->name);
  183. ast_string_field_free_memory(db);
  184. db_stop_batch(db);
  185. if (db->handle) {
  186. ao2_lock(db);
  187. sqlite3_close(db->handle);
  188. ao2_unlock(db);
  189. }
  190. }
  191. static struct realtime_sqlite3_db *find_database(const char *database)
  192. {
  193. return ao2_find(databases, database, OBJ_KEY);
  194. }
  195. static void unref_db(struct realtime_sqlite3_db **db)
  196. {
  197. ao2_ref(*db, -1);
  198. *db = NULL;
  199. }
  200. static int stop_batch_cb(void *obj, void *arg, int flags)
  201. {
  202. struct realtime_sqlite3_db *db = obj;
  203. db_stop_batch(db);
  204. return CMP_MATCH;
  205. }
  206. static int mark_dirty_cb(void *obj, void *arg, int flags)
  207. {
  208. struct realtime_sqlite3_db *db = obj;
  209. db->dirty = 1;
  210. return CMP_MATCH;
  211. }
  212. static void mark_all_databases_dirty(void)
  213. {
  214. ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA, mark_dirty_cb, NULL);
  215. }
  216. static int is_dirty_cb(void *obj, void *arg, int flags)
  217. {
  218. struct realtime_sqlite3_db *db = obj;
  219. if (db->dirty) {
  220. db_stop_batch(db);
  221. return CMP_MATCH;
  222. }
  223. return 0;
  224. }
  225. static void unlink_dirty_databases(void)
  226. {
  227. ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA | OBJ_UNLINK, is_dirty_cb, NULL);
  228. }
  229. static int str_to_requirements(const char *data)
  230. {
  231. if (!strcasecmp(data, "createclose")) {
  232. return REALTIME_SQLITE3_REQ_CLOSE;
  233. } else if (!strcasecmp(data, "createchar")) {
  234. return REALTIME_SQLITE3_REQ_CHAR;
  235. }
  236. /* default */
  237. return REALTIME_SQLITE3_REQ_WARN;
  238. }
  239. /*! \note Since this is called while a query is executing, we should already hold the db lock */
  240. static void trace_cb(void *arg, const char *sql)
  241. {
  242. struct realtime_sqlite3_db *db = arg;
  243. ast_debug(3, "DB: %s SQL: %s\n", db->name, sql);
  244. }
  245. /*! \brief Wrap commands in transactions increased write performance */
  246. static void *db_sync_thread(void *data)
  247. {
  248. struct realtime_sqlite3_db *db = data;
  249. ao2_lock(db);
  250. realtime_sqlite3_execute_handle(db, "BEGIN TRANSACTION", NULL, NULL, 0);
  251. for (;;) {
  252. if (!db->wakeup) {
  253. ast_cond_wait(&db->cond, ao2_object_get_lockaddr(db));
  254. }
  255. db->wakeup = 0;
  256. if (realtime_sqlite3_execute_handle(db, "COMMIT", NULL, NULL, 0) < 0) {
  257. realtime_sqlite3_execute_handle(db, "ROLLBACK", NULL, NULL, 0);
  258. }
  259. if (db->exiting) {
  260. ao2_unlock(db);
  261. break;
  262. }
  263. realtime_sqlite3_execute_handle(db, "BEGIN TRANSACTION", NULL, NULL, 0);
  264. ao2_unlock(db);
  265. usleep(1000 * db->batch);
  266. ao2_lock(db);
  267. }
  268. unref_db(&db);
  269. return NULL;
  270. }
  271. /*! \brief Open a database and appropriately set debugging on the db handle */
  272. static int db_open(struct realtime_sqlite3_db *db)
  273. {
  274. ao2_lock(db);
  275. if (sqlite3_open(db->filename, &db->handle) != SQLITE_OK) {
  276. ast_log(LOG_WARNING, "Could not open %s: %s\n", db->filename, sqlite3_errmsg(db->handle));
  277. ao2_unlock(db);
  278. return -1;
  279. }
  280. sqlite3_busy_timeout(db->handle, 1000);
  281. if (db->debug) {
  282. sqlite3_trace(db->handle, trace_cb, db);
  283. } else {
  284. sqlite3_trace(db->handle, NULL, NULL);
  285. }
  286. ao2_unlock(db);
  287. return 0;
  288. }
  289. static void db_sync(struct realtime_sqlite3_db *db)
  290. {
  291. db->wakeup = 1;
  292. ast_cond_signal(&db->cond);
  293. }
  294. void db_start_batch(struct realtime_sqlite3_db *db)
  295. {
  296. if (db->batch) {
  297. ast_cond_init(&db->cond, NULL);
  298. ao2_ref(db, +1);
  299. ast_pthread_create_background(&db->syncthread, NULL, db_sync_thread, db);
  300. }
  301. }
  302. void db_stop_batch(struct realtime_sqlite3_db *db)
  303. {
  304. if (db->batch) {
  305. db->exiting = 1;
  306. db_sync(db);
  307. pthread_join(db->syncthread, NULL);
  308. }
  309. }
  310. /*! \brief Create a db object based on a config category
  311. * \note Opening the db handle and linking to databases must be handled outside of this function
  312. */
  313. static struct realtime_sqlite3_db *new_realtime_sqlite3_db(struct ast_config *config, const char *cat)
  314. {
  315. struct ast_variable *var;
  316. struct realtime_sqlite3_db *db;
  317. if (!(db = ao2_alloc(sizeof(*db), db_destructor))) {
  318. return NULL;
  319. }
  320. if (ast_string_field_init(db, 64)) {
  321. unref_db(&db);
  322. return NULL;
  323. }
  324. /* Set defaults */
  325. db->requirements = REALTIME_SQLITE3_REQ_WARN;
  326. db->batch = 100;
  327. ast_string_field_set(db, name, cat);
  328. for (var = ast_variable_browse(config, cat); var; var = var->next) {
  329. if (!strcasecmp(var->name, "dbfile")) {
  330. ast_string_field_set(db, filename, var->value);
  331. } else if (!strcasecmp(var->name, "requirements")) {
  332. db->requirements = str_to_requirements(var->value);
  333. } else if (!strcasecmp(var->name, "batch")) {
  334. ast_app_parse_timelen(var->value, (int *) &db->batch, TIMELEN_MILLISECONDS);
  335. } else if (!strcasecmp(var->name, "debug")) {
  336. db->debug = ast_true(var->value);
  337. }
  338. }
  339. if (ast_strlen_zero(db->filename)) {
  340. ast_log(LOG_WARNING, "Must specify dbfile in res_config_sqlite3.conf\n");
  341. unref_db(&db);
  342. return NULL;
  343. }
  344. return db;
  345. }
  346. /*! \brief Update an existing db object based on config data
  347. * \param db The database object to update
  348. * \param config The configuration data with which to update the db
  349. * \param cat The config category (which becomes db->name)
  350. */
  351. static int update_realtime_sqlite3_db(struct realtime_sqlite3_db *db, struct ast_config *config, const char *cat)
  352. {
  353. struct realtime_sqlite3_db *new;
  354. if (!(new = new_realtime_sqlite3_db(config, cat))) {
  355. return -1;
  356. }
  357. /* Copy fields that don't need anything special done on change */
  358. db->requirements = new->requirements;
  359. /* Handle changes that require immediate behavior modification */
  360. if (db->debug != new->debug) {
  361. if (db->debug) {
  362. sqlite3_trace(db->handle, NULL, NULL);
  363. } else {
  364. sqlite3_trace(db->handle, trace_cb, db);
  365. }
  366. db->debug = new->debug;
  367. }
  368. if (strcmp(db->filename, new->filename)) {
  369. sqlite3_close(db->handle);
  370. ast_string_field_set(db, filename, new->filename);
  371. db_open(db); /* Also handles setting appropriate debug on new handle */
  372. }
  373. if (db->batch != new->batch) {
  374. if (db->batch == 0) {
  375. db->batch = new->batch;
  376. db_start_batch(db);
  377. } else if (new->batch == 0) {
  378. db->batch = new->batch;
  379. db_stop_batch(db);
  380. }
  381. db->batch = new->batch;
  382. }
  383. db->dirty = 0;
  384. unref_db(&new);
  385. return 0;
  386. }
  387. /*! \brief Create a varlist from a single sqlite3 result row */
  388. static int row_to_varlist(void *arg, int num_columns, char **values, char **columns)
  389. {
  390. struct ast_variable **head = arg, *tail;
  391. int i;
  392. struct ast_variable *new;
  393. if (!(new = ast_variable_new(columns[0], S_OR(values[0], ""), ""))) {
  394. return SQLITE_ABORT;
  395. }
  396. *head = tail = new;
  397. for (i = 1; i < num_columns; i++) {
  398. if (!(new = ast_variable_new(columns[i], S_OR(values[i], ""), ""))) {
  399. ast_variables_destroy(*head);
  400. *head = NULL;
  401. return SQLITE_ABORT;
  402. }
  403. tail->next = new;
  404. tail = new;
  405. }
  406. return 0;
  407. }
  408. /*! \brief Callback for creating an ast_config from a successive sqlite3 result rows */
  409. static int append_row_to_cfg(void *arg, int num_columns, char **values, char **columns)
  410. {
  411. struct ast_config *cfg = arg;
  412. struct ast_category *cat;
  413. int i;
  414. if (!(cat = ast_category_new("", "", 99999))) {
  415. return SQLITE_ABORT;
  416. }
  417. for (i = 0; i < num_columns; i++) {
  418. struct ast_variable *var;
  419. if (!(var = ast_variable_new(columns[i], S_OR(values[i], ""), ""))) {
  420. ast_log(LOG_ERROR, "Could not create new variable for '%s: %s', throwing away list\n", columns[i], values[i]);
  421. continue;
  422. }
  423. ast_variable_append(cat, var);
  424. }
  425. ast_category_append(cfg, cat);
  426. return 0;
  427. }
  428. /*!
  429. * Structure sent to the SQLite 3 callback function for static configuration.
  430. *
  431. * \see static_realtime_cb()
  432. */
  433. struct cfg_entry_args {
  434. struct ast_config *cfg;
  435. struct ast_category *cat;
  436. char *cat_name;
  437. struct ast_flags flags;
  438. const char *who_asked;
  439. };
  440. /*! Exeute an SQL statement given the database object
  441. *
  442. * \retval -1 ERROR
  443. * \retval > -1 Number of rows changed
  444. */
  445. static int realtime_sqlite3_execute_handle(struct realtime_sqlite3_db *db, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync)
  446. {
  447. int res = 0;
  448. char *errmsg;
  449. ao2_lock(db);
  450. if (sqlite3_exec(db->handle, sql, callback, arg, &errmsg) != SQLITE_OK) {
  451. ast_log(LOG_WARNING, "Could not execute '%s': %s\n", sql, errmsg);
  452. sqlite3_free(errmsg);
  453. res = -1;
  454. } else {
  455. res = sqlite3_changes(db->handle);
  456. }
  457. ao2_unlock(db);
  458. if (sync) {
  459. db_sync(db);
  460. }
  461. return res;
  462. }
  463. /*! Exeute an SQL statement give the database name
  464. *
  465. * \retval -1 ERROR
  466. * \retval > -1 Number of rows changed
  467. */
  468. static int realtime_sqlite3_execute(const char *database, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync)
  469. {
  470. struct realtime_sqlite3_db *db;
  471. int res;
  472. if (!(db = find_database(database))) {
  473. ast_log(LOG_WARNING, "Could not find database: %s\n", database);
  474. return -1;
  475. }
  476. res = realtime_sqlite3_execute_handle(db, sql, callback, arg, sync);
  477. ao2_ref(db, -1);
  478. return res;
  479. }
  480. /*! \note It is important that the COL_* enum matches the order of the columns selected in static_sql */
  481. static const char *static_sql = "SELECT category, var_name, var_val FROM \"%q\" WHERE filename = %Q AND commented = 0 ORDER BY cat_metric ASC, var_metric ASC";
  482. enum {
  483. COL_CATEGORY,
  484. COL_VAR_NAME,
  485. COL_VAR_VAL,
  486. COL_COLUMNS,
  487. };
  488. static int static_realtime_cb(void *arg, int num_columns, char **values, char **columns)
  489. {
  490. struct cfg_entry_args *args = arg;
  491. struct ast_variable *var;
  492. if (!strcmp(values[COL_VAR_NAME], "#include")) {
  493. struct ast_config *cfg;
  494. char *val;
  495. val = values[COL_VAR_VAL];
  496. if (!(cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked))) {
  497. ast_log(LOG_WARNING, "Unable to include %s\n", val);
  498. return SQLITE_ABORT;
  499. } else {
  500. args->cfg = cfg;
  501. return 0;
  502. }
  503. }
  504. if (!args->cat_name || strcmp(args->cat_name, values[COL_CATEGORY])) {
  505. if (!(args->cat = ast_category_new(values[COL_CATEGORY], "", 99999))) {
  506. ast_log(LOG_WARNING, "Unable to allocate category\n");
  507. return SQLITE_ABORT;
  508. }
  509. ast_free(args->cat_name);
  510. if (!(args->cat_name = ast_strdup(values[COL_CATEGORY]))) {
  511. ast_category_destroy(args->cat);
  512. return SQLITE_ABORT;
  513. }
  514. ast_category_append(args->cfg, args->cat);
  515. }
  516. if (!(var = ast_variable_new(values[COL_VAR_NAME], values[COL_VAR_VAL], ""))) {
  517. ast_log(LOG_WARNING, "Unable to allocate variable\n");
  518. return SQLITE_ABORT;
  519. }
  520. ast_variable_append(args->cat, var);
  521. return 0;
  522. }
  523. /*! \brief Realtime callback for static realtime
  524. * \return ast_config on success, NULL on failure
  525. */
  526. static struct ast_config *realtime_sqlite3_load(const char *database, const char *table, const char *configfile, struct ast_config *config, struct ast_flags flags, const char *suggested_include_file, const char *who_asked)
  527. {
  528. char *sql;
  529. struct cfg_entry_args args;
  530. if (ast_strlen_zero(table)) {
  531. ast_log(LOG_WARNING, "Must have a table to query!\n");
  532. return NULL;
  533. }
  534. if (!(sql = sqlite3_mprintf(static_sql, table, configfile))) {
  535. ast_log(LOG_WARNING, "Couldn't allocate query\n");
  536. return NULL;
  537. };
  538. args.cfg = config;
  539. args.cat = NULL;
  540. args.cat_name = NULL;
  541. args.flags = flags;
  542. args.who_asked = who_asked;
  543. realtime_sqlite3_execute(database, sql, static_realtime_cb, &args, 0);
  544. sqlite3_free(sql);
  545. return config;
  546. }
  547. /*! \brief Helper function for single and multi-row realtime load functions */
  548. static int realtime_sqlite3_helper(const char *database, const char *table, const struct ast_variable *fields, int is_multi, void *arg)
  549. {
  550. struct ast_str *sql;
  551. const struct ast_variable *field;
  552. int first = 1;
  553. if (ast_strlen_zero(table)) {
  554. ast_log(LOG_WARNING, "Must have a table to query!\n");
  555. return -1;
  556. }
  557. if (!(sql = ast_str_create(128))) {
  558. return -1;
  559. }
  560. for (field = fields; field; field = field->next) {
  561. if (first) {
  562. ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s %s", sqlite3_escape_table(table),
  563. sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
  564. first = 0;
  565. } else {
  566. ast_str_append(&sql, 0, " AND %s %s", sqlite3_escape_column_op(field->name),
  567. sqlite3_escape_value(field->value));
  568. }
  569. }
  570. if (!is_multi) {
  571. ast_str_append(&sql, 0, "%s", " LIMIT 1");
  572. }
  573. if (realtime_sqlite3_execute(database, ast_str_buffer(sql), is_multi ? append_row_to_cfg : row_to_varlist, arg, 0) < 0) {
  574. ast_free(sql);
  575. return -1;
  576. }
  577. ast_free(sql);
  578. return 0;
  579. }
  580. /*! \brief Realtime callback for a single row query
  581. * \return ast_variable list for single result on success, NULL on empty/failure
  582. */
  583. static struct ast_variable *realtime_sqlite3(const char *database, const char *table, const struct ast_variable *fields)
  584. {
  585. struct ast_variable *result_row = NULL;
  586. realtime_sqlite3_helper(database, table, fields, 0, &result_row);
  587. return result_row;
  588. }
  589. /*! \brief Realtime callback for a multi-row query
  590. * \return ast_config containing possibly many results on success, NULL on empty/failure
  591. */
  592. static struct ast_config *realtime_sqlite3_multi(const char *database, const char *table, const struct ast_variable *fields)
  593. {
  594. struct ast_config *cfg;
  595. if (!(cfg = ast_config_new())) {
  596. return NULL;
  597. }
  598. if (realtime_sqlite3_helper(database, table, fields, 1, cfg)) {
  599. ast_config_destroy(cfg);
  600. return NULL;
  601. }
  602. return cfg;
  603. }
  604. /*! \brief Realtime callback for updating a row based on a single criteria
  605. * \return Number of rows affected or -1 on error
  606. */
  607. static int realtime_sqlite3_update(const char *database, const char *table, const char *keyfield, const char *entity, const struct ast_variable *fields)
  608. {
  609. struct ast_str *sql;
  610. const struct ast_variable *field;
  611. int first = 1, res;
  612. if (ast_strlen_zero(table)) {
  613. ast_log(LOG_WARNING, "Must have a table to query!\n");
  614. return -1;
  615. }
  616. if (!(sql = ast_str_create(128))) {
  617. return -1;
  618. }
  619. for (field = fields; field; field = field->next) {
  620. if (first) {
  621. ast_str_set(&sql, 0, "UPDATE %s SET %s = %s",
  622. sqlite3_escape_table(table), sqlite3_escape_column(field->name), sqlite3_escape_value(field->value));
  623. first = 0;
  624. } else {
  625. ast_str_append(&sql, 0, ", %s = %s", sqlite3_escape_column(field->name), sqlite3_escape_value(field->value));
  626. }
  627. }
  628. ast_str_append(&sql, 0, " WHERE %s %s", sqlite3_escape_column_op(keyfield), sqlite3_escape_value(entity));
  629. res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
  630. ast_free(sql);
  631. return res;
  632. }
  633. /*! \brief Realtime callback for updating a row based on multiple criteria
  634. * \return Number of rows affected or -1 on error
  635. */
  636. static int realtime_sqlite3_update2(const char *database, const char *table, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields)
  637. {
  638. struct ast_str *sql;
  639. struct ast_str *where_clause;
  640. const struct ast_variable *field;
  641. int first = 1, res;
  642. if (ast_strlen_zero(table)) {
  643. ast_log(LOG_WARNING, "Must have a table to query!\n");
  644. return -1;
  645. }
  646. if (!(sql = ast_str_create(128))) {
  647. return -1;
  648. }
  649. if (!(where_clause = ast_str_create(128))) {
  650. ast_free(sql);
  651. return -1;
  652. }
  653. for (field = lookup_fields; field; field = field->next) {
  654. if (first) {
  655. ast_str_set(&where_clause, 0, " WHERE %s %s", sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
  656. first = 0;
  657. } else {
  658. ast_str_append(&where_clause, 0, " AND %s %s", sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
  659. }
  660. }
  661. first = 1;
  662. for (field = update_fields; field; field = field->next) {
  663. if (first) {
  664. ast_str_set(&sql, 0, "UPDATE %s SET %s = %s", sqlite3_escape_table(table), sqlite3_escape_column(field->name), sqlite3_escape_value(field->value));
  665. first = 0;
  666. } else {
  667. ast_str_append(&sql, 0, ", %s = %s", sqlite3_escape_column(field->name), sqlite3_escape_value(field->value));
  668. }
  669. }
  670. ast_str_append(&sql, 0, "%s", ast_str_buffer(where_clause));
  671. res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
  672. ast_free(sql);
  673. ast_free(where_clause);
  674. return res;
  675. }
  676. /*! \brief Realtime callback for inserting a row
  677. * \return Number of rows affected or -1 on error
  678. */
  679. static int realtime_sqlite3_store(const char *database, const char *table, const struct ast_variable *fields)
  680. {
  681. struct ast_str *sql, *values;
  682. const struct ast_variable *field;
  683. int first = 1, res;
  684. if (ast_strlen_zero(table)) {
  685. ast_log(LOG_WARNING, "Must have a table to query!\n");
  686. return -1;
  687. }
  688. if (!(sql = ast_str_create(128))) {
  689. return -1;
  690. }
  691. if (!(values = ast_str_create(128))) {
  692. ast_free(sql);
  693. return -1;
  694. }
  695. for (field = fields; field; field = field->next) {
  696. if (first) {
  697. ast_str_set(&sql, 0, "INSERT INTO %s (%s", sqlite3_escape_table(table), sqlite3_escape_column(field->name));
  698. ast_str_set(&values, 0, ") VALUES (%s", sqlite3_escape_value(field->value));
  699. first = 0;
  700. } else {
  701. ast_str_append(&sql, 0, ", %s", sqlite3_escape_column(field->name));
  702. ast_str_append(&values, 0, ", %s", sqlite3_escape_value(field->value));
  703. }
  704. }
  705. ast_str_append(&sql, 0, "%s)", ast_str_buffer(values));
  706. res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
  707. ast_free(sql);
  708. ast_free(values);
  709. return res;
  710. }
  711. /*! \brief Realtime callback for deleting a row
  712. * \return Number of rows affected or -1 on error
  713. */
  714. static int realtime_sqlite3_destroy(const char *database, const char *table, const char *keyfield, const char *entity, const struct ast_variable *fields)
  715. {
  716. struct ast_str *sql;
  717. const struct ast_variable *field;
  718. int first = 1, res;
  719. if (ast_strlen_zero(table)) {
  720. ast_log(LOG_WARNING, "Must have a table to query!\n");
  721. return -1;
  722. }
  723. if (!(sql = ast_str_create(128))) {
  724. return -1;
  725. }
  726. for (field = fields; field; field = field->next) {
  727. if (first) {
  728. ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s %s", sqlite3_escape_table(table),
  729. sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
  730. first = 0;
  731. } else {
  732. ast_str_append(&sql, 0, " AND %s %s", sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
  733. }
  734. }
  735. res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
  736. ast_free(sql);
  737. return res;
  738. }
  739. /*! \brief Convert Asterisk realtime types to SQLite 3 types
  740. * \note SQLite 3 has NULL, INTEGER, REAL, TEXT, and BLOB types. Any column other than
  741. * an INTEGER PRIMARY KEY will actually store any kind of data due to its dynamic
  742. * typing. When we create columns, we'll go ahead and use these base types instead
  743. * of messing with column widths, etc. */
  744. static const char *get_sqlite_column_type(int type)
  745. {
  746. switch(type) {
  747. case RQ_INTEGER1 :
  748. case RQ_UINTEGER1 :
  749. case RQ_INTEGER2 :
  750. case RQ_UINTEGER2 :
  751. case RQ_INTEGER3 :
  752. case RQ_UINTEGER3 :
  753. case RQ_INTEGER4 :
  754. case RQ_UINTEGER4 :
  755. case RQ_INTEGER8 :
  756. return "INTEGER";
  757. case RQ_UINTEGER8 : /* SQLite3 stores INTEGER as signed 8-byte */
  758. case RQ_CHAR :
  759. case RQ_DATE :
  760. case RQ_DATETIME :
  761. return "TEXT";
  762. case RQ_FLOAT :
  763. return "REAL";
  764. default :
  765. return "TEXT";
  766. }
  767. return "TEXT";
  768. }
  769. /*! \brief Create a table if ast_realtime_require shows that we are configured to handle the data
  770. */
  771. static int handle_missing_table(struct realtime_sqlite3_db *db, const char *table, va_list ap)
  772. {
  773. const char *column;
  774. int type, first = 1, res;
  775. size_t sz;
  776. struct ast_str *sql;
  777. if (!(sql = ast_str_create(128))) {
  778. return -1;
  779. }
  780. while ((column = va_arg(ap, typeof(column))) && (type = va_arg(ap, typeof(type))) && (sz = va_arg(ap, typeof(sz)))) {
  781. if (first) {
  782. ast_str_set(&sql, 0, "CREATE TABLE IF NOT EXISTS %s (%s %s", sqlite3_escape_table(table),
  783. sqlite3_escape_column(column), get_sqlite_column_type(type));
  784. first = 0;
  785. } else {
  786. ast_str_append(&sql, 0, ", %s %s", sqlite3_escape_column(column), get_sqlite_column_type(type));
  787. }
  788. }
  789. ast_str_append(&sql, 0, ")");
  790. res = realtime_sqlite3_execute_handle(db, ast_str_buffer(sql), NULL, NULL, 1) < 0 ? -1 : 0;
  791. ast_free(sql);
  792. return res;
  793. }
  794. /*! \brief If ast_realtime_require sends info about a column we don't have, create it
  795. */
  796. static int handle_missing_column(struct realtime_sqlite3_db *db, const char *table, const char *column, int type, size_t sz)
  797. {
  798. char *sql;
  799. const char *sqltype = get_sqlite_column_type(type);
  800. int res;
  801. if (db->requirements == REALTIME_SQLITE3_REQ_WARN) {
  802. ast_log(LOG_WARNING, "Missing column '%s' of type '%s' in %s.%s\n", column, sqltype, db->name, table);
  803. return -1;
  804. } else if (db->requirements == REALTIME_SQLITE3_REQ_CHAR) {
  805. sqltype = "TEXT";
  806. }
  807. if (!(sql = sqlite3_mprintf("ALTER TABLE \"%q\" ADD COLUMN \"%q\" %s", table, column, sqltype))) {
  808. return -1;
  809. }
  810. if (!(res = (realtime_sqlite3_execute_handle(db, sql, NULL, NULL, 1) < 0 ? -1 : 0))) {
  811. ast_log(LOG_NOTICE, "Creating column '%s' type %s for table %s\n", column, sqltype, table);
  812. }
  813. sqlite3_free(sql);
  814. return res;
  815. }
  816. static int str_hash_fn(const void *obj, const int flags)
  817. {
  818. return ast_str_hash((const char *) obj);
  819. }
  820. static int str_cmp_fn(void *obj, void *arg, int flags) {
  821. return !strcasecmp((const char *) obj, (const char *) arg);
  822. }
  823. /*! \brief Callback for creating a hash of column names for comparison in realtime_sqlite3_require
  824. */
  825. static int add_column_name(void *arg, int num_columns, char **values, char **columns)
  826. {
  827. char *column;
  828. struct ao2_container *cnames = arg;
  829. if (!(column = ao2_alloc(strlen(values[1]) + 1, NULL))) {
  830. return -1;
  831. }
  832. strcpy(column, values[1]);
  833. ao2_link(cnames, column);
  834. ao2_ref(column, -1);
  835. return 0;
  836. }
  837. /*! \brief Callback for ast_realtime_require
  838. * \retval 0 Required fields met specified standards
  839. * \retval -1 One or more fields was missing or insufficient
  840. */
  841. static int realtime_sqlite3_require(const char *database, const char *table, va_list ap)
  842. {
  843. const char *column;
  844. char *sql;
  845. int type;
  846. int res;
  847. size_t sz;
  848. struct ao2_container *columns;
  849. struct realtime_sqlite3_db *db;
  850. /* SQLite3 columns are dynamically typed, with type affinity. Built-in functions will
  851. * return the results as char * anyway. The only field that that cannot contain text
  852. * data is an INTEGER PRIMARY KEY, which must be a 64-bit signed integer. So, for
  853. * the purposes here we really only care whether the column exists and not what its
  854. * type or length is. */
  855. if (ast_strlen_zero(table)) {
  856. ast_log(LOG_WARNING, "Must have a table to query!\n");
  857. return -1;
  858. }
  859. if (!(db = find_database(database))) {
  860. return -1;
  861. }
  862. if (!(columns = ao2_container_alloc(31, str_hash_fn, str_cmp_fn))) {
  863. unref_db(&db);
  864. return -1;
  865. }
  866. if (!(sql = sqlite3_mprintf("PRAGMA table_info(\"%q\")", table))) {
  867. unref_db(&db);
  868. ao2_ref(columns, -1);
  869. return -1;
  870. }
  871. if ((res = realtime_sqlite3_execute_handle(db, sql, add_column_name, columns, 0)) < 0) {
  872. unref_db(&db);
  873. ao2_ref(columns, -1);
  874. sqlite3_free(sql);
  875. return -1;
  876. } else if (res == 0) {
  877. /* Table does not exist */
  878. sqlite3_free(sql);
  879. res = handle_missing_table(db, table, ap);
  880. ao2_ref(columns, -1);
  881. unref_db(&db);
  882. return res;
  883. }
  884. sqlite3_free(sql);
  885. while ((column = va_arg(ap, typeof(column))) && (type = va_arg(ap, typeof(type))) && (sz = va_arg(ap, typeof(sz)))) {
  886. char *found;
  887. if (!(found = ao2_find(columns, column, OBJ_POINTER | OBJ_UNLINK))) {
  888. if (handle_missing_column(db, table, column, type, sz)) {
  889. unref_db(&db);
  890. ao2_ref(columns, -1);
  891. return -1;
  892. }
  893. } else {
  894. ao2_ref(found, -1);
  895. }
  896. }
  897. ao2_ref(columns, -1);
  898. unref_db(&db);
  899. return 0;
  900. }
  901. /*! \brief Callback for clearing any cached info
  902. * \note We don't currently cache anything
  903. * \retval 0 If any cache was purged
  904. * \retval -1 If no cache was found
  905. */
  906. static int realtime_sqlite3_unload(const char *database, const char *table)
  907. {
  908. /* We currently do no caching */
  909. return -1;
  910. }
  911. /*! \brief Parse the res_config_sqlite3 config file
  912. */
  913. static int parse_config(int reload)
  914. {
  915. struct ast_config *config;
  916. struct ast_flags config_flags = { CONFIG_FLAG_NOREALTIME | (reload ? CONFIG_FLAG_FILEUNCHANGED : 0) };
  917. static const char *config_filename = "res_config_sqlite3.conf";
  918. config = ast_config_load(config_filename, config_flags);
  919. if (config == CONFIG_STATUS_FILEUNCHANGED) {
  920. ast_debug(1, "%s was unchanged, skipping parsing\n", config_filename);
  921. return 0;
  922. }
  923. ast_mutex_lock(&config_lock);
  924. if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
  925. ast_log(LOG_ERROR, "%s config file '%s'\n",
  926. config == CONFIG_STATUS_FILEMISSING ? "Missing" : "Invalid", config_filename);
  927. } else {
  928. const char *cat;
  929. struct realtime_sqlite3_db *db;
  930. mark_all_databases_dirty();
  931. for (cat = ast_category_browse(config, NULL); cat; cat = ast_category_browse(config, cat)) {
  932. if (!strcasecmp(cat, "general")) {
  933. continue;
  934. }
  935. if (!(db = find_database(cat))) {
  936. if (!(db = new_realtime_sqlite3_db(config, cat))) {
  937. ast_log(LOG_WARNING, "Could not allocate new db for '%s' - skipping.\n", cat);
  938. continue;
  939. }
  940. if (db_open(db)) {
  941. unref_db(&db);
  942. continue;
  943. }
  944. db_start_batch(db);
  945. ao2_link(databases, db);
  946. unref_db(&db);
  947. } else {
  948. if (update_realtime_sqlite3_db(db, config, cat)) {
  949. unref_db(&db);
  950. continue;
  951. }
  952. unref_db(&db);
  953. }
  954. }
  955. unlink_dirty_databases();
  956. }
  957. ast_mutex_unlock(&config_lock);
  958. ast_config_destroy(config);
  959. return 0;
  960. }
  961. static int reload(void)
  962. {
  963. parse_config(1);
  964. return 0;
  965. }
  966. static int unload_module(void)
  967. {
  968. ast_mutex_lock(&config_lock);
  969. ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA | OBJ_UNLINK, stop_batch_cb, NULL);
  970. ao2_ref(databases, -1);
  971. databases = NULL;
  972. ast_config_engine_deregister(&sqlite3_config_engine);
  973. ast_mutex_unlock(&config_lock);
  974. return 0;
  975. }
  976. /*!
  977. * \brief Load the module
  978. *
  979. * Module loading including tests for configuration or dependencies.
  980. * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
  981. * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
  982. * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
  983. * configuration file or other non-critical problem return
  984. * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
  985. */
  986. static int load_module(void)
  987. {
  988. if (!((databases = ao2_container_alloc(DB_BUCKETS, db_hash_fn, db_cmp_fn)))) {
  989. return AST_MODULE_LOAD_FAILURE;
  990. }
  991. if (parse_config(0)) {
  992. ao2_ref(databases, -1);
  993. return AST_MODULE_LOAD_FAILURE;
  994. }
  995. if (!(ast_config_engine_register(&sqlite3_config_engine))) {
  996. ast_log(LOG_ERROR, "The config API must have changed, this shouldn't happen.\n");
  997. ao2_ref(databases, -1);
  998. return AST_MODULE_LOAD_FAILURE;
  999. }
  1000. return AST_MODULE_LOAD_SUCCESS;
  1001. }
  1002. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "SQLite 3 realtime config engine",
  1003. .support_level = AST_MODULE_SUPPORT_CORE,
  1004. .load = load_module,
  1005. .unload = unload_module,
  1006. .reload = reload,
  1007. .load_pri = AST_MODPRI_REALTIME_DRIVER,
  1008. );