f276959a0570a78260c00d3f27339c403b6b3f6a
[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_BUF1(size)                                                                                                             \
362                         do {                                                                                                                            \
363                                 /* Lengthen buffer, if necessary */                                                             \
364                                 if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) {               \
365                                         if (ast_str_make_space(&sql, ((ast_str_size(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_BUF2(size)                                                                                                             \
376                         do {                                                                                                                            \
377                                 if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) {             \
378                                         if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) { \
379                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
380                                                 ast_free(sql);                                                                                  \
381                                                 ast_free(sql2);                                                                                 \
382                                                 AST_RWLIST_UNLOCK(&odbc_tables);                                                \
383                                                 return -1;                                                                                              \
384                                         }                                                                                                                       \
385                                 }                                                                                                                               \
386                         } while (0)
387
388 static int odbc_log(struct ast_cdr *cdr)
389 {
390         struct tables *tableptr;
391         struct columns *entry;
392         struct odbc_obj *obj;
393         struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
394         char *tmp;
395         char colbuf[1024], *colptr;
396         SQLHSTMT stmt = NULL;
397         SQLLEN rows = 0;
398         char *separator;
399         int quoted = 0;
400
401         if (!sql || !sql2) {
402                 if (sql)
403                         ast_free(sql);
404                 if (sql2)
405                         ast_free(sql2);
406                 return -1;
407         }
408
409         if (AST_RWLIST_RDLOCK(&odbc_tables)) {
410                 ast_log(LOG_ERROR, "Unable to lock table list.  Insert CDR(s) failed.\n");
411                 ast_free(sql);
412                 ast_free(sql2);
413                 return -1;
414         }
415
416         AST_LIST_TRAVERSE(&odbc_tables, tableptr, list) {
417                 separator = "";
418
419                 if (tableptr->quoted_identifiers != '\0'){
420                         quoted = 1;
421                 }
422
423                 if (ast_strlen_zero(tableptr->schema)) {
424                         if (quoted) {
425                                 ast_str_set(&sql, 0, "INSERT INTO %c%s%c (",
426                                         tableptr->quoted_identifiers, tableptr->table, tableptr->quoted_identifiers );
427                         }else{
428                                 ast_str_set(&sql, 0, "INSERT INTO %s (", tableptr->table);
429                         }
430                 } else {
431                         if (quoted) {
432                                 ast_str_set(&sql, 0, "INSERT INTO %c%s%c.%c%s%c (",
433                                                 tableptr->quoted_identifiers, tableptr->schema, tableptr->quoted_identifiers,
434                                                 tableptr->quoted_identifiers, tableptr->table,  tableptr->quoted_identifiers);
435                         }else{
436                                 ast_str_set(&sql, 0, "INSERT INTO %s.%s (", tableptr->schema, tableptr->table);
437                         }
438                 }
439                 ast_str_set(&sql2, 0, " VALUES (");
440
441                 /* No need to check the connection now; we'll handle any failure in prepare_and_execute */
442                 if (!(obj = ast_odbc_request_obj(tableptr->connection, 0))) {
443                         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));
444                         continue;
445                 }
446
447                 AST_LIST_TRAVERSE(&(tableptr->columns), entry, list) {
448                         int datefield = 0;
449                         if (strcasecmp(entry->cdrname, "start") == 0) {
450                                 datefield = 1;
451                         } else if (strcasecmp(entry->cdrname, "answer") == 0) {
452                                 datefield = 2;
453                         } else if (strcasecmp(entry->cdrname, "end") == 0) {
454                                 datefield = 3;
455                         }
456
457                         /* Check if we have a similarly named variable */
458                         if (entry->staticvalue) {
459                                 colptr = ast_strdupa(entry->staticvalue);
460                         } else if (datefield && tableptr->usegmtime) {
461                                 struct timeval date_tv = (datefield == 1) ? cdr->start : (datefield == 2) ? cdr->answer : cdr->end;
462                                 struct ast_tm tm = { 0, };
463                                 ast_localtime(&date_tv, &tm, "UTC");
464                                 ast_strftime(colbuf, sizeof(colbuf), "%Y-%m-%d %H:%M:%S", &tm);
465                                 colptr = colbuf;
466                         } else {
467                                 ast_cdr_format_var(cdr, entry->cdrname, &colptr, colbuf, sizeof(colbuf), datefield ? 0 : 1);
468                         }
469
470                         if (colptr) {
471                                 /* Check first if the column filters this entry.  Note that this
472                                  * is very specifically NOT ast_strlen_zero(), because the filter
473                                  * could legitimately specify that the field is blank, which is
474                                  * different from the field being unspecified (NULL). */
475                                 if ((entry->filtervalue && !entry->negatefiltervalue && strcasecmp(colptr, entry->filtervalue) != 0) ||
476                                         (entry->filtervalue && entry->negatefiltervalue && strcasecmp(colptr, entry->filtervalue) == 0)) {
477                                         ast_verb(4, "CDR column '%s' with value '%s' does not match filter of"
478                                                 " %s'%s'.  Cancelling this CDR.\n",
479                                                 entry->cdrname, colptr, entry->negatefiltervalue ? "!" : "", entry->filtervalue);
480                                         goto early_release;
481                                 }
482
483                                 /* Only a filter? */
484                                 if (ast_strlen_zero(entry->name))
485                                         continue;
486
487                                 LENGTHEN_BUF1(strlen(entry->name));
488
489                                 switch (entry->type) {
490                                 case SQL_CHAR:
491                                 case SQL_VARCHAR:
492                                 case SQL_LONGVARCHAR:
493 #ifdef HAVE_ODBC_WCHAR
494                                 case SQL_WCHAR:
495                                 case SQL_WVARCHAR:
496                                 case SQL_WLONGVARCHAR:
497 #endif
498                                 case SQL_BINARY:
499                                 case SQL_VARBINARY:
500                                 case SQL_LONGVARBINARY:
501                                 case SQL_GUID:
502                                         /* For these two field names, get the rendered form, instead of the raw
503                                          * form (but only when we're dealing with a character-based field).
504                                          */
505                                         if (strcasecmp(entry->name, "disposition") == 0) {
506                                                 ast_cdr_format_var(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0);
507                                         } else if (strcasecmp(entry->name, "amaflags") == 0) {
508                                                 ast_cdr_format_var(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0);
509                                         }
510
511                                         /* Truncate too-long fields */
512                                         if (entry->type != SQL_GUID) {
513                                                 if (strlen(colptr) > entry->octetlen) {
514                                                         colptr[entry->octetlen] = '\0';
515                                                 }
516                                         }
517
518                                         LENGTHEN_BUF2(strlen(colptr));
519
520                                         /* Encode value, with escaping */
521                                         ast_str_append(&sql2, 0, "%s'", separator);
522                                         for (tmp = colptr; *tmp; tmp++) {
523                                                 if (*tmp == '\'') {
524                                                         ast_str_append(&sql2, 0, "''");
525                                                 } else if (*tmp == '\\' && ast_odbc_backslash_is_escape(obj)) {
526                                                         ast_str_append(&sql2, 0, "\\\\");
527                                                 } else {
528                                                         ast_str_append(&sql2, 0, "%c", *tmp);
529                                                 }
530                                         }
531                                         ast_str_append(&sql2, 0, "'");
532                                         break;
533                                 case SQL_TYPE_DATE:
534                                         if (ast_strlen_zero(colptr)) {
535                                                 continue;
536                                         } else {
537                                                 int year = 0, month = 0, day = 0;
538                                                 if (sscanf(colptr, "%4d-%2d-%2d", &year, &month, &day) != 3 || year <= 0 ||
539                                                         month <= 0 || month > 12 || day < 0 || day > 31 ||
540                                                         ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
541                                                         (month == 2 && year % 400 == 0 && day > 29) ||
542                                                         (month == 2 && year % 100 == 0 && day > 28) ||
543                                                         (month == 2 && year % 4 == 0 && day > 29) ||
544                                                         (month == 2 && year % 4 != 0 && day > 28)) {
545                                                         ast_log(LOG_WARNING, "CDR variable %s is not a valid date ('%s').\n", entry->name, colptr);
546                                                         continue;
547                                                 }
548
549                                                 if (year > 0 && year < 100) {
550                                                         year += 2000;
551                                                 }
552
553                                                 LENGTHEN_BUF2(17);
554                                                 ast_str_append(&sql2, 0, "%s{ d '%04d-%02d-%02d' }", separator, year, month, day);
555                                         }
556                                         break;
557                                 case SQL_TYPE_TIME:
558                                         if (ast_strlen_zero(colptr)) {
559                                                 continue;
560                                         } else {
561                                                 int hour = 0, minute = 0, second = 0;
562                                                 int count = sscanf(colptr, "%2d:%2d:%2d", &hour, &minute, &second);
563
564                                                 if ((count != 2 && count != 3) || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
565                                                         ast_log(LOG_WARNING, "CDR variable %s is not a valid time ('%s').\n", entry->name, colptr);
566                                                         continue;
567                                                 }
568
569                                                 LENGTHEN_BUF2(15);
570                                                 ast_str_append(&sql2, 0, "%s{ t '%02d:%02d:%02d' }", separator, hour, minute, second);
571                                         }
572                                         break;
573                                 case SQL_TYPE_TIMESTAMP:
574                                 case SQL_TIMESTAMP:
575                                         if (ast_strlen_zero(colptr)) {
576                                                 continue;
577                                         } else {
578                                                 int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
579                                                 int count = sscanf(colptr, "%4d-%2d-%2d %2d:%2d:%2d", &year, &month, &day, &hour, &minute, &second);
580
581                                                 if ((count != 3 && count != 5 && count != 6) || year <= 0 ||
582                                                         month <= 0 || month > 12 || day < 0 || day > 31 ||
583                                                         ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
584                                                         (month == 2 && year % 400 == 0 && day > 29) ||
585                                                         (month == 2 && year % 100 == 0 && day > 28) ||
586                                                         (month == 2 && year % 4 == 0 && day > 29) ||
587                                                         (month == 2 && year % 4 != 0 && day > 28) ||
588                                                         hour > 23 || minute > 59 || second > 59 || hour < 0 || minute < 0 || second < 0) {
589                                                         ast_log(LOG_WARNING, "CDR variable %s is not a valid timestamp ('%s').\n", entry->name, colptr);
590                                                         continue;
591                                                 }
592
593                                                 if (year > 0 && year < 100) {
594                                                         year += 2000;
595                                                 }
596
597                                                 LENGTHEN_BUF2(26);
598                                                 ast_str_append(&sql2, 0, "%s{ ts '%04d-%02d-%02d %02d:%02d:%02d' }", separator, year, month, day, hour, minute, second);
599                                         }
600                                         break;
601                                 case SQL_INTEGER:
602                                         if (ast_strlen_zero(colptr)) {
603                                                 continue;
604                                         } else {
605                                                 int integer = 0;
606                                                 if (sscanf(colptr, "%30d", &integer) != 1) {
607                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
608                                                         continue;
609                                                 }
610
611                                                 LENGTHEN_BUF2(12);
612                                                 ast_str_append(&sql2, 0, "%s%d", separator, integer);
613                                         }
614                                         break;
615                                 case SQL_BIGINT:
616                                         if (ast_strlen_zero(colptr)) {
617                                                 continue;
618                                         } else {
619                                                 long long integer = 0;
620                                                 if (sscanf(colptr, "%30lld", &integer) != 1) {
621                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
622                                                         continue;
623                                                 }
624
625                                                 LENGTHEN_BUF2(24);
626                                                 ast_str_append(&sql2, 0, "%s%lld", separator, integer);
627                                         }
628                                         break;
629                                 case SQL_SMALLINT:
630                                         if (ast_strlen_zero(colptr)) {
631                                                 continue;
632                                         } else {
633                                                 short integer = 0;
634                                                 if (sscanf(colptr, "%30hd", &integer) != 1) {
635                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
636                                                         continue;
637                                                 }
638
639                                                 LENGTHEN_BUF2(6);
640                                                 ast_str_append(&sql2, 0, "%s%d", separator, integer);
641                                         }
642                                         break;
643                                 case SQL_TINYINT:
644                                         if (ast_strlen_zero(colptr)) {
645                                                 continue;
646                                         } else {
647                                                 signed char integer = 0;
648                                                 if (sscanf(colptr, "%30hhd", &integer) != 1) {
649                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
650                                                         continue;
651                                                 }
652
653                                                 LENGTHEN_BUF2(4);
654                                                 ast_str_append(&sql2, 0, "%s%d", separator, integer);
655                                         }
656                                         break;
657                                 case SQL_BIT:
658                                         if (ast_strlen_zero(colptr)) {
659                                                 continue;
660                                         } else {
661                                                 signed char integer = 0;
662                                                 if (sscanf(colptr, "%30hhd", &integer) != 1) {
663                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
664                                                         continue;
665                                                 }
666                                                 if (integer != 0)
667                                                         integer = 1;
668
669                                                 LENGTHEN_BUF2(2);
670                                                 ast_str_append(&sql2, 0, "%s%d", separator, integer);
671                                         }
672                                         break;
673                                 case SQL_NUMERIC:
674                                 case SQL_DECIMAL:
675                                         if (ast_strlen_zero(colptr)) {
676                                                 continue;
677                                         } else {
678                                                 double number = 0.0;
679
680                                                 if (!strcasecmp(entry->cdrname, "billsec")) {
681                                                         if (!ast_tvzero(cdr->answer)) {
682                                                                 snprintf(colbuf, sizeof(colbuf), "%lf",
683                                                                                         (double) (ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0));
684                                                         } else {
685                                                                 ast_copy_string(colbuf, "0", sizeof(colbuf));
686                                                         }
687                                                 } else if (!strcasecmp(entry->cdrname, "duration")) {
688                                                         snprintf(colbuf, sizeof(colbuf), "%lf",
689                                                                                 (double) (ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0));
690
691                                                         if (!ast_strlen_zero(colbuf)) {
692                                                                 colptr = colbuf;
693                                                         }
694                                                 }
695
696                                                 if (sscanf(colptr, "%30lf", &number) != 1) {
697                                                         ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
698                                                         continue;
699                                                 }
700
701                                                 LENGTHEN_BUF2(entry->decimals);
702                                                 ast_str_append(&sql2, 0, "%s%*.*lf", separator, entry->decimals, entry->radix, number);
703                                         }
704                                         break;
705                                 case SQL_FLOAT:
706                                 case SQL_REAL:
707                                 case SQL_DOUBLE:
708                                         if (ast_strlen_zero(colptr)) {
709                                                 continue;
710                                         } else {
711                                                 double number = 0.0;
712
713                                                 if (!strcasecmp(entry->cdrname, "billsec")) {
714                                                         if (!ast_tvzero(cdr->answer)) {
715                                                                 snprintf(colbuf, sizeof(colbuf), "%lf",
716                                                                                         (double) (ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0));
717                                                         } else {
718                                                                 ast_copy_string(colbuf, "0", sizeof(colbuf));
719                                                         }
720                                                 } else if (!strcasecmp(entry->cdrname, "duration")) {
721                                                         snprintf(colbuf, sizeof(colbuf), "%lf",
722                                                                                 (double) (ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0));
723
724                                                         if (!ast_strlen_zero(colbuf)) {
725                                                                 colptr = colbuf;
726                                                         }
727                                                 }
728
729                                                 if (sscanf(colptr, "%30lf", &number) != 1) {
730                                                         ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
731                                                         continue;
732                                                 }
733
734                                                 LENGTHEN_BUF2(entry->decimals);
735                                                 ast_str_append(&sql2, 0, "%s%lf", separator, number);
736                                         }
737                                         break;
738                                 default:
739                                         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);
740                                         continue;
741                                 }
742                                 if (quoted) {
743                                         ast_str_append(&sql, 0, "%s%s", separator, entry->name);
744                                 } else {
745                                         ast_str_append(&sql, 0, "%s%c%s%c", separator, tableptr->quoted_identifiers, entry->name, tableptr->quoted_identifiers);
746                                 }
747                                 separator = ", ";
748                         } else if (entry->filtervalue
749                                 && ((!entry->negatefiltervalue && entry->filtervalue[0] != '\0')
750                                         || (entry->negatefiltervalue && entry->filtervalue[0] == '\0'))) {
751                                 ast_log(AST_LOG_WARNING, "CDR column '%s' was not set and does not match filter of"
752                                         " %s'%s'.  Cancelling this CDR.\n",
753                                         entry->cdrname, entry->negatefiltervalue ? "!" : "",
754                                         entry->filtervalue);
755                                 goto early_release;
756                         }
757                 }
758
759                 /* Concatenate the two constructed buffers */
760                 LENGTHEN_BUF1(ast_str_strlen(sql2));
761                 ast_str_append(&sql, 0, ")");
762                 ast_str_append(&sql2, 0, ")");
763                 ast_str_append(&sql, 0, "%s", ast_str_buffer(sql2));
764
765                 ast_debug(3, "Executing [%s]\n", ast_str_buffer(sql));
766
767                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, ast_str_buffer(sql));
768                 if (stmt) {
769                         SQLRowCount(stmt, &rows);
770                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
771                 }
772                 if (rows == 0) {
773                         ast_log(LOG_WARNING, "cdr_adaptive_odbc: Insert failed on '%s:%s'.  CDR failed: %s\n", tableptr->connection, tableptr->table, ast_str_buffer(sql));
774                 }
775 early_release:
776                 ast_odbc_release_obj(obj);
777         }
778         AST_RWLIST_UNLOCK(&odbc_tables);
779
780         /* Next time, just allocate buffers that are that big to start with. */
781         if (ast_str_strlen(sql) > maxsize) {
782                 maxsize = ast_str_strlen(sql);
783         }
784         if (ast_str_strlen(sql2) > maxsize2) {
785                 maxsize2 = ast_str_strlen(sql2);
786         }
787
788         ast_free(sql);
789         ast_free(sql2);
790         return 0;
791 }
792
793 static int unload_module(void)
794 {
795         if (ast_cdr_unregister(name)) {
796                 return -1;
797         }
798
799         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
800                 ast_cdr_register(name, ast_module_info->description, odbc_log);
801                 ast_log(LOG_ERROR, "Unable to lock column list.  Unload failed.\n");
802                 return -1;
803         }
804
805         free_config();
806         AST_RWLIST_UNLOCK(&odbc_tables);
807         return 0;
808 }
809
810 static int load_module(void)
811 {
812         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
813                 ast_log(LOG_ERROR, "Unable to lock column list.  Load failed.\n");
814                 return 0;
815         }
816
817         load_config();
818         AST_RWLIST_UNLOCK(&odbc_tables);
819         ast_cdr_register(name, ast_module_info->description, odbc_log);
820         return 0;
821 }
822
823 static int reload(void)
824 {
825         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
826                 ast_log(LOG_ERROR, "Unable to lock column list.  Reload failed.\n");
827                 return -1;
828         }
829
830         free_config();
831         load_config();
832         AST_RWLIST_UNLOCK(&odbc_tables);
833         return 0;
834 }
835
836 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Adaptive ODBC CDR backend",
837         .support_level = AST_MODULE_SUPPORT_CORE,
838         .load = load_module,
839         .unload = unload_module,
840         .reload = reload,
841         .load_pri = AST_MODPRI_CDR_DRIVER,
842 );
843