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