We have faced situation when using CDR and CEL by sqlite3 modules. With system having...
[asterisk/asterisk.git] / cel / cel_sqlite3_custom.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007, Digium, Inc.
5  *
6  * Steve Murphy <murf@digium.com> borrowed code from cdr,
7  * Mark Spencer <markster@digium.com> and others.
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \brief Custom SQLite3 CEL records.
23  *
24  * \author Adapted by Steve Murphy <murf@digium.com> from
25  *  Alejandro Rios <alejandro.rios@avatar.com.co> and
26  *  Russell Bryant <russell@digium.com> from
27  *  cdr_mysql_custom by Edward Eastman <ed@dm3.co.uk>,
28  *      and cdr_sqlite by Holger Schurig <hs4233@mail.mn-solutions.de>
29  *
30  *
31  * \arg See also \ref AstCEL
32  *
33  *
34  * \ingroup cel_drivers
35  */
36
37 /*** MODULEINFO
38         <depend>sqlite3</depend>
39         <support_level>extended</support_level>
40  ***/
41
42 #include "asterisk.h"
43
44 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
45
46 #include <sqlite3.h>
47
48 #include "asterisk/paths.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/cel.h"
51 #include "asterisk/module.h"
52 #include "asterisk/config.h"
53 #include "asterisk/pbx.h"
54 #include "asterisk/logger.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/cli.h"
57 #include "asterisk/options.h"
58 #include "asterisk/stringfields.h"
59
60 #define SQLITE_BACKEND_NAME "CEL sqlite3 custom backend"
61
62 AST_MUTEX_DEFINE_STATIC(lock);
63
64 static const char config_file[] = "cel_sqlite3_custom.conf";
65
66 static const char name[] = "cel_sqlite3_custom";
67 static sqlite3 *db = NULL;
68
69 static char table[80];
70 /*!
71  * \bug Handling of this var is crash prone on reloads
72  */
73 static char *columns;
74
75 struct values {
76         char *expression;
77         AST_LIST_ENTRY(values) list;
78 };
79
80 static AST_LIST_HEAD_STATIC(sql_values, values);
81
82 static void free_config(void);
83
84 static int load_column_config(const char *tmp)
85 {
86         char *col = NULL;
87         char *cols = NULL, *save = NULL;
88         char *escaped = NULL;
89         struct ast_str *column_string = NULL;
90
91         if (ast_strlen_zero(tmp)) {
92                 ast_log(LOG_WARNING, "Column names not specified. Module not loaded.\n");
93                 return -1;
94         }
95         if (!(column_string = ast_str_create(1024))) {
96                 ast_log(LOG_ERROR, "Out of memory creating temporary buffer for column list for table '%s.'\n", table);
97                 return -1;
98         }
99         if (!(save = cols = ast_strdup(tmp))) {
100                 ast_log(LOG_ERROR, "Out of memory creating temporary buffer for column list for table '%s.'\n", table);
101                 ast_free(column_string);
102                 return -1;
103         }
104         while ((col = strsep(&cols, ","))) {
105                 col = ast_strip(col);
106                 escaped = sqlite3_mprintf("%q", col);
107                 if (!escaped) {
108                         ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s.'\n", col, table);
109                         ast_free(column_string);
110                         ast_free(save);
111                         return -1;
112                 }
113                 ast_str_append(&column_string, 0, "%s%s", ast_str_strlen(column_string) ? "," : "", escaped);
114                 sqlite3_free(escaped);
115         }
116         if (!(columns = ast_strdup(ast_str_buffer(column_string)))) {
117                 ast_log(LOG_ERROR, "Out of memory copying columns string for table '%s.'\n", table);
118                 ast_free(column_string);
119                 ast_free(save);
120                 return -1;
121         }
122         ast_free(column_string);
123         ast_free(save);
124
125         return 0;
126 }
127
128 static int load_values_config(const char *tmp)
129 {
130         char *val = NULL;
131         char *vals = NULL, *save = NULL;
132         struct values *value = NULL;
133
134         if (ast_strlen_zero(tmp)) {
135                 ast_log(LOG_WARNING, "Values not specified. Module not loaded.\n");
136                 return -1;
137         }
138         if (!(save = vals = ast_strdup(tmp))) {
139                 ast_log(LOG_ERROR, "Out of memory creating temporary buffer for value '%s'\n", tmp);
140                 return -1;
141         }
142         while ((val = strsep(&vals, ","))) {
143                 /* Strip the single quotes off if they are there */
144                 val = ast_strip_quoted(val, "'", "'");
145                 value = ast_calloc(sizeof(char), sizeof(*value) + strlen(val) + 1);
146                 if (!value) {
147                         ast_log(LOG_ERROR, "Out of memory creating entry for value '%s'\n", val);
148                         ast_free(save);
149                         return -1;
150                 }
151                 value->expression = (char *) value + sizeof(*value);
152                 ast_copy_string(value->expression, val, strlen(val) + 1);
153                 AST_LIST_INSERT_TAIL(&sql_values, value, list);
154         }
155         ast_free(save);
156
157         return 0;
158 }
159
160 static int load_config(int reload)
161 {
162         struct ast_config *cfg;
163         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
164         struct ast_variable *mappingvar;
165         const char *tmp;
166
167         if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
168                 ast_log(LOG_WARNING, "Failed to %sload configuration file. %s\n",
169                         reload ? "re" : "", reload ? "" : "Module not activated.");
170                 return -1;
171         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
172                 return 0;
173         }
174
175         if (reload) {
176                 free_config();
177         }
178
179         if (!(mappingvar = ast_variable_browse(cfg, "master"))) {
180                 /* Nothing configured */
181                 ast_config_destroy(cfg);
182                 return -1;
183         }
184
185         /* Mapping must have a table name */
186         if (!ast_strlen_zero(tmp = ast_variable_retrieve(cfg, "master", "table"))) {
187                 ast_copy_string(table, tmp, sizeof(table));
188         } else {
189                 ast_log(LOG_WARNING, "Table name not specified.  Assuming cel.\n");
190                 strcpy(table, "cel");
191         }
192
193         /* Columns */
194         if (load_column_config(ast_variable_retrieve(cfg, "master", "columns"))) {
195                 ast_config_destroy(cfg);
196                 free_config();
197                 return -1;
198         }
199
200         /* Values */
201         if (load_values_config(ast_variable_retrieve(cfg, "master", "values"))) {
202                 ast_config_destroy(cfg);
203                 free_config();
204                 return -1;
205         }
206
207         ast_verb(3, "Logging CEL records to table '%s' in 'master.db'\n", table);
208
209         ast_config_destroy(cfg);
210
211         return 0;
212 }
213
214 static void free_config(void)
215 {
216         struct values *value;
217
218         if (db) {
219                 sqlite3_close(db);
220                 db = NULL;
221         }
222
223         if (columns) {
224                 ast_free(columns);
225                 columns = NULL;
226         }
227
228         while ((value = AST_LIST_REMOVE_HEAD(&sql_values, list))) {
229                 ast_free(value);
230         }
231 }
232
233 static void write_cel(struct ast_event *event)
234 {
235         char *error = NULL;
236         char *sql = NULL;
237
238         if (db == NULL) {
239                 /* Should not have loaded, but be failsafe. */
240                 return;
241         }
242
243         ast_mutex_lock(&lock);
244
245         { /* Make it obvious that only sql should be used outside of this block */
246                 char *escaped;
247                 char subst_buf[2048];
248                 struct values *value;
249                 struct ast_channel *dummy;
250                 struct ast_str *value_string = ast_str_create(1024);
251
252                 dummy = ast_cel_fabricate_channel_from_event(event);
253                 if (!dummy) {
254                         ast_log(LOG_ERROR, "Unable to fabricate channel from CEL event.\n");
255                         ast_free(value_string);
256                         ast_mutex_unlock(&lock);
257                         return;
258                 }
259                 AST_LIST_TRAVERSE(&sql_values, value, list) {
260                         pbx_substitute_variables_helper(dummy, value->expression, subst_buf, sizeof(subst_buf) - 1);
261                         escaped = sqlite3_mprintf("%q", subst_buf);
262                         ast_str_append(&value_string, 0, "%s'%s'", ast_str_strlen(value_string) ? "," : "", escaped);
263                         sqlite3_free(escaped);
264                 }
265                 sql = sqlite3_mprintf("INSERT INTO %q (%s) VALUES (%s)", table, columns, ast_str_buffer(value_string));
266                 ast_debug(1, "About to log: %s\n", sql);
267                 dummy = ast_channel_unref(dummy);
268                 ast_free(value_string);
269         }
270
271         if (sqlite3_exec(db, sql, NULL, NULL, &error) != SQLITE_OK) {
272                 ast_log(LOG_ERROR, "%s. SQL: %s.\n", error, sql);
273                 sqlite3_free(error);
274         }
275
276         if (sql) {
277                 sqlite3_free(sql);
278         }
279         ast_mutex_unlock(&lock);
280
281         return;
282 }
283
284 static int unload_module(void)
285 {
286         ast_cel_backend_unregister(SQLITE_BACKEND_NAME);
287
288         free_config();
289
290         return 0;
291 }
292
293 static int load_module(void)
294 {
295         char *error;
296         char filename[PATH_MAX];
297         int res;
298         char *sql;
299
300         if (load_config(0)) {
301                 return AST_MODULE_LOAD_DECLINE;
302         }
303
304         /* is the database there? */
305         snprintf(filename, sizeof(filename), "%s/master.db", ast_config_AST_LOG_DIR);
306         res = sqlite3_open(filename, &db);
307         if (res != SQLITE_OK) {
308                 ast_log(LOG_ERROR, "Could not open database %s.\n", filename);
309                 free_config();
310                 return AST_MODULE_LOAD_DECLINE;
311         }
312         sqlite3_busy_timeout(db, 1000);
313         /* is the table there? */
314         sql = sqlite3_mprintf("SELECT COUNT(*) FROM %q;", table);
315         res = sqlite3_exec(db, sql, NULL, NULL, NULL);
316         sqlite3_free(sql);
317         if (res != SQLITE_OK) {
318                 /* We don't use %q for the column list here since we already escaped when building it */
319                 sql = sqlite3_mprintf("CREATE TABLE %q (AcctId INTEGER PRIMARY KEY, %s)", table, columns);
320                 res = sqlite3_exec(db, sql, NULL, NULL, &error);
321                 sqlite3_free(sql);
322                 if (res != SQLITE_OK) {
323                         ast_log(LOG_WARNING, "Unable to create table '%s': %s.\n", table, error);
324                         sqlite3_free(error);
325                         free_config();
326                         return AST_MODULE_LOAD_DECLINE;
327                 }
328         }
329
330         if (ast_cel_backend_register(SQLITE_BACKEND_NAME, write_cel)) {
331                 ast_log(LOG_ERROR, "Unable to register custom SQLite3 CEL handling\n");
332                 free_config();
333                 return AST_MODULE_LOAD_DECLINE;
334         }
335
336         return AST_MODULE_LOAD_SUCCESS;
337 }
338
339 static int reload(void)
340 {
341         int res = 0;
342
343         ast_mutex_lock(&lock);
344         res = load_config(1);
345         ast_mutex_unlock(&lock);
346
347         return res;
348 }
349
350 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "SQLite3 Custom CEL Module",
351         .load = load_module,
352         .unload = unload_module,
353         .reload = reload,
354         .load_pri = AST_MODPRI_CDR_DRIVER,
355 );