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