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"
111 RES_CONFIG_SQLITE_CONFIG_ID,
112 RES_CONFIG_SQLITE_CONFIG_CAT_METRIC,
113 RES_CONFIG_SQLITE_CONFIG_VAR_METRIC,
114 RES_CONFIG_SQLITE_CONFIG_COMMENTED,
115 RES_CONFIG_SQLITE_CONFIG_FILENAME,
116 RES_CONFIG_SQLITE_CONFIG_CATEGORY,
117 RES_CONFIG_SQLITE_CONFIG_VAR_NAME,
118 RES_CONFIG_SQLITE_CONFIG_VAR_VAL,
119 RES_CONFIG_SQLITE_CONFIG_COLUMNS,
122 #define SET_VAR(config, to, from) \
126 __error = set_var(&to, #to, from->value); \
129 ast_config_destroy(config); \
136 * Maximum number of loops before giving up executing a query. Calls to
137 * sqlite_xxx() functions which can return SQLITE_BUSY or SQLITE_LOCKED
138 * are enclosed by RES_CONFIG_SQLITE_BEGIN and RES_CONFIG_SQLITE_END, e.g.
143 * RES_CONFIG_SQLITE_BEGIN
144 * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
145 * RES_CONFIG_SQLITE_END(error)
151 #define RES_CONFIG_SQLITE_MAX_LOOPS 10
154 * Macro used before executing a query.
156 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
158 #define RES_CONFIG_SQLITE_BEGIN \
162 for (__i = 0; __i < RES_CONFIG_SQLITE_MAX_LOOPS; __i++) {
165 * Macro used after executing a query.
167 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
169 #define RES_CONFIG_SQLITE_END(error) \
170 if (error != SQLITE_BUSY && error != SQLITE_LOCKED) \
177 * Structure sent to the SQLite callback function for static configuration.
179 * \see add_cfg_entry()
181 struct cfg_entry_args {
182 struct ast_config *cfg;
183 struct ast_category *cat;
185 struct ast_flags flags;
189 * Structure sent to the SQLite callback function for RealTime configuration.
191 * \see add_rt_cfg_entry()
193 struct rt_cfg_entry_args {
194 struct ast_variable *var;
195 struct ast_variable *last;
199 * Structure sent to the SQLite callback function for RealTime configuration
200 * (realtime_multi_handler()).
202 * \see add_rt_multi_cfg_entry()
204 struct rt_multi_cfg_entry_args {
205 struct ast_config *cfg;
210 * \brief Allocate a variable.
211 * \param var the address of the variable to set (it will be allocated)
212 * \param name the name of the variable (for error handling)
213 * \param value the value to store in var
214 * \retval 0 on success
215 * \retval 1 if an allocation error occurred
217 static int set_var(char **var, char *name, char *value);
220 * \brief Load the configuration file.
221 * \see unload_config()
223 * This function sets dbfile, config_table, and cdr_table. It calls
224 * check_vars() before returning, and unload_config() if an error occurred.
226 * \retval 0 on success
227 * \retval 1 if an error occurred
229 static int load_config(void);
232 * \brief Free resources related to configuration.
235 static void unload_config(void);
238 * \brief Asterisk callback function for CDR support.
239 * \param cdr the CDR entry Asterisk sends us.
241 * Asterisk will call this function each time a CDR entry must be logged if
242 * CDR support is enabled.
244 * \retval 0 on success
245 * \retval 1 if an error occurred
247 static int cdr_handler(struct ast_cdr *cdr);
250 * \brief SQLite callback function for static configuration.
252 * This function is passed to the SQLite engine as a callback function to
253 * parse a row and store it in a struct ast_config object. It relies on
254 * resulting rows being sorted by category.
256 * \param arg a pointer to a struct cfg_entry_args object
257 * \param argc number of columns
258 * \param argv values in the row
259 * \param columnNames names and types of the columns
260 * \retval 0 on success
261 * \retval 1 if an error occurred
262 * \see cfg_entry_args
263 * \see sql_get_config_table
264 * \see config_handler()
266 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
269 * \brief Asterisk callback function for static configuration.
271 * Asterisk will call this function when it loads its static configuration,
272 * which usually happens at startup and reload.
274 * \param database the database to use (ignored)
275 * \param table the table to use
276 * \param file the file to load from the database
277 * \param cfg the struct ast_config object to use when storing variables
278 * \param flags Optional flags. Not used.
279 * \param suggested_incl suggest include.
281 * \retval NULL if an error occurred
282 * \see add_cfg_entry()
284 static struct ast_config * config_handler(const char *database, const char *table, const char *file,
285 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl);
288 * \brief Helper function to parse a va_list object into 2 dynamic arrays of
289 * strings, parameters and values.
291 * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
292 * arguments will be extracted to create 2 arrays:
295 * <li>params : param1 param2 param3 ...</li>
296 * <li>vals : val1 val2 val3 ...</li>
299 * The address of these arrays are stored in params_ptr and vals_ptr. It
300 * is the responsibility of the caller to release the memory of these arrays.
301 * It is considered an error that va_list has a null or odd number of strings.
303 * \param ap the va_list object to parse
304 * \param params_ptr where the address of the params array is stored
305 * \param vals_ptr where the address of the vals array is stored
306 * \retval the number of elements in the arrays (which have the same size).
307 * \retval 0 if an error occurred.
309 static size_t get_params(va_list ap, const char ***params_ptr,
310 const char ***vals_ptr);
313 * \brief SQLite callback function for RealTime configuration.
315 * This function is passed to the SQLite engine as a callback function to
316 * parse a row and store it in a linked list of struct ast_variable objects.
318 * \param arg a pointer to a struct rt_cfg_entry_args object
319 * \param argc number of columns
320 * \param argv values in the row
321 * \param columnNames names and types of the columns
322 * \retval 0 on success.
323 * \retval 1 if an error occurred.
324 * \see rt_cfg_entry_args
325 * \see realtime_handler()
327 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
331 * Asterisk callback function for RealTime configuration.
333 * Asterisk will call this function each time it requires a variable
334 * through the RealTime architecture. ap is a list of parameters and
335 * values used to find a specific row, e.g one parameter "name" and
336 * one value "123" so that the SQL query becomes <code>SELECT * FROM
337 * table WHERE name = '123';</code>.
339 * \param database the database to use (ignored)
340 * \param table the table to use
341 * \param ap list of parameters and values to match
343 * \retval a linked list of struct ast_variable objects
344 * \retval NULL if an error occurred
345 * \see add_rt_cfg_entry()
347 static struct ast_variable * realtime_handler(const char *database,
348 const char *table, va_list ap);
351 * \brief SQLite callback function for RealTime configuration.
353 * This function performs the same actions as add_rt_cfg_entry() except
354 * that the rt_multi_cfg_entry_args structure is designed to store
355 * categories in addition to variables.
357 * \param arg a pointer to a struct rt_multi_cfg_entry_args object
358 * \param argc number of columns
359 * \param argv values in the row
360 * \param columnNames names and types of the columns
361 * \retval 0 on success.
362 * \retval 1 if an error occurred.
363 * \see rt_multi_cfg_entry_args
364 * \see realtime_multi_handler()
366 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
370 * \brief Asterisk callback function for RealTime configuration.
372 * This function performs the same actions as realtime_handler() except
373 * that it can store variables per category, and can return several
376 * \param database the database to use (ignored)
377 * \param table the table to use
378 * \param ap list of parameters and values to match
379 * \retval a struct ast_config object storing categories and variables.
380 * \retval NULL if an error occurred.
382 * \see add_rt_multi_cfg_entry()
384 static struct ast_config * realtime_multi_handler(const char *database,
385 const char *table, va_list ap);
388 * \brief Asterisk callback function for RealTime configuration (variable
391 * Asterisk will call this function each time a variable has been modified
392 * internally and must be updated in the backend engine. keyfield and entity
393 * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
394 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
395 * same format as the other realtime functions.
397 * \param database the database to use (ignored)
398 * \param table the table to use
399 * \param keyfield the column of the matching cell
400 * \param entity the value of the matching cell
401 * \param ap list of parameters and new values to update in the database
402 * \retval the number of affected rows.
403 * \retval -1 if an error occurred.
405 static int realtime_update_handler(const char *database, const char *table,
406 const char *keyfield, const char *entity, va_list ap);
409 * \brief Asterisk callback function for RealTime configuration (variable
412 * Asterisk will call this function each time a variable has been created
413 * internally and must be stored in the backend engine.
414 * are used to find the row to update, e.g. ap is a list of parameters and
415 * values with the same format as the other realtime functions.
417 * \param database the database to use (ignored)
418 * \param table the table to use
419 * \param ap list of parameters and new values to insert into the database
420 * \retval the rowid of inserted row.
421 * \retval -1 if an error occurred.
423 static int realtime_store_handler(const char *database, const char *table,
427 * \brief Asterisk callback function for RealTime configuration (destroys
430 * Asterisk will call this function each time a variable has been destroyed
431 * internally and must be removed from the backend engine. keyfield and entity
432 * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
433 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
434 * same format as the other realtime functions.
436 * \param database the database to use (ignored)
437 * \param table the table to use
438 * \param keyfield the column of the matching cell
439 * \param entity the value of the matching cell
440 * \param ap list of additional parameters for cell matching
441 * \retval the number of affected rows.
442 * \retval -1 if an error occurred.
444 static int realtime_destroy_handler(const char *database, const char *table,
445 const char *keyfield, const char *entity, va_list ap);
448 * \brief Asterisk callback function for the CLI status command.
450 * \param fd file descriptor provided by Asterisk to use with ast_cli()
451 * \param argc number of arguments
452 * \param argv arguments list
453 * \return RESULT_SUCCESS
455 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
457 /*! The SQLite database object. */
460 /*! Set to 1 if CDR support is enabled. */
463 /*! Set to 1 if the CDR callback function was registered. */
464 static int cdr_registered;
466 /*! Set to 1 if the CLI status command callback function was registered. */
467 static int cli_status_registered;
469 /*! The path of the database file. */
472 /*! The name of the static configuration table. */
473 static char *config_table;
475 /*! The name of the table used to store CDR entries. */
476 static char *cdr_table;
479 * The structure specifying all callback functions used by Asterisk for static
480 * and RealTime configuration.
482 static struct ast_config_engine sqlite_engine =
484 .name = RES_CONFIG_SQLITE_DRIVER,
485 .load_func = config_handler,
486 .realtime_func = realtime_handler,
487 .realtime_multi_func = realtime_multi_handler,
488 .store_func = realtime_store_handler,
489 .destroy_func = realtime_destroy_handler,
490 .update_func = realtime_update_handler
494 * The mutex used to prevent simultaneous access to the SQLite database.
496 AST_MUTEX_DEFINE_STATIC(mutex);
499 * Structure containing details and callback functions for the CLI status
502 static struct ast_cli_entry cli_status[] = {
503 AST_CLI_DEFINE(handle_cli_show_sqlite_status, "Show status information about the SQLite 2 driver"),
507 * Taken from Asterisk 1.2 cdr_sqlite.so.
510 /*! SQL query format to create the CDR table if non existent. */
511 static char *sql_create_cdr_table =
512 "CREATE TABLE '%q' (\n"
514 " clid VARCHAR(80) NOT NULL DEFAULT '',\n"
515 " src VARCHAR(80) NOT NULL DEFAULT '',\n"
516 " dst VARCHAR(80) NOT NULL DEFAULT '',\n"
517 " dcontext VARCHAR(80) NOT NULL DEFAULT '',\n"
518 " channel VARCHAR(80) NOT NULL DEFAULT '',\n"
519 " dstchannel VARCHAR(80) NOT NULL DEFAULT '',\n"
520 " lastapp VARCHAR(80) NOT NULL DEFAULT '',\n"
521 " lastdata VARCHAR(80) NOT NULL DEFAULT '',\n"
522 " start DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
523 " answer DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
524 " end DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
525 " duration INT(11) NOT NULL DEFAULT 0,\n"
526 " billsec INT(11) NOT NULL DEFAULT 0,\n"
527 " disposition VARCHAR(45) NOT NULL DEFAULT '',\n"
528 " amaflags INT(11) NOT NULL DEFAULT 0,\n"
529 " accountcode VARCHAR(20) NOT NULL DEFAULT '',\n"
530 " uniqueid VARCHAR(32) NOT NULL DEFAULT '',\n"
531 " userfield VARCHAR(255) NOT NULL DEFAULT '',\n"
532 " PRIMARY KEY (id)\n"
535 /*! SQL query format to insert a CDR entry. */
536 static char *sql_add_cdr_entry =
565 " datetime(%d,'unixepoch'),"
566 " datetime(%d,'unixepoch'),"
567 " datetime(%d,'unixepoch'),"
578 * SQL query format to fetch the static configuration of a file.
579 * Rows must be sorted by category.
581 * \see add_cfg_entry()
583 static char *sql_get_config_table =
586 " WHERE filename = '%q' AND commented = 0"
587 " ORDER BY cat_metric ASC, var_metric ASC;";
589 static int set_var(char **var, char *name, char *value)
594 *var = ast_strdup(value);
597 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
604 static int check_vars(void)
607 ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
611 use_cdr = (cdr_table != NULL);
616 static int load_config(void)
618 struct ast_config *config;
619 struct ast_variable *var;
621 struct ast_flags config_flags = { 0 };
623 config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
626 ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
630 for (var = ast_variable_browse(config, "general"); var; var = var->next) {
631 if (!strcasecmp(var->name, "dbfile"))
632 SET_VAR(config, dbfile, var);
633 else if (!strcasecmp(var->name, "config_table"))
634 SET_VAR(config, config_table, var);
635 else if (!strcasecmp(var->name, "cdr_table"))
636 SET_VAR(config, cdr_table, var);
638 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
641 ast_config_destroy(config);
642 error = check_vars();
652 static void unload_config(void)
656 ast_free(config_table);
662 static int cdr_handler(struct ast_cdr *cdr)
664 char *query, *errormsg;
667 query = sqlite_mprintf(sql_add_cdr_entry, cdr_table, cdr->clid,
668 cdr->src, cdr->dst, cdr->dcontext, cdr->channel,
669 cdr->dstchannel, cdr->lastapp, cdr->lastdata,
670 cdr->start.tv_sec, cdr->answer.tv_sec,
671 cdr->end.tv_sec, cdr->duration, cdr->billsec,
672 cdr->disposition, cdr->amaflags, cdr->accountcode,
673 cdr->uniqueid, cdr->userfield);
676 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
680 ast_debug(1, "SQL query: %s\n", query);
682 ast_mutex_lock(&mutex);
684 RES_CONFIG_SQLITE_BEGIN
685 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
686 RES_CONFIG_SQLITE_END(error)
688 ast_mutex_unlock(&mutex);
690 sqlite_freemem(query);
693 ast_log(LOG_ERROR, "%s\n", errormsg);
694 sqlite_freemem(errormsg);
701 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
703 struct cfg_entry_args *args;
704 struct ast_variable *var;
706 if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
707 ast_log(LOG_WARNING, "Corrupt table\n");
713 if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
714 struct ast_config *cfg;
717 val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
718 cfg = ast_config_internal_load(val, args->cfg, args->flags, "");
721 ast_log(LOG_WARNING, "Unable to include %s\n", val);
729 if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
730 args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
733 ast_log(LOG_WARNING, "Unable to allocate category\n");
737 ast_free(args->cat_name);
738 args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
740 if (!args->cat_name) {
741 ast_category_destroy(args->cat);
745 ast_category_append(args->cfg, args->cat);
748 var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
751 ast_log(LOG_WARNING, "Unable to allocate variable");
755 ast_variable_append(args->cat, var);
760 static struct ast_config *config_handler(const char *database, const char *table, const char *file,
761 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl)
763 struct cfg_entry_args args;
764 char *query, *errormsg;
769 ast_log(LOG_ERROR, "Table name unspecified\n");
773 table = config_table;
775 query = sqlite_mprintf(sql_get_config_table, table, file);
778 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
782 ast_debug(1, "SQL query: %s\n", query);
785 args.cat_name = NULL;
788 ast_mutex_lock(&mutex);
790 RES_CONFIG_SQLITE_BEGIN
791 error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
792 RES_CONFIG_SQLITE_END(error)
794 ast_mutex_unlock(&mutex);
796 ast_free(args.cat_name);
797 sqlite_freemem(query);
800 ast_log(LOG_ERROR, "%s\n", errormsg);
801 sqlite_freemem(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 * realtime_handler(const char *database, const char *table, va_list ap)
877 char *query, *errormsg, *op, *tmp_str;
878 struct rt_cfg_entry_args args;
879 const char **params, **vals;
884 ast_log(LOG_WARNING, "Table name unspecified\n");
888 params_count = get_params(ap, ¶ms, &vals);
890 if (params_count == 0)
893 op = (strchr(params[0], ' ') == NULL) ? " =" : "";
895 /* \cond DOXYGEN_CAN_PARSE_THIS */
897 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
900 query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
903 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
909 if (params_count > 1) {
912 for (i = 1; i < params_count; i++) {
913 op = (strchr(params[i], ' ') == NULL) ? " =" : "";
914 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
915 sqlite_freemem(query);
918 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
931 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
932 sqlite_freemem(query);
935 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
940 ast_debug(1, "SQL query: %s\n", query);
944 ast_mutex_lock(&mutex);
946 RES_CONFIG_SQLITE_BEGIN
947 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
948 RES_CONFIG_SQLITE_END(error)
950 ast_mutex_unlock(&mutex);
952 sqlite_freemem(query);
955 ast_log(LOG_WARNING, "%s\n", errormsg);
956 sqlite_freemem(errormsg);
957 ast_variables_destroy(args.var);
964 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
966 struct rt_multi_cfg_entry_args *args;
967 struct ast_category *cat;
968 struct ast_variable *var;
976 * cat_name should always be set here, since initfield is forged from
977 * params[0] in realtime_multi_handler(), which is a search parameter
980 for (i = 0; i < argc; i++) {
981 if (!strcmp(args->initfield, columnNames[i]))
986 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
990 if (!(cat = ast_category_new(cat_name, "", 99999))) {
991 ast_log(LOG_WARNING, "Unable to allocate category\n");
995 ast_category_append(args->cfg, cat);
997 for (i = 0; i < argc; i++) {
998 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
1001 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
1002 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1006 ast_variable_append(cat, var);
1012 static struct ast_config *realtime_multi_handler(const char *database,
1013 const char *table, va_list ap)
1015 char *query, *errormsg, *op, *tmp_str, *initfield;
1016 struct rt_multi_cfg_entry_args args;
1017 const char **params, **vals;
1018 struct ast_config *cfg;
1019 size_t params_count;
1023 ast_log(LOG_WARNING, "Table name unspecified\n");
1027 if (!(cfg = ast_config_new())) {
1028 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1032 if (!(params_count = get_params(ap, ¶ms, &vals))) {
1033 ast_config_destroy(cfg);
1037 if (!(initfield = ast_strdup(params[0]))) {
1038 ast_config_destroy(cfg);
1044 tmp_str = strchr(initfield, ' ');
1049 op = (!strchr(params[0], ' ')) ? " =" : "";
1052 * Asterisk sends us an already escaped string when searching for
1053 * "exten LIKE" (uh!). Handle it separately.
1055 tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1057 /* \cond DOXYGEN_CAN_PARSE_THIS */
1059 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1062 if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1063 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1064 ast_config_destroy(cfg);
1067 ast_free(initfield);
1071 if (params_count > 1) {
1074 for (i = 1; i < params_count; i++) {
1075 op = (!strchr(params[i], ' ')) ? " =" : "";
1076 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1077 sqlite_freemem(query);
1080 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1081 ast_config_destroy(cfg);
1084 ast_free(initfield);
1095 if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1096 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1097 ast_config_destroy(cfg);
1098 ast_free(initfield);
1102 sqlite_freemem(query);
1104 ast_debug(1, "SQL query: %s\n", query);
1106 args.initfield = initfield;
1108 ast_mutex_lock(&mutex);
1110 RES_CONFIG_SQLITE_BEGIN
1111 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1112 RES_CONFIG_SQLITE_END(error)
1114 ast_mutex_unlock(&mutex);
1116 sqlite_freemem(query);
1117 ast_free(initfield);
1120 ast_log(LOG_WARNING, "%s\n", errormsg);
1121 sqlite_freemem(errormsg);
1122 ast_config_destroy(cfg);
1129 static int realtime_update_handler(const char *database, const char *table,
1130 const char *keyfield, const char *entity, va_list ap)
1132 char *query, *errormsg, *tmp_str;
1133 const char **params, **vals;
1134 size_t params_count;
1135 int error, rows_num;
1138 ast_log(LOG_WARNING, "Table name unspecified\n");
1142 if (!(params_count = get_params(ap, ¶ms, &vals)))
1145 /* \cond DOXYGEN_CAN_PARSE_THIS */
1147 #define QUERY "UPDATE '%q' SET %q = '%q'"
1150 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1151 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1157 if (params_count > 1) {
1160 for (i = 1; i < params_count; i++) {
1161 tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
1162 sqlite_freemem(query);
1165 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1178 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1179 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1183 sqlite_freemem(query);
1185 ast_debug(1, "SQL query: %s\n", query);
1187 ast_mutex_lock(&mutex);
1189 RES_CONFIG_SQLITE_BEGIN
1190 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1191 RES_CONFIG_SQLITE_END(error)
1194 rows_num = sqlite_changes(db);
1198 ast_mutex_unlock(&mutex);
1200 sqlite_freemem(query);
1203 ast_log(LOG_WARNING, "%s\n", errormsg);
1204 sqlite_freemem(errormsg);
1210 static int realtime_store_handler(const char *database, const char *table, va_list ap) {
1211 char *errormsg, *tmp_str, *tmp_keys, *tmp_keys2, *tmp_vals, *tmp_vals2;
1212 const char **params, **vals;
1213 size_t params_count;
1218 ast_log(LOG_WARNING, "Table name unspecified\n");
1222 if (!(params_count = get_params(ap, ¶ms, &vals)))
1225 /* \cond DOXYGEN_CAN_PARSE_THIS */
1227 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1232 for (i = 0; i < params_count; i++) {
1234 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1235 sqlite_freemem(tmp_keys2);
1237 tmp_keys = sqlite_mprintf("%q", params[i]);
1240 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1247 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1248 sqlite_freemem(tmp_vals2);
1250 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1253 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1260 tmp_keys2 = tmp_keys;
1261 tmp_vals2 = tmp_vals;
1267 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1268 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1272 sqlite_freemem(tmp_keys);
1273 sqlite_freemem(tmp_vals);
1275 ast_debug(1, "SQL query: %s\n", tmp_str);
1277 ast_mutex_lock(&mutex);
1279 RES_CONFIG_SQLITE_BEGIN
1280 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1281 RES_CONFIG_SQLITE_END(error)
1284 rows_id = sqlite_last_insert_rowid(db);
1289 ast_mutex_unlock(&mutex);
1291 sqlite_freemem(tmp_str);
1294 ast_log(LOG_WARNING, "%s\n", errormsg);
1295 sqlite_freemem(errormsg);
1301 static int realtime_destroy_handler(const char *database, const char *table,
1302 const char *keyfield, const char *entity, va_list ap)
1304 char *query, *errormsg, *tmp_str;
1305 const char **params, **vals;
1306 size_t params_count;
1307 int error, rows_num;
1311 ast_log(LOG_WARNING, "Table name unspecified\n");
1315 if (!(params_count = get_params(ap, ¶ms, &vals)))
1318 /* \cond DOXYGEN_CAN_PARSE_THIS */
1320 #define QUERY "DELETE FROM '%q' WHERE"
1323 if (!(query = sqlite_mprintf(QUERY, table))) {
1324 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1330 for (i = 0; i < params_count; i++) {
1331 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1332 sqlite_freemem(query);
1335 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1346 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1347 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1350 sqlite_freemem(query);
1352 ast_debug(1, "SQL query: %s\n", query);
1354 ast_mutex_lock(&mutex);
1356 RES_CONFIG_SQLITE_BEGIN
1357 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1358 RES_CONFIG_SQLITE_END(error)
1361 rows_num = sqlite_changes(db);
1365 ast_mutex_unlock(&mutex);
1367 sqlite_freemem(query);
1370 ast_log(LOG_WARNING, "%s\n", errormsg);
1371 sqlite_freemem(errormsg);
1377 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1381 e->command = "show sqlite status";
1383 "Usage: show sqlite status\n"
1384 " Show status information about the SQLite 2 driver\n";
1391 return CLI_SHOWUSAGE;
1393 ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
1394 ast_cli(a->fd, "config_table: ");
1397 ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
1399 ast_cli(a->fd, "%s\n", config_table);
1401 ast_cli(a->fd, "cdr_table: ");
1404 ast_cli(a->fd, "unspecified, CDR support disabled\n");
1406 ast_cli(a->fd, "%s\n", cdr_table);
1411 static int unload_module(void)
1413 if (cli_status_registered)
1414 ast_cli_unregister_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1417 ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
1419 ast_config_engine_deregister(&sqlite_engine);
1429 static int load_module(void)
1436 cli_status_registered = 0;
1438 config_table = NULL;
1440 error = load_config();
1443 return AST_MODULE_LOAD_DECLINE;
1445 if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1446 ast_log(LOG_ERROR, "%s\n", errormsg);
1447 sqlite_freemem(errormsg);
1452 ast_config_engine_register(&sqlite_engine);
1457 /* \cond DOXYGEN_CAN_PARSE_THIS */
1459 #define QUERY "SELECT COUNT(id) FROM %Q;"
1462 query = sqlite_mprintf(QUERY, cdr_table);
1465 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1470 ast_debug(1, "SQL query: %s\n", query);
1472 RES_CONFIG_SQLITE_BEGIN
1473 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1474 RES_CONFIG_SQLITE_END(error)
1476 sqlite_freemem(query);
1482 if (error != SQLITE_ERROR) {
1483 ast_log(LOG_ERROR, "%s\n", errormsg);
1484 sqlite_freemem(errormsg);
1489 sqlite_freemem(errormsg);
1490 query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
1493 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1498 ast_debug(1, "SQL query: %s\n", query);
1500 RES_CONFIG_SQLITE_BEGIN
1501 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1502 RES_CONFIG_SQLITE_END(error)
1504 sqlite_freemem(query);
1507 ast_log(LOG_ERROR, "%s\n", errormsg);
1508 sqlite_freemem(errormsg);
1514 error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
1524 error = ast_cli_register_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1531 cli_status_registered = 1;
1536 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1537 .load = load_module,
1538 .unload = unload_module,