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).
31 * It can also be used to log CDR entries. Finally, it can be used for simple
32 * queries in the Dialplan. Note that Asterisk already comes with a module
33 * named cdr_sqlite. There are two reasons for including it in res_config_sqlite:
34 * the first is that rewriting it was a training to learn how to write a
35 * simple module for Asterisk, the other is to have the same database open for
36 * all kinds of operations, which improves reliability and performance.
38 * There is already a module for SQLite 3 (named res_sqlite3) in the Asterisk
39 * addons. res_config_sqlite was developed because we, at Proformatique, are using
40 * PHP 4 in our embedded systems, and PHP 4 has no stable support for SQLite 3
41 * at this time. We also needed RealTime support.
43 * \section conf_sec Configuration
45 * The main configuration file is res_config_sqlite.conf. It must be readable or
46 * res_config_sqlite will fail to start. It is suggested to use the sample file
47 * in this package as a starting point. The file has only one section
48 * named <code>general</code>. Here are the supported parameters :
51 * <dt><code>dbfile</code></dt>
52 * <dd>The absolute path to the SQLite database (the file can be non existent,
53 * res_config_sqlite will create it if it has the appropriate rights)</dd>
54 * <dt><code>config_table</code></dt>
55 * <dd>The table used for static configuration</dd>
56 * <dt><code>cdr_table</code></dt>
57 * <dd>The table used to store CDR entries (if ommitted, CDR support is
61 * To use res_config_sqlite for static and/or RealTime configuration, refer to the
62 * Asterisk documentation. The file tables.sql can be used to create the
65 * \section status_sec Driver status
67 * The CLI command <code>show sqlite status</code> returns status information
68 * about the running driver.
70 * \section credits_sec Credits
72 * res_config_sqlite was developed by Richard Braun at the Proformatique company.
77 * \brief res_config_sqlite module.
81 <depend>sqlite</depend>
92 #include "asterisk/pbx.h"
93 #include "asterisk/cdr.h"
94 #include "asterisk/cli.h"
95 #include "asterisk/lock.h"
96 #include "asterisk/config.h"
97 #include "asterisk/logger.h"
98 #include "asterisk/module.h"
99 #include "asterisk/options.h"
100 #include "asterisk/linkedlists.h"
102 #define MACRO_BEGIN do {
103 #define MACRO_END } while (0)
105 #define RES_CONFIG_SQLITE_NAME "res_config_sqlite"
106 #define RES_CONFIG_SQLITE_DRIVER "sqlite"
107 #define RES_CONFIG_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
108 #define RES_CONFIG_SQLITE_CONF_FILE "res_config_sqlite.conf"
109 #define RES_CONFIG_SQLITE_STATUS_SUMMARY "Show status information about the SQLite 2 driver"
110 #define RES_CONFIG_SQLITE_STATUS_USAGE \
111 "Usage: show sqlite status\n" \
112 " " RES_CONFIG_SQLITE_STATUS_SUMMARY "\n"
115 RES_CONFIG_SQLITE_CONFIG_ID,
116 RES_CONFIG_SQLITE_CONFIG_CAT_METRIC,
117 RES_CONFIG_SQLITE_CONFIG_VAR_METRIC,
118 RES_CONFIG_SQLITE_CONFIG_COMMENTED,
119 RES_CONFIG_SQLITE_CONFIG_FILENAME,
120 RES_CONFIG_SQLITE_CONFIG_CATEGORY,
121 RES_CONFIG_SQLITE_CONFIG_VAR_NAME,
122 RES_CONFIG_SQLITE_CONFIG_VAR_VAL,
123 RES_CONFIG_SQLITE_CONFIG_COLUMNS,
126 #define SET_VAR(config, to, from) \
130 __error = set_var(&to, #to, from->value); \
133 ast_config_destroy(config); \
140 * Maximum number of loops before giving up executing a query. Calls to
141 * sqlite_xxx() functions which can return SQLITE_BUSY or SQLITE_LOCKED
142 * are enclosed by RES_CONFIG_SQLITE_BEGIN and RES_CONFIG_SQLITE_END, e.g.
147 * RES_CONFIG_SQLITE_BEGIN
148 * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
149 * RES_CONFIG_SQLITE_END(error)
155 #define RES_CONFIG_SQLITE_MAX_LOOPS 10
158 * Macro used before executing a query.
160 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
162 #define RES_CONFIG_SQLITE_BEGIN \
166 for (__i = 0; __i < RES_CONFIG_SQLITE_MAX_LOOPS; __i++) {
169 * Macro used after executing a query.
171 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
173 #define RES_CONFIG_SQLITE_END(error) \
174 if (error != SQLITE_BUSY && error != SQLITE_LOCKED) \
181 * Structure sent to the SQLite callback function for static configuration.
183 * \see add_cfg_entry()
185 struct cfg_entry_args {
186 struct ast_config *cfg;
187 struct ast_category *cat;
189 struct ast_flags flags;
193 * Structure sent to the SQLite callback function for RealTime configuration.
195 * \see add_rt_cfg_entry()
197 struct rt_cfg_entry_args {
198 struct ast_variable *var;
199 struct ast_variable *last;
203 * Structure sent to the SQLite callback function for RealTime configuration
204 * (realtime_multi_handler()).
206 * \see add_rt_multi_cfg_entry()
208 struct rt_multi_cfg_entry_args {
209 struct ast_config *cfg;
214 * \brief Allocate a variable.
215 * \param var the address of the variable to set (it will be allocated)
216 * \param name the name of the variable (for error handling)
217 * \param value the value to store in var
218 * \retval 0 on success
219 * \retval 1 if an allocation error occurred
221 static int set_var(char **var, char *name, char *value);
224 * \brief Load the configuration file.
225 * \see unload_config()
227 * This function sets dbfile, config_table, and cdr_table. It calls
228 * check_vars() before returning, and unload_config() if an error occurred.
230 * \retval 0 on success
231 * \retval 1 if an error occurred
233 static int load_config(void);
236 * \brief Free resources related to configuration.
239 static void unload_config(void);
242 * \brief Asterisk callback function for CDR support.
243 * \param cdr the CDR entry Asterisk sends us.
245 * Asterisk will call this function each time a CDR entry must be logged if
246 * CDR support is enabled.
248 * \retval 0 on success
249 * \retval 1 if an error occurred
251 static int cdr_handler(struct ast_cdr *cdr);
254 * \brief SQLite callback function for static configuration.
256 * This function is passed to the SQLite engine as a callback function to
257 * parse a row and store it in a struct ast_config object. It relies on
258 * resulting rows being sorted by category.
260 * \param arg a pointer to a struct cfg_entry_args object
261 * \param argc number of columns
262 * \param argv values in the row
263 * \param columnNames names and types of the columns
264 * \retval 0 on success
265 * \retval 1 if an error occurred
266 * \see cfg_entry_args
267 * \see sql_get_config_table
268 * \see config_handler()
270 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
273 * \brief Asterisk callback function for static configuration.
275 * Asterisk will call this function when it loads its static configuration,
276 * which usually happens at startup and reload.
278 * \param database the database to use (ignored)
279 * \param table the table to use
280 * \param file the file to load from the database
281 * \param cfg the struct ast_config object to use when storing variables
282 * \param flags Optional flags. Not used.
283 * \param suggested_incl suggest include.
285 * \retval NULL if an error occurred
286 * \see add_cfg_entry()
288 static struct ast_config * config_handler(const char *database, const char *table, const char *file,
289 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl);
292 * \brief Helper function to parse a va_list object into 2 dynamic arrays of
293 * strings, parameters and values.
295 * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
296 * arguments will be extracted to create 2 arrays:
299 * <li>params : param1 param2 param3 ...</li>
300 * <li>vals : val1 val2 val3 ...</li>
303 * The address of these arrays are stored in params_ptr and vals_ptr. It
304 * is the responsibility of the caller to release the memory of these arrays.
305 * It is considered an error that va_list has a null or odd number of strings.
307 * \param ap the va_list object to parse
308 * \param params_ptr where the address of the params array is stored
309 * \param vals_ptr where the address of the vals array is stored
310 * \retval the number of elements in the arrays (which have the same size).
311 * \retval 0 if an error occurred.
313 static size_t get_params(va_list ap, const char ***params_ptr,
314 const char ***vals_ptr);
317 * \brief SQLite callback function for RealTime configuration.
319 * This function is passed to the SQLite engine as a callback function to
320 * parse a row and store it in a linked list of struct ast_variable objects.
322 * \param arg a pointer to a struct rt_cfg_entry_args object
323 * \param argc number of columns
324 * \param argv values in the row
325 * \param columnNames names and types of the columns
326 * \retval 0 on success.
327 * \retval 1 if an error occurred.
328 * \see rt_cfg_entry_args
329 * \see realtime_handler()
331 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
335 * Asterisk callback function for RealTime configuration.
337 * Asterisk will call this function each time it requires a variable
338 * through the RealTime architecture. ap is a list of parameters and
339 * values used to find a specific row, e.g one parameter "name" and
340 * one value "123" so that the SQL query becomes <code>SELECT * FROM
341 * table WHERE name = '123';</code>.
343 * \param database the database to use (ignored)
344 * \param table the table to use
345 * \param ap list of parameters and values to match
347 * \retval a linked list of struct ast_variable objects
348 * \retval NULL if an error occurred
349 * \see add_rt_cfg_entry()
351 static struct ast_variable * realtime_handler(const char *database,
352 const char *table, va_list ap);
355 * \brief SQLite callback function for RealTime configuration.
357 * This function performs the same actions as add_rt_cfg_entry() except
358 * that the rt_multi_cfg_entry_args structure is designed to store
359 * categories in addition to variables.
361 * \param arg a pointer to a struct rt_multi_cfg_entry_args object
362 * \param argc number of columns
363 * \param argv values in the row
364 * \param columnNames names and types of the columns
365 * \retval 0 on success.
366 * \retval 1 if an error occurred.
367 * \see rt_multi_cfg_entry_args
368 * \see realtime_multi_handler()
370 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
374 * \brief Asterisk callback function for RealTime configuration.
376 * This function performs the same actions as realtime_handler() except
377 * that it can store variables per category, and can return several
380 * \param database the database to use (ignored)
381 * \param table the table to use
382 * \param ap list of parameters and values to match
383 * \retval a struct ast_config object storing categories and variables.
384 * \retval NULL if an error occurred.
386 * \see add_rt_multi_cfg_entry()
388 static struct ast_config * realtime_multi_handler(const char *database,
389 const char *table, va_list ap);
392 * \brief Asterisk callback function for RealTime configuration (variable
395 * Asterisk will call this function each time a variable has been modified
396 * internally and must be updated in the backend engine. keyfield and entity
397 * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
398 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
399 * same format as the other realtime functions.
401 * \param database the database to use (ignored)
402 * \param table the table to use
403 * \param keyfield the column of the matching cell
404 * \param entity the value of the matching cell
405 * \param ap list of parameters and new values to update in the database
406 * \retval the number of affected rows.
407 * \retval -1 if an error occurred.
409 static int realtime_update_handler(const char *database, const char *table,
410 const char *keyfield, const char *entity, va_list ap);
413 * \brief Asterisk callback function for RealTime configuration (variable
416 * Asterisk will call this function each time a variable has been created
417 * internally and must be stored in the backend engine.
418 * are used to find the row to update, e.g. ap is a list of parameters and
419 * values with the same format as the other realtime functions.
421 * \param database the database to use (ignored)
422 * \param table the table to use
423 * \param ap list of parameters and new values to insert into the database
424 * \retval the rowid of inserted row.
425 * \retval -1 if an error occurred.
427 static int realtime_store_handler(const char *database, const char *table,
431 * \brief Asterisk callback function for RealTime configuration (destroys
434 * Asterisk will call this function each time a variable has been destroyed
435 * internally and must be removed from the backend engine. keyfield and entity
436 * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
437 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
438 * same format as the other realtime functions.
440 * \param database the database to use (ignored)
441 * \param table the table to use
442 * \param keyfield the column of the matching cell
443 * \param entity the value of the matching cell
444 * \param ap list of additional parameters for cell matching
445 * \retval the number of affected rows.
446 * \retval -1 if an error occurred.
448 static int realtime_destroy_handler(const char *database, const char *table,
449 const char *keyfield, const char *entity, va_list ap);
452 * \brief Asterisk callback function for the CLI status command.
454 * \param fd file descriptor provided by Asterisk to use with ast_cli()
455 * \param argc number of arguments
456 * \param argv arguments list
457 * \return RESULT_SUCCESS
459 static int cli_status(int fd, int argc, char *argv[]);
461 /*! The SQLite database object. */
464 /*! Set to 1 if CDR support is enabled. */
467 /*! Set to 1 if the CDR callback function was registered. */
468 static int cdr_registered;
470 /*! Set to 1 if the CLI status command callback function was registered. */
471 static int cli_status_registered;
473 /*! The path of the database file. */
476 /*! The name of the static configuration table. */
477 static char *config_table;
479 /*! The name of the table used to store CDR entries. */
480 static char *cdr_table;
483 * The structure specifying all callback functions used by Asterisk for static
484 * and RealTime configuration.
486 static struct ast_config_engine sqlite_engine =
488 .name = RES_CONFIG_SQLITE_DRIVER,
489 .load_func = config_handler,
490 .realtime_func = realtime_handler,
491 .realtime_multi_func = realtime_multi_handler,
492 .store_func = realtime_store_handler,
493 .destroy_func = realtime_destroy_handler,
494 .update_func = realtime_update_handler
498 * The mutex used to prevent simultaneous access to the SQLite database.
500 AST_MUTEX_DEFINE_STATIC(mutex);
503 * Structure containing details and callback functions for the CLI status
506 static struct ast_cli_entry cli_status_cmd =
508 .cmda = {"show", "sqlite", "status", NULL},
509 .handler = cli_status,
510 .summary = RES_CONFIG_SQLITE_STATUS_SUMMARY,
511 .usage = RES_CONFIG_SQLITE_STATUS_USAGE
515 * Taken from Asterisk 1.2 cdr_sqlite.so.
518 /*! SQL query format to create the CDR table if non existent. */
519 static char *sql_create_cdr_table =
520 "CREATE TABLE '%q' (\n"
522 " clid VARCHAR(80) NOT NULL DEFAULT '',\n"
523 " src VARCHAR(80) NOT NULL DEFAULT '',\n"
524 " dst VARCHAR(80) NOT NULL DEFAULT '',\n"
525 " dcontext VARCHAR(80) NOT NULL DEFAULT '',\n"
526 " channel VARCHAR(80) NOT NULL DEFAULT '',\n"
527 " dstchannel VARCHAR(80) NOT NULL DEFAULT '',\n"
528 " lastapp VARCHAR(80) NOT NULL DEFAULT '',\n"
529 " lastdata VARCHAR(80) NOT NULL DEFAULT '',\n"
530 " start DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
531 " answer DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
532 " end DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
533 " duration INT(11) NOT NULL DEFAULT 0,\n"
534 " billsec INT(11) NOT NULL DEFAULT 0,\n"
535 " disposition VARCHAR(45) NOT NULL DEFAULT '',\n"
536 " amaflags INT(11) NOT NULL DEFAULT 0,\n"
537 " accountcode VARCHAR(20) NOT NULL DEFAULT '',\n"
538 " uniqueid VARCHAR(32) NOT NULL DEFAULT '',\n"
539 " userfield VARCHAR(255) NOT NULL DEFAULT '',\n"
540 " PRIMARY KEY (id)\n"
543 /*! SQL query format to insert a CDR entry. */
544 static char *sql_add_cdr_entry =
573 " datetime(%d,'unixepoch'),"
574 " datetime(%d,'unixepoch'),"
575 " datetime(%d,'unixepoch'),"
586 * SQL query format to fetch the static configuration of a file.
587 * Rows must be sorted by category.
589 * \see add_cfg_entry()
591 static char *sql_get_config_table =
594 " WHERE filename = '%q' AND commented = 0"
595 " ORDER BY cat_metric ASC, var_metric ASC;";
597 static int set_var(char **var, char *name, char *value)
602 *var = ast_strdup(value);
605 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
612 static int check_vars(void)
615 ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
619 use_cdr = (cdr_table != NULL);
624 static int load_config(void)
626 struct ast_config *config;
627 struct ast_variable *var;
629 struct ast_flags config_flags = { 0 };
631 config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
634 ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
638 for (var = ast_variable_browse(config, "general"); var; var = var->next) {
639 if (!strcasecmp(var->name, "dbfile"))
640 SET_VAR(config, dbfile, var);
641 else if (!strcasecmp(var->name, "config_table"))
642 SET_VAR(config, config_table, var);
643 else if (!strcasecmp(var->name, "cdr_table"))
644 SET_VAR(config, cdr_table, var);
646 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
649 ast_config_destroy(config);
650 error = check_vars();
660 static void unload_config(void)
664 ast_free(config_table);
670 static int cdr_handler(struct ast_cdr *cdr)
672 char *query, *errormsg;
675 query = sqlite_mprintf(sql_add_cdr_entry, cdr_table, cdr->clid,
676 cdr->src, cdr->dst, cdr->dcontext, cdr->channel,
677 cdr->dstchannel, cdr->lastapp, cdr->lastdata,
678 cdr->start.tv_sec, cdr->answer.tv_sec,
679 cdr->end.tv_sec, cdr->duration, cdr->billsec,
680 cdr->disposition, cdr->amaflags, cdr->accountcode,
681 cdr->uniqueid, cdr->userfield);
684 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
688 ast_debug(1, "SQL query: %s\n", query);
690 ast_mutex_lock(&mutex);
692 RES_CONFIG_SQLITE_BEGIN
693 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
694 RES_CONFIG_SQLITE_END(error)
696 ast_mutex_unlock(&mutex);
698 sqlite_freemem(query);
701 ast_log(LOG_ERROR, "%s\n", errormsg);
702 sqlite_freemem(errormsg);
709 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
711 struct cfg_entry_args *args;
712 struct ast_variable *var;
714 if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
715 ast_log(LOG_WARNING, "Corrupt table\n");
721 if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
722 struct ast_config *cfg;
725 val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
726 cfg = ast_config_internal_load(val, args->cfg, args->flags, "");
729 ast_log(LOG_WARNING, "Unable to include %s\n", val);
737 if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
738 args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
741 ast_log(LOG_WARNING, "Unable to allocate category\n");
745 ast_free(args->cat_name);
746 args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
748 if (!args->cat_name) {
749 ast_category_destroy(args->cat);
753 ast_category_append(args->cfg, args->cat);
756 var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
759 ast_log(LOG_WARNING, "Unable to allocate variable");
763 ast_variable_append(args->cat, var);
768 static struct ast_config *config_handler(const char *database, const char *table, const char *file,
769 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl)
771 struct cfg_entry_args args;
772 char *query, *errormsg;
777 ast_log(LOG_ERROR, "Table name unspecified\n");
781 table = config_table;
783 query = sqlite_mprintf(sql_get_config_table, table, file);
786 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
790 ast_debug(1, "SQL query: %s\n", query);
793 args.cat_name = NULL;
796 ast_mutex_lock(&mutex);
798 RES_CONFIG_SQLITE_BEGIN
799 error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
800 RES_CONFIG_SQLITE_END(error)
802 ast_mutex_unlock(&mutex);
804 ast_free(args.cat_name);
805 sqlite_freemem(query);
808 ast_log(LOG_ERROR, "%s\n", errormsg);
809 sqlite_freemem(errormsg);
816 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
818 const char **tmp, *param, *val, **params, **vals;
825 while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
826 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
833 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
840 params[params_count] = param;
841 vals[params_count] = val;
845 if (params_count > 0) {
846 *params_ptr = params;
849 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
854 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
856 struct rt_cfg_entry_args *args;
857 struct ast_variable *var;
862 for (i = 0; i < argc; i++) {
866 if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
875 args->last->next = var;
883 static struct ast_variable * realtime_handler(const char *database, const char *table, va_list ap)
885 char *query, *errormsg, *op, *tmp_str;
886 struct rt_cfg_entry_args args;
887 const char **params, **vals;
892 ast_log(LOG_WARNING, "Table name unspecified\n");
896 params_count = get_params(ap, ¶ms, &vals);
898 if (params_count == 0)
901 op = (strchr(params[0], ' ') == NULL) ? " =" : "";
903 /* \cond DOXYGEN_CAN_PARSE_THIS */
905 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
908 query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
911 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
917 if (params_count > 1) {
920 for (i = 1; i < params_count; i++) {
921 op = (strchr(params[i], ' ') == NULL) ? " =" : "";
922 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
923 sqlite_freemem(query);
926 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
939 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
940 sqlite_freemem(query);
943 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
948 ast_debug(1, "SQL query: %s\n", query);
952 ast_mutex_lock(&mutex);
954 RES_CONFIG_SQLITE_BEGIN
955 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
956 RES_CONFIG_SQLITE_END(error)
958 ast_mutex_unlock(&mutex);
960 sqlite_freemem(query);
963 ast_log(LOG_WARNING, "%s\n", errormsg);
964 sqlite_freemem(errormsg);
965 ast_variables_destroy(args.var);
972 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
974 struct rt_multi_cfg_entry_args *args;
975 struct ast_category *cat;
976 struct ast_variable *var;
984 * cat_name should always be set here, since initfield is forged from
985 * params[0] in realtime_multi_handler(), which is a search parameter
988 for (i = 0; i < argc; i++) {
989 if (!strcmp(args->initfield, columnNames[i]))
994 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
998 if (!(cat = ast_category_new(cat_name, "", 99999))) {
999 ast_log(LOG_WARNING, "Unable to allocate category\n");
1003 ast_category_append(args->cfg, cat);
1005 for (i = 0; i < argc; i++) {
1006 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
1009 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
1010 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1014 ast_variable_append(cat, var);
1020 static struct ast_config *realtime_multi_handler(const char *database,
1021 const char *table, va_list ap)
1023 char *query, *errormsg, *op, *tmp_str, *initfield;
1024 struct rt_multi_cfg_entry_args args;
1025 const char **params, **vals;
1026 struct ast_config *cfg;
1027 size_t params_count;
1031 ast_log(LOG_WARNING, "Table name unspecified\n");
1035 if (!(cfg = ast_config_new())) {
1036 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1040 if (!(params_count = get_params(ap, ¶ms, &vals))) {
1041 ast_config_destroy(cfg);
1045 if (!(initfield = ast_strdup(params[0]))) {
1046 ast_config_destroy(cfg);
1052 tmp_str = strchr(initfield, ' ');
1057 op = (!strchr(params[0], ' ')) ? " =" : "";
1060 * Asterisk sends us an already escaped string when searching for
1061 * "exten LIKE" (uh!). Handle it separately.
1063 tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1065 /* \cond DOXYGEN_CAN_PARSE_THIS */
1067 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1070 if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1071 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1072 ast_config_destroy(cfg);
1075 ast_free(initfield);
1079 if (params_count > 1) {
1082 for (i = 1; i < params_count; i++) {
1083 op = (!strchr(params[i], ' ')) ? " =" : "";
1084 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1085 sqlite_freemem(query);
1088 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1089 ast_config_destroy(cfg);
1092 ast_free(initfield);
1103 if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1104 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1105 ast_config_destroy(cfg);
1106 ast_free(initfield);
1110 sqlite_freemem(query);
1112 ast_debug(1, "SQL query: %s\n", query);
1114 args.initfield = initfield;
1116 ast_mutex_lock(&mutex);
1118 RES_CONFIG_SQLITE_BEGIN
1119 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1120 RES_CONFIG_SQLITE_END(error)
1122 ast_mutex_unlock(&mutex);
1124 sqlite_freemem(query);
1125 ast_free(initfield);
1128 ast_log(LOG_WARNING, "%s\n", errormsg);
1129 sqlite_freemem(errormsg);
1130 ast_config_destroy(cfg);
1137 static int realtime_update_handler(const char *database, const char *table,
1138 const char *keyfield, const char *entity, va_list ap)
1140 char *query, *errormsg, *tmp_str;
1141 const char **params, **vals;
1142 size_t params_count;
1143 int error, rows_num;
1146 ast_log(LOG_WARNING, "Table name unspecified\n");
1150 if (!(params_count = get_params(ap, ¶ms, &vals)))
1153 /* \cond DOXYGEN_CAN_PARSE_THIS */
1155 #define QUERY "UPDATE '%q' SET %q = '%q'"
1158 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1159 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1165 if (params_count > 1) {
1168 for (i = 1; i < params_count; i++) {
1169 tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
1170 sqlite_freemem(query);
1173 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1186 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1187 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1191 sqlite_freemem(query);
1193 ast_debug(1, "SQL query: %s\n", query);
1195 ast_mutex_lock(&mutex);
1197 RES_CONFIG_SQLITE_BEGIN
1198 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1199 RES_CONFIG_SQLITE_END(error)
1202 rows_num = sqlite_changes(db);
1206 ast_mutex_unlock(&mutex);
1208 sqlite_freemem(query);
1211 ast_log(LOG_WARNING, "%s\n", errormsg);
1212 sqlite_freemem(errormsg);
1218 static int realtime_store_handler(const char *database, const char *table, va_list ap) {
1219 char *errormsg, *tmp_str, *tmp_keys, *tmp_keys2, *tmp_vals, *tmp_vals2;
1220 const char **params, **vals;
1221 size_t params_count;
1226 ast_log(LOG_WARNING, "Table name unspecified\n");
1230 if (!(params_count = get_params(ap, ¶ms, &vals)))
1233 /* \cond DOXYGEN_CAN_PARSE_THIS */
1235 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1240 for (i = 0; i < params_count; i++) {
1242 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1243 sqlite_freemem(tmp_keys2);
1245 tmp_keys = sqlite_mprintf("%q", params[i]);
1248 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1255 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1256 sqlite_freemem(tmp_vals2);
1258 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1261 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1268 tmp_keys2 = tmp_keys;
1269 tmp_vals2 = tmp_vals;
1275 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1276 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1280 sqlite_freemem(tmp_keys);
1281 sqlite_freemem(tmp_vals);
1283 ast_debug(1, "SQL query: %s\n", tmp_str);
1285 ast_mutex_lock(&mutex);
1287 RES_CONFIG_SQLITE_BEGIN
1288 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1289 RES_CONFIG_SQLITE_END(error)
1292 rows_id = sqlite_last_insert_rowid(db);
1297 ast_mutex_unlock(&mutex);
1299 sqlite_freemem(tmp_str);
1302 ast_log(LOG_WARNING, "%s\n", errormsg);
1303 sqlite_freemem(errormsg);
1309 static int realtime_destroy_handler(const char *database, const char *table,
1310 const char *keyfield, const char *entity, va_list ap)
1312 char *query, *errormsg, *tmp_str;
1313 const char **params, **vals;
1314 size_t params_count;
1315 int error, rows_num;
1319 ast_log(LOG_WARNING, "Table name unspecified\n");
1323 if (!(params_count = get_params(ap, ¶ms, &vals)))
1326 /* \cond DOXYGEN_CAN_PARSE_THIS */
1328 #define QUERY "DELETE FROM '%q' WHERE"
1331 if (!(query = sqlite_mprintf(QUERY, table))) {
1332 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1338 for (i = 0; i < params_count; i++) {
1339 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1340 sqlite_freemem(query);
1343 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1354 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1355 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1358 sqlite_freemem(query);
1360 ast_debug(1, "SQL query: %s\n", query);
1362 ast_mutex_lock(&mutex);
1364 RES_CONFIG_SQLITE_BEGIN
1365 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1366 RES_CONFIG_SQLITE_END(error)
1369 rows_num = sqlite_changes(db);
1373 ast_mutex_unlock(&mutex);
1375 sqlite_freemem(query);
1378 ast_log(LOG_WARNING, "%s\n", errormsg);
1379 sqlite_freemem(errormsg);
1386 static int cli_status(int fd, int argc, char *argv[])
1388 ast_cli(fd, "SQLite database path: %s\n", dbfile);
1389 ast_cli(fd, "config_table: ");
1392 ast_cli(fd, "unspecified, must be present in extconfig.conf\n");
1394 ast_cli(fd, "%s\n", config_table);
1396 ast_cli(fd, "cdr_table: ");
1399 ast_cli(fd, "unspecified, CDR support disabled\n");
1401 ast_cli(fd, "%s\n", cdr_table);
1403 return RESULT_SUCCESS;
1406 static int unload_module(void)
1408 if (cli_status_registered)
1409 ast_cli_unregister(&cli_status_cmd);
1412 ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
1414 ast_config_engine_deregister(&sqlite_engine);
1424 static int load_module(void)
1431 cli_status_registered = 0;
1433 config_table = NULL;
1435 error = load_config();
1438 return AST_MODULE_LOAD_DECLINE;
1440 if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1441 ast_log(LOG_ERROR, "%s\n", errormsg);
1442 sqlite_freemem(errormsg);
1447 ast_config_engine_register(&sqlite_engine);
1452 /* \cond DOXYGEN_CAN_PARSE_THIS */
1454 #define QUERY "SELECT COUNT(id) FROM %Q;"
1457 query = sqlite_mprintf(QUERY, cdr_table);
1460 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1465 ast_debug(1, "SQL query: %s\n", query);
1467 RES_CONFIG_SQLITE_BEGIN
1468 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1469 RES_CONFIG_SQLITE_END(error)
1471 sqlite_freemem(query);
1477 if (error != SQLITE_ERROR) {
1478 ast_log(LOG_ERROR, "%s\n", errormsg);
1479 sqlite_freemem(errormsg);
1484 sqlite_freemem(errormsg);
1485 query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
1488 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1493 ast_debug(1, "SQL query: %s\n", query);
1495 RES_CONFIG_SQLITE_BEGIN
1496 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1497 RES_CONFIG_SQLITE_END(error)
1499 sqlite_freemem(query);
1502 ast_log(LOG_ERROR, "%s\n", errormsg);
1503 sqlite_freemem(errormsg);
1509 error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
1519 error = ast_cli_register(&cli_status_cmd);
1526 cli_status_registered = 1;
1531 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1532 .load = load_module,
1533 .unload = unload_module,