cel_tds.c 14 KB

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