Don't include logger.h in asterisk.h by default as it is causing problems building
[asterisk/asterisk.git] / res / res_config_sqlite.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2006, Proformatique
5  *
6  * Written by Richard Braun <rbraun@proformatique.com>
7  *
8  * Based on res_sqlite3 by Anthony Minessale II,
9  * and res_config_mysql by Matthew Boehm
10  *
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.
16  *
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.
20  */
21
22 /*!
23  * \page res_config_sqlite
24  *
25  * \section intro_sec Presentation
26  *
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).  It can also be used to log CDR entries. 
31  * Note that Asterisk already comes with a module named cdr_sqlite.
32  * There are two reasons for including it in res_config_sqlite:
33  * the first is that rewriting it was a training to learn how to write a
34  * simple module for Asterisk, the other is to have the same database open for
35  * all kinds of operations, which improves reliability and performance.
36  *
37  * \section conf_sec Configuration
38  *
39  * The main configuration file is res_config_sqlite.conf. It must be readable or
40  * res_config_sqlite will fail to start. It is suggested to use the sample file
41  * in this package as a starting point. The file has only one section
42  * named <code>general</code>. Here are the supported parameters :
43  *
44  * <dl>
45  *      <dt><code>dbfile</code></dt>
46  *      <dd>The absolute path to the SQLite database (the file can be non existent,
47  *                      res_config_sqlite will create it if it has the appropriate rights)</dd>
48  *      <dt><code>config_table</code></dt>
49  *      <dd>The table used for static configuration</dd>
50  *      <dt><code>cdr_table</code></dt>
51  *      <dd>The table used to store CDR entries (if ommitted, CDR support is
52  *                      disabled)</dd>
53  * </dl>
54  *
55  * To use res_config_sqlite for static and/or RealTime configuration, refer to the
56  * Asterisk documentation. The file tables.sql can be used to create the
57  * needed tables.
58  *
59  * \section status_sec Driver status
60  *
61  * The CLI command <code>show sqlite status</code> returns status information
62  * about the running driver.
63  *
64  * \section credits_sec Credits
65  *
66  * res_config_sqlite was developed by Richard Braun at the Proformatique company.
67  */
68
69 /*!
70  * \file
71  * \brief res_config_sqlite module.
72  */
73
74 /*** MODULEINFO
75         <depend>sqlite</depend>
76  ***/
77
78 #include "asterisk.h"
79 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
80
81 #include <sqlite.h>
82
83 #include "asterisk/logger.h"
84 #include "asterisk/app.h"
85 #include "asterisk/pbx.h"
86 #include "asterisk/cdr.h"
87 #include "asterisk/cli.h"
88 #include "asterisk/lock.h"
89 #include "asterisk/config.h"
90 #include "asterisk/module.h"
91 #include "asterisk/linkedlists.h"
92
93 #define MACRO_BEGIN     do {
94 #define MACRO_END       } while (0)
95
96 #define RES_CONFIG_SQLITE_NAME "res_config_sqlite"
97 #define RES_CONFIG_SQLITE_DRIVER "sqlite"
98 #define RES_CONFIG_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
99 #define RES_CONFIG_SQLITE_CONF_FILE "res_config_sqlite.conf"
100
101 enum {
102         RES_CONFIG_SQLITE_CONFIG_ID,
103         RES_CONFIG_SQLITE_CONFIG_CAT_METRIC,
104         RES_CONFIG_SQLITE_CONFIG_VAR_METRIC,
105         RES_CONFIG_SQLITE_CONFIG_COMMENTED,
106         RES_CONFIG_SQLITE_CONFIG_FILENAME,
107         RES_CONFIG_SQLITE_CONFIG_CATEGORY,
108         RES_CONFIG_SQLITE_CONFIG_VAR_NAME,
109         RES_CONFIG_SQLITE_CONFIG_VAR_VAL,
110         RES_CONFIG_SQLITE_CONFIG_COLUMNS,
111 };
112
113 #define SET_VAR(config, to, from)                       \
114 MACRO_BEGIN                                             \
115         int __error;                                    \
116                                                         \
117         __error = set_var(&to, #to, from->value);       \
118                                                         \
119         if (__error) {                                  \
120                 ast_config_destroy(config);             \
121                 unload_config();                        \
122                 return 1;                               \
123         }                                               \
124 MACRO_END
125
126 /*!
127  * Maximum number of loops before giving up executing a query. Calls to
128  * sqlite_xxx() functions which can return SQLITE_BUSY
129  * are enclosed by RES_CONFIG_SQLITE_BEGIN and RES_CONFIG_SQLITE_END, e.g.
130  * <pre>
131  * char *errormsg;
132  * int error;
133  *
134  * RES_CONFIG_SQLITE_BEGIN
135  *       error = sqlite_exec(db, query, NULL, NULL, &errormsg);
136  * RES_CONFIG_SQLITE_END(error)
137  *
138  * if (error)
139  *       ...;
140  * </pre>
141  */
142 #define RES_CONFIG_SQLITE_MAX_LOOPS 10
143
144 /*!
145  * Macro used before executing a query.
146  *
147  * \see RES_CONFIG_SQLITE_MAX_LOOPS.
148  */
149 #define RES_CONFIG_SQLITE_BEGIN                                         \
150 MACRO_BEGIN                                                             \
151         int __i;                                                        \
152                                                                         \
153         for (__i = 0; __i < RES_CONFIG_SQLITE_MAX_LOOPS; __i++) {
154
155 /*!
156  * Macro used after executing a query.
157  *
158  * \see RES_CONFIG_SQLITE_MAX_LOOPS.
159  */
160 #define RES_CONFIG_SQLITE_END(error)                                    \
161                 if (error != SQLITE_BUSY)       \
162                         break;                                          \
163                 usleep(1000);                                           \
164         }                                                               \
165 MACRO_END;
166
167 /*!
168  * Structure sent to the SQLite callback function for static configuration.
169  *
170  * \see add_cfg_entry()
171  */
172 struct cfg_entry_args {
173         struct ast_config *cfg;
174         struct ast_category *cat;
175         char *cat_name;
176         struct ast_flags flags;
177         const char *who_asked;
178 };
179
180 /*!
181  * Structure sent to the SQLite callback function for RealTime configuration.
182  *
183  * \see add_rt_cfg_entry()
184  */
185 struct rt_cfg_entry_args {
186         struct ast_variable *var;
187         struct ast_variable *last;
188 };
189
190 /*!
191  * Structure sent to the SQLite callback function for RealTime configuration
192  * (realtime_multi_handler()).
193  *
194  * \see add_rt_multi_cfg_entry()
195  */
196 struct rt_multi_cfg_entry_args {
197         struct ast_config *cfg;
198         char *initfield;
199 };
200
201 /*!
202  * \brief Allocate a variable.
203  * \param var the address of the variable to set (it will be allocated)
204  * \param name the name of the variable (for error handling)
205  * \param value the value to store in var
206  * \retval 0 on success
207  * \retval 1 if an allocation error occurred
208  */
209 static int set_var(char **var, const char *name, const char *value);
210
211 /*!
212  * \brief Load the configuration file.
213  * \see unload_config()
214  *
215  * This function sets dbfile, config_table, and cdr_table. It calls
216  * check_vars() before returning, and unload_config() if an error occurred.
217  *
218  * \retval 0 on success
219  * \retval 1 if an error occurred
220  */
221 static int load_config(void);
222
223 /*!
224  * \brief Free resources related to configuration.
225  * \see load_config()
226  */
227 static void unload_config(void);
228
229 /*!
230  * \brief Asterisk callback function for CDR support.
231  * \param cdr the CDR entry Asterisk sends us.
232  *
233  * Asterisk will call this function each time a CDR entry must be logged if
234  * CDR support is enabled.
235  *
236  * \retval 0 on success
237  * \retval 1 if an error occurred
238  */
239 static int cdr_handler(struct ast_cdr *cdr);
240
241 /*!
242  * \brief SQLite callback function for static configuration.
243  *
244  * This function is passed to the SQLite engine as a callback function to
245  * parse a row and store it in a struct ast_config object. It relies on
246  * resulting rows being sorted by category.
247  *
248  * \param arg a pointer to a struct cfg_entry_args object
249  * \param argc number of columns
250  * \param argv values in the row
251  * \param columnNames names and types of the columns
252  * \retval 0 on success
253  * \retval 1 if an error occurred
254  * \see cfg_entry_args
255  * \see sql_get_config_table
256  * \see config_handler()
257  */
258 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
259
260 /*!
261  * \brief Asterisk callback function for static configuration.
262  *
263  * Asterisk will call this function when it loads its static configuration,
264  * which usually happens at startup and reload.
265  *
266  * \param database the database to use (ignored)
267  * \param table the table to use
268  * \param file the file to load from the database
269  * \param cfg the struct ast_config object to use when storing variables
270  * \param flags Optional flags.  Not used.
271  * \param suggested_incl suggest include.
272  * \retval cfg object
273  * \retval NULL if an error occurred
274  * \see add_cfg_entry()
275  */
276 static struct ast_config * config_handler(const char *database, const char *table, const char *file,
277         struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked);
278
279 /*!
280  * \brief Helper function to parse a va_list object into 2 dynamic arrays of
281  * strings, parameters and values.
282  *
283  * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
284  * arguments will be extracted to create 2 arrays:
285  *
286  * <ul>
287  *      <li>params : param1 param2 param3 ...</li>
288  *      <li>vals : val1 val2 val3 ...</li>
289  * </ul>
290  *
291  * The address of these arrays are stored in params_ptr and vals_ptr. It
292  * is the responsibility of the caller to release the memory of these arrays.
293  * It is considered an error that va_list has a null or odd number of strings.
294  *
295  * \param ap the va_list object to parse
296  * \param params_ptr where the address of the params array is stored
297  * \param vals_ptr where the address of the vals array is stored
298  * \retval the number of elements in the arrays (which have the same size).
299  * \retval 0 if an error occurred.
300  */
301 static size_t get_params(va_list ap, const char ***params_ptr,
302         const char ***vals_ptr);
303
304 /*!
305  * \brief SQLite callback function for RealTime configuration.
306  *
307  * This function is passed to the SQLite engine as a callback function to
308  * parse a row and store it in a linked list of struct ast_variable objects.
309  *
310  * \param arg a pointer to a struct rt_cfg_entry_args object
311  * \param argc number of columns
312  * \param argv values in the row
313  * \param columnNames names and types of the columns
314  * \retval 0 on success.
315  * \retval 1 if an error occurred.
316  * \see rt_cfg_entry_args
317  * \see realtime_handler()
318  */
319 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
320         char **columnNames);
321
322 /*!
323  * \brief Asterisk callback function for RealTime configuration.
324  *
325  * Asterisk will call this function each time it requires a variable
326  * through the RealTime architecture. ap is a list of parameters and
327  * values used to find a specific row, e.g one parameter "name" and
328  * one value "123" so that the SQL query becomes <code>SELECT * FROM
329  * table WHERE name = '123';</code>.
330  *
331  * \param database the database to use (ignored)
332  * \param table the table to use
333  * \param ap list of parameters and values to match
334  *
335  * \retval a linked list of struct ast_variable objects
336  * \retval NULL if an error occurred
337  * \see add_rt_cfg_entry()
338  */
339 static struct ast_variable * realtime_handler(const char *database,
340         const char *table, va_list ap);
341
342 /*!
343  * \brief SQLite callback function for RealTime configuration.
344  *
345  * This function performs the same actions as add_rt_cfg_entry() except
346  * that the rt_multi_cfg_entry_args structure is designed to store
347  * categories in addition to variables.
348  *
349  * \param arg a pointer to a struct rt_multi_cfg_entry_args object
350  * \param argc number of columns
351  * \param argv values in the row
352  * \param columnNames names and types of the columns
353  * \retval 0 on success.
354  * \retval 1 if an error occurred.
355  * \see rt_multi_cfg_entry_args
356  * \see realtime_multi_handler()
357  */
358 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
359         char **columnNames);
360
361 /*!
362  * \brief Asterisk callback function for RealTime configuration.
363  *
364  * This function performs the same actions as realtime_handler() except
365  * that it can store variables per category, and can return several
366  * categories.
367  *
368  * \param database the database to use (ignored)
369  * \param table the table to use
370  * \param ap list of parameters and values to match
371  * \retval a struct ast_config object storing categories and variables.
372  * \retval NULL if an error occurred.
373  *
374  * \see add_rt_multi_cfg_entry()
375  */
376 static struct ast_config * realtime_multi_handler(const char *database,
377         const char *table, va_list ap);
378
379 /*!
380  * \brief Asterisk callback function for RealTime configuration (variable
381  * update).
382  *
383  * Asterisk will call this function each time a variable has been modified
384  * internally and must be updated in the backend engine. keyfield and entity
385  * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
386  * keyfield = 'entity';</code>. ap is a list of parameters and values with the
387  * same format as the other realtime functions.
388  *
389  * \param database the database to use (ignored)
390  * \param table the table to use
391  * \param keyfield the column of the matching cell
392  * \param entity the value of the matching cell
393  * \param ap list of parameters and new values to update in the database
394  * \retval the number of affected rows.
395  * \retval -1 if an error occurred.
396  */
397 static int realtime_update_handler(const char *database, const char *table,
398         const char *keyfield, const char *entity, va_list ap);
399
400 /*!
401  * \brief Asterisk callback function for RealTime configuration (variable
402  * create/store).
403  *
404  * Asterisk will call this function each time a variable has been created
405  * internally and must be stored in the backend engine.
406  * are used to find the row to update, e.g. ap is a list of parameters and
407  * values with the same format as the other realtime functions.
408  *
409  * \param database the database to use (ignored)
410  * \param table the table to use
411  * \param ap list of parameters and new values to insert into the database
412  * \retval the rowid of inserted row.
413  * \retval -1 if an error occurred.
414  */
415 static int realtime_store_handler(const char *database, const char *table,
416         va_list ap);
417
418 /*!
419  * \brief Asterisk callback function for RealTime configuration (destroys
420  * variable).
421  *
422  * Asterisk will call this function each time a variable has been destroyed
423  * internally and must be removed from the backend engine. keyfield and entity
424  * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
425  * keyfield = 'entity';</code>. ap is a list of parameters and values with the
426  * same format as the other realtime functions.
427  *
428  * \param database the database to use (ignored)
429  * \param table the table to use
430  * \param keyfield the column of the matching cell
431  * \param entity the value of the matching cell
432  * \param ap list of additional parameters for cell matching
433  * \retval the number of affected rows.
434  * \retval -1 if an error occurred.
435  */
436 static int realtime_destroy_handler(const char *database, const char *table,
437         const char *keyfield, const char *entity, va_list ap);
438
439 /*!
440  * \brief Asterisk callback function for the CLI status command.
441  *
442  * \param e CLI command
443  * \param cmd 
444  * \param a CLI argument list
445  * \return RESULT_SUCCESS
446  */
447 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
448 static char *handle_cli_sqlite_show_tables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
449
450 static int realtime_require_handler(const char *database, const char *table, va_list ap);
451 static int realtime_unload_handler(const char *unused, const char *tablename);
452
453 /*! The SQLite database object. */
454 static sqlite *db;
455
456 /*! Set to 1 if CDR support is enabled. */
457 static int use_cdr;
458
459 /*! Set to 1 if the CDR callback function was registered. */
460 static int cdr_registered;
461
462 /*! Set to 1 if the CLI status command callback function was registered. */
463 static int cli_status_registered;
464
465 /*! The path of the database file. */
466 static char *dbfile;
467
468 /*! The name of the static configuration table. */
469 static char *config_table;
470
471 /*! The name of the table used to store CDR entries. */
472 static char *cdr_table;
473
474 /*!
475  * The structure specifying all callback functions used by Asterisk for static
476  * and RealTime configuration.
477  */
478 static struct ast_config_engine sqlite_engine =
479 {
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,
487         .require_func = realtime_require_handler,
488         .unload_func = realtime_unload_handler,
489 };
490
491 /*!
492  * The mutex used to prevent simultaneous access to the SQLite database.
493  */
494 AST_MUTEX_DEFINE_STATIC(mutex);
495
496 /*!
497  * Structure containing details and callback functions for the CLI status
498  * command.
499  */
500 static struct ast_cli_entry cli_status[] = {
501         AST_CLI_DEFINE(handle_cli_show_sqlite_status, "Show status information about the SQLite 2 driver"),
502         AST_CLI_DEFINE(handle_cli_sqlite_show_tables, "Cached table information about the SQLite 2 driver"),
503 };
504
505 struct sqlite_cache_columns {
506         char *name;
507         char *type;
508         unsigned char isint;    /*!< By definition, only INTEGER PRIMARY KEY is an integer; everything else is a string. */
509         AST_RWLIST_ENTRY(sqlite_cache_columns) list;
510 };
511
512 struct sqlite_cache_tables {
513         char *name;
514         AST_RWLIST_HEAD(_columns, sqlite_cache_columns) columns;
515         AST_RWLIST_ENTRY(sqlite_cache_tables) list;
516 };
517
518 static AST_RWLIST_HEAD_STATIC(sqlite_tables, sqlite_cache_tables);
519
520 /*
521  * Taken from Asterisk 1.2 cdr_sqlite.so.
522  */
523
524 /*! SQL query format to create the CDR table if non existent. */
525 static char *sql_create_cdr_table =
526 "CREATE TABLE '%q' (\n"
527 "       id              INTEGER,\n"
528 "       clid            VARCHAR(80)     NOT NULL        DEFAULT '',\n"
529 "       src             VARCHAR(80)     NOT NULL        DEFAULT '',\n"
530 "       dst             VARCHAR(80)     NOT NULL        DEFAULT '',\n"
531 "       dcontext        VARCHAR(80)     NOT NULL        DEFAULT '',\n"
532 "       channel         VARCHAR(80)     NOT NULL        DEFAULT '',\n"
533 "       dstchannel      VARCHAR(80)     NOT NULL        DEFAULT '',\n"
534 "       lastapp         VARCHAR(80)     NOT NULL        DEFAULT '',\n"
535 "       lastdata        VARCHAR(80)     NOT NULL        DEFAULT '',\n"
536 "       start           DATETIME        NOT NULL        DEFAULT '0000-00-00 00:00:00',\n"
537 "       answer          DATETIME        NOT NULL        DEFAULT '0000-00-00 00:00:00',\n"
538 "       end             DATETIME        NOT NULL        DEFAULT '0000-00-00 00:00:00',\n"
539 "       duration        INT(11)         NOT NULL        DEFAULT 0,\n"
540 "       billsec         INT(11)         NOT NULL        DEFAULT 0,\n"
541 "       disposition     VARCHAR(45)     NOT NULL        DEFAULT '',\n"
542 "       amaflags        INT(11)         NOT NULL        DEFAULT 0,\n"
543 "       accountcode     VARCHAR(20)     NOT NULL        DEFAULT '',\n"
544 "       uniqueid        VARCHAR(32)     NOT NULL        DEFAULT '',\n"
545 "       userfield       VARCHAR(255)    NOT NULL        DEFAULT '',\n"
546 "       PRIMARY KEY     (id)\n"
547 ");";
548
549 /*!
550  * SQL query format to describe the table structure
551  */
552 static char *sql_table_structure =
553 "SELECT sql FROM sqlite_master WHERE type='table' AND tbl_name='%s'";
554
555 /*!
556  * SQL query format to fetch the static configuration of a file.
557  * Rows must be sorted by category.
558  *
559  * \see add_cfg_entry()
560  */
561 static const char *sql_get_config_table =
562 "SELECT *"
563 "       FROM '%q'"
564 "       WHERE filename = '%q' AND commented = 0"
565 "       ORDER BY cat_metric ASC, var_metric ASC;";
566
567 static void free_table(struct sqlite_cache_tables *tblptr)
568 {
569         struct sqlite_cache_columns *col;
570
571         /* Obtain a write lock to ensure there are no read locks outstanding */
572         AST_RWLIST_WRLOCK(&(tblptr->columns));
573         while ((col = AST_RWLIST_REMOVE_HEAD(&(tblptr->columns), list))) {
574                 ast_free(col);
575         }
576         AST_RWLIST_UNLOCK(&(tblptr->columns));
577         AST_RWLIST_HEAD_DESTROY(&(tblptr->columns));
578         ast_free(tblptr);
579 }
580
581 static int find_table_cb(void *vtblptr, int argc, char **argv, char **columnNames)
582 {
583         struct sqlite_cache_tables *tblptr = vtblptr;
584         char *sql = ast_strdupa(argv[0]), *start, *end, *type, *remainder;
585         int i;
586         AST_DECLARE_APP_ARGS(fie,
587                 AST_APP_ARG(ld)[100]; /* This means we support up to 100 columns per table */
588         );
589         struct sqlite_cache_columns *col;
590
591         /* This is really fun.  We get to parse an SQL statement to figure out
592          * what columns are in the table.
593          */
594         if ((start = strchr(sql, '(')) && (end = strrchr(sql, ')'))) {
595                 start++;
596                 *end = '\0';
597         } else {
598                 /* Abort */
599                 return -1;
600         }
601
602         AST_STANDARD_APP_ARGS(fie, start);
603         for (i = 0; i < fie.argc; i++) {
604                 fie.ld[i] = ast_skip_blanks(fie.ld[i]);
605                 ast_debug(5, "Found field: %s\n", fie.ld[i]);
606                 if (strncasecmp(fie.ld[i], "PRIMARY KEY", 11) == 0 && (start = strchr(fie.ld[i], '(')) && (end = strchr(fie.ld[i], ')'))) {
607                         *end = '\0';
608                         AST_RWLIST_TRAVERSE(&(tblptr->columns), col, list) {
609                                 if (strcasecmp(start + 1, col->name) == 0 && strcasestr(col->type, "INTEGER")) {
610                                         col->isint = 1;
611                                 }
612                         }
613                         continue;
614                 }
615                 /* type delimiter could be any space character */
616                 for (type = fie.ld[i]; *type > 32; type++);
617                 *type++ = '\0';
618                 type = ast_skip_blanks(type);
619                 for (remainder = type; *remainder > 32; remainder++);
620                 *remainder = '\0';
621                 if (!(col = ast_calloc(1, sizeof(*col) + strlen(fie.ld[i]) + strlen(type) + 2))) {
622                         return -1;
623                 }
624                 col->name = (char *)col + sizeof(*col);
625                 col->type = (char *)col + sizeof(*col) + strlen(fie.ld[i]) + 1;
626                 strcpy(col->name, fie.ld[i]); /* SAFE */
627                 strcpy(col->type, type); /* SAFE */
628                 if (strcasestr(col->type, "INTEGER") && strcasestr(col->type, "PRIMARY KEY")) {
629                         col->isint = 1;
630                 }
631                 AST_LIST_INSERT_TAIL(&(tblptr->columns), col, list);
632         }
633         return 0;
634 }
635
636 static struct sqlite_cache_tables *find_table(const char *tablename)
637 {
638         struct sqlite_cache_tables *tblptr;
639         int i, err;
640         char *sql, *errstr = NULL;
641
642         AST_RWLIST_RDLOCK(&sqlite_tables);
643
644         for (i = 0; i < 2; i++) {
645                 AST_RWLIST_TRAVERSE(&sqlite_tables, tblptr, list) {
646                         if (strcmp(tblptr->name, tablename) == 0) {
647                                 break;
648                         }
649                 }
650                 if (tblptr) {
651                         AST_RWLIST_RDLOCK(&(tblptr->columns));
652                         AST_RWLIST_UNLOCK(&sqlite_tables);
653                         return tblptr;
654                 }
655
656                 if (i == 0) {
657                         AST_RWLIST_UNLOCK(&sqlite_tables);
658                         AST_RWLIST_WRLOCK(&sqlite_tables);
659                 }
660         }
661
662         /* Table structure not cached; build the structure now */
663         asprintf(&sql, sql_table_structure, tablename);
664         if (!(tblptr = ast_calloc(1, sizeof(*tblptr) + strlen(tablename) + 1))) {
665                 AST_RWLIST_UNLOCK(&sqlite_tables);
666                 ast_log(LOG_ERROR, "Memory error.  Cannot cache table '%s'\n", tablename);
667                 return NULL;
668         }
669         tblptr->name = (char *)tblptr + sizeof(*tblptr);
670         strcpy(tblptr->name, tablename); /* SAFE */
671         AST_RWLIST_HEAD_INIT(&(tblptr->columns));
672
673         ast_debug(1, "About to query table structure: %s\n", sql);
674
675         ast_mutex_lock(&mutex);
676         if ((err = sqlite_exec(db, sql, find_table_cb, tblptr, &errstr))) {
677                 ast_mutex_unlock(&mutex);
678                 ast_log(LOG_WARNING, "SQLite error %d: %s\n", err, errstr);
679                 ast_free(errstr);
680                 free_table(tblptr);
681                 return NULL;
682         }
683         ast_mutex_unlock(&mutex);
684
685         if (AST_LIST_EMPTY(&(tblptr->columns))) {
686                 free_table(tblptr);
687                 return NULL;
688         }
689
690         AST_RWLIST_INSERT_TAIL(&sqlite_tables, tblptr, list);
691         AST_RWLIST_RDLOCK(&(tblptr->columns));
692         AST_RWLIST_UNLOCK(&sqlite_tables);
693         return tblptr;
694 }
695
696 #define release_table(a)        AST_RWLIST_UNLOCK(&((a)->columns))
697
698 static int set_var(char **var, const char *name, const char *value)
699 {
700         if (*var)
701                 ast_free(*var);
702
703         *var = ast_strdup(value);
704
705         if (!*var) {
706                 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
707                 return 1;
708         }
709
710         return 0;
711 }
712
713 static int check_vars(void)
714 {
715         if (!dbfile) {
716                 ast_log(LOG_ERROR, "Required parameter undefined: dbfile\n");
717                 return 1;
718         }
719
720         use_cdr = (cdr_table != NULL);
721
722         return 0;
723 }
724
725 static int load_config(void)
726 {
727         struct ast_config *config;
728         struct ast_variable *var;
729         int error;
730         struct ast_flags config_flags = { 0 };
731
732         config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
733
734         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
735                 ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
736                 return 1;
737         }
738
739         for (var = ast_variable_browse(config, "general"); var; var = var->next) {
740                 if (!strcasecmp(var->name, "dbfile"))
741                         SET_VAR(config, dbfile, var);
742                 else if (!strcasecmp(var->name, "config_table"))
743                         SET_VAR(config, config_table, var);
744                 else if (!strcasecmp(var->name, "cdr_table")) {
745                         SET_VAR(config, cdr_table, var);
746                 } else
747                         ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
748         }
749
750         ast_config_destroy(config);
751         error = check_vars();
752
753         if (error) {
754                 unload_config();
755                 return 1;
756         }
757
758         return 0;
759 }
760
761 static void unload_config(void)
762 {
763         struct sqlite_cache_tables *tbl;
764         ast_free(dbfile);
765         dbfile = NULL;
766         ast_free(config_table);
767         config_table = NULL;
768         ast_free(cdr_table);
769         cdr_table = NULL;
770         AST_RWLIST_WRLOCK(&sqlite_tables);
771         while ((tbl = AST_RWLIST_REMOVE_HEAD(&sqlite_tables, list))) {
772                 free_table(tbl);
773         }
774         AST_RWLIST_UNLOCK(&sqlite_tables);
775 }
776
777 static int cdr_handler(struct ast_cdr *cdr)
778 {
779         char *errormsg = NULL, *tmp, workspace[500];
780         int error, scannum;
781         struct sqlite_cache_tables *tbl = find_table(cdr_table);
782         struct sqlite_cache_columns *col;
783         struct ast_str *sql1 = ast_str_create(160), *sql2 = ast_str_create(16);
784
785         if (!tbl) {
786                 ast_log(LOG_WARNING, "No such table: %s\n", cdr_table);
787                 return -1;
788         }
789
790         ast_str_set(&sql1, 0, "INSERT INTO %s (", cdr_table);
791         ast_str_set(&sql2, 0, ") VALUES (");
792
793         AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
794                 if (col->isint) {
795                         ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 1);
796                         if (!tmp) {
797                                 continue;
798                         }
799                         if (sscanf(tmp, "%d", &scannum) == 1) {
800                                 ast_str_append(&sql1, 0, "%s,", col->name);
801                                 ast_str_append(&sql2, 0, "%d,", scannum);
802                         }
803                 } else {
804                         ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 0);
805                         if (!tmp) {
806                                 continue;
807                         }
808                         ast_str_append(&sql1, 0, "%s,", col->name);
809                         tmp = sqlite_mprintf("%Q", tmp);
810                         ast_str_append(&sql2, 0, "%s,", tmp);
811                         sqlite_freemem(tmp);
812                 }
813         }
814         release_table(tbl);
815
816         sql1->str[--sql1->used] = '\0';
817         sql2->str[--sql2->used] = '\0';
818         ast_str_append(&sql1, 0, "%s)", sql2->str);
819         ast_free(sql2);
820
821         ast_debug(1, "SQL query: %s\n", sql1->str);
822
823         ast_mutex_lock(&mutex);
824
825         RES_CONFIG_SQLITE_BEGIN
826                 error = sqlite_exec(db, sql1->str, NULL, NULL, &errormsg);
827         RES_CONFIG_SQLITE_END(error)
828
829         ast_mutex_unlock(&mutex);
830
831         ast_free(sql1);
832
833         if (error) {
834                 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
835                 sqlite_freemem(errormsg);
836                 return 1;
837         }
838         sqlite_freemem(errormsg);
839
840         return 0;
841 }
842
843 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
844 {
845         struct cfg_entry_args *args;
846         struct ast_variable *var;
847
848         if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
849                 ast_log(LOG_WARNING, "Corrupt table\n");
850                 return 1;
851         }
852
853         args = arg;
854
855         if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
856                 struct ast_config *cfg;
857                 char *val;
858
859                 val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
860                 cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked);
861
862                 if (!cfg) {
863                         ast_log(LOG_WARNING, "Unable to include %s\n", val);
864                         return 1;
865                 } else {
866                         args->cfg = cfg;
867                         return 0;
868                 }
869         }
870
871         if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
872                 args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
873
874                 if (!args->cat) {
875                         ast_log(LOG_WARNING, "Unable to allocate category\n");
876                         return 1;
877                 }
878
879                 ast_free(args->cat_name);
880                 args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
881
882                 if (!args->cat_name) {
883                         ast_category_destroy(args->cat);
884                         return 1;
885                 }
886
887                 ast_category_append(args->cfg, args->cat);
888         }
889
890         var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
891
892         if (!var) {
893                 ast_log(LOG_WARNING, "Unable to allocate variable");
894                 return 1;
895         }
896
897         ast_variable_append(args->cat, var);
898
899         return 0;
900 }
901
902 static struct ast_config *config_handler(const char *database,  const char *table, const char *file,
903         struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked)
904 {
905         struct cfg_entry_args args;
906         char *query, *errormsg = NULL;
907         int error;
908
909         if (!config_table) {
910                 if (!table) {
911                         ast_log(LOG_ERROR, "Table name unspecified\n");
912                         return NULL;
913                 }
914         } else
915                 table = config_table;
916
917         query = sqlite_mprintf(sql_get_config_table, table, file);
918
919         if (!query) {
920                 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
921                 return NULL;
922         }
923
924         ast_debug(1, "SQL query: %s\n", query);
925         args.cfg = cfg;
926         args.cat = NULL;
927         args.cat_name = NULL;
928         args.flags = flags;
929         args.who_asked = who_asked;
930
931         ast_mutex_lock(&mutex);
932
933         RES_CONFIG_SQLITE_BEGIN
934                 error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
935         RES_CONFIG_SQLITE_END(error)
936
937         ast_mutex_unlock(&mutex);
938
939         ast_free(args.cat_name);
940         sqlite_freemem(query);
941
942         if (error) {
943                 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
944                 sqlite_freemem(errormsg);
945                 return NULL;
946         }
947         sqlite_freemem(errormsg);
948
949         return cfg;
950 }
951
952 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
953 {
954         const char **tmp, *param, *val, **params, **vals;
955         size_t params_count;
956
957         params = NULL;
958         vals = NULL;
959         params_count = 0;
960
961         while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
962                 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
963                         ast_free(params);
964                         ast_free(vals);
965                         return 0;
966                 }
967                 params = tmp;
968
969                 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
970                         ast_free(params);
971                         ast_free(vals);
972                         return 0;
973                 }
974                 vals = tmp;
975
976                 params[params_count] = param;
977                 vals[params_count] = val;
978                 params_count++;
979         }
980
981         if (params_count > 0) {
982                 *params_ptr = params;
983                 *vals_ptr = vals;
984         } else
985                 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
986
987         return params_count;
988 }
989
990 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
991 {
992         struct rt_cfg_entry_args *args;
993         struct ast_variable *var;
994         int i;
995
996         args = arg;
997
998         for (i = 0; i < argc; i++) {
999                 if (!argv[i])
1000                         continue;
1001
1002                 if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
1003                         return 1;
1004
1005                 if (!args->var)
1006                         args->var = var;
1007
1008                 if (!args->last)
1009                         args->last = var;
1010                 else {
1011                         args->last->next = var;
1012                         args->last = var;
1013                 }
1014         }
1015
1016         return 0;
1017 }
1018
1019 static struct ast_variable * realtime_handler(const char *database, const char *table, va_list ap)
1020 {
1021         char *query, *errormsg = NULL, *op, *tmp_str;
1022         struct rt_cfg_entry_args args;
1023         const char **params, **vals;
1024         size_t params_count;
1025         int error;
1026
1027         if (!table) {
1028                 ast_log(LOG_WARNING, "Table name unspecified\n");
1029                 return NULL;
1030         }
1031
1032         params_count = get_params(ap, &params, &vals);
1033
1034         if (params_count == 0)
1035                 return NULL;
1036
1037         op = (strchr(params[0], ' ') == NULL) ? " =" : "";
1038
1039 /* \cond DOXYGEN_CAN_PARSE_THIS */
1040 #undef QUERY
1041 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1042 /* \endcond */
1043
1044         query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
1045
1046         if (!query) {
1047                 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1048                 ast_free(params);
1049                 ast_free(vals);
1050                 return NULL;
1051         }
1052
1053         if (params_count > 1) {
1054                 size_t i;
1055
1056                 for (i = 1; i < params_count; i++) {
1057                         op = (strchr(params[i], ' ') == NULL) ? " =" : "";
1058                         tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1059                         sqlite_freemem(query);
1060
1061                         if (!tmp_str) {
1062                                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1063                                 ast_free(params);
1064                                 ast_free(vals);
1065                                 return NULL;
1066                         }
1067
1068                         query = tmp_str;
1069                 }
1070         }
1071
1072         ast_free(params);
1073         ast_free(vals);
1074
1075         tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
1076         sqlite_freemem(query);
1077
1078         if (!tmp_str) {
1079                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1080                 return NULL;
1081         }
1082
1083         query = tmp_str;
1084         ast_debug(1, "SQL query: %s\n", query);
1085         args.var = NULL;
1086         args.last = NULL;
1087
1088         ast_mutex_lock(&mutex);
1089
1090         RES_CONFIG_SQLITE_BEGIN
1091                 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
1092         RES_CONFIG_SQLITE_END(error)
1093
1094         ast_mutex_unlock(&mutex);
1095
1096         sqlite_freemem(query);
1097
1098         if (error) {
1099                 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1100                 sqlite_freemem(errormsg);
1101                 ast_variables_destroy(args.var);
1102                 return NULL;
1103         }
1104         sqlite_freemem(errormsg);
1105
1106         return args.var;
1107 }
1108
1109 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
1110 {
1111         struct rt_multi_cfg_entry_args *args;
1112         struct ast_category *cat;
1113         struct ast_variable *var;
1114         char *cat_name;
1115         size_t i;
1116
1117         args = arg;
1118         cat_name = NULL;
1119
1120         /*
1121          * cat_name should always be set here, since initfield is forged from
1122          * params[0] in realtime_multi_handler(), which is a search parameter
1123          * of the SQL query.
1124          */
1125         for (i = 0; i < argc; i++) {
1126                 if (!strcmp(args->initfield, columnNames[i]))
1127                         cat_name = argv[i];
1128         }
1129
1130         if (!cat_name) {
1131                 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
1132                 return 1;
1133         }
1134
1135         if (!(cat = ast_category_new(cat_name, "", 99999))) {
1136                 ast_log(LOG_WARNING, "Unable to allocate category\n");
1137                 return 1;
1138         }
1139
1140         ast_category_append(args->cfg, cat);
1141
1142         for (i = 0; i < argc; i++) {
1143                 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
1144                         continue;
1145
1146                 if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
1147                         ast_log(LOG_WARNING, "Unable to allocate variable\n");
1148                         return 1;
1149                 }
1150
1151                 ast_variable_append(cat, var);
1152         }
1153
1154         return 0;
1155 }
1156
1157 static struct ast_config *realtime_multi_handler(const char *database,
1158         const char *table, va_list ap)
1159 {
1160         char *query, *errormsg = NULL, *op, *tmp_str, *initfield;
1161         struct rt_multi_cfg_entry_args args;
1162         const char **params, **vals;
1163         struct ast_config *cfg;
1164         size_t params_count;
1165         int error;
1166
1167         if (!table) {
1168                 ast_log(LOG_WARNING, "Table name unspecified\n");
1169                 return NULL;
1170         }
1171
1172         if (!(cfg = ast_config_new())) {
1173                 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1174                 return NULL;
1175         }
1176
1177         if (!(params_count = get_params(ap, &params, &vals))) {
1178                 ast_config_destroy(cfg);
1179                 return NULL;
1180         }
1181
1182         if (!(initfield = ast_strdup(params[0]))) {
1183                 ast_config_destroy(cfg);
1184                 ast_free(params);
1185                 ast_free(vals);
1186                 return NULL;
1187         }
1188
1189         tmp_str = strchr(initfield, ' ');
1190
1191         if (tmp_str)
1192                 *tmp_str = '\0';
1193
1194         op = (!strchr(params[0], ' ')) ? " =" : "";
1195
1196         /*
1197          * Asterisk sends us an already escaped string when searching for
1198          * "exten LIKE" (uh!). Handle it separately.
1199          */
1200         tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1201
1202 /* \cond DOXYGEN_CAN_PARSE_THIS */
1203 #undef QUERY
1204 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1205 /* \endcond */
1206
1207         if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1208                 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1209                 ast_config_destroy(cfg);
1210                 ast_free(params);
1211                 ast_free(vals);
1212                 ast_free(initfield);
1213                 return NULL;
1214         }
1215
1216         if (params_count > 1) {
1217                 size_t i;
1218
1219                 for (i = 1; i < params_count; i++) {
1220                         op = (!strchr(params[i], ' ')) ? " =" : "";
1221                         tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
1222                         sqlite_freemem(query);
1223
1224                         if (!tmp_str) {
1225                                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1226                                 ast_config_destroy(cfg);
1227                                 ast_free(params);
1228                                 ast_free(vals);
1229                                 ast_free(initfield);
1230                                 return NULL;
1231                         }
1232
1233                         query = tmp_str;
1234                 }
1235         }
1236
1237         ast_free(params);
1238         ast_free(vals);
1239
1240         if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1241                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1242                 sqlite_freemem(query);
1243                 ast_config_destroy(cfg);
1244                 ast_free(initfield);
1245                 return NULL;
1246         }
1247
1248         sqlite_freemem(query);
1249         query = tmp_str;
1250         ast_debug(1, "SQL query: %s\n", query);
1251         args.cfg = cfg;
1252         args.initfield = initfield;
1253
1254         ast_mutex_lock(&mutex);
1255
1256         RES_CONFIG_SQLITE_BEGIN
1257                 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1258         RES_CONFIG_SQLITE_END(error)
1259
1260         ast_mutex_unlock(&mutex);
1261
1262         sqlite_freemem(query);
1263         ast_free(initfield);
1264
1265         if (error) {
1266                 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1267                 sqlite_freemem(errormsg);
1268                 ast_config_destroy(cfg);
1269                 return NULL;
1270         }
1271         sqlite_freemem(errormsg);
1272
1273         return cfg;
1274 }
1275
1276 static int realtime_update_handler(const char *database, const char *table,
1277         const char *keyfield, const char *entity, va_list ap)
1278 {
1279         char *query, *errormsg = NULL, *tmp_str;
1280         const char **params, **vals;
1281         size_t params_count;
1282         int error, rows_num;
1283
1284         if (!table) {
1285                 ast_log(LOG_WARNING, "Table name unspecified\n");
1286                 return -1;
1287         }
1288
1289         if (!(params_count = get_params(ap, &params, &vals)))
1290                 return -1;
1291
1292 /* \cond DOXYGEN_CAN_PARSE_THIS */
1293 #undef QUERY
1294 #define QUERY "UPDATE '%q' SET %q = '%q'"
1295 /* \endcond */
1296
1297         if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1298                 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1299                 ast_free(params);
1300                 ast_free(vals);
1301                 return -1;
1302         }
1303
1304         if (params_count > 1) {
1305                 size_t i;
1306
1307                 for (i = 1; i < params_count; i++) {
1308                         tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
1309                         sqlite_freemem(query);
1310
1311                         if (!tmp_str) {
1312                                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1313                                 ast_free(params);
1314                                 ast_free(vals);
1315                                 return -1;
1316                         }
1317
1318                         query = tmp_str;
1319                 }
1320         }
1321
1322         ast_free(params);
1323         ast_free(vals);
1324
1325         if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1326                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1327                 sqlite_freemem(query);
1328                 return -1;
1329         }
1330
1331         sqlite_freemem(query);
1332         query = tmp_str;
1333         ast_debug(1, "SQL query: %s\n", query);
1334
1335         ast_mutex_lock(&mutex);
1336
1337         RES_CONFIG_SQLITE_BEGIN
1338                 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1339         RES_CONFIG_SQLITE_END(error)
1340
1341         if (!error)
1342                 rows_num = sqlite_changes(db);
1343         else
1344                 rows_num = -1;
1345
1346         ast_mutex_unlock(&mutex);
1347
1348         sqlite_freemem(query);
1349
1350         if (error) {
1351                 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1352         }
1353         sqlite_freemem(errormsg);
1354
1355         return rows_num;
1356 }
1357
1358 static int realtime_store_handler(const char *database, const char *table, va_list ap)
1359 {
1360         char *errormsg = NULL, *tmp_str, *tmp_keys = NULL, *tmp_keys2 = NULL, *tmp_vals = NULL, *tmp_vals2 = NULL;
1361         const char **params, **vals;
1362         size_t params_count;
1363         int error, rows_id;
1364         size_t i;
1365
1366         if (!table) {
1367                 ast_log(LOG_WARNING, "Table name unspecified\n");
1368                 return -1;
1369         }
1370
1371         if (!(params_count = get_params(ap, &params, &vals)))
1372                 return -1;
1373
1374 /* \cond DOXYGEN_CAN_PARSE_THIS */
1375 #undef QUERY
1376 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1377 /* \endcond */
1378
1379         for (i = 0; i < params_count; i++) {
1380                 if ( tmp_keys2 ) {
1381                         tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1382                         sqlite_freemem(tmp_keys2);
1383                 } else {
1384                         tmp_keys = sqlite_mprintf("%q", params[i]);
1385                 }
1386                 if (!tmp_keys) {
1387                         ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1388                         sqlite_freemem(tmp_vals);
1389                         ast_free(params);
1390                         ast_free(vals);
1391                         return -1;
1392                 }
1393
1394                 if ( tmp_vals2 ) {
1395                         tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1396                         sqlite_freemem(tmp_vals2);
1397                 } else {
1398                         tmp_vals = sqlite_mprintf("'%q'", params[i]);
1399                 }
1400                 if (!tmp_vals) {
1401                         ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1402                         sqlite_freemem(tmp_keys);
1403                         ast_free(params);
1404                         ast_free(vals);
1405                         return -1;
1406                 }
1407
1408
1409                 tmp_keys2 = tmp_keys;
1410                 tmp_vals2 = tmp_vals;
1411         }
1412
1413         ast_free(params);
1414         ast_free(vals);
1415
1416         if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1417                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1418                 sqlite_freemem(tmp_keys);
1419                 sqlite_freemem(tmp_vals);
1420                 return -1;
1421         }
1422
1423         sqlite_freemem(tmp_keys);
1424         sqlite_freemem(tmp_vals);
1425
1426         ast_debug(1, "SQL query: %s\n", tmp_str);
1427
1428         ast_mutex_lock(&mutex);
1429
1430         RES_CONFIG_SQLITE_BEGIN
1431                 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1432         RES_CONFIG_SQLITE_END(error)
1433
1434         if (!error) {
1435                 rows_id = sqlite_last_insert_rowid(db);
1436         } else {
1437                 rows_id = -1;
1438         }
1439
1440         ast_mutex_unlock(&mutex);
1441
1442         sqlite_freemem(tmp_str);
1443
1444         if (error) {
1445                 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1446         }
1447         sqlite_freemem(errormsg);
1448
1449         return rows_id;
1450 }
1451
1452 static int realtime_destroy_handler(const char *database, const char *table,
1453         const char *keyfield, const char *entity, va_list ap)
1454 {
1455         char *query, *errormsg = NULL, *tmp_str;
1456         const char **params, **vals;
1457         size_t params_count;
1458         int error, rows_num;
1459         size_t i;
1460
1461         if (!table) {
1462                 ast_log(LOG_WARNING, "Table name unspecified\n");
1463                 return -1;
1464         }
1465
1466         if (!(params_count = get_params(ap, &params, &vals)))
1467                 return -1;
1468
1469 /* \cond DOXYGEN_CAN_PARSE_THIS */
1470 #undef QUERY
1471 #define QUERY "DELETE FROM '%q' WHERE"
1472 /* \endcond */
1473
1474         if (!(query = sqlite_mprintf(QUERY, table))) {
1475                 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1476                 ast_free(params);
1477                 ast_free(vals);
1478                 return -1;
1479         }
1480
1481         for (i = 0; i < params_count; i++) {
1482                 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1483                 sqlite_freemem(query);
1484
1485                 if (!tmp_str) {
1486                         ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1487                         ast_free(params);
1488                         ast_free(vals);
1489                         return -1;
1490                 }
1491
1492                 query = tmp_str;
1493         }
1494
1495         ast_free(params);
1496         ast_free(vals);
1497         if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1498                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1499                 sqlite_freemem(query);
1500                 return -1;
1501         }
1502         sqlite_freemem(query);
1503         query = tmp_str;
1504         ast_debug(1, "SQL query: %s\n", query);
1505
1506         ast_mutex_lock(&mutex);
1507
1508         RES_CONFIG_SQLITE_BEGIN
1509                 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1510         RES_CONFIG_SQLITE_END(error)
1511
1512         if (!error)
1513                 rows_num = sqlite_changes(db);
1514         else
1515                 rows_num = -1;
1516
1517         ast_mutex_unlock(&mutex);
1518
1519         sqlite_freemem(query);
1520
1521         if (error) {
1522                 ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1523         }
1524         sqlite_freemem(errormsg);
1525
1526         return rows_num;
1527 }
1528
1529 static int realtime_require_handler(const char *unused, const char *tablename, va_list ap)
1530 {
1531         struct sqlite_cache_tables *tbl = find_table(tablename);
1532         struct sqlite_cache_columns *col;
1533         char *elm;
1534         int type, size, res = 0;
1535
1536         if (!tbl) {
1537                 return -1;
1538         }
1539
1540         while ((elm = va_arg(ap, char *))) {
1541                 type = va_arg(ap, require_type);
1542                 size = va_arg(ap, int);
1543                 /* Check if the field matches the criteria */
1544                 AST_RWLIST_TRAVERSE(&tbl->columns, col, list) {
1545                         if (strcmp(col->name, elm) == 0) {
1546                                 /* SQLite only has two types - the 32-bit integer field that
1547                                  * is the key column, and everything else (everything else
1548                                  * being a string).
1549                                  */
1550                                 if (col->isint && !ast_rq_is_int(type)) {
1551                                         ast_log(LOG_WARNING, "Realtime table %s: column '%s' is an integer field, but Asterisk requires that it not be!\n", tablename, col->name);
1552                                         res = -1;
1553                                 }
1554                                 break;
1555                         }
1556                 }
1557                 if (!col) {
1558                         ast_log(LOG_WARNING, "Realtime table %s requires column '%s', but that column does not exist!\n", tablename, elm);
1559                 }
1560         }
1561         AST_RWLIST_UNLOCK(&(tbl->columns));
1562         return res;
1563 }
1564
1565 static int realtime_unload_handler(const char *unused, const char *tablename)
1566 {
1567         struct sqlite_cache_tables *tbl;
1568         AST_RWLIST_WRLOCK(&sqlite_tables);
1569         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&sqlite_tables, tbl, list) {
1570                 if (!strcasecmp(tbl->name, tablename)) {
1571                         AST_RWLIST_REMOVE_CURRENT(list);
1572                         free_table(tbl);
1573                 }
1574         }
1575         AST_RWLIST_TRAVERSE_SAFE_END
1576         AST_RWLIST_UNLOCK(&sqlite_tables);
1577         return 0;
1578 }
1579
1580 static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1581 {
1582         switch (cmd) {
1583         case CLI_INIT:
1584                 e->command = "sqlite show status";
1585                 e->usage =
1586                         "Usage: sqlite show status\n"
1587                         "       Show status information about the SQLite 2 driver\n";
1588                 return NULL;
1589         case CLI_GENERATE:
1590                 return NULL;
1591         }
1592
1593         if (a->argc != 3)
1594                 return CLI_SHOWUSAGE;
1595
1596         ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
1597         ast_cli(a->fd, "config_table: ");
1598
1599         if (!config_table)
1600                 ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
1601         else
1602                 ast_cli(a->fd, "%s\n", config_table);
1603
1604         ast_cli(a->fd, "cdr_table: ");
1605
1606         if (!cdr_table)
1607                 ast_cli(a->fd, "unspecified, CDR support disabled\n");
1608         else
1609                 ast_cli(a->fd, "%s\n", cdr_table);
1610
1611         return CLI_SUCCESS;
1612 }
1613
1614 static char *handle_cli_sqlite_show_tables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1615 {
1616         struct sqlite_cache_tables *tbl;
1617         struct sqlite_cache_columns *col;
1618         int found = 0;
1619
1620         switch (cmd) {
1621         case CLI_INIT:
1622                 e->command = "sqlite show tables";
1623                 e->usage =
1624                         "Usage: sqlite show tables\n"
1625                         "       Show table information about the SQLite 2 driver\n";
1626                 return NULL;
1627         case CLI_GENERATE:
1628                 return NULL;
1629         }
1630
1631         if (a->argc != 3)
1632                 return CLI_SHOWUSAGE;
1633
1634         AST_RWLIST_RDLOCK(&sqlite_tables);
1635         AST_RWLIST_TRAVERSE(&sqlite_tables, tbl, list) {
1636                 found++;
1637                 ast_cli(a->fd, "Table %s:\n", tbl->name);
1638                 AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
1639                         fprintf(stderr, "%s\n", col->name);
1640                         ast_cli(a->fd, "  %20.20s  %-30.30s\n", col->name, col->type);
1641                 }
1642         }
1643         AST_RWLIST_UNLOCK(&sqlite_tables);
1644
1645         if (!found) {
1646                 ast_cli(a->fd, "No tables currently in cache\n");
1647         }
1648
1649         return CLI_SUCCESS;
1650 }
1651
1652 static int unload_module(void)
1653 {
1654         if (cli_status_registered)
1655                 ast_cli_unregister_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1656
1657         if (cdr_registered)
1658                 ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
1659
1660         ast_config_engine_deregister(&sqlite_engine);
1661
1662         if (db)
1663                 sqlite_close(db);
1664
1665         unload_config();
1666
1667         return 0;
1668 }
1669
1670 static int load_module(void)
1671 {
1672         char *errormsg = NULL;
1673         int error;
1674
1675         db = NULL;
1676         cdr_registered = 0;
1677         cli_status_registered = 0;
1678         dbfile = NULL;
1679         config_table = NULL;
1680         cdr_table = NULL;
1681         error = load_config();
1682
1683         if (error)
1684                 return AST_MODULE_LOAD_DECLINE;
1685
1686         if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1687                 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1688                 sqlite_freemem(errormsg);
1689                 unload_module();
1690                 return 1;
1691         }
1692
1693         sqlite_freemem(errormsg);
1694         errormsg = NULL;
1695         ast_config_engine_register(&sqlite_engine);
1696
1697         if (use_cdr) {
1698                 char *query;
1699
1700 /* \cond DOXYGEN_CAN_PARSE_THIS */
1701 #undef QUERY
1702 #define QUERY "SELECT COUNT(id) FROM %Q;"
1703 /* \endcond */
1704
1705                 query = sqlite_mprintf(QUERY, cdr_table);
1706
1707                 if (!query) {
1708                         ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1709                         unload_module();
1710                         return 1;
1711                 }
1712
1713                 ast_debug(1, "SQL query: %s\n", query);
1714
1715                 RES_CONFIG_SQLITE_BEGIN
1716                         error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1717                 RES_CONFIG_SQLITE_END(error)
1718
1719                 sqlite_freemem(query);
1720
1721                 if (error) {
1722                         /*
1723                          * Unexpected error.
1724                          */
1725                         if (error != SQLITE_ERROR) {
1726                                 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1727                                 sqlite_freemem(errormsg);
1728                                 unload_module();
1729                                 return 1;
1730                         }
1731
1732                         sqlite_freemem(errormsg);
1733                         errormsg = NULL;
1734                         query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
1735
1736                         if (!query) {
1737                                 ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
1738                                 unload_module();
1739                                 return 1;
1740                         }
1741
1742                         ast_debug(1, "SQL query: %s\n", query);
1743
1744                         RES_CONFIG_SQLITE_BEGIN
1745                                 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1746                         RES_CONFIG_SQLITE_END(error)
1747
1748                         sqlite_freemem(query);
1749
1750                         if (error) {
1751                                 ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
1752                                 sqlite_freemem(errormsg);
1753                                 unload_module();
1754                                 return 1;
1755                         }
1756                 }
1757                 sqlite_freemem(errormsg);
1758                 errormsg = NULL;
1759
1760                 error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
1761
1762                 if (error) {
1763                         unload_module();
1764                         return 1;
1765                 }
1766
1767                 cdr_registered = 1;
1768         }
1769
1770         error = ast_cli_register_multiple(cli_status, sizeof(cli_status) / sizeof(struct ast_cli_entry));
1771
1772         if (error) {
1773                 unload_module();
1774                 return 1;
1775         }
1776
1777         cli_status_registered = 1;
1778
1779         return 0;
1780 }
1781
1782 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1783                 .load = load_module,
1784                 .unload = unload_module,
1785 );