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