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