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