Merged revisions 186229 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 /*! \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>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 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         char *sql = data;
286         SQLHSTMT stmt;
287         SQLINTEGER nativeerror = 0, numfields = 0;
288         SQLSMALLINT diagbytes = 0;
289         unsigned char state[10], diagnostic[256];
290
291         res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
292         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
293                 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
294                 return NULL;
295         }
296
297         res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
298         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
299                 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
300                 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
301                 for (i = 0; i < numfields; i++) {
302                         SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
303                         ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
304                         if (i > 10) {
305                                 ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
306                                 break;
307                         }
308                 }
309                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
310                 return NULL;
311         }
312
313         return stmt;
314 }
315
316 #define LENGTHEN_BUF1(size)                                                                                                             \
317                         do {                                                                                                                            \
318                                 /* Lengthen buffer, if necessary */                                                             \
319                                 if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) {       \
320                                         if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 1) / 512 + 1) * 512) != 0) { \
321                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
322                                                 ast_free(sql);                                                                                  \
323                                                 ast_free(sql2);                                                                                 \
324                                                 AST_RWLIST_UNLOCK(&odbc_tables);                                                \
325                                                 return -1;                                                                                              \
326                                         }                                                                                                                       \
327                                 }                                                                                                                               \
328                         } while (0)
329
330 #define LENGTHEN_BUF2(size)                                                                                                             \
331                         do {                                                                                                                            \
332                                 if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) {     \
333                                         if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) { \
334                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
335                                                 ast_free(sql);                                                                                  \
336                                                 ast_free(sql2);                                                                                 \
337                                                 AST_RWLIST_UNLOCK(&odbc_tables);                                                \
338                                                 return -1;                                                                                              \
339                                         }                                                                                                                       \
340                                 }                                                                                                                               \
341                         } while (0)
342
343 static int odbc_log(struct ast_cdr *cdr)
344 {
345         struct tables *tableptr;
346         struct columns *entry;
347         struct odbc_obj *obj;
348         struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
349         char *tmp;
350         char colbuf[1024], *colptr;
351         SQLHSTMT stmt = NULL;
352         SQLLEN rows = 0;
353
354         if (!sql || !sql2) {
355                 if (sql)
356                         ast_free(sql);
357                 if (sql2)
358                         ast_free(sql2);
359                 return -1;
360         }
361
362         if (AST_RWLIST_RDLOCK(&odbc_tables)) {
363                 ast_log(LOG_ERROR, "Unable to lock table list.  Insert CDR(s) failed.\n");
364                 ast_free(sql);
365                 ast_free(sql2);
366                 return -1;
367         }
368
369         AST_LIST_TRAVERSE(&odbc_tables, tableptr, list) {
370                 int first = 1;
371                 ast_str_set(&sql, 0, "INSERT INTO %s (", tableptr->table);
372                 ast_str_set(&sql2, 0, " VALUES (");
373
374                 /* No need to check the connection now; we'll handle any failure in prepare_and_execute */
375                 if (!(obj = ast_odbc_request_obj(tableptr->connection, 0))) {
376                         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));
377                         continue;
378                 }
379
380                 AST_LIST_TRAVERSE(&(tableptr->columns), entry, list) {
381                         int datefield = 0;
382                         if (strcasecmp(entry->cdrname, "start") == 0) {
383                                 datefield = 1;
384                         } else if (strcasecmp(entry->cdrname, "answer") == 0) {
385                                 datefield = 2;
386                         } else if (strcasecmp(entry->cdrname, "end") == 0) {
387                                 datefield = 3;
388                         }
389
390                         /* Check if we have a similarly named variable */
391                         if (entry->staticvalue) {
392                                 colptr = ast_strdupa(entry->staticvalue);
393                         } else if (datefield && tableptr->usegmtime) {
394                                 struct timeval date_tv = (datefield == 1) ? cdr->start : (datefield == 2) ? cdr->answer : cdr->end;
395                                 struct ast_tm tm = { 0, };
396                                 ast_localtime(&date_tv, &tm, "UTC");
397                                 ast_strftime(colbuf, sizeof(colbuf), "%Y-%m-%d %H:%M:%S", &tm);
398                                 colptr = colbuf;
399                         } else {
400                                 ast_cdr_getvar(cdr, entry->cdrname, &colptr, colbuf, sizeof(colbuf), 0, datefield ? 0 : 1);
401                         }
402
403                         if (colptr) {
404                                 /* Check first if the column filters this entry.  Note that this
405                                  * is very specifically NOT ast_strlen_zero(), because the filter
406                                  * could legitimately specify that the field is blank, which is
407                                  * different from the field being unspecified (NULL). */
408                                 if (entry->filtervalue && strcasecmp(colptr, entry->filtervalue) != 0) {
409                                         ast_verb(4, "CDR column '%s' with value '%s' does not match filter of"
410                                                 " '%s'.  Cancelling this CDR.\n",
411                                                 entry->cdrname, colptr, entry->filtervalue);
412                                         goto early_release;
413                                 }
414
415                                 /* Only a filter? */
416                                 if (ast_strlen_zero(entry->name))
417                                         continue;
418
419                                 LENGTHEN_BUF1(strlen(entry->name));
420
421                                 switch (entry->type) {
422                                 case SQL_CHAR:
423                                 case SQL_VARCHAR:
424                                 case SQL_LONGVARCHAR:
425                                 case SQL_BINARY:
426                                 case SQL_VARBINARY:
427                                 case SQL_LONGVARBINARY:
428                                 case SQL_GUID:
429                                         /* For these two field names, get the rendered form, instead of the raw
430                                          * form (but only when we're dealing with a character-based field).
431                                          */
432                                         if (strcasecmp(entry->name, "disposition") == 0) {
433                                                 ast_cdr_getvar(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0, 0);
434                                         } else if (strcasecmp(entry->name, "amaflags") == 0) {
435                                                 ast_cdr_getvar(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0, 0);
436                                         }
437
438                                         /* Truncate too-long fields */
439                                         if (entry->type != SQL_GUID) {
440                                                 if (strlen(colptr) > entry->octetlen) {
441                                                         colptr[entry->octetlen] = '\0';
442                                                 }
443                                         }
444
445                                         ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
446                                         LENGTHEN_BUF2(strlen(colptr));
447
448                                         /* Encode value, with escaping */
449                                         ast_str_append(&sql2, 0, "%s'", first ? "" : ",");
450                                         for (tmp = colptr; *tmp; tmp++) {
451                                                 if (*tmp == '\'') {
452                                                         ast_str_append(&sql2, 0, "''");
453                                                 } else if (*tmp == '\\' && ast_odbc_backslash_is_escape(obj)) {
454                                                         ast_str_append(&sql2, 0, "\\\\");
455                                                 } else {
456                                                         ast_str_append(&sql2, 0, "%c", *tmp);
457                                                 }
458                                         }
459                                         ast_str_append(&sql2, 0, "'");
460                                         break;
461                                 case SQL_TYPE_DATE:
462                                         {
463                                                 int year = 0, month = 0, day = 0;
464                                                 if (sscanf(colptr, "%d-%d-%d", &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                                         {
486                                                 int hour = 0, minute = 0, second = 0;
487                                                 int count = sscanf(colptr, "%d:%d:%d", &hour, &minute, &second);
488
489                                                 if ((count != 2 && count != 3) || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
490                                                         ast_log(LOG_WARNING, "CDR variable %s is not a valid time ('%s').\n", entry->name, colptr);
491                                                         continue;
492                                                 }
493
494                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
495                                                 LENGTHEN_BUF2(15);
496                                                 ast_str_append(&sql2, 0, "%s{ t '%02d:%02d:%02d' }", first ? "" : ",", hour, minute, second);
497                                         }
498                                         break;
499                                 case SQL_TYPE_TIMESTAMP:
500                                 case SQL_TIMESTAMP:
501                                         {
502                                                 int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
503                                                 int count = sscanf(colptr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
504
505                                                 if ((count != 3 && count != 5 && count != 6) || year <= 0 ||
506                                                         month <= 0 || month > 12 || day < 0 || day > 31 ||
507                                                         ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
508                                                         (month == 2 && year % 400 == 0 && day > 29) ||
509                                                         (month == 2 && year % 100 == 0 && day > 28) ||
510                                                         (month == 2 && year % 4 == 0 && day > 29) ||
511                                                         (month == 2 && year % 4 != 0 && day > 28) ||
512                                                         hour > 23 || minute > 59 || second > 59 || hour < 0 || minute < 0 || second < 0) {
513                                                         ast_log(LOG_WARNING, "CDR variable %s is not a valid timestamp ('%s').\n", entry->name, colptr);
514                                                         continue;
515                                                 }
516
517                                                 if (year > 0 && year < 100) {
518                                                         year += 2000;
519                                                 }
520
521                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
522                                                 LENGTHEN_BUF2(26);
523                                                 ast_str_append(&sql2, 0, "%s{ ts '%04d-%02d-%02d %02d:%02d:%02d' }", first ? "" : ",", year, month, day, hour, minute, second);
524                                         }
525                                         break;
526                                 case SQL_INTEGER:
527                                         {
528                                                 int integer = 0;
529                                                 if (sscanf(colptr, "%d", &integer) != 1) {
530                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
531                                                         continue;
532                                                 }
533
534                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
535                                                 LENGTHEN_BUF2(12);
536                                                 ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
537                                         }
538                                         break;
539                                 case SQL_BIGINT:
540                                         {
541                                                 long long integer = 0;
542                                                 if (sscanf(colptr, "%lld", &integer) != 1) {
543                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
544                                                         continue;
545                                                 }
546
547                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
548                                                 LENGTHEN_BUF2(24);
549                                                 ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", integer);
550                                         }
551                                         break;
552                                 case SQL_SMALLINT:
553                                         {
554                                                 short integer = 0;
555                                                 if (sscanf(colptr, "%hd", &integer) != 1) {
556                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
557                                                         continue;
558                                                 }
559
560                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
561                                                 LENGTHEN_BUF2(6);
562                                                 ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
563                                         }
564                                         break;
565                                 case SQL_TINYINT:
566                                         {
567                                                 char integer = 0;
568                                                 if (sscanf(colptr, "%hhd", &integer) != 1) {
569                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
570                                                         continue;
571                                                 }
572
573                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
574                                                 LENGTHEN_BUF2(4);
575                                                 ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
576                                         }
577                                         break;
578                                 case SQL_BIT:
579                                         {
580                                                 char integer = 0;
581                                                 if (sscanf(colptr, "%hhd", &integer) != 1) {
582                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
583                                                         continue;
584                                                 }
585                                                 if (integer != 0)
586                                                         integer = 1;
587
588                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
589                                                 LENGTHEN_BUF2(2);
590                                                 ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
591                                         }
592                                         break;
593                                 case SQL_NUMERIC:
594                                 case SQL_DECIMAL:
595                                         {
596                                                 double number = 0.0;
597                                                 if (sscanf(colptr, "%lf", &number) != 1) {
598                                                         ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
599                                                         continue;
600                                                 }
601
602                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
603                                                 LENGTHEN_BUF2(entry->decimals);
604                                                 ast_str_append(&sql2, 0, "%s%*.*lf", first ? "" : ",", entry->decimals, entry->radix, number);
605                                         }
606                                         break;
607                                 case SQL_FLOAT:
608                                 case SQL_REAL:
609                                 case SQL_DOUBLE:
610                                         {
611                                                 double number = 0.0;
612                                                 if (sscanf(colptr, "%lf", &number) != 1) {
613                                                         ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
614                                                         continue;
615                                                 }
616
617                                                 ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
618                                                 LENGTHEN_BUF2(entry->decimals);
619                                                 ast_str_append(&sql2, 0, "%s%lf", first ? "" : ",", number);
620                                         }
621                                         break;
622                                 default:
623                                         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);
624                                         continue;
625                                 }
626                                 first = 0;
627                         }
628                 }
629
630                 /* Concatenate the two constructed buffers */
631                 LENGTHEN_BUF1(ast_str_strlen(sql2));
632                 ast_str_append(&sql, 0, ")");
633                 ast_str_append(&sql2, 0, ")");
634                 ast_str_append(&sql, 0, "%s", ast_str_buffer(sql2));
635
636                 ast_verb(11, "[%s]\n", ast_str_buffer(sql));
637
638                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, ast_str_buffer(sql));
639                 if (stmt) {
640                         SQLRowCount(stmt, &rows);
641                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
642                 }
643                 if (rows == 0) {
644                         ast_log(LOG_WARNING, "cdr_adaptive_odbc: Insert failed on '%s:%s'.  CDR failed: %s\n", tableptr->connection, tableptr->table, ast_str_buffer(sql));
645                 }
646 early_release:
647                 ast_odbc_release_obj(obj);
648         }
649         AST_RWLIST_UNLOCK(&odbc_tables);
650
651         /* Next time, just allocate buffers that are that big to start with. */
652         if (ast_str_strlen(sql) > maxsize) {
653                 maxsize = ast_str_strlen(sql);
654         }
655         if (ast_str_strlen(sql2) > maxsize2) {
656                 maxsize2 = ast_str_strlen(sql2);
657         }
658
659         ast_free(sql);
660         ast_free(sql2);
661         return 0;
662 }
663
664 static int unload_module(void)
665 {
666         ast_cdr_unregister(name);
667         usleep(1);
668         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
669                 ast_cdr_register(name, ast_module_info->description, odbc_log);
670                 ast_log(LOG_ERROR, "Unable to lock column list.  Unload failed.\n");
671                 return -1;
672         }
673
674         free_config();
675         AST_RWLIST_UNLOCK(&odbc_tables);
676         return 0;
677 }
678
679 static int load_module(void)
680 {
681         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
682                 ast_log(LOG_ERROR, "Unable to lock column list.  Load failed.\n");
683                 return 0;
684         }
685
686         load_config();
687         AST_RWLIST_UNLOCK(&odbc_tables);
688         ast_cdr_register(name, ast_module_info->description, odbc_log);
689         return 0;
690 }
691
692 static int reload(void)
693 {
694         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
695                 ast_log(LOG_ERROR, "Unable to lock column list.  Reload failed.\n");
696                 return -1;
697         }
698
699         free_config();
700         load_config();
701         AST_RWLIST_UNLOCK(&odbc_tables);
702         return 0;
703 }
704
705 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Adaptive ODBC CDR backend",
706         .load = load_module,
707         .unload = unload_module,
708         .reload = reload,
709 );
710