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/logger.h"
84 #include "asterisk/app.h"
85 #include "asterisk/pbx.h"
86 #include "asterisk/cdr.h"
87 #include "asterisk/cli.h"
88 #include "asterisk/lock.h"
89 #include "asterisk/config.h"
90 #include "asterisk/module.h"
91 #include "asterisk/linkedlists.h"
93 #define MACRO_BEGIN do {
94 #define MACRO_END } while (0)
96 #define RES_CONFIG_SQLITE_NAME "res_config_sqlite"
97 #define RES_CONFIG_SQLITE_DRIVER "sqlite"
98 #define RES_CONFIG_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
99 #define RES_CONFIG_SQLITE_CONF_FILE "res_config_sqlite.conf"
102 RES_CONFIG_SQLITE_CONFIG_ID,
103 RES_CONFIG_SQLITE_CONFIG_CAT_METRIC,
104 RES_CONFIG_SQLITE_CONFIG_VAR_METRIC,
105 RES_CONFIG_SQLITE_CONFIG_COMMENTED,
106 RES_CONFIG_SQLITE_CONFIG_FILENAME,
107 RES_CONFIG_SQLITE_CONFIG_CATEGORY,
108 RES_CONFIG_SQLITE_CONFIG_VAR_NAME,
109 RES_CONFIG_SQLITE_CONFIG_VAR_VAL,
110 RES_CONFIG_SQLITE_CONFIG_COLUMNS,
113 #define SET_VAR(config, to, from) \
117 __error = set_var(&to, #to, from->value); \
120 ast_config_destroy(config); \
127 * Maximum number of loops before giving up executing a query. Calls to
128 * sqlite_xxx() functions which can return SQLITE_BUSY
129 * are enclosed by RES_CONFIG_SQLITE_BEGIN and RES_CONFIG_SQLITE_END, e.g.
134 * RES_CONFIG_SQLITE_BEGIN
135 * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
136 * RES_CONFIG_SQLITE_END(error)
142 #define RES_CONFIG_SQLITE_MAX_LOOPS 10
145 * Macro used before executing a query.
147 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
149 #define RES_CONFIG_SQLITE_BEGIN \
153 for (__i = 0; __i < RES_CONFIG_SQLITE_MAX_LOOPS; __i++) {
156 * Macro used after executing a query.
158 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
160 #define RES_CONFIG_SQLITE_END(error) \
161 if (error != SQLITE_BUSY) \
168 * Structure sent to the SQLite callback function for static configuration.
170 * \see add_cfg_entry()
172 struct cfg_entry_args {
173 struct ast_config *cfg;
174 struct ast_category *cat;
176 struct ast_flags flags;
177 const char *who_asked;
181 * Structure sent to the SQLite callback function for RealTime configuration.
183 * \see add_rt_cfg_entry()
185 struct rt_cfg_entry_args {
186 struct ast_variable *var;
187 struct ast_variable *last;
191 * Structure sent to the SQLite callback function for RealTime configuration
192 * (realtime_multi_handler()).
194 * \see add_rt_multi_cfg_entry()
196 struct rt_multi_cfg_entry_args {
197 struct ast_config *cfg;
202 * \brief Allocate a variable.
203 * \param var the address of the variable to set (it will be allocated)
204 * \param name the name of the variable (for error handling)
205 * \param value the value to store in var
206 * \retval 0 on success
207 * \retval 1 if an allocation error occurred
209 static int set_var(char **var, const char *name, const char *value);
212 * \brief Load the configuration file.
213 * \see unload_config()
215 * This function sets dbfile, config_table, and cdr_table. It calls
216 * check_vars() before returning, and unload_config() if an error occurred.
218 * \retval 0 on success
219 * \retval 1 if an error occurred
221 static int load_config(void);
224 * \brief Free resources related to configuration.
227 static void unload_config(void);
230 * \brief Asterisk callback function for CDR support.
231 * \param cdr the CDR entry Asterisk sends us.
233 * Asterisk will call this function each time a CDR entry must be logged if
234 * CDR support is enabled.
236 * \retval 0 on success
237 * \retval 1 if an error occurred
239 static int cdr_handler(struct ast_cdr *cdr);
242 * \brief SQLite callback function for static configuration.
244 * This function is passed to the SQLite engine as a callback function to
245 * parse a row and store it in a struct ast_config object. It relies on
246 * resulting rows being sorted by category.
248 * \param arg a pointer to a struct cfg_entry_args object
249 * \param argc number of columns
250 * \param argv values in the row
251 * \param columnNames names and types of the columns
252 * \retval 0 on success
253 * \retval 1 if an error occurred
254 * \see cfg_entry_args
255 * \see sql_get_config_table
256 * \see config_handler()
258 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
261 * \brief Asterisk callback function for static configuration.
263 * Asterisk will call this function when it loads its static configuration,
264 * which usually happens at startup and reload.
266 * \param database the database to use (ignored)
267 * \param table the table to use
268 * \param file the file to load from the database
269 * \param cfg the struct ast_config object to use when storing variables
270 * \param flags Optional flags. Not used.
271 * \param suggested_incl suggest include.
273 * \retval NULL if an error occurred
274 * \see add_cfg_entry()
276 static struct ast_config * config_handler(const char *database, const char *table, const char *file,
277 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked);
280 * \brief Helper function to parse a va_list object into 2 dynamic arrays of
281 * strings, parameters and values.
283 * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
284 * arguments will be extracted to create 2 arrays:
287 * <li>params : param1 param2 param3 ...</li>
288 * <li>vals : val1 val2 val3 ...</li>
291 * The address of these arrays are stored in params_ptr and vals_ptr. It
292 * is the responsibility of the caller to release the memory of these arrays.
293 * It is considered an error that va_list has a null or odd number of strings.
295 * \param ap the va_list object to parse
296 * \param params_ptr where the address of the params array is stored
297 * \param vals_ptr where the address of the vals array is stored
298 * \retval the number of elements in the arrays (which have the same size).
299 * \retval 0 if an error occurred.
301 static size_t get_params(va_list ap, const char ***params_ptr,
302 const char ***vals_ptr);
305 * \brief SQLite callback function for RealTime configuration.
307 * This function is passed to the SQLite engine as a callback function to
308 * parse a row and store it in a linked list of struct ast_variable objects.
310 * \param arg a pointer to a struct rt_cfg_entry_args object
311 * \param argc number of columns
312 * \param argv values in the row
313 * \param columnNames names and types of the columns
314 * \retval 0 on success.
315 * \retval 1 if an error occurred.
316 * \see rt_cfg_entry_args
317 * \see realtime_handler()
319 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
323 * \brief Asterisk callback function for RealTime configuration.
325 * Asterisk will call this function each time it requires a variable
326 * through the RealTime architecture. ap is a list of parameters and
327 * values used to find a specific row, e.g one parameter "name" and
328 * one value "123" so that the SQL query becomes <code>SELECT * FROM
329 * table WHERE name = '123';</code>.
331 * \param database the database to use (ignored)
332 * \param table the table to use
333 * \param ap list of parameters and values to match
335 * \retval a linked list of struct ast_variable objects
336 * \retval NULL if an error occurred
337 * \see add_rt_cfg_entry()
339 static struct ast_variable * realtime_handler(const char *database,
340 const char *table, va_list ap);
343 * \brief SQLite callback function for RealTime configuration.
345 * This function performs the same actions as add_rt_cfg_entry() except
346 * that the rt_multi_cfg_entry_args structure is designed to store
347 * categories in addition to variables.
349 * \param arg a pointer to a struct rt_multi_cfg_entry_args object
350 * \param argc number of columns
351 * \param argv values in the row
352 * \param columnNames names and types of the columns
353 * \retval 0 on success.
354 * \retval 1 if an error occurred.
355 * \see rt_multi_cfg_entry_args
356 * \see realtime_multi_handler()
358 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
362 * \brief Asterisk callback function for RealTime configuration.
364 * This function performs the same actions as realtime_handler() except
365 * that it can store variables per category, and can return several
368 * \param database the database to use (ignored)
369 * \param table the table to use
370 * \param ap list of parameters and values to match
371 * \retval a struct ast_config object storing categories and variables.
372 * \retval NULL if an error occurred.
374 * \see add_rt_multi_cfg_entry()
376 static struct ast_config * realtime_multi_handler(const char *database,
377 const char *table, va_list ap);
380 * \brief Asterisk callback function for RealTime configuration (variable
383 * Asterisk will call this function each time a variable has been modified
384 * internally and must be updated in the backend engine. keyfield and entity
385 * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
386 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
387 * same format as the other realtime functions.
389 * \param database the database to use (ignored)
390 * \param table the table to use
391 * \param keyfield the column of the matching cell
392 * \param entity the value of the matching cell
393 * \param ap list of parameters and new values to update in the database
394 * \retval the number of affected rows.
395 * \retval -1 if an error occurred.
397 static int realtime_update_handler(const char *database, const char *table,
398 const char *keyfield, const char *entity, va_list ap);
401 * \brief Asterisk callback function for RealTime configuration (variable
404 * Asterisk will call this function each time a variable has been created
405 * internally and must be stored in the backend engine.
406 * are used to find the row to update, e.g. ap is a list of parameters and
407 * values with the same format as the other realtime functions.
409 * \param database the database to use (ignored)
410 * \param table the table to use
411 * \param ap list of parameters and new values to insert into the database
412 * \retval the rowid of inserted row.
413 * \retval -1 if an error occurred.
415 static int realtime_store_handler(const char *database, const char *table,
419 * \brief Asterisk callback function for RealTime configuration (destroys
422 * Asterisk will call this function each time a variable has been destroyed
423 * internally and must be removed from the backend engine. keyfield and entity
424 * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
425 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
426 * same format as the other realtime functions.
428 * \param database the database to use (ignored)
429 * \param table the table to use
430 * \param keyfield the column of the matching cell
431 * \param entity the value of the matching cell
432 * \param ap list of additional parameters for cell matching
433 * \retval the number of affected rows.
434 * \retval -1 if an error occurred.
436 static int realtime_destroy_handler(const char *database, const char *table,
437 const char *keyfield, const char *entity, va_list ap);
440 * \brief Asterisk callback function for the CLI status command.
442 * \param e CLI command
444 * \param a CLI argument list
445 * \return RESULT_SUCCESS
447 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
448 static char *handle_cli_sqlite_show_tables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
450 static int realtime_require_handler(const char *database, const char *table, va_list ap);
451 static int realtime_unload_handler(const char *unused, const char *tablename);
453 /*! The SQLite database object. */
456 /*! Set to 1 if CDR support is enabled. */
459 /*! Set to 1 if the CDR callback function was registered. */
460 static int cdr_registered;
462 /*! Set to 1 if the CLI status command callback function was registered. */
463 static int cli_status_registered;
465 /*! The path of the database file. */
468 /*! The name of the static configuration table. */
469 static char *config_table;
471 /*! The name of the table used to store CDR entries. */
472 static char *cdr_table;
475 * The structure specifying all callback functions used by Asterisk for static
476 * and RealTime configuration.
478 static struct ast_config_engine sqlite_engine =
480 .name = RES_CONFIG_SQLITE_DRIVER,
481 .load_func = config_handler,
482 .realtime_func = realtime_handler,
483 .realtime_multi_func = realtime_multi_handler,
484 .store_func = realtime_store_handler,
485 .destroy_func = realtime_destroy_handler,
486 .update_func = realtime_update_handler,
487 .require_func = realtime_require_handler,
488 .unload_func = realtime_unload_handler,
492 * The mutex used to prevent simultaneous access to the SQLite database.
494 AST_MUTEX_DEFINE_STATIC(mutex);
497 * Structure containing details and callback functions for the CLI status
500 static struct ast_cli_entry cli_status[] = {
501 AST_CLI_DEFINE(handle_cli_show_sqlite_status, "Show status information about the SQLite 2 driver"),
502 AST_CLI_DEFINE(handle_cli_sqlite_show_tables, "Cached table information about the SQLite 2 driver"),
505 struct sqlite_cache_columns {
508 unsigned char isint; /*!< By definition, only INTEGER PRIMARY KEY is an integer; everything else is a string. */
509 AST_RWLIST_ENTRY(sqlite_cache_columns) list;
512 struct sqlite_cache_tables {
514 AST_RWLIST_HEAD(_columns, sqlite_cache_columns) columns;
515 AST_RWLIST_ENTRY(sqlite_cache_tables) list;
518 static AST_RWLIST_HEAD_STATIC(sqlite_tables, sqlite_cache_tables);
521 * Taken from Asterisk 1.2 cdr_sqlite.so.
524 /*! SQL query format to create the CDR table if non existent. */
525 static char *sql_create_cdr_table =
526 "CREATE TABLE '%q' (\n"
528 " clid VARCHAR(80) NOT NULL DEFAULT '',\n"
529 " src VARCHAR(80) NOT NULL DEFAULT '',\n"
530 " dst VARCHAR(80) NOT NULL DEFAULT '',\n"
531 " dcontext VARCHAR(80) NOT NULL DEFAULT '',\n"
532 " channel VARCHAR(80) NOT NULL DEFAULT '',\n"
533 " dstchannel VARCHAR(80) NOT NULL DEFAULT '',\n"
534 " lastapp VARCHAR(80) NOT NULL DEFAULT '',\n"
535 " lastdata VARCHAR(80) NOT NULL DEFAULT '',\n"
536 " start DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
537 " answer DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
538 " end DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
539 " duration INT(11) NOT NULL DEFAULT 0,\n"
540 " billsec INT(11) NOT NULL DEFAULT 0,\n"
541 " disposition VARCHAR(45) NOT NULL DEFAULT '',\n"
542 " amaflags INT(11) NOT NULL DEFAULT 0,\n"
543 " accountcode VARCHAR(20) NOT NULL DEFAULT '',\n"
544 " uniqueid VARCHAR(32) NOT NULL DEFAULT '',\n"
545 " userfield VARCHAR(255) NOT NULL DEFAULT '',\n"
546 " PRIMARY KEY (id)\n"
550 * SQL query format to describe the table structure
552 static char *sql_table_structure =
553 "SELECT sql FROM sqlite_master WHERE type='table' AND tbl_name='%s'";
556 * SQL query format to fetch the static configuration of a file.
557 * Rows must be sorted by category.
559 * \see add_cfg_entry()
561 static const char *sql_get_config_table =
564 " WHERE filename = '%q' AND commented = 0"
565 " ORDER BY cat_metric ASC, var_metric ASC;";
567 static void free_table(struct sqlite_cache_tables *tblptr)
569 struct sqlite_cache_columns *col;
571 /* Obtain a write lock to ensure there are no read locks outstanding */
572 AST_RWLIST_WRLOCK(&(tblptr->columns));
573 while ((col = AST_RWLIST_REMOVE_HEAD(&(tblptr->columns), list))) {
576 AST_RWLIST_UNLOCK(&(tblptr->columns));
577 AST_RWLIST_HEAD_DESTROY(&(tblptr->columns));
581 static int find_table_cb(void *vtblptr, int argc, char **argv, char **columnNames)
583 struct sqlite_cache_tables *tblptr = vtblptr;
584 char *sql = ast_strdupa(argv[0]), *start, *end, *type, *remainder;
586 AST_DECLARE_APP_ARGS(fie,
587 AST_APP_ARG(ld)[100]; /* This means we support up to 100 columns per table */
589 struct sqlite_cache_columns *col;
591 /* This is really fun. We get to parse an SQL statement to figure out
592 * what columns are in the table.
594 if ((start = strchr(sql, '(')) && (end = strrchr(sql, ')'))) {
602 AST_STANDARD_APP_ARGS(fie, start);
603 for (i = 0; i < fie.argc; i++) {
604 fie.ld[i] = ast_skip_blanks(fie.ld[i]);
605 ast_debug(5, "Found field: %s\n", fie.ld[i]);
606 if (strncasecmp(fie.ld[i], "PRIMARY KEY", 11) == 0 && (start = strchr(fie.ld[i], '(')) && (end = strchr(fie.ld[i], ')'))) {
608 AST_RWLIST_TRAVERSE(&(tblptr->columns), col, list) {
609 if (strcasecmp(start + 1, col->name) == 0 && strcasestr(col->type, "INTEGER")) {
615 /* type delimiter could be any space character */
616 for (type = fie.ld[i]; *type > 32; type++);
618 type = ast_skip_blanks(type);
619 for (remainder = type; *remainder > 32; remainder++);
621 if (!(col = ast_calloc(1, sizeof(*col) + strlen(fie.ld[i]) + strlen(type) + 2))) {
624 col->name = (char *)col + sizeof(*col);
625 col->type = (char *)col + sizeof(*col) + strlen(fie.ld[i]) + 1;
626 strcpy(col->name, fie.ld[i]); /* SAFE */
627 strcpy(col->type, type); /* SAFE */
628 if (strcasestr(col->type, "INTEGER") && strcasestr(col->type, "PRIMARY KEY")) {
631 AST_LIST_INSERT_TAIL(&(tblptr->columns), col, list);
636 static struct sqlite_cache_tables *find_table(const char *tablename)
638 struct sqlite_cache_tables *tblptr;
640 char *sql, *errstr = NULL;
642 AST_RWLIST_RDLOCK(&sqlite_tables);
644 for (i = 0; i < 2; i++) {
645 AST_RWLIST_TRAVERSE(&sqlite_tables, tblptr, list) {
646 if (strcmp(tblptr->name, tablename) == 0) {
651 AST_RWLIST_RDLOCK(&(tblptr->columns));
652 AST_RWLIST_UNLOCK(&sqlite_tables);
657 AST_RWLIST_UNLOCK(&sqlite_tables);
658 AST_RWLIST_WRLOCK(&sqlite_tables);
662 /* Table structure not cached; build the structure now */
663 asprintf(&sql, sql_table_structure, tablename);
664 if (!(tblptr = ast_calloc(1, sizeof(*tblptr) + strlen(tablename) + 1))) {
665 AST_RWLIST_UNLOCK(&sqlite_tables);
666 ast_log(LOG_ERROR, "Memory error. Cannot cache table '%s'\n", tablename);
669 tblptr->name = (char *)tblptr + sizeof(*tblptr);
670 strcpy(tblptr->name, tablename); /* SAFE */
671 AST_RWLIST_HEAD_INIT(&(tblptr->columns));
673 ast_debug(1, "About to query table structure: %s\n", sql);
675 ast_mutex_lock(&mutex);
676 if ((err = sqlite_exec(db, sql, find_table_cb, tblptr, &errstr))) {
677 ast_mutex_unlock(&mutex);
678 ast_log(LOG_WARNING, "SQLite error %d: %s\n", err, errstr);
683 ast_mutex_unlock(&mutex);
685 if (AST_LIST_EMPTY(&(tblptr->columns))) {
690 AST_RWLIST_INSERT_TAIL(&sqlite_tables, tblptr, list);
691 AST_RWLIST_RDLOCK(&(tblptr->columns));
692 AST_RWLIST_UNLOCK(&sqlite_tables);
696 #define release_table(a) AST_RWLIST_UNLOCK(&((a)->columns))
698 static int set_var(char **var, const char *name, const char *value)
703 *var = ast_strdup(value);
706 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
713 static int check_vars(void)
716 ast_log(LOG_ERROR, "Required parameter undefined: dbfile\n");
720 use_cdr = (cdr_table != NULL);
725 static int load_config(void)
727 struct ast_config *config;
728 struct ast_variable *var;
730 struct ast_flags config_flags = { 0 };
732 config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
734 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
735 ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
739 for (var = ast_variable_browse(config, "general"); var; var = var->next) {
740 if (!strcasecmp(var->name, "dbfile"))
741 SET_VAR(config, dbfile, var);
742 else if (!strcasecmp(var->name, "config_table"))
743 SET_VAR(config, config_table, var);
744 else if (!strcasecmp(var->name, "cdr_table")) {
745 SET_VAR(config, cdr_table, var);
747 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
750 ast_config_destroy(config);
751 error = check_vars();
761 static void unload_config(void)
763 struct sqlite_cache_tables *tbl;
766 ast_free(config_table);
770 AST_RWLIST_WRLOCK(&sqlite_tables);
771 while ((tbl = AST_RWLIST_REMOVE_HEAD(&sqlite_tables, list))) {
774 AST_RWLIST_UNLOCK(&sqlite_tables);
777 static int cdr_handler(struct ast_cdr *cdr)
779 char *errormsg = NULL, *tmp, workspace[500];
781 struct sqlite_cache_tables *tbl = find_table(cdr_table);
782 struct sqlite_cache_columns *col;
783 struct ast_str *sql1 = ast_str_create(160), *sql2 = ast_str_create(16);
786 ast_log(LOG_WARNING, "No such table: %s\n", cdr_table);
790 ast_str_set(&sql1, 0, "INSERT INTO %s (", cdr_table);
791 ast_str_set(&sql2, 0, ") VALUES (");
793 AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
795 ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 1);
799 if (sscanf(tmp, "%d", &scannum) == 1) {
800 ast_str_append(&sql1, 0, "%s,", col->name);
801 ast_str_append(&sql2, 0, "%d,", scannum);
804 ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 0);
808 ast_str_append(&sql1, 0, "%s,", col->name);
809 tmp = sqlite_mprintf("%Q", tmp);
810 ast_str_append(&sql2, 0, "%s,", tmp);
816 sql1->str[--sql1->used] = '\0';
817 sql2->str[--sql2->used] = '\0';
818 ast_str_append(&sql1, 0, "%s)", sql2->str);
821 ast_debug(1, "SQL query: %s\n", sql1->str);
823 ast_mutex_lock(&mutex);
825 RES_CONFIG_SQLITE_BEGIN
826 error = sqlite_exec(db, sql1->str, NULL, NULL, &errormsg);
827 RES_CONFIG_SQLITE_END(error)
829 ast_mutex_unlock(&mutex);
834 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
835 sqlite_freemem(errormsg);
838 sqlite_freemem(errormsg);
843 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
845 struct cfg_entry_args *args;
846 struct ast_variable *var;
848 if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
849 ast_log(LOG_WARNING, "Corrupt table\n");
855 if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
856 struct ast_config *cfg;
859 val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
860 cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked);
863 ast_log(LOG_WARNING, "Unable to include %s\n", val);
871 if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
872 args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
875 ast_log(LOG_WARNING, "Unable to allocate category\n");
879 ast_free(args->cat_name);
880 args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
882 if (!args->cat_name) {
883 ast_category_destroy(args->cat);
887 ast_category_append(args->cfg, args->cat);
890 var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
893 ast_log(LOG_WARNING, "Unable to allocate variable");
897 ast_variable_append(args->cat, var);
902 static struct ast_config *config_handler(const char *database, const char *table, const char *file,
903 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked)
905 struct cfg_entry_args args;
906 char *query, *errormsg = NULL;
911 ast_log(LOG_ERROR, "Table name unspecified\n");
915 table = config_table;
917 query = sqlite_mprintf(sql_get_config_table, table, file);
920 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
924 ast_debug(1, "SQL query: %s\n", query);
927 args.cat_name = NULL;
929 args.who_asked = who_asked;
931 ast_mutex_lock(&mutex);
933 RES_CONFIG_SQLITE_BEGIN
934 error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
935 RES_CONFIG_SQLITE_END(error)
937 ast_mutex_unlock(&mutex);
939 ast_free(args.cat_name);
940 sqlite_freemem(query);
943 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
944 sqlite_freemem(errormsg);
947 sqlite_freemem(errormsg);
952 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
954 const char **tmp, *param, *val, **params, **vals;
961 while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
962 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
969 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
976 params[params_count] = param;
977 vals[params_count] = val;
981 if (params_count > 0) {
982 *params_ptr = params;
985 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
990 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
992 struct rt_cfg_entry_args *args;
993 struct ast_variable *var;
998 for (i = 0; i < argc; i++) {
1002 if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
1011 args->last->next = var;
1019 static struct ast_variable * realtime_handler(const char *database, const char *table, va_list ap)
1021 char *query, *errormsg = NULL, *op, *tmp_str;
1022 struct rt_cfg_entry_args args;
1023 const char **params, **vals;
1024 size_t params_count;
1028 ast_log(LOG_WARNING, "Table name unspecified\n");
1032 params_count = get_params(ap, ¶ms, &vals);
1034 if (params_count == 0)
1037 op = (strchr(params[0], ' ') == NULL) ? " =" : "";
1039 /* \cond DOXYGEN_CAN_PARSE_THIS */
1041 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1044 query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
1047 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1053 if (params_count > 1) {
1056 for (i = 1; i < params_count; i++) {
1057 op = (strchr(params[i], ' ') == NULL) ? " =" : "";
1058 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1059 sqlite_freemem(query);
1062 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1075 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
1076 sqlite_freemem(query);
1079 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1084 ast_debug(1, "SQL query: %s\n", query);
1088 ast_mutex_lock(&mutex);
1090 RES_CONFIG_SQLITE_BEGIN
1091 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
1092 RES_CONFIG_SQLITE_END(error)
1094 ast_mutex_unlock(&mutex);
1096 sqlite_freemem(query);
1099 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1100 sqlite_freemem(errormsg);
1101 ast_variables_destroy(args.var);
1104 sqlite_freemem(errormsg);
1109 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
1111 struct rt_multi_cfg_entry_args *args;
1112 struct ast_category *cat;
1113 struct ast_variable *var;
1121 * cat_name should always be set here, since initfield is forged from
1122 * params[0] in realtime_multi_handler(), which is a search parameter
1125 for (i = 0; i < argc; i++) {
1126 if (!strcmp(args->initfield, columnNames[i]))
1131 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
1135 if (!(cat = ast_category_new(cat_name, "", 99999))) {
1136 ast_log(LOG_WARNING, "Unable to allocate category\n");
1140 ast_category_append(args->cfg, cat);
1142 for (i = 0; i < argc; i++) {
1143 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
1146 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
1147 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1151 ast_variable_append(cat, var);
1157 static struct ast_config *realtime_multi_handler(const char *database,
1158 const char *table, va_list ap)
1160 char *query, *errormsg = NULL, *op, *tmp_str, *initfield;
1161 struct rt_multi_cfg_entry_args args;
1162 const char **params, **vals;
1163 struct ast_config *cfg;
1164 size_t params_count;
1168 ast_log(LOG_WARNING, "Table name unspecified\n");
1172 if (!(cfg = ast_config_new())) {
1173 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1177 if (!(params_count = get_params(ap, ¶ms, &vals))) {
1178 ast_config_destroy(cfg);
1182 if (!(initfield = ast_strdup(params[0]))) {
1183 ast_config_destroy(cfg);
1189 tmp_str = strchr(initfield, ' ');
1194 op = (!strchr(params[0], ' ')) ? " =" : "";
1197 * Asterisk sends us an already escaped string when searching for
1198 * "exten LIKE" (uh!). Handle it separately.
1200 tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1202 /* \cond DOXYGEN_CAN_PARSE_THIS */
1204 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1207 if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1208 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1209 ast_config_destroy(cfg);
1212 ast_free(initfield);
1216 if (params_count > 1) {
1219 for (i = 1; i < params_count; i++) {
1220 op = (!strchr(params[i], ' ')) ? " =" : "";
1221 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1222 sqlite_freemem(query);
1225 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1226 ast_config_destroy(cfg);
1229 ast_free(initfield);
1240 if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1241 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1242 sqlite_freemem(query);
1243 ast_config_destroy(cfg);
1244 ast_free(initfield);
1248 sqlite_freemem(query);
1250 ast_debug(1, "SQL query: %s\n", query);
1252 args.initfield = initfield;
1254 ast_mutex_lock(&mutex);
1256 RES_CONFIG_SQLITE_BEGIN
1257 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1258 RES_CONFIG_SQLITE_END(error)
1260 ast_mutex_unlock(&mutex);
1262 sqlite_freemem(query);
1263 ast_free(initfield);
1266 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1267 sqlite_freemem(errormsg);
1268 ast_config_destroy(cfg);
1271 sqlite_freemem(errormsg);
1276 static int realtime_update_handler(const char *database, const char *table,
1277 const char *keyfield, const char *entity, va_list ap)
1279 char *query, *errormsg = NULL, *tmp_str;
1280 const char **params, **vals;
1281 size_t params_count;
1282 int error, rows_num;
1285 ast_log(LOG_WARNING, "Table name unspecified\n");
1289 if (!(params_count = get_params(ap, ¶ms, &vals)))
1292 /* \cond DOXYGEN_CAN_PARSE_THIS */
1294 #define QUERY "UPDATE '%q' SET %q = '%q'"
1297 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1298 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1304 if (params_count > 1) {
1307 for (i = 1; i < params_count; i++) {
1308 tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
1309 sqlite_freemem(query);
1312 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1325 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1326 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1327 sqlite_freemem(query);
1331 sqlite_freemem(query);
1333 ast_debug(1, "SQL query: %s\n", query);
1335 ast_mutex_lock(&mutex);
1337 RES_CONFIG_SQLITE_BEGIN
1338 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1339 RES_CONFIG_SQLITE_END(error)
1342 rows_num = sqlite_changes(db);
1346 ast_mutex_unlock(&mutex);
1348 sqlite_freemem(query);
1351 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1353 sqlite_freemem(errormsg);
1358 static int realtime_store_handler(const char *database, const char *table, va_list ap)
1360 char *errormsg = NULL, *tmp_str, *tmp_keys = NULL, *tmp_keys2 = NULL, *tmp_vals = NULL, *tmp_vals2 = NULL;
1361 const char **params, **vals;
1362 size_t params_count;
1367 ast_log(LOG_WARNING, "Table name unspecified\n");
1371 if (!(params_count = get_params(ap, ¶ms, &vals)))
1374 /* \cond DOXYGEN_CAN_PARSE_THIS */
1376 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1379 for (i = 0; i < params_count; i++) {
1381 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1382 sqlite_freemem(tmp_keys2);
1384 tmp_keys = sqlite_mprintf("%q", params[i]);
1387 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1388 sqlite_freemem(tmp_vals);
1395 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1396 sqlite_freemem(tmp_vals2);
1398 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1401 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1402 sqlite_freemem(tmp_keys);
1409 tmp_keys2 = tmp_keys;
1410 tmp_vals2 = tmp_vals;
1416 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1417 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1418 sqlite_freemem(tmp_keys);
1419 sqlite_freemem(tmp_vals);
1423 sqlite_freemem(tmp_keys);
1424 sqlite_freemem(tmp_vals);
1426 ast_debug(1, "SQL query: %s\n", tmp_str);
1428 ast_mutex_lock(&mutex);
1430 RES_CONFIG_SQLITE_BEGIN
1431 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1432 RES_CONFIG_SQLITE_END(error)
1435 rows_id = sqlite_last_insert_rowid(db);
1440 ast_mutex_unlock(&mutex);
1442 sqlite_freemem(tmp_str);
1445 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1447 sqlite_freemem(errormsg);
1452 static int realtime_destroy_handler(const char *database, const char *table,
1453 const char *keyfield, const char *entity, va_list ap)
1455 char *query, *errormsg = NULL, *tmp_str;
1456 const char **params, **vals;
1457 size_t params_count;
1458 int error, rows_num;
1462 ast_log(LOG_WARNING, "Table name unspecified\n");
1466 if (!(params_count = get_params(ap, ¶ms, &vals)))
1469 /* \cond DOXYGEN_CAN_PARSE_THIS */
1471 #define QUERY "DELETE FROM '%q' WHERE"
1474 if (!(query = sqlite_mprintf(QUERY, table))) {
1475 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1481 for (i = 0; i < params_count; i++) {
1482 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1483 sqlite_freemem(query);
1486 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1497 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1498 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1499 sqlite_freemem(query);
1502 sqlite_freemem(query);
1504 ast_debug(1, "SQL query: %s\n", query);
1506 ast_mutex_lock(&mutex);
1508 RES_CONFIG_SQLITE_BEGIN
1509 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1510 RES_CONFIG_SQLITE_END(error)
1513 rows_num = sqlite_changes(db);
1517 ast_mutex_unlock(&mutex);
1519 sqlite_freemem(query);
1522 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1524 sqlite_freemem(errormsg);
1529 static int realtime_require_handler(const char *unused, const char *tablename, va_list ap)
1531 struct sqlite_cache_tables *tbl = find_table(tablename);
1532 struct sqlite_cache_columns *col;
1534 int type, size, res = 0;
1540 while ((elm = va_arg(ap, char *))) {
1541 type = va_arg(ap, require_type);
1542 size = va_arg(ap, int);
1543 /* Check if the field matches the criteria */
1544 AST_RWLIST_TRAVERSE(&tbl->columns, col, list) {
1545 if (strcmp(col->name, elm) == 0) {
1546 /* SQLite only has two types - the 32-bit integer field that
1547 * is the key column, and everything else (everything else
1550 if (col->isint && !ast_rq_is_int(type)) {
1551 ast_log(LOG_WARNING, "Realtime table %s: column '%s' is an integer field, but Asterisk requires that it not be!\n", tablename, col->name);
1558 ast_log(LOG_WARNING, "Realtime table %s requires column '%s', but that column does not exist!\n", tablename, elm);
1561 AST_RWLIST_UNLOCK(&(tbl->columns));
1565 static int realtime_unload_handler(const char *unused, const char *tablename)
1567 struct sqlite_cache_tables *tbl;
1568 AST_RWLIST_WRLOCK(&sqlite_tables);
1569 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&sqlite_tables, tbl, list) {
1570 if (!strcasecmp(tbl->name, tablename)) {
1571 AST_RWLIST_REMOVE_CURRENT(list);
1575 AST_RWLIST_TRAVERSE_SAFE_END
1576 AST_RWLIST_UNLOCK(&sqlite_tables);
1580 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1584 e->command = "sqlite show status";
1586 "Usage: sqlite show status\n"
1587 " Show status information about the SQLite 2 driver\n";
1594 return CLI_SHOWUSAGE;
1596 ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
1597 ast_cli(a->fd, "config_table: ");
1600 ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
1602 ast_cli(a->fd, "%s\n", config_table);
1604 ast_cli(a->fd, "cdr_table: ");
1607 ast_cli(a->fd, "unspecified, CDR support disabled\n");
1609 ast_cli(a->fd, "%s\n", cdr_table);
1614 static char *handle_cli_sqlite_show_tables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1616 struct sqlite_cache_tables *tbl;
1617 struct sqlite_cache_columns *col;
1622 e->command = "sqlite show tables";
1624 "Usage: sqlite show tables\n"
1625 " Show table information about the SQLite 2 driver\n";
1632 return CLI_SHOWUSAGE;
1634 AST_RWLIST_RDLOCK(&sqlite_tables);
1635 AST_RWLIST_TRAVERSE(&sqlite_tables, tbl, list) {
1637 ast_cli(a->fd, "Table %s:\n", tbl->name);
1638 AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
1639 fprintf(stderr, "%s\n", col->name);
1640 ast_cli(a->fd, " %20.20s %-30.30s\n", col->name, col->type);
1643 AST_RWLIST_UNLOCK(&sqlite_tables);
1646 ast_cli(a->fd, "No tables currently in cache\n");
1652 static int unload_module(void)
1654 if (cli_status_registered)
1655 ast_cli_unregister_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1658 ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
1660 ast_config_engine_deregister(&sqlite_engine);
1670 static int load_module(void)
1672 char *errormsg = NULL;
1677 cli_status_registered = 0;
1679 config_table = NULL;
1681 error = load_config();
1684 return AST_MODULE_LOAD_DECLINE;
1686 if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1687 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1688 sqlite_freemem(errormsg);
1693 sqlite_freemem(errormsg);
1695 ast_config_engine_register(&sqlite_engine);
1700 /* \cond DOXYGEN_CAN_PARSE_THIS */
1702 #define QUERY "SELECT COUNT(id) FROM %Q;"
1705 query = sqlite_mprintf(QUERY, cdr_table);
1708 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1713 ast_debug(1, "SQL query: %s\n", query);
1715 RES_CONFIG_SQLITE_BEGIN
1716 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1717 RES_CONFIG_SQLITE_END(error)
1719 sqlite_freemem(query);
1725 if (error != SQLITE_ERROR) {
1726 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1727 sqlite_freemem(errormsg);
1732 sqlite_freemem(errormsg);
1734 query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
1737 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1742 ast_debug(1, "SQL query: %s\n", query);
1744 RES_CONFIG_SQLITE_BEGIN
1745 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1746 RES_CONFIG_SQLITE_END(error)
1748 sqlite_freemem(query);
1751 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1752 sqlite_freemem(errormsg);
1757 sqlite_freemem(errormsg);
1760 error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
1770 error = ast_cli_register_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1777 cli_status_registered = 1;
1782 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1783 .load = load_module,
1784 .unload = unload_module,