res_config_sqlite3.c 37 KB

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