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