store and destroy implementations for sqlite (closes issue #10446) and odbc (closes...
[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).
31  * It can also be used to log CDR entries. Finally, it can be used for simple
32  * queries in the Dialplan. Note that Asterisk already comes with a module
33  * named cdr_sqlite. There are two reasons for including it in res_sqlite:
34  * the first is that rewriting it was a training to learn how to write a
35  * simple module for Asterisk, the other is to have the same database open for
36  * all kinds of operations, which improves reliability and performance.
37  * 
38  * There is already a module for SQLite 3 (named res_sqlite3) in the Asterisk
39  * addons. res_sqlite was developed because we, at Proformatique, are using
40  * PHP 4 in our embedded systems, and PHP 4 has no stable support for SQLite 3
41  * at this time. We also needed RealTime support.
42  * 
43  * \section conf_sec Configuration
44  * 
45  * The main configuration file is res_config_sqlite.conf. It must be readable or
46  * res_sqlite will fail to start. It is suggested to use the sample file
47  * in this package as a starting point. The file has only one section
48  * named <code>general</code>. Here are the supported parameters :
49  * 
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_sqlite will create it if is has the appropriate rights)</dd>
54  *      <dt><code>config_table</code></dt>
55  *      <dd>The table used for static configuration</dd>
56  *      <dt><code>cdr_table</code></dt>
57  *      <dd>The table used to store CDR entries (if ommitted, CDR support is
58  *                      disabled)</dd>
59  * </dl>
60  * 
61  * To use res_sqlite for static and/or RealTime configuration, refer to the
62  * Asterisk documentation. The file tables.sql can be used to create the
63  * needed tables.
64  * 
65  * The SQLITE() application is very similar to the MYSQL() application. You
66  * can find more details at
67  * <a href="http://voip-info.org/wiki/view/Asterisk+cmd+MYSQL">http://voip-info.org/wiki/view/Asterisk+cmd+MYSQL</a>.
68  * The main difference is that you cannot choose your database - it's the
69  * file set in the <code>dbfile</code> parameter. As a result, there is no
70  * Connect or Disconnect command, and there is no connid variable.
71  * 
72  * \section status_sec Driver status
73  * 
74  * The CLI command <code>show sqlite status</code> returns status information
75  * about the running driver. One information is more important than others:
76  * the number of registered virtual machines. A SQLite virtual machine is
77  * created each time a SQLITE() query command is used. If the number of
78  * registered virtual machines isn't 0 (or near 0, since one or more SQLITE()
79  * commands can be running when requesting the module status) and increases
80  * over time, this probably means that you're badly using the application
81  * and you're creating resource leaks. You should check your Dialplan and
82  * reload res_sqlite (by unloading and then loading again - reloading isn't
83  * supported)
84  * 
85  * \section credits_sec Credits
86  * 
87  * res_config_sqlite was developed by Richard Braun at the Proformatique company.
88  */
89
90 /*!
91  * \file 
92  * \brief res_sqlite module.
93  */
94
95 /*** MODULEINFO
96         <depend>sqlite</depend>
97  ***/
98
99 #include "asterisk.h"
100
101 #include <stdio.h>
102 #include <stdarg.h>
103 #include <stdlib.h>
104 #include <string.h>
105 #include <sqlite.h>
106
107 #include "asterisk/pbx.h"
108 #include "asterisk/cdr.h"
109 #include "asterisk/cli.h"
110 #include "asterisk/lock.h"
111 #include "asterisk/config.h"
112 #include "asterisk/logger.h"
113 #include "asterisk/module.h"
114 #include "asterisk/options.h"
115 #include "asterisk/linkedlists.h"
116
117 #define RES_SQLITE_NAME "res_sqlite"
118 #define RES_SQLITE_DRIVER "sqlite"
119 #define RES_SQLITE_APP_DRIVER "SQLITE"
120 #define RES_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
121 #define RES_SQLITE_CONF_FILE "res_config_sqlite.conf"
122 #define RES_SQLITE_APP_SYNOPSIS "Dialplan access to SQLite 2"
123 #define RES_SQLITE_APP_DESCRIPTION \
124 "SQLITE(): " RES_SQLITE_APP_SYNOPSIS "\n"
125 #define RES_SQLITE_STATUS_SUMMARY \
126 "Show status information about the SQLite 2 driver"
127 #define RES_SQLITE_STATUS_USAGE \
128 "Usage: show sqlite status\n" \
129 "       " RES_SQLITE_STATUS_SUMMARY "\n"
130
131 enum {
132         RES_SQLITE_CONFIG_ID,
133         RES_SQLITE_CONFIG_COMMENTED,
134         RES_SQLITE_CONFIG_FILENAME,
135         RES_SQLITE_CONFIG_CATEGORY,
136         RES_SQLITE_CONFIG_VAR_NAME,
137         RES_SQLITE_CONFIG_VAR_VAL,
138         RES_SQLITE_CONFIG_COLUMNS,
139 };
140
141 /*!
142  * Limit the number of maximum simultaneous registered SQLite VMs to avoid
143  * a denial of service attack.
144  */
145 #define RES_SQLITE_VM_MAX 1024
146
147 #define SET_VAR(config, to, from) \
148 do \
149         { \
150                 int __error; \
151                 __error = set_var(&to, #to, from->value); \
152                 if (__error) \
153                         { \
154                                 ast_config_destroy(config); \
155                                 unload_config(); \
156                                 return 1; \
157                         } \
158         } \
159 while (0)
160
161 /*!
162  * Maximum number of loops before giving up executing a query. Calls to
163  * sqlite_xxx() functions which can return SQLITE_BUSY or SQLITE_LOCKED
164  * are enclosed by RES_SQLITE_BEGIN and RES_SQLITE_END, e.g.
165  * <pre>
166  * char *errormsg;
167  * int error;
168  * 
169  * RES_SQLITE_BEGIN
170  *       error = sqlite_exec(db, query, NULL, NULL, &errormsg);
171  * RES_SQLITE_END(error)
172  * 
173  * if (error)
174  *       ...;
175  * </pre>
176  */
177 #define RES_SQLITE_MAX_LOOPS 10
178
179 /*!
180  * Macro used before executing a query.
181  * 
182  * \see RES_SQLITE_MAX_LOOPS.
183  */
184 #define RES_SQLITE_BEGIN \
185 { \
186         int __i; \
187         for (__i = 0; __i < RES_SQLITE_MAX_LOOPS; __i++) \
188                 {
189
190 /*!
191  * Macro used after executing a query.
192  * 
193  * \see RES_SQLITE_MAX_LOOPS.
194  */
195 #define RES_SQLITE_END(error) \
196                         if (error != SQLITE_BUSY && error != SQLITE_LOCKED) \
197                                 break; \
198                         usleep(1000); \
199                 } \
200 }
201
202 /*!
203  * Structure sent to the SQLite callback function for static configuration.
204  * 
205  * \see add_cfg_entry()
206  */
207 struct cfg_entry_args {
208         struct ast_config *cfg;
209         struct ast_category *cat;
210         char *cat_name;
211 };
212
213 /*!
214  * Structure sent to the SQLite callback function for RealTime configuration.
215  * 
216  * \see add_rt_cfg_entry()
217  */
218 struct rt_cfg_entry_args {
219         struct ast_variable *var;
220         struct ast_variable *last;
221 };
222
223 /*!
224  * Structure sent to the SQLite callback function for RealTime configuration
225  * (realtime_multi_handler()).
226  * 
227  * \see add_rt_multi_cfg_entry()
228  */
229 struct rt_multi_cfg_entry_args {
230         struct ast_config *cfg;
231         char *initfield;
232 };
233
234 /*!
235  * \brief Allocate a variable.
236  * \param var the address of the variable to set (it will be allocated)
237  * \param name the name of the variable (for error handling)
238  * \param value the value to store in var
239  * \retval 0 on success
240  * \retval 1 if an allocation error occurred
241  */
242 static int set_var(char **var, char *name, char *value);
243
244 /*!
245  * \brief Load the configuration file.
246  * \see unload_config()
247  * 
248  * This function sets dbfile, config_table, and cdr_table. It calls
249  * check_vars() before returning, and unload_config() if an error occurred.
250  * 
251  * \retval 0 on success
252  * \retval 1 if an error occurred
253  */
254 static int load_config(void);
255
256 /*!
257  * \brief Free resources related to configuration.
258  * \see load_config()
259  */
260 static void unload_config(void);
261
262 /*!
263  * \brief Asterisk callback function for CDR support.
264  * \param cdr the CDR entry Asterisk sends us
265  * 
266  * Asterisk will call this function each time a CDR entry must be logged if
267  * CDR support is enabled.
268  * 
269  * \retval 0 on success
270  * \retval 1 if an error occurred
271  */
272 static int cdr_handler(struct ast_cdr *cdr);
273
274 /*!
275  * \brief SQLite callback function for static configuration.
276  * 
277  * This function is passed to the SQLite engine as a callback function to
278  * parse a row and store it in a struct ast_config object. It relies on
279  * resulting rows       being sorted by category.
280  * 
281  * \param arg a pointer to a struct cfg_entry_args object
282  * \param argc number of columns
283  * \param argv values in the row
284  * \param columnNames names and types of the columns
285  * \retval 0 on success
286  * \retval 1 if an error occurred
287  * \see cfg_entry_args
288  * \see sql_get_config_table
289  * \see config_handler()
290  */
291 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
292
293 /*!
294  * \brief Asterisk callback function for static configuration.
295  * 
296  * Asterisk will call this function when it loads its static configuration,
297  * which usually happens at startup and reload.
298  * 
299  * \param database the database to use (ignored)
300  * \param table the table to use
301  * \param file the file to load from the database
302  * \param cfg the struct ast_config object to use when storing variables
303  * \param flags Optional flags.  Not used.
304  * \retval cfg object
305  * \retval NULL if an error occurred
306  * \see add_cfg_entry()
307  */
308 static struct ast_config * config_handler(const char *database,
309         const char *table, const char *file,
310         struct ast_config *cfg, struct ast_flags flags);
311
312 /*!
313  * \brief Helper function to parse a va_list object into 2 dynamic arrays of
314  * strings, parameters and values.
315  * 
316  * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
317  * arguments will be extracted to create 2 arrays:
318  * 
319  * <ul>
320  *      <li>params : param1 param2 param3 ...</li>
321  *      <li>vals : val1 val2 val3 ...</li>
322  * </ul>
323  * 
324  * The address of these arrays are stored in params_ptr and vals_ptr. It
325  * is the responsibility of the caller to release the memory of these arrays.
326  * It is considered an error that va_list has a null or odd number of strings.
327  * 
328  * \param ap the va_list object to parse
329  * \param params_ptr where the address of the params array is stored
330  * \param vals_ptr where the address of the vals array is stored
331  * \retval the number of elements in the arrays (which have the same size).
332  * \retval 0 if an error occurred.
333  */
334 static size_t get_params(va_list ap, const char ***params_ptr,
335         const char ***vals_ptr);
336
337 /*!
338  * \brief SQLite callback function for RealTime configuration.
339  * 
340  * This function is passed to the SQLite engine as a callback function to
341  * parse a row and store it in a linked list of struct ast_variable objects.
342  * 
343  * \param arg a pointer to a struct rt_cfg_entry_args object
344  * \param argc number of columns
345  * \param argv values in the row
346  * \param columnNames names and types of the columns
347  * \retval 0 on success.
348  * \retval 1 if an error occurred.
349  * \see rt_cfg_entry_args
350  * \see realtime_handler()
351  */
352 static int add_rt_cfg_entry(void *arg, int argc, char **argv,
353         char **columnNames);
354
355 /*!
356  * Asterisk callback function for RealTime configuration.
357  * 
358  * Asterisk will call this function each time it requires a variable
359  * through the RealTime architecture. ap is a list of parameters and
360  * values used to find a specific row, e.g one parameter "name" and
361  * one value "123" so that the SQL query becomes <code>SELECT * FROM
362  * table WHERE name = '123';</code>.
363  * 
364  * \param database the database to use (ignored)
365  * \param table         the table to use
366  * \param ap                     list of parameters and values to match
367  *
368  * \retval a linked list of struct ast_variable objects
369  * \retval NULL if an error occurred
370  * \see add_rt_cfg_entry()
371  */
372 static struct ast_variable * realtime_handler(const char *database,
373         const char *table, va_list ap);
374
375 /*!
376  * \brief SQLite callback function for RealTime configuration.
377  * 
378  * This function performs the same actions as add_rt_cfg_entry() except
379  * that the rt_multi_cfg_entry_args structure is designed to store
380  * categories in addition of variables.
381  * 
382  * \param arg a pointer to a struct rt_multi_cfg_entry_args object
383  * \param argc number of columns
384  * \param argv values in the row
385  * \param columnNames names and types of the columns
386  * \retval 0 on success.
387  * \retval 1 if an error occurred.
388  * \see rt_multi_cfg_entry_args
389  * \see realtime_multi_handler()
390  */
391 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
392         char **columnNames);
393
394 /*!
395  * \brief Asterisk callback function for RealTime configuration.
396  * 
397  * This function performs the same actions as realtime_handler() except
398  * that it can store variables per category, and can return several
399  * categories.
400  * 
401  * \param database the database to use (ignored)
402  * \param table the table to use
403  * \param ap list of parameters and values to match
404  * \retval a struct ast_config object storing categories and variables.
405  * \retval NULL if an error occurred.
406  *
407  * \see add_rt_multi_cfg_entry()
408  */
409 static struct ast_config * realtime_multi_handler(const char *database,
410         const char *table,
411         va_list ap);
412
413 /*!
414  * \brief Asterisk callback function for RealTime configuration (variable
415  * update).
416  * 
417  * Asterisk will call this function each time a variable has been modified
418  * internally and must be updated in the backend engine. keyfield and entity
419  * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
420  * keyfield = 'entity';</code>. ap is a list of parameters and values with the
421  * same format as the other realtime functions.
422  * 
423  * \param database the database to use (ignored)
424  * \param table the table to use
425  * \param keyfield the column of the matching cell
426  * \param entity the value of the matching cell
427  * \param ap list of parameters and new values to update in the database
428  * \retval the number of affected rows.
429  * \retval -1 if an error occurred.
430  */
431 static int realtime_update_handler(const char *database, const char *table,
432         const char *keyfield, const char *entity,
433         va_list ap);
434
435 /*!
436  * \brief Asterisk callback function for RealTime configuration (variable
437  * create/store).
438  * 
439  * Asterisk will call this function each time a variable has been created
440  * internally and must be stored in the backend engine. 
441  * are used to find the row to update, e.g. ap is a list of parameters and 
442  * values with the same format as the other realtime functions.
443  * 
444  * \param database the database to use (ignored)
445  * \param table the table to use
446  * \param ap list of parameters and new values to insert into the database
447  * \retval the rowid of inserted row.
448  * \retval -1 if an error occurred.
449  */
450 static int realtime_store_handler(const char *database, const char *table,
451         va_list ap);
452
453 /*!
454  * \brief Asterisk callback function for RealTime configuration (destroys 
455  * variable).
456  * 
457  * Asterisk will call this function each time a variable has been destroyed
458  * internally and must be removed from the backend engine. keyfield and entity
459  * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
460  * keyfield = 'entity';</code>. ap is a list of parameters and values with the
461  * same format as the other realtime functions.
462  * 
463  * \param database the database to use (ignored)
464  * \param table the table to use
465  * \param keyfield the column of the matching cell
466  * \param entity the value of the matching cell
467  * \param ap list of additional parameters for cell matching
468  * \retval the number of affected rows.
469  * \retval -1 if an error occurred.
470  */
471 static int realtime_destroy_handler(const char *database, const char *table,
472         const char *keyfield, const char *entity,
473         va_list ap);
474
475 /*!
476  * \brief Asterisk callback function for the CLI status command.
477  * 
478  * \param fd file descriptor provided by Asterisk to use with ast_cli()
479  * \param argc number of arguments
480  * \param argv arguments list
481  * \return RESULT_SUCCESS
482  */
483 static int cli_status(int fd, int argc, char *argv[]);
484
485 /*! The SQLite database object. */
486 static sqlite *db;
487
488 /*! Set to 1 if CDR support is enabled. */
489 static int use_cdr;
490
491 /*! Set to 1 if the CDR callback function was registered. */
492 static int cdr_registered;
493
494 /*! Set to 1 if the CLI status command callback function was registered. */
495 static int cli_status_registered;
496
497 /*! The path of the database file. */
498 static char *dbfile;
499
500 /*! The name of the static configuration table. */
501 static char *config_table;
502
503 /*! The name of the table used to store CDR entries. */
504 static char *cdr_table;
505
506 /*! The number of registered virtual machines. */
507 static int vm_count;
508
509 /*!
510  * The structure specifying all callback functions used by Asterisk for static
511  * and RealTime configuration.
512  */
513 static struct ast_config_engine sqlite_engine =
514 {
515         .name = RES_SQLITE_DRIVER,
516         .load_func = config_handler,
517         .realtime_func = realtime_handler,
518         .realtime_multi_func = realtime_multi_handler,
519         .store_func = realtime_store_handler,
520         .destroy_func = realtime_destroy_handler,
521         .update_func = realtime_update_handler
522 };
523
524 /*!
525  * The mutex used to prevent simultaneous access to the SQLite database.
526  * SQLite isn't always compiled with thread safety.
527  */
528 AST_MUTEX_DEFINE_STATIC(mutex);
529
530 /*!
531  * Structure containing details and callback functions for the CLI status
532  * command.
533  */
534 static struct ast_cli_entry cli_status_cmd =
535 {
536         .cmda = {"show", "sqlite", "status", NULL},
537         .handler = cli_status,
538         .summary = RES_SQLITE_STATUS_SUMMARY,
539         .usage = RES_SQLITE_STATUS_USAGE
540 };
541
542 /*
543  * Taken from Asterisk 1.2 cdr_sqlite.so.
544  */
545
546 /*! SQL query format to create the CDR table if non existent. */
547 static char *sql_create_cdr_table =
548 "CREATE TABLE '%q' ("
549 "       id              INTEGER PRIMARY KEY,"
550 "       clid            VARCHAR(80) NOT NULL DEFAULT '',"
551 "       src             VARCHAR(80) NOT NULL DEFAULT '',"
552 "       dst             VARCHAR(80) NOT NULL DEFAULT '',"
553 "       dcontext        VARCHAR(80) NOT NULL DEFAULT '',"
554 "       channel         VARCHAR(80) NOT NULL DEFAULT '',"
555 "       dstchannel      VARCHAR(80) NOT NULL DEFAULT '',"
556 "       lastapp         VARCHAR(80) NOT NULL DEFAULT '',"
557 "       lastdata        VARCHAR(80) NOT NULL DEFAULT '',"
558 "       start           CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
559 "       answer          CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
560 "       end             CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
561 "       duration        INT(11) NOT NULL DEFAULT '0',"
562 "       billsec         INT(11) NOT NULL DEFAULT '0',"
563 "       disposition     INT(11) NOT NULL DEFAULT '0',"
564 "       amaflags        INT(11) NOT NULL DEFAULT '0',"
565 "       accountcode     VARCHAR(20) NOT NULL DEFAULT '',"
566 "       uniqueid        VARCHAR(32) NOT NULL DEFAULT '',"
567 "       userfield       VARCHAR(255) NOT NULL DEFAULT ''"
568 ");";
569
570 /*! SQL query format to insert a CDR entry. */
571 static char *sql_add_cdr_entry =
572 "INSERT INTO '%q' ("
573 "                        clid,"
574 "       src,"
575 "       dst,"
576 "       dcontext,"
577 "       channel,"
578 "       dstchannel,"
579 "       lastapp,"
580 "       lastdata,"
581 "       start,"
582 "       answer,"
583 "       end,"
584 "       duration,"
585 "       billsec,"
586 "       disposition,"
587 "       amaflags,"
588 "       accountcode,"
589 "       uniqueid,"
590 "       userfield"
591 ") VALUES ("
592 "       '%q',"
593 "       '%q',"
594 "       '%q',"
595 "       '%q',"
596 "       '%q',"
597 "       '%q',"
598 "       '%q',"
599 "       '%q',"
600 "       datetime(%d,'unixepoch'),"
601 "       datetime(%d,'unixepoch'),"
602 "       datetime(%d,'unixepoch'),"
603 "       '%ld',"
604 "       '%ld',"
605 "       '%ld',"
606 "       '%ld',"
607 "       '%q',"
608 "       '%q',"
609 "       '%q'"
610 ");";
611
612 /*!
613  * SQL query format to fetch the static configuration of a file.
614  * Rows must be sorted by category.
615  * 
616  * \see add_cfg_entry()
617  */
618 static char *sql_get_config_table =
619 "SELECT *"
620 "       FROM '%q'"
621 "       WHERE filename = '%q' AND commented = 0"
622 "       ORDER BY category;";
623
624 static int set_var(char **var, char *name, char *value)
625 {
626         if (*var)
627                 ast_free(*var);
628
629         *var = ast_strdup(value);
630
631         if (!*var) {
632                 ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
633                 return 1;
634         }
635
636         return 0;
637 }
638
639 static int check_vars(void)
640 {
641         if (!dbfile) {
642                 ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
643                 return 1;
644         }
645
646         use_cdr = (cdr_table != NULL);
647
648         return 0;
649 }
650
651 static int load_config(void)
652 {
653         struct ast_config *config;
654         struct ast_variable *var;
655         int error;
656         struct ast_flags config_flags = { 0 };
657
658         config = ast_config_load(RES_SQLITE_CONF_FILE, config_flags);
659
660         if (!config) {
661                 ast_log(LOG_ERROR, "Unable to load " RES_SQLITE_CONF_FILE "\n");
662                 return 1;
663         }
664
665         for (var = ast_variable_browse(config, "general"); var; var = var->next) {
666                 if (!strcasecmp(var->name, "dbfile"))
667                         SET_VAR(config, dbfile, var);
668                 else if (!strcasecmp(var->name, "config_table"))
669                         SET_VAR(config, config_table, var);
670                 else if (!strcasecmp(var->name, "cdr_table"))
671                         SET_VAR(config, cdr_table, var);
672                 else
673                         ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
674         }
675
676         ast_config_destroy(config);
677         error = check_vars();
678
679         if (error) {
680                 unload_config();
681                 return 1;
682         }
683
684         return 0;
685 }
686
687 static void unload_config(void)
688 {
689         ast_free(dbfile);
690         dbfile = NULL;
691         ast_free(config_table);
692         config_table = NULL;
693         ast_free(cdr_table);
694         cdr_table = NULL;
695 }
696
697 static int cdr_handler(struct ast_cdr *cdr)
698 {
699         char *errormsg;
700         int error;
701
702         ast_mutex_lock(&mutex);
703
704         RES_SQLITE_BEGIN
705                 error = sqlite_exec_printf(db, sql_add_cdr_entry, NULL, NULL, &errormsg,
706                                          cdr_table, cdr->clid, cdr->src, cdr->dst,
707                                          cdr->dcontext, cdr->channel, cdr->dstchannel,
708                                          cdr->lastapp, cdr->lastdata, cdr->start.tv_sec,
709                                          cdr->answer.tv_sec, cdr->end.tv_sec,
710                                          cdr->duration, cdr->billsec, cdr->disposition,
711                                          cdr->amaflags, cdr->accountcode, cdr->uniqueid,
712                                          cdr->userfield);
713         RES_SQLITE_END(error)
714
715         ast_mutex_unlock(&mutex);
716
717         if (error) {
718                 ast_log(LOG_ERROR, "%s\n", errormsg);
719                 ast_free(errormsg);
720                 return 1;
721         }
722
723         return 0;
724 }
725
726 static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
727 {
728         struct cfg_entry_args *args;
729         struct ast_variable *var;
730
731         if (argc != RES_SQLITE_CONFIG_COLUMNS) {
732                 ast_log(LOG_WARNING, "Corrupt table\n");
733                 return 1;
734         }
735
736         args = arg;
737
738         if (!args->cat_name || strcmp(args->cat_name, argv[RES_SQLITE_CONFIG_CATEGORY])) {
739                 args->cat = ast_category_new(argv[RES_SQLITE_CONFIG_CATEGORY]);
740
741                 if (!args->cat) {
742                         ast_log(LOG_WARNING, "Unable to allocate category\n");
743                         return 1;
744                 }
745
746                 ast_free(args->cat_name);
747                 args->cat_name = ast_strdup(argv[RES_SQLITE_CONFIG_CATEGORY]);
748
749                 if (!args->cat_name) {
750                         ast_category_destroy(args->cat);
751                         return 1;
752                 }
753
754                 ast_category_append(args->cfg, args->cat);
755         }
756
757         var = ast_variable_new(argv[RES_SQLITE_CONFIG_VAR_NAME],
758                  argv[RES_SQLITE_CONFIG_VAR_VAL]);
759
760         if (!var) {
761                 ast_log(LOG_WARNING, "Unable to allocate variable");
762                 return 1;
763         }
764
765         ast_variable_append(args->cat, var);
766         
767         return 0;
768 }
769
770 static struct ast_config *config_handler(const char *database, 
771         const char *table, const char *file, struct ast_config *cfg, struct ast_flags flags)
772 {
773         struct cfg_entry_args args;
774         char *errormsg;
775         int error;
776
777         if (!config_table) {
778                 if (!table) {
779                         ast_log(LOG_ERROR, "Table name unspecified\n");
780                         return NULL;
781                 }
782         } else
783                 table = config_table;
784
785         args.cfg = cfg;
786         args.cat = NULL;
787         args.cat_name = NULL;
788
789         ast_mutex_lock(&mutex);
790
791         RES_SQLITE_BEGIN
792                 error = sqlite_exec_printf(db, sql_get_config_table, add_cfg_entry,
793                                         &args, &errormsg, table, file);
794         RES_SQLITE_END(error)
795
796         ast_mutex_unlock(&mutex);
797
798         ast_free(args.cat_name);
799
800         if (error) {
801                 ast_log(LOG_ERROR, "%s\n", errormsg);
802                 ast_free(errormsg);
803                 return NULL;
804         }
805
806         return cfg;
807 }
808
809 static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
810 {
811         const char **tmp, *param, *val, **params, **vals;
812         size_t params_count;
813
814         params = NULL;
815         vals = NULL;
816         params_count = 0;
817
818         while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
819                 if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
820                         ast_free(params);
821                         ast_free(vals);
822                         return 0;
823                 }
824                 params = tmp;
825
826                 if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
827                         ast_free(params);
828                         ast_free(vals);
829                         return 0;
830                 }
831                 vals = tmp;
832
833                 params[params_count] = param;
834                 vals[params_count] = val;
835                 params_count++;
836         }
837
838         if (params_count > 0) {
839                 *params_ptr = params;
840                 *vals_ptr = vals;
841         } else
842                 ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
843
844         return params_count;
845 }
846
847 static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
848 {
849         struct rt_cfg_entry_args *args;
850         struct ast_variable *var;
851         int i;
852
853         args = arg;
854
855         for (i = 0; i < argc; i++) {
856                 if (!argv[i])
857                         continue;
858
859                 if (!(var = ast_variable_new(columnNames[i], argv[i])))
860                         return 1;
861
862                 if (!args->var)
863                         args->var = var;
864
865                 if (!args->last)
866                         args->last = var;
867                 else {
868                         args->last->next = var;
869                         args->last = var;
870                 }
871         }
872
873         return 0;
874 }
875
876 static struct ast_variable *
877 realtime_handler(const char *database, const char *table, va_list ap)
878 {
879         char *query, *errormsg, *op, *tmp_str;
880         struct rt_cfg_entry_args args;
881         const char **params, **vals;
882         size_t params_count;
883         int error;
884
885         if (!table) {
886                 ast_log(LOG_WARNING, "Table name unspecified\n");
887                 return NULL;
888         }
889
890         params_count = get_params(ap, &params, &vals);
891
892         if (params_count == 0)
893                 return NULL;
894
895         op = (strchr(params[0], ' ') == NULL) ? " =" : "";
896
897 /* \cond DOXYGEN_CAN_PARSE_THIS */
898 #undef QUERY
899 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
900 /* \endcond */
901
902         query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
903
904         if (!query) {
905                 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
906                 ast_free(params);
907                 ast_free(vals);
908                 return NULL;
909         }
910
911         if (params_count > 1) {
912                 size_t i;
913
914                 for (i = 1; i < params_count; i++) {
915                         op = (strchr(params[i], ' ') == NULL) ? " =" : "";
916                         tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op,
917                                                                                                                          vals[i]);
918                         sqlite_freemem(query);
919
920                         if (!tmp_str) {
921                                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
922                                 ast_free(params);
923                                 ast_free(vals);
924                                 return NULL;
925                         }
926
927                         query = tmp_str;
928                 }
929         }
930
931         ast_free(params);
932         ast_free(vals);
933
934         tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
935         sqlite_freemem(query);
936
937         if (!tmp_str) {
938                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
939                 return NULL;
940         }
941
942         query = tmp_str;
943         ast_debug(1, "SQL query: %s\n", query);
944         args.var = NULL;
945         args.last = NULL;
946
947         ast_mutex_lock(&mutex);
948
949         RES_SQLITE_BEGIN
950                 error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
951         RES_SQLITE_END(error)
952
953         ast_mutex_unlock(&mutex);
954
955         sqlite_freemem(query);
956
957         if (error) {
958                 ast_log(LOG_WARNING, "%s\n", errormsg);
959                 ast_free(errormsg);
960                 ast_variables_destroy(args.var);
961                 return NULL;
962         }
963
964         return args.var;
965 }
966
967 static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
968 {
969         struct rt_multi_cfg_entry_args *args;
970         struct ast_category *cat;
971         struct ast_variable *var;
972         char *cat_name;
973         size_t i;
974
975         args = (struct rt_multi_cfg_entry_args *)arg;
976         cat_name = NULL;
977
978         /*
979          * cat_name should always be set here, since initfield is forged from
980          * params[0] in realtime_multi_handler(), which is a search parameter
981          * of the SQL query.
982          */
983         for (i = 0; i < argc; i++) {
984                 if (!strcmp(args->initfield, columnNames[i]))
985                         cat_name = argv[i];
986         }
987
988         if (!cat_name) {
989                 ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
990                 return 1;
991         }
992
993         if (!(cat = ast_category_new(cat_name))) {
994                 ast_log(LOG_WARNING, "Unable to allocate category\n");
995                 return 1;
996         }
997
998         ast_category_append(args->cfg, cat);
999
1000         for (i = 0; i < argc; i++) {
1001                 if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
1002                         continue;
1003
1004                 if (!(var = ast_variable_new(columnNames[i], argv[i]))) {
1005                         ast_log(LOG_WARNING, "Unable to allocate variable\n");
1006                         return 1;
1007                 }
1008
1009                 ast_variable_append(cat, var);
1010         }
1011
1012         return 0;
1013 }
1014
1015 static struct ast_config *realtime_multi_handler(const char *database, 
1016         const char *table, va_list ap)
1017 {
1018         char *query, *errormsg, *op, *tmp_str, *initfield;
1019         struct rt_multi_cfg_entry_args args;
1020         const char **params, **vals;
1021         struct ast_config *cfg;
1022         size_t params_count;
1023         int error;
1024
1025         if (!table) {
1026                 ast_log(LOG_WARNING, "Table name unspecified\n");
1027                 return NULL;
1028         }
1029
1030         if (!(cfg = ast_config_new())) {
1031                 ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
1032                 return NULL;
1033         }
1034
1035         if (!(params_count = get_params(ap, &params, &vals))) {
1036                 ast_config_destroy(cfg);
1037                 return NULL;
1038         }
1039
1040         if (!(initfield = ast_strdup(params[0]))) {
1041                 ast_config_destroy(cfg);
1042                 ast_free(params);
1043                 ast_free(vals);
1044                 return NULL;
1045         }
1046
1047         tmp_str = strchr(initfield, ' ');
1048
1049         if (tmp_str)
1050                 *tmp_str = '\0';
1051
1052         op = (!strchr(params[0], ' ')) ? " =" : "";
1053
1054         /*
1055          * Asterisk sends us an already escaped string when searching for
1056          * "exten LIKE" (uh!). Handle it separately.
1057          */
1058         tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
1059
1060 /* \cond DOXYGEN_CAN_PARSE_THIS */
1061 #undef QUERY
1062 #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
1063 /* \endcond */
1064
1065         if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
1066                 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1067                 ast_config_destroy(cfg);
1068                 ast_free(params);
1069                 ast_free(vals);
1070                 ast_free(initfield);
1071                 return NULL;
1072         }
1073
1074         if (params_count > 1) {
1075                 size_t i;
1076
1077                 for (i = 1; i < params_count; i++) {
1078                         op = (!strchr(params[i], ' ')) ? " =" : "";
1079                         tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op,
1080                                                                                                                          vals[i]);
1081                         sqlite_freemem(query);
1082
1083                         if (!tmp_str) {
1084                                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1085                                 ast_config_destroy(cfg);
1086                                 ast_free(params);
1087                                 ast_free(vals);
1088                                 ast_free(initfield);
1089                                 return NULL;
1090                         }
1091
1092                         query = tmp_str;
1093                 }
1094         }
1095
1096         ast_free(params);
1097         ast_free(vals);
1098
1099         if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
1100                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1101                 ast_config_destroy(cfg);
1102                 ast_free(initfield);
1103                 return NULL;
1104         }
1105
1106         sqlite_freemem(query);
1107         query = tmp_str;
1108         ast_debug(1, "SQL query: %s\n", query);
1109         args.cfg = cfg;
1110         args.initfield = initfield;
1111
1112         ast_mutex_lock(&mutex);
1113
1114         RES_SQLITE_BEGIN
1115                 error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
1116         RES_SQLITE_END(error)
1117
1118         ast_mutex_unlock(&mutex);
1119
1120         sqlite_freemem(query);
1121         ast_free(initfield);
1122
1123         if (error) {
1124                 ast_log(LOG_WARNING, "%s\n", errormsg);
1125                 ast_free(errormsg);
1126                 ast_config_destroy(cfg);
1127                 return NULL;
1128         }
1129
1130         return cfg;
1131 }
1132
1133 static int realtime_update_handler(const char *database, const char *table,
1134         const char *keyfield, const char *entity,
1135         va_list ap)
1136 {
1137         char *query, *errormsg, *tmp_str;
1138         const char **params, **vals;
1139         size_t params_count;
1140         int error, rows_num;
1141
1142         if (!table) {
1143                 ast_log(LOG_WARNING, "Table name unspecified\n");
1144                 return -1;
1145         }
1146
1147         if (!(params_count = get_params(ap, &params, &vals)))
1148                 return -1;
1149
1150 /* \cond DOXYGEN_CAN_PARSE_THIS */
1151 #undef QUERY
1152 #define QUERY "UPDATE '%q' SET %q = '%q'"
1153 /* \endcond */
1154
1155         if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
1156                 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1157                 ast_free(params);
1158                 ast_free(vals);
1159                 return -1;
1160         }
1161
1162         if (params_count > 1) {
1163                 size_t i;
1164
1165                 for (i = 1; i < params_count; i++) {
1166                         tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i],
1167                                                                                                                          vals[i]);
1168                         sqlite_freemem(query);
1169
1170                         if (!tmp_str) {
1171                                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1172                                 ast_free(params);
1173                                 ast_free(vals);
1174                                 return -1;
1175                         }
1176
1177                         query = tmp_str;
1178                 }
1179         }
1180
1181         ast_free(params);
1182         ast_free(vals);
1183
1184         if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
1185                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1186                 return -1;
1187         }
1188
1189         sqlite_freemem(query);
1190         query = tmp_str;
1191         ast_debug(1, "SQL query: %s\n", query);
1192
1193         ast_mutex_lock(&mutex);
1194
1195         RES_SQLITE_BEGIN
1196                 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1197         RES_SQLITE_END(error)
1198
1199         if (!error)
1200                 rows_num = sqlite_changes(db);
1201         else
1202                 rows_num = -1;
1203
1204         ast_mutex_unlock(&mutex);
1205
1206         sqlite_freemem(query);
1207
1208         if (error) {
1209                 ast_log(LOG_WARNING, "%s\n", errormsg);
1210                 ast_free(errormsg);
1211         }
1212
1213         return rows_num;
1214 }
1215
1216 static int realtime_store_handler(const char *database, const char *table, va_list ap) {
1217         char *errormsg, *tmp_str, *tmp_keys, *tmp_keys2, *tmp_vals, *tmp_vals2;
1218         const char **params, **vals;
1219         size_t params_count;
1220         int error, rows_id;
1221         size_t i;
1222
1223         if (!table) {
1224                 ast_log(LOG_WARNING, "Table name unspecified\n");
1225                 return -1;
1226         }
1227
1228         if (!(params_count = get_params(ap, &params, &vals)))
1229                 return -1;
1230
1231 /* \cond DOXYGEN_CAN_PARSE_THIS */
1232 #undef QUERY
1233 #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
1234 /* \endcond */
1235
1236         tmp_keys2 = NULL;
1237         tmp_vals2 = NULL;
1238         for (i = 0; i < params_count; i++) {
1239                 if ( tmp_keys2 ) {
1240                         tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
1241                         sqlite_freemem(tmp_keys2);
1242                 } else {
1243                         tmp_keys = sqlite_mprintf("%q", params[i]);
1244                 }
1245                 if (!tmp_keys) {
1246                         ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1247                         ast_free(params);
1248                         ast_free(vals);
1249                         return -1;
1250                 }
1251
1252                 if ( tmp_vals2 ) {
1253                         tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, params[i]);
1254                         sqlite_freemem(tmp_vals2);
1255                 } else {
1256                         tmp_vals = sqlite_mprintf("'%q'", params[i]);
1257                 }
1258                 if (!tmp_vals) {
1259                         ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1260                         ast_free(params);
1261                         ast_free(vals);
1262                         return -1;
1263                 }
1264
1265
1266                 tmp_keys2 = tmp_keys;
1267                 tmp_vals2 = tmp_vals;
1268         }
1269
1270         ast_free(params);
1271         ast_free(vals);
1272
1273         if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
1274                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1275                 return -1;
1276         }
1277
1278         sqlite_freemem(tmp_keys);
1279         sqlite_freemem(tmp_vals);
1280
1281         ast_debug(1, "SQL query: %s\n", tmp_str);
1282
1283         ast_mutex_lock(&mutex);
1284
1285         RES_SQLITE_BEGIN
1286                 error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
1287         RES_SQLITE_END(error)
1288
1289         if (!error) {
1290                 rows_id = sqlite_last_insert_rowid(db);
1291         } else {
1292                 rows_id = -1;
1293         }
1294
1295         ast_mutex_unlock(&mutex);
1296
1297         sqlite_freemem(tmp_str);
1298
1299         if (error) {
1300                 ast_log(LOG_WARNING, "%s\n", errormsg);
1301                 ast_free(errormsg);
1302         }
1303
1304         return rows_id;
1305 }
1306
1307 static int realtime_destroy_handler(const char *database, const char *table,
1308         const char *keyfield, const char *entity,
1309         va_list ap)
1310 {
1311         char *query, *errormsg, *tmp_str;
1312         const char **params, **vals;
1313         size_t params_count;
1314         int error, rows_num;
1315         size_t i;
1316
1317         if (!table) {
1318                 ast_log(LOG_WARNING, "Table name unspecified\n");
1319                 return -1;
1320         }
1321
1322         if (!(params_count = get_params(ap, &params, &vals)))
1323                 return -1;
1324
1325 /* \cond DOXYGEN_CAN_PARSE_THIS */
1326 #undef QUERY
1327 #define QUERY "DELETE FROM '%q' WHERE"
1328 /* \endcond */
1329
1330         if (!(query = sqlite_mprintf(QUERY, table))) {
1331                 ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
1332                 ast_free(params);
1333                 ast_free(vals);
1334                 return -1;
1335         }
1336
1337         for (i = 0; i < params_count; i++) {
1338                 tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
1339                 sqlite_freemem(query);
1340
1341                 if (!tmp_str) {
1342                         ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1343                         ast_free(params);
1344                         ast_free(vals);
1345                         return -1;
1346                 }
1347
1348                 query = tmp_str;
1349         }
1350
1351         ast_free(params);
1352         ast_free(vals);
1353         if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
1354                 ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
1355                 return -1;
1356         }
1357         sqlite_freemem(query);
1358         query = tmp_str;
1359
1360         ast_debug(1, "SQL query: %s\n", query);
1361
1362         ast_mutex_lock(&mutex);
1363
1364         RES_SQLITE_BEGIN
1365                 error = sqlite_exec(db, query, NULL, NULL, &errormsg);
1366         RES_SQLITE_END(error)
1367
1368         if (!error)
1369                 rows_num = sqlite_changes(db);
1370         else
1371                 rows_num = -1;
1372
1373         ast_mutex_unlock(&mutex);
1374
1375         sqlite_freemem(query);
1376
1377         if (error) {
1378                 ast_log(LOG_WARNING, "%s\n", errormsg);
1379                 ast_free(errormsg);
1380         }
1381
1382         return rows_num;
1383 }
1384
1385
1386 static int cli_status(int fd, int argc, char *argv[])
1387 {
1388         ast_cli(fd, "SQLite database path: %s\n", dbfile);
1389         ast_cli(fd, "config_table: ");
1390
1391         if (!config_table)
1392                 ast_cli(fd, "unspecified, must be present in extconfig.conf\n");
1393         else
1394                 ast_cli(fd, "%s\n", config_table);
1395
1396         ast_cli(fd, "cdr_table: ");
1397
1398         if (!cdr_table)
1399                 ast_cli(fd, "unspecified, CDR support disabled\n");
1400         else
1401                 ast_cli(fd, "%s\n", cdr_table);
1402
1403         return RESULT_SUCCESS;
1404 }
1405
1406 static int unload_module(void)
1407 {
1408         if (cli_status_registered)
1409                 ast_cli_unregister(&cli_status_cmd);
1410
1411         if (cdr_registered)
1412                 ast_cdr_unregister(RES_SQLITE_NAME);
1413
1414         ast_config_engine_deregister(&sqlite_engine);
1415
1416         if (db)
1417                 sqlite_close(db);
1418
1419         unload_config();
1420
1421         return 0;
1422 }
1423
1424 static int load_module(void)
1425 {
1426         char *errormsg;
1427         int error;
1428
1429         db = NULL;
1430         cdr_registered = 0;
1431         cli_status_registered = 0;
1432         dbfile = NULL;
1433         config_table = NULL;
1434         cdr_table = NULL;
1435         vm_count = 0;
1436         error = load_config();
1437
1438         if (error)
1439                 return AST_MODULE_LOAD_DECLINE;
1440
1441         if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
1442                 ast_log(LOG_ERROR, "%s\n", errormsg);
1443                 ast_free(errormsg);
1444                 unload_module();
1445                 return 1;
1446         }
1447
1448         ast_config_engine_register(&sqlite_engine);
1449
1450         if (use_cdr) {
1451                 RES_SQLITE_BEGIN
1452                         error = sqlite_exec_printf(db, "SELECT COUNT(id) FROM %Q;", NULL, NULL,
1453                                                                                                                                  &errormsg, cdr_table);
1454                 RES_SQLITE_END(error)
1455
1456                 if (error) {
1457                         /*
1458                          * Unexpected error.
1459                          */
1460                         if (error != SQLITE_ERROR) {
1461                                 ast_log(LOG_ERROR, "%s\n", errormsg);
1462                                 ast_free(errormsg);
1463                                 unload_module();
1464                                 return 1;
1465                         }
1466
1467                         RES_SQLITE_BEGIN
1468                                 error = sqlite_exec_printf(db, sql_create_cdr_table, NULL, NULL,
1469                                                                 &errormsg, cdr_table);
1470                         RES_SQLITE_END(error)
1471
1472                         if (error) {
1473                                 ast_log(LOG_ERROR, "%s\n", errormsg);
1474                                 ast_free(errormsg);
1475                                 unload_module();
1476                                 return 1;
1477                         }
1478                 }
1479
1480                 error = ast_cdr_register(RES_SQLITE_NAME, RES_SQLITE_DESCRIPTION,
1481                                                                                                                  cdr_handler);
1482
1483                 if (error) {
1484                         unload_module();
1485                         return 1;
1486                 }
1487
1488                 cdr_registered = 1;
1489         }
1490
1491         error = ast_cli_register(&cli_status_cmd);
1492
1493         if (error) {
1494                 unload_module();
1495                 return 1;
1496         }
1497
1498         cli_status_registered = 1;
1499
1500         return 0;
1501 }
1502
1503 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Realtime SQLite configuration",
1504                 .load = load_module,
1505                 .unload = unload_module,
1506 );