2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2007, Tilghman Lesher
6 * Tilghman Lesher <cdr_adaptive_odbc__v1@the-tilghman.com>
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.
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.
21 * \brief Adaptive ODBC CDR backend
23 * \author Tilghman Lesher <cdr_adaptive_odbc__v1@the-tilghman.com>
24 * \ingroup cdr_drivers
28 <depend>unixodbc</depend>
33 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35 #include <sys/types.h>
42 #include "asterisk/config.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/lock.h"
45 #include "asterisk/linkedlists.h"
46 #include "asterisk/res_odbc.h"
47 #include "asterisk/cdr.h"
48 #include "asterisk/module.h"
50 #define CONFIG "cdr_adaptive_odbc.conf"
52 static char *name = "Adaptive ODBC";
53 /* Optimization to reduce number of memory allocations */
54 static int maxsize = 512, maxsize2 = 512;
66 AST_LIST_ENTRY(columns) list;
72 unsigned int usegmtime:1;
73 AST_LIST_HEAD_NOLOCK(odbc_columns, columns) columns;
74 AST_RWLIST_ENTRY(tables) list;
77 static AST_RWLIST_HEAD_STATIC(odbc_tables, tables);
79 static int load_config(void)
81 struct ast_config *cfg;
82 struct ast_variable *var;
83 const char *tmp, *catg;
84 struct tables *tableptr;
85 struct columns *entry;
90 int lenconnection, lentable, usegmtime;
94 struct ast_flags config_flags = { 0 }; /* Part of our config comes from the database */
96 cfg = ast_config_load(CONFIG, config_flags);
98 ast_log(LOG_WARNING, "Unable to load " CONFIG ". No adaptive ODBC CDRs.\n");
102 for (catg = ast_category_browse(cfg, NULL); catg; catg = ast_category_browse(cfg, catg)) {
103 var = ast_variable_browse(cfg, catg);
107 if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "connection"))) {
108 ast_log(LOG_WARNING, "No connection parameter found in '%s'. Skipping.\n", catg);
111 ast_copy_string(connection, tmp, sizeof(connection));
112 lenconnection = strlen(connection);
114 if (!ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "usegmtime"))) {
115 usegmtime = ast_true(tmp);
118 /* When loading, we want to be sure we can connect. */
119 obj = ast_odbc_request_obj(connection, 1);
121 ast_log(LOG_WARNING, "No such connection '%s' in the '%s' section of " CONFIG ". Check res_odbc.conf.\n", connection, catg);
125 if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "table"))) {
126 ast_log(LOG_NOTICE, "No table name found. Assuming 'cdr'.\n");
129 ast_copy_string(table, tmp, sizeof(table));
130 lentable = strlen(table);
132 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
133 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
134 ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", connection);
135 ast_odbc_release_obj(obj);
139 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)table, SQL_NTS, (unsigned char *)"%", SQL_NTS);
140 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
141 ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'. Skipping.\n", connection);
142 ast_odbc_release_obj(obj);
146 tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + lenconnection + 1 + lentable + 1);
148 ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", table, connection);
149 ast_odbc_release_obj(obj);
154 tableptr->usegmtime = usegmtime;
155 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
156 tableptr->table = (char *)tableptr + sizeof(*tableptr) + lenconnection + 1;
157 ast_copy_string(tableptr->connection, connection, lenconnection + 1);
158 ast_copy_string(tableptr->table, table, lentable + 1);
160 ast_verb(3, "Found adaptive CDR table %s@%s.\n", tableptr->table, tableptr->connection);
162 /* Check for filters first */
163 for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
164 if (strncmp(var->name, "filter", 6) == 0) {
165 char *cdrvar = ast_strdupa(var->name + 6);
166 cdrvar = ast_strip(cdrvar);
167 ast_verb(3, "Found filter %s for cdr variable %s in %s@%s\n", var->value, cdrvar, tableptr->table, tableptr->connection);
169 entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(cdrvar) + 1 + strlen(var->value) + 1);
171 ast_log(LOG_ERROR, "Out of memory creating filter entry for CDR variable '%s' in table '%s' on connection '%s'\n", cdrvar, table, connection);
176 /* NULL column entry means this isn't a column in the database */
178 entry->cdrname = (char *)entry + sizeof(*entry);
179 entry->filtervalue = (char *)entry + sizeof(*entry) + strlen(cdrvar) + 1;
180 strcpy(entry->cdrname, cdrvar);
181 strcpy(entry->filtervalue, var->value);
183 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
187 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
190 SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
192 /* Is there an alias for this column? */
194 /* NOTE: This seems like a non-optimal parse method, but I'm going
195 * for user configuration readability, rather than fast parsing. We
196 * really don't parse this file all that often, anyway.
198 for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
199 if (strncmp(var->name, "alias", 5) == 0 && strcasecmp(var->value, columnname) == 0) {
200 char *alias = ast_strdupa(var->name + 5);
201 cdrvar = ast_strip(alias);
202 ast_verb(3, "Found alias %s for column %s in %s@%s\n", cdrvar, columnname, tableptr->table, tableptr->connection);
207 entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1 + strlen(cdrvar) + 1);
209 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, table, connection);
213 entry->name = (char *)entry + sizeof(*entry);
214 strcpy(entry->name, columnname);
216 if (!ast_strlen_zero(cdrvar)) {
217 entry->cdrname = entry->name + strlen(columnname) + 1;
218 strcpy(entry->cdrname, cdrvar);
219 } else /* Point to same place as the column name */
220 entry->cdrname = (char *)entry + sizeof(*entry);
222 SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
223 SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
224 SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
225 SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
226 SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
227 SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
229 /* Specification states that the octenlen should be the maximum number of bytes
230 * returned in a char or binary column, but it seems that some drivers just set
231 * it to NULL. (Bad Postgres! No biscuit!) */
232 if (entry->octetlen == 0)
233 entry->octetlen = entry->size;
235 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);
236 /* Insert column info into column list */
237 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
241 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
242 ast_odbc_release_obj(obj);
244 if (AST_LIST_FIRST(&(tableptr->columns)))
245 AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
252 static int free_config(void)
254 struct tables *table;
255 struct columns *entry;
256 while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
257 while ((entry = AST_LIST_REMOVE_HEAD(&(table->columns), list))) {
265 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
270 SQLINTEGER nativeerror = 0, numfields = 0;
271 SQLSMALLINT diagbytes = 0;
272 unsigned char state[10], diagnostic[256];
274 res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
275 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
276 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
280 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
281 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
282 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
283 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
284 for (i = 0; i < numfields; i++) {
285 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
286 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
288 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
292 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
299 #define LENGTHEN_BUF1(size) \
301 /* Lengthen buffer, if necessary */ \
302 if (sql->used + size + 1 > sql->len) { \
303 if (ast_str_make_space(&sql, ((sql->len + size + 1) / 512 + 1) * 512) != 0) { \
304 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
307 AST_RWLIST_UNLOCK(&odbc_tables); \
313 #define LENGTHEN_BUF2(size) \
315 if (sql2->used + size + 1 > sql2->len) { \
316 if (ast_str_make_space(&sql2, ((sql2->len + size + 3) / 512 + 1) * 512) != 0) { \
317 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
320 AST_RWLIST_UNLOCK(&odbc_tables); \
326 static int odbc_log(struct ast_cdr *cdr)
328 struct tables *tableptr;
329 struct columns *entry;
330 struct odbc_obj *obj;
331 struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
333 char colbuf[1024], *colptr;
334 SQLHSTMT stmt = NULL;
345 if (AST_RWLIST_RDLOCK(&odbc_tables)) {
346 ast_log(LOG_ERROR, "Unable to lock table list. Insert CDR(s) failed.\n");
352 AST_LIST_TRAVERSE(&odbc_tables, tableptr, list) {
353 ast_str_set(&sql, 0, "INSERT INTO %s (", tableptr->table);
354 ast_str_set(&sql2, 0, " VALUES (");
356 /* No need to check the connection now; we'll handle any failure in prepare_and_execute */
357 if (!(obj = ast_odbc_request_obj(tableptr->connection, 0))) {
358 ast_log(LOG_WARNING, "cdr_adaptive_odbc: Unable to retrieve database handle for '%s:%s'. CDR failed: %s\n", tableptr->connection, tableptr->table, sql->str);
362 AST_LIST_TRAVERSE(&(tableptr->columns), entry, list) {
364 if (strcasecmp(entry->cdrname, "start") == 0) {
366 } else if (strcasecmp(entry->cdrname, "answer") == 0) {
368 } else if (strcasecmp(entry->cdrname, "end") == 0) {
372 /* Check if we have a similarly named variable */
373 if (datefield && tableptr->usegmtime) {
374 struct timeval tv = (datefield == 1) ? cdr->start : (datefield == 2) ? cdr->answer : cdr->end;
375 struct ast_tm tm = { 0, };
376 ast_localtime(&tv, &tm, "UTC");
377 ast_strftime(colbuf, sizeof(colbuf), "%Y-%m-%d %H:%M:%S", &tm);
379 ast_cdr_getvar(cdr, entry->cdrname, &colptr, colbuf, sizeof(colbuf), 0, datefield ? 0 : 1);
383 /* Check first if the column filters this entry. Note that this
384 * is very specifically NOT ast_strlen_zero(), because the filter
385 * could legitimately specify that the field is blank, which is
386 * different from the field being unspecified (NULL). */
387 if (entry->filtervalue && strcasecmp(colptr, entry->filtervalue) != 0) {
388 ast_verb(4, "CDR column '%s' with value '%s' does not match filter of"
389 " '%s'. Cancelling this CDR.\n",
390 entry->cdrname, colptr, entry->filtervalue);
395 if (ast_strlen_zero(entry->name))
398 LENGTHEN_BUF1(strlen(entry->name));
400 switch (entry->type) {
403 case SQL_LONGVARCHAR:
406 case SQL_LONGVARBINARY:
408 /* For these two field names, get the rendered form, instead of the raw
409 * form (but only when we're dealing with a character-based field).
411 if (strcasecmp(entry->name, "disposition") == 0)
412 ast_cdr_getvar(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0, 0);
413 else if (strcasecmp(entry->name, "amaflags") == 0)
414 ast_cdr_getvar(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0, 0);
416 /* Truncate too-long fields */
417 if (entry->type != SQL_GUID) {
418 if (strlen(colptr) > entry->octetlen)
419 colptr[entry->octetlen] = '\0';
422 ast_str_append(&sql, 0, "%s,", entry->name);
423 LENGTHEN_BUF2(strlen(colptr));
425 /* Encode value, with escaping */
426 ast_str_append(&sql2, 0, "'");
427 for (tmp = colptr; *tmp; tmp++) {
429 ast_str_append(&sql2, 0, "''");
430 } else if (*tmp == '\\' && ast_odbc_backslash_is_escape(obj)) {
431 ast_str_append(&sql2, 0, "\\\\");
433 ast_str_append(&sql2, 0, "%c", *tmp);
436 ast_str_append(&sql2, 0, "',");
440 int year = 0, month = 0, day = 0;
441 if (sscanf(colptr, "%d-%d-%d", &year, &month, &day) != 3 || year <= 0 ||
442 month <= 0 || month > 12 || day < 0 || day > 31 ||
443 ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
444 (month == 2 && year % 400 == 0 && day > 29) ||
445 (month == 2 && year % 100 == 0 && day > 28) ||
446 (month == 2 && year % 4 == 0 && day > 29) ||
447 (month == 2 && year % 4 != 0 && day > 28)) {
448 ast_log(LOG_WARNING, "CDR variable %s is not a valid date ('%s').\n", entry->name, colptr);
452 if (year > 0 && year < 100)
455 ast_str_append(&sql, 0, "%s,", entry->name);
457 ast_str_append(&sql2, 0, "{ d '%04d-%02d-%02d' },", year, month, day);
462 int hour = 0, minute = 0, second = 0;
463 int count = sscanf(colptr, "%d:%d:%d", &hour, &minute, &second);
465 if ((count != 2 && count != 3) || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
466 ast_log(LOG_WARNING, "CDR variable %s is not a valid time ('%s').\n", entry->name, colptr);
470 ast_str_append(&sql, 0, "%s,", entry->name);
472 ast_str_append(&sql2, 0, "{ t '%02d:%02d:%02d' },", hour, minute, second);
475 case SQL_TYPE_TIMESTAMP:
478 int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
479 int count = sscanf(colptr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
481 if ((count != 3 && count != 5 && count != 6) || year <= 0 ||
482 month <= 0 || month > 12 || day < 0 || day > 31 ||
483 ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
484 (month == 2 && year % 400 == 0 && day > 29) ||
485 (month == 2 && year % 100 == 0 && day > 28) ||
486 (month == 2 && year % 4 == 0 && day > 29) ||
487 (month == 2 && year % 4 != 0 && day > 28) ||
488 hour > 23 || minute > 59 || second > 59 || hour < 0 || minute < 0 || second < 0) {
489 ast_log(LOG_WARNING, "CDR variable %s is not a valid timestamp ('%s').\n", entry->name, colptr);
493 if (year > 0 && year < 100)
496 ast_str_append(&sql, 0, "%s,", entry->name);
498 ast_str_append(&sql2, 0, "{ ts '%04d-%02d-%02d %02d:%02d:%02d' },", year, month, day, hour, minute, second);
504 if (sscanf(colptr, "%d", &integer) != 1) {
505 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
509 ast_str_append(&sql, 0, "%s,", entry->name);
511 ast_str_append(&sql2, 0, "%d,", integer);
516 long long integer = 0;
517 if (sscanf(colptr, "%lld", &integer) != 1) {
518 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
522 ast_str_append(&sql, 0, "%s,", entry->name);
524 ast_str_append(&sql2, 0, "%lld,", integer);
530 if (sscanf(colptr, "%hd", &integer) != 1) {
531 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
535 ast_str_append(&sql, 0, "%s,", entry->name);
537 ast_str_append(&sql2, 0, "%d,", integer);
543 if (sscanf(colptr, "%hhd", &integer) != 1) {
544 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
548 ast_str_append(&sql, 0, "%s,", entry->name);
550 ast_str_append(&sql2, 0, "%d,", integer);
556 if (sscanf(colptr, "%hhd", &integer) != 1) {
557 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
563 ast_str_append(&sql, 0, "%s,", entry->name);
565 ast_str_append(&sql2, 0, "%d,", integer);
572 if (sscanf(colptr, "%lf", &number) != 1) {
573 ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
577 ast_str_append(&sql, 0, "%s,", entry->name);
578 LENGTHEN_BUF2(entry->decimals);
579 ast_str_append(&sql2, 0, "%*.*lf,", entry->decimals, entry->radix, number);
587 if (sscanf(colptr, "%lf", &number) != 1) {
588 ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
592 ast_str_append(&sql, 0, "%s,", entry->name);
593 LENGTHEN_BUF2(entry->decimals);
594 ast_str_append(&sql2, 0, "%lf,", number);
598 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);
603 /* Concatenate the two constructed buffers */
604 LENGTHEN_BUF1(sql2->used);
605 sql->str[sql->used - 1] = ')';
606 sql2->str[sql2->used - 1] = ')';
607 ast_str_append(&sql, 0, "%s", sql2->str);
609 ast_verb(11, "[%s]\n", sql->str);
611 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, sql->str);
613 SQLRowCount(stmt, &rows);
614 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
617 ast_log(LOG_WARNING, "cdr_adaptive_odbc: Insert failed on '%s:%s'. CDR failed: %s\n", tableptr->connection, tableptr->table, sql->str);
620 ast_odbc_release_obj(obj);
622 AST_RWLIST_UNLOCK(&odbc_tables);
624 /* Next time, just allocate buffers that are that big to start with. */
625 if (sql->used > maxsize)
627 if (sql2->used > maxsize2)
628 maxsize2 = sql2->used;
635 static int unload_module(void)
637 ast_cdr_unregister(name);
639 if (AST_RWLIST_WRLOCK(&odbc_tables)) {
640 ast_cdr_register(name, ast_module_info->description, odbc_log);
641 ast_log(LOG_ERROR, "Unable to lock column list. Unload failed.\n");
646 AST_RWLIST_UNLOCK(&odbc_tables);
650 static int load_module(void)
652 if (AST_RWLIST_WRLOCK(&odbc_tables)) {
653 ast_log(LOG_ERROR, "Unable to lock column list. Load failed.\n");
658 AST_RWLIST_UNLOCK(&odbc_tables);
659 ast_cdr_register(name, ast_module_info->description, odbc_log);
663 static int reload(void)
665 if (AST_RWLIST_WRLOCK(&odbc_tables)) {
666 ast_log(LOG_ERROR, "Unable to lock column list. Reload failed.\n");
672 AST_RWLIST_UNLOCK(&odbc_tables);
676 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Adaptive ODBC CDR backend",
678 .unload = unload_module,