Merge changes from team/russell/sqlite:
authorRussell Bryant <russell@russellbryant.com>
Tue, 13 Mar 2007 21:22:33 +0000 (21:22 +0000)
committerRussell Bryant <russell@russellbryant.com>
Tue, 13 Mar 2007 21:22:33 +0000 (21:22 +0000)
* Add new module, cdr_sqlite3_custom which allows logging custom CDRs into a
  SQLite3 database.  (issue #7149, alerios)
* Add new module, res_config_sqlite, which adds realtime database configuration
  support for SQLite version 2.  I decided that this was ok since we didn't have
  any realtime support for version 3.  If someone ports this to version 3, then
  version 2 support can be removed or marked deprecated.
  (issue #7790, rbarun_proformatique)
* Mark cdr_sqlite as deprecated in favor of cdr_sqlite3_custom.

Also, note that there were other modules on the bug tracker that did not make
the cut because they provided some duplicated functionality.  Those are:

* cdr_sqlite3 (issue #6754, moy)
* cdr_sqlite3 (issue #8694, bsd)

git-svn-id: https://origsvn.digium.com/svn/asterisk/trunk@58866 65c4cc65-6c06-0410-ace0-fbb531ad65f3

14 files changed:
CHANGES
UPGRADE.txt
build_tools/menuselect-deps.in
cdr/cdr_sqlite.c
cdr/cdr_sqlite3_custom.c [new file with mode: 0644]
configs/cdr_sqlite3_custom.conf [new file with mode: 0644]
configs/extconfig.conf.sample
configs/res_config_sqlite.conf [new file with mode: 0644]
configure
configure.ac
doc/res_config_sqlite.txt [new file with mode: 0644]
include/asterisk/autoconfig.h.in
makeopts.in
res/res_config_sqlite.c [new file with mode: 0644]

diff --git a/CHANGES b/CHANGES
index cf3f04e..3f62445 100644 (file)
--- a/CHANGES
+++ b/CHANGES
@@ -66,6 +66,8 @@ Miscellaneous
   * Added the parkedcallreparking option to features.conf
   * SMDI is now enabled in voicemail using the smdienable option.
   * Added zap show version CLI command to chan_zap.
+  * Added a new CDR module, cdr_sqlite3_custom.
+  * Added a new realtime configuration module, res_config_sqlite
 
 AMI - The manager (TCP/TLS/HTTP)
 --------------------------------
index e14d4fe..0ed1d3b 100644 (file)
@@ -36,3 +36,9 @@ Applications:
   performs mostly a 'ChanExists' sort of function.
 * SetCallerPres() has been replaced with the CALLERPRES() dialplan function
   and is now deprecated.
+
+CDR:
+
+* The cdr_sqlite module has been marked as deprecated in favor of
+  cdr_sqlite3_custom.  It will potentially be removed from the tree
+  after Asterisk 1.6 is released.
index f0f343e..fd5b22e 100644 (file)
@@ -23,6 +23,7 @@ QT=@PBX_QT@
 RADIUS=@PBX_RADIUS@
 SPEEX=@PBX_SPEEX@
 SQLITE=@PBX_SQLITE@
+SQLITE3=@PBX_SQLITE3@
 SSL=@PBX_OPENSSL@
 TONEZONE=@PBX_TONEZONE@
 UNIXODBC=@PBX_UNIXODBC@
index bcc50aa..bd232b4 100644 (file)
@@ -30,6 +30,8 @@
  * 
  * Creates the database and table on-the-fly
  * \ingroup cdr_drivers
+ *
+ * \note This module has been marked deprecated in favor for cdr_sqlite3_custom
  */
 
 /*** MODULEINFO
@@ -180,6 +182,9 @@ static int load_module(void)
        char fn[PATH_MAX];
        int res;
 
+       ast_log(LOG_WARNING, "This module has been marked deprecated in favor of "
+               "using cdr_sqlite3_custom. (May be removed after Asterisk 1.6)\n");
+
        /* is the database there? */
        snprintf(fn, sizeof(fn), "%s/cdr.db", ast_config_AST_LOG_DIR);
        db = sqlite_open(fn, AST_FILE_MODE, &zErr);
diff --git a/cdr/cdr_sqlite3_custom.c b/cdr/cdr_sqlite3_custom.c
new file mode 100644 (file)
index 0000000..c3dcbd2
--- /dev/null
@@ -0,0 +1,264 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 1999 - 2007, Digium, Inc.
+ *
+ * Mark Spencer <markster@digium.com> and others.
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ *
+ * \brief Custom SQLite3 CDR records.
+ *
+ * \author Adapted by Alejandro Rios <alejandro.rios@avatar.com.co> and
+ *  Russell Bryant <russell@digium.com> from 
+ *  cdr_mysql_custom by Edward Eastman <ed@dm3.co.uk>,
+ *     and cdr_sqlite by Holger Schurig <hs4233@mail.mn-solutions.de>
+ *     
+ *
+ * \arg See also \ref AstCDR
+ *
+ *
+ * \ingroup cdr_drivers
+ */
+
+/*** MODULEINFO
+       <depend>sqlite3</depend>
+ ***/
+
+#include "asterisk.h"
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sqlite3.h>
+
+#include "asterisk/channel.h"
+#include "asterisk/cdr.h"
+#include "asterisk/module.h"
+#include "asterisk/config.h"
+#include "asterisk/pbx.h"
+#include "asterisk/logger.h"
+#include "asterisk/utils.h"
+#include "asterisk/cli.h"
+#include "asterisk/options.h"
+
+AST_MUTEX_DEFINE_STATIC(lock);
+
+static const char config_file[] = "cdr_sqlite3_custom.conf";
+
+static char *desc = "Customizable SQLite3 CDR Backend";
+static char *name = "cdr_sqlite3_custom";
+static sqlite3 *db = NULL;
+
+static char table[80];
+static char columns[1024];
+static char values[1024];
+
+static int load_config(int reload)
+{
+       struct ast_config *cfg;
+       struct ast_variable *mappingvar;
+       const char *tmp;
+
+       if (!(cfg = ast_config_load(config_file))) {
+               if (reload)
+                       ast_log(LOG_WARNING, "%s: Failed to reload configuration file.\n", name);
+               else {
+                       ast_log(LOG_WARNING,
+                                       "%s: Failed to load configuration file. Module not activated.\n",
+                                       name);
+               }
+               return -1;
+       }
+
+       if (!reload)
+               ast_mutex_lock(&lock);
+
+       if (!(mappingvar = ast_variable_browse(cfg, "master"))) {
+               /* nothing configured */
+               ast_config_destroy(cfg);
+               return 0;
+       }
+       
+       /* Mapping must have a table name */
+       tmp = ast_variable_retrieve(cfg, "master", "table");
+       if (!ast_strlen_zero(tmp))
+               ast_copy_string(table, tmp, sizeof(table));
+       else {
+               ast_log(LOG_WARNING, "%s: Table name not specified.  Assuming cdr.\n", name);
+               strcpy(table, "cdr");
+       }
+
+       tmp = ast_variable_retrieve(cfg, "master", "columns");
+       if (!ast_strlen_zero(tmp))
+               ast_copy_string(columns, tmp, sizeof(columns));
+       else {
+               ast_log(LOG_WARNING, "%s: Column names not specified. Module not loaded.\n",
+                               name);
+               ast_config_destroy(cfg);
+               return -1;
+       }
+
+       tmp = ast_variable_retrieve(cfg, "master", "values");
+       if (!ast_strlen_zero(tmp))
+               ast_copy_string(values, tmp, sizeof(values));
+       else {
+               ast_log(LOG_WARNING, "%s: Values not specified. Module not loaded.\n", name);
+               ast_config_destroy(cfg);
+               return -1;
+       }
+
+       if (!reload)
+               ast_mutex_unlock(&lock);
+
+       ast_config_destroy(cfg);
+
+       return 0;
+}
+
+/* assumues 'to' buffer is at least strlen(from) * 2 + 1 bytes */
+static int do_escape(char *to, const char *from)
+{
+       char *out = to;
+
+       for (; *from; from++) {
+               if (*from == '\'' || *from == '\\')
+                       *out++ = *from;
+               *out++ = *from;
+       }
+       *out = '\0';
+
+       return 0;
+}
+
+static int sqlite3_log(struct ast_cdr *cdr)
+{
+       int res = 0;
+       char *zErr = 0;
+       char *sql_cmd;
+       struct ast_channel dummy = { 0, };
+       int count;
+
+       { /* Make it obvious that only sql_cmd should be used outside of this block */
+               char *sql_tmp_cmd;
+               char sql_insert_cmd[2048] = "";
+               sql_tmp_cmd = sqlite3_mprintf("INSERT INTO %q (%q) VALUES (%q)", table, columns, values);
+               dummy.cdr = cdr;
+               pbx_substitute_variables_helper(&dummy, sql_tmp_cmd, sql_insert_cmd, sizeof(sql_insert_cmd) - 1);
+               sqlite3_free(sql_tmp_cmd);
+               sql_cmd = alloca(strlen(sql_insert_cmd) * 2 + 1);
+               do_escape(sql_cmd, sql_insert_cmd);
+       }
+
+       ast_mutex_lock(&lock);
+
+       for (count = 0; count < 5; count++) {
+               res = sqlite3_exec(db, sql_cmd, NULL, NULL, &zErr);
+               if (res != SQLITE_BUSY && res != SQLITE_LOCKED)
+                       break;
+               usleep(200);
+       }
+
+       if (zErr) {
+               ast_log(LOG_ERROR, "%s: %s. sentence: %s.\n", name, zErr, sql_cmd);
+               sqlite3_free(zErr);
+       }
+
+       ast_mutex_unlock(&lock);
+
+       return res;
+}
+
+static int unload_module(void)
+{
+       if (db)
+               sqlite3_close(db);
+
+       ast_cdr_unregister(name);
+
+       return 0;
+}
+
+static int load_module(void)
+{
+       char *zErr;
+       char fn[PATH_MAX];
+       int res;
+       char *sql_cmd;
+
+       if (!load_config(0)) {
+               res = ast_cdr_register(name, desc, sqlite3_log);
+               if (res) {
+                       ast_log(LOG_ERROR, "%s: Unable to register custom SQLite3 CDR handling\n", name);
+                       return AST_MODULE_LOAD_DECLINE;
+               }
+       }
+
+       /* is the database there? */
+       snprintf(fn, sizeof(fn), "%s/master.db", ast_config_AST_LOG_DIR);
+       res = sqlite3_open(fn, &db);
+       if (!db) {
+               ast_log(LOG_ERROR, "%s: Could not open database %s.\n", name, fn);
+               sqlite3_free(zErr);
+               return AST_MODULE_LOAD_DECLINE;
+       }
+
+       /* is the table there? */
+       sql_cmd = sqlite3_mprintf("SELECT COUNT(AcctId) FROM %q;", table);
+       res = sqlite3_exec(db, sql_cmd, NULL, NULL, NULL);
+       sqlite3_free(sql_cmd);
+       if (res) {
+               sql_cmd = sqlite3_mprintf("CREATE TABLE %q (AcctId INTEGER PRIMARY KEY,%q)", table, columns);
+               res = sqlite3_exec(db, sql_cmd, NULL, NULL, &zErr);
+               sqlite3_free(sql_cmd);
+               if (zErr) {
+                       ast_log(LOG_WARNING, "%s: %s.\n", name, zErr);
+                       sqlite3_free(zErr);
+                       return 0;
+               }
+
+               if (res) {
+                       ast_log(LOG_ERROR, "%s: Unable to create table '%s': %s.\n", name, table, zErr);
+                       sqlite3_free(zErr);
+                       if (db)
+                               sqlite3_close(db);
+                       return AST_MODULE_LOAD_DECLINE;
+               }
+       }
+
+       return 0;
+}
+
+static int reload(void)
+{
+       int res;
+
+       ast_mutex_lock(&lock);
+       res = load_config(1);
+       ast_mutex_unlock(&lock);
+
+       return res;
+}
+
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "SQLite3 Custom CDR Module",
+       .load = load_module,
+       .unload = unload_module,
+       .reload = reload,
+);
diff --git a/configs/cdr_sqlite3_custom.conf b/configs/cdr_sqlite3_custom.conf
new file mode 100644 (file)
index 0000000..55872b3
--- /dev/null
@@ -0,0 +1,7 @@
+;
+; Mappings for custom config file
+;
+[master] ; currently, only file "master.db" is supported, with only one table at a time.
+table  => cdr
+columns        => calldate, clid, dcontext, channel, dstchannel, lastapp, lastdata, duration, billsec, disposition, amaflags, accountcode, uniqueid, userfield, test
+values => '${CDR(start)}','${CDR(clid)}','${CDR(dcontext)}','${CDR(channel)}','${CDR(dstchannel)}','${CDR(lastapp)}','${CDR(lastdata)}','${CDR(duration)}','${CDR(billsec)}','${CDR(disposition)}','${CDR(amaflags)}','${CDR(accountcode)}','${CDR(uniqueid)}','${CDR(userfield)}','${CDR(test)}'
index 0266ddc..82f33f8 100644 (file)
@@ -18,6 +18,7 @@
 ;uncomment to load queues.conf via the odbc engine.
 ;
 ;queues.conf => odbc,asterisk,ast_config
+;extensions.conf => sqlite,asterisk,ast_config
 ;
 ; The following files CANNOT be loaded from Realtime storage:
 ;      asterisk.conf
 ;example => odbc,asterisk,alttable
 ;example2 => ldap,"dc=oxymium,dc=net",example2
 ;
+; "odbc" is shown in the examples below, but is not the only valid realtime
+; engine.  There is:
+;    odbc ... res_config_odbc
+;    sqlite ... res_config_sqlite
+;    pgsql ... res_config_pgsql
+;
 ;iaxusers => odbc,asterisk
 ;iaxpeers => odbc,asterisk
 ;sipusers => odbc,asterisk
diff --git a/configs/res_config_sqlite.conf b/configs/res_config_sqlite.conf
new file mode 100644 (file)
index 0000000..87f1e08
--- /dev/null
@@ -0,0 +1,15 @@
+[general]
+
+; The database file.
+dbfile => /var/lib/asterisk/sqlite.db
+
+; Both config_table and cdr_table are optional. If config_table is omitted,
+; you must specify it in extconfig.conf. If it is both provided here and in
+; extconfig.conf, the value given here is used. If cdr_table is omitted, CDR
+; support is simply disabled.
+config_table => ast_config
+cdr_table => ast_cdr
+
+; This parameter controls the registration of the SQLITE() Dialplan application.
+app_enable => yes
+
index 93c395c..99f6c43 100755 (executable)
--- a/configure
+++ b/configure
@@ -1,5 +1,5 @@
 #! /bin/sh
-# From configure.ac Revision: 57557 .
+# From configure.ac Revision: 58858 .
 # Guess values for system-dependent variables and create Makefiles.
 # Generated by GNU Autoconf 2.60.
 #
@@ -819,6 +819,10 @@ SQLITE_LIB
 SQLITE_INCLUDE
 SQLITE_DIR
 PBX_SQLITE
+SQLITE3_LIB
+SQLITE3_INCLUDE
+SQLITE3_DIR
+PBX_SQLITE3
 SUPPSERV_LIB
 SUPPSERV_INCLUDE
 SUPPSERV_DIR
@@ -1520,6 +1524,7 @@ Optional Packages:
   --with-radius=PATH      use Radius Client files in PATH
   --with-speex=PATH       use Speex files in PATH
   --with-sqlite=PATH      use SQLite files in PATH
+  --with-sqlite3=PATH     use SQLite files in PATH
   --with-suppserv=PATH    use mISDN Supplemental Services files in PATH
   --with-ssl=PATH         use OpenSSL files in PATH
   --with-tds=PATH         use FreeTDS files in PATH
@@ -8820,6 +8825,34 @@ PBX_SQLITE=0
 
 
 
+SQLITE3_DESCRIP="SQLite"
+SQLITE3_OPTION="sqlite3"
+
+# Check whether --with-sqlite3 was given.
+if test "${with_sqlite3+set}" = set; then
+  withval=$with_sqlite3;
+case ${withval} in
+     n|no)
+     USE_SQLITE3=no
+     ;;
+     y|ye|yes)
+     ac_mandatory_list="${ac_mandatory_list} SQLITE3"
+     ;;
+     *)
+     SQLITE3_DIR="${withval}"
+     ac_mandatory_list="${ac_mandatory_list} SQLITE3"
+     ;;
+esac
+
+fi
+
+PBX_SQLITE3=0
+
+
+
+
+
+
 SUPPSERV_DESCRIP="mISDN Supplemental Services"
 SUPPSERV_OPTION="suppserv"
 
 
 
 
+if test "x${PBX_SQLITE3}" != "x1" -a "${USE_SQLITE3}" != "no"; then
+   pbxlibdir=""
+   if test "x${SQLITE3_DIR}" != "x"; then
+      if test -d ${SQLITE3_DIR}/lib; then
+        pbxlibdir="-L${SQLITE3_DIR}/lib"
+      else
+        pbxlibdir="-L${SQLITE3_DIR}"
+      fi
+   fi
+   pbxfuncname="sqlite3_open"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_SQLITE3_FOUND=yes
+   else
+      as_ac_Lib=`echo "ac_cv_lib_sqlite3_${pbxfuncname}" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for ${pbxfuncname} in -lsqlite3" >&5
+echo $ECHO_N "checking for ${pbxfuncname} in -lsqlite3... $ECHO_C" >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lsqlite3 ${pbxlibdir}  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+        { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+        { ac_try='test -s conftest$ac_exeext'
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  eval "$as_ac_Lib=yes"
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       eval "$as_ac_Lib=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+ac_res=`eval echo '${'$as_ac_Lib'}'`
+              { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_Lib'}'` = yes; then
+  AST_SQLITE3_FOUND=yes
+else
+  AST_SQLITE3_FOUND=no
+fi
+
+   fi
+
+   if test "${AST_SQLITE3_FOUND}" = "yes"; then
+      SQLITE3_LIB="-lsqlite3 "
+      SQLITE3_HEADER_FOUND="1"
+      if test "x${SQLITE3_DIR}" != "x"; then
+         SQLITE3_LIB="${pbxlibdir} ${SQLITE3_LIB}"
+        SQLITE3_INCLUDE="-I${SQLITE3_DIR}/include"
+        saved_cppflags="${CPPFLAGS}"
+        CPPFLAGS="${CPPFLAGS} -I${SQLITE3_DIR}/include"
+        if test "xsqlite3.h" != "x" ; then
+           as_ac_Header=`echo "ac_cv_header_${SQLITE3_DIR}/include/sqlite3.h" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+  { echo "$as_me:$LINENO: checking for ${SQLITE3_DIR}/include/sqlite3.h" >&5
+echo $ECHO_N "checking for ${SQLITE3_DIR}/include/sqlite3.h... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+              { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+  # Is the header compilable?
+{ echo "$as_me:$LINENO: checking ${SQLITE3_DIR}/include/sqlite3.h usability" >&5
+echo $ECHO_N "checking ${SQLITE3_DIR}/include/sqlite3.h usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+#include <${SQLITE3_DIR}/include/sqlite3.h>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+        { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+        { ac_try='test -s conftest.$ac_objext'
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_header_compiler=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking ${SQLITE3_DIR}/include/sqlite3.h presence" >&5
+echo $ECHO_N "checking ${SQLITE3_DIR}/include/sqlite3.h presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <${SQLITE3_DIR}/include/sqlite3.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_c_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+  ac_header_preproc=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So?  What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+  yes:no: )
+    { echo "$as_me:$LINENO: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
+    { echo "$as_me:$LINENO: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: proceeding with the compiler's result" >&2;}
+    ac_header_preproc=yes
+    ;;
+  no:yes:* )
+    { echo "$as_me:$LINENO: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: present but cannot be compiled" >&5
+echo "$as_me: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: present but cannot be compiled" >&2;}
+    { echo "$as_me:$LINENO: WARNING: ${SQLITE3_DIR}/include/sqlite3.h:     check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: ${SQLITE3_DIR}/include/sqlite3.h:     check for missing prerequisite headers?" >&2;}
+    { echo "$as_me:$LINENO: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: see the Autoconf documentation" >&2;}
+    { echo "$as_me:$LINENO: WARNING: ${SQLITE3_DIR}/include/sqlite3.h:     section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: ${SQLITE3_DIR}/include/sqlite3.h:     section \"Present But Cannot Be Compiled\"" >&2;}
+    { echo "$as_me:$LINENO: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: proceeding with the preprocessor's result" >&2;}
+    { echo "$as_me:$LINENO: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: ${SQLITE3_DIR}/include/sqlite3.h: in the future, the compiler will take precedence" >&2;}
+
+    ;;
+esac
+{ echo "$as_me:$LINENO: checking for ${SQLITE3_DIR}/include/sqlite3.h" >&5
+echo $ECHO_N "checking for ${SQLITE3_DIR}/include/sqlite3.h... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+              { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+  SQLITE3_HEADER_FOUND=1
+else
+  SQLITE3_HEADER_FOUND=0
+fi
+
+
+        fi
+        CPPFLAGS="${saved_cppflags}"
+      else
+        if test "xsqlite3.h" != "x" ; then
+            if test "${ac_cv_header_sqlite3_h+set}" = set; then
+  { echo "$as_me:$LINENO: checking for sqlite3.h" >&5
+echo $ECHO_N "checking for sqlite3.h... $ECHO_C" >&6; }
+if test "${ac_cv_header_sqlite3_h+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_sqlite3_h" >&5
+echo "${ECHO_T}$ac_cv_header_sqlite3_h" >&6; }
+else
+  # Is the header compilable?
+{ echo "$as_me:$LINENO: checking sqlite3.h usability" >&5
+echo $ECHO_N "checking sqlite3.h usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+#include <sqlite3.h>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+        { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+        { ac_try='test -s conftest.$ac_objext'
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_header_compiler=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking sqlite3.h presence" >&5
+echo $ECHO_N "checking sqlite3.h presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <sqlite3.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_c_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+  ac_header_preproc=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So?  What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+  yes:no: )
+    { echo "$as_me:$LINENO: WARNING: sqlite3.h: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: sqlite3.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
+    { echo "$as_me:$LINENO: WARNING: sqlite3.h: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: sqlite3.h: proceeding with the compiler's result" >&2;}
+    ac_header_preproc=yes
+    ;;
+  no:yes:* )
+    { echo "$as_me:$LINENO: WARNING: sqlite3.h: present but cannot be compiled" >&5
+echo "$as_me: WARNING: sqlite3.h: present but cannot be compiled" >&2;}
+    { echo "$as_me:$LINENO: WARNING: sqlite3.h:     check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: sqlite3.h:     check for missing prerequisite headers?" >&2;}
+    { echo "$as_me:$LINENO: WARNING: sqlite3.h: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: sqlite3.h: see the Autoconf documentation" >&2;}
+    { echo "$as_me:$LINENO: WARNING: sqlite3.h:     section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: sqlite3.h:     section \"Present But Cannot Be Compiled\"" >&2;}
+    { echo "$as_me:$LINENO: WARNING: sqlite3.h: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: sqlite3.h: proceeding with the preprocessor's result" >&2;}
+    { echo "$as_me:$LINENO: WARNING: sqlite3.h: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: sqlite3.h: in the future, the compiler will take precedence" >&2;}
+
+    ;;
+esac
+{ echo "$as_me:$LINENO: checking for sqlite3.h" >&5
+echo $ECHO_N "checking for sqlite3.h... $ECHO_C" >&6; }
+if test "${ac_cv_header_sqlite3_h+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_cv_header_sqlite3_h=$ac_header_preproc
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_sqlite3_h" >&5
+echo "${ECHO_T}$ac_cv_header_sqlite3_h" >&6; }
+
+fi
+if test $ac_cv_header_sqlite3_h = yes; then
+  SQLITE3_HEADER_FOUND=1
+else
+  SQLITE3_HEADER_FOUND=0
+fi
+
+
+        fi
+      fi
+      if test "x${SQLITE3_HEADER_FOUND}" = "x0" ; then
+         SQLITE3_LIB=""
+         SQLITE3_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then                # only checking headers -> no library
+           SQLITE3_LIB=""
+        fi
+         PBX_SQLITE3=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_SQLITE3 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_SQLITE3_VERSION
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+
 if test "x${PBX_OPENSSL}" != "x1" -a "${USE_OPENSSL}" != "no"; then
    pbxlibdir=""
    if test "x${OPENSSL_DIR}" != "x"; then
@@ -39371,6 +39859,10 @@ SQLITE_LIB!$SQLITE_LIB$ac_delim
 SQLITE_INCLUDE!$SQLITE_INCLUDE$ac_delim
 SQLITE_DIR!$SQLITE_DIR$ac_delim
 PBX_SQLITE!$PBX_SQLITE$ac_delim
+SQLITE3_LIB!$SQLITE3_LIB$ac_delim
+SQLITE3_INCLUDE!$SQLITE3_INCLUDE$ac_delim
+SQLITE3_DIR!$SQLITE3_DIR$ac_delim
+PBX_SQLITE3!$PBX_SQLITE3$ac_delim
 SUPPSERV_LIB!$SUPPSERV_LIB$ac_delim
 SUPPSERV_INCLUDE!$SUPPSERV_INCLUDE$ac_delim
 SUPPSERV_DIR!$SUPPSERV_DIR$ac_delim
@@ -39441,10 +39933,6 @@ OPENH323_SUFFIX!$OPENH323_SUFFIX$ac_delim
 OPENH323_BUILD!$OPENH323_BUILD$ac_delim
 QTMOC!$QTMOC$ac_delim
 EDITLINE_LIB!$EDITLINE_LIB$ac_delim
-PBX_H323!$PBX_H323$ac_delim
-PBX_IXJUSER!$PBX_IXJUSER$ac_delim
-GTKCONFIG!$GTKCONFIG$ac_delim
-PBX_GTK!$PBX_GTK$ac_delim
 _ACEOF
 
   if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 97; then
@@ -39486,13 +39974,17 @@ _ACEOF
 ac_delim='%!_!# '
 for ac_last_try in false false false false false :; do
   cat >conf$$subs.sed <<_ACEOF
+PBX_H323!$PBX_H323$ac_delim
+PBX_IXJUSER!$PBX_IXJUSER$ac_delim
+GTKCONFIG!$GTKCONFIG$ac_delim
+PBX_GTK!$PBX_GTK$ac_delim
 GTK_INCLUDE!$GTK_INCLUDE$ac_delim
 GTK_LIB!$GTK_LIB$ac_delim
 CURL_CONFIG!$CURL_CONFIG$ac_delim
 LTLIBOBJS!$LTLIBOBJS$ac_delim
 _ACEOF
 
-  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 4; then
+  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 8; then
     break
   elif $ac_last_try; then
     { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
index 2039153..0f6acbf 100644 (file)
@@ -210,6 +210,7 @@ AST_EXT_LIB_SETUP([QT], [Qt], [qt])
 AST_EXT_LIB_SETUP([RADIUS], [Radius Client], [radius])
 AST_EXT_LIB_SETUP([SPEEX], [Speex], [speex])
 AST_EXT_LIB_SETUP([SQLITE], [SQLite], [sqlite])
+AST_EXT_LIB_SETUP([SQLITE3], [SQLite], [sqlite3])
 AST_EXT_LIB_SETUP([SUPPSERV], [mISDN Supplemental Services], [suppserv])
 AST_EXT_LIB_SETUP([OPENSSL], [OpenSSL], [ssl])
 AST_EXT_LIB_SETUP([FREETDS], [FreeTDS], [tds])
@@ -832,6 +833,8 @@ AST_EXT_LIB_CHECK([SPEEX], [speex], [speex_encode], [speex/speex.h], [-lm])
 
 AST_EXT_LIB_CHECK([SQLITE], [sqlite], [sqlite_exec], [sqlite.h])
 
+AST_EXT_LIB_CHECK([SQLITE3], [sqlite3], [sqlite3_open], [sqlite3.h])
+
 AST_EXT_LIB_CHECK([OPENSSL], [ssl], [ssl2_connect], [openssl/ssl.h], [-lcrypto])
 
 AST_EXT_LIB_CHECK([FREETDS], [tds], [tds_version], [tds.h])
diff --git a/doc/res_config_sqlite.txt b/doc/res_config_sqlite.txt
new file mode 100644 (file)
index 0000000..682dbaa
--- /dev/null
@@ -0,0 +1,117 @@
+/*
+ * res_sqlite - SQLite 2 support for Asterisk
+ * 
+ * This module can be used as a static/RealTime configuration module, and a CDR
+ * handler.  See the Doxygen documentation for a detailed description of the 
+ * module, and the configs/ directory for the sample configuration file.
+ */
+
+/*
+ * Tables for res_config_sqlite.so.
+ */
+
+/*
+ * RealTime static table.
+ */
+CREATE TABLE ast_config
+(
+ id INTEGER PRIMARY KEY,
+ commented INT(11) NOT NULL DEFAULT '0',
+ filename VARCHAR(128) NOT NULL,
+ category VARCHAR(128) NOT NULL,
+ var_name VARCHAR(128) NOT NULL,
+ var_val VARCHAR(128) NOT NULL
+);
+
+CREATE INDEX ast_config_filename_commented ON ast_config(filename, commented);
+
+/*
+ * CDR table (this table is automatically created if non existent).
+ * 
+ * CREATE TABLE ast_cdr
+ * (
+ *  id INTEGER PRIMARY KEY,
+ *  clid VARCHAR(80) NOT NULL DEFAULT '',
+ *  src VARCHAR(80) NOT NULL DEFAULT '',
+ *  dst VARCHAR(80) NOT NULL DEFAULT '',
+ *  dcontext VARCHAR(80) NOT NULL DEFAULT '',
+ *  channel VARCHAR(80) NOT NULL DEFAULT '',
+ *  dstchannel VARCHAR(80) NOT NULL DEFAULT '',
+ *  lastapp VARCHAR(80) NOT NULL DEFAULT '',
+ *  lastdata VARCHAR(80) NOT NULL DEFAULT '',
+ *  start CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',
+ *  answer CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',
+ *  end CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',
+ *  duration INT(11) NOT NULL DEFAULT '0',
+ *  billsec INT(11) NOT NULL DEFAULT '0',
+ *  disposition INT(11) NOT NULL DEFAULT '0',
+ *  amaflags INT(11) NOT NULL DEFAULT '0',
+ *  accountcode VARCHAR(20) NOT NULL DEFAULT '',
+ *  uniqueid VARCHAR(32) NOT NULL DEFAULT '',
+ *  userfield VARCHAR(255) NOT NULL DEFAULT ''
+ * );
+ */
+
+/*
+ * SIP RealTime table.
+ */
+CREATE TABLE ast_sip
+(
+ id INTEGER PRIMARY KEY,
+ commented INT(11) NOT NULL DEFAULT '0',
+ name VARCHAR(80) NOT NULL,
+ accountcode VARCHAR(20),
+ amaflags VARCHAR(13),
+ callgroup VARCHAR(10),
+ callerid VARCHAR(80),
+ canreinvite CHAR(3),
+ context VARCHAR(80),
+ defaultip VARCHAR(15),
+ dtmfmode VARCHAR(7),
+ fromuser VARCHAR(80),
+ fromdomain VARCHAR(80),
+ fullcontact VARCHAR(80),
+ host VARCHAR(31) NOT NULL,
+ insecure VARCHAR(4),
+ language CHAR(2),
+ mailbox VARCHAR(50),
+ md5secret VARCHAR(80),
+ nat VARCHAR(5) NOT NULL DEFAULT 'no',
+ deny VARCHAR(95),
+ permit VARCHAR(95),
+ mask VARCHAR(95),
+ pickupgroup VARCHAR(10),
+ port VARCHAR(5) NOT NULL,
+ qualify CHAR(3),
+ restrictcid CHAR(1),
+ rtptimeout CHAR(3),
+ rtpholdtimeout CHAR(3),
+ secret VARCHAR(80),
+ type VARCHAR(6) NOT NULL DEFAULT 'friend',
+ username VARCHAR(80) NOT NULL,
+ disallow VARCHAR(100),
+ allow VARCHAR(100),
+ musiconhold VARCHAR(100),
+ regseconds INT(11) NOT NULL DEFAULT '0',
+ ipaddr VARCHAR(15) NOT NULL,
+ regexten VARCHAR(80) NOT NULL,
+ cancallforward CHAR(3),
+ setvar VARCHAR(100) NOT NULL
+);
+
+CREATE UNIQUE INDEX ast_sip_name ON ast_sip(name);
+
+/*
+ * Dialplan RealTime table.
+ */
+CREATE TABLE ast_exten
+(
+ id INTEGER PRIMARY KEY,
+ commented INT(11) NOT NULL DEFAULT '0',
+ context VARCHAR(20) NOT NULL,
+ exten VARCHAR(20) NOT NULL,
+ priority TINYINT(4) NOT NULL,
+ app VARCHAR(20) NOT NULL,
+ appdata VARCHAR(128) NOT NULL
+);
+
index 9c3dd0f..d620302 100644 (file)
 /* Define this to indicate the ${SQLITE_DESCRIP} library */
 #undef HAVE_SQLITE
 
+/* Define this to indicate the ${SQLITE3_DESCRIP} library */
+#undef HAVE_SQLITE3
+
+/* Define to indicate the ${SQLITE3_DESCRIP} library version */
+#undef HAVE_SQLITE3_VERSION
+
 /* Define to indicate the ${SQLITE_DESCRIP} library version */
 #undef HAVE_SQLITE_VERSION
 
index 792afc6..24c8f9d 100644 (file)
@@ -141,6 +141,9 @@ SPEEX_LIB=@SPEEX_LIB@
 SQLITE_INCLUDE=@SQLITE_INCLUDE@
 SQLITE_LIB=@SQLITE_LIB@
 
+SQLITE3_INCLUDE=@SQLITE3_INCLUDE@
+SQLITE3_LIB=@SQLITE3_LIB@
+
 SSL_INCLUDE=@OPENSSL_INCLUDE@
 SSL_LIB=@OPENSSL_LIB@
 
diff --git a/res/res_config_sqlite.c b/res/res_config_sqlite.c
new file mode 100644 (file)
index 0000000..1cc3f79
--- /dev/null
@@ -0,0 +1,1311 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2006, Proformatique
+ *
+ * Written by Richard Braun <rbraun@proformatique.com>
+ *
+ * Based on res_sqlite3 by Anthony Minessale II, 
+ * and res_config_mysql by Matthew Boehm
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*!
+ * \mainpage res_sqlite
+ * 
+ * \section intro_sec Presentation
+ * 
+ * res_sqlite is a module for the Asterisk Open Source PBX to support SQLite 2
+ * databases. It can be used to fetch configuration from a database (static
+ * configuration files and/or using the Asterisk RealTime Architecture - ARA).
+ * It can also be used to log CDR entries. Finally, it can be used for simple
+ * queries in the Dialplan. Note that Asterisk already comes with a module
+ * named cdr_sqlite. There are two reasons for including it in res_sqlite:
+ * the first is that rewriting it was a training to learn how to write a
+ * simple module for Asterisk, the other is to have the same database open for
+ * all kinds of operations, which improves reliability and performance.
+ * 
+ * There is already a module for SQLite 3 (named res_sqlite3) in the Asterisk
+ * addons. res_sqlite was developed because we, at Proformatique, are using
+ * PHP 4 in our embedded systems, and PHP 4 has no stable support for SQLite 3
+ * at this time. We also needed RealTime support.
+ * 
+ * \section build_install_sec Building and installing
+ * 
+ * To build res_sqlite, simply enter <code>make</code>. To install it,
+ * enter make install. The Makefile has been slightly designed for
+ * cross compilation and installation in non standard locations, to ease
+ * the work of packagers. Read it for more details.
+ * 
+ * \section conf_sec Configuration
+ * 
+ * The main configuration file is res_config_sqlite.conf. It must be readable or
+ * res_sqlite will fail to start. It is suggested to use the sample file
+ * in this package as a starting point. The file has only one section
+ * named <code>general</code>. Here are the supported parameters :
+ * 
+ * <dl>
+ *     <dt><code>dbfile</code></dt>
+ *     <dd>The absolute path to the SQLite database (the file can be non existent,
+ *                     res_sqlite will create it if is has the appropriate rights)</dd>
+ *     <dt><code>config_table</code></dt>
+ *     <dd>The table used for static configuration</dd>
+ *     <dt><code>cdr_table</code></dt>
+ *     <dd>The table used to store CDR entries (if ommitted, CDR support is
+ *                     disabled)</dd>
+ * </dl>
+ * 
+ * To use res_sqlite for static and/or RealTime configuration, refer to the
+ * Asterisk documentation. The file tables.sql can be used to create the
+ * needed tables.
+ * 
+ * The SQLITE() application is very similar to the MYSQL() application. You
+ * can find more details at
+ * <a href="http://voip-info.org/wiki/view/Asterisk+cmd+MYSQL">http://voip-info.org/wiki/view/Asterisk+cmd+MYSQL</a>.
+ * The main difference is that you cannot choose your database - it's the
+ * file set in the <code>dbfile</code> parameter. As a result, there is no
+ * Connect or Disconnect command, and there is no connid variable.
+ * 
+ * \section status_sec Driver status
+ * 
+ * The CLI command <code>show sqlite status</code> returns status information
+ * about the running driver. One information is more important than others:
+ * the number of registered virtual machines. A SQLite virtual machine is
+ * created each time a SQLITE() query command is used. If the number of
+ * registered virtual machines isn't 0 (or near 0, since one or more SQLITE()
+ * commands can be running when requesting the module status) and increases
+ * over time, this probably means that you're badly using the application
+ * and you're creating resource leaks. You should check your Dialplan and
+ * reload res_sqlite (by unloading and then loading again - reloading isn't
+ * supported)
+ * 
+ * \section credits_sec Credits
+ * 
+ * res_sqlite was developed by Richard Braun at the Proformatique company.
+ */
+
+/*!
+ * \file res_sqlite.c
+ * \brief res_sqlite module.
+ */
+
+/*** MODULEINFO
+       <depend>sqlite</depend>
+ ***/
+
+#include "asterisk.h"
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sqlite.h>
+
+#include "asterisk/pbx.h"
+#include "asterisk/cdr.h"
+#include "asterisk/cli.h"
+#include "asterisk/lock.h"
+#include "asterisk/config.h"
+#include "asterisk/logger.h"
+#include "asterisk/module.h"
+#include "asterisk/options.h"
+#include "asterisk/linkedlists.h"
+
+#define RES_SQLITE_NAME "res_sqlite"
+#define RES_SQLITE_DRIVER "sqlite"
+#define RES_SQLITE_APP_DRIVER "SQLITE"
+#define RES_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
+#define RES_SQLITE_CONF_FILE "res_config_sqlite.conf"
+#define RES_SQLITE_APP_SYNOPSIS "Dialplan access to SQLite 2"
+#define RES_SQLITE_APP_DESCRIPTION \
+"SQLITE(): " RES_SQLITE_APP_SYNOPSIS "\n"
+#define RES_SQLITE_STATUS_SUMMARY \
+"Show status information about the SQLite 2 driver"
+#define RES_SQLITE_STATUS_USAGE \
+"Usage: show sqlite status\n" \
+"      " RES_SQLITE_STATUS_SUMMARY "\n"
+
+enum {
+       RES_SQLITE_CONFIG_ID,
+       RES_SQLITE_CONFIG_COMMENTED,
+       RES_SQLITE_CONFIG_FILENAME,
+       RES_SQLITE_CONFIG_CATEGORY,
+       RES_SQLITE_CONFIG_VAR_NAME,
+       RES_SQLITE_CONFIG_VAR_VAL,
+       RES_SQLITE_CONFIG_COLUMNS,
+};
+
+/*!
+ * Limit the number of maximum simultaneous registered SQLite VMs to avoid
+ * a denial of service attack.
+ */
+#define RES_SQLITE_VM_MAX 1024
+
+#define SET_VAR(config, to, from) \
+do \
+       { \
+               int __error; \
+               __error = set_var(&to, #to, from->value); \
+               if (__error) \
+                       { \
+                               ast_config_destroy(config); \
+                               unload_config(); \
+                               return 1; \
+                       } \
+       } \
+while (0)
+
+/*!
+ * Maximum number of loops before giving up executing a query. Calls to
+ * sqlite_xxx() functions which can return SQLITE_BUSY or SQLITE_LOCKED
+ * are enclosed by RES_SQLITE_BEGIN and RES_SQLITE_END, e.g.
+ * <pre>
+ * char *errormsg;
+ * int error;
+ * 
+ * RES_SQLITE_BEGIN
+ *      error = sqlite_exec(db, query, NULL, NULL, &errormsg);
+ * RES_SQLITE_END(error)
+ * 
+ * if (error)
+ *      ...;
+ * </pre>
+ */
+#define RES_SQLITE_MAX_LOOPS 10
+
+/*!
+ * Macro used before executing a query.
+ * 
+ * \see RES_SQLITE_MAX_LOOPS.
+ */
+#define RES_SQLITE_BEGIN \
+{ \
+       int __i; \
+       for (__i = 0; __i < RES_SQLITE_MAX_LOOPS; __i++) \
+               {
+
+/*!
+ * Macro used after executing a query.
+ * 
+ * \see RES_SQLITE_MAX_LOOPS.
+ */
+#define RES_SQLITE_END(error) \
+                       if (error != SQLITE_BUSY && error != SQLITE_LOCKED) \
+                               break; \
+                       usleep(1000); \
+               } \
+}
+
+/*!
+ * Structure sent to the SQLite callback function for static configuration.
+ * 
+ * \see add_cfg_entry()
+ */
+struct cfg_entry_args {
+       struct ast_config *cfg;
+       struct ast_category *cat;
+       char *cat_name;
+};
+
+/*!
+ * Structure sent to the SQLite callback function for RealTime configuration.
+ * 
+ * \see add_rt_cfg_entry()
+ */
+struct rt_cfg_entry_args {
+       struct ast_variable *var;
+       struct ast_variable *last;
+};
+
+/*!
+ * Structure sent to the SQLite callback function for RealTime configuration
+ * (realtime_multi_handler()).
+ * 
+ * \see add_rt_multi_cfg_entry()
+ */
+struct rt_multi_cfg_entry_args {
+       struct ast_config *cfg;
+       char *initfield;
+};
+
+/*!
+ * Allocate a variable.
+ * 
+ * \param var   the address of the variable to set (it will be allocated)
+ * \param name the name of the variable (for error handling)
+ * \param value the value to store in var
+ * \return 1 if an allocation error occurred, 0 otherwise
+ */
+static int set_var(char **var, char *name, char *value);
+
+/*!
+ * Load the configuration file.
+ * 
+ * This function sets dbfile, config_table, and cdr_table. It calls
+ * check_vars() before returning, and unload_config() if an error occurred.
+ * 
+ * \return 1 if an error occurred, 0 otherwise
+ * \see unload_config()
+ */
+static int load_config(void);
+
+/*!
+ * Free resources related to configuration.
+ * 
+ * \see load_config()
+ */
+static void unload_config(void);
+
+/*!
+ * Asterisk callback function for CDR support.
+ * 
+ * Asterisk will call this function each time a CDR entry must be logged if
+ * CDR support is enabled.
+ * 
+ * \param cdr the CDR entry Asterisk sends us
+ * \return 1 if an error occurred, 0 otherwise
+ */
+static int cdr_handler(struct ast_cdr *cdr);
+
+/*!
+ * SQLite callback function for static configuration.
+ * 
+ * This function is passed to the SQLite engine as a callback function to
+ * parse a row and store it in a struct ast_config object. It relies on
+ * resulting rows      being sorted by category.
+ * 
+ * \param arg                           a pointer to a struct cfg_entry_args object
+ * \param argc                         number of columns
+ * \param argv                         values in the row
+ * \param columnNames names and types of the columns
+ * \return 1 if an error occurred, 0 otherwise
+ * \see cfg_entry_args
+ * \see sql_get_config_table
+ * \see config_handler()
+ */
+static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
+
+/*!
+ * Asterisk callback function for static configuration.
+ * 
+ * Asterisk will call this function when it loads its static configuration,
+ * which usually happens at startup and reload.
+ * 
+ * \param database the database to use (ignored)
+ * \param table                the table to use
+ * \param file          the file to load from the database
+ * \param cfg                  the struct ast_config object to use when storing variables
+ * \return NULL if an error occurred, cfg otherwise
+ * \see add_cfg_entry()
+ */
+static struct ast_config * config_handler(const char *database,
+       const char *table, const char *file,
+       struct ast_config *cfg, int withcomments);
+
+/*!
+ * Helper function to parse a va_list object into 2 dynamic arrays of
+ * strings, parameters and values.
+ * 
+ * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
+ * arguments will be extracted to create 2 arrays:
+ * 
+ * <ul>
+ *     <li>params : param1 param2 param3 ...</li>
+ *     <li>vals : val1 val2 val3 ...</li>
+ * </ul>
+ * 
+ * The address of these arrays are stored in params_ptr and vals_ptr. It
+ * is the responsibility of the caller to release the memory of these arrays.
+ * It is considered an error that va_list has a null or odd number of strings.
+ * 
+ * \param ap                            the va_list object to parse
+ * \param params_ptr where the address of the params array is stored
+ * \param vals_ptr      where the address of the vals array is stored
+ * \return 0 if an error occurred, the number of elements in the arrays (which
+ *                              have the same size) otherwise
+ */
+static size_t get_params(va_list ap, const char ***params_ptr,
+       const char ***vals_ptr);
+
+/*!
+ * SQLite callback function for RealTime configuration.
+ * 
+ * This function is passed to the SQLite engine as a callback function to
+ * parse a row and store it in a linked list of struct ast_variable objects.
+ * 
+ * \param arg                           a pointer to a struct rt_cfg_entry_args object
+ * \param argc                         number of columns
+ * \param argv                         values in the row
+ * \param columnNames names and types of the columns
+ * \return 1 if an error occurred, 0 otherwise
+ * \see rt_cfg_entry_args
+ * \see realtime_handler()
+ */
+static int add_rt_cfg_entry(void *arg, int argc, char **argv,
+       char **columnNames);
+
+/*!
+ * Asterisk callback function for RealTime configuration.
+ * 
+ * Asterisk will call this function each time it requires a variable
+ * through the RealTime architecture. ap is a list of parameters and
+ * values used to find a specific row, e.g one parameter "name" and
+ * one value "123" so that the SQL query becomes <code>SELECT * FROM
+ * table WHERE name = '123';</code>.
+ * 
+ * \param database the database to use (ignored)
+ * \param table                the table to use
+ * \param ap                    list of parameters and values to match
+ * \return NULL if an error occurred, a linked list of struct ast_variable
+ *                              objects otherwise
+ * \see add_rt_cfg_entry()
+ */
+static struct ast_variable * realtime_handler(const char *database,
+       const char *table, va_list ap);
+
+/*!
+ * SQLite callback function for RealTime configuration.
+ * 
+ * This function performs the same actions as add_rt_cfg_entry() except
+ * that the rt_multi_cfg_entry_args structure is designed to store
+ * categories in addition of variables.
+ * 
+ * \param arg                           a pointer to a struct rt_multi_cfg_entry_args object
+ * \param argc                         number of columns
+ * \param argv                         values in the row
+ * \param columnNames names and types of the columns
+ * \return 1 if an error occurred, 0 otherwise
+ * \see rt_multi_cfg_entry_args
+ * \see realtime_multi_handler()
+ */
+static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
+       char **columnNames);
+
+/*!
+ * Asterisk callback function for RealTime configuration.
+ * 
+ * This function performs the same actions as realtime_handler() except
+ * that it can store variables per category, and can return several
+ * categories.
+ * 
+ * \param database the database to use (ignored)
+ * \param table                the table to use
+ * \param ap                    list of parameters and values to match
+ * \return NULL if an error occurred, a struct ast_config object storing
+ *                              categories and variables
+ * \see add_rt_multi_cfg_entry()
+ */
+static struct ast_config * realtime_multi_handler(const char *database,
+       const char *table,
+       va_list ap);
+
+/*!
+ * Asterisk callback function for RealTime configuration (variable
+ * update).
+ * 
+ * Asterisk will call this function each time a variable has been modified
+ * internally and must be updated in the backend engine. keyfield and entity
+ * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
+ * keyfield = 'entity';</code>. ap is a list of parameters and values with the
+ * same format as the other realtime functions.
+ * 
+ * \param database the database to use (ignored)
+ * \param table                the table to use
+ * \param keyfield the column of the matching cell
+ * \param entity        the value of the matching cell
+ * \param ap                    list of parameters and new values to update in the database
+ * \return -1 if an error occurred, the number of affected rows otherwise
+ */
+static int realtime_update_handler(const char *database, const char *table,
+       const char *keyfield, const char *entity,
+       va_list ap);
+
+/*!
+ * Asterisk callback function for the CLI status command.
+ * 
+ * \param fd    file descriptor provided by Asterisk to use with ast_cli()
+ * \param argc number of arguments
+ * \param argv arguments list
+ * \return RESULT_SUCCESS
+ */
+static int cli_status(int fd, int argc, char *argv[]);
+
+/*!
+ * The SQLite database object.
+ */
+static sqlite *db;
+
+/*!
+ * Set to 1 if CDR support is enabled.
+ */
+static int use_cdr;
+
+/*!
+ * Set to 1 if the CDR callback function was registered.
+ */
+static int cdr_registered;
+
+/*!
+ * Set to 1 if the CLI status command callback function was registered.
+ */
+static int cli_status_registered;
+
+/*!
+ * The path of the database file.
+ */
+static char *dbfile;
+
+/*!
+ * The name of the static configuration table.
+ */
+static char *config_table;
+
+/*!
+ * The name of the table used to store CDR entries.
+ */
+static char *cdr_table;
+
+/*!
+ * The number of registered virtual machines.
+ */
+static int vm_count;
+
+/*!
+ * The structure specifying all callback functions used by Asterisk for static
+ * and RealTime configuration.
+ */
+static struct ast_config_engine sqlite_engine =
+{
+       .name = RES_SQLITE_DRIVER,
+       .load_func = config_handler,
+       .realtime_func = realtime_handler,
+       .realtime_multi_func = realtime_multi_handler,
+       .update_func = realtime_update_handler
+};
+
+/*!
+ * The mutex used to prevent simultaneous access to the SQLite database.
+ * SQLite isn't always compiled with thread safety.
+ */
+AST_MUTEX_DEFINE_STATIC(mutex);
+
+/*!
+ * Structure containing details and callback functions for the CLI status
+ * command.
+ */
+static struct ast_cli_entry cli_status_cmd =
+{
+       .cmda = {"show", "sqlite", "status", NULL},
+       .handler = cli_status,
+       .summary = RES_SQLITE_STATUS_SUMMARY,
+       .usage = RES_SQLITE_STATUS_USAGE
+};
+
+/*
+ * Taken from Asterisk 1.2 cdr_sqlite.so.
+ */
+
+/*!
+ * SQL query format to create the CDR table if non existent.
+ */
+static char *sql_create_cdr_table =
+"CREATE TABLE '%q' ("
+"      id              INTEGER PRIMARY KEY,"
+"      clid            VARCHAR(80) NOT NULL DEFAULT '',"
+"      src             VARCHAR(80) NOT NULL DEFAULT '',"
+"      dst             VARCHAR(80) NOT NULL DEFAULT '',"
+"      dcontext        VARCHAR(80) NOT NULL DEFAULT '',"
+"      channel         VARCHAR(80) NOT NULL DEFAULT '',"
+"      dstchannel      VARCHAR(80) NOT NULL DEFAULT '',"
+"      lastapp         VARCHAR(80) NOT NULL DEFAULT '',"
+"      lastdata        VARCHAR(80) NOT NULL DEFAULT '',"
+"      start           CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
+"      answer          CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
+"      end             CHAR(19) NOT NULL DEFAULT '0000-00-00 00:00:00',"
+"      duration        INT(11) NOT NULL DEFAULT '0',"
+"      billsec         INT(11) NOT NULL DEFAULT '0',"
+"      disposition     INT(11) NOT NULL DEFAULT '0',"
+"      amaflags        INT(11) NOT NULL DEFAULT '0',"
+"      accountcode     VARCHAR(20) NOT NULL DEFAULT '',"
+"      uniqueid        VARCHAR(32) NOT NULL DEFAULT '',"
+"      userfield       VARCHAR(255) NOT NULL DEFAULT ''"
+");";
+
+/*!
+ * SQL query format to insert a CDR entry.
+ */
+static char *sql_add_cdr_entry =
+"INSERT INTO '%q' ("
+"                       clid,"
+"      src,"
+"      dst,"
+"      dcontext,"
+"      channel,"
+"      dstchannel,"
+"      lastapp,"
+"      lastdata,"
+"      start,"
+"      answer,"
+"      end,"
+"      duration,"
+"      billsec,"
+"      disposition,"
+"      amaflags,"
+"      accountcode,"
+"      uniqueid,"
+"      userfield"
+") VALUES ("
+"      '%q',"
+"      '%q',"
+"      '%q',"
+"      '%q',"
+"      '%q',"
+"      '%q',"
+"      '%q',"
+"      '%q',"
+"      datetime(%d,'unixepoch'),"
+"      datetime(%d,'unixepoch'),"
+"      datetime(%d,'unixepoch'),"
+"      '%ld',"
+"      '%ld',"
+"      '%ld',"
+"      '%ld',"
+"      '%q',"
+"      '%q',"
+"      '%q'"
+");";
+
+/*!
+ * SQL query format to fetch the static configuration of a file.
+ * Rows must be sorted by category.
+ * 
+ * @see add_cfg_entry()
+ */
+static char *sql_get_config_table =
+"SELECT *"
+"      FROM '%q'"
+"      WHERE filename = '%q' AND commented = 0"
+"      ORDER BY category;";
+
+static int set_var(char **var, char *name, char *value)
+{
+       if (*var)
+               free(*var);
+
+       *var = ast_strdup(value);
+
+       if (!*var) {
+               ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
+               return 1;
+       }
+
+       return 0;
+}
+
+static int check_vars(void)
+{
+       if (!dbfile) {
+               ast_log(LOG_ERROR, "Undefined parameter %s\n", dbfile);
+               return 1;
+       }
+
+       use_cdr = (cdr_table != NULL);
+
+       return 0;
+}
+
+static int load_config(void)
+{
+       struct ast_config *config;
+       struct ast_variable *var;
+       int error;
+
+       config = ast_config_load(RES_SQLITE_CONF_FILE);
+
+       if (!config) {
+               ast_log(LOG_ERROR, "Unable to load " RES_SQLITE_CONF_FILE "\n");
+               return 1;
+       }
+
+       for (var = ast_variable_browse(config, "general"); var; var = var->next) {
+               if (!strcasecmp(var->name, "dbfile"))
+                       SET_VAR(config, dbfile, var);
+               else if (!strcasecmp(var->name, "config_table"))
+                       SET_VAR(config, config_table, var);
+               else if (!strcasecmp(var->name, "cdr_table"))
+                       SET_VAR(config, cdr_table, var);
+               else
+                       ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
+       }
+
+       ast_config_destroy(config);
+       error = check_vars();
+
+       if (error) {
+               unload_config();
+               return 1;
+       }
+
+       return 0;
+}
+
+static void unload_config(void)
+{
+       free(dbfile);
+       dbfile = NULL;
+       free(config_table);
+       config_table = NULL;
+       free(cdr_table);
+       cdr_table = NULL;
+}
+
+static int cdr_handler(struct ast_cdr *cdr)
+{
+       char *errormsg;
+       int error;
+
+       ast_mutex_lock(&mutex);
+
+       RES_SQLITE_BEGIN
+               error = sqlite_exec_printf(db, sql_add_cdr_entry, NULL, NULL, &errormsg,
+                                        cdr_table, cdr->clid, cdr->src, cdr->dst,
+                                        cdr->dcontext, cdr->channel, cdr->dstchannel,
+                                        cdr->lastapp, cdr->lastdata, cdr->start.tv_sec,
+                                        cdr->answer.tv_sec, cdr->end.tv_sec,
+                                        cdr->duration, cdr->billsec, cdr->disposition,
+                                        cdr->amaflags, cdr->accountcode, cdr->uniqueid,
+                                        cdr->userfield);
+       RES_SQLITE_END(error)
+
+       ast_mutex_unlock(&mutex);
+
+       if (error) {
+               ast_log(LOG_ERROR, "%s\n", errormsg);
+               free(errormsg);
+               return 1;
+       }
+
+       return 0;
+}
+
+static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
+{
+       struct cfg_entry_args *args;
+       struct ast_variable *var;
+
+       if (argc != RES_SQLITE_CONFIG_COLUMNS) {
+               ast_log(LOG_WARNING, "Corrupt table\n");
+               return 1;
+       }
+
+       args = arg;
+
+       if (!args->cat_name || strcmp(args->cat_name, argv[RES_SQLITE_CONFIG_CATEGORY])) {
+               args->cat = ast_category_new(argv[RES_SQLITE_CONFIG_CATEGORY]);
+
+               if (!args->cat) {
+                       ast_log(LOG_WARNING, "Unable to allocate category\n");
+                       return 1;
+               }
+
+               free(args->cat_name);
+               args->cat_name = ast_strdup(argv[RES_SQLITE_CONFIG_CATEGORY]);
+
+               if (!args->cat_name) {
+                       ast_category_destroy(args->cat);
+                       return 1;
+               }
+
+               ast_category_append(args->cfg, args->cat);
+       }
+
+       var = ast_variable_new(argv[RES_SQLITE_CONFIG_VAR_NAME],
+                argv[RES_SQLITE_CONFIG_VAR_VAL]);
+
+       if (!var) {
+               ast_log(LOG_WARNING, "Unable to allocate variable");
+               return 1;
+       }
+
+       ast_variable_append(args->cat, var);
+       
+       return 0;
+}
+
+static struct ast_config *config_handler(const char *database, 
+       const char *table, const char *file, struct ast_config *cfg, int withcomments)
+{
+       struct cfg_entry_args args;
+       char *errormsg;
+       int error;
+
+       if (!config_table) {
+               if (!table) {
+                       ast_log(LOG_ERROR, "Table name unspecified\n");
+                       return NULL;
+               }
+       } else
+               table = config_table;
+
+       args.cfg = cfg;
+       args.cat = NULL;
+       args.cat_name = NULL;
+
+       ast_mutex_lock(&mutex);
+
+       RES_SQLITE_BEGIN
+               error = sqlite_exec_printf(db, sql_get_config_table, add_cfg_entry,
+                                       &args, &errormsg, table, file);
+       RES_SQLITE_END(error)
+
+       ast_mutex_unlock(&mutex);
+
+       free(args.cat_name);
+
+       if (error) {
+               ast_log(LOG_ERROR, "%s\n", errormsg);
+               free(errormsg);
+               return NULL;
+       }
+
+       return cfg;
+}
+
+static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr)
+{
+       const char **tmp, *param, *val, **params, **vals;
+       size_t params_count;
+
+       params = NULL;
+       vals = NULL;
+       params_count = 0;
+
+       while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
+               if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
+                       free(params);
+                       free(vals);
+                       return 0;
+               }
+               params = tmp;
+
+               if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
+                       free(params);
+                       free(vals);
+                       return 0;
+               }
+               vals = tmp;
+
+               params[params_count] = param;
+               vals[params_count] = val;
+               params_count++;
+       }
+
+       if (params_count)
+               ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
+       else {
+               *params_ptr = params;
+               *vals_ptr = vals;
+       }
+
+       return params_count;
+}
+
+static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
+{
+       struct rt_cfg_entry_args *args;
+       struct ast_variable *var;
+       int i;
+
+       args = arg;
+
+       for (i = 0; i < argc; i++) {
+               if (!argv[i])
+                       continue;
+
+               if (!(var = ast_variable_new(columnNames[i], argv[i])))
+                       return 1;
+
+               if (!args->var)
+                       args->var = var;
+
+               if (!args->last)
+                       args->last = var;
+               else {
+                       args->last->next = var;
+                       args->last = var;
+               }
+       }
+
+       return 0;
+}
+
+static struct ast_variable *
+realtime_handler(const char *database, const char *table, va_list ap)
+{
+       char *query, *errormsg, *op, *tmp_str;
+       struct rt_cfg_entry_args args;
+       const char **params, **vals;
+       size_t params_count;
+       int error;
+
+       if (!table) {
+               ast_log(LOG_WARNING, "Table name unspecified\n");
+               return NULL;
+       }
+
+       params_count = get_params(ap, &params, &vals);
+
+       if (params_count == 0)
+               return NULL;
+
+       op = (strchr(params[0], ' ') == NULL) ? " =" : "";
+
+/* \cond DOXYGEN_CAN_PARSE_THIS */
+#undef QUERY
+#define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
+/* \endcond */
+
+       query = sqlite_mprintf(QUERY, table, params[0], op, vals[0]);
+
+       if (!query) {
+               ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
+               free(params);
+               free(vals);
+               return NULL;
+       }
+
+       if (params_count > 1) {
+               size_t i;
+
+               for (i = 1; i < params_count; i++) {
+                       op = (strchr(params[i], ' ') == NULL) ? " =" : "";
+                       tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op,
+                                                                                                                        vals[i]);
+                       sqlite_freemem(query);
+
+                       if (!tmp_str) {
+                               ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
+                               free(params);
+                               free(vals);
+                               return NULL;
+                       }
+
+                       query = tmp_str;
+               }
+       }
+
+       free(params);
+       free(vals);
+
+       tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
+       sqlite_freemem(query);
+
+       if (!tmp_str) {
+               ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
+               return NULL;
+       }
+
+       query = tmp_str;
+       ast_log(LOG_DEBUG, "SQL query: %s\n", query);
+       args.var = NULL;
+       args.last = NULL;
+
+       ast_mutex_lock(&mutex);
+
+       RES_SQLITE_BEGIN
+               error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
+       RES_SQLITE_END(error)
+
+       ast_mutex_unlock(&mutex);
+
+       sqlite_freemem(query);
+
+       if (error) {
+               ast_log(LOG_WARNING, "%s\n", errormsg);
+               free(errormsg);
+               ast_variables_destroy(args.var);
+               return NULL;
+       }
+
+       return args.var;
+}
+
+static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
+{
+       struct rt_multi_cfg_entry_args *args;
+       struct ast_category *cat;
+       struct ast_variable *var;
+       char *cat_name;
+       size_t i;
+
+       args = (struct rt_multi_cfg_entry_args *)arg;
+       cat_name = NULL;
+
+       /*
+        * cat_name should always be set here, since initfield is forged from
+        * params[0] in realtime_multi_handler(), which is a search parameter
+        * of the SQL query.
+        */
+       for (i = 0; i < argc; i++) {
+               if (!strcmp(args->initfield, columnNames[i]))
+                       cat_name = argv[i];
+       }
+
+       if (!cat_name) {
+               ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
+               return 1;
+       }
+
+       if (!(cat = ast_category_new(cat_name))) {
+               ast_log(LOG_WARNING, "Unable to allocate category\n");
+               return 1;
+       }
+
+       ast_category_append(args->cfg, cat);
+
+       for (i = 0; i < argc; i++) {
+               if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
+                       continue;
+
+               if (!(var = ast_variable_new(columnNames[i], argv[i]))) {
+                       ast_log(LOG_WARNING, "Unable to allocate variable\n");
+                       return 1;
+               }
+
+               ast_variable_append(cat, var);
+       }
+
+       return 0;
+}
+
+static struct ast_config *realtime_multi_handler(const char *database, 
+       const char *table, va_list ap)
+{
+       char *query, *errormsg, *op, *tmp_str, *initfield;
+       struct rt_multi_cfg_entry_args args;
+       const char **params, **vals;
+       struct ast_config *cfg;
+       size_t params_count;
+       int error;
+
+       if (!table) {
+               ast_log(LOG_WARNING, "Table name unspecified\n");
+               return NULL;
+       }
+
+       if (!(cfg = ast_config_new())) {
+               ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
+               return NULL;
+       }
+
+       if (!(params_count = get_params(ap, &params, &vals))) {
+               ast_config_destroy(cfg);
+               return NULL;
+       }
+
+       if (!(initfield = ast_strdup(params[0]))) {
+               ast_config_destroy(cfg);
+               free(params);
+               free(vals);
+               return NULL;
+       }
+
+       tmp_str = strchr(initfield, ' ');
+
+       if (tmp_str)
+               *tmp_str = '\0';
+
+       op = (!strchr(params[0], ' ')) ? " =" : "";
+
+       /*
+        * Asterisk sends us an already escaped string when searching for
+        * "exten LIKE" (uh!). Handle it separately.
+        */
+       tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
+
+/* \cond DOXYGEN_CAN_PARSE_THIS */
+#undef QUERY
+#define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
+/* \endcond */
+
+       if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
+               ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
+               ast_config_destroy(cfg);
+               free(params);
+               free(vals);
+               free(initfield);
+               return NULL;
+       }
+
+       if (params_count > 1) {
+               size_t i;
+
+               for (i = 1; i < params_count; i++) {
+                       op = (!strchr(params[i], ' ')) ? " =" : "";
+                       tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op,
+                                                                                                                        vals[i]);
+                       sqlite_freemem(query);
+
+                       if (!tmp_str) {
+                               ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
+                               ast_config_destroy(cfg);
+                               free(params);
+                               free(vals);
+                               free(initfield);
+                               return NULL;
+                       }
+
+                       query = tmp_str;
+               }
+       }
+
+       free(params);
+       free(vals);
+
+       if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
+               ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
+               ast_config_destroy(cfg);
+               free(initfield);
+               return NULL;
+       }
+
+       sqlite_freemem(query);
+       query = tmp_str;
+       ast_log(LOG_DEBUG, "SQL query: %s\n", query);
+       args.cfg = cfg;
+       args.initfield = initfield;
+
+       ast_mutex_lock(&mutex);
+
+       RES_SQLITE_BEGIN
+               error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
+       RES_SQLITE_END(error)
+
+       ast_mutex_unlock(&mutex);
+
+       sqlite_freemem(query);
+       free(initfield);
+
+       if (error) {
+               ast_log(LOG_WARNING, "%s\n", errormsg);
+               free(errormsg);
+               ast_config_destroy(cfg);
+               return NULL;
+       }
+
+       return cfg;
+}
+
+static int realtime_update_handler(const char *database, const char *table,
+       const char *keyfield, const char *entity,
+       va_list ap)
+{
+       char *query, *errormsg, *tmp_str;
+       const char **params, **vals;
+       size_t params_count;
+       int error, rows_num;
+
+       if (!table) {
+               ast_log(LOG_WARNING, "Table name unspecified\n");
+               return -1;
+       }
+
+       if (!(params_count = get_params(ap, &params, &vals)))
+               return -1;
+
+/* \cond DOXYGEN_CAN_PARSE_THIS */
+#undef QUERY
+#define QUERY "UPDATE '%q' SET %q = '%q'"
+/* \endcond */
+
+       if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
+               ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
+               free(params);
+               free(vals);
+               return -1;
+       }
+
+       if (params_count > 1) {
+               size_t i;
+
+               for (i = 1; i < params_count; i++) {
+                       tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i],
+                                                                                                                        vals[i]);
+                       sqlite_freemem(query);
+
+                       if (!tmp_str) {
+                               ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
+                               free(params);
+                               free(vals);
+                               return -1;
+                       }
+
+                       query = tmp_str;
+               }
+       }
+
+       free(params);
+       free(vals);
+
+       if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
+               ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
+               return -1;
+       }
+
+       sqlite_freemem(query);
+       query = tmp_str;
+       ast_log(LOG_DEBUG, "SQL query: %s\n", query);
+
+       ast_mutex_lock(&mutex);
+
+       RES_SQLITE_BEGIN
+               error = sqlite_exec(db, query, NULL, NULL, &errormsg);
+       RES_SQLITE_END(error)
+
+       if (!error)
+               rows_num = sqlite_changes(db);
+       else
+               rows_num = -1;
+
+       ast_mutex_unlock(&mutex);
+
+       sqlite_freemem(query);
+
+       if (error) {
+               ast_log(LOG_WARNING, "%s\n", errormsg);
+               free(errormsg);
+       }
+
+       return rows_num;
+}
+
+static int cli_status(int fd, int argc, char *argv[])
+{
+       ast_cli(fd, "SQLite database path: %s\n", dbfile);
+       ast_cli(fd, "config_table: ");
+
+       if (!config_table)
+               ast_cli(fd, "unspecified, must be present in extconfig.conf\n");
+       else
+               ast_cli(fd, "%s\n", config_table);
+
+       ast_cli(fd, "cdr_table: ");
+
+       if (!cdr_table)
+               ast_cli(fd, "unspecified, CDR support disabled\n");
+       else
+               ast_cli(fd, "%s\n", cdr_table);
+
+       return RESULT_SUCCESS;
+}
+
+static int unload_module(void)
+{
+       if (cli_status_registered)
+               ast_cli_unregister(&cli_status_cmd);
+
+       if (cdr_registered)
+               ast_cdr_unregister(RES_SQLITE_NAME);
+
+       ast_config_engine_deregister(&sqlite_engine);
+
+       if (db)
+               sqlite_close(db);
+
+       unload_config();
+
+       return 0;
+}
+
+static int load_module(void)
+{
+       char *errormsg;
+       int error;
+
+       db = NULL;
+       cdr_registered = 0;
+       cli_status_registered = 0;
+       dbfile = NULL;
+       config_table = NULL;
+       cdr_table = NULL;
+       vm_count = 0;
+       error = load_config();
+
+       if (error)
+               return AST_MODULE_LOAD_DECLINE;
+
+       if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
+               ast_log(LOG_ERROR, "%s\n", errormsg);
+               free(errormsg);
+               unload_module();
+               return 1;
+       }
+
+       ast_config_engine_register(&sqlite_engine);
+
+       if (use_cdr) {
+               RES_SQLITE_BEGIN
+                       error = sqlite_exec_printf(db, "SELECT COUNT(id) FROM %Q;", NULL, NULL,
+                                                                                                                                &errormsg, cdr_table);
+               RES_SQLITE_END(error)
+
+               if (error) {
+                       /*
+                        * Unexpected error.
+                        */
+                       if (error != SQLITE_ERROR) {
+                               ast_log(LOG_ERROR, "%s\n", errormsg);
+                               free(errormsg);
+                               unload_module();
+                               return 1;
+                       }
+
+                       RES_SQLITE_BEGIN
+                               error = sqlite_exec_printf(db, sql_create_cdr_table, NULL, NULL,
+                                                               &errormsg, cdr_table);
+                       RES_SQLITE_END(error)
+
+                       if (error) {
+                               ast_log(LOG_ERROR, "%s\n", errormsg);
+                               free(errormsg);
+                               unload_module();
+                               return 1;
+                       }
+               }
+
+               error = ast_cdr_register(RES_SQLITE_NAME, RES_SQLITE_DESCRIPTION,
+                                                                                                                cdr_handler);
+
+               if (error) {
+                       unload_module();
+                       return 1;
+               }
+
+               cdr_registered = 1;
+       }
+
+       error = ast_cli_register(&cli_status_cmd);
+
+       if (error) {
+               unload_module();
+               return 1;
+       }
+
+       cli_status_registered = 1;
+
+       return 0;
+}
+
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "SQLite Configuration",
+               .load = load_module,
+               .unload = unload_module,
+);