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