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