2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2006, Proformatique
6 * Written by Richard Braun <rbraun@proformatique.com>
8 * Based on res_sqlite3 by Anthony Minessale II,
9 * and res_config_mysql by Matthew Boehm
11 * See http://www.asterisk.org for more information about
12 * the Asterisk project. Please do not directly contact
13 * any of the maintainers of this project for assistance;
14 * the project provides a web site, mailing lists and IRC
15 * channels for your use.
17 * This program is free software, distributed under the terms of
18 * the GNU General Public License Version 2. See the LICENSE file
19 * at the top of the source tree.
23 * \page res_config_sqlite
25 * \section intro_sec Presentation
27 * res_config_sqlite is a module for the Asterisk Open Source PBX to
28 * support SQLite 2 databases. It can be used to fetch configuration
29 * from a database (static configuration files and/or using the Asterisk
30 * RealTime Architecture - ARA). It can also be used to log CDR entries.
31 * Note that Asterisk already comes with a module named cdr_sqlite.
32 * There are two reasons for including it in res_config_sqlite:
33 * the first is that rewriting it was a training to learn how to write a
34 * simple module for Asterisk, the other is to have the same database open for
35 * all kinds of operations, which improves reliability and performance.
37 * \section conf_sec Configuration
39 * The main configuration file is res_config_sqlite.conf. It must be readable or
40 * res_config_sqlite will fail to start. It is suggested to use the sample file
41 * in this package as a starting point. The file has only one section
42 * named <code>general</code>. Here are the supported parameters :
45 * <dt><code>dbfile</code></dt>
46 * <dd>The absolute path to the SQLite database (the file can be non existent,
47 * res_config_sqlite will create it if it has the appropriate rights)</dd>
48 * <dt><code>config_table</code></dt>
49 * <dd>The table used for static configuration</dd>
50 * <dt><code>cdr_table</code></dt>
51 * <dd>The table used to store CDR entries (if ommitted, CDR support is
55 * To use res_config_sqlite for static and/or RealTime configuration, refer to the
56 * Asterisk documentation. The file tables.sql can be used to create the
59 * \section status_sec Driver status
61 * The CLI command <code>show sqlite status</code> returns status information
62 * about the running driver.
64 * \section credits_sec Credits
66 * res_config_sqlite was developed by Richard Braun at the Proformatique company.
71 * \brief res_config_sqlite module.
75 <depend>sqlite</depend>
79 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
83 #include "asterisk/app.h"
84 #include "asterisk/pbx.h"
85 #include "asterisk/cdr.h"
86 #include "asterisk/cli.h"
87 #include "asterisk/lock.h"
88 #include "asterisk/config.h"
89 #include "asterisk/module.h"
90 #include "asterisk/linkedlists.h"
92 #define MACRO_BEGIN do {
93 #define MACRO_END } while (0)
95 #define RES_CONFIG_SQLITE_NAME "res_config_sqlite"
96 #define RES_CONFIG_SQLITE_DRIVER "sqlite"
97 #define RES_CONFIG_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
98 #define RES_CONFIG_SQLITE_CONF_FILE "res_config_sqlite.conf"
101 RES_CONFIG_SQLITE_CONFIG_ID,
102 RES_CONFIG_SQLITE_CONFIG_CAT_METRIC,
103 RES_CONFIG_SQLITE_CONFIG_VAR_METRIC,
104 RES_CONFIG_SQLITE_CONFIG_COMMENTED,
105 RES_CONFIG_SQLITE_CONFIG_FILENAME,
106 RES_CONFIG_SQLITE_CONFIG_CATEGORY,
107 RES_CONFIG_SQLITE_CONFIG_VAR_NAME,
108 RES_CONFIG_SQLITE_CONFIG_VAR_VAL,
109 RES_CONFIG_SQLITE_CONFIG_COLUMNS,
112 #define SET_VAR(config, to, from) \
116 __error = set_var(&to, #to, from->value); \
119 ast_config_destroy(config); \
126 * Maximum number of loops before giving up executing a query. Calls to
127 * sqlite_xxx() functions which can return SQLITE_BUSY
128 * are enclosed by RES_CONFIG_SQLITE_BEGIN and RES_CONFIG_SQLITE_END, e.g.
133 * RES_CONFIG_SQLITE_BEGIN
134 * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
135 * RES_CONFIG_SQLITE_END(error)
141 #define RES_CONFIG_SQLITE_MAX_LOOPS 10
144 * Macro used before executing a query.
146 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
148 #define RES_CONFIG_SQLITE_BEGIN \
152 for (__i = 0; __i < RES_CONFIG_SQLITE_MAX_LOOPS; __i++) {
155 * Macro used after executing a query.
157 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
159 #define RES_CONFIG_SQLITE_END(error) \
160 if (error != SQLITE_BUSY) \
167 * Structure sent to the SQLite callback function for static configuration.
169 * \see add_cfg_entry()
171 struct cfg_entry_args {
172 struct ast_config *cfg;
173 struct ast_category *cat;
175 struct ast_flags flags;
176 const char *who_asked;
180 * Structure sent to the SQLite callback function for RealTime configuration.
182 * \see add_rt_cfg_entry()
184 struct rt_cfg_entry_args {
185 struct ast_variable *var;
186 struct ast_variable *last;
190 * Structure sent to the SQLite callback function for RealTime configuration
191 * (realtime_multi_handler()).
193 * \see add_rt_multi_cfg_entry()
195 struct rt_multi_cfg_entry_args {
196 struct ast_config *cfg;
201 * \brief Allocate a variable.
202 * \param var the address of the variable to set (it will be allocated)
203 * \param name the name of the variable (for error handling)
204 * \param value the value to store in var
205 * \retval 0 on success
206 * \retval 1 if an allocation error occurred
208 static int set_var(char **var, const char *name, const char *value);
211 * \brief Load the configuration file.
212 * \see unload_config()
214 * This function sets dbfile, config_table, and cdr_table. It calls
215 * check_vars() before returning, and unload_config() if an error occurred.
217 * \retval 0 on success
218 * \retval 1 if an error occurred
220 static int load_config(void);
223 * \brief Free resources related to configuration.
226 static void unload_config(void);
229 * \brief Asterisk callback function for CDR support.
230 * \param cdr the CDR entry Asterisk sends us.
232 * Asterisk will call this function each time a CDR entry must be logged if
233 * CDR support is enabled.
235 * \retval 0 on success
236 * \retval 1 if an error occurred
238 static int cdr_handler(struct ast_cdr *cdr);
241 * \brief SQLite callback function for static configuration.
243 * This function is passed to the SQLite engine as a callback function to
244 * parse a row and store it in a struct ast_config object. It relies on
245 * resulting rows being sorted by category.
247 * \param arg a pointer to a struct cfg_entry_args object
248 * \param argc number of columns
249 * \param argv values in the row
250 * \param columnNames names and types of the columns
251 * \retval 0 on success
252 * \retval 1 if an error occurred
253 * \see cfg_entry_args
254 * \see sql_get_config_table
255 * \see config_handler()
257 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
260 * \brief Asterisk callback function for static configuration.
262 * Asterisk will call this function when it loads its static configuration,
263 * which usually happens at startup and reload.
265 * \param database the database to use (ignored)
266 * \param table the table to use
267 * \param file the file to load from the database
268 * \param cfg the struct ast_config object to use when storing variables
269 * \param flags Optional flags. Not used.
270 * \param suggested_incl suggest include.
272 * \retval NULL if an error occurred
273 * \see add_cfg_entry()
275 static struct ast_config * config_handler(const char *database, const char *table, const char *file,
276 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked);
279 * \brief Helper function to parse a va_list object into 2 dynamic arrays of
280 * strings, parameters and values.
282 * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
283 * arguments will be extracted to create 2 arrays:
286 * <li>params : param1 param2 param3 ...</li>
287 * <li>vals : val1 val2 val3 ...</li>
290 * The address of these arrays are stored in params_ptr and vals_ptr. It
291 * is the responsibility of the caller to release the memory of these arrays.
292 * It is considered an error that va_list has a null or odd number of strings.
294 * \param ap the va_list object to parse
295 * \param params_ptr where the address of the params array is stored
296 * \param vals_ptr where the address of the vals array is stored
297 * \retval the number of elements in the arrays (which have the same size).
298 * \retval 0 if an error occurred.
300 static size_t get_params(va_list ap, const char ***params_ptr,
301 const char ***vals_ptr);
304 * \brief SQLite callback function for RealTime configuration.
306 * This function is passed to the SQLite engine as a callback function to
307 * parse a row and store it in a linked list of struct ast_variable objects.
309 * \param arg a pointer to a struct rt_cfg_entry_args object
310 * \param argc number of columns
311 * \param argv values in the row
312 * \param columnNames names and types of the columns
313 * \retval 0 on success.
314 * \retval 1 if an error occurred.
315 * \see rt_cfg_entry_args
316 * \see realtime_handler()
318 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
322 * \brief Asterisk callback function for RealTime configuration.
324 * Asterisk will call this function each time it requires a variable
325 * through the RealTime architecture. ap is a list of parameters and
326 * values used to find a specific row, e.g one parameter "name" and
327 * one value "123" so that the SQL query becomes <code>SELECT * FROM
328 * table WHERE name = '123';</code>.
330 * \param database the database to use (ignored)
331 * \param table the table to use
332 * \param ap list of parameters and values to match
334 * \retval a linked list of struct ast_variable objects
335 * \retval NULL if an error occurred
336 * \see add_rt_cfg_entry()
338 static struct ast_variable * realtime_handler(const char *database,
339 const char *table, va_list ap);
342 * \brief SQLite callback function for RealTime configuration.
344 * This function performs the same actions as add_rt_cfg_entry() except
345 * that the rt_multi_cfg_entry_args structure is designed to store
346 * categories in addition to variables.
348 * \param arg a pointer to a struct rt_multi_cfg_entry_args object
349 * \param argc number of columns
350 * \param argv values in the row
351 * \param columnNames names and types of the columns
352 * \retval 0 on success.
353 * \retval 1 if an error occurred.
354 * \see rt_multi_cfg_entry_args
355 * \see realtime_multi_handler()
357 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
361 * \brief Asterisk callback function for RealTime configuration.
363 * This function performs the same actions as realtime_handler() except
364 * that it can store variables per category, and can return several
367 * \param database the database to use (ignored)
368 * \param table the table to use
369 * \param ap list of parameters and values to match
370 * \retval a struct ast_config object storing categories and variables.
371 * \retval NULL if an error occurred.
373 * \see add_rt_multi_cfg_entry()
375 static struct ast_config * realtime_multi_handler(const char *database,
376 const char *table, va_list ap);
379 * \brief Asterisk callback function for RealTime configuration (variable
382 * Asterisk will call this function each time a variable has been modified
383 * internally and must be updated in the backend engine. keyfield and entity
384 * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
385 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
386 * same format as the other realtime functions.
388 * \param database the database to use (ignored)
389 * \param table the table to use
390 * \param keyfield the column of the matching cell
391 * \param entity the value of the matching cell
392 * \param ap list of parameters and new values to update in the database
393 * \retval the number of affected rows.
394 * \retval -1 if an error occurred.
396 static int realtime_update_handler(const char *database, const char *table,
397 const char *keyfield, const char *entity, va_list ap);
400 * \brief Asterisk callback function for RealTime configuration (variable
403 * Asterisk will call this function each time a variable has been created
404 * internally and must be stored in the backend engine.
405 * are used to find the row to update, e.g. ap is a list of parameters and
406 * values with the same format as the other realtime functions.
408 * \param database the database to use (ignored)
409 * \param table the table to use
410 * \param ap list of parameters and new values to insert into the database
411 * \retval the rowid of inserted row.
412 * \retval -1 if an error occurred.
414 static int realtime_store_handler(const char *database, const char *table,
418 * \brief Asterisk callback function for RealTime configuration (destroys
421 * Asterisk will call this function each time a variable has been destroyed
422 * internally and must be removed from the backend engine. keyfield and entity
423 * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
424 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
425 * same format as the other realtime functions.
427 * \param database the database to use (ignored)
428 * \param table the table to use
429 * \param keyfield the column of the matching cell
430 * \param entity the value of the matching cell
431 * \param ap list of additional parameters for cell matching
432 * \retval the number of affected rows.
433 * \retval -1 if an error occurred.
435 static int realtime_destroy_handler(const char *database, const char *table,
436 const char *keyfield, const char *entity, va_list ap);
439 * \brief Asterisk callback function for the CLI status command.
441 * \param e CLI command
443 * \param a CLI argument list
444 * \return RESULT_SUCCESS
446 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
447 static char *handle_cli_sqlite_show_tables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
449 static int realtime_require_handler(const char *database, const char *table, va_list ap);
450 static int realtime_unload_handler(const char *unused, const char *tablename);
452 /*! The SQLite database object. */
455 /*! Set to 1 if CDR support is enabled. */
458 /*! Set to 1 if the CDR callback function was registered. */
459 static int cdr_registered;
461 /*! Set to 1 if the CLI status command callback function was registered. */
462 static int cli_status_registered;
464 /*! The path of the database file. */
467 /*! The name of the static configuration table. */
468 static char *config_table;
470 /*! The name of the table used to store CDR entries. */
471 static char *cdr_table;
474 * The structure specifying all callback functions used by Asterisk for static
475 * and RealTime configuration.
477 static struct ast_config_engine sqlite_engine =
479 .name = RES_CONFIG_SQLITE_DRIVER,
480 .load_func = config_handler,
481 .realtime_func = realtime_handler,
482 .realtime_multi_func = realtime_multi_handler,
483 .store_func = realtime_store_handler,
484 .destroy_func = realtime_destroy_handler,
485 .update_func = realtime_update_handler,
486 .require_func = realtime_require_handler,
487 .unload_func = realtime_unload_handler,
491 * The mutex used to prevent simultaneous access to the SQLite database.
493 AST_MUTEX_DEFINE_STATIC(mutex);
496 * Structure containing details and callback functions for the CLI status
499 static struct ast_cli_entry cli_status[] = {
500 AST_CLI_DEFINE(handle_cli_show_sqlite_status, "Show status information about the SQLite 2 driver"),
501 AST_CLI_DEFINE(handle_cli_sqlite_show_tables, "Cached table information about the SQLite 2 driver"),
504 struct sqlite_cache_columns {
507 unsigned char isint; /*!< By definition, only INTEGER PRIMARY KEY is an integer; everything else is a string. */
508 AST_RWLIST_ENTRY(sqlite_cache_columns) list;
511 struct sqlite_cache_tables {
513 AST_RWLIST_HEAD(_columns, sqlite_cache_columns) columns;
514 AST_RWLIST_ENTRY(sqlite_cache_tables) list;
517 static AST_RWLIST_HEAD_STATIC(sqlite_tables, sqlite_cache_tables);
520 * Taken from Asterisk 1.2 cdr_sqlite.so.
523 /*! SQL query format to create the CDR table if non existent. */
524 static char *sql_create_cdr_table =
525 "CREATE TABLE '%q' (\n"
527 " clid VARCHAR(80) NOT NULL DEFAULT '',\n"
528 " src VARCHAR(80) NOT NULL DEFAULT '',\n"
529 " dst VARCHAR(80) NOT NULL DEFAULT '',\n"
530 " dcontext VARCHAR(80) NOT NULL DEFAULT '',\n"
531 " channel VARCHAR(80) NOT NULL DEFAULT '',\n"
532 " dstchannel VARCHAR(80) NOT NULL DEFAULT '',\n"
533 " lastapp VARCHAR(80) NOT NULL DEFAULT '',\n"
534 " lastdata VARCHAR(80) NOT NULL DEFAULT '',\n"
535 " start DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
536 " answer DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
537 " end DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
538 " duration INT(11) NOT NULL DEFAULT 0,\n"
539 " billsec INT(11) NOT NULL DEFAULT 0,\n"
540 " disposition VARCHAR(45) NOT NULL DEFAULT '',\n"
541 " amaflags INT(11) NOT NULL DEFAULT 0,\n"
542 " accountcode VARCHAR(20) NOT NULL DEFAULT '',\n"
543 " uniqueid VARCHAR(32) NOT NULL DEFAULT '',\n"
544 " userfield VARCHAR(255) NOT NULL DEFAULT '',\n"
545 " PRIMARY KEY (id)\n"
549 * SQL query format to describe the table structure
551 static char *sql_table_structure =
552 "SELECT sql FROM sqlite_master WHERE type='table' AND tbl_name='%s'";
555 * SQL query format to fetch the static configuration of a file.
556 * Rows must be sorted by category.
558 * \see add_cfg_entry()
560 static const char *sql_get_config_table =
563 " WHERE filename = '%q' AND commented = 0"
564 " ORDER BY cat_metric ASC, var_metric ASC;";
566 static void free_table(struct sqlite_cache_tables *tblptr)
568 struct sqlite_cache_columns *col;
570 /* Obtain a write lock to ensure there are no read locks outstanding */
571 AST_RWLIST_WRLOCK(&(tblptr->columns));
572 while ((col = AST_RWLIST_REMOVE_HEAD(&(tblptr->columns), list))) {
575 AST_RWLIST_UNLOCK(&(tblptr->columns));
576 AST_RWLIST_HEAD_DESTROY(&(tblptr->columns));
580 static int find_table_cb(void *vtblptr, int argc, char **argv, char **columnNames)
582 struct sqlite_cache_tables *tblptr = vtblptr;
583 char *sql = ast_strdupa(argv[0]), *start, *end, *type, *remainder;
585 AST_DECLARE_APP_ARGS(fie,
586 AST_APP_ARG(ld)[100]; /* This means we support up to 100 columns per table */
588 struct sqlite_cache_columns *col;
590 /* This is really fun. We get to parse an SQL statement to figure out
591 * what columns are in the table.
593 if ((start = strchr(sql, '(')) && (end = strrchr(sql, ')'))) {
601 AST_STANDARD_APP_ARGS(fie, start);
602 for (i = 0; i < fie.argc; i++) {
603 fie.ld[i] = ast_skip_blanks(fie.ld[i]);
604 ast_debug(5, "Found field: %s\n", fie.ld[i]);
605 if (strncasecmp(fie.ld[i], "PRIMARY KEY", 11) == 0 && (start = strchr(fie.ld[i], '(')) && (end = strchr(fie.ld[i], ')'))) {
607 AST_RWLIST_TRAVERSE(&(tblptr->columns), col, list) {
608 if (strcasecmp(start + 1, col->name) == 0 && strcasestr(col->type, "INTEGER")) {
614 /* type delimiter could be any space character */
615 for (type = fie.ld[i]; *type > 32; type++);
617 type = ast_skip_blanks(type);
618 for (remainder = type; *remainder > 32; remainder++);
620 if (!(col = ast_calloc(1, sizeof(*col) + strlen(fie.ld[i]) + strlen(type) + 2))) {
623 col->name = (char *)col + sizeof(*col);
624 col->type = (char *)col + sizeof(*col) + strlen(fie.ld[i]) + 1;
625 strcpy(col->name, fie.ld[i]); /* SAFE */
626 strcpy(col->type, type); /* SAFE */
627 if (strcasestr(col->type, "INTEGER") && strcasestr(col->type, "PRIMARY KEY")) {
630 AST_LIST_INSERT_TAIL(&(tblptr->columns), col, list);
635 static struct sqlite_cache_tables *find_table(const char *tablename)
637 struct sqlite_cache_tables *tblptr;
639 char *sql, *errstr = NULL;
641 AST_RWLIST_RDLOCK(&sqlite_tables);
643 for (i = 0; i < 2; i++) {
644 AST_RWLIST_TRAVERSE(&sqlite_tables, tblptr, list) {
645 if (strcmp(tblptr->name, tablename) == 0) {
650 AST_RWLIST_RDLOCK(&(tblptr->columns));
651 AST_RWLIST_UNLOCK(&sqlite_tables);
656 AST_RWLIST_UNLOCK(&sqlite_tables);
657 AST_RWLIST_WRLOCK(&sqlite_tables);
661 /* Table structure not cached; build the structure now */
662 asprintf(&sql, sql_table_structure, tablename);
663 if (!(tblptr = ast_calloc(1, sizeof(*tblptr) + strlen(tablename) + 1))) {
664 AST_RWLIST_UNLOCK(&sqlite_tables);
665 ast_log(LOG_ERROR, "Memory error. Cannot cache table '%s'\n", tablename);
668 tblptr->name = (char *)tblptr + sizeof(*tblptr);
669 strcpy(tblptr->name, tablename); /* SAFE */
670 AST_RWLIST_HEAD_INIT(&(tblptr->columns));
672 ast_debug(1, "About to query table structure: %s\n", sql);
674 ast_mutex_lock(&mutex);
675 if ((err = sqlite_exec(db, sql, find_table_cb, tblptr, &errstr))) {
676 ast_mutex_unlock(&mutex);
677 ast_log(LOG_WARNING, "SQLite error %d: %s\n", err, errstr);
682 ast_mutex_unlock(&mutex);
684 if (AST_LIST_EMPTY(&(tblptr->columns))) {
689 AST_RWLIST_INSERT_TAIL(&sqlite_tables, tblptr, list);
690 AST_RWLIST_RDLOCK(&(tblptr->columns));
691 AST_RWLIST_UNLOCK(&sqlite_tables);
695 #define release_table(a) AST_RWLIST_UNLOCK(&((a)->columns))
697 static int set_var(char **var, const char *name, const char *value)
702 *var = ast_strdup(value);
705 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
712 static int check_vars(void)
715 ast_log(LOG_ERROR, "Required parameter undefined: dbfile\n");
719 use_cdr = (cdr_table != NULL);
724 static int load_config(void)
726 struct ast_config *config;
727 struct ast_variable *var;
729 struct ast_flags config_flags = { 0 };
731 config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
733 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
734 ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
738 for (var = ast_variable_browse(config, "general"); var; var = var->next) {
739 if (!strcasecmp(var->name, "dbfile"))
740 SET_VAR(config, dbfile, var);
741 else if (!strcasecmp(var->name, "config_table"))
742 SET_VAR(config, config_table, var);
743 else if (!strcasecmp(var->name, "cdr_table")) {
744 SET_VAR(config, cdr_table, var);
746 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
749 ast_config_destroy(config);
750 error = check_vars();
760 static void unload_config(void)
762 struct sqlite_cache_tables *tbl;
765 ast_free(config_table);
769 AST_RWLIST_WRLOCK(&sqlite_tables);
770 while ((tbl = AST_RWLIST_REMOVE_HEAD(&sqlite_tables, list))) {
773 AST_RWLIST_UNLOCK(&sqlite_tables);
776 static int cdr_handler(struct ast_cdr *cdr)
778 char *errormsg = NULL, *tmp, workspace[500];
780 struct sqlite_cache_tables *tbl = find_table(cdr_table);
781 struct sqlite_cache_columns *col;
782 struct ast_str *sql1 = ast_str_create(160), *sql2 = ast_str_create(16);
785 ast_log(LOG_WARNING, "No such table: %s\n", cdr_table);
789 ast_str_set(&sql1, 0, "INSERT INTO %s (", cdr_table);
790 ast_str_set(&sql2, 0, ") VALUES (");
792 AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
794 ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 1);
798 if (sscanf(tmp, "%d", &scannum) == 1) {
799 ast_str_append(&sql1, 0, "%s,", col->name);
800 ast_str_append(&sql2, 0, "%d,", scannum);
803 ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 0);
807 ast_str_append(&sql1, 0, "%s,", col->name);
808 tmp = sqlite_mprintf("%Q", tmp);
809 ast_str_append(&sql2, 0, "%s,", tmp);
815 sql1->str[--sql1->used] = '\0';
816 sql2->str[--sql2->used] = '\0';
817 ast_str_append(&sql1, 0, "%s)", sql2->str);
820 ast_debug(1, "SQL query: %s\n", sql1->str);
822 ast_mutex_lock(&mutex);
824 RES_CONFIG_SQLITE_BEGIN
825 error = sqlite_exec(db, sql1->str, NULL, NULL, &errormsg);
826 RES_CONFIG_SQLITE_END(error)
828 ast_mutex_unlock(&mutex);
833 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
834 sqlite_freemem(errormsg);
837 sqlite_freemem(errormsg);
842 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
844 struct cfg_entry_args *args;
845 struct ast_variable *var;
847 if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
848 ast_log(LOG_WARNING, "Corrupt table\n");
854 if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
855 struct ast_config *cfg;
858 val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
859 cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked);
862 ast_log(LOG_WARNING, "Unable to include %s\n", val);
870 if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
871 args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
874 ast_log(LOG_WARNING, "Unable to allocate category\n");
878 ast_free(args->cat_name);
879 args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
881 if (!args->cat_name) {
882 ast_category_destroy(args->cat);
886 ast_category_append(args->cfg, args->cat);
889 var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
892 ast_log(LOG_WARNING, "Unable to allocate variable");
896 ast_variable_append(args->cat, var);
901 static struct ast_config *config_handler(const char *database, const char *table, const char *file,
902 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked)
904 struct cfg_entry_args args;
905 char *query, *errormsg = NULL;
910 ast_log(LOG_ERROR, "Table name unspecified\n");
914 table = config_table;
916 query = sqlite_mprintf(sql_get_config_table, table, file);
919 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
923 ast_debug(1, "SQL query: %s\n", query);
926 args.cat_name = NULL;
928 args.who_asked = who_asked;
930 ast_mutex_lock(&mutex);
932 RES_CONFIG_SQLITE_BEGIN
933 error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
934 RES_CONFIG_SQLITE_END(error)
936 ast_mutex_unlock(&mutex);
938 ast_free(args.cat_name);
939 sqlite_freemem(query);
942 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
943 sqlite_freemem(errormsg);
946 sqlite_freemem(errormsg);
951 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
953 const char **tmp, *param, *val, **params, **vals;
960 while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
961 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
968 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
975 params[params_count] = param;
976 vals[params_count] = val;
980 if (params_count > 0) {
981 *params_ptr = params;
984 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
989 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
991 struct rt_cfg_entry_args *args;
992 struct ast_variable *var;
997 for (i = 0; i < argc; i++) {
1001 if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
1010 args->last->next = var;
1018 static struct ast_variable * realtime_handler(const char *database, const char *table, va_list ap)
1020 char *query, *errormsg = NULL, *op, *tmp_str;
1021 struct rt_cfg_entry_args args;
1022 const char **params, **vals;
1023 size_t params_count;
1027 ast_log(LOG_WARNING, "Table name unspecified\n");
1031 params_count = get_params(ap, ¶ms, &vals);
1033 if (params_count == 0)
1036 op = (strchr(params[0], ' ') == NULL) ? " =" : "";
1038 /* \cond DOXYGEN_CAN_PARSE_THIS */
1040 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1043 query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
1046 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1052 if (params_count > 1) {
1055 for (i = 1; i < params_count; i++) {
1056 op = (strchr(params[i], ' ') == NULL) ? " =" : "";
1057 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1058 sqlite_freemem(query);
1061 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1074 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
1075 sqlite_freemem(query);
1078 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1083 ast_debug(1, "SQL query: %s\n", query);
1087 ast_mutex_lock(&mutex);
1089 RES_CONFIG_SQLITE_BEGIN
1090 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
1091 RES_CONFIG_SQLITE_END(error)
1093 ast_mutex_unlock(&mutex);
1095 sqlite_freemem(query);
1098 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1099 sqlite_freemem(errormsg);
1100 ast_variables_destroy(args.var);
1103 sqlite_freemem(errormsg);
1108 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
1110 struct rt_multi_cfg_entry_args *args;
1111 struct ast_category *cat;
1112 struct ast_variable *var;
1120 * cat_name should always be set here, since initfield is forged from
1121 * params[0] in realtime_multi_handler(), which is a search parameter
1124 for (i = 0; i < argc; i++) {
1125 if (!strcmp(args->initfield, columnNames[i]))
1130 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
1134 if (!(cat = ast_category_new(cat_name, "", 99999))) {
1135 ast_log(LOG_WARNING, "Unable to allocate category\n");
1139 ast_category_append(args->cfg, cat);
1141 for (i = 0; i < argc; i++) {
1142 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
1145 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
1146 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1150 ast_variable_append(cat, var);
1156 static struct ast_config *realtime_multi_handler(const char *database,
1157 const char *table, va_list ap)
1159 char *query, *errormsg = NULL, *op, *tmp_str, *initfield;
1160 struct rt_multi_cfg_entry_args args;
1161 const char **params, **vals;
1162 struct ast_config *cfg;
1163 size_t params_count;
1167 ast_log(LOG_WARNING, "Table name unspecified\n");
1171 if (!(cfg = ast_config_new())) {
1172 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1176 if (!(params_count = get_params(ap, ¶ms, &vals))) {
1177 ast_config_destroy(cfg);
1181 if (!(initfield = ast_strdup(params[0]))) {
1182 ast_config_destroy(cfg);
1188 tmp_str = strchr(initfield, ' ');
1193 op = (!strchr(params[0], ' ')) ? " =" : "";
1196 * Asterisk sends us an already escaped string when searching for
1197 * "exten LIKE" (uh!). Handle it separately.
1199 tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1201 /* \cond DOXYGEN_CAN_PARSE_THIS */
1203 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1206 if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1207 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1208 ast_config_destroy(cfg);
1211 ast_free(initfield);
1215 if (params_count > 1) {
1218 for (i = 1; i < params_count; i++) {
1219 op = (!strchr(params[i], ' ')) ? " =" : "";
1220 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1221 sqlite_freemem(query);
1224 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1225 ast_config_destroy(cfg);
1228 ast_free(initfield);
1239 if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1240 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1241 sqlite_freemem(query);
1242 ast_config_destroy(cfg);
1243 ast_free(initfield);
1247 sqlite_freemem(query);
1249 ast_debug(1, "SQL query: %s\n", query);
1251 args.initfield = initfield;
1253 ast_mutex_lock(&mutex);
1255 RES_CONFIG_SQLITE_BEGIN
1256 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1257 RES_CONFIG_SQLITE_END(error)
1259 ast_mutex_unlock(&mutex);
1261 sqlite_freemem(query);
1262 ast_free(initfield);
1265 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1266 sqlite_freemem(errormsg);
1267 ast_config_destroy(cfg);
1270 sqlite_freemem(errormsg);
1275 static int realtime_update_handler(const char *database, const char *table,
1276 const char *keyfield, const char *entity, va_list ap)
1278 char *query, *errormsg = NULL, *tmp_str;
1279 const char **params, **vals;
1280 size_t params_count;
1281 int error, rows_num;
1284 ast_log(LOG_WARNING, "Table name unspecified\n");
1288 if (!(params_count = get_params(ap, ¶ms, &vals)))
1291 /* \cond DOXYGEN_CAN_PARSE_THIS */
1293 #define QUERY "UPDATE '%q' SET %q = '%q'"
1296 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1297 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1303 if (params_count > 1) {
1306 for (i = 1; i < params_count; i++) {
1307 tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
1308 sqlite_freemem(query);
1311 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1324 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1325 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1326 sqlite_freemem(query);
1330 sqlite_freemem(query);
1332 ast_debug(1, "SQL query: %s\n", query);
1334 ast_mutex_lock(&mutex);
1336 RES_CONFIG_SQLITE_BEGIN
1337 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1338 RES_CONFIG_SQLITE_END(error)
1341 rows_num = sqlite_changes(db);
1345 ast_mutex_unlock(&mutex);
1347 sqlite_freemem(query);
1350 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1352 sqlite_freemem(errormsg);
1357 static int realtime_store_handler(const char *database, const char *table, va_list ap)
1359 char *errormsg = NULL, *tmp_str, *tmp_keys = NULL, *tmp_keys2 = NULL, *tmp_vals = NULL, *tmp_vals2 = NULL;
1360 const char **params, **vals;
1361 size_t params_count;
1366 ast_log(LOG_WARNING, "Table name unspecified\n");
1370 if (!(params_count = get_params(ap, ¶ms, &vals)))
1373 /* \cond DOXYGEN_CAN_PARSE_THIS */
1375 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1378 for (i = 0; i < params_count; i++) {
1380 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1381 sqlite_freemem(tmp_keys2);
1383 tmp_keys = sqlite_mprintf("%q", params[i]);
1386 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1387 sqlite_freemem(tmp_vals);
1394 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1395 sqlite_freemem(tmp_vals2);
1397 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1400 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1401 sqlite_freemem(tmp_keys);
1408 tmp_keys2 = tmp_keys;
1409 tmp_vals2 = tmp_vals;
1415 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1416 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1417 sqlite_freemem(tmp_keys);
1418 sqlite_freemem(tmp_vals);
1422 sqlite_freemem(tmp_keys);
1423 sqlite_freemem(tmp_vals);
1425 ast_debug(1, "SQL query: %s\n", tmp_str);
1427 ast_mutex_lock(&mutex);
1429 RES_CONFIG_SQLITE_BEGIN
1430 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1431 RES_CONFIG_SQLITE_END(error)
1434 rows_id = sqlite_last_insert_rowid(db);
1439 ast_mutex_unlock(&mutex);
1441 sqlite_freemem(tmp_str);
1444 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1446 sqlite_freemem(errormsg);
1451 static int realtime_destroy_handler(const char *database, const char *table,
1452 const char *keyfield, const char *entity, va_list ap)
1454 char *query, *errormsg = NULL, *tmp_str;
1455 const char **params, **vals;
1456 size_t params_count;
1457 int error, rows_num;
1461 ast_log(LOG_WARNING, "Table name unspecified\n");
1465 if (!(params_count = get_params(ap, ¶ms, &vals)))
1468 /* \cond DOXYGEN_CAN_PARSE_THIS */
1470 #define QUERY "DELETE FROM '%q' WHERE"
1473 if (!(query = sqlite_mprintf(QUERY, table))) {
1474 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1480 for (i = 0; i < params_count; i++) {
1481 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1482 sqlite_freemem(query);
1485 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1496 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1497 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1498 sqlite_freemem(query);
1501 sqlite_freemem(query);
1503 ast_debug(1, "SQL query: %s\n", query);
1505 ast_mutex_lock(&mutex);
1507 RES_CONFIG_SQLITE_BEGIN
1508 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1509 RES_CONFIG_SQLITE_END(error)
1512 rows_num = sqlite_changes(db);
1516 ast_mutex_unlock(&mutex);
1518 sqlite_freemem(query);
1521 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1523 sqlite_freemem(errormsg);
1528 static int realtime_require_handler(const char *unused, const char *tablename, va_list ap)
1530 struct sqlite_cache_tables *tbl = find_table(tablename);
1531 struct sqlite_cache_columns *col;
1533 int type, size, res = 0;
1539 while ((elm = va_arg(ap, char *))) {
1540 type = va_arg(ap, require_type);
1541 size = va_arg(ap, int);
1542 /* Check if the field matches the criteria */
1543 AST_RWLIST_TRAVERSE(&tbl->columns, col, list) {
1544 if (strcmp(col->name, elm) == 0) {
1545 /* SQLite only has two types - the 32-bit integer field that
1546 * is the key column, and everything else (everything else
1549 if (col->isint && !ast_rq_is_int(type)) {
1550 ast_log(LOG_WARNING, "Realtime table %s: column '%s' is an integer field, but Asterisk requires that it not be!\n", tablename, col->name);
1557 ast_log(LOG_WARNING, "Realtime table %s requires column '%s', but that column does not exist!\n", tablename, elm);
1560 AST_RWLIST_UNLOCK(&(tbl->columns));
1564 static int realtime_unload_handler(const char *unused, const char *tablename)
1566 struct sqlite_cache_tables *tbl;
1567 AST_RWLIST_WRLOCK(&sqlite_tables);
1568 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&sqlite_tables, tbl, list) {
1569 if (!strcasecmp(tbl->name, tablename)) {
1570 AST_RWLIST_REMOVE_CURRENT(list);
1574 AST_RWLIST_TRAVERSE_SAFE_END
1575 AST_RWLIST_UNLOCK(&sqlite_tables);
1579 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1583 e->command = "sqlite show status";
1585 "Usage: sqlite show status\n"
1586 " Show status information about the SQLite 2 driver\n";
1593 return CLI_SHOWUSAGE;
1595 ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
1596 ast_cli(a->fd, "config_table: ");
1599 ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
1601 ast_cli(a->fd, "%s\n", config_table);
1603 ast_cli(a->fd, "cdr_table: ");
1606 ast_cli(a->fd, "unspecified, CDR support disabled\n");
1608 ast_cli(a->fd, "%s\n", cdr_table);
1613 static char *handle_cli_sqlite_show_tables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1615 struct sqlite_cache_tables *tbl;
1616 struct sqlite_cache_columns *col;
1621 e->command = "sqlite show tables";
1623 "Usage: sqlite show tables\n"
1624 " Show table information about the SQLite 2 driver\n";
1631 return CLI_SHOWUSAGE;
1633 AST_RWLIST_RDLOCK(&sqlite_tables);
1634 AST_RWLIST_TRAVERSE(&sqlite_tables, tbl, list) {
1636 ast_cli(a->fd, "Table %s:\n", tbl->name);
1637 AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
1638 fprintf(stderr, "%s\n", col->name);
1639 ast_cli(a->fd, " %20.20s %-30.30s\n", col->name, col->type);
1642 AST_RWLIST_UNLOCK(&sqlite_tables);
1645 ast_cli(a->fd, "No tables currently in cache\n");
1651 static int unload_module(void)
1653 if (cli_status_registered)
1654 ast_cli_unregister_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1657 ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
1659 ast_config_engine_deregister(&sqlite_engine);
1669 static int load_module(void)
1671 char *errormsg = NULL;
1676 cli_status_registered = 0;
1678 config_table = NULL;
1680 error = load_config();
1683 return AST_MODULE_LOAD_DECLINE;
1685 if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1686 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1687 sqlite_freemem(errormsg);
1692 sqlite_freemem(errormsg);
1694 ast_config_engine_register(&sqlite_engine);
1699 /* \cond DOXYGEN_CAN_PARSE_THIS */
1701 #define QUERY "SELECT COUNT(id) FROM %Q;"
1704 query = sqlite_mprintf(QUERY, cdr_table);
1707 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1712 ast_debug(1, "SQL query: %s\n", query);
1714 RES_CONFIG_SQLITE_BEGIN
1715 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1716 RES_CONFIG_SQLITE_END(error)
1718 sqlite_freemem(query);
1724 if (error != SQLITE_ERROR) {
1725 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1726 sqlite_freemem(errormsg);
1731 sqlite_freemem(errormsg);
1733 query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
1736 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1741 ast_debug(1, "SQL query: %s\n", query);
1743 RES_CONFIG_SQLITE_BEGIN
1744 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1745 RES_CONFIG_SQLITE_END(error)
1747 sqlite_freemem(query);
1750 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1751 sqlite_freemem(errormsg);
1756 sqlite_freemem(errormsg);
1759 error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
1769 error = ast_cli_register_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1776 cli_status_registered = 1;
1781 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1782 .load = load_module,
1783 .unload = unload_module,