Merge another change from team/russell/events ...
[asterisk-bristuff.git] / res / res_config_sqlite.c
bloba2c72d18291f68c689ec54be9767a6bc7f15549c
1 /*
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.
22 /*!
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 :
50 * <dl>
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
58 * disabled)</dd>
59 * </dl>
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
63 * needed tables.
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.
75 /*!
76 * \file
77 * \brief res_config_sqlite module.
80 /*** MODULEINFO
81 <depend>sqlite</depend>
82 ***/
84 #include "asterisk.h"
85 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
87 #include <sqlite.h>
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"
105 enum {
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) \
118 MACRO_BEGIN \
119 int __error; \
121 __error = set_var(&to, #to, from->value); \
123 if (__error) { \
124 ast_config_destroy(config); \
125 unload_config(); \
126 return 1; \
128 MACRO_END
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.
134 * <pre>
135 * char *errormsg;
136 * int error;
138 * RES_CONFIG_SQLITE_BEGIN
139 * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
140 * RES_CONFIG_SQLITE_END(error)
142 * if (error)
143 * ...;
144 * </pre>
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 \
154 MACRO_BEGIN \
155 int __i; \
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) \
166 break; \
167 usleep(1000); \
169 MACRO_END;
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;
179 char *cat_name;
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;
202 char *initfield;
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.
229 * \see load_config()
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.
276 * \retval cfg object
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:
290 * <ul>
291 * <li>params : param1 param2 param3 ...</li>
292 * <li>vals : val1 val2 val3 ...</li>
293 * </ul>
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,
324 char **columnNames);
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,
363 char **columnNames);
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
370 * categories.
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
385 * update).
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
406 * create/store).
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,
420 va_list ap);
423 * \brief Asterisk callback function for RealTime configuration (destroys
424 * variable).
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
447 * \param cmd
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. */
454 static sqlite *db;
456 /*! Set to 1 if CDR support is enabled. */
457 static int use_cdr;
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. */
466 static char *dbfile;
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
496 * command.
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"
509 " id INTEGER,\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"
529 ");";
531 /*! SQL query format to insert a CDR entry. */
532 static char *sql_add_cdr_entry =
533 "INSERT INTO '%q' ("
534 " clid,"
535 " src,"
536 " dst,"
537 " dcontext,"
538 " channel,"
539 " dstchannel,"
540 " lastapp,"
541 " lastdata,"
542 " start,"
543 " answer,"
544 " end,"
545 " duration,"
546 " billsec,"
547 " disposition,"
548 " amaflags,"
549 " accountcode,"
550 " uniqueid,"
551 " userfield"
552 ") VALUES ("
553 " '%q',"
554 " '%q',"
555 " '%q',"
556 " '%q',"
557 " '%q',"
558 " '%q',"
559 " '%q',"
560 " '%q',"
561 " datetime(%d,'unixepoch','localtime'),"
562 " datetime(%d,'unixepoch','localtime'),"
563 " datetime(%d,'unixepoch','localtime'),"
564 " '%ld',"
565 " '%ld',"
566 " '%ld',"
567 " '%ld',"
568 " '%q',"
569 " '%q',"
570 " '%q'"
571 ");";
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 =
580 "SELECT *"
581 " FROM '%q'"
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)
587 if (*var)
588 ast_free(*var);
590 *var = ast_strdup(value);
592 if (!*var) {
593 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
594 return 1;
597 return 0;
600 static int check_vars(void)
602 if (!dbfile) {
603 ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
604 return 1;
607 use_cdr = (cdr_table != NULL);
609 return 0;
612 static int load_config(void)
614 struct ast_config *config;
615 struct ast_variable *var;
616 int error;
617 struct ast_flags config_flags = { 0 };
619 config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
621 if (!config) {
622 ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
623 return 1;
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);
633 else
634 ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
637 ast_config_destroy(config);
638 error = check_vars();
640 if (error) {
641 unload_config();
642 return 1;
645 return 0;
648 static void unload_config(void)
650 ast_free(dbfile);
651 dbfile = NULL;
652 ast_free(config_table);
653 config_table = NULL;
654 ast_free(cdr_table);
655 cdr_table = NULL;
658 static int cdr_handler(struct ast_cdr *cdr)
660 char *query, *errormsg;
661 int error;
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);
671 if (!query) {
672 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
673 return 1;
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);
688 if (error) {
689 ast_log(LOG_ERROR, "%s\n", errormsg);
690 sqlite_freemem(errormsg);
691 return 1;
694 return 0;
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");
704 return 1;
707 args = arg;
709 if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
710 struct ast_config *cfg;
711 char *val;
713 val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
714 cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked);
716 if (!cfg) {
717 ast_log(LOG_WARNING, "Unable to include %s\n", val);
718 return 1;
719 } else {
720 args->cfg = cfg;
721 return 0;
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);
728 if (!args->cat) {
729 ast_log(LOG_WARNING, "Unable to allocate category\n");
730 return 1;
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);
738 return 1;
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], "");
746 if (!var) {
747 ast_log(LOG_WARNING, "Unable to allocate variable");
748 return 1;
751 ast_variable_append(args->cat, var);
753 return 0;
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;
761 int error;
763 if (!config_table) {
764 if (!table) {
765 ast_log(LOG_ERROR, "Table name unspecified\n");
766 return NULL;
768 } else
769 table = config_table;
771 query = sqlite_mprintf(sql_get_config_table, table, file);
773 if (!query) {
774 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
775 return NULL;
778 ast_debug(1, "SQL query: %s\n", query);
779 args.cfg = cfg;
780 args.cat = NULL;
781 args.cat_name = NULL;
782 args.flags = flags;
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);
796 if (error) {
797 ast_log(LOG_ERROR, "%s\n", errormsg);
798 sqlite_freemem(errormsg);
799 return NULL;
802 return cfg;
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;
808 size_t params_count;
810 params = NULL;
811 vals = NULL;
812 params_count = 0;
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 *)))) {
816 ast_free(params);
817 ast_free(vals);
818 return 0;
820 params = tmp;
822 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
823 ast_free(params);
824 ast_free(vals);
825 return 0;
827 vals = tmp;
829 params[params_count] = param;
830 vals[params_count] = val;
831 params_count++;
834 if (params_count > 0) {
835 *params_ptr = params;
836 *vals_ptr = vals;
837 } else
838 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
840 return params_count;
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;
847 int i;
849 args = arg;
851 for (i = 0; i < argc; i++) {
852 if (!argv[i])
853 continue;
855 if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
856 return 1;
858 if (!args->var)
859 args->var = var;
861 if (!args->last)
862 args->last = var;
863 else {
864 args->last->next = var;
865 args->last = var;
869 return 0;
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;
877 size_t params_count;
878 int error;
880 if (!table) {
881 ast_log(LOG_WARNING, "Table name unspecified\n");
882 return NULL;
885 params_count = get_params(ap, &params, &vals);
887 if (params_count == 0)
888 return NULL;
890 op = (strchr(params[0], ' ') == NULL) ? " =" : "";
892 /* \cond DOXYGEN_CAN_PARSE_THIS */
893 #undef QUERY
894 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
895 /* \endcond */
897 query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
899 if (!query) {
900 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
901 ast_free(params);
902 ast_free(vals);
903 return NULL;
906 if (params_count > 1) {
907 size_t i;
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);
914 if (!tmp_str) {
915 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
916 ast_free(params);
917 ast_free(vals);
918 return NULL;
921 query = tmp_str;
925 ast_free(params);
926 ast_free(vals);
928 tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
929 sqlite_freemem(query);
931 if (!tmp_str) {
932 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
933 return NULL;
936 query = tmp_str;
937 ast_debug(1, "SQL query: %s\n", query);
938 args.var = NULL;
939 args.last = NULL;
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);
951 if (error) {
952 ast_log(LOG_WARNING, "%s\n", errormsg);
953 sqlite_freemem(errormsg);
954 ast_variables_destroy(args.var);
955 return NULL;
958 return 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;
966 char *cat_name;
967 size_t i;
969 args = arg;
970 cat_name = NULL;
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
975 * of the SQL query.
977 for (i = 0; i < argc; i++) {
978 if (!strcmp(args->initfield, columnNames[i]))
979 cat_name = argv[i];
982 if (!cat_name) {
983 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
984 return 1;
987 if (!(cat = ast_category_new(cat_name, "", 99999))) {
988 ast_log(LOG_WARNING, "Unable to allocate category\n");
989 return 1;
992 ast_category_append(args->cfg, cat);
994 for (i = 0; i < argc; i++) {
995 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
996 continue;
998 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
999 ast_log(LOG_WARNING, "Unable to allocate variable\n");
1000 return 1;
1003 ast_variable_append(cat, var);
1006 return 0;
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;
1017 int error;
1019 if (!table) {
1020 ast_log(LOG_WARNING, "Table name unspecified\n");
1021 return NULL;
1024 if (!(cfg = ast_config_new())) {
1025 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1026 return NULL;
1029 if (!(params_count = get_params(ap, &params, &vals))) {
1030 ast_config_destroy(cfg);
1031 return NULL;
1034 if (!(initfield = ast_strdup(params[0]))) {
1035 ast_config_destroy(cfg);
1036 ast_free(params);
1037 ast_free(vals);
1038 return NULL;
1041 tmp_str = strchr(initfield, ' ');
1043 if (tmp_str)
1044 *tmp_str = '\0';
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 */
1055 #undef QUERY
1056 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1057 /* \endcond */
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);
1062 ast_free(params);
1063 ast_free(vals);
1064 ast_free(initfield);
1065 return NULL;
1068 if (params_count > 1) {
1069 size_t i;
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);
1076 if (!tmp_str) {
1077 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1078 ast_config_destroy(cfg);
1079 ast_free(params);
1080 ast_free(vals);
1081 ast_free(initfield);
1082 return NULL;
1085 query = tmp_str;
1089 ast_free(params);
1090 ast_free(vals);
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);
1096 return NULL;
1099 sqlite_freemem(query);
1100 query = tmp_str;
1101 ast_debug(1, "SQL query: %s\n", query);
1102 args.cfg = cfg;
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);
1116 if (error) {
1117 ast_log(LOG_WARNING, "%s\n", errormsg);
1118 sqlite_freemem(errormsg);
1119 ast_config_destroy(cfg);
1120 return NULL;
1123 return 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;
1134 if (!table) {
1135 ast_log(LOG_WARNING, "Table name unspecified\n");
1136 return -1;
1139 if (!(params_count = get_params(ap, &params, &vals)))
1140 return -1;
1142 /* \cond DOXYGEN_CAN_PARSE_THIS */
1143 #undef QUERY
1144 #define QUERY "UPDATE '%q' SET %q = '%q'"
1145 /* \endcond */
1147 if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1148 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1149 ast_free(params);
1150 ast_free(vals);
1151 return -1;
1154 if (params_count > 1) {
1155 size_t i;
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);
1161 if (!tmp_str) {
1162 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1163 ast_free(params);
1164 ast_free(vals);
1165 return -1;
1168 query = tmp_str;
1172 ast_free(params);
1173 ast_free(vals);
1175 if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1176 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1177 return -1;
1180 sqlite_freemem(query);
1181 query = tmp_str;
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)
1190 if (!error)
1191 rows_num = sqlite_changes(db);
1192 else
1193 rows_num = -1;
1195 ast_mutex_unlock(&mutex);
1197 sqlite_freemem(query);
1199 if (error) {
1200 ast_log(LOG_WARNING, "%s\n", errormsg);
1201 sqlite_freemem(errormsg);
1204 return rows_num;
1207 static int realtime_store_handler(const char *database, const char *table, va_list ap)
1209 char *errormsg, *tmp_str, *tmp_keys = NULL, *tmp_keys2 = NULL, *tmp_vals = NULL, *tmp_vals2 = NULL;
1210 const char **params, **vals;
1211 size_t params_count;
1212 int error, rows_id;
1213 size_t i;
1215 if (!table) {
1216 ast_log(LOG_WARNING, "Table name unspecified\n");
1217 return -1;
1220 if (!(params_count = get_params(ap, &params, &vals)))
1221 return -1;
1223 /* \cond DOXYGEN_CAN_PARSE_THIS */
1224 #undef QUERY
1225 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1226 /* \endcond */
1228 for (i = 0; i < params_count; i++) {
1229 if ( tmp_keys2 ) {
1230 tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1231 sqlite_freemem(tmp_keys2);
1232 } else {
1233 tmp_keys = sqlite_mprintf("%q", params[i]);
1235 if (!tmp_keys) {
1236 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1237 ast_free(params);
1238 ast_free(vals);
1239 return -1;
1242 if ( tmp_vals2 ) {
1243 tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1244 sqlite_freemem(tmp_vals2);
1245 } else {
1246 tmp_vals = sqlite_mprintf("'%q'", params[i]);
1248 if (!tmp_vals) {
1249 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1250 ast_free(params);
1251 ast_free(vals);
1252 return -1;
1256 tmp_keys2 = tmp_keys;
1257 tmp_vals2 = tmp_vals;
1260 ast_free(params);
1261 ast_free(vals);
1263 if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1264 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1265 return -1;
1268 sqlite_freemem(tmp_keys);
1269 sqlite_freemem(tmp_vals);
1271 ast_debug(1, "SQL query: %s\n", tmp_str);
1273 ast_mutex_lock(&mutex);
1275 RES_CONFIG_SQLITE_BEGIN
1276 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1277 RES_CONFIG_SQLITE_END(error)
1279 if (!error) {
1280 rows_id = sqlite_last_insert_rowid(db);
1281 } else {
1282 rows_id = -1;
1285 ast_mutex_unlock(&mutex);
1287 sqlite_freemem(tmp_str);
1289 if (error) {
1290 ast_log(LOG_WARNING, "%s\n", errormsg);
1291 sqlite_freemem(errormsg);
1294 return rows_id;
1297 static int realtime_destroy_handler(const char *database, const char *table,
1298 const char *keyfield, const char *entity, va_list ap)
1300 char *query, *errormsg, *tmp_str;
1301 const char **params, **vals;
1302 size_t params_count;
1303 int error, rows_num;
1304 size_t i;
1306 if (!table) {
1307 ast_log(LOG_WARNING, "Table name unspecified\n");
1308 return -1;
1311 if (!(params_count = get_params(ap, &params, &vals)))
1312 return -1;
1314 /* \cond DOXYGEN_CAN_PARSE_THIS */
1315 #undef QUERY
1316 #define QUERY "DELETE FROM '%q' WHERE"
1317 /* \endcond */
1319 if (!(query = sqlite_mprintf(QUERY, table))) {
1320 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1321 ast_free(params);
1322 ast_free(vals);
1323 return -1;
1326 for (i = 0; i < params_count; i++) {
1327 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1328 sqlite_freemem(query);
1330 if (!tmp_str) {
1331 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1332 ast_free(params);
1333 ast_free(vals);
1334 return -1;
1337 query = tmp_str;
1340 ast_free(params);
1341 ast_free(vals);
1342 if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1343 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1344 return -1;
1346 sqlite_freemem(query);
1347 query = tmp_str;
1348 ast_debug(1, "SQL query: %s\n", query);
1350 ast_mutex_lock(&mutex);
1352 RES_CONFIG_SQLITE_BEGIN
1353 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1354 RES_CONFIG_SQLITE_END(error)
1356 if (!error)
1357 rows_num = sqlite_changes(db);
1358 else
1359 rows_num = -1;
1361 ast_mutex_unlock(&mutex);
1363 sqlite_freemem(query);
1365 if (error) {
1366 ast_log(LOG_WARNING, "%s\n", errormsg);
1367 sqlite_freemem(errormsg);
1370 return rows_num;
1373 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1375 switch (cmd) {
1376 case CLI_INIT:
1377 e->command = "show sqlite status";
1378 e->usage =
1379 "Usage: show sqlite status\n"
1380 " Show status information about the SQLite 2 driver\n";
1381 return NULL;
1382 case CLI_GENERATE:
1383 return NULL;
1386 if (a->argc != 3)
1387 return CLI_SHOWUSAGE;
1389 ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
1390 ast_cli(a->fd, "config_table: ");
1392 if (!config_table)
1393 ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
1394 else
1395 ast_cli(a->fd, "%s\n", config_table);
1397 ast_cli(a->fd, "cdr_table: ");
1399 if (!cdr_table)
1400 ast_cli(a->fd, "unspecified, CDR support disabled\n");
1401 else
1402 ast_cli(a->fd, "%s\n", cdr_table);
1404 return CLI_SUCCESS;
1407 static int unload_module(void)
1409 if (cli_status_registered)
1410 ast_cli_unregister_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1412 if (cdr_registered)
1413 ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
1415 ast_config_engine_deregister(&sqlite_engine);
1417 if (db)
1418 sqlite_close(db);
1420 unload_config();
1422 return 0;
1425 static int load_module(void)
1427 char *errormsg;
1428 int error;
1430 db = NULL;
1431 cdr_registered = 0;
1432 cli_status_registered = 0;
1433 dbfile = NULL;
1434 config_table = NULL;
1435 cdr_table = NULL;
1436 error = load_config();
1438 if (error)
1439 return AST_MODULE_LOAD_DECLINE;
1441 if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1442 ast_log(LOG_ERROR, "%s\n", errormsg);
1443 sqlite_freemem(errormsg);
1444 unload_module();
1445 return 1;
1448 ast_config_engine_register(&sqlite_engine);
1450 if (use_cdr) {
1451 char *query;
1453 /* \cond DOXYGEN_CAN_PARSE_THIS */
1454 #undef QUERY
1455 #define QUERY "SELECT COUNT(id) FROM %Q;"
1456 /* \endcond */
1458 query = sqlite_mprintf(QUERY, cdr_table);
1460 if (!query) {
1461 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1462 unload_module();
1463 return 1;
1466 ast_debug(1, "SQL query: %s\n", query);
1468 RES_CONFIG_SQLITE_BEGIN
1469 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1470 RES_CONFIG_SQLITE_END(error)
1472 sqlite_freemem(query);
1474 if (error) {
1476 * Unexpected error.
1478 if (error != SQLITE_ERROR) {
1479 ast_log(LOG_ERROR, "%s\n", errormsg);
1480 sqlite_freemem(errormsg);
1481 unload_module();
1482 return 1;
1485 sqlite_freemem(errormsg);
1486 query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
1488 if (!query) {
1489 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1490 unload_module();
1491 return 1;
1494 ast_debug(1, "SQL query: %s\n", query);
1496 RES_CONFIG_SQLITE_BEGIN
1497 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1498 RES_CONFIG_SQLITE_END(error)
1500 sqlite_freemem(query);
1502 if (error) {
1503 ast_log(LOG_ERROR, "%s\n", errormsg);
1504 sqlite_freemem(errormsg);
1505 unload_module();
1506 return 1;
1510 error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
1512 if (error) {
1513 unload_module();
1514 return 1;
1517 cdr_registered = 1;
1520 error = ast_cli_register_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1522 if (error) {
1523 unload_module();
1524 return 1;
1527 cli_status_registered = 1;
1529 return 0;
1532 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1533 .load = load_module,
1534 .unload = unload_module,