Let's also include aclocal.m4
[asterisk-bristuff.git] / funcs / func_odbc.c
blobb0a13adefc8f7d68f89e48f30cab11c0b88967a0
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (c) 2005, 2006 Tilghman Lesher
6 * Tilghman Lesher <func_odbc__200508@the-tilghman.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
19 /*!
20 * \file
22 * \brief ODBC lookups
24 * \author Tilghman Lesher <func_odbc__200508@the-tilghman.com>
27 /*** MODULEINFO
28 <depend>unixodbc</depend>
29 <depend>ltdl</depend>
30 <depend>res_odbc</depend>
31 ***/
33 #include "asterisk.h"
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37 #include <sys/types.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <string.h>
43 #include "asterisk/module.h"
44 #include "asterisk/file.h"
45 #include "asterisk/logger.h"
46 #include "asterisk/options.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/pbx.h"
49 #include "asterisk/module.h"
50 #include "asterisk/config.h"
51 #include "asterisk/res_odbc.h"
52 #include "asterisk/app.h"
54 static char *config = "func_odbc.conf";
56 enum {
57 OPT_ESCAPECOMMAS = (1 << 0),
58 } odbc_option_flags;
60 struct acf_odbc_query {
61 AST_LIST_ENTRY(acf_odbc_query) list;
62 char dsn[30];
63 char sql_read[2048];
64 char sql_write[2048];
65 unsigned int flags;
66 struct ast_custom_function *acf;
69 AST_LIST_HEAD_STATIC(queries, acf_odbc_query);
71 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
73 int res;
74 char *sql = data;
75 SQLHSTMT stmt;
77 res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
78 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
79 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
80 return NULL;
83 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
84 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
85 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
86 SQLCloseCursor(stmt);
87 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
88 return NULL;
91 return stmt;
95 * Master control routine
97 static int acf_odbc_write(struct ast_channel *chan, char *cmd, char *s, const char *value)
99 struct odbc_obj *obj;
100 struct acf_odbc_query *query;
101 char *t, buf[2048]="", varname[15];
102 int i, bogus_chan = 0;
103 AST_DECLARE_APP_ARGS(values,
104 AST_APP_ARG(field)[100];
106 AST_DECLARE_APP_ARGS(args,
107 AST_APP_ARG(field)[100];
109 SQLHSTMT stmt;
110 SQLLEN rows=0;
112 AST_LIST_LOCK(&queries);
113 AST_LIST_TRAVERSE(&queries, query, list) {
114 if (!strcmp(query->acf->name, cmd)) {
115 break;
119 if (!query) {
120 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
121 AST_LIST_UNLOCK(&queries);
122 return -1;
125 obj = ast_odbc_request_obj(query->dsn, 0);
127 if (!obj) {
128 ast_log(LOG_ERROR, "No database handle available with the name of '%s' (check res_odbc.conf)\n", query->dsn);
129 AST_LIST_UNLOCK(&queries);
130 return -1;
133 if (!chan) {
134 if ((chan = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/func_odbc")))
135 bogus_chan = 1;
138 if (chan)
139 ast_autoservice_start(chan);
141 /* Parse our arguments */
142 t = value ? ast_strdupa(value) : "";
144 if (!s || !t) {
145 ast_log(LOG_ERROR, "Out of memory\n");
146 AST_LIST_UNLOCK(&queries);
147 if (chan)
148 ast_autoservice_stop(chan);
149 if (bogus_chan)
150 ast_channel_free(chan);
151 return -1;
154 AST_STANDARD_APP_ARGS(args, s);
155 for (i = 0; i < args.argc; i++) {
156 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
157 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
160 /* Parse values, just like arguments */
161 /* Can't use the pipe, because app Set removes them */
162 AST_NONSTANDARD_APP_ARGS(values, t, ',');
163 for (i = 0; i < values.argc; i++) {
164 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
165 pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
168 /* Additionally set the value as a whole (but push an empty string if value is NULL) */
169 pbx_builtin_pushvar_helper(chan, "VALUE", value ? value : "");
171 pbx_substitute_variables_helper(chan, query->sql_write, buf, sizeof(buf) - 1);
173 /* Restore prior values */
174 for (i = 0; i < args.argc; i++) {
175 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
176 pbx_builtin_setvar_helper(chan, varname, NULL);
179 for (i = 0; i < values.argc; i++) {
180 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
181 pbx_builtin_setvar_helper(chan, varname, NULL);
183 pbx_builtin_setvar_helper(chan, "VALUE", NULL);
185 AST_LIST_UNLOCK(&queries);
187 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, buf);
189 if (stmt) {
190 /* Rows affected */
191 SQLRowCount(stmt, &rows);
194 /* Output the affected rows, for all cases. In the event of failure, we
195 * flag this as -1 rows. Note that this is different from 0 affected rows
196 * which would be the case if we succeeded in our query, but the values did
197 * not change. */
198 snprintf(varname, sizeof(varname), "%d", (int)rows);
199 pbx_builtin_setvar_helper(chan, "ODBCROWS", varname);
201 if (stmt) {
202 SQLCloseCursor(stmt);
203 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
205 if (obj)
206 ast_odbc_release_obj(obj);
208 if (chan)
209 ast_autoservice_stop(chan);
210 if (bogus_chan)
211 ast_channel_free(chan);
213 return 0;
216 static int acf_odbc_read(struct ast_channel *chan, char *cmd, char *s, char *buf, size_t len)
218 struct odbc_obj *obj;
219 struct acf_odbc_query *query;
220 char sql[2048] = "", varname[15];
221 int res, x, buflen = 1, escapecommas, bogus_chan = 0;
222 AST_DECLARE_APP_ARGS(args,
223 AST_APP_ARG(field)[100];
225 SQLHSTMT stmt;
226 SQLSMALLINT colcount=0;
227 SQLLEN indicator;
229 AST_LIST_LOCK(&queries);
230 AST_LIST_TRAVERSE(&queries, query, list) {
231 if (!strcmp(query->acf->name, cmd)) {
232 break;
236 if (!query) {
237 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
238 AST_LIST_UNLOCK(&queries);
239 return -1;
242 obj = ast_odbc_request_obj(query->dsn, 0);
244 if (!obj) {
245 ast_log(LOG_ERROR, "No such DSN registered (or out of connections): %s (check res_odbc.conf)\n", query->dsn);
246 AST_LIST_UNLOCK(&queries);
247 return -1;
250 if (!chan) {
251 if ((chan = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/func_odbc")))
252 bogus_chan = 1;
255 if (chan)
256 ast_autoservice_start(chan);
258 AST_STANDARD_APP_ARGS(args, s);
259 for (x = 0; x < args.argc; x++) {
260 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
261 pbx_builtin_pushvar_helper(chan, varname, args.field[x]);
264 pbx_substitute_variables_helper(chan, query->sql_read, sql, sizeof(sql) - 1);
266 /* Restore prior values */
267 for (x = 0; x < args.argc; x++) {
268 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
269 pbx_builtin_setvar_helper(chan, varname, NULL);
272 /* Save this flag, so we can release the lock */
273 escapecommas = ast_test_flag(query, OPT_ESCAPECOMMAS);
275 AST_LIST_UNLOCK(&queries);
277 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, sql);
279 if (!stmt) {
280 ast_odbc_release_obj(obj);
281 if (chan)
282 ast_autoservice_stop(chan);
283 if (bogus_chan)
284 ast_channel_free(chan);
285 return -1;
288 res = SQLNumResultCols(stmt, &colcount);
289 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
290 ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
291 SQLCloseCursor(stmt);
292 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
293 ast_odbc_release_obj(obj);
294 if (chan)
295 ast_autoservice_stop(chan);
296 if (bogus_chan)
297 ast_channel_free(chan);
298 return -1;
301 *buf = '\0';
303 res = SQLFetch(stmt);
304 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
305 int res1 = -1;
306 if (res == SQL_NO_DATA) {
307 if (option_verbose > 3) {
308 ast_verbose(VERBOSE_PREFIX_4 "Found no rows [%s]\n", sql);
310 res1 = 0;
311 } else if (option_verbose > 3) {
312 ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, sql);
314 SQLCloseCursor(stmt);
315 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
316 ast_odbc_release_obj(obj);
317 if (chan)
318 ast_autoservice_stop(chan);
319 if (bogus_chan)
320 ast_channel_free(chan);
321 return res1;
324 for (x = 0; x < colcount; x++) {
325 int i;
326 char coldata[256];
328 buflen = strlen(buf);
329 res = SQLGetData(stmt, x + 1, SQL_CHAR, coldata, sizeof(coldata), &indicator);
330 if (indicator == SQL_NULL_DATA) {
331 coldata[0] = '\0';
332 res = SQL_SUCCESS;
335 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
336 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
337 SQLCloseCursor(stmt);
338 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
339 ast_odbc_release_obj(obj);
340 if (chan)
341 ast_autoservice_stop(chan);
342 if (bogus_chan)
343 ast_channel_free(chan);
344 return -1;
347 /* Copy data, encoding '\' and ',' for the argument parser */
348 for (i = 0; i < sizeof(coldata); i++) {
349 if (escapecommas && (coldata[i] == '\\' || coldata[i] == ',')) {
350 buf[buflen++] = '\\';
352 buf[buflen++] = coldata[i];
354 if (buflen >= len - 2)
355 break;
357 if (coldata[i] == '\0')
358 break;
361 buf[buflen - 1] = ',';
362 buf[buflen] = '\0';
364 /* Trim trailing comma */
365 buf[buflen - 1] = '\0';
367 SQLCloseCursor(stmt);
368 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
369 ast_odbc_release_obj(obj);
370 if (chan)
371 ast_autoservice_stop(chan);
372 if (bogus_chan)
373 ast_channel_free(chan);
374 return 0;
377 static int acf_escape(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
379 char *out = buf;
381 for (; *data && out - buf < len; data++) {
382 if (*data == '\'') {
383 *out = '\'';
384 out++;
386 *out++ = *data;
388 *out = '\0';
390 return 0;
393 static struct ast_custom_function escape_function = {
394 .name = "SQL_ESC",
395 .synopsis = "Escapes single ticks for use in SQL statements",
396 .syntax = "SQL_ESC(<string>)",
397 .desc =
398 "Used in SQL templates to escape data which may contain single ticks (') which\n"
399 "are otherwise used to delimit data. For example:\n"
400 "SELECT foo FROM bar WHERE baz='${SQL_ESC(${ARG1})}'\n",
401 .read = acf_escape,
402 .write = NULL,
405 static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
407 const char *tmp;
409 if (!cfg || !catg) {
410 return -1;
413 *query = ast_calloc(1, sizeof(struct acf_odbc_query));
414 if (! (*query))
415 return -1;
417 if ((tmp = ast_variable_retrieve(cfg, catg, "dsn"))) {
418 ast_copy_string((*query)->dsn, tmp, sizeof((*query)->dsn));
419 } else if ((tmp = ast_variable_retrieve(cfg, catg, "writehandle")) || (tmp = ast_variable_retrieve(cfg, catg, "readhandle"))) {
420 ast_log(LOG_WARNING, "Separate read and write handles are not supported in this version of func_odbc.so\n");
421 ast_copy_string((*query)->dsn, tmp, sizeof((*query)->dsn));
422 } else {
423 free(*query);
424 *query = NULL;
425 ast_log(LOG_ERROR, "No database handle was specified for func_odbc class '%s'\n", catg);
426 return -1;
429 if ((tmp = ast_variable_retrieve(cfg, catg, "read")) || (tmp = ast_variable_retrieve(cfg, catg, "readsql"))) {
430 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
433 if ((tmp = ast_variable_retrieve(cfg, catg, "write")) || (tmp = ast_variable_retrieve(cfg, catg, "writesql"))) {
434 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
437 /* Allow escaping of embedded commas in fields to be turned off */
438 ast_set_flag((*query), OPT_ESCAPECOMMAS);
439 if ((tmp = ast_variable_retrieve(cfg, catg, "escapecommas"))) {
440 if (ast_false(tmp))
441 ast_clear_flag((*query), OPT_ESCAPECOMMAS);
444 (*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
445 if (! (*query)->acf) {
446 free(*query);
447 *query = NULL;
448 return -1;
451 if ((tmp = ast_variable_retrieve(cfg, catg, "prefix")) && !ast_strlen_zero(tmp)) {
452 asprintf((char **)&((*query)->acf->name), "%s_%s", tmp, catg);
453 } else {
454 asprintf((char **)&((*query)->acf->name), "ODBC_%s", catg);
457 if (!((*query)->acf->name)) {
458 free((*query)->acf);
459 free(*query);
460 *query = NULL;
461 return -1;
464 asprintf((char **)&((*query)->acf->syntax), "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
466 if (!((*query)->acf->syntax)) {
467 free((char *)(*query)->acf->name);
468 free((*query)->acf);
469 free(*query);
470 *query = NULL;
471 return -1;
474 (*query)->acf->synopsis = "Runs the referenced query with the specified arguments";
475 if (!ast_strlen_zero((*query)->sql_read) && !ast_strlen_zero((*query)->sql_write)) {
476 asprintf((char **)&((*query)->acf->desc),
477 "Runs the following query, as defined in func_odbc.conf, performing\n"
478 "substitution of the arguments into the query as specified by ${ARG1},\n"
479 "${ARG2}, ... ${ARGn}. When setting the function, the values are provided\n"
480 "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
481 "\nRead:\n%s\n\nWrite:\n%s\n",
482 (*query)->sql_read,
483 (*query)->sql_write);
484 } else if (!ast_strlen_zero((*query)->sql_read)) {
485 asprintf((char **)&((*query)->acf->desc),
486 "Runs the following query, as defined in func_odbc.conf, performing\n"
487 "substitution of the arguments into the query as specified by ${ARG1},\n"
488 "${ARG2}, ... ${ARGn}. This function may only be read, not set.\n\nSQL:\n%s\n",
489 (*query)->sql_read);
490 } else if (!ast_strlen_zero((*query)->sql_write)) {
491 asprintf((char **)&((*query)->acf->desc),
492 "Runs the following query, as defined in func_odbc.conf, performing\n"
493 "substitution of the arguments into the query as specified by ${ARG1},\n"
494 "${ARG2}, ... ${ARGn}. The values are provided either in whole as\n"
495 "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
496 "This function may only be set.\nSQL:\n%s\n",
497 (*query)->sql_write);
498 } else {
499 ast_log(LOG_ERROR, "No SQL was found for func_odbc class '%s'\n", catg);
502 /* Could be out of memory, or could be we have neither sql_read nor sql_write */
503 if (! ((*query)->acf->desc)) {
504 free((char *)(*query)->acf->syntax);
505 free((char *)(*query)->acf->name);
506 free((*query)->acf);
507 free(*query);
508 *query = NULL;
509 return -1;
512 if (ast_strlen_zero((*query)->sql_read)) {
513 (*query)->acf->read = NULL;
514 } else {
515 (*query)->acf->read = acf_odbc_read;
518 if (ast_strlen_zero((*query)->sql_write)) {
519 (*query)->acf->write = NULL;
520 } else {
521 (*query)->acf->write = acf_odbc_write;
524 return 0;
527 static int free_acf_query(struct acf_odbc_query *query)
529 if (query) {
530 if (query->acf) {
531 if (query->acf->name)
532 free((char *)query->acf->name);
533 if (query->acf->syntax)
534 free((char *)query->acf->syntax);
535 if (query->acf->desc)
536 free((char *)query->acf->desc);
537 free(query->acf);
539 free(query);
541 return 0;
544 static int odbc_load_module(void)
546 int res = 0;
547 struct ast_config *cfg;
548 char *catg;
550 AST_LIST_LOCK(&queries);
552 cfg = ast_config_load(config);
553 if (!cfg) {
554 ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
555 AST_LIST_UNLOCK(&queries);
556 return AST_MODULE_LOAD_DECLINE;
559 for (catg = ast_category_browse(cfg, NULL);
560 catg;
561 catg = ast_category_browse(cfg, catg)) {
562 struct acf_odbc_query *query = NULL;
564 if (init_acf_query(cfg, catg, &query)) {
565 free_acf_query(query);
566 } else {
567 AST_LIST_INSERT_HEAD(&queries, query, list);
568 ast_custom_function_register(query->acf);
572 ast_config_destroy(cfg);
573 ast_custom_function_register(&escape_function);
575 AST_LIST_UNLOCK(&queries);
576 return res;
579 static int odbc_unload_module(void)
581 struct acf_odbc_query *query;
583 AST_LIST_LOCK(&queries);
584 while (!AST_LIST_EMPTY(&queries)) {
585 query = AST_LIST_REMOVE_HEAD(&queries, list);
586 ast_custom_function_unregister(query->acf);
587 free_acf_query(query);
590 ast_custom_function_unregister(&escape_function);
592 /* Allow any threads waiting for this lock to pass (avoids a race) */
593 AST_LIST_UNLOCK(&queries);
594 AST_LIST_LOCK(&queries);
596 AST_LIST_UNLOCK(&queries);
597 return 0;
600 static int reload(void)
602 int res = 0;
603 struct ast_config *cfg;
604 struct acf_odbc_query *oldquery;
605 char *catg;
607 AST_LIST_LOCK(&queries);
609 while (!AST_LIST_EMPTY(&queries)) {
610 oldquery = AST_LIST_REMOVE_HEAD(&queries, list);
611 ast_custom_function_unregister(oldquery->acf);
612 free_acf_query(oldquery);
615 cfg = ast_config_load(config);
616 if (!cfg) {
617 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
618 goto reload_out;
621 for (catg = ast_category_browse(cfg, NULL);
622 catg;
623 catg = ast_category_browse(cfg, catg)) {
624 struct acf_odbc_query *query = NULL;
626 if (init_acf_query(cfg, catg, &query)) {
627 ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
628 } else {
629 AST_LIST_INSERT_HEAD(&queries, query, list);
630 ast_custom_function_register(query->acf);
634 ast_config_destroy(cfg);
635 reload_out:
636 AST_LIST_UNLOCK(&queries);
637 return res;
640 static int unload_module(void)
642 return odbc_unload_module();
645 static int load_module(void)
647 return odbc_load_module();
650 /* XXX need to revise usecount - set if query_lock is set */
652 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
653 .load = load_module,
654 .unload = unload_module,
655 .reload = reload,