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
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37 #include <sys/types.h>
44 #include "asterisk/config.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/lock.h"
47 #include "asterisk/linkedlists.h"
48 #include "asterisk/res_odbc.h"
49 #include "asterisk/cdr.h"
50 #include "asterisk/module.h"
52 #define CONFIG "cdr_adaptive_odbc.conf"
54 static char *name = "Adaptive ODBC";
55 /* Optimization to reduce number of memory allocations */
56 static int maxsize = 512, maxsize2 = 512;
68 AST_LIST_ENTRY(columns) list;
74 unsigned int usegmtime:1;
75 AST_LIST_HEAD_NOLOCK(odbc_columns, columns) columns;
76 AST_RWLIST_ENTRY(tables) list;
79 static AST_RWLIST_HEAD_STATIC(odbc_tables, tables);
81 static int load_config(void)
83 struct ast_config *cfg;
84 struct ast_variable *var;
85 const char *tmp, *catg;
86 struct tables *tableptr;
87 struct columns *entry;
92 int lenconnection, lentable, usegmtime = 0;
96 struct ast_flags config_flags = { 0 }; /* Part of our config comes from the database */
98 cfg = ast_config_load(CONFIG, config_flags);
100 ast_log(LOG_WARNING, "Unable to load " CONFIG ". No adaptive ODBC CDRs.\n");
104 for (catg = ast_category_browse(cfg, NULL); catg; catg = ast_category_browse(cfg, catg)) {
105 var = ast_variable_browse(cfg, catg);
109 if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "connection"))) {
110 ast_log(LOG_WARNING, "No connection parameter found in '%s'. Skipping.\n", catg);
113 ast_copy_string(connection, tmp, sizeof(connection));
114 lenconnection = strlen(connection);
116 if (!ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "usegmtime"))) {
117 usegmtime = ast_true(tmp);
120 /* When loading, we want to be sure we can connect. */
121 obj = ast_odbc_request_obj(connection, 1);
123 ast_log(LOG_WARNING, "No such connection '%s' in the '%s' section of " CONFIG ". Check res_odbc.conf.\n", connection, catg);
127 if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "table"))) {
128 ast_log(LOG_NOTICE, "No table name found. Assuming 'cdr'.\n");
131 ast_copy_string(table, tmp, sizeof(table));
132 lentable = strlen(table);
134 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
135 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
136 ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", connection);
137 ast_odbc_release_obj(obj);
141 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)table, SQL_NTS, (unsigned char *)"%", SQL_NTS);
142 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
143 ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'. Skipping.\n", connection);
144 ast_odbc_release_obj(obj);
148 tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + lenconnection + 1 + lentable + 1);
150 ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", table, connection);
151 ast_odbc_release_obj(obj);
156 tableptr->usegmtime = usegmtime;
157 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
158 tableptr->table = (char *)tableptr + sizeof(*tableptr) + lenconnection + 1;
159 ast_copy_string(tableptr->connection, connection, lenconnection + 1);
160 ast_copy_string(tableptr->table, table, lentable + 1);
162 ast_verb(3, "Found adaptive CDR table %s@%s.\n", tableptr->table, tableptr->connection);
164 /* Check for filters first */
165 for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
166 if (strncmp(var->name, "filter", 6) == 0) {
167 char *cdrvar = ast_strdupa(var->name + 6);
168 cdrvar = ast_strip(cdrvar);
169 ast_verb(3, "Found filter %s for cdr variable %s in %s@%s\n", var->value, cdrvar, tableptr->table, tableptr->connection);
171 entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(cdrvar) + 1 + strlen(var->value) + 1);
173 ast_log(LOG_ERROR, "Out of memory creating filter entry for CDR variable '%s' in table '%s' on connection '%s'\n", cdrvar, table, connection);
178 /* NULL column entry means this isn't a column in the database */
180 entry->cdrname = (char *)entry + sizeof(*entry);
181 entry->filtervalue = (char *)entry + sizeof(*entry) + strlen(cdrvar) + 1;
182 strcpy(entry->cdrname, cdrvar);
183 strcpy(entry->filtervalue, var->value);
185 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
189 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
192 SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
194 /* Is there an alias for this column? */
196 /* NOTE: This seems like a non-optimal parse method, but I'm going
197 * for user configuration readability, rather than fast parsing. We
198 * really don't parse this file all that often, anyway.
200 for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
201 if (strncmp(var->name, "alias", 5) == 0 && strcasecmp(var->value, columnname) == 0) {
202 char *alias = ast_strdupa(var->name + 5);
203 cdrvar = ast_strip(alias);
204 ast_verb(3, "Found alias %s for column %s in %s@%s\n", cdrvar, columnname, tableptr->table, tableptr->connection);
209 entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1 + strlen(cdrvar) + 1);
211 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, table, connection);
215 entry->name = (char *)entry + sizeof(*entry);
216 strcpy(entry->name, columnname);
218 if (!ast_strlen_zero(cdrvar)) {
219 entry->cdrname = entry->name + strlen(columnname) + 1;
220 strcpy(entry->cdrname, cdrvar);
221 } else /* Point to same place as the column name */
222 entry->cdrname = (char *)entry + sizeof(*entry);
224 SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
225 SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
226 SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
227 SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
228 SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
229 SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
231 /* Specification states that the octenlen should be the maximum number of bytes
232 * returned in a char or binary column, but it seems that some drivers just set
233 * it to NULL. (Bad Postgres! No biscuit!) */
234 if (entry->octetlen == 0)
235 entry->octetlen = entry->size;
237 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);
238 /* Insert column info into column list */
239 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
243 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
244 ast_odbc_release_obj(obj);
246 if (AST_LIST_FIRST(&(tableptr->columns)))
247 AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
254 static int free_config(void)
256 struct tables *table;
257 struct columns *entry;
258 while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
259 while ((entry = AST_LIST_REMOVE_HEAD(&(table->columns), list))) {
267 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
272 SQLINTEGER nativeerror = 0, numfields = 0;
273 SQLSMALLINT diagbytes = 0;
274 unsigned char state[10], diagnostic[256];
276 res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
277 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
278 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
282 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
283 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
284 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
285 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
286 for (i = 0; i < numfields; i++) {
287 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
288 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
290 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
294 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
301 #define LENGTHEN_BUF1(size) \
303 /* Lengthen buffer, if necessary */ \
304 if (sql->used + size + 1 > sql->len) { \
305 if (ast_str_make_space(&sql, ((sql->len + size + 1) / 512 + 1) * 512) != 0) { \
306 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
309 AST_RWLIST_UNLOCK(&odbc_tables); \
315 #define LENGTHEN_BUF2(size) \
317 if (sql2->used + size + 1 > sql2->len) { \
318 if (ast_str_make_space(&sql2, ((sql2->len + size + 3) / 512 + 1) * 512) != 0) { \
319 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
322 AST_RWLIST_UNLOCK(&odbc_tables); \
328 static int odbc_log(struct ast_cdr *cdr)
330 struct tables *tableptr;
331 struct columns *entry;
332 struct odbc_obj *obj;
333 struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
335 char colbuf[1024], *colptr;
336 SQLHSTMT stmt = NULL;
347 if (AST_RWLIST_RDLOCK(&odbc_tables)) {
348 ast_log(LOG_ERROR, "Unable to lock table list. Insert CDR(s) failed.\n");
354 AST_LIST_TRAVERSE(&odbc_tables, tableptr, list) {
355 ast_str_set(&sql, 0, "INSERT INTO %s (", tableptr->table);
356 ast_str_set(&sql2, 0, " VALUES (");
358 /* No need to check the connection now; we'll handle any failure in prepare_and_execute */
359 if (!(obj = ast_odbc_request_obj(tableptr->connection, 0))) {
360 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);
364 AST_LIST_TRAVERSE(&(tableptr->columns), entry, list) {
366 if (strcasecmp(entry->cdrname, "start") == 0) {
368 } else if (strcasecmp(entry->cdrname, "answer") == 0) {
370 } else if (strcasecmp(entry->cdrname, "end") == 0) {
374 /* Check if we have a similarly named variable */
375 if (datefield && tableptr->usegmtime) {
376 struct timeval date_tv = (datefield == 1) ? cdr->start : (datefield == 2) ? cdr->answer : cdr->end;
377 struct ast_tm tm = { 0, };
378 ast_localtime(&date_tv, &tm, "UTC");
379 ast_strftime(colbuf, sizeof(colbuf), "%Y-%m-%d %H:%M:%S", &tm);
381 ast_cdr_getvar(cdr, entry->cdrname, &colptr, colbuf, sizeof(colbuf), 0, datefield ? 0 : 1);
385 /* Check first if the column filters this entry. Note that this
386 * is very specifically NOT ast_strlen_zero(), because the filter
387 * could legitimately specify that the field is blank, which is
388 * different from the field being unspecified (NULL). */
389 if (entry->filtervalue && strcasecmp(colptr, entry->filtervalue) != 0) {
390 ast_verb(4, "CDR column '%s' with value '%s' does not match filter of"
391 " '%s'. Cancelling this CDR.\n",
392 entry->cdrname, colptr, entry->filtervalue);
397 if (ast_strlen_zero(entry->name))
400 LENGTHEN_BUF1(strlen(entry->name));
402 switch (entry->type) {
405 case SQL_LONGVARCHAR:
408 case SQL_LONGVARBINARY:
410 /* For these two field names, get the rendered form, instead of the raw
411 * form (but only when we're dealing with a character-based field).
413 if (strcasecmp(entry->name, "disposition") == 0)
414 ast_cdr_getvar(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0, 0);
415 else if (strcasecmp(entry->name, "amaflags") == 0)
416 ast_cdr_getvar(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0, 0);
418 /* Truncate too-long fields */
419 if (entry->type != SQL_GUID) {
420 if (strlen(colptr) > entry->octetlen)
421 colptr[entry->octetlen] = '\0';
424 ast_str_append(&sql, 0, "%s,", entry->name);
425 LENGTHEN_BUF2(strlen(colptr));
427 /* Encode value, with escaping */
428 ast_str_append(&sql2, 0, "'");
429 for (tmp = colptr; *tmp; tmp++) {
431 ast_str_append(&sql2, 0, "''");
432 } else if (*tmp == '\\' && ast_odbc_backslash_is_escape(obj)) {
433 ast_str_append(&sql2, 0, "\\\\");
435 ast_str_append(&sql2, 0, "%c", *tmp);
438 ast_str_append(&sql2, 0, "',");
442 int year = 0, month = 0, day = 0;
443 if (sscanf(colptr, "%d-%d-%d", &year, &month, &day) != 3 || year <= 0 ||
444 month <= 0 || month > 12 || day < 0 || day > 31 ||
445 ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
446 (month == 2 && year % 400 == 0 && day > 29) ||
447 (month == 2 && year % 100 == 0 && day > 28) ||
448 (month == 2 && year % 4 == 0 && day > 29) ||
449 (month == 2 && year % 4 != 0 && day > 28)) {
450 ast_log(LOG_WARNING, "CDR variable %s is not a valid date ('%s').\n", entry->name, colptr);
454 if (year > 0 && year < 100)
457 ast_str_append(&sql, 0, "%s,", entry->name);
459 ast_str_append(&sql2, 0, "{ d '%04d-%02d-%02d' },", year, month, day);
464 int hour = 0, minute = 0, second = 0;
465 int count = sscanf(colptr, "%d:%d:%d", &hour, &minute, &second);
467 if ((count != 2 && count != 3) || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
468 ast_log(LOG_WARNING, "CDR variable %s is not a valid time ('%s').\n", entry->name, colptr);
472 ast_str_append(&sql, 0, "%s,", entry->name);
474 ast_str_append(&sql2, 0, "{ t '%02d:%02d:%02d' },", hour, minute, second);
477 case SQL_TYPE_TIMESTAMP:
480 int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
481 int count = sscanf(colptr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
483 if ((count != 3 && count != 5 && count != 6) || year <= 0 ||
484 month <= 0 || month > 12 || day < 0 || day > 31 ||
485 ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
486 (month == 2 && year % 400 == 0 && day > 29) ||
487 (month == 2 && year % 100 == 0 && day > 28) ||
488 (month == 2 && year % 4 == 0 && day > 29) ||
489 (month == 2 && year % 4 != 0 && day > 28) ||
490 hour > 23 || minute > 59 || second > 59 || hour < 0 || minute < 0 || second < 0) {
491 ast_log(LOG_WARNING, "CDR variable %s is not a valid timestamp ('%s').\n", entry->name, colptr);
495 if (year > 0 && year < 100)
498 ast_str_append(&sql, 0, "%s,", entry->name);
500 ast_str_append(&sql2, 0, "{ ts '%04d-%02d-%02d %02d:%02d:%02d' },", year, month, day, hour, minute, second);
506 if (sscanf(colptr, "%d", &integer) != 1) {
507 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
511 ast_str_append(&sql, 0, "%s,", entry->name);
513 ast_str_append(&sql2, 0, "%d,", integer);
518 long long integer = 0;
519 if (sscanf(colptr, "%lld", &integer) != 1) {
520 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
524 ast_str_append(&sql, 0, "%s,", entry->name);
526 ast_str_append(&sql2, 0, "%lld,", integer);
532 if (sscanf(colptr, "%hd", &integer) != 1) {
533 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
537 ast_str_append(&sql, 0, "%s,", entry->name);
539 ast_str_append(&sql2, 0, "%d,", integer);
545 if (sscanf(colptr, "%hhd", &integer) != 1) {
546 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
550 ast_str_append(&sql, 0, "%s,", entry->name);
552 ast_str_append(&sql2, 0, "%d,", integer);
558 if (sscanf(colptr, "%hhd", &integer) != 1) {
559 ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
565 ast_str_append(&sql, 0, "%s,", entry->name);
567 ast_str_append(&sql2, 0, "%d,", integer);
574 if (sscanf(colptr, "%lf", &number) != 1) {
575 ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
579 ast_str_append(&sql, 0, "%s,", entry->name);
580 LENGTHEN_BUF2(entry->decimals);
581 ast_str_append(&sql2, 0, "%*.*lf,", entry->decimals, entry->radix, number);
589 if (sscanf(colptr, "%lf", &number) != 1) {
590 ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
594 ast_str_append(&sql, 0, "%s,", entry->name);
595 LENGTHEN_BUF2(entry->decimals);
596 ast_str_append(&sql2, 0, "%lf,", number);
600 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);
605 /* Concatenate the two constructed buffers */
606 LENGTHEN_BUF1(sql2->used);
607 sql->str[sql->used - 1] = ')';
608 sql2->str[sql2->used - 1] = ')';
609 ast_str_append(&sql, 0, "%s", sql2->str);
611 ast_verb(11, "[%s]\n", sql->str);
613 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, sql->str);
615 SQLRowCount(stmt, &rows);
616 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
619 ast_log(LOG_WARNING, "cdr_adaptive_odbc: Insert failed on '%s:%s'. CDR failed: %s\n", tableptr->connection, tableptr->table, sql->str);
622 ast_odbc_release_obj(obj);
624 AST_RWLIST_UNLOCK(&odbc_tables);
626 /* Next time, just allocate buffers that are that big to start with. */
627 if (sql->used > maxsize)
629 if (sql2->used > maxsize2)
630 maxsize2 = sql2->used;
637 static int unload_module(void)
639 ast_cdr_unregister(name);
641 if (AST_RWLIST_WRLOCK(&odbc_tables)) {
642 ast_cdr_register(name, ast_module_info->description, odbc_log);
643 ast_log(LOG_ERROR, "Unable to lock column list. Unload failed.\n");
648 AST_RWLIST_UNLOCK(&odbc_tables);
652 static int load_module(void)
654 if (AST_RWLIST_WRLOCK(&odbc_tables)) {
655 ast_log(LOG_ERROR, "Unable to lock column list. Load failed.\n");
660 AST_RWLIST_UNLOCK(&odbc_tables);
661 ast_cdr_register(name, ast_module_info->description, odbc_log);
665 static int reload(void)
667 if (AST_RWLIST_WRLOCK(&odbc_tables)) {
668 ast_log(LOG_ERROR, "Unable to lock column list. Reload failed.\n");
674 AST_RWLIST_UNLOCK(&odbc_tables);
678 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Adaptive ODBC CDR backend",
680 .unload = unload_module,