Asterisk - The Open Source Telephony Project  18.5.0
cdr_sqlite3_custom.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2007, Digium, Inc.
5  *
6  * Mark Spencer <[email protected]> and others.
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18 
19 /*!
20  * \file
21  * \brief Custom SQLite3 CDR records.
22  *
23  * \author Adapted by Alejandro Rios <[email protected]> and
24  * Russell Bryant <[email protected]> from
25  * cdr_mysql_custom by Edward Eastman <[email protected]>,
26  * and cdr_sqlite by Holger Schurig <[email protected]>
27  *
28  *
29  * \arg See also \ref AstCDR
30  *
31  *
32  * \ingroup cdr_drivers
33  */
34 
35 /*** MODULEINFO
36  <depend>sqlite3</depend>
37  <support_level>extended</support_level>
38  ***/
39 
40 #include "asterisk.h"
41 
42 #include <sqlite3.h>
43 
44 #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
45 #include "asterisk/channel.h"
46 #include "asterisk/cdr.h"
47 #include "asterisk/module.h"
48 #include "asterisk/config.h"
49 #include "asterisk/pbx.h"
50 #include "asterisk/utils.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/app.h"
53 
55 
56 static const char config_file[] = "cdr_sqlite3_custom.conf";
57 
58 static const char desc[] = "Customizable SQLite3 CDR Backend";
59 static const char name[] = "cdr_sqlite3_custom";
60 static sqlite3 *db = NULL;
61 
62 static char table[80];
63 static char *columns;
64 static int busy_timeout;
65 
66 struct values {
68  char expression[1];
69 };
70 
72 
73 static void free_config(int reload);
74 
75 static int load_column_config(const char *tmp)
76 {
77  char *col = NULL;
78  char *cols = NULL, *save = NULL;
79  char *escaped = NULL;
80  struct ast_str *column_string = NULL;
81 
82  if (ast_strlen_zero(tmp)) {
83  ast_log(LOG_WARNING, "Column names not specified. Module not loaded.\n");
84  return -1;
85  }
86  if (!(column_string = ast_str_create(1024))) {
87  ast_log(LOG_ERROR, "Out of memory creating temporary buffer for column list for table '%s.'\n", table);
88  return -1;
89  }
90  if (!(save = cols = ast_strdup(tmp))) {
91  ast_log(LOG_ERROR, "Out of memory creating temporary buffer for column list for table '%s.'\n", table);
92  ast_free(column_string);
93  return -1;
94  }
95  while ((col = strsep(&cols, ","))) {
96  col = ast_strip(col);
97  escaped = sqlite3_mprintf("%q", col);
98  if (!escaped) {
99  ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s.'\n", col, table);
100  ast_free(column_string);
101  ast_free(save);
102  return -1;
103  }
104  ast_str_append(&column_string, 0, "%s%s", ast_str_strlen(column_string) ? "," : "", escaped);
105  sqlite3_free(escaped);
106  }
107  if (!(columns = ast_strdup(ast_str_buffer(column_string)))) {
108  ast_log(LOG_ERROR, "Out of memory copying columns string for table '%s.'\n", table);
109  ast_free(column_string);
110  ast_free(save);
111  return -1;
112  }
113  ast_free(column_string);
114  ast_free(save);
115 
116  return 0;
117 }
118 
119 static int load_values_config(const char *tmp)
120 {
121  char *vals = NULL, *save = NULL;
122  struct values *value = NULL;
123  int i;
125  AST_APP_ARG(ues)[200]; /* More than 200 columns in this CDR? Yeah, right... */
126  );
127 
128  if (ast_strlen_zero(tmp)) {
129  ast_log(LOG_WARNING, "Values not specified. Module not loaded.\n");
130  return -1;
131  }
132  if (!(save = vals = ast_strdup(tmp))) {
133  ast_log(LOG_ERROR, "Out of memory creating temporary buffer for value '%s'\n", tmp);
134  return -1;
135  }
136  AST_STANDARD_RAW_ARGS(val, vals);
137  for (i = 0; i < val.argc; i++) {
138  /* Strip the single quotes off if they are there */
139  char *v = ast_strip_quoted(val.ues[i], "'", "'");
140  value = ast_calloc(sizeof(char), sizeof(*value) + strlen(v));
141  if (!value) {
142  ast_log(LOG_ERROR, "Out of memory creating entry for value '%s'\n", v);
143  ast_free(save);
144  return -1;
145  }
146  strcpy(value->expression, v); /* SAFE */
148  }
149  ast_free(save);
150 
151  return 0;
152 }
153 
154 static int load_config(int reload)
155 {
156  struct ast_config *cfg;
157  struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
158  const char *tmp;
159 
160  if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
161  ast_log(LOG_WARNING, "Failed to %sload configuration file. %s\n", reload ? "re" : "", reload ? "" : "Module not activated.");
162  return -1;
163  } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
164  return 0;
165  }
166 
167  if (reload) {
168  free_config(1);
169  }
170 
171  if (!ast_variable_browse(cfg, "master")) {
172  /* Nothing configured */
173  ast_config_destroy(cfg);
174  return -1;
175  }
176 
177  /* Mapping must have a table name */
178  if (!ast_strlen_zero(tmp = ast_variable_retrieve(cfg, "master", "table"))) {
179  ast_copy_string(table, tmp, sizeof(table));
180  } else {
181  ast_log(LOG_WARNING, "Table name not specified. Assuming cdr.\n");
182  strcpy(table, "cdr");
183  }
184 
185  /* sqlite3_busy_timeout in miliseconds */
186  if ((tmp = ast_variable_retrieve(cfg, "master", "busy_timeout")) != NULL) {
187  if (ast_parse_arg(tmp, PARSE_INT32|PARSE_DEFAULT, &busy_timeout, 1000) != 0) {
188  ast_log(LOG_WARNING, "Invalid busy_timeout value '%s' specified. Using 1000 instead.\n", tmp);
189  }
190  } else {
191  busy_timeout = 1000;
192  }
193 
194  /* Columns */
195  if (load_column_config(ast_variable_retrieve(cfg, "master", "columns"))) {
196  ast_config_destroy(cfg);
197  free_config(0);
198  return -1;
199  }
200 
201  /* Values */
202  if (load_values_config(ast_variable_retrieve(cfg, "master", "values"))) {
203  ast_config_destroy(cfg);
204  free_config(0);
205  return -1;
206  }
207 
208  ast_verb(4, "cdr_sqlite3_custom: Logging CDR records to table '%s' in 'master.db'\n", table);
209 
210  ast_config_destroy(cfg);
211 
212  return 0;
213 }
214 
215 static void free_config(int reload)
216 {
217  struct values *value;
218 
219  if (!reload && db) {
220  sqlite3_close(db);
221  db = NULL;
222  }
223 
224  if (columns) {
225  ast_free(columns);
226  columns = NULL;
227  }
228 
229  while ((value = AST_LIST_REMOVE_HEAD(&sql_values, list))) {
230  ast_free(value);
231  }
232 }
233 
234 static int write_cdr(struct ast_cdr *cdr)
235 {
236  int res = 0;
237  char *error = NULL;
238  char *sql = NULL;
239 
240  if (db == NULL) {
241  /* Should not have loaded, but be failsafe. */
242  return 0;
243  }
244 
246 
247  { /* Make it obvious that only sql should be used outside of this block */
248  char *escaped;
249  char subst_buf[2048];
250  struct values *value;
251  struct ast_channel *dummy;
252  struct ast_str *value_string = ast_str_create(1024);
253 
254  dummy = ast_dummy_channel_alloc();
255  if (!dummy) {
256  ast_log(LOG_ERROR, "Unable to allocate channel for variable subsitution.\n");
257  ast_free(value_string);
259  return 0;
260  }
261  ast_channel_cdr_set(dummy, ast_cdr_dup(cdr));
262  AST_LIST_TRAVERSE(&sql_values, value, list) {
263  pbx_substitute_variables_helper(dummy, value->expression, subst_buf, sizeof(subst_buf) - 1);
264  escaped = sqlite3_mprintf("%q", subst_buf);
265  ast_str_append(&value_string, 0, "%s'%s'", ast_str_strlen(value_string) ? "," : "", escaped);
266  sqlite3_free(escaped);
267  }
268  sql = sqlite3_mprintf("INSERT INTO %q (%s) VALUES (%s)", table, columns, ast_str_buffer(value_string));
269  ast_debug(1, "About to log: %s\n", sql);
270  ast_channel_unref(dummy);
271  ast_free(value_string);
272  }
273 
274  if (sqlite3_exec(db, sql, NULL, NULL, &error) != SQLITE_OK) {
275  ast_log(LOG_ERROR, "%s. SQL: %s.\n", error, sql);
276  sqlite3_free(error);
277  }
278 
279  if (sql) {
280  sqlite3_free(sql);
281  }
282 
284 
285  return res;
286 }
287 
288 static int unload_module(void)
289 {
290  if (ast_cdr_unregister(name)) {
291  return -1;
292  }
293 
294  free_config(0);
295 
296  return 0;
297 }
298 
299 static int load_module(void)
300 {
301  char *error;
302  char filename[PATH_MAX];
303  int res;
304  char *sql;
305 
306  if (load_config(0)) {
308  }
309 
310  /* is the database there? */
311  snprintf(filename, sizeof(filename), "%s/master.db", ast_config_AST_LOG_DIR);
312  res = sqlite3_open(filename, &db);
313  if (res != SQLITE_OK) {
314  ast_log(LOG_ERROR, "Could not open database %s.\n", filename);
315  free_config(0);
317  }
318  sqlite3_busy_timeout(db, busy_timeout);
319  /* is the table there? */
320  sql = sqlite3_mprintf("SELECT COUNT(AcctId) FROM %q;", table);
321  res = sqlite3_exec(db, sql, NULL, NULL, NULL);
322  sqlite3_free(sql);
323  if (res != SQLITE_OK) {
324  /* We don't use %q for the column list here since we already escaped when building it */
325  sql = sqlite3_mprintf("CREATE TABLE %q (AcctId INTEGER PRIMARY KEY, %s)", table, columns);
326  res = sqlite3_exec(db, sql, NULL, NULL, &error);
327  sqlite3_free(sql);
328  if (res != SQLITE_OK) {
329  ast_log(LOG_WARNING, "Unable to create table '%s': %s.\n", table, error);
330  sqlite3_free(error);
331  free_config(0);
333  }
334  }
335 
336  res = ast_cdr_register(name, desc, write_cdr);
337  if (res) {
338  ast_log(LOG_ERROR, "Unable to register custom SQLite3 CDR handling\n");
339  free_config(0);
341  }
342 
344 }
345 
346 static int reload(void)
347 {
348  int res = 0;
349 
351  res = load_config(1);
353 
354  return res;
355 }
356 
357 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "SQLite3 Custom CDR Module",
358  .support_level = AST_MODULE_SUPPORT_EXTENDED,
359  .load = load_module,
360  .unload = unload_module,
361  .reload = reload,
362  .load_pri = AST_MODPRI_CDR_DRIVER,
363  .requires = "cdr",
364 );
struct values::@101 list
Main Channel structure associated with a channel.
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
static char * columns
Definition: ast_expr2.c:325
static int busy_timeout
#define ast_channel_unref(c)
Decrease channel reference count.
Definition: channel.h:2981
struct ast_variable * ast_variable_browse(const struct ast_config *config, const char *category_name)
Definition: extconf.c:1216
static int load_config(void)
static sqlite3 * db
#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 const char name[]
static void dummy(char *unused,...)
Definition: chan_unistim.c:220
#define CONFIG_STATUS_FILEINVALID
static int tmp()
Definition: bt_open.c:389
static int load_values_config(const char *tmp)
struct ast_cdr * ast_cdr_dup(struct ast_cdr *cdr)
Duplicate a public CDR.
Definition: cdr.c:2998
static int load_module(void)
Load the module.
Definition: app_mysql.c:633
#define AST_STANDARD_RAW_ARGS(args, parse)
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_mutex_lock(a)
Definition: lock.h:187
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:243
#define NULL
Definition: resample.c:96
int value
Definition: syslog.c:37
#define ast_verb(level,...)
Definition: logger.h:463
Utility functions.
#define ast_strlen_zero(foo)
Definition: strings.h:52
Call Detail Record API.
Configuration File Parser.
char * ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
Strip leading/trailing whitespace and quotes from a string.
Definition: main/utils.c:1639
#define ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:452
#define ast_log
Definition: astobj2.c:42
void ast_channel_cdr_set(struct ast_channel *chan, struct ast_cdr *value)
#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
General Asterisk PBX channel definitions.
#define unload_module
Definition: agent.c:79
Asterisk file paths, configured in asterisk.conf.
static void free_config(int reload)
char expression[1]
#define ast_dummy_channel_alloc()
Create a fake channel structure.
Definition: channel.h:1283
static const char config_file[]
char * ast_strip(char *s)
Strip leading/trailing whitespace from a string.
Definition: strings.h:219
void ast_config_destroy(struct ast_config *config)
Destroys a config.
Definition: extconf.c:1290
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
Definition: linkedlists.h:832
Core PBX routines and definitions.
#define CONFIG_STATUS_FILEUNCHANGED
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
Definition: linkedlists.h:290
Responsible for call detail data.
Definition: cdr.h:276
static char table[80]
#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
const char * ast_config_AST_LOG_DIR
Definition: options.c:159
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
Definition: linkedlists.h:490
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
Definition: linkedlists.h:409
static const char desc[]
#define ast_free(a)
Definition: astmm.h:182
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204
static int reload(void)
Definition: cdr_mysql.c:741
int ast_parse_arg(const char *arg, enum ast_parse_flags flags, void *result,...)
The argument parsing routine.
Definition: main/config.c:3657
Module has failed to load, may be in an inconsistent state.
Definition: module.h:78
Structure used to handle boolean flags.
Definition: utils.h:199
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",)
static ast_mutex_t lock
#define CONFIG_STATUS_FILEMISSING
const char * ast_variable_retrieve(struct ast_config *config, const char *category, const char *variable)
Definition: main/config.c:694
size_t ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
Definition: strings.h:688
char * strsep(char **str, const char *delims)
Standard Command Line Interface.
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:401
void pbx_substitute_variables_helper(struct ast_channel *c, const char *cp1, char *cp2, int count)
Definition: ael_main.c:211
static int load_column_config(const char *tmp)
int error(const char *format,...)
Definition: utils/frame.c:999
#define PATH_MAX
Definition: asterisk.h:40
#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_MUTEX_DEFINE_STATIC(mutex)
Definition: lock.h:518
#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.