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;
181 const char *who_asked;
185 * Structure sent to the SQLite callback function for RealTime configuration.
187 * \see add_rt_cfg_entry()
189 struct rt_cfg_entry_args {
190 struct ast_variable *var;
191 struct ast_variable *last;
195 * Structure sent to the SQLite callback function for RealTime configuration
196 * (realtime_multi_handler()).
198 * \see add_rt_multi_cfg_entry()
200 struct rt_multi_cfg_entry_args {
201 struct ast_config *cfg;
206 * \brief Allocate a variable.
207 * \param var the address of the variable to set (it will be allocated)
208 * \param name the name of the variable (for error handling)
209 * \param value the value to store in var
210 * \retval 0 on success
211 * \retval 1 if an allocation error occurred
213 static int set_var(char **var, const char *name, const char *value);
216 * \brief Load the configuration file.
217 * \see unload_config()
219 * This function sets dbfile, config_table, and cdr_table. It calls
220 * check_vars() before returning, and unload_config() if an error occurred.
222 * \retval 0 on success
223 * \retval 1 if an error occurred
225 static int load_config(void);
228 * \brief Free resources related to configuration.
231 static void unload_config(void);
234 * \brief Asterisk callback function for CDR support.
235 * \param cdr the CDR entry Asterisk sends us.
237 * Asterisk will call this function each time a CDR entry must be logged if
238 * CDR support is enabled.
240 * \retval 0 on success
241 * \retval 1 if an error occurred
243 static int cdr_handler(struct ast_cdr *cdr);
246 * \brief SQLite callback function for static configuration.
248 * This function is passed to the SQLite engine as a callback function to
249 * parse a row and store it in a struct ast_config object. It relies on
250 * resulting rows being sorted by category.
252 * \param arg a pointer to a struct cfg_entry_args object
253 * \param argc number of columns
254 * \param argv values in the row
255 * \param columnNames names and types of the columns
256 * \retval 0 on success
257 * \retval 1 if an error occurred
258 * \see cfg_entry_args
259 * \see sql_get_config_table
260 * \see config_handler()
262 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
265 * \brief Asterisk callback function for static configuration.
267 * Asterisk will call this function when it loads its static configuration,
268 * which usually happens at startup and reload.
270 * \param database the database to use (ignored)
271 * \param table the table to use
272 * \param file the file to load from the database
273 * \param cfg the struct ast_config object to use when storing variables
274 * \param flags Optional flags. Not used.
275 * \param suggested_incl suggest include.
277 * \retval NULL if an error occurred
278 * \see add_cfg_entry()
280 static struct ast_config * config_handler(const char *database, const char *table, const char *file,
281 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked);
284 * \brief Helper function to parse a va_list object into 2 dynamic arrays of
285 * strings, parameters and values.
287 * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
288 * arguments will be extracted to create 2 arrays:
291 * <li>params : param1 param2 param3 ...</li>
292 * <li>vals : val1 val2 val3 ...</li>
295 * The address of these arrays are stored in params_ptr and vals_ptr. It
296 * is the responsibility of the caller to release the memory of these arrays.
297 * It is considered an error that va_list has a null or odd number of strings.
299 * \param ap the va_list object to parse
300 * \param params_ptr where the address of the params array is stored
301 * \param vals_ptr where the address of the vals array is stored
302 * \retval the number of elements in the arrays (which have the same size).
303 * \retval 0 if an error occurred.
305 static size_t get_params(va_list ap, const char ***params_ptr,
306 const char ***vals_ptr);
309 * \brief SQLite callback function for RealTime configuration.
311 * This function is passed to the SQLite engine as a callback function to
312 * parse a row and store it in a linked list of struct ast_variable objects.
314 * \param arg a pointer to a struct rt_cfg_entry_args object
315 * \param argc number of columns
316 * \param argv values in the row
317 * \param columnNames names and types of the columns
318 * \retval 0 on success.
319 * \retval 1 if an error occurred.
320 * \see rt_cfg_entry_args
321 * \see realtime_handler()
323 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
327 * Asterisk callback function for RealTime configuration.
329 * Asterisk will call this function each time it requires a variable
330 * through the RealTime architecture. ap is a list of parameters and
331 * values used to find a specific row, e.g one parameter "name" and
332 * one value "123" so that the SQL query becomes <code>SELECT * FROM
333 * table WHERE name = '123';</code>.
335 * \param database the database to use (ignored)
336 * \param table the table to use
337 * \param ap list of parameters and values to match
339 * \retval a linked list of struct ast_variable objects
340 * \retval NULL if an error occurred
341 * \see add_rt_cfg_entry()
343 static struct ast_variable * realtime_handler(const char *database,
344 const char *table, va_list ap);
347 * \brief SQLite callback function for RealTime configuration.
349 * This function performs the same actions as add_rt_cfg_entry() except
350 * that the rt_multi_cfg_entry_args structure is designed to store
351 * categories in addition to variables.
353 * \param arg a pointer to a struct rt_multi_cfg_entry_args object
354 * \param argc number of columns
355 * \param argv values in the row
356 * \param columnNames names and types of the columns
357 * \retval 0 on success.
358 * \retval 1 if an error occurred.
359 * \see rt_multi_cfg_entry_args
360 * \see realtime_multi_handler()
362 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
366 * \brief Asterisk callback function for RealTime configuration.
368 * This function performs the same actions as realtime_handler() except
369 * that it can store variables per category, and can return several
372 * \param database the database to use (ignored)
373 * \param table the table to use
374 * \param ap list of parameters and values to match
375 * \retval a struct ast_config object storing categories and variables.
376 * \retval NULL if an error occurred.
378 * \see add_rt_multi_cfg_entry()
380 static struct ast_config * realtime_multi_handler(const char *database,
381 const char *table, va_list ap);
384 * \brief Asterisk callback function for RealTime configuration (variable
387 * Asterisk will call this function each time a variable has been modified
388 * internally and must be updated in the backend engine. keyfield and entity
389 * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
390 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
391 * same format as the other realtime functions.
393 * \param database the database to use (ignored)
394 * \param table the table to use
395 * \param keyfield the column of the matching cell
396 * \param entity the value of the matching cell
397 * \param ap list of parameters and new values to update in the database
398 * \retval the number of affected rows.
399 * \retval -1 if an error occurred.
401 static int realtime_update_handler(const char *database, const char *table,
402 const char *keyfield, const char *entity, va_list ap);
405 * \brief Asterisk callback function for RealTime configuration (variable
408 * Asterisk will call this function each time a variable has been created
409 * internally and must be stored in the backend engine.
410 * are used to find the row to update, e.g. ap is a list of parameters and
411 * values with the same format as the other realtime functions.
413 * \param database the database to use (ignored)
414 * \param table the table to use
415 * \param ap list of parameters and new values to insert into the database
416 * \retval the rowid of inserted row.
417 * \retval -1 if an error occurred.
419 static int realtime_store_handler(const char *database, const char *table,
423 * \brief Asterisk callback function for RealTime configuration (destroys
426 * Asterisk will call this function each time a variable has been destroyed
427 * internally and must be removed from the backend engine. keyfield and entity
428 * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
429 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
430 * same format as the other realtime functions.
432 * \param database the database to use (ignored)
433 * \param table the table to use
434 * \param keyfield the column of the matching cell
435 * \param entity the value of the matching cell
436 * \param ap list of additional parameters for cell matching
437 * \retval the number of affected rows.
438 * \retval -1 if an error occurred.
440 static int realtime_destroy_handler(const char *database, const char *table,
441 const char *keyfield, const char *entity, va_list ap);
444 * \brief Asterisk callback function for the CLI status command.
446 * \param e CLI command
448 * \param a CLI argument list
449 * \return RESULT_SUCCESS
451 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
453 /*! The SQLite database object. */
456 /*! Set to 1 if CDR support is enabled. */
459 /*! Set to 1 if the CDR callback function was registered. */
460 static int cdr_registered;
462 /*! Set to 1 if the CLI status command callback function was registered. */
463 static int cli_status_registered;
465 /*! The path of the database file. */
468 /*! The name of the static configuration table. */
469 static char *config_table;
471 /*! The name of the table used to store CDR entries. */
472 static char *cdr_table;
475 * The structure specifying all callback functions used by Asterisk for static
476 * and RealTime configuration.
478 static struct ast_config_engine sqlite_engine =
480 .name = RES_CONFIG_SQLITE_DRIVER,
481 .load_func = config_handler,
482 .realtime_func = realtime_handler,
483 .realtime_multi_func = realtime_multi_handler,
484 .store_func = realtime_store_handler,
485 .destroy_func = realtime_destroy_handler,
486 .update_func = realtime_update_handler
490 * The mutex used to prevent simultaneous access to the SQLite database.
492 AST_MUTEX_DEFINE_STATIC(mutex);
495 * Structure containing details and callback functions for the CLI status
498 static struct ast_cli_entry cli_status[] = {
499 AST_CLI_DEFINE(handle_cli_show_sqlite_status, "Show status information about the SQLite 2 driver"),
503 * Taken from Asterisk 1.2 cdr_sqlite.so.
506 /*! SQL query format to create the CDR table if non existent. */
507 static char *sql_create_cdr_table =
508 "CREATE TABLE '%q' (\n"
510 " clid VARCHAR(80) NOT NULL DEFAULT '',\n"
511 " src VARCHAR(80) NOT NULL DEFAULT '',\n"
512 " dst VARCHAR(80) NOT NULL DEFAULT '',\n"
513 " dcontext VARCHAR(80) NOT NULL DEFAULT '',\n"
514 " channel VARCHAR(80) NOT NULL DEFAULT '',\n"
515 " dstchannel VARCHAR(80) NOT NULL DEFAULT '',\n"
516 " lastapp VARCHAR(80) NOT NULL DEFAULT '',\n"
517 " lastdata VARCHAR(80) NOT NULL DEFAULT '',\n"
518 " start DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
519 " answer DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
520 " end DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
521 " duration INT(11) NOT NULL DEFAULT 0,\n"
522 " billsec INT(11) NOT NULL DEFAULT 0,\n"
523 " disposition VARCHAR(45) NOT NULL DEFAULT '',\n"
524 " amaflags INT(11) NOT NULL DEFAULT 0,\n"
525 " accountcode VARCHAR(20) NOT NULL DEFAULT '',\n"
526 " uniqueid VARCHAR(32) NOT NULL DEFAULT '',\n"
527 " userfield VARCHAR(255) NOT NULL DEFAULT '',\n"
528 " PRIMARY KEY (id)\n"
531 /*! SQL query format to insert a CDR entry. */
532 static char *sql_add_cdr_entry =
561 " datetime(%d,'unixepoch','localtime'),"
562 " datetime(%d,'unixepoch','localtime'),"
563 " datetime(%d,'unixepoch','localtime'),"
574 * SQL query format to fetch the static configuration of a file.
575 * Rows must be sorted by category.
577 * \see add_cfg_entry()
579 static char *sql_get_config_table =
582 " WHERE filename = '%q' AND commented = 0"
583 " ORDER BY cat_metric ASC, var_metric ASC;";
585 static int set_var(char **var, const char *name, const char *value)
590 *var = ast_strdup(value);
593 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
600 static int check_vars(void)
603 ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
607 use_cdr = (cdr_table != NULL);
612 static int load_config(void)
614 struct ast_config *config;
615 struct ast_variable *var;
617 struct ast_flags config_flags = { 0 };
619 config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
622 ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
626 for (var = ast_variable_browse(config, "general"); var; var = var->next) {
627 if (!strcasecmp(var->name, "dbfile"))
628 SET_VAR(config, dbfile, var);
629 else if (!strcasecmp(var->name, "config_table"))
630 SET_VAR(config, config_table, var);
631 else if (!strcasecmp(var->name, "cdr_table"))
632 SET_VAR(config, cdr_table, var);
634 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
637 ast_config_destroy(config);
638 error = check_vars();
648 static void unload_config(void)
652 ast_free(config_table);
658 static int cdr_handler(struct ast_cdr *cdr)
660 char *query, *errormsg;
663 query = sqlite_mprintf(sql_add_cdr_entry, cdr_table, cdr->clid,
664 cdr->src, cdr->dst, cdr->dcontext, cdr->channel,
665 cdr->dstchannel, cdr->lastapp, cdr->lastdata,
666 cdr->start.tv_sec, cdr->answer.tv_sec,
667 cdr->end.tv_sec, cdr->duration, cdr->billsec,
668 cdr->disposition, cdr->amaflags, cdr->accountcode,
669 cdr->uniqueid, cdr->userfield);
672 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
676 ast_debug(1, "SQL query: %s\n", query);
678 ast_mutex_lock(&mutex);
680 RES_CONFIG_SQLITE_BEGIN
681 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
682 RES_CONFIG_SQLITE_END(error)
684 ast_mutex_unlock(&mutex);
686 sqlite_freemem(query);
689 ast_log(LOG_ERROR, "%s\n", errormsg);
690 sqlite_freemem(errormsg);
697 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
699 struct cfg_entry_args *args;
700 struct ast_variable *var;
702 if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
703 ast_log(LOG_WARNING, "Corrupt table\n");
709 if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
710 struct ast_config *cfg;
713 val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
714 cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked);
717 ast_log(LOG_WARNING, "Unable to include %s\n", val);
725 if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
726 args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
729 ast_log(LOG_WARNING, "Unable to allocate category\n");
733 ast_free(args->cat_name);
734 args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
736 if (!args->cat_name) {
737 ast_category_destroy(args->cat);
741 ast_category_append(args->cfg, args->cat);
744 var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
747 ast_log(LOG_WARNING, "Unable to allocate variable");
751 ast_variable_append(args->cat, var);
756 static struct ast_config *config_handler(const char *database, const char *table, const char *file,
757 struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked)
759 struct cfg_entry_args args;
760 char *query, *errormsg;
765 ast_log(LOG_ERROR, "Table name unspecified\n");
769 table = config_table;
771 query = sqlite_mprintf(sql_get_config_table, table, file);
774 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
778 ast_debug(1, "SQL query: %s\n", query);
781 args.cat_name = NULL;
783 args.who_asked = who_asked;
785 ast_mutex_lock(&mutex);
787 RES_CONFIG_SQLITE_BEGIN
788 error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
789 RES_CONFIG_SQLITE_END(error)
791 ast_mutex_unlock(&mutex);
793 ast_free(args.cat_name);
794 sqlite_freemem(query);
797 ast_log(LOG_ERROR, "%s\n", errormsg);
798 sqlite_freemem(errormsg);
805 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
807 const char **tmp, *param, *val, **params, **vals;
814 while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
815 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
822 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
829 params[params_count] = param;
830 vals[params_count] = val;
834 if (params_count > 0) {
835 *params_ptr = params;
838 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
843 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
845 struct rt_cfg_entry_args *args;
846 struct ast_variable *var;
851 for (i = 0; i < argc; i++) {
855 if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
864 args->last->next = var;
872 static struct ast_variable * realtime_handler(const char *database, const char *table, va_list ap)
874 char *query, *errormsg, *op, *tmp_str;
875 struct rt_cfg_entry_args args;
876 const char **params, **vals;
881 ast_log(LOG_WARNING, "Table name unspecified\n");
885 params_count = get_params(ap, ¶ms, &vals);
887 if (params_count == 0)
890 op = (strchr(params[0], ' ') == NULL) ? " =" : "";
892 /* \cond DOXYGEN_CAN_PARSE_THIS */
894 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
897 query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
900 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
906 if (params_count > 1) {
909 for (i = 1; i < params_count; i++) {
910 op = (strchr(params[i], ' ') == NULL) ? " =" : "";
911 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
912 sqlite_freemem(query);
915 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
928 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
929 sqlite_freemem(query);
932 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
937 ast_debug(1, "SQL query: %s\n", query);
941 ast_mutex_lock(&mutex);
943 RES_CONFIG_SQLITE_BEGIN
944 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
945 RES_CONFIG_SQLITE_END(error)
947 ast_mutex_unlock(&mutex);
949 sqlite_freemem(query);
952 ast_log(LOG_WARNING, "%s\n", errormsg);
953 sqlite_freemem(errormsg);
954 ast_variables_destroy(args.var);
961 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
963 struct rt_multi_cfg_entry_args *args;
964 struct ast_category *cat;
965 struct ast_variable *var;
973 * cat_name should always be set here, since initfield is forged from
974 * params[0] in realtime_multi_handler(), which is a search parameter
977 for (i = 0; i < argc; i++) {
978 if (!strcmp(args->initfield, columnNames[i]))
983 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
987 if (!(cat = ast_category_new(cat_name, "", 99999))) {
988 ast_log(LOG_WARNING, "Unable to allocate category\n");
992 ast_category_append(args->cfg, cat);
994 for (i = 0; i < argc; i++) {
995 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
998 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
999 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1003 ast_variable_append(cat, var);
1009 static struct ast_config *realtime_multi_handler(const char *database,
1010 const char *table, va_list ap)
1012 char *query, *errormsg, *op, *tmp_str, *initfield;
1013 struct rt_multi_cfg_entry_args args;
1014 const char **params, **vals;
1015 struct ast_config *cfg;
1016 size_t params_count;
1020 ast_log(LOG_WARNING, "Table name unspecified\n");
1024 if (!(cfg = ast_config_new())) {
1025 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1029 if (!(params_count = get_params(ap, ¶ms, &vals))) {
1030 ast_config_destroy(cfg);
1034 if (!(initfield = ast_strdup(params[0]))) {
1035 ast_config_destroy(cfg);
1041 tmp_str = strchr(initfield, ' ');
1046 op = (!strchr(params[0], ' ')) ? " =" : "";
1049 * Asterisk sends us an already escaped string when searching for
1050 * "exten LIKE" (uh!). Handle it separately.
1052 tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1054 /* \cond DOXYGEN_CAN_PARSE_THIS */
1056 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1059 if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1060 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1061 ast_config_destroy(cfg);
1064 ast_free(initfield);
1068 if (params_count > 1) {
1071 for (i = 1; i < params_count; i++) {
1072 op = (!strchr(params[i], ' ')) ? " =" : "";
1073 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1074 sqlite_freemem(query);
1077 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1078 ast_config_destroy(cfg);
1081 ast_free(initfield);
1092 if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1093 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1094 ast_config_destroy(cfg);
1095 ast_free(initfield);
1099 sqlite_freemem(query);
1101 ast_debug(1, "SQL query: %s\n", query);
1103 args.initfield = initfield;
1105 ast_mutex_lock(&mutex);
1107 RES_CONFIG_SQLITE_BEGIN
1108 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1109 RES_CONFIG_SQLITE_END(error)
1111 ast_mutex_unlock(&mutex);
1113 sqlite_freemem(query);
1114 ast_free(initfield);
1117 ast_log(LOG_WARNING, "%s\n", errormsg);
1118 sqlite_freemem(errormsg);
1119 ast_config_destroy(cfg);
1126 static int realtime_update_handler(const char *database, const char *table,
1127 const char *keyfield, const char *entity, va_list ap)
1129 char *query, *errormsg, *tmp_str;
1130 const char **params, **vals;
1131 size_t params_count;
1132 int error, rows_num;
1135 ast_log(LOG_WARNING, "Table name unspecified\n");
1139 if (!(params_count = get_params(ap, ¶ms, &vals)))
1142 /* \cond DOXYGEN_CAN_PARSE_THIS */
1144 #define QUERY "UPDATE '%q' SET %q = '%q'"
1147 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1148 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1154 if (params_count > 1) {
1157 for (i = 1; i < params_count; i++) {
1158 tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
1159 sqlite_freemem(query);
1162 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1175 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1176 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1180 sqlite_freemem(query);
1182 ast_debug(1, "SQL query: %s\n", query);
1184 ast_mutex_lock(&mutex);
1186 RES_CONFIG_SQLITE_BEGIN
1187 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1188 RES_CONFIG_SQLITE_END(error)
1191 rows_num = sqlite_changes(db);
1195 ast_mutex_unlock(&mutex);
1197 sqlite_freemem(query);
1200 ast_log(LOG_WARNING, "%s\n", errormsg);
1201 sqlite_freemem(errormsg);
1207 static int realtime_store_handler(const char *database, const char *table, va_list ap) {
1208 char *errormsg, *tmp_str, *tmp_keys, *tmp_keys2, *tmp_vals, *tmp_vals2;
1209 const char **params, **vals;
1210 size_t params_count;
1215 ast_log(LOG_WARNING, "Table name unspecified\n");
1219 if (!(params_count = get_params(ap, ¶ms, &vals)))
1222 /* \cond DOXYGEN_CAN_PARSE_THIS */
1224 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1229 for (i = 0; i < params_count; i++) {
1231 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1232 sqlite_freemem(tmp_keys2);
1234 tmp_keys = sqlite_mprintf("%q", params[i]);
1237 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1244 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1245 sqlite_freemem(tmp_vals2);
1247 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1250 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1257 tmp_keys2 = tmp_keys;
1258 tmp_vals2 = tmp_vals;
1264 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1265 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1269 sqlite_freemem(tmp_keys);
1270 sqlite_freemem(tmp_vals);
1272 ast_debug(1, "SQL query: %s\n", tmp_str);
1274 ast_mutex_lock(&mutex);
1276 RES_CONFIG_SQLITE_BEGIN
1277 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1278 RES_CONFIG_SQLITE_END(error)
1281 rows_id = sqlite_last_insert_rowid(db);
1286 ast_mutex_unlock(&mutex);
1288 sqlite_freemem(tmp_str);
1291 ast_log(LOG_WARNING, "%s\n", errormsg);
1292 sqlite_freemem(errormsg);
1298 static int realtime_destroy_handler(const char *database, const char *table,
1299 const char *keyfield, const char *entity, va_list ap)
1301 char *query, *errormsg, *tmp_str;
1302 const char **params, **vals;
1303 size_t params_count;
1304 int error, rows_num;
1308 ast_log(LOG_WARNING, "Table name unspecified\n");
1312 if (!(params_count = get_params(ap, ¶ms, &vals)))
1315 /* \cond DOXYGEN_CAN_PARSE_THIS */
1317 #define QUERY "DELETE FROM '%q' WHERE"
1320 if (!(query = sqlite_mprintf(QUERY, table))) {
1321 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1327 for (i = 0; i < params_count; i++) {
1328 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1329 sqlite_freemem(query);
1332 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1343 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1344 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1347 sqlite_freemem(query);
1349 ast_debug(1, "SQL query: %s\n", query);
1351 ast_mutex_lock(&mutex);
1353 RES_CONFIG_SQLITE_BEGIN
1354 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1355 RES_CONFIG_SQLITE_END(error)
1358 rows_num = sqlite_changes(db);
1362 ast_mutex_unlock(&mutex);
1364 sqlite_freemem(query);
1367 ast_log(LOG_WARNING, "%s\n", errormsg);
1368 sqlite_freemem(errormsg);
1374 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1378 e->command = "show sqlite status";
1380 "Usage: show sqlite status\n"
1381 " Show status information about the SQLite 2 driver\n";
1388 return CLI_SHOWUSAGE;
1390 ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
1391 ast_cli(a->fd, "config_table: ");
1394 ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
1396 ast_cli(a->fd, "%s\n", config_table);
1398 ast_cli(a->fd, "cdr_table: ");
1401 ast_cli(a->fd, "unspecified, CDR support disabled\n");
1403 ast_cli(a->fd, "%s\n", cdr_table);
1408 static int unload_module(void)
1410 if (cli_status_registered)
1411 ast_cli_unregister_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1414 ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
1416 ast_config_engine_deregister(&sqlite_engine);
1426 static int load_module(void)
1433 cli_status_registered = 0;
1435 config_table = NULL;
1437 error = load_config();
1440 return AST_MODULE_LOAD_DECLINE;
1442 if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1443 ast_log(LOG_ERROR, "%s\n", errormsg);
1444 sqlite_freemem(errormsg);
1449 ast_config_engine_register(&sqlite_engine);
1454 /* \cond DOXYGEN_CAN_PARSE_THIS */
1456 #define QUERY "SELECT COUNT(id) FROM %Q;"
1459 query = sqlite_mprintf(QUERY, cdr_table);
1462 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1467 ast_debug(1, "SQL query: %s\n", query);
1469 RES_CONFIG_SQLITE_BEGIN
1470 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1471 RES_CONFIG_SQLITE_END(error)
1473 sqlite_freemem(query);
1479 if (error != SQLITE_ERROR) {
1480 ast_log(LOG_ERROR, "%s\n", errormsg);
1481 sqlite_freemem(errormsg);
1486 sqlite_freemem(errormsg);
1487 query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
1490 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1495 ast_debug(1, "SQL query: %s\n", query);
1497 RES_CONFIG_SQLITE_BEGIN
1498 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1499 RES_CONFIG_SQLITE_END(error)
1501 sqlite_freemem(query);
1504 ast_log(LOG_ERROR, "%s\n", errormsg);
1505 sqlite_freemem(errormsg);
1511 error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
1521 error = ast_cli_register_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1528 cli_status_registered = 1;
1533 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1534 .load = load_module,
1535 .unload = unload_module,