cdr_tds.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2004 - 2006, Digium, Inc.
  5. *
  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.
  11. *
  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.
  15. */
  16. /*!
  17. * \file
  18. * \brief FreeTDS CDR logger
  19. *
  20. * See also
  21. * \arg \ref Config_cdr
  22. * \arg http://www.freetds.org/
  23. * \ingroup cdr_drivers
  24. */
  25. /*!
  26. * \verbatim
  27. *
  28. * Table Structure for `cdr`
  29. *
  30. * Created on: 05/20/2004 16:16
  31. * Last changed on: 07/27/2004 20:01
  32. CREATE TABLE [dbo].[cdr] (
  33. [accountcode] [varchar] (20) NULL ,
  34. [src] [varchar] (80) NULL ,
  35. [dst] [varchar] (80) NULL ,
  36. [dcontext] [varchar] (80) NULL ,
  37. [clid] [varchar] (80) NULL ,
  38. [channel] [varchar] (80) NULL ,
  39. [dstchannel] [varchar] (80) NULL ,
  40. [lastapp] [varchar] (80) NULL ,
  41. [lastdata] [varchar] (80) NULL ,
  42. [start] [datetime] NULL ,
  43. [answer] [datetime] NULL ,
  44. [end] [datetime] NULL ,
  45. [duration] [int] NULL ,
  46. [billsec] [int] NULL ,
  47. [disposition] [varchar] (20) NULL ,
  48. [amaflags] [varchar] (16) NULL ,
  49. [uniqueid] [varchar] (32) NULL ,
  50. [userfield] [varchar] (256) NULL
  51. ) ON [PRIMARY]
  52. \endverbatim
  53. */
  54. /*** MODULEINFO
  55. <depend>freetds</depend>
  56. <support_level>extended</support_level>
  57. ***/
  58. #include "asterisk.h"
  59. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  60. #include "asterisk/config.h"
  61. #include "asterisk/channel.h"
  62. #include "asterisk/cdr.h"
  63. #include "asterisk/module.h"
  64. #include <sqlfront.h>
  65. #include <sybdb.h>
  66. #define DATE_FORMAT "%Y/%m/%d %T"
  67. static const char name[] = "FreeTDS (MSSQL)";
  68. static const char config[] = "cdr_tds.conf";
  69. struct cdr_tds_config {
  70. AST_DECLARE_STRING_FIELDS(
  71. AST_STRING_FIELD(hostname);
  72. AST_STRING_FIELD(database);
  73. AST_STRING_FIELD(username);
  74. AST_STRING_FIELD(password);
  75. AST_STRING_FIELD(table);
  76. AST_STRING_FIELD(charset);
  77. AST_STRING_FIELD(language);
  78. AST_STRING_FIELD(hrtime);
  79. );
  80. DBPROCESS *dbproc;
  81. unsigned int connected:1;
  82. unsigned int has_userfield:1;
  83. };
  84. AST_MUTEX_DEFINE_STATIC(tds_lock);
  85. static struct cdr_tds_config *settings;
  86. static char *anti_injection(const char *, int);
  87. static void get_date(char *, size_t len, struct timeval);
  88. static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
  89. __attribute__((format(printf, 2, 3)));
  90. static int mssql_connect(void);
  91. static int mssql_disconnect(void);
  92. static int tds_log(struct ast_cdr *cdr)
  93. {
  94. char start[80], answer[80], end[80];
  95. char *accountcode, *src, *dst, *dcontext, *clid, *channel, *dstchannel, *lastapp, *lastdata, *uniqueid, *userfield = NULL;
  96. RETCODE erc;
  97. int res = -1;
  98. int attempt = 1;
  99. accountcode = anti_injection(cdr->accountcode, 20);
  100. src = anti_injection(cdr->src, 80);
  101. dst = anti_injection(cdr->dst, 80);
  102. dcontext = anti_injection(cdr->dcontext, 80);
  103. clid = anti_injection(cdr->clid, 80);
  104. channel = anti_injection(cdr->channel, 80);
  105. dstchannel = anti_injection(cdr->dstchannel, 80);
  106. lastapp = anti_injection(cdr->lastapp, 80);
  107. lastdata = anti_injection(cdr->lastdata, 80);
  108. uniqueid = anti_injection(cdr->uniqueid, 32);
  109. get_date(start, sizeof(start), cdr->start);
  110. get_date(answer, sizeof(answer), cdr->answer);
  111. get_date(end, sizeof(end), cdr->end);
  112. ast_mutex_lock(&tds_lock);
  113. if (settings->has_userfield) {
  114. userfield = anti_injection(cdr->userfield, AST_MAX_USER_FIELD);
  115. }
  116. retry:
  117. /* Ensure that we are connected */
  118. if (!settings->connected) {
  119. ast_log(LOG_NOTICE, "Attempting to reconnect to %s (Attempt %d)\n", settings->hostname, attempt);
  120. if (mssql_connect()) {
  121. /* Connect failed */
  122. if (attempt++ < 3) {
  123. goto retry;
  124. }
  125. goto done;
  126. }
  127. }
  128. if (settings->has_userfield) {
  129. if (settings->hrtime) {
  130. double hrbillsec = 0.0;
  131. double hrduration;
  132. if (!ast_tvzero(cdr->answer)) {
  133. hrbillsec = (double)(ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0);
  134. }
  135. hrduration = (double)(ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0);
  136. erc = dbfcmd(settings->dbproc,
  137. "INSERT INTO %s "
  138. "("
  139. "accountcode, src, dst, dcontext, clid, channel, "
  140. "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
  141. "billsec, disposition, amaflags, uniqueid, userfield"
  142. ") "
  143. "VALUES "
  144. "("
  145. "'%s', '%s', '%s', '%s', '%s', '%s', "
  146. "'%s', '%s', '%s', %s, %s, %s, %lf, "
  147. "%lf, '%s', '%s', '%s', '%s'"
  148. ")",
  149. settings->table,
  150. accountcode, src, dst, dcontext, clid, channel,
  151. dstchannel, lastapp, lastdata, start, answer, end, hrduration,
  152. hrbillsec, ast_cdr_disp2str(cdr->disposition), ast_channel_amaflags2string(cdr->amaflags), uniqueid,
  153. userfield
  154. );
  155. } else {
  156. erc = dbfcmd(settings->dbproc,
  157. "INSERT INTO %s "
  158. "("
  159. "accountcode, src, dst, dcontext, clid, channel, "
  160. "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
  161. "billsec, disposition, amaflags, uniqueid, userfield"
  162. ") "
  163. "VALUES "
  164. "("
  165. "'%s', '%s', '%s', '%s', '%s', '%s', "
  166. "'%s', '%s', '%s', %s, %s, %s, %ld, "
  167. "%ld, '%s', '%s', '%s', '%s'"
  168. ")",
  169. settings->table,
  170. accountcode, src, dst, dcontext, clid, channel,
  171. dstchannel, lastapp, lastdata, start, answer, end, cdr->duration,
  172. cdr->billsec, ast_cdr_disp2str(cdr->disposition), ast_channel_amaflags2string(cdr->amaflags), uniqueid,
  173. userfield
  174. );
  175. }
  176. } else {
  177. if (settings->hrtime) {
  178. double hrbillsec = 0.0;
  179. double hrduration;
  180. if (!ast_tvzero(cdr->answer)) {
  181. hrbillsec = (double)(ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0);
  182. }
  183. hrduration = (double)(ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0);
  184. erc = dbfcmd(settings->dbproc,
  185. "INSERT INTO %s "
  186. "("
  187. "accountcode, src, dst, dcontext, clid, channel, "
  188. "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
  189. "billsec, disposition, amaflags, uniqueid"
  190. ") "
  191. "VALUES "
  192. "("
  193. "'%s', '%s', '%s', '%s', '%s', '%s', "
  194. "'%s', '%s', '%s', %s, %s, %s, %lf, "
  195. "%lf, '%s', '%s', '%s'"
  196. ")",
  197. settings->table,
  198. accountcode, src, dst, dcontext, clid, channel,
  199. dstchannel, lastapp, lastdata, start, answer, end, hrduration,
  200. hrbillsec, ast_cdr_disp2str(cdr->disposition), ast_channel_amaflags2string(cdr->amaflags), uniqueid
  201. );
  202. } else {
  203. erc = dbfcmd(settings->dbproc,
  204. "INSERT INTO %s "
  205. "("
  206. "accountcode, src, dst, dcontext, clid, channel, "
  207. "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
  208. "billsec, disposition, amaflags, uniqueid"
  209. ") "
  210. "VALUES "
  211. "("
  212. "'%s', '%s', '%s', '%s', '%s', '%s', "
  213. "'%s', '%s', '%s', %s, %s, %s, %ld, "
  214. "%ld, '%s', '%s', '%s'"
  215. ")",
  216. settings->table,
  217. accountcode, src, dst, dcontext, clid, channel,
  218. dstchannel, lastapp, lastdata, start, answer, end, cdr->duration,
  219. cdr->billsec, ast_cdr_disp2str(cdr->disposition), ast_channel_amaflags2string(cdr->amaflags), uniqueid
  220. );
  221. }
  222. }
  223. if (erc == FAIL) {
  224. if (attempt++ < 3) {
  225. ast_log(LOG_NOTICE, "Failed to build INSERT statement, retrying...\n");
  226. mssql_disconnect();
  227. goto retry;
  228. } else {
  229. ast_log(LOG_ERROR, "Failed to build INSERT statement, no CDR was logged.\n");
  230. goto done;
  231. }
  232. }
  233. if (dbsqlexec(settings->dbproc) == FAIL) {
  234. if (attempt++ < 3) {
  235. ast_log(LOG_NOTICE, "Failed to execute INSERT statement, retrying...\n");
  236. mssql_disconnect();
  237. goto retry;
  238. } else {
  239. ast_log(LOG_ERROR, "Failed to execute INSERT statement, no CDR was logged.\n");
  240. goto done;
  241. }
  242. }
  243. /* Consume any results we might get back (this is more of a sanity check than
  244. * anything else, since an INSERT shouldn't return results). */
  245. while (dbresults(settings->dbproc) != NO_MORE_RESULTS) {
  246. while (dbnextrow(settings->dbproc) != NO_MORE_ROWS);
  247. }
  248. res = 0;
  249. done:
  250. ast_mutex_unlock(&tds_lock);
  251. ast_free(accountcode);
  252. ast_free(src);
  253. ast_free(dst);
  254. ast_free(dcontext);
  255. ast_free(clid);
  256. ast_free(channel);
  257. ast_free(dstchannel);
  258. ast_free(lastapp);
  259. ast_free(lastdata);
  260. ast_free(uniqueid);
  261. if (userfield) {
  262. ast_free(userfield);
  263. }
  264. return res;
  265. }
  266. static char *anti_injection(const char *str, int len)
  267. {
  268. /* Reference to http://www.nextgenss.com/papers/advanced_sql_injection.pdf */
  269. char *buf;
  270. char *buf_ptr, *srh_ptr;
  271. char *known_bad[] = {"select", "insert", "update", "delete", "drop", ";", "--", "\0"};
  272. int idx;
  273. if (!(buf = ast_calloc(1, len + 1))) {
  274. ast_log(LOG_ERROR, "Out of memory\n");
  275. return NULL;
  276. }
  277. buf_ptr = buf;
  278. /* Escape single quotes */
  279. for (; *str && strlen(buf) < len; str++) {
  280. if (*str == '\'') {
  281. *buf_ptr++ = '\'';
  282. }
  283. *buf_ptr++ = *str;
  284. }
  285. *buf_ptr = '\0';
  286. /* Erase known bad input */
  287. for (idx = 0; *known_bad[idx]; idx++) {
  288. while ((srh_ptr = strcasestr(buf, known_bad[idx]))) {
  289. memmove(srh_ptr, srh_ptr + strlen(known_bad[idx]), strlen(srh_ptr + strlen(known_bad[idx])) + 1);
  290. }
  291. }
  292. return buf;
  293. }
  294. static void get_date(char *dateField, size_t len, struct timeval when)
  295. {
  296. /* To make sure we have date variable if not insert null to SQL */
  297. if (!ast_tvzero(when)) {
  298. struct ast_tm tm;
  299. ast_localtime(&when, &tm, NULL);
  300. ast_strftime(dateField, len, "'" DATE_FORMAT "'", &tm);
  301. } else {
  302. ast_copy_string(dateField, "null", len);
  303. }
  304. }
  305. static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
  306. {
  307. va_list ap;
  308. char *buffer;
  309. va_start(ap, fmt);
  310. if (ast_vasprintf(&buffer, fmt, ap) < 0) {
  311. va_end(ap);
  312. return 1;
  313. }
  314. va_end(ap);
  315. if (dbfcmd(dbproc, buffer) == FAIL) {
  316. ast_free(buffer);
  317. return 1;
  318. }
  319. ast_free(buffer);
  320. if (dbsqlexec(dbproc) == FAIL) {
  321. return 1;
  322. }
  323. /* Consume the result set (we don't really care about the result, though) */
  324. while (dbresults(dbproc) != NO_MORE_RESULTS) {
  325. while (dbnextrow(dbproc) != NO_MORE_ROWS);
  326. }
  327. return 0;
  328. }
  329. static int mssql_disconnect(void)
  330. {
  331. if (settings->dbproc) {
  332. dbclose(settings->dbproc);
  333. settings->dbproc = NULL;
  334. }
  335. settings->connected = 0;
  336. return 0;
  337. }
  338. static int mssql_connect(void)
  339. {
  340. LOGINREC *login;
  341. if ((login = dblogin()) == NULL) {
  342. ast_log(LOG_ERROR, "Unable to allocate login structure for db-lib\n");
  343. return -1;
  344. }
  345. DBSETLAPP(login, "TSQL");
  346. DBSETLUSER(login, (char *) settings->username);
  347. DBSETLPWD(login, (char *) settings->password);
  348. DBSETLCHARSET(login, (char *) settings->charset);
  349. DBSETLNATLANG(login, (char *) settings->language);
  350. if ((settings->dbproc = dbopen(login, (char *) settings->hostname)) == NULL) {
  351. ast_log(LOG_ERROR, "Unable to connect to %s\n", settings->hostname);
  352. dbloginfree(login);
  353. return -1;
  354. }
  355. dbloginfree(login);
  356. if (dbuse(settings->dbproc, (char *) settings->database) == FAIL) {
  357. ast_log(LOG_ERROR, "Unable to select database %s\n", settings->database);
  358. goto failed;
  359. }
  360. if (execute_and_consume(settings->dbproc, "SELECT 1 FROM [%s] WHERE 1 = 0", settings->table)) {
  361. ast_log(LOG_ERROR, "Unable to find table '%s'\n", settings->table);
  362. goto failed;
  363. }
  364. /* Check to see if we have a userfield column in the table */
  365. if (execute_and_consume(settings->dbproc, "SELECT userfield FROM [%s] WHERE 1 = 0", settings->table)) {
  366. ast_log(LOG_NOTICE, "Unable to find 'userfield' column in table '%s'\n", settings->table);
  367. settings->has_userfield = 0;
  368. } else {
  369. settings->has_userfield = 1;
  370. }
  371. settings->connected = 1;
  372. return 0;
  373. failed:
  374. dbclose(settings->dbproc);
  375. settings->dbproc = NULL;
  376. return -1;
  377. }
  378. static int tds_unload_module(void)
  379. {
  380. if (ast_cdr_unregister(name)) {
  381. return -1;
  382. }
  383. if (settings) {
  384. ast_mutex_lock(&tds_lock);
  385. mssql_disconnect();
  386. ast_mutex_unlock(&tds_lock);
  387. ast_string_field_free_memory(settings);
  388. ast_free(settings);
  389. }
  390. dbexit();
  391. return 0;
  392. }
  393. static int tds_error_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
  394. {
  395. ast_log(LOG_ERROR, "%s (%d)\n", dberrstr, dberr);
  396. if (oserr != DBNOERR) {
  397. ast_log(LOG_ERROR, "%s (%d)\n", oserrstr, oserr);
  398. }
  399. return INT_CANCEL;
  400. }
  401. static int tds_message_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line)
  402. {
  403. ast_debug(1, "Msg %d, Level %d, State %d, Line %d\n", msgno, severity, msgstate, line);
  404. ast_log(LOG_NOTICE, "%s\n", msgtext);
  405. return 0;
  406. }
  407. static int tds_load_module(int reload)
  408. {
  409. struct ast_config *cfg;
  410. const char *ptr = NULL;
  411. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  412. cfg = ast_config_load(config, config_flags);
  413. if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
  414. ast_log(LOG_NOTICE, "Unable to load TDS config for CDRs: %s\n", config);
  415. return 0;
  416. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
  417. return 0;
  418. if (!ast_variable_browse(cfg, "global")) {
  419. /* nothing configured */
  420. ast_config_destroy(cfg);
  421. return 0;
  422. }
  423. ast_mutex_lock(&tds_lock);
  424. /* Clear out any existing settings */
  425. ast_string_field_init(settings, 0);
  426. /* 'connection' is the new preferred configuration option */
  427. ptr = ast_variable_retrieve(cfg, "global", "connection");
  428. if (ptr) {
  429. ast_string_field_set(settings, hostname, ptr);
  430. } else {
  431. /* But we keep 'hostname' for backwards compatibility */
  432. ptr = ast_variable_retrieve(cfg, "global", "hostname");
  433. if (ptr) {
  434. ast_string_field_set(settings, hostname, ptr);
  435. } else {
  436. ast_log(LOG_ERROR, "Failed to connect: Database server connection not specified.\n");
  437. goto failed;
  438. }
  439. }
  440. ptr = ast_variable_retrieve(cfg, "global", "dbname");
  441. if (ptr) {
  442. ast_string_field_set(settings, database, ptr);
  443. } else {
  444. ast_log(LOG_ERROR, "Failed to connect: Database dbname not specified.\n");
  445. goto failed;
  446. }
  447. ptr = ast_variable_retrieve(cfg, "global", "user");
  448. if (ptr) {
  449. ast_string_field_set(settings, username, ptr);
  450. } else {
  451. ast_log(LOG_ERROR, "Failed to connect: Database dbuser not specified.\n");
  452. goto failed;
  453. }
  454. ptr = ast_variable_retrieve(cfg, "global", "password");
  455. if (ptr) {
  456. ast_string_field_set(settings, password, ptr);
  457. } else {
  458. ast_log(LOG_ERROR, "Failed to connect: Database password not specified.\n");
  459. goto failed;
  460. }
  461. ptr = ast_variable_retrieve(cfg, "global", "charset");
  462. if (ptr) {
  463. ast_string_field_set(settings, charset, ptr);
  464. } else {
  465. ast_string_field_set(settings, charset, "iso_1");
  466. }
  467. ptr = ast_variable_retrieve(cfg, "global", "language");
  468. if (ptr) {
  469. ast_string_field_set(settings, language, ptr);
  470. } else {
  471. ast_string_field_set(settings, language, "us_english");
  472. }
  473. ptr = ast_variable_retrieve(cfg, "global", "table");
  474. if (ptr) {
  475. ast_string_field_set(settings, table, ptr);
  476. } else {
  477. ast_log(LOG_NOTICE, "Table name not specified, using 'cdr' by default.\n");
  478. ast_string_field_set(settings, table, "cdr");
  479. }
  480. ptr = ast_variable_retrieve(cfg, "global", "hrtime");
  481. if (ptr && ast_true(ptr)) {
  482. ast_string_field_set(settings, hrtime, ptr);
  483. } else {
  484. ast_log(LOG_NOTICE, "High Resolution Time not found, using integers for billsec and duration fields by default.\n");
  485. }
  486. mssql_disconnect();
  487. if (mssql_connect()) {
  488. /* We failed to connect (mssql_connect takes care of logging it) */
  489. goto failed;
  490. }
  491. ast_mutex_unlock(&tds_lock);
  492. ast_config_destroy(cfg);
  493. return 1;
  494. failed:
  495. ast_mutex_unlock(&tds_lock);
  496. ast_config_destroy(cfg);
  497. return 0;
  498. }
  499. static int reload(void)
  500. {
  501. return tds_load_module(1);
  502. }
  503. static int load_module(void)
  504. {
  505. if (dbinit() == FAIL) {
  506. ast_log(LOG_ERROR, "Failed to initialize FreeTDS db-lib\n");
  507. return AST_MODULE_LOAD_DECLINE;
  508. }
  509. dberrhandle(tds_error_handler);
  510. dbmsghandle(tds_message_handler);
  511. settings = ast_calloc_with_stringfields(1, struct cdr_tds_config, 256);
  512. if (!settings) {
  513. dbexit();
  514. return AST_MODULE_LOAD_DECLINE;
  515. }
  516. if (!tds_load_module(0)) {
  517. ast_string_field_free_memory(settings);
  518. ast_free(settings);
  519. settings = NULL;
  520. dbexit();
  521. return AST_MODULE_LOAD_DECLINE;
  522. }
  523. ast_cdr_register(name, ast_module_info->description, tds_log);
  524. return AST_MODULE_LOAD_SUCCESS;
  525. }
  526. static int unload_module(void)
  527. {
  528. return tds_unload_module();
  529. }
  530. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "FreeTDS CDR Backend",
  531. .support_level = AST_MODULE_SUPPORT_EXTENDED,
  532. .load = load_module,
  533. .unload = unload_module,
  534. .reload = reload,
  535. .load_pri = AST_MODPRI_CDR_DRIVER,
  536. );