bfb2d37f5de8c9ba711d749125f40e300a09bddd
[asterisk/asterisk.git] / funcs / func_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (c) 2005, 2006 Tilghman Lesher
5  *
6  * Tilghman Lesher <func_odbc__200508@the-tilghman.com>
7  *
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.
13  *
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.
17  */
18
19 /*!
20  * \file
21  *
22  * \brief ODBC lookups
23  *
24  * \author Tilghman Lesher <func_odbc__200508@the-tilghman.com>
25  *
26  * \ingroup functions
27  */
28
29 /*** MODULEINFO
30         <depend>unixodbc</depend>
31         <depend>res_odbc</depend>
32  ***/
33
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include <sys/types.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <unistd.h>
42 #include <string.h>
43 #include <errno.h>
44
45 #include "asterisk/module.h"
46 #include "asterisk/file.h"
47 #include "asterisk/logger.h"
48 #include "asterisk/options.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/pbx.h"
51 #include "asterisk/module.h"
52 #include "asterisk/config.h"
53 #include "asterisk/res_odbc.h"
54 #include "asterisk/app.h"
55
56 static char *config = "func_odbc.conf";
57
58 enum {
59         OPT_ESCAPECOMMAS =      (1 << 0),
60         OPT_MULTIROW     =      (1 << 1),
61 } odbc_option_flags;
62
63 struct acf_odbc_query {
64         AST_LIST_ENTRY(acf_odbc_query) list;
65         char readhandle[5][30];
66         char writehandle[5][30];
67         char sql_read[2048];
68         char sql_write[2048];
69         unsigned int flags;
70         int rowlimit;
71         struct ast_custom_function *acf;
72 };
73
74 static void odbc_datastore_free(void *data);
75
76 struct ast_datastore_info odbc_info = {
77         .type = "FUNC_ODBC",
78         .destroy = odbc_datastore_free,
79 };
80
81 /* For storing each result row */
82 struct odbc_datastore_row {
83         AST_LIST_ENTRY(odbc_datastore_row) list;
84         char data[0];
85 };
86
87 /* For storing each result set */
88 struct odbc_datastore {
89         AST_LIST_HEAD(, odbc_datastore_row);
90         char names[0];
91 };
92
93 AST_LIST_HEAD_STATIC(queries, acf_odbc_query);
94
95 static int resultcount = 0;
96 AST_MUTEX_DEFINE_STATIC(resultlock);
97
98 static void odbc_datastore_free(void *data)
99 {
100         struct odbc_datastore *result = data;
101         struct odbc_datastore_row *row;
102         AST_LIST_LOCK(result);
103         while ((row = AST_LIST_REMOVE_HEAD(result, list))) {
104                 ast_free(row);
105         }
106         AST_LIST_UNLOCK(result);
107         AST_LIST_HEAD_DESTROY(result);
108         ast_free(result);
109 }
110
111 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
112 {
113         int res;
114         char *sql = data;
115         SQLHSTMT stmt;
116
117         res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
118         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
119                 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
120                 return NULL;
121         }
122
123         res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
124         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
125                 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
126                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
127                 return NULL;
128         }
129
130         return stmt;
131 }
132
133 /*
134  * Master control routine
135  */
136 static int acf_odbc_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
137 {
138         struct odbc_obj *obj = NULL;
139         struct acf_odbc_query *query;
140         char *t, buf[2048]="", varname[15];
141         int i, dsn;
142         AST_DECLARE_APP_ARGS(values,
143                 AST_APP_ARG(field)[100];
144         );
145         AST_DECLARE_APP_ARGS(args,
146                 AST_APP_ARG(field)[100];
147         );
148         SQLHSTMT stmt = NULL;
149         SQLLEN rows=0;
150
151         AST_LIST_LOCK(&queries);
152         AST_LIST_TRAVERSE(&queries, query, list) {
153                 if (!strcmp(query->acf->name, cmd)) {
154                         break;
155                 }
156         }
157
158         if (!query) {
159                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
160                 AST_LIST_UNLOCK(&queries);
161                 return -1;
162         }
163
164         /* Parse our arguments */
165         t = value ? ast_strdupa(value) : "";
166
167         if (!s || !t) {
168                 ast_log(LOG_ERROR, "Out of memory\n");
169                 AST_LIST_UNLOCK(&queries);
170                 return -1;
171         }
172
173         AST_STANDARD_APP_ARGS(args, s);
174         for (i = 0; i < args.argc; i++) {
175                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
176                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
177         }
178
179         /* Parse values, just like arguments */
180         /* Can't use the pipe, because app Set removes them */
181         AST_NONSTANDARD_APP_ARGS(values, t, ',');
182         for (i = 0; i < values.argc; i++) {
183                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
184                 pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
185         }
186
187         /* Additionally set the value as a whole (but push an empty string if value is NULL) */
188         pbx_builtin_pushvar_helper(chan, "VALUE", value ? value : "");
189
190         pbx_substitute_variables_helper(chan, query->sql_write, buf, sizeof(buf) - 1);
191
192         /* Restore prior values */
193         for (i = 0; i < args.argc; i++) {
194                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
195                 pbx_builtin_setvar_helper(chan, varname, NULL);
196         }
197
198         for (i = 0; i < values.argc; i++) {
199                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
200                 pbx_builtin_setvar_helper(chan, varname, NULL);
201         }
202         pbx_builtin_setvar_helper(chan, "VALUE", NULL);
203
204         AST_LIST_UNLOCK(&queries);
205
206         for (dsn = 0; dsn < 5; dsn++) {
207                 if (!ast_strlen_zero(query->writehandle[dsn])) {
208                         obj = ast_odbc_request_obj(query->writehandle[dsn], 0);
209                         if (obj)
210                                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, buf);
211                 }
212                 if (stmt)
213                         break;
214         }
215
216         if (stmt) {
217                 /* Rows affected */
218                 SQLRowCount(stmt, &rows);
219         }
220
221         /* Output the affected rows, for all cases.  In the event of failure, we
222          * flag this as -1 rows.  Note that this is different from 0 affected rows
223          * which would be the case if we succeeded in our query, but the values did
224          * not change. */
225         snprintf(varname, sizeof(varname), "%d", (int)rows);
226         pbx_builtin_setvar_helper(chan, "ODBCROWS", varname);
227
228         if (stmt)
229                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
230         if (obj)
231                 ast_odbc_release_obj(obj);
232
233         return 0;
234 }
235
236 static int acf_odbc_read(struct ast_channel *chan, const char *cmd, char *s, char *buf, size_t len)
237 {
238         struct odbc_obj *obj = NULL;
239         struct acf_odbc_query *query;
240         char sql[2048] = "", varname[15], colnames[2048] = "", rowcount[12] = "-1";
241         int res, x, y, buflen = 0, escapecommas, rowlimit = 1, dsn;
242         AST_DECLARE_APP_ARGS(args,
243                 AST_APP_ARG(field)[100];
244         );
245         SQLHSTMT stmt = NULL;
246         SQLSMALLINT colcount=0;
247         SQLLEN indicator;
248         SQLSMALLINT collength;
249         struct odbc_datastore *resultset = NULL;
250         struct odbc_datastore_row *row = NULL;
251
252         AST_LIST_LOCK(&queries);
253         AST_LIST_TRAVERSE(&queries, query, list) {
254                 if (!strcmp(query->acf->name, cmd)) {
255                         break;
256                 }
257         }
258
259         if (!query) {
260                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
261                 AST_LIST_UNLOCK(&queries);
262                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
263                 return -1;
264         }
265
266         AST_STANDARD_APP_ARGS(args, s);
267         for (x = 0; x < args.argc; x++) {
268                 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
269                 pbx_builtin_pushvar_helper(chan, varname, args.field[x]);
270         }
271
272         pbx_substitute_variables_helper(chan, query->sql_read, sql, sizeof(sql) - 1);
273
274         /* Restore prior values */
275         for (x = 0; x < args.argc; x++) {
276                 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
277                 pbx_builtin_setvar_helper(chan, varname, NULL);
278         }
279
280         /* Save these flags, so we can release the lock */
281         escapecommas = ast_test_flag(query, OPT_ESCAPECOMMAS);
282         if (ast_test_flag(query, OPT_MULTIROW)) {
283                 resultset = ast_calloc(1, sizeof(*resultset));
284                 AST_LIST_HEAD_INIT(resultset);
285                 if (query->rowlimit)
286                         rowlimit = query->rowlimit;
287                 else
288                         rowlimit = INT_MAX;
289         }
290         AST_LIST_UNLOCK(&queries);
291
292         for (dsn = 0; dsn < 5; dsn++) {
293                 if (!ast_strlen_zero(query->writehandle[dsn])) {
294                         obj = ast_odbc_request_obj(query->writehandle[dsn], 0);
295                         if (obj)
296                                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, sql);
297                 }
298                 if (stmt)
299                         break;
300         }
301
302         if (!stmt) {
303                 ast_log(LOG_ERROR, "Unable to execute query [%s]\n", sql);
304                 if (obj)
305                         ast_odbc_release_obj(obj);
306                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
307                 return -1;
308         }
309
310         res = SQLNumResultCols(stmt, &colcount);
311         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
312                 ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
313                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
314                 ast_odbc_release_obj(obj);
315                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
316                 return -1;
317         }
318
319         res = SQLFetch(stmt);
320         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
321                 int res1 = -1;
322                 if (res == SQL_NO_DATA) {
323                         if (option_verbose > 3)
324                                 ast_verbose(VERBOSE_PREFIX_4 "Found no rows [%s]\n", sql);
325                         res1 = 0;
326                         ast_copy_string(rowcount, "0", sizeof(rowcount));
327                 } else {
328                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, sql);
329                 }
330                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
331                 ast_odbc_release_obj(obj);
332                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
333                 return res1;
334         }
335
336         for (y = 0; y < rowlimit; y++) {
337                 *buf = '\0';
338                 for (x = 0; x < colcount; x++) {
339                         int i;
340                         char coldata[256];
341
342                         if (y == 0) {
343                                 char colname[256];
344                                 int namelen;
345
346                                 res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, NULL, NULL, NULL);
347                                 if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
348                                         snprintf(colname, sizeof(colname), "field%d", x);
349                                 }
350
351                                 if (!ast_strlen_zero(colnames))
352                                         strncat(colnames, ",", sizeof(colnames) - 1);
353                                 namelen = strlen(colnames);
354
355                                 /* Copy data, encoding '\' and ',' for the argument parser */
356                                 for (i = 0; i < sizeof(colname); i++) {
357                                         if (escapecommas && (colname[i] == '\\' || colname[i] == ',')) {
358                                                 colnames[namelen++] = '\\';
359                                         }
360                                         colnames[namelen++] = colname[i];
361
362                                         if (namelen >= sizeof(colnames) - 2) {
363                                                 colnames[namelen >= sizeof(colnames) ? sizeof(colnames) - 1 : namelen] = '\0';
364                                                 break;
365                                         }
366
367                                         if (colname[i] == '\0')
368                                                 break;
369                                 }
370
371                                 if (resultset) {
372                                         void *tmp = ast_realloc(resultset, sizeof(*resultset) + strlen(colnames) + 1);
373                                         if (!tmp) {
374                                                 ast_log(LOG_ERROR, "No space for a new resultset?\n");
375                                                 ast_free(resultset);
376                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
377                                                 ast_odbc_release_obj(obj);
378                                                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
379                                                 return -1;
380                                         }
381                                         resultset = tmp;
382                                         strcpy((char *)resultset + sizeof(*resultset), colnames);
383                                 }
384                         }
385
386                         buflen = strlen(buf);
387                         res = SQLGetData(stmt, x + 1, SQL_CHAR, coldata, sizeof(coldata), &indicator);
388                         if (indicator == SQL_NULL_DATA) {
389                                 coldata[0] = '\0';
390                                 res = SQL_SUCCESS;
391                         }
392
393                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
394                                 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
395                                 y = -1;
396                                 goto end_acf_read;
397                         }
398
399                         /* Copy data, encoding '\' and ',' for the argument parser */
400                         for (i = 0; i < sizeof(coldata); i++) {
401                                 if (escapecommas && (coldata[i] == '\\' || coldata[i] == ',')) {
402                                         buf[buflen++] = '\\';
403                                 }
404                                 buf[buflen++] = coldata[i];
405
406                                 if (buflen >= len - 2)
407                                         break;
408
409                                 if (coldata[i] == '\0')
410                                         break;
411                         }
412
413                         buf[buflen - 1] = ',';
414                         buf[buflen] = '\0';
415                 }
416                 /* Trim trailing comma */
417                 buf[buflen - 1] = '\0';
418
419                 if (resultset) {
420                         row = ast_calloc(1, sizeof(*row) + buflen);
421                         if (!row) {
422                                 ast_log(LOG_ERROR, "Unable to allocate space for more rows in this resultset.\n");
423                                 goto end_acf_read;
424                         }
425                         strcpy((char *)row + sizeof(*row), buf);
426                         AST_LIST_INSERT_TAIL(resultset, row, list);
427
428                         /* Get next row */
429                         res = SQLFetch(stmt);
430                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
431                                 if (res != SQL_NO_DATA)
432                                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, sql);
433                                 y++;
434                                 break;
435                         }
436                 }
437         }
438
439 end_acf_read:
440         snprintf(rowcount, sizeof(rowcount), "%d", y);
441         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
442         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", colnames);
443         if (resultset) {
444                 int uid;
445                 struct ast_datastore *odbc_store;
446                 ast_mutex_lock(&resultlock);
447                 uid = ++resultcount;
448                 ast_mutex_unlock(&resultlock);
449                 snprintf(buf, len, "%d", uid);
450                 odbc_store = ast_channel_datastore_alloc(&odbc_info, buf);
451                 if (!odbc_store) {
452                         ast_log(LOG_ERROR, "Rows retrieved, but unable to store it in the channel.  Results fail.\n");
453                         odbc_datastore_free(resultset);
454                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
455                         ast_odbc_release_obj(obj);
456                         return -1;
457                 }
458                 odbc_store->data = resultset;
459                 ast_channel_datastore_add(chan, odbc_store);
460         }
461         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
462         ast_odbc_release_obj(obj);
463         return 0;
464 }
465
466 static int acf_escape(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
467 {
468         char *out = buf;
469
470         for (; *data && out - buf < len; data++) {
471                 if (*data == '\'') {
472                         *out = '\'';
473                         out++;
474                 }
475                 *out++ = *data;
476         }
477         *out = '\0';
478
479         return 0;
480 }
481
482 static struct ast_custom_function escape_function = {
483         .name = "SQL_ESC",
484         .synopsis = "Escapes single ticks for use in SQL statements",
485         .syntax = "SQL_ESC(<string>)",
486         .desc =
487 "Used in SQL templates to escape data which may contain single ticks (') which\n"
488 "are otherwise used to delimit data.  For example:\n"
489 "SELECT foo FROM bar WHERE baz='${SQL_ESC(${ARG1})}'\n",
490         .read = acf_escape,
491         .write = NULL,
492 };
493
494 static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
495 {
496         struct ast_datastore *store;
497         struct odbc_datastore *resultset;
498         struct odbc_datastore_row *row;
499         store = ast_channel_datastore_find(chan, &odbc_info, data);
500         if (!store) {
501                 return -1;
502         }
503         resultset = store->data;
504         AST_LIST_LOCK(resultset);
505         row = AST_LIST_REMOVE_HEAD(resultset, list);
506         AST_LIST_UNLOCK(resultset);
507         if (!row) {
508                 /* Cleanup datastore */
509                 ast_channel_datastore_remove(chan, store);
510                 ast_channel_datastore_free(store);
511                 return -1;
512         }
513         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", resultset->names);
514         ast_copy_string(buf, row->data, len);
515         ast_free(row);
516         return 0;
517 }
518
519 static struct ast_custom_function fetch_function = {
520         .name = "ODBC_FETCH",
521         .synopsis = "Fetch a row from a multirow query",
522         .syntax = "ODBC_FETCH(<result-id>)",
523         .desc =
524 "For queries which are marked as mode=multirow, the original query returns a\n"
525 "result-id from which results may be fetched.  This function implements the\n"
526 "actual fetch of the results.\n",
527         .read = acf_fetch,
528         .write = NULL,
529 };
530
531 static char *app_odbcfinish = "ODBCFinish";
532 static char *syn_odbcfinish = "Clear the resultset of a successful multirow query";
533 static char *desc_odbcfinish =
534 "ODBCFinish(<result-id>)\n"
535 "  Clears any remaining rows of the specified resultset\n";
536
537
538 static int exec_odbcfinish(struct ast_channel *chan, void *data)
539 {
540         struct ast_datastore *store = ast_channel_datastore_find(chan, &odbc_info, data);
541         if (!store) /* Already freed; no big deal. */
542                 return 0;
543         ast_channel_datastore_remove(chan, store);
544         ast_channel_datastore_free(store);
545         return 0;
546 }
547
548 static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
549 {
550         const char *tmp;
551         int i;
552
553         if (!cfg || !catg) {
554                 return EINVAL;
555         }
556
557         *query = ast_calloc(1, sizeof(struct acf_odbc_query));
558         if (! (*query))
559                 return ENOMEM;
560
561         if (((tmp = ast_variable_retrieve(cfg, catg, "writehandle"))) || ((tmp = ast_variable_retrieve(cfg, catg, "dsn")))) {
562                 char *tmp2 = ast_strdupa(tmp);
563                 AST_DECLARE_APP_ARGS(write,
564                         AST_APP_ARG(dsn)[5];
565                 );
566                 AST_NONSTANDARD_APP_ARGS(write, tmp2, ',');
567                 for (i = 0; i < 5; i++) {
568                         if (!ast_strlen_zero(write.dsn[i]))
569                                 ast_copy_string((*query)->writehandle[i], write.dsn[i], sizeof((*query)->writehandle[i]));
570                 }
571         }
572
573         if ((tmp = ast_variable_retrieve(cfg, catg, "readhandle"))) {
574                 char *tmp2 = ast_strdupa(tmp);
575                 AST_DECLARE_APP_ARGS(read,
576                         AST_APP_ARG(dsn)[5];
577                 );
578                 AST_NONSTANDARD_APP_ARGS(read, tmp2, ',');
579                 for (i = 0; i < 5; i++) {
580                         if (!ast_strlen_zero(read.dsn[i]))
581                                 ast_copy_string((*query)->readhandle[i], read.dsn[i], sizeof((*query)->readhandle[i]));
582                 }
583         } else {
584                 /* If no separate readhandle, then use the writehandle for reading */
585                 for (i = 0; i < 5; i++) {
586                         if (!ast_strlen_zero((*query)->writehandle[i]))
587                                 ast_copy_string((*query)->readhandle[i], (*query)->writehandle[i], sizeof((*query)->readhandle[i]));
588                 }
589         }
590
591         if ((tmp = ast_variable_retrieve(cfg, catg, "read"))) {
592                 ast_log(LOG_WARNING, "Parameter 'read' is deprecated for category %s.  Please use 'readsql' instead.\n", catg);
593                 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
594         } else if ((tmp = ast_variable_retrieve(cfg, catg, "readsql")))
595                 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
596
597         if (!ast_strlen_zero((*query)->sql_read) && ast_strlen_zero((*query)->readhandle[0])) {
598                 free(*query);
599                 *query = NULL;
600                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for reading: %s\n", catg);
601                 return EINVAL;
602         }
603
604         if ((tmp = ast_variable_retrieve(cfg, catg, "write"))) {
605                 ast_log(LOG_WARNING, "Parameter 'write' is deprecated for category %s.  Please use 'writesql' instead.\n", catg);
606                 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
607         } else if ((tmp = ast_variable_retrieve(cfg, catg, "writesql")))
608                 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
609
610         if (!ast_strlen_zero((*query)->sql_write) && ast_strlen_zero((*query)->writehandle[0])) {
611                 free(*query);
612                 *query = NULL;
613                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for writing: %s\n", catg);
614                 return EINVAL;
615         }
616
617         /* Allow escaping of embedded commas in fields to be turned off */
618         ast_set_flag((*query), OPT_ESCAPECOMMAS);
619         if ((tmp = ast_variable_retrieve(cfg, catg, "escapecommas"))) {
620                 if (ast_false(tmp))
621                         ast_clear_flag((*query), OPT_ESCAPECOMMAS);
622         }
623
624         if ((tmp = ast_variable_retrieve(cfg, catg, "mode"))) {
625                 if (strcasecmp(tmp, "multirow") == 0)
626                         ast_set_flag((*query), OPT_MULTIROW);
627                 if ((tmp = ast_variable_retrieve(cfg, catg, "rowlimit")))
628                         sscanf(tmp, "%d", &((*query)->rowlimit));
629         }
630
631         (*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
632         if (! (*query)->acf) {
633                 free(*query);
634                 *query = NULL;
635                 return ENOMEM;
636         }
637
638         if ((tmp = ast_variable_retrieve(cfg, catg, "prefix")) && !ast_strlen_zero(tmp)) {
639                 asprintf((char **)&((*query)->acf->name), "%s_%s", tmp, catg);
640         } else {
641                 asprintf((char **)&((*query)->acf->name), "ODBC_%s", catg);
642         }
643
644         if (!((*query)->acf->name)) {
645                 free((*query)->acf);
646                 free(*query);
647                 *query = NULL;
648                 return ENOMEM;
649         }
650
651         asprintf((char **)&((*query)->acf->syntax), "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
652
653         if (!((*query)->acf->syntax)) {
654                 free((char *)(*query)->acf->name);
655                 free((*query)->acf);
656                 free(*query);
657                 *query = NULL;
658                 return ENOMEM;
659         }
660
661         (*query)->acf->synopsis = "Runs the referenced query with the specified arguments";
662         if (!ast_strlen_zero((*query)->sql_read) && !ast_strlen_zero((*query)->sql_write)) {
663                 asprintf((char **)&((*query)->acf->desc),
664                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
665                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
666                                         "${ARG2}, ... ${ARGn}.  When setting the function, the values are provided\n"
667                                         "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
668                                         "\nRead:\n%s\n\nWrite:\n%s\n",
669                                         (*query)->sql_read,
670                                         (*query)->sql_write);
671         } else if (!ast_strlen_zero((*query)->sql_read)) {
672                 asprintf((char **)&((*query)->acf->desc),
673                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
674                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
675                                         "${ARG2}, ... ${ARGn}.  This function may only be read, not set.\n\nSQL:\n%s\n",
676                                         (*query)->sql_read);
677         } else if (!ast_strlen_zero((*query)->sql_write)) {
678                 asprintf((char **)&((*query)->acf->desc),
679                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
680                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
681                                         "${ARG2}, ... ${ARGn}.  The values are provided either in whole as\n"
682                                         "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
683                                         "This function may only be set.\nSQL:\n%s\n",
684                                         (*query)->sql_write);
685         } else {
686                 free((char *)(*query)->acf->syntax);
687                 free((char *)(*query)->acf->name);
688                 free((*query)->acf);
689                 free(*query);
690                 ast_log(LOG_WARNING, "Section %s was found, but there was no SQL to execute.  Ignoring.\n", catg);
691                 return EINVAL;
692         }
693
694         if (! ((*query)->acf->desc)) {
695                 free((char *)(*query)->acf->syntax);
696                 free((char *)(*query)->acf->name);
697                 free((*query)->acf);
698                 free(*query);
699                 *query = NULL;
700                 return ENOMEM;
701         }
702
703         if (ast_strlen_zero((*query)->sql_read)) {
704                 (*query)->acf->read = NULL;
705         } else {
706                 (*query)->acf->read = acf_odbc_read;
707         }
708
709         if (ast_strlen_zero((*query)->sql_write)) {
710                 (*query)->acf->write = NULL;
711         } else {
712                 (*query)->acf->write = acf_odbc_write;
713         }
714
715         return 0;
716 }
717
718 static int free_acf_query(struct acf_odbc_query *query)
719 {
720         if (query) {
721                 if (query->acf) {
722                         if (query->acf->name)
723                                 free((char *)query->acf->name);
724                         if (query->acf->syntax)
725                                 free((char *)query->acf->syntax);
726                         if (query->acf->desc)
727                                 free((char *)query->acf->desc);
728                         free(query->acf);
729                 }
730                 free(query);
731         }
732         return 0;
733 }
734
735 static int load_module(void)
736 {
737         int res = 0;
738         struct ast_config *cfg;
739         char *catg;
740
741         res |= ast_custom_function_register(&fetch_function);
742         res |= ast_register_application(app_odbcfinish, exec_odbcfinish, syn_odbcfinish, desc_odbcfinish);
743         AST_LIST_LOCK(&queries);
744
745         cfg = ast_config_load(config);
746         if (!cfg) {
747                 ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
748                 AST_LIST_UNLOCK(&queries);
749                 return AST_MODULE_LOAD_DECLINE;
750         }
751
752         for (catg = ast_category_browse(cfg, NULL);
753              catg;
754              catg = ast_category_browse(cfg, catg)) {
755                 struct acf_odbc_query *query = NULL;
756                 int err;
757
758                 if ((err = init_acf_query(cfg, catg, &query))) {
759                         if (err == ENOMEM)
760                                 ast_log(LOG_ERROR, "Out of memory\n");
761                         else if (err == EINVAL)
762                                 ast_log(LOG_ERROR, "Invalid parameters for category %s\n", catg);
763                         else
764                                 ast_log(LOG_ERROR, "%s (%d)\n", strerror(err), err);
765                 } else {
766                         AST_LIST_INSERT_HEAD(&queries, query, list);
767                         ast_custom_function_register(query->acf);
768                 }
769         }
770
771         ast_config_destroy(cfg);
772         res |= ast_custom_function_register(&escape_function);
773
774         AST_LIST_UNLOCK(&queries);
775         return res;
776 }
777
778 static int unload_module(void)
779 {
780         struct acf_odbc_query *query;
781         int res = 0;
782
783         AST_LIST_LOCK(&queries);
784         while (!AST_LIST_EMPTY(&queries)) {
785                 query = AST_LIST_REMOVE_HEAD(&queries, list);
786                 ast_custom_function_unregister(query->acf);
787                 free_acf_query(query);
788         }
789
790         res |= ast_custom_function_unregister(&escape_function);
791         res |= ast_custom_function_unregister(&fetch_function);
792         res |= ast_unregister_application(app_odbcfinish);
793
794         /* Allow any threads waiting for this lock to pass (avoids a race) */
795         AST_LIST_UNLOCK(&queries);
796         usleep(1);
797         AST_LIST_LOCK(&queries);
798
799         AST_LIST_UNLOCK(&queries);
800         return 0;
801 }
802
803 static int reload(void)
804 {
805         int res = 0;
806         struct ast_config *cfg;
807         struct acf_odbc_query *oldquery;
808         char *catg;
809
810         AST_LIST_LOCK(&queries);
811
812         while (!AST_LIST_EMPTY(&queries)) {
813                 oldquery = AST_LIST_REMOVE_HEAD(&queries, list);
814                 ast_custom_function_unregister(oldquery->acf);
815                 free_acf_query(oldquery);
816         }
817
818         cfg = ast_config_load(config);
819         if (!cfg) {
820                 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
821                 goto reload_out;
822         }
823
824         for (catg = ast_category_browse(cfg, NULL);
825              catg;
826              catg = ast_category_browse(cfg, catg)) {
827                 struct acf_odbc_query *query = NULL;
828
829                 if (init_acf_query(cfg, catg, &query)) {
830                         ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
831                 } else {
832                         AST_LIST_INSERT_HEAD(&queries, query, list);
833                         ast_custom_function_register(query->acf);
834                 }
835         }
836
837         ast_config_destroy(cfg);
838 reload_out:
839         AST_LIST_UNLOCK(&queries);
840         return res;
841 }
842
843 /* XXX need to revise usecount - set if query_lock is set */
844
845 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
846                 .load = load_module,
847                 .unload = unload_module,
848                 .reload = reload,
849                );
850