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