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