2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2006, Proformatique
6 * Written by Richard Braun <rbraun@proformatique.com>
8 * Based on res_sqlite3 by Anthony Minessale II,
9 * and res_config_mysql by Matthew Boehm
11 * See http://www.asterisk.org for more information about
12 * the Asterisk project. Please do not directly contact
13 * any of the maintainers of this project for assistance;
14 * the project provides a web site, mailing lists and IRC
15 * channels for your use.
17 * This program is free software, distributed under the terms of
18 * the GNU General Public License Version 2. See the LICENSE file
19 * at the top of the source tree.
23 * \page res_config_sqlite
25 * \section intro_sec Presentation
27 * res_config_sqlite is a module for the Asterisk Open Source PBX to
28 * support SQLite 2 databases. It can be used to fetch configuration
29 * from a database (static configuration files and/or using the Asterisk
30 * RealTime Architecture - ARA).
31 * It can also be used to log CDR entries. Finally, it can be used for simple
32 * queries in the Dialplan. Note that Asterisk already comes with a module
33 * named cdr_sqlite. There are two reasons for including it in res_sqlite:
34 * the first is that rewriting it was a training to learn how to write a
35 * simple module for Asterisk, the other is to have the same database open for
36 * all kinds of operations, which improves reliability and performance.
38 * There is already a module for SQLite 3 (named res_sqlite3) in the Asterisk
39 * addons. res_sqlite was developed because we, at Proformatique, are using
40 * PHP 4 in our embedded systems, and PHP 4 has no stable support for SQLite 3
41 * at this time. We also needed RealTime support.
43 * \section conf_sec Configuration
45 * The main configuration file is res_config_sqlite.conf. It must be readable or
46 * res_sqlite will fail to start. It is suggested to use the sample file
47 * in this package as a starting point. The file has only one section
48 * named <code>general</code>. Here are the supported parameters :
51 * <dt><code>dbfile</code></dt>
52 * <dd>The absolute path to the SQLite database (the file can be non existent,
53 * res_sqlite will create it if is has the appropriate rights)</dd>
54 * <dt><code>config_table</code></dt>
55 * <dd>The table used for static configuration</dd>
56 * <dt><code>cdr_table</code></dt>
57 * <dd>The table used to store CDR entries (if ommitted, CDR support is
61 * To use res_sqlite for static and/or RealTime configuration, refer to the
62 * Asterisk documentation. The file tables.sql can be used to create the
65 * The SQLITE() application is very similar to the MYSQL() application. You
66 * can find more details at
67 * <a href="http://voip-info.org/wiki/view/Asterisk+cmd+MYSQL">http://voip-info.org/wiki/view/Asterisk+cmd+MYSQL</a>.
68 * The main difference is that you cannot choose your database - it's the
69 * file set in the <code>dbfile</code> parameter. As a result, there is no
70 * Connect or Disconnect command, and there is no connid variable.
72 * \section status_sec Driver status
74 * The CLI command <code>show sqlite status</code> returns status information
75 * about the running driver. One information is more important than others:
76 * the number of registered virtual machines. A SQLite virtual machine is
77 * created each time a SQLITE() query command is used. If the number of
78 * registered virtual machines isn't 0 (or near 0, since one or more SQLITE()
79 * commands can be running when requesting the module status) and increases
80 * over time, this probably means that you're badly using the application
81 * and you're creating resource leaks. You should check your Dialplan and
82 * reload res_sqlite (by unloading and then loading again - reloading isn't
85 * \section credits_sec Credits
87 * res_config_sqlite was developed by Richard Braun at the Proformatique company.
92 * \brief res_sqlite module.
96 <depend>sqlite</depend>
107 #include "asterisk/pbx.h"
108 #include "asterisk/cdr.h"
109 #include "asterisk/cli.h"
110 #include "asterisk/lock.h"
111 #include "asterisk/config.h"
112 #include "asterisk/logger.h"
113 #include "asterisk/module.h"
114 #include "asterisk/options.h"
115 #include "asterisk/linkedlists.h"
117 #define RES_SQLITE_NAME "res_sqlite"
118 #define RES_SQLITE_DRIVER "sqlite"
119 #define RES_SQLITE_APP_DRIVER "SQLITE"
120 #define RES_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
121 #define RES_SQLITE_CONF_FILE "res_config_sqlite.conf"
122 #define RES_SQLITE_APP_SYNOPSIS "Dialplan access to SQLite 2"
123 #define RES_SQLITE_APP_DESCRIPTION \
124 "SQLITE(): " RES_SQLITE_APP_SYNOPSIS "\n"
125 #define RES_SQLITE_STATUS_SUMMARY \
126 "Show status information about the SQLite 2 driver"
127 #define RES_SQLITE_STATUS_USAGE \
128 "Usage: show sqlite status\n" \
129 " " RES_SQLITE_STATUS_SUMMARY "\n"
132 RES_SQLITE_CONFIG_ID,
133 RES_SQLITE_CONFIG_COMMENTED,
134 RES_SQLITE_CONFIG_FILENAME,
135 RES_SQLITE_CONFIG_CATEGORY,
136 RES_SQLITE_CONFIG_VAR_NAME,
137 RES_SQLITE_CONFIG_VAR_VAL,
138 RES_SQLITE_CONFIG_COLUMNS,
142 * Limit the number of maximum simultaneous registered SQLite VMs to avoid
143 * a denial of service attack.
145 #define RES_SQLITE_VM_MAX 1024
147 #define SET_VAR(config, to, from) \
151 __error = set_var(&to, #to, from->value); \
154 ast_config_destroy(config); \
162 * Maximum number of loops before giving up executing a query. Calls to
163 * sqlite_xxx() functions which can return SQLITE_BUSY or SQLITE_LOCKED
164 * are enclosed by RES_SQLITE_BEGIN and RES_SQLITE_END, e.g.
170 * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
171 * RES_SQLITE_END(error)
177 #define RES_SQLITE_MAX_LOOPS 10
180 * Macro used before executing a query.
182 * \see RES_SQLITE_MAX_LOOPS.
184 #define RES_SQLITE_BEGIN \
187 for (__i = 0; __i < RES_SQLITE_MAX_LOOPS; __i++) \
191 * Macro used after executing a query.
193 * \see RES_SQLITE_MAX_LOOPS.
195 #define RES_SQLITE_END(error) \
196 if (error != SQLITE_BUSY && error != SQLITE_LOCKED) \
203 * Structure sent to the SQLite callback function for static configuration.
205 * \see add_cfg_entry()
207 struct cfg_entry_args {
208 struct ast_config *cfg;
209 struct ast_category *cat;
214 * Structure sent to the SQLite callback function for RealTime configuration.
216 * \see add_rt_cfg_entry()
218 struct rt_cfg_entry_args {
219 struct ast_variable *var;
220 struct ast_variable *last;
224 * Structure sent to the SQLite callback function for RealTime configuration
225 * (realtime_multi_handler()).
227 * \see add_rt_multi_cfg_entry()
229 struct rt_multi_cfg_entry_args {
230 struct ast_config *cfg;
235 * \brief Allocate a variable.
236 * \param var the address of the variable to set (it will be allocated)
237 * \param name the name of the variable (for error handling)
238 * \param value the value to store in var
239 * \retval 0 on success
240 * \retval 1 if an allocation error occurred
242 static int set_var(char **var, char *name, char *value);
245 * \brief Load the configuration file.
246 * \see unload_config()
248 * This function sets dbfile, config_table, and cdr_table. It calls
249 * check_vars() before returning, and unload_config() if an error occurred.
251 * \retval 0 on success
252 * \retval 1 if an error occurred
254 static int load_config(void);
257 * \brief Free resources related to configuration.
260 static void unload_config(void);
263 * \brief Asterisk callback function for CDR support.
264 * \param cdr the CDR entry Asterisk sends us
266 * Asterisk will call this function each time a CDR entry must be logged if
267 * CDR support is enabled.
269 * \retval 0 on success
270 * \retval 1 if an error occurred
272 static int cdr_handler(struct ast_cdr *cdr);
275 * \brief SQLite callback function for static configuration.
277 * This function is passed to the SQLite engine as a callback function to
278 * parse a row and store it in a struct ast_config object. It relies on
279 * resulting rows being sorted by category.
281 * \param arg a pointer to a struct cfg_entry_args object
282 * \param argc number of columns
283 * \param argv values in the row
284 * \param columnNames names and types of the columns
285 * \retval 0 on success
286 * \retval 1 if an error occurred
287 * \see cfg_entry_args
288 * \see sql_get_config_table
289 * \see config_handler()
291 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
294 * \brief Asterisk callback function for static configuration.
296 * Asterisk will call this function when it loads its static configuration,
297 * which usually happens at startup and reload.
299 * \param database the database to use (ignored)
300 * \param table the table to use
301 * \param file the file to load from the database
302 * \param cfg the struct ast_config object to use when storing variables
303 * \param flags Optional flags. Not used.
305 * \retval NULL if an error occurred
306 * \see add_cfg_entry()
308 static struct ast_config * config_handler(const char *database,
309 const char *table, const char *file,
310 struct ast_config *cfg, struct ast_flags flags);
313 * \brief Helper function to parse a va_list object into 2 dynamic arrays of
314 * strings, parameters and values.
316 * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
317 * arguments will be extracted to create 2 arrays:
320 * <li>params : param1 param2 param3 ...</li>
321 * <li>vals : val1 val2 val3 ...</li>
324 * The address of these arrays are stored in params_ptr and vals_ptr. It
325 * is the responsibility of the caller to release the memory of these arrays.
326 * It is considered an error that va_list has a null or odd number of strings.
328 * \param ap the va_list object to parse
329 * \param params_ptr where the address of the params array is stored
330 * \param vals_ptr where the address of the vals array is stored
331 * \retval the number of elements in the arrays (which have the same size).
332 * \retval 0 if an error occurred.
334 static size_t get_params(va_list ap, const char ***params_ptr,
335 const char ***vals_ptr);
338 * \brief SQLite callback function for RealTime configuration.
340 * This function is passed to the SQLite engine as a callback function to
341 * parse a row and store it in a linked list of struct ast_variable objects.
343 * \param arg a pointer to a struct rt_cfg_entry_args object
344 * \param argc number of columns
345 * \param argv values in the row
346 * \param columnNames names and types of the columns
347 * \retval 0 on success.
348 * \retval 1 if an error occurred.
349 * \see rt_cfg_entry_args
350 * \see realtime_handler()
352 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
356 * Asterisk callback function for RealTime configuration.
358 * Asterisk will call this function each time it requires a variable
359 * through the RealTime architecture. ap is a list of parameters and
360 * values used to find a specific row, e.g one parameter "name" and
361 * one value "123" so that the SQL query becomes <code>SELECT * FROM
362 * table WHERE name = '123';</code>.
364 * \param database the database to use (ignored)
365 * \param table the table to use
366 * \param ap list of parameters and values to match
368 * \retval a linked list of struct ast_variable objects
369 * \retval NULL if an error occurred
370 * \see add_rt_cfg_entry()
372 static struct ast_variable * realtime_handler(const char *database,
373 const char *table, va_list ap);
376 * \brief SQLite callback function for RealTime configuration.
378 * This function performs the same actions as add_rt_cfg_entry() except
379 * that the rt_multi_cfg_entry_args structure is designed to store
380 * categories in addition of variables.
382 * \param arg a pointer to a struct rt_multi_cfg_entry_args object
383 * \param argc number of columns
384 * \param argv values in the row
385 * \param columnNames names and types of the columns
386 * \retval 0 on success.
387 * \retval 1 if an error occurred.
388 * \see rt_multi_cfg_entry_args
389 * \see realtime_multi_handler()
391 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
395 * \brief Asterisk callback function for RealTime configuration.
397 * This function performs the same actions as realtime_handler() except
398 * that it can store variables per category, and can return several
401 * \param database the database to use (ignored)
402 * \param table the table to use
403 * \param ap list of parameters and values to match
404 * \retval a struct ast_config object storing categories and variables.
405 * \retval NULL if an error occurred.
407 * \see add_rt_multi_cfg_entry()
409 static struct ast_config * realtime_multi_handler(const char *database,
414 * \brief Asterisk callback function for RealTime configuration (variable
417 * Asterisk will call this function each time a variable has been modified
418 * internally and must be updated in the backend engine. keyfield and entity
419 * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
420 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
421 * same format as the other realtime functions.
423 * \param database the database to use (ignored)
424 * \param table the table to use
425 * \param keyfield the column of the matching cell
426 * \param entity the value of the matching cell
427 * \param ap list of parameters and new values to update in the database
428 * \retval the number of affected rows.
429 * \retval -1 if an error occurred.
431 static int realtime_update_handler(const char *database, const char *table,
432 const char *keyfield, const char *entity,
436 * \brief Asterisk callback function for RealTime configuration (variable
439 * Asterisk will call this function each time a variable has been created
440 * internally and must be stored in the backend engine.
441 * are used to find the row to update, e.g. ap is a list of parameters and
442 * values with the same format as the other realtime functions.
444 * \param database the database to use (ignored)
445 * \param table the table to use
446 * \param ap list of parameters and new values to insert into the database
447 * \retval the rowid of inserted row.
448 * \retval -1 if an error occurred.
450 static int realtime_store_handler(const char *database, const char *table,
454 * \brief Asterisk callback function for RealTime configuration (destroys
457 * Asterisk will call this function each time a variable has been destroyed
458 * internally and must be removed from the backend engine. keyfield and entity
459 * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
460 * keyfield = 'entity';</code>. ap is a list of parameters and values with the
461 * same format as the other realtime functions.
463 * \param database the database to use (ignored)
464 * \param table the table to use
465 * \param keyfield the column of the matching cell
466 * \param entity the value of the matching cell
467 * \param ap list of additional parameters for cell matching
468 * \retval the number of affected rows.
469 * \retval -1 if an error occurred.
471 static int realtime_destroy_handler(const char *database, const char *table,
472 const char *keyfield, const char *entity,
476 * \brief Asterisk callback function for the CLI status command.
478 * \param fd file descriptor provided by Asterisk to use with ast_cli()
479 * \param argc number of arguments
480 * \param argv arguments list
481 * \return RESULT_SUCCESS
483 static int cli_status(int fd, int argc, char *argv[]);
485 /*! The SQLite database object. */
488 /*! Set to 1 if CDR support is enabled. */
491 /*! Set to 1 if the CDR callback function was registered. */
492 static int cdr_registered;
494 /*! Set to 1 if the CLI status command callback function was registered. */
495 static int cli_status_registered;
497 /*! The path of the database file. */
500 /*! The name of the static configuration table. */
501 static char *config_table;
503 /*! The name of the table used to store CDR entries. */
504 static char *cdr_table;
506 /*! The number of registered virtual machines. */
510 * The structure specifying all callback functions used by Asterisk for static
511 * and RealTime configuration.
513 static struct ast_config_engine sqlite_engine =
515 .name = RES_SQLITE_DRIVER,
516 .load_func = config_handler,
517 .realtime_func = realtime_handler,
518 .realtime_multi_func = realtime_multi_handler,
519 .store_func = realtime_store_handler,
520 .destroy_func = realtime_destroy_handler,
521 .update_func = realtime_update_handler
525 * The mutex used to prevent simultaneous access to the SQLite database.
526 * SQLite isn't always compiled with thread safety.
528 AST_MUTEX_DEFINE_STATIC(mutex);
531 * Structure containing details and callback functions for the CLI status
534 static struct ast_cli_entry cli_status_cmd =
536 .cmda = {"show", "sqlite", "status", NULL},
537 .handler = cli_status,
538 .summary = RES_SQLITE_STATUS_SUMMARY,
539 .usage = RES_SQLITE_STATUS_USAGE
543 * Taken from Asterisk 1.2 cdr_sqlite.so.
546 /*! SQL query format to create the CDR table if non existent. */
547 static char *sql_create_cdr_table =
548 "CREATE TABLE '%q' ("
549 " id INTEGER PRIMARY KEY,"
550 " clid VARCHAR(80) NOT NULL DEFAULT '',"
551 " src VARCHAR(80) NOT NULL DEFAULT '',"
552 " dst VARCHAR(80) NOT NULL DEFAULT '',"
553 " dcontext VARCHAR(80) NOT NULL DEFAULT '',"
554 " channel VARCHAR(80) NOT NULL DEFAULT '',"
555 " dstchannel VARCHAR(80) NOT NULL DEFAULT '',"
556 " lastapp VARCHAR(80) NOT NULL DEFAULT '',"
557 " lastdata VARCHAR(80) NOT NULL DEFAULT '',"
558 " start CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
559 " answer CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
560 " end CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
561 " duration INT(11) NOT NULL DEFAULT '0',"
562 " billsec INT(11) NOT NULL DEFAULT '0',"
563 " disposition INT(11) NOT NULL DEFAULT '0',"
564 " amaflags INT(11) NOT NULL DEFAULT '0',"
565 " accountcode VARCHAR(20) NOT NULL DEFAULT '',"
566 " uniqueid VARCHAR(32) NOT NULL DEFAULT '',"
567 " userfield VARCHAR(255) NOT NULL DEFAULT ''"
570 /*! SQL query format to insert a CDR entry. */
571 static char *sql_add_cdr_entry =
600 " datetime(%d,'unixepoch'),"
601 " datetime(%d,'unixepoch'),"
602 " datetime(%d,'unixepoch'),"
613 * SQL query format to fetch the static configuration of a file.
614 * Rows must be sorted by category.
616 * \see add_cfg_entry()
618 static char *sql_get_config_table =
621 " WHERE filename = '%q' AND commented = 0"
622 " ORDER BY category;";
624 static int set_var(char **var, char *name, char *value)
629 *var = ast_strdup(value);
632 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
639 static int check_vars(void)
642 ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
646 use_cdr = (cdr_table != NULL);
651 static int load_config(void)
653 struct ast_config *config;
654 struct ast_variable *var;
656 struct ast_flags config_flags = { 0 };
658 config = ast_config_load(RES_SQLITE_CONF_FILE, config_flags);
661 ast_log(LOG_ERROR, "Unable to load " RES_SQLITE_CONF_FILE "\n");
665 for (var = ast_variable_browse(config, "general"); var; var = var->next) {
666 if (!strcasecmp(var->name, "dbfile"))
667 SET_VAR(config, dbfile, var);
668 else if (!strcasecmp(var->name, "config_table"))
669 SET_VAR(config, config_table, var);
670 else if (!strcasecmp(var->name, "cdr_table"))
671 SET_VAR(config, cdr_table, var);
673 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
676 ast_config_destroy(config);
677 error = check_vars();
687 static void unload_config(void)
691 ast_free(config_table);
697 static int cdr_handler(struct ast_cdr *cdr)
702 ast_mutex_lock(&mutex);
705 error = sqlite_exec_printf(db, sql_add_cdr_entry, NULL, NULL, &errormsg,
706 cdr_table, cdr->clid, cdr->src, cdr->dst,
707 cdr->dcontext, cdr->channel, cdr->dstchannel,
708 cdr->lastapp, cdr->lastdata, cdr->start.tv_sec,
709 cdr->answer.tv_sec, cdr->end.tv_sec,
710 cdr->duration, cdr->billsec, cdr->disposition,
711 cdr->amaflags, cdr->accountcode, cdr->uniqueid,
713 RES_SQLITE_END(error)
715 ast_mutex_unlock(&mutex);
718 ast_log(LOG_ERROR, "%s\n", errormsg);
726 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
728 struct cfg_entry_args *args;
729 struct ast_variable *var;
731 if (argc != RES_SQLITE_CONFIG_COLUMNS) {
732 ast_log(LOG_WARNING, "Corrupt table\n");
738 if (!args->cat_name || strcmp(args->cat_name, argv[RES_SQLITE_CONFIG_CATEGORY])) {
739 args->cat = ast_category_new(argv[RES_SQLITE_CONFIG_CATEGORY]);
742 ast_log(LOG_WARNING, "Unable to allocate category\n");
746 ast_free(args->cat_name);
747 args->cat_name = ast_strdup(argv[RES_SQLITE_CONFIG_CATEGORY]);
749 if (!args->cat_name) {
750 ast_category_destroy(args->cat);
754 ast_category_append(args->cfg, args->cat);
757 var = ast_variable_new(argv[RES_SQLITE_CONFIG_VAR_NAME],
758 argv[RES_SQLITE_CONFIG_VAR_VAL]);
761 ast_log(LOG_WARNING, "Unable to allocate variable");
765 ast_variable_append(args->cat, var);
770 static struct ast_config *config_handler(const char *database,
771 const char *table, const char *file, struct ast_config *cfg, struct ast_flags flags)
773 struct cfg_entry_args args;
779 ast_log(LOG_ERROR, "Table name unspecified\n");
783 table = config_table;
787 args.cat_name = NULL;
789 ast_mutex_lock(&mutex);
792 error = sqlite_exec_printf(db, sql_get_config_table, add_cfg_entry,
793 &args, &errormsg, table, file);
794 RES_SQLITE_END(error)
796 ast_mutex_unlock(&mutex);
798 ast_free(args.cat_name);
801 ast_log(LOG_ERROR, "%s\n", errormsg);
809 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
811 const char **tmp, *param, *val, **params, **vals;
818 while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
819 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
826 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
833 params[params_count] = param;
834 vals[params_count] = val;
838 if (params_count > 0) {
839 *params_ptr = params;
842 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
847 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
849 struct rt_cfg_entry_args *args;
850 struct ast_variable *var;
855 for (i = 0; i < argc; i++) {
859 if (!(var = ast_variable_new(columnNames[i], argv[i])))
868 args->last->next = var;
876 static struct ast_variable *
877 realtime_handler(const char *database, const char *table, va_list ap)
879 char *query, *errormsg, *op, *tmp_str;
880 struct rt_cfg_entry_args args;
881 const char **params, **vals;
886 ast_log(LOG_WARNING, "Table name unspecified\n");
890 params_count = get_params(ap, ¶ms, &vals);
892 if (params_count == 0)
895 op = (strchr(params[0], ' ') == NULL) ? " =" : "";
897 /* \cond DOXYGEN_CAN_PARSE_THIS */
899 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
902 query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
905 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
911 if (params_count > 1) {
914 for (i = 1; i < params_count; i++) {
915 op = (strchr(params[i], ' ') == NULL) ? " =" : "";
916 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op,
918 sqlite_freemem(query);
921 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
934 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
935 sqlite_freemem(query);
938 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
943 ast_debug(1, "SQL query: %s\n", query);
947 ast_mutex_lock(&mutex);
950 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
951 RES_SQLITE_END(error)
953 ast_mutex_unlock(&mutex);
955 sqlite_freemem(query);
958 ast_log(LOG_WARNING, "%s\n", errormsg);
960 ast_variables_destroy(args.var);
967 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
969 struct rt_multi_cfg_entry_args *args;
970 struct ast_category *cat;
971 struct ast_variable *var;
975 args = (struct rt_multi_cfg_entry_args *)arg;
979 * cat_name should always be set here, since initfield is forged from
980 * params[0] in realtime_multi_handler(), which is a search parameter
983 for (i = 0; i < argc; i++) {
984 if (!strcmp(args->initfield, columnNames[i]))
989 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
993 if (!(cat = ast_category_new(cat_name))) {
994 ast_log(LOG_WARNING, "Unable to allocate category\n");
998 ast_category_append(args->cfg, cat);
1000 for (i = 0; i < argc; i++) {
1001 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
1004 if (!(var = ast_variable_new(columnNames[i], argv[i]))) {
1005 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1009 ast_variable_append(cat, var);
1015 static struct ast_config *realtime_multi_handler(const char *database,
1016 const char *table, va_list ap)
1018 char *query, *errormsg, *op, *tmp_str, *initfield;
1019 struct rt_multi_cfg_entry_args args;
1020 const char **params, **vals;
1021 struct ast_config *cfg;
1022 size_t params_count;
1026 ast_log(LOG_WARNING, "Table name unspecified\n");
1030 if (!(cfg = ast_config_new())) {
1031 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1035 if (!(params_count = get_params(ap, ¶ms, &vals))) {
1036 ast_config_destroy(cfg);
1040 if (!(initfield = ast_strdup(params[0]))) {
1041 ast_config_destroy(cfg);
1047 tmp_str = strchr(initfield, ' ');
1052 op = (!strchr(params[0], ' ')) ? " =" : "";
1055 * Asterisk sends us an already escaped string when searching for
1056 * "exten LIKE" (uh!). Handle it separately.
1058 tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1060 /* \cond DOXYGEN_CAN_PARSE_THIS */
1062 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1065 if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1066 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1067 ast_config_destroy(cfg);
1070 ast_free(initfield);
1074 if (params_count > 1) {
1077 for (i = 1; i < params_count; i++) {
1078 op = (!strchr(params[i], ' ')) ? " =" : "";
1079 tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op,
1081 sqlite_freemem(query);
1084 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1085 ast_config_destroy(cfg);
1088 ast_free(initfield);
1099 if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1100 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1101 ast_config_destroy(cfg);
1102 ast_free(initfield);
1106 sqlite_freemem(query);
1108 ast_debug(1, "SQL query: %s\n", query);
1110 args.initfield = initfield;
1112 ast_mutex_lock(&mutex);
1115 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1116 RES_SQLITE_END(error)
1118 ast_mutex_unlock(&mutex);
1120 sqlite_freemem(query);
1121 ast_free(initfield);
1124 ast_log(LOG_WARNING, "%s\n", errormsg);
1126 ast_config_destroy(cfg);
1133 static int realtime_update_handler(const char *database, const char *table,
1134 const char *keyfield, const char *entity,
1137 char *query, *errormsg, *tmp_str;
1138 const char **params, **vals;
1139 size_t params_count;
1140 int error, rows_num;
1143 ast_log(LOG_WARNING, "Table name unspecified\n");
1147 if (!(params_count = get_params(ap, ¶ms, &vals)))
1150 /* \cond DOXYGEN_CAN_PARSE_THIS */
1152 #define QUERY "UPDATE '%q' SET %q = '%q'"
1155 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1156 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1162 if (params_count > 1) {
1165 for (i = 1; i < params_count; i++) {
1166 tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i],
1168 sqlite_freemem(query);
1171 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1184 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1185 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1189 sqlite_freemem(query);
1191 ast_debug(1, "SQL query: %s\n", query);
1193 ast_mutex_lock(&mutex);
1196 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1197 RES_SQLITE_END(error)
1200 rows_num = sqlite_changes(db);
1204 ast_mutex_unlock(&mutex);
1206 sqlite_freemem(query);
1209 ast_log(LOG_WARNING, "%s\n", errormsg);
1216 static int realtime_store_handler(const char *database, const char *table, va_list ap) {
1217 char *errormsg, *tmp_str, *tmp_keys, *tmp_keys2, *tmp_vals, *tmp_vals2;
1218 const char **params, **vals;
1219 size_t params_count;
1224 ast_log(LOG_WARNING, "Table name unspecified\n");
1228 if (!(params_count = get_params(ap, ¶ms, &vals)))
1231 /* \cond DOXYGEN_CAN_PARSE_THIS */
1233 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1238 for (i = 0; i < params_count; i++) {
1240 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1241 sqlite_freemem(tmp_keys2);
1243 tmp_keys = sqlite_mprintf("%q", params[i]);
1246 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1253 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1254 sqlite_freemem(tmp_vals2);
1256 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1259 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1266 tmp_keys2 = tmp_keys;
1267 tmp_vals2 = tmp_vals;
1273 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1274 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1278 sqlite_freemem(tmp_keys);
1279 sqlite_freemem(tmp_vals);
1281 ast_debug(1, "SQL query: %s\n", tmp_str);
1283 ast_mutex_lock(&mutex);
1286 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1287 RES_SQLITE_END(error)
1290 rows_id = sqlite_last_insert_rowid(db);
1295 ast_mutex_unlock(&mutex);
1297 sqlite_freemem(tmp_str);
1300 ast_log(LOG_WARNING, "%s\n", errormsg);
1307 static int realtime_destroy_handler(const char *database, const char *table,
1308 const char *keyfield, const char *entity,
1311 char *query, *errormsg, *tmp_str;
1312 const char **params, **vals;
1313 size_t params_count;
1314 int error, rows_num;
1318 ast_log(LOG_WARNING, "Table name unspecified\n");
1322 if (!(params_count = get_params(ap, ¶ms, &vals)))
1325 /* \cond DOXYGEN_CAN_PARSE_THIS */
1327 #define QUERY "DELETE FROM '%q' WHERE"
1330 if (!(query = sqlite_mprintf(QUERY, table))) {
1331 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1337 for (i = 0; i < params_count; i++) {
1338 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1339 sqlite_freemem(query);
1342 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1353 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1354 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1357 sqlite_freemem(query);
1360 ast_debug(1, "SQL query: %s\n", query);
1362 ast_mutex_lock(&mutex);
1365 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1366 RES_SQLITE_END(error)
1369 rows_num = sqlite_changes(db);
1373 ast_mutex_unlock(&mutex);
1375 sqlite_freemem(query);
1378 ast_log(LOG_WARNING, "%s\n", errormsg);
1386 static int cli_status(int fd, int argc, char *argv[])
1388 ast_cli(fd, "SQLite database path: %s\n", dbfile);
1389 ast_cli(fd, "config_table: ");
1392 ast_cli(fd, "unspecified, must be present in extconfig.conf\n");
1394 ast_cli(fd, "%s\n", config_table);
1396 ast_cli(fd, "cdr_table: ");
1399 ast_cli(fd, "unspecified, CDR support disabled\n");
1401 ast_cli(fd, "%s\n", cdr_table);
1403 return RESULT_SUCCESS;
1406 static int unload_module(void)
1408 if (cli_status_registered)
1409 ast_cli_unregister(&cli_status_cmd);
1412 ast_cdr_unregister(RES_SQLITE_NAME);
1414 ast_config_engine_deregister(&sqlite_engine);
1424 static int load_module(void)
1431 cli_status_registered = 0;
1433 config_table = NULL;
1436 error = load_config();
1439 return AST_MODULE_LOAD_DECLINE;
1441 if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1442 ast_log(LOG_ERROR, "%s\n", errormsg);
1448 ast_config_engine_register(&sqlite_engine);
1452 error = sqlite_exec_printf(db, "SELECT COUNT(id) FROM %Q;", NULL, NULL,
1453 &errormsg, cdr_table);
1454 RES_SQLITE_END(error)
1460 if (error != SQLITE_ERROR) {
1461 ast_log(LOG_ERROR, "%s\n", errormsg);
1468 error = sqlite_exec_printf(db, sql_create_cdr_table, NULL, NULL,
1469 &errormsg, cdr_table);
1470 RES_SQLITE_END(error)
1473 ast_log(LOG_ERROR, "%s\n", errormsg);
1480 error = ast_cdr_register(RES_SQLITE_NAME, RES_SQLITE_DESCRIPTION,
1491 error = ast_cli_register(&cli_status_cmd);
1498 cli_status_registered = 1;
1503 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1504 .load = load_module,
1505 .unload = unload_module,