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