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