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$")
89 #include "asterisk/pbx.h"
90 #include "asterisk/cdr.h"
91 #include "asterisk/cli.h"
92 #include "asterisk/lock.h"
93 #include "asterisk/config.h"
94 #include "asterisk/module.h"
95 #include "asterisk/linkedlists.h"
97 #define MACRO_BEGIN do {
98 #define MACRO_END } while (0)
100 #define RES_CONFIG_SQLITE_NAME "res_config_sqlite"
101 #define RES_CONFIG_SQLITE_DRIVER "sqlite"
102 #define RES_CONFIG_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
103 #define RES_CONFIG_SQLITE_CONF_FILE "res_config_sqlite.conf"
106 RES_CONFIG_SQLITE_CONFIG_ID,
107 RES_CONFIG_SQLITE_CONFIG_CAT_METRIC,
108 RES_CONFIG_SQLITE_CONFIG_VAR_METRIC,
109 RES_CONFIG_SQLITE_CONFIG_COMMENTED,
110 RES_CONFIG_SQLITE_CONFIG_FILENAME,
111 RES_CONFIG_SQLITE_CONFIG_CATEGORY,
112 RES_CONFIG_SQLITE_CONFIG_VAR_NAME,
113 RES_CONFIG_SQLITE_CONFIG_VAR_VAL,
114 RES_CONFIG_SQLITE_CONFIG_COLUMNS,
117 #define SET_VAR(config, to, from) \
121 __error = set_var(&to, #to, from->value); \
124 ast_config_destroy(config); \
131 * Maximum number of loops before giving up executing a query. Calls to
132 * sqlite_xxx() functions which can return SQLITE_BUSY or SQLITE_LOCKED
133 * are enclosed by RES_CONFIG_SQLITE_BEGIN and RES_CONFIG_SQLITE_END, e.g.
138 * RES_CONFIG_SQLITE_BEGIN
139 * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
140 * RES_CONFIG_SQLITE_END(error)
146 #define RES_CONFIG_SQLITE_MAX_LOOPS 10
149 * Macro used before executing a query.
151 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
153 #define RES_CONFIG_SQLITE_BEGIN \
157 for (__i = 0; __i < RES_CONFIG_SQLITE_MAX_LOOPS; __i++) {
160 * Macro used after executing a query.
162 * \see RES_CONFIG_SQLITE_MAX_LOOPS.
164 #define RES_CONFIG_SQLITE_END(error) \
165 if (error != SQLITE_BUSY && error != SQLITE_LOCKED) \
172 * Structure sent to the SQLite callback function for static configuration.
174 * \see add_cfg_entry()
176 struct cfg_entry_args {
177 struct ast_config *cfg;
178 struct ast_category *cat;
180 struct ast_flags flags;
184 * Structure sent to the SQLite callback function for RealTime configuration.
186 * \see add_rt_cfg_entry()
188 struct rt_cfg_entry_args {
189 struct ast_variable *var;
190 struct ast_variable *last;
194 * Structure sent to the SQLite callback function for RealTime configuration
195 * (realtime_multi_handler()).
197 * \see add_rt_multi_cfg_entry()
199 struct rt_multi_cfg_entry_args {
200 struct ast_config *cfg;
205 * \brief Allocate a variable.
206 * \param var the address of the variable to set (it will be allocated)
207 * \param name the name of the variable (for error handling)
208 * \param value the value to store in var
209 * \retval 0 on success
210 * \retval 1 if an allocation error occurred
212 static int set_var(char **var, const char *name, const char *value);
215 * \brief Load the configuration file.
216 * \see unload_config()
218 * This function sets dbfile, config_table, and cdr_table. It calls
219 * check_vars() before returning, and unload_config() if an error occurred.
221 * \retval 0 on success
222 * \retval 1 if an error occurred
224 static int load_config(void);
227 * \brief Free resources related to configuration.
230 static void unload_config(void);
233 * \brief Asterisk callback function for CDR support.
234 * \param cdr the CDR entry Asterisk sends us.
236 * Asterisk will call this function each time a CDR entry must be logged if
237 * CDR support is enabled.
239 * \retval 0 on success
240 * \retval 1 if an error occurred
242 static int cdr_handler(struct ast_cdr *cdr);
245 * \brief SQLite callback function for static configuration.
247 * This function is passed to the SQLite engine as a callback function to
248 * parse a row and store it in a struct ast_config object. It relies on
249 * resulting rows being sorted by category.
251 * \param arg a pointer to a struct cfg_entry_args object
252 * \param argc number of columns
253 * \param argv values in the row
254 * \param columnNames names and types of the columns
255 * \retval 0 on success
256 * \retval 1 if an error occurred
257 * \see cfg_entry_args
258 * \see sql_get_config_table
259 * \see config_handler()
261 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
264 * \brief Asterisk callback function for static configuration.
266 * Asterisk will call this function when it loads its static configuration,
267 * which usually happens at startup and reload.
269 * \param database the database to use (ignored)
270 * \param table the table to use
271 * \param file the file to load from the database
272 * \param cfg the struct ast_config object to use when storing variables
273 * \param flags Optional flags. Not used.
274 * \param suggested_incl suggest include.
276 * \retval NULL if an error occurred
277 * \see add_cfg_entry()
279 static struct ast_config * config_handler(const char *database, const char *table, const char *file,
280 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl);
283 * \brief Helper function to parse a va_list object into 2 dynamic arrays of
284 * strings, parameters and values.
286 * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
287 * arguments will be extracted to create 2 arrays:
290 * <li>params : param1 param2 param3 ...</li>
291 * <li>vals : val1 val2 val3 ...</li>
294 * The address of these arrays are stored in params_ptr and vals_ptr. It
295 * is the responsibility of the caller to release the memory of these arrays.
296 * It is considered an error that va_list has a null or odd number of strings.
298 * \param ap the va_list object to parse
299 * \param params_ptr where the address of the params array is stored
300 * \param vals_ptr where the address of the vals array is stored
301 * \retval the number of elements in the arrays (which have the same size).
302 * \retval 0 if an error occurred.
304 static size_t get_params(va_list ap, const char ***params_ptr,
305 const char ***vals_ptr);
308 * \brief SQLite callback function for RealTime configuration.
310 * This function is passed to the SQLite engine as a callback function to
311 * parse a row and store it in a linked list of struct ast_variable objects.
313 * \param arg a pointer to a struct rt_cfg_entry_args object
314 * \param argc number of columns
315 * \param argv values in the row
316 * \param columnNames names and types of the columns
317 * \retval 0 on success.
318 * \retval 1 if an error occurred.
319 * \see rt_cfg_entry_args
320 * \see realtime_handler()
322 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
326 * Asterisk callback function for RealTime configuration.
328 * Asterisk will call this function each time it requires a variable
329 * through the RealTime architecture. ap is a list of parameters and
330 * values used to find a specific row, e.g one parameter "name" and
331 * one value "123" so that the SQL query becomes <code>SELECT * FROM
332 * table WHERE name = '123';</code>.
334 * \param database the database to use (ignored)
335 * \param table the table to use
336 * \param ap list of parameters and values to match
338 * \retval a linked list of struct ast_variable objects
339 * \retval NULL if an error occurred
340 * \see add_rt_cfg_entry()
342 static struct ast_variable * realtime_handler(const char *database,
343 const char *table, va_list ap);
346 * \brief SQLite callback function for RealTime configuration.
348 * This function performs the same actions as add_rt_cfg_entry() except
349 * that the rt_multi_cfg_entry_args structure is designed to store
350 * categories in addition to variables.
352 * \param arg a pointer to a struct rt_multi_cfg_entry_args object
353 * \param argc number of columns
354 * \param argv values in the row
355 * \param columnNames names and types of the columns
356 * \retval 0 on success.
357 * \retval 1 if an error occurred.
358 * \see rt_multi_cfg_entry_args
359 * \see realtime_multi_handler()
361 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
365 * \brief Asterisk callback function for RealTime configuration.
367 * This function performs the same actions as realtime_handler() except
368 * that it can store variables per category, and can return several
371 * \param database the database to use (ignored)
372 * \param table the table to use
373 * \param ap list of parameters and values to match
374 * \retval a struct ast_config object storing categories and variables.
375 * \retval NULL if an error occurred.
377 * \see add_rt_multi_cfg_entry()
379 static struct ast_config * realtime_multi_handler(const char *database,
380 const char *table, va_list ap);
383 * \brief Asterisk callback function for RealTime configuration (variable
386 * Asterisk will call this function each time a variable has been modified
387 * internally and must be updated in the backend engine. keyfield and entity
388 * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
389 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
390 * same format as the other realtime functions.
392 * \param database the database to use (ignored)
393 * \param table the table to use
394 * \param keyfield the column of the matching cell
395 * \param entity the value of the matching cell
396 * \param ap list of parameters and new values to update in the database
397 * \retval the number of affected rows.
398 * \retval -1 if an error occurred.
400 static int realtime_update_handler(const char *database, const char *table,
401 const char *keyfield, const char *entity, va_list ap);
404 * \brief Asterisk callback function for RealTime configuration (variable
407 * Asterisk will call this function each time a variable has been created
408 * internally and must be stored in the backend engine.
409 * are used to find the row to update, e.g. ap is a list of parameters and
410 * values with the same format as the other realtime functions.
412 * \param database the database to use (ignored)
413 * \param table the table to use
414 * \param ap list of parameters and new values to insert into the database
415 * \retval the rowid of inserted row.
416 * \retval -1 if an error occurred.
418 static int realtime_store_handler(const char *database, const char *table,
422 * \brief Asterisk callback function for RealTime configuration (destroys
425 * Asterisk will call this function each time a variable has been destroyed
426 * internally and must be removed from the backend engine. keyfield and entity
427 * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
428 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
429 * same format as the other realtime functions.
431 * \param database the database to use (ignored)
432 * \param table the table to use
433 * \param keyfield the column of the matching cell
434 * \param entity the value of the matching cell
435 * \param ap list of additional parameters for cell matching
436 * \retval the number of affected rows.
437 * \retval -1 if an error occurred.
439 static int realtime_destroy_handler(const char *database, const char *table,
440 const char *keyfield, const char *entity, va_list ap);
443 * \brief Asterisk callback function for the CLI status command.
445 * \param e CLI command
447 * \param a CLI argument list
448 * \return RESULT_SUCCESS
450 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
452 /*! The SQLite database object. */
455 /*! Set to 1 if CDR support is enabled. */
458 /*! Set to 1 if the CDR callback function was registered. */
459 static int cdr_registered;
461 /*! Set to 1 if the CLI status command callback function was registered. */
462 static int cli_status_registered;
464 /*! The path of the database file. */
467 /*! The name of the static configuration table. */
468 static char *config_table;
470 /*! The name of the table used to store CDR entries. */
471 static char *cdr_table;
474 * The structure specifying all callback functions used by Asterisk for static
475 * and RealTime configuration.
477 static struct ast_config_engine sqlite_engine =
479 .name = RES_CONFIG_SQLITE_DRIVER,
480 .load_func = config_handler,
481 .realtime_func = realtime_handler,
482 .realtime_multi_func = realtime_multi_handler,
483 .store_func = realtime_store_handler,
484 .destroy_func = realtime_destroy_handler,
485 .update_func = realtime_update_handler
489 * The mutex used to prevent simultaneous access to the SQLite database.
491 AST_MUTEX_DEFINE_STATIC(mutex);
494 * Structure containing details and callback functions for the CLI status
497 static struct ast_cli_entry cli_status[] = {
498 AST_CLI_DEFINE(handle_cli_show_sqlite_status, "Show status information about the SQLite 2 driver"),
502 * Taken from Asterisk 1.2 cdr_sqlite.so.
505 /*! SQL query format to create the CDR table if non existent. */
506 static char *sql_create_cdr_table =
507 "CREATE TABLE '%q' (\n"
509 " clid VARCHAR(80) NOT NULL DEFAULT '',\n"
510 " src VARCHAR(80) NOT NULL DEFAULT '',\n"
511 " dst VARCHAR(80) NOT NULL DEFAULT '',\n"
512 " dcontext VARCHAR(80) NOT NULL DEFAULT '',\n"
513 " channel VARCHAR(80) NOT NULL DEFAULT '',\n"
514 " dstchannel VARCHAR(80) NOT NULL DEFAULT '',\n"
515 " lastapp VARCHAR(80) NOT NULL DEFAULT '',\n"
516 " lastdata VARCHAR(80) NOT NULL DEFAULT '',\n"
517 " start DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
518 " answer DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
519 " end DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
520 " duration INT(11) NOT NULL DEFAULT 0,\n"
521 " billsec INT(11) NOT NULL DEFAULT 0,\n"
522 " disposition VARCHAR(45) NOT NULL DEFAULT '',\n"
523 " amaflags INT(11) NOT NULL DEFAULT 0,\n"
524 " accountcode VARCHAR(20) NOT NULL DEFAULT '',\n"
525 " uniqueid VARCHAR(32) NOT NULL DEFAULT '',\n"
526 " userfield VARCHAR(255) NOT NULL DEFAULT '',\n"
527 " PRIMARY KEY (id)\n"
530 /*! SQL query format to insert a CDR entry. */
531 static char *sql_add_cdr_entry =
560 " datetime(%d,'unixepoch'),"
561 " datetime(%d,'unixepoch'),"
562 " datetime(%d,'unixepoch'),"
573 * SQL query format to fetch the static configuration of a file.
574 * Rows must be sorted by category.
576 * \see add_cfg_entry()
578 static char *sql_get_config_table =
581 " WHERE filename = '%q' AND commented = 0"
582 " ORDER BY cat_metric ASC, var_metric ASC;";
584 static int set_var(char **var, const char *name, const char *value)
589 *var = ast_strdup(value);
592 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
599 static int check_vars(void)
602 ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
606 use_cdr = (cdr_table != NULL);
611 static int load_config(void)
613 struct ast_config *config;
614 struct ast_variable *var;
616 struct ast_flags config_flags = { 0 };
618 config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
621 ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
625 for (var = ast_variable_browse(config, "general"); var; var = var->next) {
626 if (!strcasecmp(var->name, "dbfile"))
627 SET_VAR(config, dbfile, var);
628 else if (!strcasecmp(var->name, "config_table"))
629 SET_VAR(config, config_table, var);
630 else if (!strcasecmp(var->name, "cdr_table"))
631 SET_VAR(config, cdr_table, var);
633 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
636 ast_config_destroy(config);
637 error = check_vars();
647 static void unload_config(void)
651 ast_free(config_table);
657 static int cdr_handler(struct ast_cdr *cdr)
659 char *query, *errormsg;
662 query = sqlite_mprintf(sql_add_cdr_entry, cdr_table, cdr->clid,
663 cdr->src, cdr->dst, cdr->dcontext, cdr->channel,
664 cdr->dstchannel, cdr->lastapp, cdr->lastdata,
665 cdr->start.tv_sec, cdr->answer.tv_sec,
666 cdr->end.tv_sec, cdr->duration, cdr->billsec,
667 cdr->disposition, cdr->amaflags, cdr->accountcode,
668 cdr->uniqueid, cdr->userfield);
671 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
675 ast_debug(1, "SQL query: %s\n", query);
677 ast_mutex_lock(&mutex);
679 RES_CONFIG_SQLITE_BEGIN
680 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
681 RES_CONFIG_SQLITE_END(error)
683 ast_mutex_unlock(&mutex);
685 sqlite_freemem(query);
688 ast_log(LOG_ERROR, "%s\n", errormsg);
689 sqlite_freemem(errormsg);
696 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
698 struct cfg_entry_args *args;
699 struct ast_variable *var;
701 if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
702 ast_log(LOG_WARNING, "Corrupt table\n");
708 if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
709 struct ast_config *cfg;
712 val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
713 cfg = ast_config_internal_load(val, args->cfg, args->flags, "");
716 ast_log(LOG_WARNING, "Unable to include %s\n", val);
724 if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
725 args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
728 ast_log(LOG_WARNING, "Unable to allocate category\n");
732 ast_free(args->cat_name);
733 args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
735 if (!args->cat_name) {
736 ast_category_destroy(args->cat);
740 ast_category_append(args->cfg, args->cat);
743 var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
746 ast_log(LOG_WARNING, "Unable to allocate variable");
750 ast_variable_append(args->cat, var);
755 static struct ast_config *config_handler(const char *database, const char *table, const char *file,
756 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl)
758 struct cfg_entry_args args;
759 char *query, *errormsg;
764 ast_log(LOG_ERROR, "Table name unspecified\n");
768 table = config_table;
770 query = sqlite_mprintf(sql_get_config_table, table, file);
773 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
777 ast_debug(1, "SQL query: %s\n", query);
780 args.cat_name = NULL;
783 ast_mutex_lock(&mutex);
785 RES_CONFIG_SQLITE_BEGIN
786 error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
787 RES_CONFIG_SQLITE_END(error)
789 ast_mutex_unlock(&mutex);
791 ast_free(args.cat_name);
792 sqlite_freemem(query);
795 ast_log(LOG_ERROR, "%s\n", errormsg);
796 sqlite_freemem(errormsg);
803 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
805 const char **tmp, *param, *val, **params, **vals;
812 while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
813 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
820 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
827 params[params_count] = param;
828 vals[params_count] = val;
832 if (params_count > 0) {
833 *params_ptr = params;
836 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
841 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
843 struct rt_cfg_entry_args *args;
844 struct ast_variable *var;
849 for (i = 0; i < argc; i++) {
853 if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
862 args->last->next = var;
870 static struct ast_variable * realtime_handler(const char *database, const char *table, va_list ap)
872 char *query, *errormsg, *op, *tmp_str;
873 struct rt_cfg_entry_args args;
874 const char **params, **vals;
879 ast_log(LOG_WARNING, "Table name unspecified\n");
883 params_count = get_params(ap, ¶ms, &vals);
885 if (params_count == 0)
888 op = (strchr(params[0], ' ') == NULL) ? " =" : "";
890 /* \cond DOXYGEN_CAN_PARSE_THIS */
892 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
895 query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
898 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
904 if (params_count > 1) {
907 for (i = 1; i < params_count; i++) {
908 op = (strchr(params[i], ' ') == NULL) ? " =" : "";
909 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
910 sqlite_freemem(query);
913 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
926 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
927 sqlite_freemem(query);
930 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
935 ast_debug(1, "SQL query: %s\n", query);
939 ast_mutex_lock(&mutex);
941 RES_CONFIG_SQLITE_BEGIN
942 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
943 RES_CONFIG_SQLITE_END(error)
945 ast_mutex_unlock(&mutex);
947 sqlite_freemem(query);
950 ast_log(LOG_WARNING, "%s\n", errormsg);
951 sqlite_freemem(errormsg);
952 ast_variables_destroy(args.var);
959 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
961 struct rt_multi_cfg_entry_args *args;
962 struct ast_category *cat;
963 struct ast_variable *var;
971 * cat_name should always be set here, since initfield is forged from
972 * params[0] in realtime_multi_handler(), which is a search parameter
975 for (i = 0; i < argc; i++) {
976 if (!strcmp(args->initfield, columnNames[i]))
981 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
985 if (!(cat = ast_category_new(cat_name, "", 99999))) {
986 ast_log(LOG_WARNING, "Unable to allocate category\n");
990 ast_category_append(args->cfg, cat);
992 for (i = 0; i < argc; i++) {
993 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
996 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
997 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1001 ast_variable_append(cat, var);
1007 static struct ast_config *realtime_multi_handler(const char *database,
1008 const char *table, va_list ap)
1010 char *query, *errormsg, *op, *tmp_str, *initfield;
1011 struct rt_multi_cfg_entry_args args;
1012 const char **params, **vals;
1013 struct ast_config *cfg;
1014 size_t params_count;
1018 ast_log(LOG_WARNING, "Table name unspecified\n");
1022 if (!(cfg = ast_config_new())) {
1023 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1027 if (!(params_count = get_params(ap, ¶ms, &vals))) {
1028 ast_config_destroy(cfg);
1032 if (!(initfield = ast_strdup(params[0]))) {
1033 ast_config_destroy(cfg);
1039 tmp_str = strchr(initfield, ' ');
1044 op = (!strchr(params[0], ' ')) ? " =" : "";
1047 * Asterisk sends us an already escaped string when searching for
1048 * "exten LIKE" (uh!). Handle it separately.
1050 tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1052 /* \cond DOXYGEN_CAN_PARSE_THIS */
1054 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1057 if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1058 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1059 ast_config_destroy(cfg);
1062 ast_free(initfield);
1066 if (params_count > 1) {
1069 for (i = 1; i < params_count; i++) {
1070 op = (!strchr(params[i], ' ')) ? " =" : "";
1071 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1072 sqlite_freemem(query);
1075 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1076 ast_config_destroy(cfg);
1079 ast_free(initfield);
1090 if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1091 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1092 ast_config_destroy(cfg);
1093 ast_free(initfield);
1097 sqlite_freemem(query);
1099 ast_debug(1, "SQL query: %s\n", query);
1101 args.initfield = initfield;
1103 ast_mutex_lock(&mutex);
1105 RES_CONFIG_SQLITE_BEGIN
1106 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1107 RES_CONFIG_SQLITE_END(error)
1109 ast_mutex_unlock(&mutex);
1111 sqlite_freemem(query);
1112 ast_free(initfield);
1115 ast_log(LOG_WARNING, "%s\n", errormsg);
1116 sqlite_freemem(errormsg);
1117 ast_config_destroy(cfg);
1124 static int realtime_update_handler(const char *database, const char *table,
1125 const char *keyfield, const char *entity, va_list ap)
1127 char *query, *errormsg, *tmp_str;
1128 const char **params, **vals;
1129 size_t params_count;
1130 int error, rows_num;
1133 ast_log(LOG_WARNING, "Table name unspecified\n");
1137 if (!(params_count = get_params(ap, ¶ms, &vals)))
1140 /* \cond DOXYGEN_CAN_PARSE_THIS */
1142 #define QUERY "UPDATE '%q' SET %q = '%q'"
1145 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1146 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1152 if (params_count > 1) {
1155 for (i = 1; i < params_count; i++) {
1156 tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
1157 sqlite_freemem(query);
1160 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1173 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1174 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1178 sqlite_freemem(query);
1180 ast_debug(1, "SQL query: %s\n", query);
1182 ast_mutex_lock(&mutex);
1184 RES_CONFIG_SQLITE_BEGIN
1185 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1186 RES_CONFIG_SQLITE_END(error)
1189 rows_num = sqlite_changes(db);
1193 ast_mutex_unlock(&mutex);
1195 sqlite_freemem(query);
1198 ast_log(LOG_WARNING, "%s\n", errormsg);
1199 sqlite_freemem(errormsg);
1205 static int realtime_store_handler(const char *database, const char *table, va_list ap) {
1206 char *errormsg, *tmp_str, *tmp_keys, *tmp_keys2, *tmp_vals, *tmp_vals2;
1207 const char **params, **vals;
1208 size_t params_count;
1213 ast_log(LOG_WARNING, "Table name unspecified\n");
1217 if (!(params_count = get_params(ap, ¶ms, &vals)))
1220 /* \cond DOXYGEN_CAN_PARSE_THIS */
1222 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1227 for (i = 0; i < params_count; i++) {
1229 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1230 sqlite_freemem(tmp_keys2);
1232 tmp_keys = sqlite_mprintf("%q", params[i]);
1235 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1242 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1243 sqlite_freemem(tmp_vals2);
1245 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1248 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1255 tmp_keys2 = tmp_keys;
1256 tmp_vals2 = tmp_vals;
1262 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1263 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1267 sqlite_freemem(tmp_keys);
1268 sqlite_freemem(tmp_vals);
1270 ast_debug(1, "SQL query: %s\n", tmp_str);
1272 ast_mutex_lock(&mutex);
1274 RES_CONFIG_SQLITE_BEGIN
1275 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1276 RES_CONFIG_SQLITE_END(error)
1279 rows_id = sqlite_last_insert_rowid(db);
1284 ast_mutex_unlock(&mutex);
1286 sqlite_freemem(tmp_str);
1289 ast_log(LOG_WARNING, "%s\n", errormsg);
1290 sqlite_freemem(errormsg);
1296 static int realtime_destroy_handler(const char *database, const char *table,
1297 const char *keyfield, const char *entity, va_list ap)
1299 char *query, *errormsg, *tmp_str;
1300 const char **params, **vals;
1301 size_t params_count;
1302 int error, rows_num;
1306 ast_log(LOG_WARNING, "Table name unspecified\n");
1310 if (!(params_count = get_params(ap, ¶ms, &vals)))
1313 /* \cond DOXYGEN_CAN_PARSE_THIS */
1315 #define QUERY "DELETE FROM '%q' WHERE"
1318 if (!(query = sqlite_mprintf(QUERY, table))) {
1319 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1325 for (i = 0; i < params_count; i++) {
1326 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1327 sqlite_freemem(query);
1330 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1341 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1342 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1345 sqlite_freemem(query);
1347 ast_debug(1, "SQL query: %s\n", query);
1349 ast_mutex_lock(&mutex);
1351 RES_CONFIG_SQLITE_BEGIN
1352 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1353 RES_CONFIG_SQLITE_END(error)
1356 rows_num = sqlite_changes(db);
1360 ast_mutex_unlock(&mutex);
1362 sqlite_freemem(query);
1365 ast_log(LOG_WARNING, "%s\n", errormsg);
1366 sqlite_freemem(errormsg);
1372 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1376 e->command = "show sqlite status";
1378 "Usage: show sqlite status\n"
1379 " Show status information about the SQLite 2 driver\n";
1386 return CLI_SHOWUSAGE;
1388 ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
1389 ast_cli(a->fd, "config_table: ");
1392 ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
1394 ast_cli(a->fd, "%s\n", config_table);
1396 ast_cli(a->fd, "cdr_table: ");
1399 ast_cli(a->fd, "unspecified, CDR support disabled\n");
1401 ast_cli(a->fd, "%s\n", cdr_table);
1406 static int unload_module(void)
1408 if (cli_status_registered)
1409 ast_cli_unregister_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1412 ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
1414 ast_config_engine_deregister(&sqlite_engine);
1424 static int load_module(void)
1431 cli_status_registered = 0;
1433 config_table = NULL;
1435 error = load_config();
1438 return AST_MODULE_LOAD_DECLINE;
1440 if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1441 ast_log(LOG_ERROR, "%s\n", errormsg);
1442 sqlite_freemem(errormsg);
1447 ast_config_engine_register(&sqlite_engine);
1452 /* \cond DOXYGEN_CAN_PARSE_THIS */
1454 #define QUERY "SELECT COUNT(id) FROM %Q;"
1457 query = sqlite_mprintf(QUERY, cdr_table);
1460 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1465 ast_debug(1, "SQL query: %s\n", query);
1467 RES_CONFIG_SQLITE_BEGIN
1468 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1469 RES_CONFIG_SQLITE_END(error)
1471 sqlite_freemem(query);
1477 if (error != SQLITE_ERROR) {
1478 ast_log(LOG_ERROR, "%s\n", errormsg);
1479 sqlite_freemem(errormsg);
1484 sqlite_freemem(errormsg);
1485 query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
1488 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1493 ast_debug(1, "SQL query: %s\n", query);
1495 RES_CONFIG_SQLITE_BEGIN
1496 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1497 RES_CONFIG_SQLITE_END(error)
1499 sqlite_freemem(query);
1502 ast_log(LOG_ERROR, "%s\n", errormsg);
1503 sqlite_freemem(errormsg);
1509 error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
1519 error = ast_cli_register_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1526 cli_status_registered = 1;
1531 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1532 .load = load_module,
1533 .unload = unload_module,