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