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_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_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_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_sqlite will create it if is 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_sqlite for static and/or RealTime configuration, refer to the
62 * Asterisk documentation. The file tables.sql can be used to create the
65 * The SQLITE() application is very similar to the MYSQL() application. You
66 * can find more details at
67 * <a href="http://voip-info.org/wiki/view/Asterisk+cmd+MYSQL">http://voip-info.org/wiki/view/Asterisk+cmd+MYSQL</a>.
68 * The main difference is that you cannot choose your database - it's the
69 * file set in the <code>dbfile</code> parameter. As a result, there is no
70 * Connect or Disconnect command, and there is no connid variable.
72 * \section status_sec Driver status
74 * The CLI command <code>show sqlite status</code> returns status information
75 * about the running driver. One information is more important than others:
76 * the number of registered virtual machines. A SQLite virtual machine is
77 * created each time a SQLITE() query command is used. If the number of
78 * registered virtual machines isn't 0 (or near 0, since one or more SQLITE()
79 * commands can be running when requesting the module status) and increases
80 * over time, this probably means that you're badly using the application
81 * and you're creating resource leaks. You should check your Dialplan and
82 * reload res_sqlite (by unloading and then loading again - reloading isn't
85 * \section credits_sec Credits
87 * res_config_sqlite was developed by Richard Braun at the Proformatique company.
92 * \brief res_sqlite module.
96 <depend>sqlite</depend>
107 #include "asterisk/pbx.h"
108 #include "asterisk/cdr.h"
109 #include "asterisk/cli.h"
110 #include "asterisk/lock.h"
111 #include "asterisk/config.h"
112 #include "asterisk/logger.h"
113 #include "asterisk/module.h"
114 #include "asterisk/options.h"
115 #include "asterisk/linkedlists.h"
117 #define RES_SQLITE_NAME "res_sqlite"
118 #define RES_SQLITE_DRIVER "sqlite"
119 #define RES_SQLITE_APP_DRIVER "SQLITE"
120 #define RES_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
121 #define RES_SQLITE_CONF_FILE "res_config_sqlite.conf"
122 #define RES_SQLITE_APP_SYNOPSIS "Dialplan access to SQLite 2"
123 #define RES_SQLITE_APP_DESCRIPTION \
124 "SQLITE(): " RES_SQLITE_APP_SYNOPSIS "\n"
125 #define RES_SQLITE_STATUS_SUMMARY \
126 "Show status information about the SQLite 2 driver"
127 #define RES_SQLITE_STATUS_USAGE \
128 "Usage: show sqlite status\n" \
129 " " RES_SQLITE_STATUS_SUMMARY "\n"
132 RES_SQLITE_CONFIG_ID,
133 RES_SQLITE_CONFIG_COMMENTED,
134 RES_SQLITE_CONFIG_FILENAME,
135 RES_SQLITE_CONFIG_CATEGORY,
136 RES_SQLITE_CONFIG_VAR_NAME,
137 RES_SQLITE_CONFIG_VAR_VAL,
138 RES_SQLITE_CONFIG_COLUMNS,
142 * Limit the number of maximum simultaneous registered SQLite VMs to avoid
143 * a denial of service attack.
145 #define RES_SQLITE_VM_MAX 1024
147 #define SET_VAR(config, to, from) \
151 __error = set_var(&to, #to, from->value); \
154 ast_config_destroy(config); \
162 * Maximum number of loops before giving up executing a query. Calls to
163 * sqlite_xxx() functions which can return SQLITE_BUSY or SQLITE_LOCKED
164 * are enclosed by RES_SQLITE_BEGIN and RES_SQLITE_END, e.g.
170 * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
171 * RES_SQLITE_END(error)
177 #define RES_SQLITE_MAX_LOOPS 10
180 * Macro used before executing a query.
182 * \see RES_SQLITE_MAX_LOOPS.
184 #define RES_SQLITE_BEGIN \
187 for (__i = 0; __i < RES_SQLITE_MAX_LOOPS; __i++) \
191 * Macro used after executing a query.
193 * \see RES_SQLITE_MAX_LOOPS.
195 #define RES_SQLITE_END(error) \
196 if (error != SQLITE_BUSY && error != SQLITE_LOCKED) \
203 * Structure sent to the SQLite callback function for static configuration.
205 * \see add_cfg_entry()
207 struct cfg_entry_args {
208 struct ast_config *cfg;
209 struct ast_category *cat;
214 * Structure sent to the SQLite callback function for RealTime configuration.
216 * \see add_rt_cfg_entry()
218 struct rt_cfg_entry_args {
219 struct ast_variable *var;
220 struct ast_variable *last;
224 * Structure sent to the SQLite callback function for RealTime configuration
225 * (realtime_multi_handler()).
227 * \see add_rt_multi_cfg_entry()
229 struct rt_multi_cfg_entry_args {
230 struct ast_config *cfg;
235 * \brief Allocate a variable.
236 * \param var the address of the variable to set (it will be allocated)
237 * \param name the name of the variable (for error handling)
238 * \param value the value to store in var
239 * \retval 0 on success
240 * \retval 1 if an allocation error occurred
242 static int set_var(char **var, char *name, char *value);
245 * \brief Load the configuration file.
246 * \see unload_config()
248 * This function sets dbfile, config_table, and cdr_table. It calls
249 * check_vars() before returning, and unload_config() if an error occurred.
251 * \retval 0 on success
252 * \retval 1 if an error occurred
254 static int load_config(void);
257 * \brief Free resources related to configuration.
260 static void unload_config(void);
263 * \brief Asterisk callback function for CDR support.
264 * \param cdr the CDR entry Asterisk sends us
266 * Asterisk will call this function each time a CDR entry must be logged if
267 * CDR support is enabled.
269 * \retval 0 on success
270 * \retval 1 if an error occurred
272 static int cdr_handler(struct ast_cdr *cdr);
275 * \brief SQLite callback function for static configuration.
277 * This function is passed to the SQLite engine as a callback function to
278 * parse a row and store it in a struct ast_config object. It relies on
279 * resulting rows being sorted by category.
281 * \param arg a pointer to a struct cfg_entry_args object
282 * \param argc number of columns
283 * \param argv values in the row
284 * \param columnNames names and types of the columns
285 * \retval 0 on success
286 * \retval 1 if an error occurred
287 * \see cfg_entry_args
288 * \see sql_get_config_table
289 * \see config_handler()
291 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
294 * \brief Asterisk callback function for static configuration.
296 * Asterisk will call this function when it loads its static configuration,
297 * which usually happens at startup and reload.
299 * \param database the database to use (ignored)
300 * \param table the table to use
301 * \param file the file to load from the database
302 * \param cfg the struct ast_config object to use when storing variables
303 * \param flags Optional flags. Not used.
305 * \retval NULL if an error occurred
306 * \see add_cfg_entry()
308 static struct ast_config * config_handler(const char *database, const char *table, const char *file,
309 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl);
312 * \brief Helper function to parse a va_list object into 2 dynamic arrays of
313 * strings, parameters and values.
315 * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
316 * arguments will be extracted to create 2 arrays:
319 * <li>params : param1 param2 param3 ...</li>
320 * <li>vals : val1 val2 val3 ...</li>
323 * The address of these arrays are stored in params_ptr and vals_ptr. It
324 * is the responsibility of the caller to release the memory of these arrays.
325 * It is considered an error that va_list has a null or odd number of strings.
327 * \param ap the va_list object to parse
328 * \param params_ptr where the address of the params array is stored
329 * \param vals_ptr where the address of the vals array is stored
330 * \retval the number of elements in the arrays (which have the same size).
331 * \retval 0 if an error occurred.
333 static size_t get_params(va_list ap, const char ***params_ptr,
334 const char ***vals_ptr);
337 * \brief SQLite callback function for RealTime configuration.
339 * This function is passed to the SQLite engine as a callback function to
340 * parse a row and store it in a linked list of struct ast_variable objects.
342 * \param arg a pointer to a struct rt_cfg_entry_args object
343 * \param argc number of columns
344 * \param argv values in the row
345 * \param columnNames names and types of the columns
346 * \retval 0 on success.
347 * \retval 1 if an error occurred.
348 * \see rt_cfg_entry_args
349 * \see realtime_handler()
351 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
355 * Asterisk callback function for RealTime configuration.
357 * Asterisk will call this function each time it requires a variable
358 * through the RealTime architecture. ap is a list of parameters and
359 * values used to find a specific row, e.g one parameter "name" and
360 * one value "123" so that the SQL query becomes <code>SELECT * FROM
361 * table WHERE name = '123';</code>.
363 * \param database the database to use (ignored)
364 * \param table the table to use
365 * \param ap list of parameters and values to match
367 * \retval a linked list of struct ast_variable objects
368 * \retval NULL if an error occurred
369 * \see add_rt_cfg_entry()
371 static struct ast_variable * realtime_handler(const char *database,
372 const char *table, va_list ap);
375 * \brief SQLite callback function for RealTime configuration.
377 * This function performs the same actions as add_rt_cfg_entry() except
378 * that the rt_multi_cfg_entry_args structure is designed to store
379 * categories in addition of variables.
381 * \param arg a pointer to a struct rt_multi_cfg_entry_args object
382 * \param argc number of columns
383 * \param argv values in the row
384 * \param columnNames names and types of the columns
385 * \retval 0 on success.
386 * \retval 1 if an error occurred.
387 * \see rt_multi_cfg_entry_args
388 * \see realtime_multi_handler()
390 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
394 * \brief Asterisk callback function for RealTime configuration.
396 * This function performs the same actions as realtime_handler() except
397 * that it can store variables per category, and can return several
400 * \param database the database to use (ignored)
401 * \param table the table to use
402 * \param ap list of parameters and values to match
403 * \retval a struct ast_config object storing categories and variables.
404 * \retval NULL if an error occurred.
406 * \see add_rt_multi_cfg_entry()
408 static struct ast_config * realtime_multi_handler(const char *database,
413 * \brief Asterisk callback function for RealTime configuration (variable
416 * Asterisk will call this function each time a variable has been modified
417 * internally and must be updated in the backend engine. keyfield and entity
418 * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
419 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
420 * same format as the other realtime functions.
422 * \param database the database to use (ignored)
423 * \param table the table to use
424 * \param keyfield the column of the matching cell
425 * \param entity the value of the matching cell
426 * \param ap list of parameters and new values to update in the database
427 * \retval the number of affected rows.
428 * \retval -1 if an error occurred.
430 static int realtime_update_handler(const char *database, const char *table,
431 const char *keyfield, const char *entity,
435 * \brief Asterisk callback function for RealTime configuration (variable
438 * Asterisk will call this function each time a variable has been created
439 * internally and must be stored in the backend engine.
440 * are used to find the row to update, e.g. ap is a list of parameters and
441 * values with the same format as the other realtime functions.
443 * \param database the database to use (ignored)
444 * \param table the table to use
445 * \param ap list of parameters and new values to insert into the database
446 * \retval the rowid of inserted row.
447 * \retval -1 if an error occurred.
449 static int realtime_store_handler(const char *database, const char *table,
453 * \brief Asterisk callback function for RealTime configuration (destroys
456 * Asterisk will call this function each time a variable has been destroyed
457 * internally and must be removed from the backend engine. keyfield and entity
458 * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
459 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
460 * same format as the other realtime functions.
462 * \param database the database to use (ignored)
463 * \param table the table to use
464 * \param keyfield the column of the matching cell
465 * \param entity the value of the matching cell
466 * \param ap list of additional parameters for cell matching
467 * \retval the number of affected rows.
468 * \retval -1 if an error occurred.
470 static int realtime_destroy_handler(const char *database, const char *table,
471 const char *keyfield, const char *entity,
475 * \brief Asterisk callback function for the CLI status command.
477 * \param fd file descriptor provided by Asterisk to use with ast_cli()
478 * \param argc number of arguments
479 * \param argv arguments list
480 * \return RESULT_SUCCESS
482 static int cli_status(int fd, int argc, char *argv[]);
484 /*! The SQLite database object. */
487 /*! Set to 1 if CDR support is enabled. */
490 /*! Set to 1 if the CDR callback function was registered. */
491 static int cdr_registered;
493 /*! Set to 1 if the CLI status command callback function was registered. */
494 static int cli_status_registered;
496 /*! The path of the database file. */
499 /*! The name of the static configuration table. */
500 static char *config_table;
502 /*! The name of the table used to store CDR entries. */
503 static char *cdr_table;
505 /*! The number of registered virtual machines. */
509 * The structure specifying all callback functions used by Asterisk for static
510 * and RealTime configuration.
512 static struct ast_config_engine sqlite_engine =
514 .name = RES_SQLITE_DRIVER,
515 .load_func = config_handler,
516 .realtime_func = realtime_handler,
517 .realtime_multi_func = realtime_multi_handler,
518 .store_func = realtime_store_handler,
519 .destroy_func = realtime_destroy_handler,
520 .update_func = realtime_update_handler
524 * The mutex used to prevent simultaneous access to the SQLite database.
525 * SQLite isn't always compiled with thread safety.
527 AST_MUTEX_DEFINE_STATIC(mutex);
530 * Structure containing details and callback functions for the CLI status
533 static struct ast_cli_entry cli_status_cmd =
535 .cmda = {"show", "sqlite", "status", NULL},
536 .handler = cli_status,
537 .summary = RES_SQLITE_STATUS_SUMMARY,
538 .usage = RES_SQLITE_STATUS_USAGE
542 * Taken from Asterisk 1.2 cdr_sqlite.so.
545 /*! SQL query format to create the CDR table if non existent. */
546 static char *sql_create_cdr_table =
547 "CREATE TABLE '%q' ("
548 " id INTEGER PRIMARY KEY,"
549 " clid VARCHAR(80) NOT NULL DEFAULT '',"
550 " src VARCHAR(80) NOT NULL DEFAULT '',"
551 " dst VARCHAR(80) NOT NULL DEFAULT '',"
552 " dcontext VARCHAR(80) NOT NULL DEFAULT '',"
553 " channel VARCHAR(80) NOT NULL DEFAULT '',"
554 " dstchannel VARCHAR(80) NOT NULL DEFAULT '',"
555 " lastapp VARCHAR(80) NOT NULL DEFAULT '',"
556 " lastdata VARCHAR(80) NOT NULL DEFAULT '',"
557 " start CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
558 " answer CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
559 " end CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
560 " duration INT(11) NOT NULL DEFAULT '0',"
561 " billsec INT(11) NOT NULL DEFAULT '0',"
562 " disposition INT(11) NOT NULL DEFAULT '0',"
563 " amaflags INT(11) NOT NULL DEFAULT '0',"
564 " accountcode VARCHAR(20) NOT NULL DEFAULT '',"
565 " uniqueid VARCHAR(32) NOT NULL DEFAULT '',"
566 " userfield VARCHAR(255) NOT NULL DEFAULT ''"
569 /*! SQL query format to insert a CDR entry. */
570 static char *sql_add_cdr_entry =
599 " datetime(%d,'unixepoch'),"
600 " datetime(%d,'unixepoch'),"
601 " datetime(%d,'unixepoch'),"
612 * SQL query format to fetch the static configuration of a file.
613 * Rows must be sorted by category.
615 * \see add_cfg_entry()
617 static char *sql_get_config_table =
620 " WHERE filename = '%q' AND commented = 0"
621 " ORDER BY category;";
623 static int set_var(char **var, char *name, char *value)
628 *var = ast_strdup(value);
631 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
638 static int check_vars(void)
641 ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
645 use_cdr = (cdr_table != NULL);
650 static int load_config(void)
652 struct ast_config *config;
653 struct ast_variable *var;
655 struct ast_flags config_flags = { 0 };
657 config = ast_config_load(RES_SQLITE_CONF_FILE, config_flags);
660 ast_log(LOG_ERROR, "Unable to load " RES_SQLITE_CONF_FILE "\n");
664 for (var = ast_variable_browse(config, "general"); var; var = var->next) {
665 if (!strcasecmp(var->name, "dbfile"))
666 SET_VAR(config, dbfile, var);
667 else if (!strcasecmp(var->name, "config_table"))
668 SET_VAR(config, config_table, var);
669 else if (!strcasecmp(var->name, "cdr_table"))
670 SET_VAR(config, cdr_table, var);
672 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
675 ast_config_destroy(config);
676 error = check_vars();
686 static void unload_config(void)
690 ast_free(config_table);
696 static int cdr_handler(struct ast_cdr *cdr)
701 ast_mutex_lock(&mutex);
704 error = sqlite_exec_printf(db, sql_add_cdr_entry, NULL, NULL, &errormsg,
705 cdr_table, cdr->clid, cdr->src, cdr->dst,
706 cdr->dcontext, cdr->channel, cdr->dstchannel,
707 cdr->lastapp, cdr->lastdata, cdr->start.tv_sec,
708 cdr->answer.tv_sec, cdr->end.tv_sec,
709 cdr->duration, cdr->billsec, cdr->disposition,
710 cdr->amaflags, cdr->accountcode, cdr->uniqueid,
712 RES_SQLITE_END(error)
714 ast_mutex_unlock(&mutex);
717 ast_log(LOG_ERROR, "%s\n", errormsg);
725 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
727 struct cfg_entry_args *args;
728 struct ast_variable *var;
730 if (argc != RES_SQLITE_CONFIG_COLUMNS) {
731 ast_log(LOG_WARNING, "Corrupt table\n");
737 if (!args->cat_name || strcmp(args->cat_name, argv[RES_SQLITE_CONFIG_CATEGORY])) {
738 args->cat = ast_category_new(argv[RES_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_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_SQLITE_CONFIG_VAR_NAME],
757 argv[RES_SQLITE_CONFIG_VAR_VAL], "");
760 ast_log(LOG_WARNING, "Unable to allocate variable");
764 ast_variable_append(args->cat, var);
769 static struct ast_config *config_handler(const char *database, const char *table, const char *file,
770 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl)
772 struct cfg_entry_args args;
778 ast_log(LOG_ERROR, "Table name unspecified\n");
782 table = config_table;
786 args.cat_name = NULL;
788 ast_mutex_lock(&mutex);
791 error = sqlite_exec_printf(db, sql_get_config_table, add_cfg_entry,
792 &args, &errormsg, table, file);
793 RES_SQLITE_END(error)
795 ast_mutex_unlock(&mutex);
797 ast_free(args.cat_name);
800 ast_log(LOG_ERROR, "%s\n", errormsg);
808 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
810 const char **tmp, *param, *val, **params, **vals;
817 while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
818 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
825 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
832 params[params_count] = param;
833 vals[params_count] = val;
837 if (params_count > 0) {
838 *params_ptr = params;
841 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
846 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
848 struct rt_cfg_entry_args *args;
849 struct ast_variable *var;
854 for (i = 0; i < argc; i++) {
858 if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
867 args->last->next = var;
875 static struct ast_variable *
876 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,
917 sqlite_freemem(query);
920 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
933 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
934 sqlite_freemem(query);
937 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
942 ast_debug(1, "SQL query: %s\n", query);
946 ast_mutex_lock(&mutex);
949 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
950 RES_SQLITE_END(error)
952 ast_mutex_unlock(&mutex);
954 sqlite_freemem(query);
957 ast_log(LOG_WARNING, "%s\n", errormsg);
959 ast_variables_destroy(args.var);
966 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
968 struct rt_multi_cfg_entry_args *args;
969 struct ast_category *cat;
970 struct ast_variable *var;
974 args = (struct rt_multi_cfg_entry_args *)arg;
978 * cat_name should always be set here, since initfield is forged from
979 * params[0] in realtime_multi_handler(), which is a search parameter
982 for (i = 0; i < argc; i++) {
983 if (!strcmp(args->initfield, columnNames[i]))
988 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
992 if (!(cat = ast_category_new(cat_name, "", 99999))) {
993 ast_log(LOG_WARNING, "Unable to allocate category\n");
997 ast_category_append(args->cfg, cat);
999 for (i = 0; i < argc; i++) {
1000 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
1003 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
1004 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1008 ast_variable_append(cat, var);
1014 static struct ast_config *realtime_multi_handler(const char *database,
1015 const char *table, va_list ap)
1017 char *query, *errormsg, *op, *tmp_str, *initfield;
1018 struct rt_multi_cfg_entry_args args;
1019 const char **params, **vals;
1020 struct ast_config *cfg;
1021 size_t params_count;
1025 ast_log(LOG_WARNING, "Table name unspecified\n");
1029 if (!(cfg = ast_config_new())) {
1030 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1034 if (!(params_count = get_params(ap, ¶ms, &vals))) {
1035 ast_config_destroy(cfg);
1039 if (!(initfield = ast_strdup(params[0]))) {
1040 ast_config_destroy(cfg);
1046 tmp_str = strchr(initfield, ' ');
1051 op = (!strchr(params[0], ' ')) ? " =" : "";
1054 * Asterisk sends us an already escaped string when searching for
1055 * "exten LIKE" (uh!). Handle it separately.
1057 tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1059 /* \cond DOXYGEN_CAN_PARSE_THIS */
1061 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1064 if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1065 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1066 ast_config_destroy(cfg);
1069 ast_free(initfield);
1073 if (params_count > 1) {
1076 for (i = 1; i < params_count; i++) {
1077 op = (!strchr(params[i], ' ')) ? " =" : "";
1078 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op,
1080 sqlite_freemem(query);
1083 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1084 ast_config_destroy(cfg);
1087 ast_free(initfield);
1098 if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1099 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1100 ast_config_destroy(cfg);
1101 ast_free(initfield);
1105 sqlite_freemem(query);
1107 ast_debug(1, "SQL query: %s\n", query);
1109 args.initfield = initfield;
1111 ast_mutex_lock(&mutex);
1114 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1115 RES_SQLITE_END(error)
1117 ast_mutex_unlock(&mutex);
1119 sqlite_freemem(query);
1120 ast_free(initfield);
1123 ast_log(LOG_WARNING, "%s\n", errormsg);
1125 ast_config_destroy(cfg);
1132 static int realtime_update_handler(const char *database, const char *table,
1133 const char *keyfield, const char *entity,
1136 char *query, *errormsg, *tmp_str;
1137 const char **params, **vals;
1138 size_t params_count;
1139 int error, rows_num;
1142 ast_log(LOG_WARNING, "Table name unspecified\n");
1146 if (!(params_count = get_params(ap, ¶ms, &vals)))
1149 /* \cond DOXYGEN_CAN_PARSE_THIS */
1151 #define QUERY "UPDATE '%q' SET %q = '%q'"
1154 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1155 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1161 if (params_count > 1) {
1164 for (i = 1; i < params_count; i++) {
1165 tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i],
1167 sqlite_freemem(query);
1170 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1183 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1184 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1188 sqlite_freemem(query);
1190 ast_debug(1, "SQL query: %s\n", query);
1192 ast_mutex_lock(&mutex);
1195 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1196 RES_SQLITE_END(error)
1199 rows_num = sqlite_changes(db);
1203 ast_mutex_unlock(&mutex);
1205 sqlite_freemem(query);
1208 ast_log(LOG_WARNING, "%s\n", errormsg);
1215 static int realtime_store_handler(const char *database, const char *table, va_list ap) {
1216 char *errormsg, *tmp_str, *tmp_keys, *tmp_keys2, *tmp_vals, *tmp_vals2;
1217 const char **params, **vals;
1218 size_t params_count;
1223 ast_log(LOG_WARNING, "Table name unspecified\n");
1227 if (!(params_count = get_params(ap, ¶ms, &vals)))
1230 /* \cond DOXYGEN_CAN_PARSE_THIS */
1232 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1237 for (i = 0; i < params_count; i++) {
1239 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1240 sqlite_freemem(tmp_keys2);
1242 tmp_keys = sqlite_mprintf("%q", params[i]);
1245 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1252 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1253 sqlite_freemem(tmp_vals2);
1255 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1258 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1265 tmp_keys2 = tmp_keys;
1266 tmp_vals2 = tmp_vals;
1272 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1273 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1277 sqlite_freemem(tmp_keys);
1278 sqlite_freemem(tmp_vals);
1280 ast_debug(1, "SQL query: %s\n", tmp_str);
1282 ast_mutex_lock(&mutex);
1285 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1286 RES_SQLITE_END(error)
1289 rows_id = sqlite_last_insert_rowid(db);
1294 ast_mutex_unlock(&mutex);
1296 sqlite_freemem(tmp_str);
1299 ast_log(LOG_WARNING, "%s\n", errormsg);
1306 static int realtime_destroy_handler(const char *database, const char *table,
1307 const char *keyfield, const char *entity,
1310 char *query, *errormsg, *tmp_str;
1311 const char **params, **vals;
1312 size_t params_count;
1313 int error, rows_num;
1317 ast_log(LOG_WARNING, "Table name unspecified\n");
1321 if (!(params_count = get_params(ap, ¶ms, &vals)))
1324 /* \cond DOXYGEN_CAN_PARSE_THIS */
1326 #define QUERY "DELETE FROM '%q' WHERE"
1329 if (!(query = sqlite_mprintf(QUERY, table))) {
1330 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1336 for (i = 0; i < params_count; i++) {
1337 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1338 sqlite_freemem(query);
1341 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1352 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1353 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1356 sqlite_freemem(query);
1359 ast_debug(1, "SQL query: %s\n", query);
1361 ast_mutex_lock(&mutex);
1364 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1365 RES_SQLITE_END(error)
1368 rows_num = sqlite_changes(db);
1372 ast_mutex_unlock(&mutex);
1374 sqlite_freemem(query);
1377 ast_log(LOG_WARNING, "%s\n", errormsg);
1385 static int cli_status(int fd, int argc, char *argv[])
1387 ast_cli(fd, "SQLite database path: %s\n", dbfile);
1388 ast_cli(fd, "config_table: ");
1391 ast_cli(fd, "unspecified, must be present in extconfig.conf\n");
1393 ast_cli(fd, "%s\n", config_table);
1395 ast_cli(fd, "cdr_table: ");
1398 ast_cli(fd, "unspecified, CDR support disabled\n");
1400 ast_cli(fd, "%s\n", cdr_table);
1402 return RESULT_SUCCESS;
1405 static int unload_module(void)
1407 if (cli_status_registered)
1408 ast_cli_unregister(&cli_status_cmd);
1411 ast_cdr_unregister(RES_SQLITE_NAME);
1413 ast_config_engine_deregister(&sqlite_engine);
1423 static int load_module(void)
1430 cli_status_registered = 0;
1432 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);
1447 ast_config_engine_register(&sqlite_engine);
1451 error = sqlite_exec_printf(db, "SELECT COUNT(id) FROM %Q;", NULL, NULL,
1452 &errormsg, cdr_table);
1453 RES_SQLITE_END(error)
1459 if (error != SQLITE_ERROR) {
1460 ast_log(LOG_ERROR, "%s\n", errormsg);
1467 error = sqlite_exec_printf(db, sql_create_cdr_table, NULL, NULL,
1468 &errormsg, cdr_table);
1469 RES_SQLITE_END(error)
1472 ast_log(LOG_ERROR, "%s\n", errormsg);
1479 error = ast_cdr_register(RES_SQLITE_NAME, RES_SQLITE_DESCRIPTION,
1490 error = ast_cli_register(&cli_status_cmd);
1497 cli_status_registered = 1;
1502 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1503 .load = load_module,
1504 .unload = unload_module,