8ff3bd702ffe09e61fe84ffc32dd863e80b13594
[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         int count = 0;
238
239         if (db == NULL) {
240                 /* Should not have loaded, but be failsafe. */
241                 return;
242         }
243
244         ast_mutex_lock(&lock);
245
246         { /* Make it obvious that only sql should be used outside of this block */
247                 char *escaped;
248                 char subst_buf[2048];
249                 struct values *value;
250                 struct ast_channel *dummy;
251                 struct ast_str *value_string = ast_str_create(1024);
252
253                 dummy = ast_cel_fabricate_channel_from_event(event);
254                 if (!dummy) {
255                         ast_log(LOG_ERROR, "Unable to fabricate channel from CEL event.\n");
256                         ast_free(value_string);
257                         ast_mutex_unlock(&lock);
258                         return;
259                 }
260                 AST_LIST_TRAVERSE(&sql_values, value, list) {
261                         pbx_substitute_variables_helper(dummy, value->expression, subst_buf, sizeof(subst_buf) - 1);
262                         escaped = sqlite3_mprintf("%q", subst_buf);
263                         ast_str_append(&value_string, 0, "%s'%s'", ast_str_strlen(value_string) ? "," : "", escaped);
264                         sqlite3_free(escaped);
265                 }
266                 sql = sqlite3_mprintf("INSERT INTO %q (%s) VALUES (%s)", table, columns, ast_str_buffer(value_string));
267                 ast_debug(1, "About to log: %s\n", sql);
268                 dummy = ast_channel_unref(dummy);
269                 ast_free(value_string);
270         }
271
272         /* XXX This seems awful arbitrary... */
273         for (count = 0; count < 5; count++) {
274                 int res = sqlite3_exec(db, sql, NULL, NULL, &error);
275                 if (res != SQLITE_BUSY && res != SQLITE_LOCKED) {
276                         break;
277                 }
278                 usleep(200);
279         }
280
281         ast_mutex_unlock(&lock);
282
283         if (error) {
284                 ast_log(LOG_ERROR, "%s. SQL: %s.\n", error, sql);
285                 sqlite3_free(error);
286         }
287
288         if (sql) {
289                 sqlite3_free(sql);
290         }
291
292         return;
293 }
294
295 static int unload_module(void)
296 {
297         ast_cel_backend_unregister(SQLITE_BACKEND_NAME);
298
299         free_config();
300
301         return 0;
302 }
303
304 static int load_module(void)
305 {
306         char *error;
307         char filename[PATH_MAX];
308         int res;
309         char *sql;
310
311         if (load_config(0)) {
312                 return AST_MODULE_LOAD_DECLINE;
313         }
314
315         /* is the database there? */
316         snprintf(filename, sizeof(filename), "%s/master.db", ast_config_AST_LOG_DIR);
317         res = sqlite3_open(filename, &db);
318         if (res != SQLITE_OK) {
319                 ast_log(LOG_ERROR, "Could not open database %s.\n", filename);
320                 free_config();
321                 return AST_MODULE_LOAD_DECLINE;
322         }
323
324         /* is the table there? */
325         sql = sqlite3_mprintf("SELECT COUNT(*) FROM %q;", table);
326         res = sqlite3_exec(db, sql, NULL, NULL, NULL);
327         sqlite3_free(sql);
328         if (res != SQLITE_OK) {
329                 /* We don't use %q for the column list here since we already escaped when building it */
330                 sql = sqlite3_mprintf("CREATE TABLE %q (AcctId INTEGER PRIMARY KEY, %s)", table, columns);
331                 res = sqlite3_exec(db, sql, NULL, NULL, &error);
332                 sqlite3_free(sql);
333                 if (res != SQLITE_OK) {
334                         ast_log(LOG_WARNING, "Unable to create table '%s': %s.\n", table, error);
335                         sqlite3_free(error);
336                         free_config();
337                         return AST_MODULE_LOAD_DECLINE;
338                 }
339         }
340
341         if (ast_cel_backend_register(SQLITE_BACKEND_NAME, write_cel)) {
342                 ast_log(LOG_ERROR, "Unable to register custom SQLite3 CEL handling\n");
343                 free_config();
344                 return AST_MODULE_LOAD_DECLINE;
345         }
346
347         return AST_MODULE_LOAD_SUCCESS;
348 }
349
350 static int reload(void)
351 {
352         int res = 0;
353
354         ast_mutex_lock(&lock);
355         res = load_config(1);
356         ast_mutex_unlock(&lock);
357
358         return res;
359 }
360
361 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "SQLite3 Custom CEL Module",
362         .load = load_module,
363         .unload = unload_module,
364         .reload = reload,
365         .load_pri = AST_MODPRI_CDR_DRIVER,
366 );