cel_tds.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2008, 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. /*! \file
  17. *
  18. * \brief FreeTDS CEL logger
  19. *
  20. * See also
  21. * \arg \ref Config_cel
  22. * \arg http://www.freetds.org/
  23. * \ingroup cel_drivers
  24. */
  25. /*! \verbatim
  26. *
  27. * Table Structure for `cel`
  28. *
  29. CREATE TABLE [dbo].[cel] (
  30. [accountcode] [varchar] (20) NULL ,
  31. [cidname] [varchar] (80) NULL ,
  32. [cidnum] [varchar] (80) NULL ,
  33. [cidani] [varchar] (80) NULL ,
  34. [cidrdnis] [varchar] (80) NULL ,
  35. [ciddnid] [varchar] (80) NULL ,
  36. [exten] [varchar] (80) NULL ,
  37. [context] [varchar] (80) NULL ,
  38. [channame] [varchar] (80) NULL ,
  39. [appname] [varchar] (80) NULL ,
  40. [appdata] [varchar] (80) NULL ,
  41. [eventtime] [datetime] NULL ,
  42. [eventtype] [varchar] (32) NULL ,
  43. [uniqueid] [varchar] (32) NULL ,
  44. [linkedid] [varchar] (32) NULL ,
  45. [amaflags] [varchar] (16) NULL ,
  46. [userfield] [varchar] (32) NULL ,
  47. [peer] [varchar] (32) 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. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  57. #include <time.h>
  58. #include <math.h>
  59. #include "asterisk/config.h"
  60. #include "asterisk/channel.h"
  61. #include "asterisk/cel.h"
  62. #include "asterisk/module.h"
  63. #include "asterisk/logger.h"
  64. #include <sqlfront.h>
  65. #include <sybdb.h>
  66. #ifdef FREETDS_PRE_0_62
  67. #warning "You have older TDS, you should upgrade!"
  68. #endif
  69. #define DATE_FORMAT "%Y/%m/%d %T"
  70. #define TDS_BACKEND_NAME "CEL TDS logging backend"
  71. static char *config = "cel_tds.conf";
  72. struct cel_tds_config {
  73. AST_DECLARE_STRING_FIELDS(
  74. AST_STRING_FIELD(connection);
  75. AST_STRING_FIELD(database);
  76. AST_STRING_FIELD(username);
  77. AST_STRING_FIELD(password);
  78. AST_STRING_FIELD(table);
  79. AST_STRING_FIELD(charset);
  80. AST_STRING_FIELD(language);
  81. );
  82. DBPROCESS *dbproc;
  83. unsigned int connected:1;
  84. };
  85. AST_MUTEX_DEFINE_STATIC(tds_lock);
  86. static struct cel_tds_config *settings;
  87. static char *anti_injection(const char *, int);
  88. static void get_date(char *, size_t len, struct timeval);
  89. static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
  90. __attribute__((format(printf, 2, 3)));
  91. static int mssql_connect(void);
  92. static int mssql_disconnect(void);
  93. static void tds_log(struct ast_event *event)
  94. {
  95. char start[80];
  96. char *accountcode_ai, *clidnum_ai, *exten_ai, *context_ai, *clid_ai, *channel_ai, *app_ai, *appdata_ai, *uniqueid_ai, *linkedid_ai, *cidani_ai, *cidrdnis_ai, *ciddnid_ai, *peer_ai, *userfield_ai;
  97. RETCODE erc;
  98. int attempt = 1;
  99. struct ast_cel_event_record record = {
  100. .version = AST_CEL_EVENT_RECORD_VERSION,
  101. };
  102. if (ast_cel_fill_record(event, &record)) {
  103. return;
  104. }
  105. ast_mutex_lock(&tds_lock);
  106. accountcode_ai = anti_injection(record.account_code, 20);
  107. clidnum_ai = anti_injection(record.caller_id_num, 80);
  108. clid_ai = anti_injection(record.caller_id_name, 80);
  109. cidani_ai = anti_injection(record.caller_id_ani, 80);
  110. cidrdnis_ai = anti_injection(record.caller_id_rdnis, 80);
  111. ciddnid_ai = anti_injection(record.caller_id_dnid, 80);
  112. exten_ai = anti_injection(record.extension, 80);
  113. context_ai = anti_injection(record.context, 80);
  114. channel_ai = anti_injection(record.channel_name, 80);
  115. app_ai = anti_injection(record.application_name, 80);
  116. appdata_ai = anti_injection(record.application_data, 80);
  117. uniqueid_ai = anti_injection(record.unique_id, 32);
  118. linkedid_ai = anti_injection(record.linked_id, 32);
  119. userfield_ai = anti_injection(record.user_field, 32);
  120. peer_ai = anti_injection(record.peer, 32);
  121. get_date(start, sizeof(start), record.event_time);
  122. retry:
  123. /* Ensure that we are connected */
  124. if (!settings->connected) {
  125. ast_log(LOG_NOTICE, "Attempting to reconnect to %s (Attempt %d)\n", settings->connection, attempt);
  126. if (mssql_connect()) {
  127. /* Connect failed */
  128. if (attempt++ < 3) {
  129. goto retry;
  130. }
  131. goto done;
  132. }
  133. }
  134. erc = dbfcmd(settings->dbproc,
  135. "INSERT INTO %s "
  136. "("
  137. "accountcode,"
  138. "cidnum,"
  139. "cidname,"
  140. "cidani,"
  141. "cidrdnis,"
  142. "ciddnid,"
  143. "exten,"
  144. "context,"
  145. "channel,"
  146. "appname,"
  147. "appdata,"
  148. "eventtime,"
  149. "eventtype,"
  150. "amaflags, "
  151. "uniqueid,"
  152. "linkedid,"
  153. "userfield,"
  154. "peer"
  155. ") "
  156. "VALUES "
  157. "("
  158. "'%s'," /* accountcode */
  159. "'%s'," /* clidnum */
  160. "'%s'," /* clid */
  161. "'%s'," /* cid-ani */
  162. "'%s'," /* cid-rdnis */
  163. "'%s'," /* cid-dnid */
  164. "'%s'," /* exten */
  165. "'%s'," /* context */
  166. "'%s'," /* channel */
  167. "'%s'," /* app */
  168. "'%s'," /* appdata */
  169. "%s, " /* eventtime */
  170. "'%s'," /* eventtype */
  171. "'%s'," /* amaflags */
  172. "'%s'," /* uniqueid */
  173. "'%s'," /* linkedid */
  174. "'%s'," /* userfield */
  175. "'%s'" /* peer */
  176. ")",
  177. settings->table, accountcode_ai, clidnum_ai, clid_ai, cidani_ai, cidrdnis_ai,
  178. ciddnid_ai, exten_ai, context_ai, channel_ai, app_ai, appdata_ai, start,
  179. (record.event_type == AST_CEL_USER_DEFINED)
  180. ? record.user_defined_name : record.event_name,
  181. ast_channel_amaflags2string(record.amaflag), uniqueid_ai, linkedid_ai,
  182. userfield_ai, peer_ai);
  183. if (erc == FAIL) {
  184. if (attempt++ < 3) {
  185. ast_log(LOG_NOTICE, "Failed to build INSERT statement, retrying...\n");
  186. mssql_disconnect();
  187. goto retry;
  188. } else {
  189. ast_log(LOG_ERROR, "Failed to build INSERT statement, no CEL was logged.\n");
  190. goto done;
  191. }
  192. }
  193. if (dbsqlexec(settings->dbproc) == FAIL) {
  194. if (attempt++ < 3) {
  195. ast_log(LOG_NOTICE, "Failed to execute INSERT statement, retrying...\n");
  196. mssql_disconnect();
  197. goto retry;
  198. } else {
  199. ast_log(LOG_ERROR, "Failed to execute INSERT statement, no CEL was logged.\n");
  200. goto done;
  201. }
  202. }
  203. /* Consume any results we might get back (this is more of a sanity check than
  204. * anything else, since an INSERT shouldn't return results). */
  205. while (dbresults(settings->dbproc) != NO_MORE_RESULTS) {
  206. while (dbnextrow(settings->dbproc) != NO_MORE_ROWS);
  207. }
  208. done:
  209. ast_mutex_unlock(&tds_lock);
  210. free(accountcode_ai);
  211. free(clidnum_ai);
  212. free(clid_ai);
  213. free(cidani_ai);
  214. free(cidrdnis_ai);
  215. free(ciddnid_ai);
  216. free(exten_ai);
  217. free(context_ai);
  218. free(channel_ai);
  219. free(app_ai);
  220. free(appdata_ai);
  221. free(uniqueid_ai);
  222. free(linkedid_ai);
  223. free(userfield_ai);
  224. free(peer_ai);
  225. return;
  226. }
  227. static char *anti_injection(const char *str, int len)
  228. {
  229. /* Reference to http://www.nextgenss.com/papers/advanced_sql_injection.pdf */
  230. char *buf;
  231. char *buf_ptr, *srh_ptr;
  232. char *known_bad[] = {"select", "insert", "update", "delete", "drop", ";", "--", "\0"};
  233. int idx;
  234. if (!(buf = ast_calloc(1, len + 1))) {
  235. ast_log(LOG_ERROR, "Out of memory\n");
  236. return NULL;
  237. }
  238. buf_ptr = buf;
  239. /* Escape single quotes */
  240. for (; *str && strlen(buf) < len; str++) {
  241. if (*str == '\'') {
  242. *buf_ptr++ = '\'';
  243. }
  244. *buf_ptr++ = *str;
  245. }
  246. *buf_ptr = '\0';
  247. /* Erase known bad input */
  248. for (idx = 0; *known_bad[idx]; idx++) {
  249. while ((srh_ptr = strcasestr(buf, known_bad[idx]))) {
  250. memmove(srh_ptr, srh_ptr + strlen(known_bad[idx]), strlen(srh_ptr + strlen(known_bad[idx])) + 1);
  251. }
  252. }
  253. return buf;
  254. }
  255. static void get_date(char *dateField, size_t len, struct timeval when)
  256. {
  257. /* To make sure we have date variable if not insert null to SQL */
  258. if (!ast_tvzero(when)) {
  259. struct ast_tm tm;
  260. ast_localtime(&when, &tm, NULL);
  261. ast_strftime(dateField, len, "'" DATE_FORMAT "'", &tm);
  262. } else {
  263. ast_copy_string(dateField, "null", len);
  264. }
  265. }
  266. static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
  267. {
  268. va_list ap;
  269. char *buffer;
  270. va_start(ap, fmt);
  271. if (ast_vasprintf(&buffer, fmt, ap) < 0) {
  272. va_end(ap);
  273. return 1;
  274. }
  275. va_end(ap);
  276. if (dbfcmd(dbproc, buffer) == FAIL) {
  277. free(buffer);
  278. return 1;
  279. }
  280. free(buffer);
  281. if (dbsqlexec(dbproc) == FAIL) {
  282. return 1;
  283. }
  284. /* Consume the result set (we don't really care about the result, though) */
  285. while (dbresults(dbproc) != NO_MORE_RESULTS) {
  286. while (dbnextrow(dbproc) != NO_MORE_ROWS);
  287. }
  288. return 0;
  289. }
  290. static int mssql_disconnect(void)
  291. {
  292. if (settings->dbproc) {
  293. dbclose(settings->dbproc);
  294. settings->dbproc = NULL;
  295. }
  296. settings->connected = 0;
  297. return 0;
  298. }
  299. static int mssql_connect(void)
  300. {
  301. LOGINREC *login;
  302. if ((login = dblogin()) == NULL) {
  303. ast_log(LOG_ERROR, "Unable to allocate login structure for db-lib\n");
  304. return -1;
  305. }
  306. DBSETLAPP(login, "TSQL");
  307. DBSETLUSER(login, (char *) settings->username);
  308. DBSETLPWD(login, (char *) settings->password);
  309. if (!ast_strlen_zero(settings->charset)) {
  310. DBSETLCHARSET(login, (char *) settings->charset);
  311. }
  312. if (!ast_strlen_zero(settings->language)) {
  313. DBSETLNATLANG(login, (char *) settings->language);
  314. }
  315. if ((settings->dbproc = dbopen(login, (char *) settings->connection)) == NULL) {
  316. ast_log(LOG_ERROR, "Unable to connect to %s\n", settings->connection);
  317. dbloginfree(login);
  318. return -1;
  319. }
  320. dbloginfree(login);
  321. if (dbuse(settings->dbproc, (char *) settings->database) == FAIL) {
  322. ast_log(LOG_ERROR, "Unable to select database %s\n", settings->database);
  323. goto failed;
  324. }
  325. if (execute_and_consume(settings->dbproc, "SELECT 1 FROM [%s]", settings->table)) {
  326. ast_log(LOG_ERROR, "Unable to find table '%s'\n", settings->table);
  327. goto failed;
  328. }
  329. settings->connected = 1;
  330. return 0;
  331. failed:
  332. dbclose(settings->dbproc);
  333. settings->dbproc = NULL;
  334. return -1;
  335. }
  336. static int tds_unload_module(void)
  337. {
  338. ast_cel_backend_unregister(TDS_BACKEND_NAME);
  339. if (settings) {
  340. ast_mutex_lock(&tds_lock);
  341. mssql_disconnect();
  342. ast_mutex_unlock(&tds_lock);
  343. ast_string_field_free_memory(settings);
  344. ast_free(settings);
  345. }
  346. dbexit();
  347. return 0;
  348. }
  349. static int tds_error_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
  350. {
  351. ast_log(LOG_ERROR, "%s (%d)\n", dberrstr, dberr);
  352. if (oserr != DBNOERR) {
  353. ast_log(LOG_ERROR, "%s (%d)\n", oserrstr, oserr);
  354. }
  355. return INT_CANCEL;
  356. }
  357. static int tds_message_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line)
  358. {
  359. ast_debug(1, "Msg %d, Level %d, State %d, Line %d\n", msgno, severity, msgstate, line);
  360. ast_log(LOG_NOTICE, "%s\n", msgtext);
  361. return 0;
  362. }
  363. static int tds_load_module(int reload)
  364. {
  365. struct ast_config *cfg;
  366. const char *ptr = NULL;
  367. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  368. cfg = ast_config_load(config, config_flags);
  369. if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
  370. ast_log(LOG_NOTICE, "Unable to load TDS config for CELs: %s\n", config);
  371. return 0;
  372. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  373. return 0;
  374. }
  375. if (!ast_variable_browse(cfg, "global")) {
  376. /* nothing configured */
  377. ast_config_destroy(cfg);
  378. ast_log(LOG_NOTICE, "cel_tds has no global category, nothing to configure.\n");
  379. return 0;
  380. }
  381. ast_mutex_lock(&tds_lock);
  382. /* Clear out any existing settings */
  383. ast_string_field_init(settings, 0);
  384. ptr = ast_variable_retrieve(cfg, "global", "connection");
  385. if (ptr) {
  386. ast_string_field_set(settings, connection, ptr);
  387. } else {
  388. ast_log(LOG_ERROR, "Failed to connect: Database connection name not specified.\n");
  389. goto failed;
  390. }
  391. ptr = ast_variable_retrieve(cfg, "global", "dbname");
  392. if (ptr) {
  393. ast_string_field_set(settings, database, ptr);
  394. } else {
  395. ast_log(LOG_ERROR, "Failed to connect: Database dbname not specified.\n");
  396. goto failed;
  397. }
  398. ptr = ast_variable_retrieve(cfg, "global", "user");
  399. if (ptr) {
  400. ast_string_field_set(settings, username, ptr);
  401. } else {
  402. ast_log(LOG_ERROR, "Failed to connect: Database dbuser not specified.\n");
  403. goto failed;
  404. }
  405. ptr = ast_variable_retrieve(cfg, "global", "password");
  406. if (ptr) {
  407. ast_string_field_set(settings, password, ptr);
  408. } else {
  409. ast_log(LOG_ERROR, "Failed to connect: Database password not specified.\n");
  410. goto failed;
  411. }
  412. ptr = ast_variable_retrieve(cfg, "global", "charset");
  413. if (ptr) {
  414. ast_string_field_set(settings, charset, ptr);
  415. }
  416. ptr = ast_variable_retrieve(cfg, "global", "language");
  417. if (ptr) {
  418. ast_string_field_set(settings, language, ptr);
  419. }
  420. ptr = ast_variable_retrieve(cfg, "global", "table");
  421. if (ptr) {
  422. ast_string_field_set(settings, table, ptr);
  423. } else {
  424. ast_log(LOG_NOTICE, "Table name not specified, using 'cel' by default.\n");
  425. ast_string_field_set(settings, table, "cel");
  426. }
  427. mssql_disconnect();
  428. if (mssql_connect()) {
  429. /* We failed to connect (mssql_connect takes care of logging it) */
  430. goto failed;
  431. }
  432. ast_mutex_unlock(&tds_lock);
  433. ast_config_destroy(cfg);
  434. return 1;
  435. failed:
  436. ast_mutex_unlock(&tds_lock);
  437. ast_config_destroy(cfg);
  438. return 0;
  439. }
  440. static int reload(void)
  441. {
  442. return tds_load_module(1);
  443. }
  444. static int load_module(void)
  445. {
  446. if (dbinit() == FAIL) {
  447. ast_log(LOG_ERROR, "Failed to initialize FreeTDS db-lib\n");
  448. return AST_MODULE_LOAD_DECLINE;
  449. }
  450. dberrhandle(tds_error_handler);
  451. dbmsghandle(tds_message_handler);
  452. settings = ast_calloc_with_stringfields(1, struct cel_tds_config, 256);
  453. if (!settings) {
  454. dbexit();
  455. return AST_MODULE_LOAD_DECLINE;
  456. }
  457. if (!tds_load_module(0)) {
  458. ast_string_field_free_memory(settings);
  459. ast_free(settings);
  460. settings = NULL;
  461. dbexit();
  462. ast_log(LOG_WARNING,"cel_tds module had config problems; declining load\n");
  463. return AST_MODULE_LOAD_DECLINE;
  464. }
  465. /* Register MSSQL CEL handler */
  466. if (ast_cel_backend_register(TDS_BACKEND_NAME, tds_log)) {
  467. ast_log(LOG_ERROR, "Unable to register MSSQL CEL handling\n");
  468. ast_string_field_free_memory(settings);
  469. ast_free(settings);
  470. settings = NULL;
  471. dbexit();
  472. return AST_MODULE_LOAD_DECLINE;
  473. }
  474. return AST_MODULE_LOAD_SUCCESS;
  475. }
  476. static int unload_module(void)
  477. {
  478. return tds_unload_module();
  479. }
  480. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "FreeTDS CEL Backend",
  481. .support_level = AST_MODULE_SUPPORT_EXTENDED,
  482. .load = load_module,
  483. .unload = unload_module,
  484. .reload = reload,
  485. .load_pri = AST_MODPRI_CDR_DRIVER,
  486. );