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