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