cel_odbc.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2008 Digium
  5. *
  6. * Adapted from cdr_adaptive_odbc:
  7. * Tilghman Lesher <tlesher AT digium DOT com>
  8. * by Steve Murphy
  9. *
  10. * See http://www.asterisk.org for more information about
  11. * the Asterisk project. Please do not directly contact
  12. * any of the maintainers of this project for assistance;
  13. * the project provides a web site, mailing lists and IRC
  14. * channels for your use.
  15. *
  16. * This program is free software, distributed under the terms of
  17. * the GNU General Public License Version 2. See the LICENSE file
  18. * at the top of the source tree.
  19. */
  20. /*! \file
  21. *
  22. * \brief ODBC CEL backend
  23. *
  24. * \author Tilghman Lesher \verbatim <tlesher AT digium DOT com> \endverbatim
  25. * \ingroup cel_drivers
  26. */
  27. /*** MODULEINFO
  28. <depend>res_odbc</depend>
  29. <depend>generic_odbc</depend>
  30. <support_level>core</support_level>
  31. ***/
  32. #include "asterisk.h"
  33. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  34. #include <sys/types.h>
  35. #include <time.h>
  36. #include <math.h>
  37. #include <sql.h>
  38. #include <sqlext.h>
  39. #include <sqltypes.h>
  40. #include "asterisk/config.h"
  41. #include "asterisk/channel.h"
  42. #include "asterisk/lock.h"
  43. #include "asterisk/linkedlists.h"
  44. #include "asterisk/res_odbc.h"
  45. #include "asterisk/cel.h"
  46. #include "asterisk/module.h"
  47. #define CONFIG "cel_odbc.conf"
  48. #define ODBC_BACKEND_NAME "ODBC CEL backend"
  49. /*! \brief show_user_def is off by default */
  50. #define CEL_SHOW_USERDEF_DEFAULT 0
  51. /*! TRUE if we should set the eventtype field to USER_DEFINED on user events. */
  52. static unsigned char cel_show_user_def;
  53. /* Optimization to reduce number of memory allocations */
  54. static int maxsize = 512, maxsize2 = 512;
  55. struct columns {
  56. char *name;
  57. char *celname;
  58. char *filtervalue;
  59. char *staticvalue;
  60. SQLSMALLINT type;
  61. SQLINTEGER size;
  62. SQLSMALLINT decimals;
  63. SQLSMALLINT radix;
  64. SQLSMALLINT nullable;
  65. SQLINTEGER octetlen;
  66. AST_LIST_ENTRY(columns) list;
  67. };
  68. struct tables {
  69. char *connection;
  70. char *table;
  71. unsigned int usegmtime:1;
  72. unsigned int allowleapsec:1;
  73. AST_LIST_HEAD_NOLOCK(odbc_columns, columns) columns;
  74. AST_RWLIST_ENTRY(tables) list;
  75. };
  76. static AST_RWLIST_HEAD_STATIC(odbc_tables, tables);
  77. static int load_config(void)
  78. {
  79. struct ast_config *cfg;
  80. struct ast_variable *var;
  81. const char *tmp, *catg;
  82. struct tables *tableptr;
  83. struct columns *entry;
  84. struct odbc_obj *obj;
  85. char columnname[80];
  86. char connection[40];
  87. char table[40];
  88. int lenconnection, lentable;
  89. SQLLEN sqlptr;
  90. int res = 0;
  91. SQLHSTMT stmt = NULL;
  92. struct ast_flags config_flags = { 0 }; /* Part of our config comes from the database */
  93. cfg = ast_config_load(CONFIG, config_flags);
  94. if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
  95. ast_log(LOG_WARNING, "Unable to load " CONFIG ". No ODBC CEL records!\n");
  96. return -1;
  97. }
  98. /* Process the general category */
  99. cel_show_user_def = CEL_SHOW_USERDEF_DEFAULT;
  100. for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
  101. if (!strcasecmp(var->name, "show_user_defined")) {
  102. cel_show_user_def = ast_true(var->value) ? 1 : 0;
  103. } else {
  104. /* Unknown option name. */
  105. }
  106. }
  107. for (catg = ast_category_browse(cfg, NULL); catg; catg = ast_category_browse(cfg, catg)) {
  108. if (!strcasecmp(catg, "general")) {
  109. continue;
  110. }
  111. var = ast_variable_browse(cfg, catg);
  112. if (!var)
  113. continue;
  114. if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "connection"))) {
  115. ast_log(LOG_WARNING, "No connection parameter found in '%s'. Skipping.\n", catg);
  116. continue;
  117. }
  118. ast_copy_string(connection, tmp, sizeof(connection));
  119. lenconnection = strlen(connection);
  120. /* When loading, we want to be sure we can connect. */
  121. obj = ast_odbc_request_obj(connection, 1);
  122. if (!obj) {
  123. ast_log(LOG_WARNING, "No such connection '%s' in the '%s' section of " CONFIG ". Check res_odbc.conf.\n", connection, catg);
  124. continue;
  125. }
  126. if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "table"))) {
  127. ast_log(LOG_NOTICE, "No table name found. Assuming 'cel'.\n");
  128. tmp = "cel";
  129. }
  130. ast_copy_string(table, tmp, sizeof(table));
  131. lentable = strlen(table);
  132. res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
  133. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  134. ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", connection);
  135. ast_odbc_release_obj(obj);
  136. continue;
  137. }
  138. res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)table, SQL_NTS, (unsigned char *)"%", SQL_NTS);
  139. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  140. ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'. Skipping.\n", connection);
  141. ast_odbc_release_obj(obj);
  142. continue;
  143. }
  144. tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + lenconnection + 1 + lentable + 1);
  145. if (!tableptr) {
  146. ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", table, connection);
  147. ast_odbc_release_obj(obj);
  148. res = -1;
  149. break;
  150. }
  151. tableptr->connection = (char *)tableptr + sizeof(*tableptr);
  152. tableptr->table = (char *)tableptr + sizeof(*tableptr) + lenconnection + 1;
  153. ast_copy_string(tableptr->connection, connection, lenconnection + 1);
  154. ast_copy_string(tableptr->table, table, lentable + 1);
  155. tableptr->usegmtime = 0;
  156. if (!ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "usegmtime"))) {
  157. tableptr->usegmtime = ast_true(tmp);
  158. }
  159. tableptr->allowleapsec = 1;
  160. if (!ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "allowleapsecond"))) {
  161. tableptr->allowleapsec = ast_true(tmp);
  162. }
  163. ast_verb(3, "Found CEL table %s@%s.\n", tableptr->table, tableptr->connection);
  164. /* Check for filters first */
  165. for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
  166. if (strncmp(var->name, "filter", 6) == 0) {
  167. char *celvar = ast_strdupa(var->name + 6);
  168. celvar = ast_strip(celvar);
  169. ast_verb(3, "Found filter %s for cel variable %s in %s@%s\n", var->value, celvar, tableptr->table, tableptr->connection);
  170. entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(celvar) + 1 + strlen(var->value) + 1);
  171. if (!entry) {
  172. ast_log(LOG_ERROR, "Out of memory creating filter entry for CEL variable '%s' in table '%s' on connection '%s'\n", celvar, table, connection);
  173. res = -1;
  174. break;
  175. }
  176. /* NULL column entry means this isn't a column in the database */
  177. entry->name = NULL;
  178. entry->celname = (char *)entry + sizeof(*entry);
  179. entry->filtervalue = (char *)entry + sizeof(*entry) + strlen(celvar) + 1;
  180. strcpy(entry->celname, celvar);
  181. strcpy(entry->filtervalue, var->value);
  182. AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
  183. }
  184. }
  185. while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
  186. char *celvar = "", *staticvalue = "";
  187. SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
  188. /* Is there an alias for this column? */
  189. /* NOTE: This seems like a non-optimal parse method, but I'm going
  190. * for user configuration readability, rather than fast parsing. We
  191. * really don't parse this file all that often, anyway.
  192. */
  193. for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
  194. if (strncmp(var->name, "alias", 5) == 0 && strcasecmp(var->value, columnname) == 0) {
  195. char *alias = ast_strdupa(var->name + 5);
  196. celvar = ast_strip(alias);
  197. ast_verb(3, "Found alias %s for column %s in %s@%s\n", celvar, columnname, tableptr->table, tableptr->connection);
  198. break;
  199. } else if (strncmp(var->name, "static", 6) == 0 && strcasecmp(var->value, columnname) == 0) {
  200. char *item = ast_strdupa(var->name + 6);
  201. item = ast_strip(item);
  202. if (item[0] == '"' && item[strlen(item) - 1] == '"') {
  203. /* Remove surrounding quotes */
  204. item[strlen(item) - 1] = '\0';
  205. item++;
  206. }
  207. staticvalue = item;
  208. }
  209. }
  210. entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1 + strlen(celvar) + 1 + strlen(staticvalue) + 1);
  211. if (!entry) {
  212. ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, table, connection);
  213. res = -1;
  214. break;
  215. }
  216. entry->name = (char *)entry + sizeof(*entry);
  217. strcpy(entry->name, columnname);
  218. if (!ast_strlen_zero(celvar)) {
  219. entry->celname = entry->name + strlen(columnname) + 1;
  220. strcpy(entry->celname, celvar);
  221. } else { /* Point to same place as the column name */
  222. entry->celname = (char *)entry + sizeof(*entry);
  223. }
  224. if (!ast_strlen_zero(staticvalue)) {
  225. entry->staticvalue = entry->celname + strlen(entry->celname) + 1;
  226. strcpy(entry->staticvalue, staticvalue);
  227. }
  228. SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
  229. SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
  230. SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
  231. SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
  232. SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
  233. SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
  234. /* Specification states that the octenlen should be the maximum number of bytes
  235. * returned in a char or binary column, but it seems that some drivers just set
  236. * it to NULL. (Bad Postgres! No biscuit!) */
  237. if (entry->octetlen == 0)
  238. entry->octetlen = entry->size;
  239. ast_verb(10, "Found %s column with type %hd with len %ld, octetlen %ld, and numlen (%hd,%hd)\n", entry->name, entry->type, (long) entry->size, (long) entry->octetlen, entry->decimals, entry->radix);
  240. /* Insert column info into column list */
  241. AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
  242. res = 0;
  243. }
  244. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  245. ast_odbc_release_obj(obj);
  246. if (AST_LIST_FIRST(&(tableptr->columns)))
  247. AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
  248. else
  249. ast_free(tableptr);
  250. }
  251. ast_config_destroy(cfg);
  252. return res;
  253. }
  254. static int free_config(void)
  255. {
  256. struct tables *table;
  257. struct columns *entry;
  258. while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
  259. while ((entry = AST_LIST_REMOVE_HEAD(&(table->columns), list))) {
  260. ast_free(entry);
  261. }
  262. ast_free(table);
  263. }
  264. return 0;
  265. }
  266. static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
  267. {
  268. int res, i;
  269. char *sql = data;
  270. SQLHSTMT stmt;
  271. SQLINTEGER nativeerror = 0, numfields = 0;
  272. SQLSMALLINT diagbytes = 0;
  273. unsigned char state[10], diagnostic[256];
  274. res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
  275. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  276. ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
  277. return NULL;
  278. }
  279. res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
  280. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  281. ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
  282. SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  283. for (i = 0; i < numfields; i++) {
  284. SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  285. ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
  286. if (i > 10) {
  287. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  288. break;
  289. }
  290. }
  291. SQLFreeHandle (SQL_HANDLE_STMT, stmt);
  292. return NULL;
  293. }
  294. return stmt;
  295. }
  296. #define LENGTHEN_BUF1(size) \
  297. do { \
  298. /* Lengthen buffer, if necessary */ \
  299. if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) { \
  300. if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 1) / 512 + 1) * 512) != 0) { \
  301. ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CEL '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
  302. ast_free(sql); \
  303. ast_free(sql2); \
  304. AST_RWLIST_UNLOCK(&odbc_tables); \
  305. return; \
  306. } \
  307. } \
  308. } while (0)
  309. #define LENGTHEN_BUF2(size) \
  310. do { \
  311. if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) { \
  312. if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) { \
  313. ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CEL '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
  314. ast_free(sql); \
  315. ast_free(sql2); \
  316. AST_RWLIST_UNLOCK(&odbc_tables); \
  317. return; \
  318. } \
  319. } \
  320. } while (0)
  321. static void odbc_log(struct ast_event *event)
  322. {
  323. struct tables *tableptr;
  324. struct columns *entry;
  325. struct odbc_obj *obj;
  326. struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
  327. char *tmp;
  328. char colbuf[1024], *colptr;
  329. SQLHSTMT stmt = NULL;
  330. SQLLEN rows = 0;
  331. struct ast_cel_event_record record = {
  332. .version = AST_CEL_EVENT_RECORD_VERSION,
  333. };
  334. if (ast_cel_fill_record(event, &record)) {
  335. return;
  336. }
  337. if (!sql || !sql2) {
  338. if (sql)
  339. ast_free(sql);
  340. if (sql2)
  341. ast_free(sql2);
  342. return;
  343. }
  344. if (AST_RWLIST_RDLOCK(&odbc_tables)) {
  345. ast_log(LOG_ERROR, "Unable to lock table list. Insert CEL(s) failed.\n");
  346. ast_free(sql);
  347. ast_free(sql2);
  348. return;
  349. }
  350. AST_LIST_TRAVERSE(&odbc_tables, tableptr, list) {
  351. int first = 1;
  352. ast_str_set(&sql, 0, "INSERT INTO %s (", tableptr->table);
  353. ast_str_set(&sql2, 0, " VALUES (");
  354. /* No need to check the connection now; we'll handle any failure in prepare_and_execute */
  355. if (!(obj = ast_odbc_request_obj(tableptr->connection, 0))) {
  356. ast_log(LOG_WARNING, "Unable to retrieve database handle for '%s:%s'. CEL failed: %s\n", tableptr->connection, tableptr->table, ast_str_buffer(sql));
  357. continue;
  358. }
  359. AST_LIST_TRAVERSE(&(tableptr->columns), entry, list) {
  360. int datefield = 0;
  361. int unknown = 0;
  362. if (strcasecmp(entry->celname, "eventtime") == 0) {
  363. datefield = 1;
  364. }
  365. /* Check if we have a similarly named variable */
  366. if (entry->staticvalue) {
  367. colptr = ast_strdupa(entry->staticvalue);
  368. } else if (datefield) {
  369. struct timeval date_tv = record.event_time;
  370. struct ast_tm tm = { 0, };
  371. ast_localtime(&date_tv, &tm, tableptr->usegmtime ? "UTC" : NULL);
  372. /* SQL server 2008 added datetime2 and datetimeoffset data types, that
  373. are reported to SQLColumns() as SQL_WVARCHAR, according to "Enhanced
  374. Date/Time Type Behavior with Previous SQL Server Versions (ODBC)".
  375. Here we format the event time with fraction seconds, so these new
  376. column types will be set to high-precision event time. However, 'date'
  377. and 'time' columns, also newly introduced, reported as SQL_WVARCHAR
  378. too, and insertion of the value formatted here into these will fail.
  379. This should be ok, however, as nobody is going to store just event
  380. date or just time for CDR purposes.
  381. */
  382. ast_strftime(colbuf, sizeof(colbuf), "%Y-%m-%d %H:%M:%S.%6q", &tm);
  383. colptr = colbuf;
  384. } else {
  385. if (strcmp(entry->celname, "userdeftype") == 0) {
  386. ast_copy_string(colbuf, record.user_defined_name, sizeof(colbuf));
  387. } else if (strcmp(entry->celname, "cid_name") == 0) {
  388. ast_copy_string(colbuf, record.caller_id_name, sizeof(colbuf));
  389. } else if (strcmp(entry->celname, "cid_num") == 0) {
  390. ast_copy_string(colbuf, record.caller_id_num, sizeof(colbuf));
  391. } else if (strcmp(entry->celname, "cid_ani") == 0) {
  392. ast_copy_string(colbuf, record.caller_id_ani, sizeof(colbuf));
  393. } else if (strcmp(entry->celname, "cid_rdnis") == 0) {
  394. ast_copy_string(colbuf, record.caller_id_rdnis, sizeof(colbuf));
  395. } else if (strcmp(entry->celname, "cid_dnid") == 0) {
  396. ast_copy_string(colbuf, record.caller_id_dnid, sizeof(colbuf));
  397. } else if (strcmp(entry->celname, "exten") == 0) {
  398. ast_copy_string(colbuf, record.extension, sizeof(colbuf));
  399. } else if (strcmp(entry->celname, "context") == 0) {
  400. ast_copy_string(colbuf, record.context, sizeof(colbuf));
  401. } else if (strcmp(entry->celname, "channame") == 0) {
  402. ast_copy_string(colbuf, record.channel_name, sizeof(colbuf));
  403. } else if (strcmp(entry->celname, "appname") == 0) {
  404. ast_copy_string(colbuf, record.application_name, sizeof(colbuf));
  405. } else if (strcmp(entry->celname, "appdata") == 0) {
  406. ast_copy_string(colbuf, record.application_data, sizeof(colbuf));
  407. } else if (strcmp(entry->celname, "accountcode") == 0) {
  408. ast_copy_string(colbuf, record.account_code, sizeof(colbuf));
  409. } else if (strcmp(entry->celname, "peeraccount") == 0) {
  410. ast_copy_string(colbuf, record.peer_account, sizeof(colbuf));
  411. } else if (strcmp(entry->celname, "uniqueid") == 0) {
  412. ast_copy_string(colbuf, record.unique_id, sizeof(colbuf));
  413. } else if (strcmp(entry->celname, "linkedid") == 0) {
  414. ast_copy_string(colbuf, record.linked_id, sizeof(colbuf));
  415. } else if (strcmp(entry->celname, "userfield") == 0) {
  416. ast_copy_string(colbuf, record.user_field, sizeof(colbuf));
  417. } else if (strcmp(entry->celname, "peer") == 0) {
  418. ast_copy_string(colbuf, record.peer, sizeof(colbuf));
  419. } else if (strcmp(entry->celname, "amaflags") == 0) {
  420. snprintf(colbuf, sizeof(colbuf), "%u", record.amaflag);
  421. } else if (strcmp(entry->celname, "extra") == 0) {
  422. ast_copy_string(colbuf, record.extra, sizeof(colbuf));
  423. } else if (strcmp(entry->celname, "eventtype") == 0) {
  424. snprintf(colbuf, sizeof(colbuf), "%u", record.event_type);
  425. } else {
  426. colbuf[0] = 0;
  427. unknown = 1;
  428. }
  429. colptr = colbuf;
  430. }
  431. if (colptr && !unknown) {
  432. /* Check first if the column filters this entry. Note that this
  433. * is very specifically NOT ast_strlen_zero(), because the filter
  434. * could legitimately specify that the field is blank, which is
  435. * different from the field being unspecified (NULL). */
  436. if (entry->filtervalue && strcasecmp(colptr, entry->filtervalue) != 0) {
  437. ast_verb(4, "CEL column '%s' with value '%s' does not match filter of"
  438. " '%s'. Cancelling this CEL.\n",
  439. entry->celname, colptr, entry->filtervalue);
  440. goto early_release;
  441. }
  442. /* Only a filter? */
  443. if (ast_strlen_zero(entry->name))
  444. continue;
  445. LENGTHEN_BUF1(strlen(entry->name));
  446. switch (entry->type) {
  447. case SQL_CHAR:
  448. case SQL_VARCHAR:
  449. case SQL_LONGVARCHAR:
  450. #ifdef HAVE_ODBC_WCHAR
  451. case SQL_WCHAR:
  452. case SQL_WVARCHAR:
  453. case SQL_WLONGVARCHAR:
  454. #endif
  455. case SQL_BINARY:
  456. case SQL_VARBINARY:
  457. case SQL_LONGVARBINARY:
  458. case SQL_GUID:
  459. /* For these two field names, get the rendered form, instead of the raw
  460. * form (but only when we're dealing with a character-based field).
  461. */
  462. if (strcasecmp(entry->name, "eventtype") == 0) {
  463. const char *event_name;
  464. event_name = (!cel_show_user_def
  465. && record.event_type == AST_CEL_USER_DEFINED)
  466. ? record.user_defined_name : record.event_name;
  467. snprintf(colbuf, sizeof(colbuf), "%s", event_name);
  468. }
  469. /* Truncate too-long fields */
  470. if (entry->type != SQL_GUID) {
  471. if (strlen(colptr) > entry->octetlen) {
  472. colptr[entry->octetlen] = '\0';
  473. }
  474. }
  475. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  476. LENGTHEN_BUF2(strlen(colptr));
  477. /* Encode value, with escaping */
  478. ast_str_append(&sql2, 0, "%s'", first ? "" : ",");
  479. for (tmp = colptr; *tmp; tmp++) {
  480. if (*tmp == '\'') {
  481. ast_str_append(&sql2, 0, "''");
  482. } else if (*tmp == '\\' && ast_odbc_backslash_is_escape(obj)) {
  483. ast_str_append(&sql2, 0, "\\\\");
  484. } else {
  485. ast_str_append(&sql2, 0, "%c", *tmp);
  486. }
  487. }
  488. ast_str_append(&sql2, 0, "'");
  489. break;
  490. case SQL_TYPE_DATE:
  491. if (ast_strlen_zero(colptr)) {
  492. continue;
  493. } else {
  494. int year = 0, month = 0, day = 0;
  495. if (strcasecmp(entry->name, "eventdate") == 0) {
  496. struct ast_tm tm;
  497. ast_localtime(&record.event_time, &tm, tableptr->usegmtime ? "UTC" : NULL);
  498. year = tm.tm_year + 1900;
  499. month = tm.tm_mon + 1;
  500. day = tm.tm_mday;
  501. } else {
  502. if (sscanf(colptr, "%4d-%2d-%2d", &year, &month, &day) != 3 || year <= 0 ||
  503. month <= 0 || month > 12 || day < 0 || day > 31 ||
  504. ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
  505. (month == 2 && year % 400 == 0 && day > 29) ||
  506. (month == 2 && year % 100 == 0 && day > 28) ||
  507. (month == 2 && year % 4 == 0 && day > 29) ||
  508. (month == 2 && year % 4 != 0 && day > 28)) {
  509. ast_log(LOG_WARNING, "CEL variable %s is not a valid date ('%s').\n", entry->name, colptr);
  510. continue;
  511. }
  512. if (year > 0 && year < 100) {
  513. year += 2000;
  514. }
  515. }
  516. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  517. LENGTHEN_BUF2(17);
  518. ast_str_append(&sql2, 0, "%s{d '%04d-%02d-%02d'}", first ? "" : ",", year, month, day);
  519. }
  520. break;
  521. case SQL_TYPE_TIME:
  522. if (ast_strlen_zero(colptr)) {
  523. continue;
  524. } else {
  525. int hour = 0, minute = 0, second = 0;
  526. if (strcasecmp(entry->name, "eventdate") == 0) {
  527. struct ast_tm tm;
  528. ast_localtime(&record.event_time, &tm, tableptr->usegmtime ? "UTC" : NULL);
  529. hour = tm.tm_hour;
  530. minute = tm.tm_min;
  531. second = (tableptr->allowleapsec || tm.tm_sec < 60) ? tm.tm_sec : 59;
  532. } else {
  533. int count = sscanf(colptr, "%2d:%2d:%2d", &hour, &minute, &second);
  534. if ((count != 2 && count != 3) || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > (tableptr->allowleapsec ? 60 : 59)) {
  535. ast_log(LOG_WARNING, "CEL variable %s is not a valid time ('%s').\n", entry->name, colptr);
  536. continue;
  537. }
  538. }
  539. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  540. LENGTHEN_BUF2(15);
  541. ast_str_append(&sql2, 0, "%s{t '%02d:%02d:%02d'}", first ? "" : ",", hour, minute, second);
  542. }
  543. break;
  544. case SQL_TYPE_TIMESTAMP:
  545. case SQL_TIMESTAMP:
  546. if (ast_strlen_zero(colptr)) {
  547. continue;
  548. } else {
  549. if (datefield) {
  550. /*
  551. * We've already properly formatted the timestamp so there's no need
  552. * to parse it and re-format it.
  553. */
  554. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  555. LENGTHEN_BUF2(27);
  556. ast_str_append(&sql2, 0, "%s{ts '%s'}", first ? "" : ",", colptr);
  557. } else {
  558. int year = 0, month = 0, day = 0, hour = 0, minute = 0;
  559. /* MUST use double for microsecond precision */
  560. double second = 0.0;
  561. if (strcasecmp(entry->name, "eventdate") == 0) {
  562. /*
  563. * There doesn't seem to be any reference to 'eventdate' anywhere
  564. * other than in this module. It should be considered for removal
  565. * at a later date.
  566. */
  567. struct ast_tm tm;
  568. ast_localtime(&record.event_time, &tm, tableptr->usegmtime ? "UTC" : NULL);
  569. year = tm.tm_year + 1900;
  570. month = tm.tm_mon + 1;
  571. day = tm.tm_mday;
  572. hour = tm.tm_hour;
  573. minute = tm.tm_min;
  574. second = (tableptr->allowleapsec || tm.tm_sec < 60) ? tm.tm_sec : 59;
  575. second += (tm.tm_usec / 1000000.0);
  576. } else {
  577. /*
  578. * If we're here, the data to be inserted MAY be a timestamp
  579. * but the column is. We parse as much as we can.
  580. */
  581. int count = sscanf(colptr, "%4d-%2d-%2d %2d:%2d:%lf", &year, &month, &day, &hour, &minute, &second);
  582. if ((count != 3 && count != 5 && count != 6) || year <= 0 ||
  583. month <= 0 || month > 12 || day < 0 || day > 31 ||
  584. ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
  585. (month == 2 && year % 400 == 0 && day > 29) ||
  586. (month == 2 && year % 100 == 0 && day > 28) ||
  587. (month == 2 && year % 4 == 0 && day > 29) ||
  588. (month == 2 && year % 4 != 0 && day > 28) ||
  589. hour > 23 || minute > 59 || ((int)floor(second)) > (tableptr->allowleapsec ? 60 : 59) ||
  590. hour < 0 || minute < 0 || ((int)floor(second)) < 0) {
  591. ast_log(LOG_WARNING, "CEL variable %s is not a valid timestamp ('%s').\n", entry->name, colptr);
  592. continue;
  593. }
  594. if (year > 0 && year < 100) {
  595. year += 2000;
  596. }
  597. }
  598. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  599. LENGTHEN_BUF2(27);
  600. ast_str_append(&sql2, 0, "%s{ts '%04d-%02d-%02d %02d:%02d:%09.6lf'}", first ? "" : ",", year, month, day, hour, minute, second);
  601. }
  602. }
  603. break;
  604. case SQL_INTEGER:
  605. {
  606. int integer = 0;
  607. if (sscanf(colptr, "%30d", &integer) != 1) {
  608. ast_log(LOG_WARNING, "CEL variable %s is not an integer.\n", entry->name);
  609. continue;
  610. }
  611. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  612. LENGTHEN_BUF2(12);
  613. ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
  614. }
  615. break;
  616. case SQL_BIGINT:
  617. {
  618. long long integer = 0;
  619. int ret;
  620. if ((ret = sscanf(colptr, "%30lld", &integer)) != 1) {
  621. ast_log(LOG_WARNING, "CEL variable %s is not an integer. (%d - '%s')\n", entry->name, ret, colptr);
  622. continue;
  623. }
  624. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  625. LENGTHEN_BUF2(24);
  626. ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", integer);
  627. }
  628. break;
  629. case SQL_SMALLINT:
  630. {
  631. short integer = 0;
  632. if (sscanf(colptr, "%30hd", &integer) != 1) {
  633. ast_log(LOG_WARNING, "CEL variable %s is not an integer.\n", entry->name);
  634. continue;
  635. }
  636. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  637. LENGTHEN_BUF2(7);
  638. ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
  639. }
  640. break;
  641. case SQL_TINYINT:
  642. {
  643. signed char integer = 0;
  644. if (sscanf(colptr, "%30hhd", &integer) != 1) {
  645. ast_log(LOG_WARNING, "CEL variable %s is not an integer.\n", entry->name);
  646. continue;
  647. }
  648. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  649. LENGTHEN_BUF2(4);
  650. ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
  651. }
  652. break;
  653. case SQL_BIT:
  654. {
  655. signed char integer = 0;
  656. if (sscanf(colptr, "%30hhd", &integer) != 1) {
  657. ast_log(LOG_WARNING, "CEL variable %s is not an integer.\n", entry->name);
  658. continue;
  659. }
  660. if (integer != 0)
  661. integer = 1;
  662. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  663. LENGTHEN_BUF2(2);
  664. ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", integer);
  665. }
  666. break;
  667. case SQL_NUMERIC:
  668. case SQL_DECIMAL:
  669. {
  670. double number = 0.0;
  671. if (sscanf(colptr, "%30lf", &number) != 1) {
  672. ast_log(LOG_WARNING, "CEL variable %s is not an numeric type.\n", entry->name);
  673. continue;
  674. }
  675. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  676. LENGTHEN_BUF2(entry->decimals + 2);
  677. ast_str_append(&sql2, 0, "%s%*.*lf", first ? "" : ",", entry->decimals, entry->radix, number);
  678. }
  679. break;
  680. case SQL_FLOAT:
  681. case SQL_REAL:
  682. case SQL_DOUBLE:
  683. {
  684. double number = 0.0;
  685. if (sscanf(colptr, "%30lf", &number) != 1) {
  686. ast_log(LOG_WARNING, "CEL variable %s is not an numeric type.\n", entry->name);
  687. continue;
  688. }
  689. ast_str_append(&sql, 0, "%s%s", first ? "" : ",", entry->name);
  690. LENGTHEN_BUF2(entry->decimals);
  691. ast_str_append(&sql2, 0, "%s%lf", first ? "" : ",", number);
  692. }
  693. break;
  694. default:
  695. ast_log(LOG_WARNING, "Column type %d (field '%s:%s:%s') is unsupported at this time.\n", entry->type, tableptr->connection, tableptr->table, entry->name);
  696. continue;
  697. }
  698. first = 0;
  699. }
  700. }
  701. /* Concatenate the two constructed buffers */
  702. LENGTHEN_BUF1(ast_str_strlen(sql2));
  703. ast_str_append(&sql, 0, ")");
  704. ast_str_append(&sql2, 0, ")");
  705. ast_str_append(&sql, 0, "%s", ast_str_buffer(sql2));
  706. ast_debug(3, "Executing SQL statement: [%s]\n", ast_str_buffer(sql));
  707. stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, ast_str_buffer(sql));
  708. if (stmt) {
  709. SQLRowCount(stmt, &rows);
  710. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  711. }
  712. if (rows == 0) {
  713. ast_log(LOG_WARNING, "Insert failed on '%s:%s'. CEL failed: %s\n", tableptr->connection, tableptr->table, ast_str_buffer(sql));
  714. }
  715. early_release:
  716. ast_odbc_release_obj(obj);
  717. }
  718. AST_RWLIST_UNLOCK(&odbc_tables);
  719. /* Next time, just allocate buffers that are that big to start with. */
  720. if (ast_str_strlen(sql) > maxsize) {
  721. maxsize = ast_str_strlen(sql);
  722. }
  723. if (ast_str_strlen(sql2) > maxsize2) {
  724. maxsize2 = ast_str_strlen(sql2);
  725. }
  726. ast_free(sql);
  727. ast_free(sql2);
  728. }
  729. static int unload_module(void)
  730. {
  731. if (AST_RWLIST_WRLOCK(&odbc_tables)) {
  732. ast_log(LOG_ERROR, "Unable to lock column list. Unload failed.\n");
  733. return -1;
  734. }
  735. ast_cel_backend_unregister(ODBC_BACKEND_NAME);
  736. free_config();
  737. AST_RWLIST_UNLOCK(&odbc_tables);
  738. AST_RWLIST_HEAD_DESTROY(&odbc_tables);
  739. return 0;
  740. }
  741. static int load_module(void)
  742. {
  743. AST_RWLIST_HEAD_INIT(&odbc_tables);
  744. if (AST_RWLIST_WRLOCK(&odbc_tables)) {
  745. ast_log(LOG_ERROR, "Unable to lock column list. Load failed.\n");
  746. return AST_MODULE_LOAD_DECLINE;
  747. }
  748. load_config();
  749. AST_RWLIST_UNLOCK(&odbc_tables);
  750. if (ast_cel_backend_register(ODBC_BACKEND_NAME, odbc_log)) {
  751. ast_log(LOG_ERROR, "Unable to subscribe to CEL events\n");
  752. free_config();
  753. return AST_MODULE_LOAD_DECLINE;
  754. }
  755. return AST_MODULE_LOAD_SUCCESS;
  756. }
  757. static int reload(void)
  758. {
  759. if (AST_RWLIST_WRLOCK(&odbc_tables)) {
  760. ast_log(LOG_ERROR, "Unable to lock column list. Reload failed.\n");
  761. return AST_MODULE_LOAD_DECLINE;
  762. }
  763. free_config();
  764. load_config();
  765. AST_RWLIST_UNLOCK(&odbc_tables);
  766. return AST_MODULE_LOAD_SUCCESS;
  767. }
  768. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "ODBC CEL backend",
  769. .support_level = AST_MODULE_SUPPORT_CORE,
  770. .load = load_module,
  771. .unload = unload_module,
  772. .reload = reload,
  773. .load_pri = AST_MODPRI_CDR_DRIVER,
  774. );