fix compilation warnings
[asterisk-bristuff.git] / funcs / func_odbc.c
blob8bc07076756dd15c82a0bf81989a1254cd78ee36
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 = 0, 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 {
420 free(*query);
421 *query = NULL;
422 return -1;
425 if ((tmp = ast_variable_retrieve(cfg, catg, "read"))) {
426 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
429 if ((tmp = ast_variable_retrieve(cfg, catg, "write"))) {
430 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
433 /* Allow escaping of embedded commas in fields to be turned off */
434 ast_set_flag((*query), OPT_ESCAPECOMMAS);
435 if ((tmp = ast_variable_retrieve(cfg, catg, "escapecommas"))) {
436 if (ast_false(tmp))
437 ast_clear_flag((*query), OPT_ESCAPECOMMAS);
440 (*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
441 if (! (*query)->acf) {
442 free(*query);
443 *query = NULL;
444 return -1;
447 if ((tmp = ast_variable_retrieve(cfg, catg, "prefix")) && !ast_strlen_zero(tmp)) {
448 asprintf((char **)&((*query)->acf->name), "%s_%s", tmp, catg);
449 } else {
450 asprintf((char **)&((*query)->acf->name), "ODBC_%s", catg);
453 if (!((*query)->acf->name)) {
454 free((*query)->acf);
455 free(*query);
456 *query = NULL;
457 return -1;
460 asprintf((char **)&((*query)->acf->syntax), "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
462 if (!((*query)->acf->syntax)) {
463 free((char *)(*query)->acf->name);
464 free((*query)->acf);
465 free(*query);
466 *query = NULL;
467 return -1;
470 (*query)->acf->synopsis = "Runs the referenced query with the specified arguments";
471 if (!ast_strlen_zero((*query)->sql_read) && !ast_strlen_zero((*query)->sql_write)) {
472 asprintf((char **)&((*query)->acf->desc),
473 "Runs the following query, as defined in func_odbc.conf, performing\n"
474 "substitution of the arguments into the query as specified by ${ARG1},\n"
475 "${ARG2}, ... ${ARGn}. When setting the function, the values are provided\n"
476 "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
477 "\nRead:\n%s\n\nWrite:\n%s\n",
478 (*query)->sql_read,
479 (*query)->sql_write);
480 } else if (!ast_strlen_zero((*query)->sql_read)) {
481 asprintf((char **)&((*query)->acf->desc),
482 "Runs the following query, as defined in func_odbc.conf, performing\n"
483 "substitution of the arguments into the query as specified by ${ARG1},\n"
484 "${ARG2}, ... ${ARGn}. This function may only be read, not set.\n\nSQL:\n%s\n",
485 (*query)->sql_read);
486 } else if (!ast_strlen_zero((*query)->sql_write)) {
487 asprintf((char **)&((*query)->acf->desc),
488 "Runs the following query, as defined in func_odbc.conf, performing\n"
489 "substitution of the arguments into the query as specified by ${ARG1},\n"
490 "${ARG2}, ... ${ARGn}. The values are provided either in whole as\n"
491 "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
492 "This function may only be set.\nSQL:\n%s\n",
493 (*query)->sql_write);
496 /* Could be out of memory, or could be we have neither sql_read nor sql_write */
497 if (! ((*query)->acf->desc)) {
498 free((char *)(*query)->acf->syntax);
499 free((char *)(*query)->acf->name);
500 free((*query)->acf);
501 free(*query);
502 *query = NULL;
503 return -1;
506 if (ast_strlen_zero((*query)->sql_read)) {
507 (*query)->acf->read = NULL;
508 } else {
509 (*query)->acf->read = acf_odbc_read;
512 if (ast_strlen_zero((*query)->sql_write)) {
513 (*query)->acf->write = NULL;
514 } else {
515 (*query)->acf->write = acf_odbc_write;
518 return 0;
521 static int free_acf_query(struct acf_odbc_query *query)
523 if (query) {
524 if (query->acf) {
525 if (query->acf->name)
526 free((char *)query->acf->name);
527 if (query->acf->syntax)
528 free((char *)query->acf->syntax);
529 if (query->acf->desc)
530 free((char *)query->acf->desc);
531 free(query->acf);
533 free(query);
535 return 0;
538 static int odbc_load_module(void)
540 int res = 0;
541 struct ast_config *cfg;
542 char *catg;
544 AST_LIST_LOCK(&queries);
546 cfg = ast_config_load(config);
547 if (!cfg) {
548 ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
549 AST_LIST_UNLOCK(&queries);
550 return AST_MODULE_LOAD_DECLINE;
553 for (catg = ast_category_browse(cfg, NULL);
554 catg;
555 catg = ast_category_browse(cfg, catg)) {
556 struct acf_odbc_query *query = NULL;
558 if (init_acf_query(cfg, catg, &query)) {
559 free_acf_query(query);
560 } else {
561 AST_LIST_INSERT_HEAD(&queries, query, list);
562 ast_custom_function_register(query->acf);
566 ast_config_destroy(cfg);
567 ast_custom_function_register(&escape_function);
569 AST_LIST_UNLOCK(&queries);
570 return res;
573 static int odbc_unload_module(void)
575 struct acf_odbc_query *query;
577 AST_LIST_LOCK(&queries);
578 while (!AST_LIST_EMPTY(&queries)) {
579 query = AST_LIST_REMOVE_HEAD(&queries, list);
580 ast_custom_function_unregister(query->acf);
581 free_acf_query(query);
584 ast_custom_function_unregister(&escape_function);
586 /* Allow any threads waiting for this lock to pass (avoids a race) */
587 AST_LIST_UNLOCK(&queries);
588 AST_LIST_LOCK(&queries);
590 AST_LIST_UNLOCK(&queries);
591 return 0;
594 static int reload(void)
596 int res = 0;
597 struct ast_config *cfg;
598 struct acf_odbc_query *oldquery;
599 char *catg;
601 AST_LIST_LOCK(&queries);
603 while (!AST_LIST_EMPTY(&queries)) {
604 oldquery = AST_LIST_REMOVE_HEAD(&queries, list);
605 ast_custom_function_unregister(oldquery->acf);
606 free_acf_query(oldquery);
609 cfg = ast_config_load(config);
610 if (!cfg) {
611 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
612 goto reload_out;
615 for (catg = ast_category_browse(cfg, NULL);
616 catg;
617 catg = ast_category_browse(cfg, catg)) {
618 struct acf_odbc_query *query = NULL;
620 if (init_acf_query(cfg, catg, &query)) {
621 ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
622 } else {
623 AST_LIST_INSERT_HEAD(&queries, query, list);
624 ast_custom_function_register(query->acf);
628 ast_config_destroy(cfg);
629 reload_out:
630 AST_LIST_UNLOCK(&queries);
631 return res;
634 static int unload_module(void)
636 return odbc_unload_module();
639 static int load_module(void)
641 return odbc_load_module();
644 /* XXX need to revise usecount - set if query_lock is set */
646 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
647 .load = load_module,
648 .unload = unload_module,
649 .reload = reload,