Merged revisions 319812 via svnmerge from
[asterisk/asterisk.git] / cel / cel_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008 Digium
5  *
6  * Adapted from cdr_adaptive_odbc:
7  * Tilghman Lesher <tlesher AT digium DOT com>
8  * by Steve Murphy
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  * This program is free software, distributed under the terms of
17  * the GNU General Public License Version 2. See the LICENSE file
18  * at the top of the source tree.
19  */
20
21 /*! \file
22  *
23  * \brief ODBC CEL backend
24  *
25  * \author Tilghman Lesher <tlesher AT digium DOT com>
26  * \ingroup cel_drivers
27  */
28
29 /*** MODULEINFO
30         <depend>res_odbc</depend>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <sys/types.h>
38 #include <time.h>
39
40 #include <sql.h>
41 #include <sqlext.h>
42 #include <sqltypes.h>
43
44 #include "asterisk/config.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/lock.h"
47 #include "asterisk/linkedlists.h"
48 #include "asterisk/res_odbc.h"
49 #include "asterisk/cel.h"
50 #include "asterisk/module.h"
51
52 #define CONFIG  "cel_odbc.conf"
53 static struct ast_event_sub *event_sub = NULL;
54
55 /* Optimization to reduce number of memory allocations */
56 static int maxsize = 512, maxsize2 = 512;
57
58 struct columns {
59         char *name;
60         char *celname;
61         char *filtervalue;
62         char *staticvalue;
63         SQLSMALLINT type;
64         SQLINTEGER size;
65         SQLSMALLINT decimals;
66         SQLSMALLINT radix;
67         SQLSMALLINT nullable;
68         SQLINTEGER octetlen;
69         AST_LIST_ENTRY(columns) list;
70 };
71
72 struct tables {
73         char *connection;
74         char *table;
75         unsigned int usegmtime:1;
76         AST_LIST_HEAD_NOLOCK(odbc_columns, columns) columns;
77         AST_RWLIST_ENTRY(tables) list;
78 };
79
80 static AST_RWLIST_HEAD_STATIC(odbc_tables, tables);
81
82 static int load_config(void)
83 {
84         struct ast_config *cfg;
85         struct ast_variable *var;
86         const char *tmp, *catg;
87         struct tables *tableptr;
88         struct columns *entry;
89         struct odbc_obj *obj;
90         char columnname[80];
91         char connection[40];
92         char table[40];
93         int lenconnection, lentable, usegmtime = 0;
94         SQLLEN sqlptr;
95         int res = 0;
96         SQLHSTMT stmt = NULL;
97         struct ast_flags config_flags = { 0 }; /* Part of our config comes from the database */
98
99         cfg = ast_config_load(CONFIG, config_flags);
100         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
101                 ast_log(LOG_WARNING, "Unable to load " CONFIG ".  No ODBC CEL records!\n");
102                 return -1;
103         }
104
105         for (catg = ast_category_browse(cfg, NULL); catg; catg = ast_category_browse(cfg, catg)) {
106                 var = ast_variable_browse(cfg, catg);
107                 if (!var)
108                         continue;
109
110                 if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "connection"))) {
111                         ast_log(LOG_WARNING, "No connection parameter found in '%s'.  Skipping.\n", catg);
112                         continue;
113                 }
114                 ast_copy_string(connection, tmp, sizeof(connection));
115                 lenconnection = strlen(connection);
116
117                 if (!ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "usegmtime"))) {
118                         usegmtime = ast_true(tmp);
119                 }
120
121                 /* When loading, we want to be sure we can connect. */
122                 obj = ast_odbc_request_obj(connection, 1);
123                 if (!obj) {
124                         ast_log(LOG_WARNING, "No such connection '%s' in the '%s' section of " CONFIG ".  Check res_odbc.conf.\n", connection, catg);
125                         continue;
126                 }
127
128                 if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "table"))) {
129                         ast_log(LOG_NOTICE, "No table name found.  Assuming 'cel'.\n");
130                         tmp = "cel";
131                 }
132                 ast_copy_string(table, tmp, sizeof(table));
133                 lentable = strlen(table);
134
135                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
136                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
137                         ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", connection);
138                         ast_odbc_release_obj(obj);
139                         continue;
140                 }
141
142                 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)table, SQL_NTS, (unsigned char *)"%", SQL_NTS);
143                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
144                         ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.  Skipping.\n", connection);
145                         ast_odbc_release_obj(obj);
146                         continue;
147                 }
148
149                 tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + lenconnection + 1 + lentable + 1);
150                 if (!tableptr) {
151                         ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", table, connection);
152                         ast_odbc_release_obj(obj);
153                         res = -1;
154                         break;
155                 }
156
157                 tableptr->usegmtime = usegmtime;
158                 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
159                 tableptr->table = (char *)tableptr + sizeof(*tableptr) + lenconnection + 1;
160                 ast_copy_string(tableptr->connection, connection, lenconnection + 1);
161                 ast_copy_string(tableptr->table, table, lentable + 1);
162
163                 ast_verb(3, "Found CEL table %s@%s.\n", tableptr->table, tableptr->connection);
164
165                 /* Check for filters first */
166                 for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
167                         if (strncmp(var->name, "filter", 6) == 0) {
168                                 char *celvar = ast_strdupa(var->name + 6);
169                                 celvar = ast_strip(celvar);
170                                 ast_verb(3, "Found filter %s for cel variable %s in %s@%s\n", var->value, celvar, tableptr->table, tableptr->connection);
171
172                                 entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(celvar) + 1 + strlen(var->value) + 1);
173                                 if (!entry) {
174                                         ast_log(LOG_ERROR, "Out of memory creating filter entry for CEL variable '%s' in table '%s' on connection '%s'\n", celvar, table, connection);
175                                         res = -1;
176                                         break;
177                                 }
178
179                                 /* NULL column entry means this isn't a column in the database */
180                                 entry->name = NULL;
181                                 entry->celname = (char *)entry + sizeof(*entry);
182                                 entry->filtervalue = (char *)entry + sizeof(*entry) + strlen(celvar) + 1;
183                                 strcpy(entry->celname, celvar);
184                                 strcpy(entry->filtervalue, var->value);
185
186                                 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
187                         }
188                 }
189
190                 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
191                         char *celvar = "", *staticvalue = "";
192
193                         SQLGetData(stmt,  4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
194
195                         /* Is there an alias for this column? */
196
197                         /* NOTE: This seems like a non-optimal parse method, but I'm going
198                          * for user configuration readability, rather than fast parsing. We
199                          * really don't parse this file all that often, anyway.
200                          */
201                         for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
202                                 if (strncmp(var->name, "alias", 5) == 0 && strcasecmp(var->value, columnname) == 0) {
203                                         char *alias = ast_strdupa(var->name + 5);
204                                         celvar = ast_strip(alias);
205                                         ast_verb(3, "Found alias %s for column %s in %s@%s\n", celvar, columnname, tableptr->table, tableptr->connection);
206                                         break;
207                                 } else if (strncmp(var->name, "static", 6) == 0 && strcasecmp(var->value, columnname) == 0) {
208                                         char *item = ast_strdupa(var->name + 6);
209                                         item = ast_strip(item);
210                                         if (item[0] == '"' && item[strlen(item) - 1] == '"') {
211                                                 /* Remove surrounding quotes */
212                                                 item[strlen(item) - 1] = '\0';
213                                                 item++;
214                                         }
215                                         staticvalue = item;
216                                 }
217                         }
218
219                         entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1 + strlen(celvar) + 1 + strlen(staticvalue) + 1);
220                         if (!entry) {
221                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, table, connection);
222                                 res = -1;
223                                 break;
224                         }
225                         entry->name = (char *)entry + sizeof(*entry);
226                         strcpy(entry->name, columnname);
227
228                         if (!ast_strlen_zero(celvar)) {
229                                 entry->celname = entry->name + strlen(columnname) + 1;
230                                 strcpy(entry->celname, celvar);
231                         } else { /* Point to same place as the column name */
232                                 entry->celname = (char *)entry + sizeof(*entry);
233                         }
234
235                         if (!ast_strlen_zero(staticvalue)) {
236                                 entry->staticvalue = entry->celname + strlen(entry->celname) + 1;
237                                 strcpy(entry->staticvalue, staticvalue);
238                         }
239
240                         SQLGetData(stmt,  5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
241                         SQLGetData(stmt,  7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
242                         SQLGetData(stmt,  9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
243                         SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
244                         SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
245                         SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
246
247                         /* Specification states that the octenlen should be the maximum number of bytes
248                          * returned in a char or binary column, but it seems that some drivers just set
249                          * it to NULL. (Bad Postgres! No biscuit!) */
250                         if (entry->octetlen == 0)
251                                 entry->octetlen = entry->size;
252
253                         ast_verb(10, "Found %s column with type %hd with len %ld, octetlen %ld, and numlen (%hd,%hd)\n", entry->name, entry->type, (long) entry->size, (long) entry->octetlen, entry->decimals, entry->radix);
254                         /* Insert column info into column list */
255                         AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
256                         res = 0;
257                 }
258
259                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
260                 ast_odbc_release_obj(obj);
261
262                 if (AST_LIST_FIRST(&(tableptr->columns)))
263                         AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
264                 else
265                         ast_free(tableptr);
266         }
267         return res;
268 }
269
270 static int free_config(void)
271 {
272         struct tables *table;
273         struct columns *entry;
274         while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
275                 while ((entry = AST_LIST_REMOVE_HEAD(&(table->columns), list))) {
276                         ast_free(entry);
277                 }
278                 ast_free(table);
279         }
280         return 0;
281 }
282
283 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
284 {
285         int res, i;
286         char *sql = data;
287         SQLHSTMT stmt;
288         SQLINTEGER nativeerror = 0, numfields = 0;
289         SQLSMALLINT diagbytes = 0;
290         unsigned char state[10], diagnostic[256];
291
292         res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
293         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
294                 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
295                 return NULL;
296         }
297
298         res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
299         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
300                 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
301                 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
302                 for (i = 0; i < numfields; i++) {
303                         SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
304                         ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
305                         if (i > 10) {
306                                 ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
307                                 break;
308                         }
309                 }
310                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
311                 return NULL;
312         }
313
314         return stmt;
315 }
316
317 #define LENGTHEN_BUF1(size)                                                                                                             \
318                         do {                                                                                                                            \
319                                 /* Lengthen buffer, if necessary */                                                             \
320                                 if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) {               \
321                                         if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 1) / 512 + 1) * 512) != 0) { \
322                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CEL '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
323                                                 ast_free(sql);                                                                                  \
324                                                 ast_free(sql2);                                                                                 \
325                                                 AST_RWLIST_UNLOCK(&odbc_tables);                                                \
326                                                 return;                                                                                                 \
327                                         }                                                                                                                       \
328                                 }                                                                                                                               \
329                         } while (0)
330
331 #define LENGTHEN_BUF2(size)                                                                                                             \
332                         do {                                                                                                                            \
333                                 if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) {             \
334                                         if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) { \
335                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CEL '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
336                                                 ast_free(sql);                                                                                  \
337                                                 ast_free(sql2);                                                                                 \
338                                                 AST_RWLIST_UNLOCK(&odbc_tables);                                                \
339                                                 return;                                                                                                 \
340                                         }                                                                                                                       \
341                                 }                                                                                                                               \
342                         } while (0)
343
344 static void odbc_log(const struct ast_event *event, void *userdata)
345 {
346         struct tables *tableptr;
347         struct columns *entry;
348         struct odbc_obj *obj;
349         struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
350         char *tmp;
351         char colbuf[1024], *colptr;
352         SQLHSTMT stmt = NULL;
353         SQLLEN rows = 0;
354         struct ast_cel_event_record record = {
355                 .version = AST_CEL_EVENT_RECORD_VERSION,
356         };
357
358         if (ast_cel_fill_record(event, &record)) {
359                 return;
360         }
361
362         if (!sql || !sql2) {
363                 if (sql)
364                         ast_free(sql);
365                 if (sql2)
366                         ast_free(sql2);
367                 return;
368         }
369
370         if (AST_RWLIST_RDLOCK(&odbc_tables)) {
371                 ast_log(LOG_ERROR, "Unable to lock table list.  Insert CEL(s) failed.\n");
372                 ast_free(sql);
373                 ast_free(sql2);
374                 return;
375         }
376
377         AST_LIST_TRAVERSE(&odbc_tables, tableptr, list) {
378                 int first = 1;
379                 ast_str_set(&sql, 0, "INSERT INTO %s (", tableptr->table);
380                 ast_str_set(&sql2, 0, " VALUES (");
381
382                 /* No need to check the connection now; we'll handle any failure in prepare_and_execute */
383                 if (!(obj = ast_odbc_request_obj(tableptr->connection, 0))) {
384                         ast_log(LOG_WARNING, "Unable to retrieve database handle for '%s:%s'.  CEL failed: %s\n", tableptr->connection, tableptr->table, ast_str_buffer(sql));
385                         continue;
386                 }
387
388                 AST_LIST_TRAVERSE(&(tableptr->columns), entry, list) {
389                         int datefield = 0;
390                         if (strcasecmp(entry->celname, "eventtime") == 0) {
391                                 datefield = 1;
392                         }
393
394                         /* Check if we have a similarly named variable */
395                         if (entry->staticvalue) {
396                                 colptr = ast_strdupa(entry->staticvalue);
397                         } else if (datefield) {
398                                 struct timeval date_tv = record.event_time;
399                                 struct ast_tm tm = { 0, };
400                                 ast_localtime(&date_tv, &tm, tableptr->usegmtime ? "UTC" : NULL);
401                                 ast_strftime(colbuf, sizeof(colbuf), "%Y-%m-%d %H:%M:%S", &tm);
402                                 colptr = colbuf;
403                         } else {
404                                 if (strcmp(entry->celname, "userdeftype") == 0) {
405                                         ast_copy_string(colbuf, record.user_defined_name, sizeof(colbuf));
406                                 } else if (strcmp(entry->celname, "cid_name") == 0) {
407                                         ast_copy_string(colbuf, record.caller_id_name, sizeof(colbuf));
408                                 } else if (strcmp(entry->celname, "cid_num") == 0) {
409                                         ast_copy_string(colbuf, record.caller_id_num, sizeof(colbuf));
410                                 } else if (strcmp(entry->celname, "cid_ani") == 0) {
411                                         ast_copy_string(colbuf, record.caller_id_ani, sizeof(colbuf));
412                                 } else if (strcmp(entry->celname, "cid_rdnis") == 0) {
413                                         ast_copy_string(colbuf, record.caller_id_rdnis, sizeof(colbuf));
414                                 } else if (strcmp(entry->celname, "cid_dnid") == 0) {
415                                         ast_copy_string(colbuf, record.caller_id_dnid, sizeof(colbuf));
416                                 } else if (strcmp(entry->celname, "exten") == 0) {
417                                         ast_copy_string(colbuf, record.extension, sizeof(colbuf));
418                                 } else if (strcmp(entry->celname, "context") == 0) {
419                                         ast_copy_string(colbuf, record.context, sizeof(colbuf));
420                                 } else if (strcmp(entry->celname, "channame") == 0) {
421                                         ast_copy_string(colbuf, record.channel_name, sizeof(colbuf));
422                                 } else if (strcmp(entry->celname, "appname") == 0) {
423                                         ast_copy_string(colbuf, record.application_name, sizeof(colbuf));
424                                 } else if (strcmp(entry->celname, "appdata") == 0) {
425                                         ast_copy_string(colbuf, record.application_data, sizeof(colbuf));
426                                 } else if (strcmp(entry->celname, "accountcode") == 0) {
427                                         ast_copy_string(colbuf, record.account_code, sizeof(colbuf));
428                                 } else if (strcmp(entry->celname, "peeraccount") == 0) {
429                                         ast_copy_string(colbuf, record.peer_account, sizeof(colbuf));
430                                 } else if (strcmp(entry->celname, "uniqueid") == 0) {
431                                         ast_copy_string(colbuf, record.unique_id, sizeof(colbuf));
432                                 } else if (strcmp(entry->celname, "linkedid") == 0) {
433                                         ast_copy_string(colbuf, record.linked_id, sizeof(colbuf));
434                                 } else if (strcmp(entry->celname, "userfield") == 0) {
435                                         ast_copy_string(colbuf, record.user_field, sizeof(colbuf));
436                                 } else if (strcmp(entry->celname, "peer") == 0) {
437                                         ast_copy_string(colbuf, record.peer, sizeof(colbuf));
438                                 } else if (strcmp(entry->celname, "amaflags") == 0) {
439                                         snprintf(colbuf, sizeof(colbuf), "%d", record.amaflag);
440                                 } else {
441                                         colbuf[0] = 0;
442                                 }
443                                 colptr = colbuf;
444                         }
445
446                         if (colptr) {
447                                 /* Check first if the column filters this entry.  Note that this
448                                  * is very specifically NOT ast_strlen_zero(), because the filter
449                                  * could legitimately specify that the field is blank, which is
450                                  * different from the field being unspecified (NULL). */
451                                 if (entry->filtervalue && strcasecmp(colptr, entry->filtervalue) != 0) {
452                                         ast_verb(4, "CEL column '%s' with value '%s' does not match filter of"
453                                                 " '%s'.  Cancelling this CEL.\n",
454                                                 entry->celname, colptr, entry->filtervalue);
455                                         goto early_release;
456                                 }
457
458                                 /* Only a filter? */
459                                 if (ast_strlen_zero(entry->name))
460                                         continue;
461
462                                 LENGTHEN_BUF1(strlen(entry->name));
463
464                                 switch (entry->type) {
465                                 case SQL_CHAR:
466                                 case SQL_VARCHAR:
467                                 case SQL_LONGVARCHAR:
468                                 case SQL_BINARY:
469                                 case SQL_VARBINARY:
470                                 case SQL_LONGVARBINARY:
471                                 case SQL_GUID:
472                                         /* For these two field names, get the rendered form, instead of the raw
473                                          * form (but only when we're dealing with a character-based field).
474                                          */
475                                         if (strcasecmp(entry->name, "eventtype") == 0) {
476                                                 snprintf(colbuf, sizeof(colbuf), "%s", record.event_name);
477                                         }
478
479                                         /* Truncate too-long fields */
480                                         if (entry->type != SQL_GUID) {
481                                                 if (strlen(colptr) > entry->octetlen) {
482                                                         colptr[entry->octetlen] = '\0';
483                                                 }
484                                         }
485
486                                         ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
487                                         LENGTHEN_BUF2(strlen(colptr));
488
489                                         /* Encode value, with escaping */
490                                         ast_str_append(&sql2, 0, "%s'", first ? "" : ",");
491                                         for (tmp = colptr; *tmp; tmp++) {
492                                                 if (*tmp == '\'') {
493                                                         ast_str_append(&sql2, 0, "''");
494                                                 } else if (*tmp == '\\' && ast_odbc_backslash_is_escape(obj)) {
495                                                         ast_str_append(&sql2, 0, "\\\\");
496                                                 } else {
497                                                         ast_str_append(&sql2, 0, "%c", *tmp);
498                                                 }
499                                         }
500                                         ast_str_append(&sql2, 0, "'");
501                                         break;
502                                 case SQL_TYPE_DATE:
503                                         if (ast_strlen_zero(colptr)) {
504                                                 continue;
505                                         } else {
506                                                 int year = 0, month = 0, day = 0;
507                                                 if (sscanf(colptr, "%4d-%2d-%2d", &year, &month, &day) != 3 || year <= 0 ||
508                                                         month <= 0 || month > 12 || day < 0 || day > 31 ||
509                                                         ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
510                                                         (month == 2 && year % 400 == 0 && day > 29) ||
511                                                         (month == 2 && year % 100 == 0 && day > 28) ||
512                                                         (month == 2 && year % 4 == 0 && day > 29) ||
513                                                         (month == 2 && year % 4 != 0 && day > 28)) {
514                                                         ast_log(LOG_WARNING, "CEL variable %s is not a valid date ('%s').\n", entry->name, colptr);
515                                                         continue;
516                                                 }
517
518                                                 if (year > 0 && year < 100) {
519                                                         year += 2000;
520                                                 }
521
522                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
523                                                 LENGTHEN_BUF2(17);
524                                                 ast_str_append(&sql2, 0, "%s{ d '%04d-%02d-%02d' }", first ? "" : ",", year, month, day);
525                                         }
526                                         break;
527                                 case SQL_TYPE_TIME:
528                                         if (ast_strlen_zero(colptr)) {
529                                                 continue;
530                                         } else {
531                                                 int hour = 0, minute = 0, second = 0;
532                                                 int count = sscanf(colptr, "%2d:%2d:%2d", &hour, &minute, &second);
533
534                                                 if ((count != 2 && count != 3) || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
535                                                         ast_log(LOG_WARNING, "CEL variable %s is not a valid time ('%s').\n", entry->name, colptr);
536                                                         continue;
537                                                 }
538
539                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
540                                                 LENGTHEN_BUF2(15);
541                                                 ast_str_append(&sql2, 0, "%s{ t '%02d:%02d:%02d' }", first ? "" : ",", hour, minute, second);
542                                         }
543                                         break;
544                                 case SQL_TYPE_TIMESTAMP:
545                                 case SQL_TIMESTAMP:
546                                         if (ast_strlen_zero(colptr)) {
547                                                 continue;
548                                         } else {
549                                                 int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
550                                                 int count = sscanf(colptr, "%4d-%2d-%2d %2d:%2d:%2d", &year, &month, &day, &hour, &minute, &second);
551
552                                                 if ((count != 3 && count != 5 && count != 6) || year <= 0 ||
553                                                         month <= 0 || month > 12 || day < 0 || day > 31 ||
554                                                         ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
555                                                         (month == 2 && year % 400 == 0 && day > 29) ||
556                                                         (month == 2 && year % 100 == 0 && day > 28) ||
557                                                         (month == 2 && year % 4 == 0 && day > 29) ||
558                                                         (month == 2 && year % 4 != 0 && day > 28) ||
559                                                         hour > 23 || minute > 59 || second > 59 || hour < 0 || minute < 0 || second < 0) {
560                                                         ast_log(LOG_WARNING, "CEL variable %s is not a valid timestamp ('%s').\n", entry->name, colptr);
561                                                         continue;
562                                                 }
563
564                                                 if (year > 0 && year < 100) {
565                                                         year += 2000;
566                                                 }
567
568                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
569                                                 LENGTHEN_BUF2(26);
570                                                 ast_str_append(&sql2, 0, "%s{ ts '%04d-%02d-%02d %02d:%02d:%02d' }", first ? "" : ",", year, month, day, hour, minute, second);
571                                         }
572                                         break;
573                                 case SQL_INTEGER:
574                                         {
575                                                 int integer = 0;
576                                                 if (strcasecmp(entry->name, "eventtype") == 0) {
577                                                         integer = (int) record.event_type;
578                                                 } else if (ast_strlen_zero(colptr)) {
579                                                         continue;
580                                                 } else if (sscanf(colptr, "%30d", &integer) != 1) {
581                                                         ast_log(LOG_WARNING, "CEL variable %s is not an integer.\n", entry->name);
582                                                         continue;
583                                                 }
584
585                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
586                                                 LENGTHEN_BUF2(12);
587                                                 ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
588                                         }
589                                         break;
590                                 case SQL_BIGINT:
591                                         {
592                                                 long long integer = 0;
593                                                 if (strcasecmp(entry->name, "eventtype") == 0) {
594                                                         integer = (long long) record.event_type;
595                                                 } else if (ast_strlen_zero(colptr)) {
596                                                         continue;
597                                                 } else if (sscanf(colptr, "%30lld", &integer) != 1) {
598                                                         ast_log(LOG_WARNING, "CEL variable %s is not an integer.\n", entry->name);
599                                                         continue;
600                                                 }
601
602                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
603                                                 LENGTHEN_BUF2(24);
604                                                 ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", integer);
605                                         }
606                                         break;
607                                 case SQL_SMALLINT:
608                                         {
609                                                 short integer = 0;
610                                                 if (strcasecmp(entry->name, "eventtype") == 0) {
611                                                         integer = (short) record.event_type;
612                                                 } else if (ast_strlen_zero(colptr)) {
613                                                         continue;
614                                                 } else if (sscanf(colptr, "%30hd", &integer) != 1) {
615                                                         ast_log(LOG_WARNING, "CEL variable %s is not an integer.\n", entry->name);
616                                                         continue;
617                                                 }
618
619                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
620                                                 LENGTHEN_BUF2(6);
621                                                 ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
622                                         }
623                                         break;
624                                 case SQL_TINYINT:
625                                         {
626                                                 char integer = 0;
627                                                 if (strcasecmp(entry->name, "eventtype") == 0) {
628                                                         integer = (char) record.event_type;
629                                                 } else if (ast_strlen_zero(colptr)) {
630                                                         continue;
631                                                 } else if (sscanf(colptr, "%30hhd", &integer) != 1) {
632                                                         ast_log(LOG_WARNING, "CEL variable %s is not an integer.\n", entry->name);
633                                                         continue;
634                                                 }
635
636                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
637                                                 LENGTHEN_BUF2(4);
638                                                 ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
639                                         }
640                                         break;
641                                 case SQL_BIT:
642                                         {
643                                                 char integer = 0;
644                                                 if (strcasecmp(entry->name, "eventtype") == 0) {
645                                                         integer = (char) record.event_type;
646                                                 } else if (ast_strlen_zero(colptr)) {
647                                                         continue;
648                                                 } else if (sscanf(colptr, "%30hhd", &integer) != 1) {
649                                                         ast_log(LOG_WARNING, "CEL variable %s is not an integer.\n", entry->name);
650                                                         continue;
651                                                 }
652                                                 if (integer != 0)
653                                                         integer = 1;
654
655                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
656                                                 LENGTHEN_BUF2(2);
657                                                 ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
658                                         }
659                                         break;
660                                 case SQL_NUMERIC:
661                                 case SQL_DECIMAL:
662                                         {
663                                                 double number = 0.0;
664                                                 if (strcasecmp(entry->name, "eventtype") == 0) {
665                                                         number = (double)record.event_type;
666                                                 } else if (ast_strlen_zero(colptr)) {
667                                                         continue;
668                                                 } else if (sscanf(colptr, "%30lf", &number) != 1) {
669                                                         ast_log(LOG_WARNING, "CEL variable %s is not an numeric type.\n", entry->name);
670                                                         continue;
671                                                 }
672
673                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
674                                                 LENGTHEN_BUF2(entry->decimals);
675                                                 ast_str_append(&sql2, 0, "%s%*.*lf", first ? "" : ",", entry->decimals, entry->radix, number);
676                                         }
677                                         break;
678                                 case SQL_FLOAT:
679                                 case SQL_REAL:
680                                 case SQL_DOUBLE:
681                                         {
682                                                 double number = 0.0;
683                                                 if (strcasecmp(entry->name, "eventtype") == 0) {
684                                                         number = (double) record.event_type;
685                                                 } else if (ast_strlen_zero(colptr)) {
686                                                         continue;
687                                                 } else if (sscanf(colptr, "%30lf", &number) != 1) {
688                                                         ast_log(LOG_WARNING, "CEL variable %s is not an numeric type.\n", entry->name);
689                                                         continue;
690                                                 }
691
692                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
693                                                 LENGTHEN_BUF2(entry->decimals);
694                                                 ast_str_append(&sql2, 0, "%s%lf", first ? "" : ",", number);
695                                         }
696                                         break;
697                                 default:
698                                         ast_log(LOG_WARNING, "Column type %d (field '%s:%s:%s') is unsupported at this time.\n", entry->type, tableptr->connection, tableptr->table, entry->name);
699                                         continue;
700                                 }
701                                 first = 0;
702                         }
703                 }
704
705                 /* Concatenate the two constructed buffers */
706                 LENGTHEN_BUF1(ast_str_strlen(sql2));
707                 ast_str_append(&sql, 0, ")");
708                 ast_str_append(&sql2, 0, ")");
709                 ast_str_append(&sql, 0, "%s", ast_str_buffer(sql2));
710
711                 ast_verb(11, "[%s]\n", ast_str_buffer(sql));
712
713                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, ast_str_buffer(sql));
714                 if (stmt) {
715                         SQLRowCount(stmt, &rows);
716                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
717                 }
718                 if (rows == 0) {
719                         ast_log(LOG_WARNING, "Insert failed on '%s:%s'.  CEL failed: %s\n", tableptr->connection, tableptr->table, ast_str_buffer(sql));
720                 }
721 early_release:
722                 ast_odbc_release_obj(obj);
723         }
724         AST_RWLIST_UNLOCK(&odbc_tables);
725
726         /* Next time, just allocate buffers that are that big to start with. */
727         if (ast_str_strlen(sql) > maxsize) {
728                 maxsize = ast_str_strlen(sql);
729         }
730         if (ast_str_strlen(sql2) > maxsize2) {
731                 maxsize2 = ast_str_strlen(sql2);
732         }
733
734         ast_free(sql);
735         ast_free(sql2);
736 }
737
738 static int unload_module(void)
739 {
740         if (event_sub) {
741                 event_sub = ast_event_unsubscribe(event_sub);
742         }
743         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
744                 event_sub = ast_event_subscribe(AST_EVENT_CEL, odbc_log, "ODBC CEL backend", NULL, AST_EVENT_IE_END);
745                 if (!event_sub) {
746                         ast_log(LOG_ERROR, "Unable to subscribe to CEL events\n");
747                 }
748                 ast_log(LOG_ERROR, "Unable to lock column list.  Unload failed.\n");
749                 return -1;
750         }
751
752         free_config();
753         AST_RWLIST_UNLOCK(&odbc_tables);
754         AST_RWLIST_HEAD_DESTROY(&odbc_tables);
755         
756         return 0;
757 }
758
759 static int load_module(void)
760 {
761         AST_RWLIST_HEAD_INIT(&odbc_tables);
762
763         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
764                 ast_log(LOG_ERROR, "Unable to lock column list.  Load failed.\n");
765                 return 0;
766         }
767         load_config();
768         AST_RWLIST_UNLOCK(&odbc_tables);
769         event_sub = ast_event_subscribe(AST_EVENT_CEL, odbc_log, "ODBC CEL backend", NULL, AST_EVENT_IE_END);
770         if (!event_sub) {
771                 ast_log(LOG_ERROR, "Unable to subscribe to CEL events\n");
772         }
773         return AST_MODULE_LOAD_SUCCESS;
774 }
775
776 static int reload(void)
777 {
778         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
779                 ast_log(LOG_ERROR, "Unable to lock column list.  Reload failed.\n");
780                 return -1;
781         }
782
783         free_config();
784         load_config();
785         AST_RWLIST_UNLOCK(&odbc_tables);
786         return AST_MODULE_LOAD_SUCCESS;
787 }
788
789 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "ODBC CEL backend",
790         .load = load_module,
791         .unload = unload_module,
792         .reload = reload,
793         .load_pri = AST_MODPRI_CDR_DRIVER,
794 );
795