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>
85 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
93 #include "asterisk/pbx.h"
94 #include "asterisk/cdr.h"
95 #include "asterisk/cli.h"
96 #include "asterisk/lock.h"
97 #include "asterisk/config.h"
98 #include "asterisk/logger.h"
99 #include "asterisk/module.h"
100 #include "asterisk/options.h"
101 #include "asterisk/linkedlists.h"
103 #define MACRO_BEGIN do {
104 #define MACRO_END } while (0)
106 #define RES_CONFIG_SQLITE_NAME "res_config_sqlite"
107 #define RES_CONFIG_SQLITE_DRIVER "sqlite"
108 #define RES_CONFIG_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
109 #define RES_CONFIG_SQLITE_CONF_FILE "res_config_sqlite.conf"
112 RES_CONFIG_SQLITE_CONFIG_ID,
113 RES_CONFIG_SQLITE_CONFIG_CAT_METRIC,
114 RES_CONFIG_SQLITE_CONFIG_VAR_METRIC,
115 RES_CONFIG_SQLITE_CONFIG_COMMENTED,
116 RES_CONFIG_SQLITE_CONFIG_FILENAME,
117 RES_CONFIG_SQLITE_CONFIG_CATEGORY,
118 RES_CONFIG_SQLITE_CONFIG_VAR_NAME,
119 RES_CONFIG_SQLITE_CONFIG_VAR_VAL,
120 RES_CONFIG_SQLITE_CONFIG_COLUMNS,
123 #define SET_VAR(config, to, from) \
127 __error = set_var(&to, #to, from->value); \
130 ast_config_destroy(config); \
137 * Maximum number of loops before giving up executing a query. Calls to
138 * sqlite_xxx() functions which can return SQLITE_BUSY or SQLITE_LOCKED
139 * are enclosed by RES_CONFIG_SQLITE_BEGIN and RES_CONFIG_SQLITE_END, e.g.
144 * RES_CONFIG_SQLITE_BEGIN
145 * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
146 * RES_CONFIG_SQLITE_END(error)
152 #define RES_CONFIG_SQLITE_MAX_LOOPS 10
155 * Macro used before executing a query.
157 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
159 #define RES_CONFIG_SQLITE_BEGIN \
163 for (__i = 0; __i < RES_CONFIG_SQLITE_MAX_LOOPS; __i++) {
166 * Macro used after executing a query.
168 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
170 #define RES_CONFIG_SQLITE_END(error) \
171 if (error != SQLITE_BUSY && error != SQLITE_LOCKED) \
178 * Structure sent to the SQLite callback function for static configuration.
180 * \see add_cfg_entry()
182 struct cfg_entry_args {
183 struct ast_config *cfg;
184 struct ast_category *cat;
186 struct ast_flags flags;
190 * Structure sent to the SQLite callback function for RealTime configuration.
192 * \see add_rt_cfg_entry()
194 struct rt_cfg_entry_args {
195 struct ast_variable *var;
196 struct ast_variable *last;
200 * Structure sent to the SQLite callback function for RealTime configuration
201 * (realtime_multi_handler()).
203 * \see add_rt_multi_cfg_entry()
205 struct rt_multi_cfg_entry_args {
206 struct ast_config *cfg;
211 * \brief Allocate a variable.
212 * \param var the address of the variable to set (it will be allocated)
213 * \param name the name of the variable (for error handling)
214 * \param value the value to store in var
215 * \retval 0 on success
216 * \retval 1 if an allocation error occurred
218 static int set_var(char **var, char *name, char *value);
221 * \brief Load the configuration file.
222 * \see unload_config()
224 * This function sets dbfile, config_table, and cdr_table. It calls
225 * check_vars() before returning, and unload_config() if an error occurred.
227 * \retval 0 on success
228 * \retval 1 if an error occurred
230 static int load_config(void);
233 * \brief Free resources related to configuration.
236 static void unload_config(void);
239 * \brief Asterisk callback function for CDR support.
240 * \param cdr the CDR entry Asterisk sends us.
242 * Asterisk will call this function each time a CDR entry must be logged if
243 * CDR support is enabled.
245 * \retval 0 on success
246 * \retval 1 if an error occurred
248 static int cdr_handler(struct ast_cdr *cdr);
251 * \brief SQLite callback function for static configuration.
253 * This function is passed to the SQLite engine as a callback function to
254 * parse a row and store it in a struct ast_config object. It relies on
255 * resulting rows being sorted by category.
257 * \param arg a pointer to a struct cfg_entry_args object
258 * \param argc number of columns
259 * \param argv values in the row
260 * \param columnNames names and types of the columns
261 * \retval 0 on success
262 * \retval 1 if an error occurred
263 * \see cfg_entry_args
264 * \see sql_get_config_table
265 * \see config_handler()
267 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
270 * \brief Asterisk callback function for static configuration.
272 * Asterisk will call this function when it loads its static configuration,
273 * which usually happens at startup and reload.
275 * \param database the database to use (ignored)
276 * \param table the table to use
277 * \param file the file to load from the database
278 * \param cfg the struct ast_config object to use when storing variables
279 * \param flags Optional flags. Not used.
280 * \param suggested_incl suggest include.
282 * \retval NULL if an error occurred
283 * \see add_cfg_entry()
285 static struct ast_config * config_handler(const char *database, const char *table, const char *file,
286 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl);
289 * \brief Helper function to parse a va_list object into 2 dynamic arrays of
290 * strings, parameters and values.
292 * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
293 * arguments will be extracted to create 2 arrays:
296 * <li>params : param1 param2 param3 ...</li>
297 * <li>vals : val1 val2 val3 ...</li>
300 * The address of these arrays are stored in params_ptr and vals_ptr. It
301 * is the responsibility of the caller to release the memory of these arrays.
302 * It is considered an error that va_list has a null or odd number of strings.
304 * \param ap the va_list object to parse
305 * \param params_ptr where the address of the params array is stored
306 * \param vals_ptr where the address of the vals array is stored
307 * \retval the number of elements in the arrays (which have the same size).
308 * \retval 0 if an error occurred.
310 static size_t get_params(va_list ap, const char ***params_ptr,
311 const char ***vals_ptr);
314 * \brief SQLite callback function for RealTime configuration.
316 * This function is passed to the SQLite engine as a callback function to
317 * parse a row and store it in a linked list of struct ast_variable objects.
319 * \param arg a pointer to a struct rt_cfg_entry_args object
320 * \param argc number of columns
321 * \param argv values in the row
322 * \param columnNames names and types of the columns
323 * \retval 0 on success.
324 * \retval 1 if an error occurred.
325 * \see rt_cfg_entry_args
326 * \see realtime_handler()
328 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
332 * Asterisk callback function for RealTime configuration.
334 * Asterisk will call this function each time it requires a variable
335 * through the RealTime architecture. ap is a list of parameters and
336 * values used to find a specific row, e.g one parameter "name" and
337 * one value "123" so that the SQL query becomes <code>SELECT * FROM
338 * table WHERE name = '123';</code>.
340 * \param database the database to use (ignored)
341 * \param table the table to use
342 * \param ap list of parameters and values to match
344 * \retval a linked list of struct ast_variable objects
345 * \retval NULL if an error occurred
346 * \see add_rt_cfg_entry()
348 static struct ast_variable * realtime_handler(const char *database,
349 const char *table, va_list ap);
352 * \brief SQLite callback function for RealTime configuration.
354 * This function performs the same actions as add_rt_cfg_entry() except
355 * that the rt_multi_cfg_entry_args structure is designed to store
356 * categories in addition to variables.
358 * \param arg a pointer to a struct rt_multi_cfg_entry_args object
359 * \param argc number of columns
360 * \param argv values in the row
361 * \param columnNames names and types of the columns
362 * \retval 0 on success.
363 * \retval 1 if an error occurred.
364 * \see rt_multi_cfg_entry_args
365 * \see realtime_multi_handler()
367 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
371 * \brief Asterisk callback function for RealTime configuration.
373 * This function performs the same actions as realtime_handler() except
374 * that it can store variables per category, and can return several
377 * \param database the database to use (ignored)
378 * \param table the table to use
379 * \param ap list of parameters and values to match
380 * \retval a struct ast_config object storing categories and variables.
381 * \retval NULL if an error occurred.
383 * \see add_rt_multi_cfg_entry()
385 static struct ast_config * realtime_multi_handler(const char *database,
386 const char *table, va_list ap);
389 * \brief Asterisk callback function for RealTime configuration (variable
392 * Asterisk will call this function each time a variable has been modified
393 * internally and must be updated in the backend engine. keyfield and entity
394 * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
395 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
396 * same format as the other realtime functions.
398 * \param database the database to use (ignored)
399 * \param table the table to use
400 * \param keyfield the column of the matching cell
401 * \param entity the value of the matching cell
402 * \param ap list of parameters and new values to update in the database
403 * \retval the number of affected rows.
404 * \retval -1 if an error occurred.
406 static int realtime_update_handler(const char *database, const char *table,
407 const char *keyfield, const char *entity, va_list ap);
410 * \brief Asterisk callback function for RealTime configuration (variable
413 * Asterisk will call this function each time a variable has been created
414 * internally and must be stored in the backend engine.
415 * are used to find the row to update, e.g. ap is a list of parameters and
416 * values with the same format as the other realtime functions.
418 * \param database the database to use (ignored)
419 * \param table the table to use
420 * \param ap list of parameters and new values to insert into the database
421 * \retval the rowid of inserted row.
422 * \retval -1 if an error occurred.
424 static int realtime_store_handler(const char *database, const char *table,
428 * \brief Asterisk callback function for RealTime configuration (destroys
431 * Asterisk will call this function each time a variable has been destroyed
432 * internally and must be removed from the backend engine. keyfield and entity
433 * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
434 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
435 * same format as the other realtime functions.
437 * \param database the database to use (ignored)
438 * \param table the table to use
439 * \param keyfield the column of the matching cell
440 * \param entity the value of the matching cell
441 * \param ap list of additional parameters for cell matching
442 * \retval the number of affected rows.
443 * \retval -1 if an error occurred.
445 static int realtime_destroy_handler(const char *database, const char *table,
446 const char *keyfield, const char *entity, va_list ap);
449 * \brief Asterisk callback function for the CLI status command.
451 * \param e CLI command
453 * \param a CLI argument list
454 * \return RESULT_SUCCESS
456 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
458 /*! The SQLite database object. */
461 /*! Set to 1 if CDR support is enabled. */
464 /*! Set to 1 if the CDR callback function was registered. */
465 static int cdr_registered;
467 /*! Set to 1 if the CLI status command callback function was registered. */
468 static int cli_status_registered;
470 /*! The path of the database file. */
473 /*! The name of the static configuration table. */
474 static char *config_table;
476 /*! The name of the table used to store CDR entries. */
477 static char *cdr_table;
480 * The structure specifying all callback functions used by Asterisk for static
481 * and RealTime configuration.
483 static struct ast_config_engine sqlite_engine =
485 .name = RES_CONFIG_SQLITE_DRIVER,
486 .load_func = config_handler,
487 .realtime_func = realtime_handler,
488 .realtime_multi_func = realtime_multi_handler,
489 .store_func = realtime_store_handler,
490 .destroy_func = realtime_destroy_handler,
491 .update_func = realtime_update_handler
495 * The mutex used to prevent simultaneous access to the SQLite database.
497 AST_MUTEX_DEFINE_STATIC(mutex);
500 * Structure containing details and callback functions for the CLI status
503 static struct ast_cli_entry cli_status[] = {
504 AST_CLI_DEFINE(handle_cli_show_sqlite_status, "Show status information about the SQLite 2 driver"),
508 * Taken from Asterisk 1.2 cdr_sqlite.so.
511 /*! SQL query format to create the CDR table if non existent. */
512 static char *sql_create_cdr_table =
513 "CREATE TABLE '%q' (\n"
515 " clid VARCHAR(80) NOT NULL DEFAULT '',\n"
516 " src VARCHAR(80) NOT NULL DEFAULT '',\n"
517 " dst VARCHAR(80) NOT NULL DEFAULT '',\n"
518 " dcontext VARCHAR(80) NOT NULL DEFAULT '',\n"
519 " channel VARCHAR(80) NOT NULL DEFAULT '',\n"
520 " dstchannel VARCHAR(80) NOT NULL DEFAULT '',\n"
521 " lastapp VARCHAR(80) NOT NULL DEFAULT '',\n"
522 " lastdata VARCHAR(80) NOT NULL DEFAULT '',\n"
523 " start DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
524 " answer DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
525 " end DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
526 " duration INT(11) NOT NULL DEFAULT 0,\n"
527 " billsec INT(11) NOT NULL DEFAULT 0,\n"
528 " disposition VARCHAR(45) NOT NULL DEFAULT '',\n"
529 " amaflags INT(11) NOT NULL DEFAULT 0,\n"
530 " accountcode VARCHAR(20) NOT NULL DEFAULT '',\n"
531 " uniqueid VARCHAR(32) NOT NULL DEFAULT '',\n"
532 " userfield VARCHAR(255) NOT NULL DEFAULT '',\n"
533 " PRIMARY KEY (id)\n"
536 /*! SQL query format to insert a CDR entry. */
537 static char *sql_add_cdr_entry =
566 " datetime(%d,'unixepoch'),"
567 " datetime(%d,'unixepoch'),"
568 " datetime(%d,'unixepoch'),"
579 * SQL query format to fetch the static configuration of a file.
580 * Rows must be sorted by category.
582 * \see add_cfg_entry()
584 static char *sql_get_config_table =
587 " WHERE filename = '%q' AND commented = 0"
588 " ORDER BY cat_metric ASC, var_metric ASC;";
590 static int set_var(char **var, char *name, char *value)
595 *var = ast_strdup(value);
598 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
605 static int check_vars(void)
608 ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
612 use_cdr = (cdr_table != NULL);
617 static int load_config(void)
619 struct ast_config *config;
620 struct ast_variable *var;
622 struct ast_flags config_flags = { 0 };
624 config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
627 ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
631 for (var = ast_variable_browse(config, "general"); var; var = var->next) {
632 if (!strcasecmp(var->name, "dbfile"))
633 SET_VAR(config, dbfile, var);
634 else if (!strcasecmp(var->name, "config_table"))
635 SET_VAR(config, config_table, var);
636 else if (!strcasecmp(var->name, "cdr_table"))
637 SET_VAR(config, cdr_table, var);
639 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
642 ast_config_destroy(config);
643 error = check_vars();
653 static void unload_config(void)
657 ast_free(config_table);
663 static int cdr_handler(struct ast_cdr *cdr)
665 char *query, *errormsg;
668 query = sqlite_mprintf(sql_add_cdr_entry, cdr_table, cdr->clid,
669 cdr->src, cdr->dst, cdr->dcontext, cdr->channel,
670 cdr->dstchannel, cdr->lastapp, cdr->lastdata,
671 cdr->start.tv_sec, cdr->answer.tv_sec,
672 cdr->end.tv_sec, cdr->duration, cdr->billsec,
673 cdr->disposition, cdr->amaflags, cdr->accountcode,
674 cdr->uniqueid, cdr->userfield);
677 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
681 ast_debug(1, "SQL query: %s\n", query);
683 ast_mutex_lock(&mutex);
685 RES_CONFIG_SQLITE_BEGIN
686 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
687 RES_CONFIG_SQLITE_END(error)
689 ast_mutex_unlock(&mutex);
691 sqlite_freemem(query);
694 ast_log(LOG_ERROR, "%s\n", errormsg);
695 sqlite_freemem(errormsg);
702 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
704 struct cfg_entry_args *args;
705 struct ast_variable *var;
707 if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
708 ast_log(LOG_WARNING, "Corrupt table\n");
714 if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
715 struct ast_config *cfg;
718 val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
719 cfg = ast_config_internal_load(val, args->cfg, args->flags, "");
722 ast_log(LOG_WARNING, "Unable to include %s\n", val);
730 if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
731 args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
734 ast_log(LOG_WARNING, "Unable to allocate category\n");
738 ast_free(args->cat_name);
739 args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
741 if (!args->cat_name) {
742 ast_category_destroy(args->cat);
746 ast_category_append(args->cfg, args->cat);
749 var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
752 ast_log(LOG_WARNING, "Unable to allocate variable");
756 ast_variable_append(args->cat, var);
761 static struct ast_config *config_handler(const char *database, const char *table, const char *file,
762 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl)
764 struct cfg_entry_args args;
765 char *query, *errormsg;
770 ast_log(LOG_ERROR, "Table name unspecified\n");
774 table = config_table;
776 query = sqlite_mprintf(sql_get_config_table, table, file);
779 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
783 ast_debug(1, "SQL query: %s\n", query);
786 args.cat_name = NULL;
789 ast_mutex_lock(&mutex);
791 RES_CONFIG_SQLITE_BEGIN
792 error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
793 RES_CONFIG_SQLITE_END(error)
795 ast_mutex_unlock(&mutex);
797 ast_free(args.cat_name);
798 sqlite_freemem(query);
801 ast_log(LOG_ERROR, "%s\n", errormsg);
802 sqlite_freemem(errormsg);
809 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
811 const char **tmp, *param, *val, **params, **vals;
818 while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
819 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
826 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
833 params[params_count] = param;
834 vals[params_count] = val;
838 if (params_count > 0) {
839 *params_ptr = params;
842 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
847 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
849 struct rt_cfg_entry_args *args;
850 struct ast_variable *var;
855 for (i = 0; i < argc; i++) {
859 if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
868 args->last->next = var;
876 static struct ast_variable * realtime_handler(const char *database, const char *table, va_list ap)
878 char *query, *errormsg, *op, *tmp_str;
879 struct rt_cfg_entry_args args;
880 const char **params, **vals;
885 ast_log(LOG_WARNING, "Table name unspecified\n");
889 params_count = get_params(ap, ¶ms, &vals);
891 if (params_count == 0)
894 op = (strchr(params[0], ' ') == NULL) ? " =" : "";
896 /* \cond DOXYGEN_CAN_PARSE_THIS */
898 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
901 query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
904 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
910 if (params_count > 1) {
913 for (i = 1; i < params_count; i++) {
914 op = (strchr(params[i], ' ') == NULL) ? " =" : "";
915 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
916 sqlite_freemem(query);
919 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
932 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
933 sqlite_freemem(query);
936 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
941 ast_debug(1, "SQL query: %s\n", query);
945 ast_mutex_lock(&mutex);
947 RES_CONFIG_SQLITE_BEGIN
948 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
949 RES_CONFIG_SQLITE_END(error)
951 ast_mutex_unlock(&mutex);
953 sqlite_freemem(query);
956 ast_log(LOG_WARNING, "%s\n", errormsg);
957 sqlite_freemem(errormsg);
958 ast_variables_destroy(args.var);
965 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
967 struct rt_multi_cfg_entry_args *args;
968 struct ast_category *cat;
969 struct ast_variable *var;
977 * cat_name should always be set here, since initfield is forged from
978 * params[0] in realtime_multi_handler(), which is a search parameter
981 for (i = 0; i < argc; i++) {
982 if (!strcmp(args->initfield, columnNames[i]))
987 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
991 if (!(cat = ast_category_new(cat_name, "", 99999))) {
992 ast_log(LOG_WARNING, "Unable to allocate category\n");
996 ast_category_append(args->cfg, cat);
998 for (i = 0; i < argc; i++) {
999 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
1002 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
1003 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1007 ast_variable_append(cat, var);
1013 static struct ast_config *realtime_multi_handler(const char *database,
1014 const char *table, va_list ap)
1016 char *query, *errormsg, *op, *tmp_str, *initfield;
1017 struct rt_multi_cfg_entry_args args;
1018 const char **params, **vals;
1019 struct ast_config *cfg;
1020 size_t params_count;
1024 ast_log(LOG_WARNING, "Table name unspecified\n");
1028 if (!(cfg = ast_config_new())) {
1029 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1033 if (!(params_count = get_params(ap, ¶ms, &vals))) {
1034 ast_config_destroy(cfg);
1038 if (!(initfield = ast_strdup(params[0]))) {
1039 ast_config_destroy(cfg);
1045 tmp_str = strchr(initfield, ' ');
1050 op = (!strchr(params[0], ' ')) ? " =" : "";
1053 * Asterisk sends us an already escaped string when searching for
1054 * "exten LIKE" (uh!). Handle it separately.
1056 tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1058 /* \cond DOXYGEN_CAN_PARSE_THIS */
1060 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1063 if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1064 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1065 ast_config_destroy(cfg);
1068 ast_free(initfield);
1072 if (params_count > 1) {
1075 for (i = 1; i < params_count; i++) {
1076 op = (!strchr(params[i], ' ')) ? " =" : "";
1077 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1078 sqlite_freemem(query);
1081 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1082 ast_config_destroy(cfg);
1085 ast_free(initfield);
1096 if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1097 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1098 ast_config_destroy(cfg);
1099 ast_free(initfield);
1103 sqlite_freemem(query);
1105 ast_debug(1, "SQL query: %s\n", query);
1107 args.initfield = initfield;
1109 ast_mutex_lock(&mutex);
1111 RES_CONFIG_SQLITE_BEGIN
1112 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1113 RES_CONFIG_SQLITE_END(error)
1115 ast_mutex_unlock(&mutex);
1117 sqlite_freemem(query);
1118 ast_free(initfield);
1121 ast_log(LOG_WARNING, "%s\n", errormsg);
1122 sqlite_freemem(errormsg);
1123 ast_config_destroy(cfg);
1130 static int realtime_update_handler(const char *database, const char *table,
1131 const char *keyfield, const char *entity, va_list ap)
1133 char *query, *errormsg, *tmp_str;
1134 const char **params, **vals;
1135 size_t params_count;
1136 int error, rows_num;
1139 ast_log(LOG_WARNING, "Table name unspecified\n");
1143 if (!(params_count = get_params(ap, ¶ms, &vals)))
1146 /* \cond DOXYGEN_CAN_PARSE_THIS */
1148 #define QUERY "UPDATE '%q' SET %q = '%q'"
1151 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1152 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1158 if (params_count > 1) {
1161 for (i = 1; i < params_count; i++) {
1162 tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
1163 sqlite_freemem(query);
1166 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1179 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1180 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1184 sqlite_freemem(query);
1186 ast_debug(1, "SQL query: %s\n", query);
1188 ast_mutex_lock(&mutex);
1190 RES_CONFIG_SQLITE_BEGIN
1191 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1192 RES_CONFIG_SQLITE_END(error)
1195 rows_num = sqlite_changes(db);
1199 ast_mutex_unlock(&mutex);
1201 sqlite_freemem(query);
1204 ast_log(LOG_WARNING, "%s\n", errormsg);
1205 sqlite_freemem(errormsg);
1211 static int realtime_store_handler(const char *database, const char *table, va_list ap) {
1212 char *errormsg, *tmp_str, *tmp_keys, *tmp_keys2, *tmp_vals, *tmp_vals2;
1213 const char **params, **vals;
1214 size_t params_count;
1219 ast_log(LOG_WARNING, "Table name unspecified\n");
1223 if (!(params_count = get_params(ap, ¶ms, &vals)))
1226 /* \cond DOXYGEN_CAN_PARSE_THIS */
1228 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1233 for (i = 0; i < params_count; i++) {
1235 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1236 sqlite_freemem(tmp_keys2);
1238 tmp_keys = sqlite_mprintf("%q", params[i]);
1241 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1248 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1249 sqlite_freemem(tmp_vals2);
1251 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1254 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1261 tmp_keys2 = tmp_keys;
1262 tmp_vals2 = tmp_vals;
1268 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1269 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1273 sqlite_freemem(tmp_keys);
1274 sqlite_freemem(tmp_vals);
1276 ast_debug(1, "SQL query: %s\n", tmp_str);
1278 ast_mutex_lock(&mutex);
1280 RES_CONFIG_SQLITE_BEGIN
1281 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1282 RES_CONFIG_SQLITE_END(error)
1285 rows_id = sqlite_last_insert_rowid(db);
1290 ast_mutex_unlock(&mutex);
1292 sqlite_freemem(tmp_str);
1295 ast_log(LOG_WARNING, "%s\n", errormsg);
1296 sqlite_freemem(errormsg);
1302 static int realtime_destroy_handler(const char *database, const char *table,
1303 const char *keyfield, const char *entity, va_list ap)
1305 char *query, *errormsg, *tmp_str;
1306 const char **params, **vals;
1307 size_t params_count;
1308 int error, rows_num;
1312 ast_log(LOG_WARNING, "Table name unspecified\n");
1316 if (!(params_count = get_params(ap, ¶ms, &vals)))
1319 /* \cond DOXYGEN_CAN_PARSE_THIS */
1321 #define QUERY "DELETE FROM '%q' WHERE"
1324 if (!(query = sqlite_mprintf(QUERY, table))) {
1325 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1331 for (i = 0; i < params_count; i++) {
1332 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1333 sqlite_freemem(query);
1336 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1347 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1348 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1351 sqlite_freemem(query);
1353 ast_debug(1, "SQL query: %s\n", query);
1355 ast_mutex_lock(&mutex);
1357 RES_CONFIG_SQLITE_BEGIN
1358 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1359 RES_CONFIG_SQLITE_END(error)
1362 rows_num = sqlite_changes(db);
1366 ast_mutex_unlock(&mutex);
1368 sqlite_freemem(query);
1371 ast_log(LOG_WARNING, "%s\n", errormsg);
1372 sqlite_freemem(errormsg);
1378 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1382 e->command = "show sqlite status";
1384 "Usage: show sqlite status\n"
1385 " Show status information about the SQLite 2 driver\n";
1392 return CLI_SHOWUSAGE;
1394 ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
1395 ast_cli(a->fd, "config_table: ");
1398 ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
1400 ast_cli(a->fd, "%s\n", config_table);
1402 ast_cli(a->fd, "cdr_table: ");
1405 ast_cli(a->fd, "unspecified, CDR support disabled\n");
1407 ast_cli(a->fd, "%s\n", cdr_table);
1412 static int unload_module(void)
1414 if (cli_status_registered)
1415 ast_cli_unregister_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1418 ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
1420 ast_config_engine_deregister(&sqlite_engine);
1430 static int load_module(void)
1437 cli_status_registered = 0;
1439 config_table = NULL;
1441 error = load_config();
1444 return AST_MODULE_LOAD_DECLINE;
1446 if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1447 ast_log(LOG_ERROR, "%s\n", errormsg);
1448 sqlite_freemem(errormsg);
1453 ast_config_engine_register(&sqlite_engine);
1458 /* \cond DOXYGEN_CAN_PARSE_THIS */
1460 #define QUERY "SELECT COUNT(id) FROM %Q;"
1463 query = sqlite_mprintf(QUERY, cdr_table);
1466 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1471 ast_debug(1, "SQL query: %s\n", query);
1473 RES_CONFIG_SQLITE_BEGIN
1474 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1475 RES_CONFIG_SQLITE_END(error)
1477 sqlite_freemem(query);
1483 if (error != SQLITE_ERROR) {
1484 ast_log(LOG_ERROR, "%s\n", errormsg);
1485 sqlite_freemem(errormsg);
1490 sqlite_freemem(errormsg);
1491 query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
1494 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1499 ast_debug(1, "SQL query: %s\n", query);
1501 RES_CONFIG_SQLITE_BEGIN
1502 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1503 RES_CONFIG_SQLITE_END(error)
1505 sqlite_freemem(query);
1508 ast_log(LOG_ERROR, "%s\n", errormsg);
1509 sqlite_freemem(errormsg);
1515 error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
1525 error = ast_cli_register_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1532 cli_status_registered = 1;
1537 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1538 .load = load_module,
1539 .unload = unload_module,