cdr_tds.c 16 KB

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