2 * Asterisk -- A telephony toolkit for Linux.
6 * Copyright (c) 2005 Tilghman Lesher
8 * Tilghman Lesher <func_odbc__200508@the-tilghman.com>
10 * Special thanks to Anthony Minessale II for debugging help.
13 #include <sys/types.h>
18 #include <asterisk/file.h>
19 #include <asterisk/logger.h>
20 #include <asterisk/options.h>
21 #include <asterisk/channel.h>
22 #include <asterisk/pbx.h>
23 #include <asterisk/module.h>
24 #include <asterisk/config.h>
25 #include <asterisk/res_odbc.h>
27 static char *tdesc = "ODBC lookups";
29 static char *config = "func_odbc.conf";
31 struct acf_odbc_query {
36 struct ast_custom_function *acf;
37 unsigned int deleteme:1;
38 struct acf_odbc_query *next;
41 static struct acf_odbc_query *queries = NULL;
42 AST_MUTEX_DEFINE_STATIC(query_lock);
45 static void acf_odbc_error(SQLHSTMT stmt, int res)
47 char state[10] = "", diagnostic[256] = "";
48 SQLINTEGER nativeerror = 0;
49 SQLSMALLINT diagbytes = 0;
50 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
51 ast_log(LOG_WARNING, "SQL return value %d: error %s: %s (len %d)\n", res, state, diagnostic, diagbytes);
56 * Master control routine
58 static void acf_odbc_write(struct ast_channel *chan, char *cmd, char *data, const char *value)
61 struct acf_odbc_query *query;
62 char *s, *t, *arg, buf[512]="", varname[15];
63 int res, argcount=0, valcount=0, i, retry=0;
64 struct ast_channel *ast;
66 SQLINTEGER nativeerror=0, numfields=0, rows=0;
67 SQLSMALLINT diagbytes=0;
68 unsigned char state[10], diagnostic[256];
70 SQLINTEGER enable = 1;
71 char *tracefile = "/tmp/odbc.trace";
74 ast_mutex_lock(&query_lock);
75 for (query=queries; query; query = query->next) {
76 if (!strcasecmp(query->name, cmd + 5)) {
82 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
83 ast_mutex_unlock(&query_lock);
87 obj = fetch_odbc_obj(query->dsn, 0);
90 ast_log(LOG_ERROR, "No such DSN registered: %s (check res_odbc.conf)\n", query->dsn);
91 ast_mutex_unlock(&query_lock);
95 /* Parse our arguments */
96 s = ast_strdupa(data);
98 t = ast_strdupa(value);
104 ast_log(LOG_ERROR, "Out of memory\n");
105 ast_mutex_unlock(&query_lock);
109 /* XXX You might be tempted to change this section into using
110 * pbx_builtin_pushvar_helper(). However, note that if you try
111 * to set a NULL (like for VALUE), then nothing gets set, and the
112 * value doesn't get masked out. Even worse, when you subsequently
113 * try to remove the value you just set, you'll wind up unsetting
114 * the previous value (which is wholly undesireable). Hence, this
115 * has to remain the way it is done here. XXX
118 /* Save old arguments as variables in a fake channel */
119 ast = ast_channel_alloc(0);
120 while ((arg = strsep(&s, "|"))) {
122 snprintf(varname, sizeof(varname), "ARG%d", argcount);
123 pbx_builtin_setvar_helper(ast, varname, pbx_builtin_getvar_helper(chan, varname));
124 pbx_builtin_setvar_helper(chan, varname, arg);
127 /* Parse values, just like arguments */
128 while ((arg = strsep(&t, "|"))) {
130 snprintf(varname, sizeof(varname), "VAL%d", valcount);
131 pbx_builtin_setvar_helper(ast, varname, pbx_builtin_getvar_helper(chan, varname));
132 pbx_builtin_setvar_helper(chan, varname, arg);
135 /* Additionally set the value as a whole */
136 /* Note that pbx_builtin_setvar_helper will quite happily take a NULL for the 3rd argument */
137 pbx_builtin_setvar_helper(ast, "VALUE", pbx_builtin_getvar_helper(chan, "VALUE"));
138 pbx_builtin_setvar_helper(chan, "VALUE", value);
140 pbx_substitute_variables_helper(chan, query->sql_write, buf, sizeof(buf) - 1);
142 /* Restore prior values */
143 for (i=1; i<=argcount; i++) {
144 snprintf(varname, sizeof(varname), "ARG%d", argcount);
145 pbx_builtin_setvar_helper(chan, varname, pbx_builtin_getvar_helper(ast, varname));
148 for (i=1; i<=valcount; i++) {
149 snprintf(varname, sizeof(varname), "VAL%d", argcount);
150 pbx_builtin_setvar_helper(chan, varname, pbx_builtin_getvar_helper(ast, varname));
152 pbx_builtin_setvar_helper(chan, "VALUE", pbx_builtin_getvar_helper(ast, "VALUE"));
154 ast_channel_free(ast);
155 ast_mutex_unlock(&query_lock);
159 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
160 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
163 res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
164 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
165 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
166 pbx_builtin_setvar_helper(chan, "ODBCROWS", "-1");
170 res = SQLPrepare(stmt, (unsigned char *)buf, SQL_NTS);
171 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
172 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", buf);
173 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
174 pbx_builtin_setvar_helper(chan, "ODBCROWS", "-1");
178 res = SQLExecute(stmt);
179 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
180 if (res == SQL_ERROR) {
181 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
182 for (i = 0; i <= numfields; i++) {
183 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
184 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
186 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
191 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
192 odbc_obj_disconnect(obj);
193 /* All handles are now invalid (after a disconnect), so we gotta redo all handles */
194 odbc_obj_connect(obj);
202 SQLRowCount(stmt, &rows);
205 /* Output the affected rows, for all cases. In the event of failure, we
206 * flag this as -1 rows. Note that this is different from 0 affected rows
207 * which would be the case if we succeeded in our query, but the values did
209 snprintf(varname, sizeof(varname), "%d", (int)rows);
210 pbx_builtin_setvar_helper(chan, "ODBCROWS", varname);
212 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
213 ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", buf);
216 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
219 static char *acf_odbc_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
222 struct acf_odbc_query *query;
223 char *s, *arg, sql[512] = "", varname[15];
226 SQLSMALLINT colcount=0;
227 SQLINTEGER indicator;
229 SQLINTEGER enable = 1;
230 char *tracefile = "/tmp/odbc.trace";
233 ast_mutex_lock(&query_lock);
234 for (query=queries; query; query = query->next) {
235 if (!strcasecmp(query->name, cmd + 5)) {
241 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
242 ast_mutex_unlock(&query_lock);
246 obj = fetch_odbc_obj(query->dsn, 0);
249 ast_log(LOG_ERROR, "No such DSN registered: %s (check res_odbc.conf)\n", query->dsn);
250 ast_mutex_unlock(&query_lock);
255 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
256 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
259 /* Parse our arguments */
260 s = ast_strdupa(data);
262 ast_log(LOG_ERROR, "Out of memory\n");
263 ast_mutex_unlock(&query_lock);
267 while ((arg = strsep(&s, "|"))) {
269 snprintf(varname, sizeof(varname), "ARG%d", count);
270 /* arg is by definition non-NULL, so this works, here */
271 pbx_builtin_pushvar_helper(chan, varname, arg);
274 pbx_substitute_variables_helper(chan, query->sql_read, sql, sizeof(sql) - 1);
276 /* Restore prior values */
277 for (x = 1; x <= count; x++) {
278 snprintf(varname, sizeof(varname), "ARG%d", x);
279 pbx_builtin_setvar_helper(chan, varname, NULL);
282 ast_mutex_unlock(&query_lock);
284 res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
285 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
286 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
290 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
291 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
292 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
293 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
297 res = odbc_smart_execute(obj, stmt);
298 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
299 ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
300 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
304 res = SQLNumResultCols(stmt, &colcount);
305 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
306 ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
307 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
313 res = SQLFetch(stmt);
314 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
315 if (res == SQL_NO_DATA) {
316 if (option_verbose > 3) {
317 ast_verbose(VERBOSE_PREFIX_4 "Found no rows [%s]\n", sql);
319 } else if (option_verbose > 3) {
320 ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, sql);
325 for (x=0; x<colcount; x++) {
326 int buflen, coldatalen;
329 buflen = strlen(buf);
330 res = SQLGetData(stmt, x + 1, SQL_CHAR, coldata, sizeof(coldata), &indicator);
331 if (indicator == SQL_NULL_DATA) {
336 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
337 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
338 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
342 strncat(buf + buflen, coldata, len - buflen);
343 coldatalen = strlen(coldata);
344 strncat(buf + buflen + coldatalen, ",", len - buflen - coldatalen);
346 /* Trim trailing comma */
347 buf[strlen(buf) - 1] = '\0';
350 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
354 static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
362 *query = calloc(1, sizeof(struct acf_odbc_query));
366 ast_copy_string((*query)->name, catg, sizeof((*query)->name));
368 if ((tmp = ast_variable_retrieve(cfg, catg, "dsn"))) {
369 ast_copy_string((*query)->dsn, tmp, sizeof((*query)->dsn));
374 if ((tmp = ast_variable_retrieve(cfg, catg, "read"))) {
375 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
378 if ((tmp = ast_variable_retrieve(cfg, catg, "write"))) {
379 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
382 (*query)->acf = calloc(1, sizeof(struct ast_custom_function));
384 asprintf(&((*query)->acf->name), "ODBC_%s", catg);
385 asprintf(&((*query)->acf->syntax), "ODBC_%s(<arg1>[...[,<argN>]])", catg);
386 (*query)->acf->synopsis = "Runs the referenced query with the specified arguments";
387 if (!ast_strlen_zero((*query)->sql_read) && !ast_strlen_zero((*query)->sql_write)) {
388 asprintf(&((*query)->acf->desc),
389 "Runs the following query, as defined in func_odbc.conf, performing\n"
390 "substitution of the arguments into the query as specified by ${ARG1},\n"
391 "${ARG2}, ... ${ARGn}. When setting the function, the values are provided\n"
392 "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
393 "\nRead:\n%s\n\nWrite:\n%s\n",
395 (*query)->sql_write);
396 } else if (!ast_strlen_zero((*query)->sql_read)) {
397 asprintf(&((*query)->acf->desc),
398 "Runs the following query, as defined in func_odbc.conf, performing\n"
399 "substitution of the arguments into the query as specified by ${ARG1},\n"
400 "${ARG2}, ... ${ARGn}. This function may only be read, not set.\n\nSQL:\n%s\n",
402 } else if (!ast_strlen_zero((*query)->sql_write)) {
403 asprintf(&((*query)->acf->desc),
404 "Runs the following query, as defined in func_odbc.conf, performing\n"
405 "substitution of the arguments into the query as specified by ${ARG1},\n"
406 "${ARG2}, ... ${ARGn}. The values are provided either in whole as\n"
407 "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
408 "This function may only be set.\nSQL:\n%s\n",
409 (*query)->sql_write);
412 if (ast_strlen_zero((*query)->sql_read)) {
413 (*query)->acf->read = NULL;
415 (*query)->acf->read = acf_odbc_read;
418 if (ast_strlen_zero((*query)->sql_write)) {
419 (*query)->acf->write = NULL;
421 (*query)->acf->write = acf_odbc_write;
424 if (! (*query)->acf->name || ! (*query)->acf->syntax || ! (*query)->acf->desc) {
433 static int free_acf_query(struct acf_odbc_query *query)
437 if (query->acf->name)
438 free(query->acf->name);
439 if (query->acf->syntax)
440 free(query->acf->syntax);
441 if (query->acf->desc)
442 free(query->acf->desc);
450 static int odbc_load_module(void)
453 struct ast_config *cfg;
456 ast_mutex_lock(&query_lock);
458 cfg = ast_config_load(config);
460 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
464 for (catg = ast_category_browse(cfg, NULL);
466 catg = ast_category_browse(cfg, catg)) {
467 struct acf_odbc_query *query=NULL;
469 if (init_acf_query(cfg, catg, &query)) {
470 ast_log(LOG_ERROR, "Out of memory\n");
471 free_acf_query(query);
473 query->next = queries;
475 ast_custom_function_register(query->acf);
479 ast_config_destroy(cfg);
481 ast_mutex_unlock(&query_lock);
485 static int odbc_unload_module(void)
487 struct acf_odbc_query *query, *lastquery = NULL;
489 ast_mutex_lock(&query_lock);
490 for (query = queries; query; query = query->next) {
492 free_acf_query(lastquery);
493 if (ast_custom_function_unregister(query->acf)) {
494 ast_log(LOG_ERROR, "Cannot unregister function '%s'?\n", query->acf->name);
495 /* Keep state valid */
497 ast_mutex_unlock(&query_lock);
500 /* If anything is waiting on this lock, this will let it pass (avoids a race) */
501 ast_mutex_unlock(&query_lock);
502 ast_mutex_lock(&query_lock);
510 ast_mutex_unlock(&query_lock);
517 struct ast_config *cfg;
518 struct acf_odbc_query *q, *prevq = NULL, *qdel = NULL;
521 ast_mutex_lock(&query_lock);
523 for (q = queries; q; q = q->next) {
527 cfg = ast_config_load(config);
529 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
533 for (catg = ast_category_browse(cfg, NULL);
535 catg = ast_category_browse(cfg, catg)) {
536 struct acf_odbc_query *query = NULL;
538 /* We do this piecemeal, so that we stay in a consistent state, if there's ever an error */
539 for (q = queries, prevq=NULL; q; prevq=q, q = q->next) {
540 if (!strcasecmp(catg, q->name)) {
545 if (init_acf_query(cfg, catg, &query)) {
546 ast_log(LOG_ERROR, "Cannot initialize query ODBC_%s\n", catg);
547 free_acf_query(query);
551 if (ast_custom_function_unregister(q->acf)) {
552 ast_log(LOG_ERROR, "Cannot reload query %s\n", query->acf->name);
553 free_acf_query(query);
555 ast_custom_function_register(query->acf);
556 /* Add it to the list */
561 query->next = q->next;
562 /* Get rid of the old record */
567 query->next = queries;
569 ast_custom_function_register(query->acf);
574 /* Any remaining sets will now be destroyed */
575 for (q = queries; q; q = q->next) {
577 free_acf_query(qdel);
582 if (ast_custom_function_unregister(q->acf)) {
583 ast_log(LOG_ERROR, "Cannot unregister function? Refusing to make 'ODBC_%s' go away.\n", q->name);
585 /* If anything is waiting on the lock to execute, this will dispose of it (without a race) */
586 ast_mutex_unlock(&query_lock);
587 ast_mutex_lock(&query_lock);
590 prevq->next = q->next;
601 free_acf_query(qdel);
603 ast_config_destroy(cfg);
605 ast_mutex_unlock(&query_lock);
609 int unload_module(void)
611 return odbc_unload_module();
614 int load_module(void)
616 return odbc_load_module();
619 char *description(void)
626 if (! ast_mutex_trylock(&query_lock)) {
627 ast_mutex_unlock(&query_lock);
636 return ASTERISK_GPL_KEY;