2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2004 - 2006, Digium, Inc.
6 * See http://www.asterisk.org for more information about
7 * the Asterisk project. Please do not directly contact
8 * any of the maintainers of this project for assistance;
9 * the project provides a web site, mailing lists and IRC
10 * channels for your use.
12 * This program is free software, distributed under the terms of
13 * the GNU General Public License Version 2. See the LICENSE file
14 * at the top of the source tree.
19 * \brief FreeTDS CDR logger
22 * \arg \ref Config_cdr
23 * \arg http://www.freetds.org/
24 * \ingroup cdr_drivers
30 * Table Structure for `cdr`
32 * Created on: 05/20/2004 16:16
33 * Last changed on: 07/27/2004 20:01
35 CREATE TABLE [dbo].[cdr] (
36 [accountcode] [varchar] (20) NULL ,
37 [src] [varchar] (80) NULL ,
38 [dst] [varchar] (80) NULL ,
39 [dcontext] [varchar] (80) NULL ,
40 [clid] [varchar] (80) NULL ,
41 [channel] [varchar] (80) NULL ,
42 [dstchannel] [varchar] (80) NULL ,
43 [lastapp] [varchar] (80) NULL ,
44 [lastdata] [varchar] (80) NULL ,
45 [start] [datetime] NULL ,
46 [answer] [datetime] NULL ,
47 [end] [datetime] NULL ,
48 [duration] [int] NULL ,
49 [billsec] [int] NULL ,
50 [disposition] [varchar] (20) NULL ,
51 [amaflags] [varchar] (16) NULL ,
52 [uniqueid] [varchar] (32) NULL ,
53 [userfield] [varchar] (256) NULL
61 <depend>freetds</depend>
62 <support_level>extended</support_level>
67 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
69 #include "asterisk/config.h"
70 #include "asterisk/channel.h"
71 #include "asterisk/cdr.h"
72 #include "asterisk/module.h"
77 #define DATE_FORMAT "%Y/%m/%d %T"
79 static const char name[] = "FreeTDS (MSSQL)";
80 static const char config[] = "cdr_tds.conf";
82 struct cdr_tds_config {
83 AST_DECLARE_STRING_FIELDS(
84 AST_STRING_FIELD(hostname);
85 AST_STRING_FIELD(database);
86 AST_STRING_FIELD(username);
87 AST_STRING_FIELD(password);
88 AST_STRING_FIELD(table);
89 AST_STRING_FIELD(charset);
90 AST_STRING_FIELD(language);
91 AST_STRING_FIELD(hrtime);
94 unsigned int connected:1;
95 unsigned int has_userfield:1;
98 AST_MUTEX_DEFINE_STATIC(tds_lock);
100 static struct cdr_tds_config *settings;
102 static char *anti_injection(const char *, int);
103 static void get_date(char *, size_t len, struct timeval);
105 static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
106 __attribute__((format(printf, 2, 3)));
108 static int mssql_connect(void);
109 static int mssql_disconnect(void);
111 static int tds_log(struct ast_cdr *cdr)
113 char start[80], answer[80], end[80];
114 char *accountcode, *src, *dst, *dcontext, *clid, *channel, *dstchannel, *lastapp, *lastdata, *uniqueid, *userfield = NULL;
119 accountcode = anti_injection(cdr->accountcode, 20);
120 src = anti_injection(cdr->src, 80);
121 dst = anti_injection(cdr->dst, 80);
122 dcontext = anti_injection(cdr->dcontext, 80);
123 clid = anti_injection(cdr->clid, 80);
124 channel = anti_injection(cdr->channel, 80);
125 dstchannel = anti_injection(cdr->dstchannel, 80);
126 lastapp = anti_injection(cdr->lastapp, 80);
127 lastdata = anti_injection(cdr->lastdata, 80);
128 uniqueid = anti_injection(cdr->uniqueid, 32);
130 get_date(start, sizeof(start), cdr->start);
131 get_date(answer, sizeof(answer), cdr->answer);
132 get_date(end, sizeof(end), cdr->end);
134 ast_mutex_lock(&tds_lock);
136 if (settings->has_userfield) {
137 userfield = anti_injection(cdr->userfield, AST_MAX_USER_FIELD);
141 /* Ensure that we are connected */
142 if (!settings->connected) {
143 ast_log(LOG_NOTICE, "Attempting to reconnect to %s (Attempt %d)\n", settings->hostname, attempt);
144 if (mssql_connect()) {
153 if (settings->has_userfield) {
154 if (settings->hrtime) {
155 double hrbillsec = 0.0;
158 if (!ast_tvzero(cdr->answer)) {
159 hrbillsec = (double)(ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0);
161 hrduration = (double)(ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0);
163 erc = dbfcmd(settings->dbproc,
166 "accountcode, src, dst, dcontext, clid, channel, "
167 "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
168 "billsec, disposition, amaflags, uniqueid, userfield"
172 "'%s', '%s', '%s', '%s', '%s', '%s', "
173 "'%s', '%s', '%s', %s, %s, %s, %lf, "
174 "%lf, '%s', '%s', '%s', '%s'"
177 accountcode, src, dst, dcontext, clid, channel,
178 dstchannel, lastapp, lastdata, start, answer, end, hrduration,
179 hrbillsec, ast_cdr_disp2str(cdr->disposition), ast_channel_amaflags2string(cdr->amaflags), uniqueid,
183 erc = dbfcmd(settings->dbproc,
186 "accountcode, src, dst, dcontext, clid, channel, "
187 "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
188 "billsec, disposition, amaflags, uniqueid, userfield"
192 "'%s', '%s', '%s', '%s', '%s', '%s', "
193 "'%s', '%s', '%s', %s, %s, %s, %ld, "
194 "%ld, '%s', '%s', '%s', '%s'"
197 accountcode, src, dst, dcontext, clid, channel,
198 dstchannel, lastapp, lastdata, start, answer, end, cdr->duration,
199 cdr->billsec, ast_cdr_disp2str(cdr->disposition), ast_channel_amaflags2string(cdr->amaflags), uniqueid,
204 if (settings->hrtime) {
205 double hrbillsec = 0.0;
208 if (!ast_tvzero(cdr->answer)) {
209 hrbillsec = (double)(ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0);
211 hrduration = (double)(ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0);
213 erc = dbfcmd(settings->dbproc,
216 "accountcode, src, dst, dcontext, clid, channel, "
217 "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
218 "billsec, disposition, amaflags, uniqueid"
222 "'%s', '%s', '%s', '%s', '%s', '%s', "
223 "'%s', '%s', '%s', %s, %s, %s, %lf, "
224 "%lf, '%s', '%s', '%s'"
227 accountcode, src, dst, dcontext, clid, channel,
228 dstchannel, lastapp, lastdata, start, answer, end, hrduration,
229 hrbillsec, ast_cdr_disp2str(cdr->disposition), ast_channel_amaflags2string(cdr->amaflags), uniqueid
232 erc = dbfcmd(settings->dbproc,
235 "accountcode, src, dst, dcontext, clid, channel, "
236 "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
237 "billsec, disposition, amaflags, uniqueid"
241 "'%s', '%s', '%s', '%s', '%s', '%s', "
242 "'%s', '%s', '%s', %s, %s, %s, %ld, "
243 "%ld, '%s', '%s', '%s'"
246 accountcode, src, dst, dcontext, clid, channel,
247 dstchannel, lastapp, lastdata, start, answer, end, cdr->duration,
248 cdr->billsec, ast_cdr_disp2str(cdr->disposition), ast_channel_amaflags2string(cdr->amaflags), uniqueid
255 ast_log(LOG_NOTICE, "Failed to build INSERT statement, retrying...\n");
259 ast_log(LOG_ERROR, "Failed to build INSERT statement, no CDR was logged.\n");
264 if (dbsqlexec(settings->dbproc) == FAIL) {
266 ast_log(LOG_NOTICE, "Failed to execute INSERT statement, retrying...\n");
270 ast_log(LOG_ERROR, "Failed to execute INSERT statement, no CDR was logged.\n");
275 /* Consume any results we might get back (this is more of a sanity check than
276 * anything else, since an INSERT shouldn't return results). */
277 while (dbresults(settings->dbproc) != NO_MORE_RESULTS) {
278 while (dbnextrow(settings->dbproc) != NO_MORE_ROWS);
284 ast_mutex_unlock(&tds_lock);
286 ast_free(accountcode);
292 ast_free(dstchannel);
304 static char *anti_injection(const char *str, int len)
306 /* Reference to http://www.nextgenss.com/papers/advanced_sql_injection.pdf */
308 char *buf_ptr, *srh_ptr;
309 char *known_bad[] = {"select", "insert", "update", "delete", "drop", ";", "--", "\0"};
312 if (!(buf = ast_calloc(1, len + 1))) {
313 ast_log(LOG_ERROR, "Out of memory\n");
319 /* Escape single quotes */
320 for (; *str && strlen(buf) < len; str++) {
328 /* Erase known bad input */
329 for (idx = 0; *known_bad[idx]; idx++) {
330 while ((srh_ptr = strcasestr(buf, known_bad[idx]))) {
331 memmove(srh_ptr, srh_ptr + strlen(known_bad[idx]), strlen(srh_ptr + strlen(known_bad[idx])) + 1);
338 static void get_date(char *dateField, size_t len, struct timeval when)
340 /* To make sure we have date variable if not insert null to SQL */
341 if (!ast_tvzero(when)) {
343 ast_localtime(&when, &tm, NULL);
344 ast_strftime(dateField, len, "'" DATE_FORMAT "'", &tm);
346 ast_copy_string(dateField, "null", len);
350 static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
356 if (ast_vasprintf(&buffer, fmt, ap) < 0) {
362 if (dbfcmd(dbproc, buffer) == FAIL) {
369 if (dbsqlexec(dbproc) == FAIL) {
373 /* Consume the result set (we don't really care about the result, though) */
374 while (dbresults(dbproc) != NO_MORE_RESULTS) {
375 while (dbnextrow(dbproc) != NO_MORE_ROWS);
381 static int mssql_disconnect(void)
383 if (settings->dbproc) {
384 dbclose(settings->dbproc);
385 settings->dbproc = NULL;
388 settings->connected = 0;
393 static int mssql_connect(void)
397 if ((login = dblogin()) == NULL) {
398 ast_log(LOG_ERROR, "Unable to allocate login structure for db-lib\n");
402 DBSETLAPP(login, "TSQL");
403 DBSETLUSER(login, (char *) settings->username);
404 DBSETLPWD(login, (char *) settings->password);
405 DBSETLCHARSET(login, (char *) settings->charset);
406 DBSETLNATLANG(login, (char *) settings->language);
408 if ((settings->dbproc = dbopen(login, (char *) settings->hostname)) == NULL) {
409 ast_log(LOG_ERROR, "Unable to connect to %s\n", settings->hostname);
416 if (dbuse(settings->dbproc, (char *) settings->database) == FAIL) {
417 ast_log(LOG_ERROR, "Unable to select database %s\n", settings->database);
421 if (execute_and_consume(settings->dbproc, "SELECT 1 FROM [%s] WHERE 1 = 0", settings->table)) {
422 ast_log(LOG_ERROR, "Unable to find table '%s'\n", settings->table);
426 /* Check to see if we have a userfield column in the table */
427 if (execute_and_consume(settings->dbproc, "SELECT userfield FROM [%s] WHERE 1 = 0", settings->table)) {
428 ast_log(LOG_NOTICE, "Unable to find 'userfield' column in table '%s'\n", settings->table);
429 settings->has_userfield = 0;
431 settings->has_userfield = 1;
434 settings->connected = 1;
439 dbclose(settings->dbproc);
440 settings->dbproc = NULL;
444 static int tds_unload_module(void)
447 ast_mutex_lock(&tds_lock);
449 ast_mutex_unlock(&tds_lock);
451 ast_string_field_free_memory(settings);
455 ast_cdr_unregister(name);
462 static int tds_error_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
464 ast_log(LOG_ERROR, "%s (%d)\n", dberrstr, dberr);
466 if (oserr != DBNOERR) {
467 ast_log(LOG_ERROR, "%s (%d)\n", oserrstr, oserr);
473 static int tds_message_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line)
475 ast_debug(1, "Msg %d, Level %d, State %d, Line %d\n", msgno, severity, msgstate, line);
476 ast_log(LOG_NOTICE, "%s\n", msgtext);
481 static int tds_load_module(int reload)
483 struct ast_config *cfg;
484 const char *ptr = NULL;
485 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
487 cfg = ast_config_load(config, config_flags);
488 if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
489 ast_log(LOG_NOTICE, "Unable to load TDS config for CDRs: %s\n", config);
491 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
494 if (!ast_variable_browse(cfg, "global")) {
495 /* nothing configured */
496 ast_config_destroy(cfg);
500 ast_mutex_lock(&tds_lock);
502 /* Clear out any existing settings */
503 ast_string_field_init(settings, 0);
505 /* 'connection' is the new preferred configuration option */
506 ptr = ast_variable_retrieve(cfg, "global", "connection");
508 ast_string_field_set(settings, hostname, ptr);
510 /* But we keep 'hostname' for backwards compatibility */
511 ptr = ast_variable_retrieve(cfg, "global", "hostname");
513 ast_string_field_set(settings, hostname, ptr);
515 ast_log(LOG_ERROR, "Failed to connect: Database server connection not specified.\n");
520 ptr = ast_variable_retrieve(cfg, "global", "dbname");
522 ast_string_field_set(settings, database, ptr);
524 ast_log(LOG_ERROR, "Failed to connect: Database dbname not specified.\n");
528 ptr = ast_variable_retrieve(cfg, "global", "user");
530 ast_string_field_set(settings, username, ptr);
532 ast_log(LOG_ERROR, "Failed to connect: Database dbuser not specified.\n");
536 ptr = ast_variable_retrieve(cfg, "global", "password");
538 ast_string_field_set(settings, password, ptr);
540 ast_log(LOG_ERROR, "Failed to connect: Database password not specified.\n");
544 ptr = ast_variable_retrieve(cfg, "global", "charset");
546 ast_string_field_set(settings, charset, ptr);
548 ast_string_field_set(settings, charset, "iso_1");
551 ptr = ast_variable_retrieve(cfg, "global", "language");
553 ast_string_field_set(settings, language, ptr);
555 ast_string_field_set(settings, language, "us_english");
558 ptr = ast_variable_retrieve(cfg, "global", "table");
560 ast_string_field_set(settings, table, ptr);
562 ast_log(LOG_NOTICE, "Table name not specified, using 'cdr' by default.\n");
563 ast_string_field_set(settings, table, "cdr");
566 ptr = ast_variable_retrieve(cfg, "global", "hrtime");
567 if (ptr && ast_true(ptr)) {
568 ast_string_field_set(settings, hrtime, ptr);
570 ast_log(LOG_NOTICE, "High Resolution Time not found, using integers for billsec and duration fields by default.\n");
575 if (mssql_connect()) {
576 /* We failed to connect (mssql_connect takes care of logging it) */
580 ast_mutex_unlock(&tds_lock);
581 ast_config_destroy(cfg);
586 ast_mutex_unlock(&tds_lock);
587 ast_config_destroy(cfg);
592 static int reload(void)
594 return tds_load_module(1);
597 static int load_module(void)
599 if (dbinit() == FAIL) {
600 ast_log(LOG_ERROR, "Failed to initialize FreeTDS db-lib\n");
601 return AST_MODULE_LOAD_DECLINE;
604 dberrhandle(tds_error_handler);
605 dbmsghandle(tds_message_handler);
607 settings = ast_calloc_with_stringfields(1, struct cdr_tds_config, 256);
611 return AST_MODULE_LOAD_DECLINE;
614 if (!tds_load_module(0)) {
615 ast_string_field_free_memory(settings);
619 return AST_MODULE_LOAD_DECLINE;
622 ast_cdr_register(name, ast_module_info->description, tds_log);
624 return AST_MODULE_LOAD_SUCCESS;
627 static int unload_module(void)
629 return tds_unload_module();
632 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "FreeTDS CDR Backend",
634 .unload = unload_module,
636 .load_pri = AST_MODPRI_CDR_DRIVER,