Merged revisions 80044 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         AST_STANDARD_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                         ast_verb(4, "Found no rows [%s]\n", sql);
328                         res1 = 0;
329                         ast_copy_string(rowcount, "0", sizeof(rowcount));
330                 } else {
331                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, sql);
332                 }
333                 SQLCloseCursor(stmt);
334                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
335                 ast_odbc_release_obj(obj);
336                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
337                 return res1;
338         }
339
340         for (y = 0; y < rowlimit; y++) {
341                 *buf = '\0';
342                 for (x = 0; x < colcount; x++) {
343                         int i;
344                         char coldata[256];
345
346                         if (y == 0) {
347                                 char colname[256];
348                                 int namelen;
349
350                                 res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, NULL, NULL, NULL);
351                                 if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
352                                         snprintf(colname, sizeof(colname), "field%d", x);
353                                 }
354
355                                 if (!ast_strlen_zero(colnames))
356                                         strncat(colnames, ",", sizeof(colnames) - 1);
357                                 namelen = strlen(colnames);
358
359                                 /* Copy data, encoding '\' and ',' for the argument parser */
360                                 for (i = 0; i < sizeof(colname); i++) {
361                                         if (escapecommas && (colname[i] == '\\' || colname[i] == ',')) {
362                                                 colnames[namelen++] = '\\';
363                                         }
364                                         colnames[namelen++] = colname[i];
365
366                                         if (namelen >= sizeof(colnames) - 2) {
367                                                 colnames[namelen >= sizeof(colnames) ? sizeof(colnames) - 1 : namelen] = '\0';
368                                                 break;
369                                         }
370
371                                         if (colname[i] == '\0')
372                                                 break;
373                                 }
374
375                                 if (resultset) {
376                                         void *tmp = ast_realloc(resultset, sizeof(*resultset) + strlen(colnames) + 1);
377                                         if (!tmp) {
378                                                 ast_log(LOG_ERROR, "No space for a new resultset?\n");
379                                                 ast_free(resultset);
380                                                 SQLCloseCursor(stmt);
381                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
382                                                 ast_odbc_release_obj(obj);
383                                                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
384                                                 return -1;
385                                         }
386                                         resultset = tmp;
387                                         strcpy((char *)resultset + sizeof(*resultset), colnames);
388                                 }
389                         }
390
391                         buflen = strlen(buf);
392                         res = SQLGetData(stmt, x + 1, SQL_CHAR, coldata, sizeof(coldata), &indicator);
393                         if (indicator == SQL_NULL_DATA) {
394                                 coldata[0] = '\0';
395                                 res = SQL_SUCCESS;
396                         }
397
398                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
399                                 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
400                                 y = -1;
401                                 goto end_acf_read;
402                         }
403
404                         /* Copy data, encoding '\' and ',' for the argument parser */
405                         for (i = 0; i < sizeof(coldata); i++) {
406                                 if (escapecommas && (coldata[i] == '\\' || coldata[i] == ',')) {
407                                         buf[buflen++] = '\\';
408                                 }
409                                 buf[buflen++] = coldata[i];
410
411                                 if (buflen >= len - 2)
412                                         break;
413
414                                 if (coldata[i] == '\0')
415                                         break;
416                         }
417
418                         buf[buflen - 1] = ',';
419                         buf[buflen] = '\0';
420                 }
421                 /* Trim trailing comma */
422                 buf[buflen - 1] = '\0';
423
424                 if (resultset) {
425                         row = ast_calloc(1, sizeof(*row) + buflen);
426                         if (!row) {
427                                 ast_log(LOG_ERROR, "Unable to allocate space for more rows in this resultset.\n");
428                                 goto end_acf_read;
429                         }
430                         strcpy((char *)row + sizeof(*row), buf);
431                         AST_LIST_INSERT_TAIL(resultset, row, list);
432
433                         /* Get next row */
434                         res = SQLFetch(stmt);
435                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
436                                 if (res != SQL_NO_DATA)
437                                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, sql);
438                                 y++;
439                                 break;
440                         }
441                 }
442         }
443
444 end_acf_read:
445         snprintf(rowcount, sizeof(rowcount), "%d", y);
446         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
447         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", colnames);
448         if (resultset) {
449                 int uid;
450                 struct ast_datastore *odbc_store;
451                 ast_mutex_lock(&resultlock);
452                 uid = ++resultcount;
453                 ast_mutex_unlock(&resultlock);
454                 snprintf(buf, len, "%d", uid);
455                 odbc_store = ast_channel_datastore_alloc(&odbc_info, buf);
456                 if (!odbc_store) {
457                         ast_log(LOG_ERROR, "Rows retrieved, but unable to store it in the channel.  Results fail.\n");
458                         odbc_datastore_free(resultset);
459                         SQLCloseCursor(stmt);
460                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
461                         ast_odbc_release_obj(obj);
462                         return -1;
463                 }
464                 odbc_store->data = resultset;
465                 ast_channel_datastore_add(chan, odbc_store);
466         }
467         SQLCloseCursor(stmt);
468         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
469         ast_odbc_release_obj(obj);
470         return 0;
471 }
472
473 static int acf_escape(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
474 {
475         char *out = buf;
476
477         for (; *data && out - buf < len; data++) {
478                 if (*data == '\'') {
479                         *out = '\'';
480                         out++;
481                 }
482                 *out++ = *data;
483         }
484         *out = '\0';
485
486         return 0;
487 }
488
489 static struct ast_custom_function escape_function = {
490         .name = "SQL_ESC",
491         .synopsis = "Escapes single ticks for use in SQL statements",
492         .syntax = "SQL_ESC(<string>)",
493         .desc =
494 "Used in SQL templates to escape data which may contain single ticks (') which\n"
495 "are otherwise used to delimit data.  For example:\n"
496 "SELECT foo FROM bar WHERE baz='${SQL_ESC(${ARG1})}'\n",
497         .read = acf_escape,
498         .write = NULL,
499 };
500
501 static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
502 {
503         struct ast_datastore *store;
504         struct odbc_datastore *resultset;
505         struct odbc_datastore_row *row;
506         store = ast_channel_datastore_find(chan, &odbc_info, data);
507         if (!store) {
508                 return -1;
509         }
510         resultset = store->data;
511         AST_LIST_LOCK(resultset);
512         row = AST_LIST_REMOVE_HEAD(resultset, list);
513         AST_LIST_UNLOCK(resultset);
514         if (!row) {
515                 /* Cleanup datastore */
516                 ast_channel_datastore_remove(chan, store);
517                 ast_channel_datastore_free(store);
518                 return -1;
519         }
520         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", resultset->names);
521         ast_copy_string(buf, row->data, len);
522         ast_free(row);
523         return 0;
524 }
525
526 static struct ast_custom_function fetch_function = {
527         .name = "ODBC_FETCH",
528         .synopsis = "Fetch a row from a multirow query",
529         .syntax = "ODBC_FETCH(<result-id>)",
530         .desc =
531 "For queries which are marked as mode=multirow, the original query returns a\n"
532 "result-id from which results may be fetched.  This function implements the\n"
533 "actual fetch of the results.\n",
534         .read = acf_fetch,
535         .write = NULL,
536 };
537
538 static char *app_odbcfinish = "ODBCFinish";
539 static char *syn_odbcfinish = "Clear the resultset of a successful multirow query";
540 static char *desc_odbcfinish =
541 "ODBCFinish(<result-id>)\n"
542 "  Clears any remaining rows of the specified resultset\n";
543
544
545 static int exec_odbcfinish(struct ast_channel *chan, void *data)
546 {
547         struct ast_datastore *store = ast_channel_datastore_find(chan, &odbc_info, data);
548         if (!store) /* Already freed; no big deal. */
549                 return 0;
550         ast_channel_datastore_remove(chan, store);
551         ast_channel_datastore_free(store);
552         return 0;
553 }
554
555 static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
556 {
557         const char *tmp;
558         int i;
559
560         if (!cfg || !catg) {
561                 return EINVAL;
562         }
563
564         *query = ast_calloc(1, sizeof(struct acf_odbc_query));
565         if (! (*query))
566                 return ENOMEM;
567
568         if (((tmp = ast_variable_retrieve(cfg, catg, "writehandle"))) || ((tmp = ast_variable_retrieve(cfg, catg, "dsn")))) {
569                 char *tmp2 = ast_strdupa(tmp);
570                 AST_DECLARE_APP_ARGS(write,
571                         AST_APP_ARG(dsn)[5];
572                 );
573                 AST_NONSTANDARD_APP_ARGS(write, tmp2, ',');
574                 for (i = 0; i < 5; i++) {
575                         if (!ast_strlen_zero(write.dsn[i]))
576                                 ast_copy_string((*query)->writehandle[i], write.dsn[i], sizeof((*query)->writehandle[i]));
577                 }
578         }
579
580         if ((tmp = ast_variable_retrieve(cfg, catg, "readhandle"))) {
581                 char *tmp2 = ast_strdupa(tmp);
582                 AST_DECLARE_APP_ARGS(read,
583                         AST_APP_ARG(dsn)[5];
584                 );
585                 AST_NONSTANDARD_APP_ARGS(read, tmp2, ',');
586                 for (i = 0; i < 5; i++) {
587                         if (!ast_strlen_zero(read.dsn[i]))
588                                 ast_copy_string((*query)->readhandle[i], read.dsn[i], sizeof((*query)->readhandle[i]));
589                 }
590         } else {
591                 /* If no separate readhandle, then use the writehandle for reading */
592                 for (i = 0; i < 5; i++) {
593                         if (!ast_strlen_zero((*query)->writehandle[i]))
594                                 ast_copy_string((*query)->readhandle[i], (*query)->writehandle[i], sizeof((*query)->readhandle[i]));
595                 }
596         }
597
598         if ((tmp = ast_variable_retrieve(cfg, catg, "readsql")))
599                 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
600         else 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         }
604
605         if (!ast_strlen_zero((*query)->sql_read) && ast_strlen_zero((*query)->readhandle[0])) {
606                 ast_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, "writesql")))
613                 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
614         else if ((tmp = ast_variable_retrieve(cfg, catg, "write"))) {
615                 ast_log(LOG_WARNING, "Parameter 'write' is deprecated for category %s.  Please use 'writesql' instead.\n", catg);
616                 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
617         }
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         struct ast_flags config_flags = { 0 };
750
751         res |= ast_custom_function_register(&fetch_function);
752         res |= ast_register_application(app_odbcfinish, exec_odbcfinish, syn_odbcfinish, desc_odbcfinish);
753         AST_LIST_LOCK(&queries);
754
755         cfg = ast_config_load(config, config_flags);
756         if (!cfg) {
757                 ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
758                 AST_LIST_UNLOCK(&queries);
759                 return AST_MODULE_LOAD_DECLINE;
760         }
761
762         for (catg = ast_category_browse(cfg, NULL);
763              catg;
764              catg = ast_category_browse(cfg, catg)) {
765                 struct acf_odbc_query *query = NULL;
766                 int err;
767
768                 if ((err = init_acf_query(cfg, catg, &query))) {
769                         if (err == ENOMEM)
770                                 ast_log(LOG_ERROR, "Out of memory\n");
771                         else if (err == EINVAL)
772                                 ast_log(LOG_ERROR, "Invalid parameters for category %s\n", catg);
773                         else
774                                 ast_log(LOG_ERROR, "%s (%d)\n", strerror(err), err);
775                 } else {
776                         AST_LIST_INSERT_HEAD(&queries, query, list);
777                         ast_custom_function_register(query->acf);
778                 }
779         }
780
781         ast_config_destroy(cfg);
782         res |= ast_custom_function_register(&escape_function);
783
784         AST_LIST_UNLOCK(&queries);
785         return res;
786 }
787
788 static int unload_module(void)
789 {
790         struct acf_odbc_query *query;
791         int res = 0;
792
793         AST_LIST_LOCK(&queries);
794         while (!AST_LIST_EMPTY(&queries)) {
795                 query = AST_LIST_REMOVE_HEAD(&queries, list);
796                 ast_custom_function_unregister(query->acf);
797                 free_acf_query(query);
798         }
799
800         res |= ast_custom_function_unregister(&escape_function);
801         res |= ast_custom_function_unregister(&fetch_function);
802         res |= ast_unregister_application(app_odbcfinish);
803
804         /* Allow any threads waiting for this lock to pass (avoids a race) */
805         AST_LIST_UNLOCK(&queries);
806         usleep(1);
807         AST_LIST_LOCK(&queries);
808
809         AST_LIST_UNLOCK(&queries);
810         return 0;
811 }
812
813 static int reload(void)
814 {
815         int res = 0;
816         struct ast_config *cfg;
817         struct acf_odbc_query *oldquery;
818         char *catg;
819         struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
820
821         cfg = ast_config_load(config, config_flags);
822         if (cfg == CONFIG_STATUS_FILEUNCHANGED)
823                 return 0;
824
825         AST_LIST_LOCK(&queries);
826
827         while (!AST_LIST_EMPTY(&queries)) {
828                 oldquery = AST_LIST_REMOVE_HEAD(&queries, list);
829                 ast_custom_function_unregister(oldquery->acf);
830                 free_acf_query(oldquery);
831         }
832
833         if (!cfg) {
834                 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
835                 goto reload_out;
836         }
837
838         for (catg = ast_category_browse(cfg, NULL);
839              catg;
840              catg = ast_category_browse(cfg, catg)) {
841                 struct acf_odbc_query *query = NULL;
842
843                 if (init_acf_query(cfg, catg, &query)) {
844                         ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
845                 } else {
846                         AST_LIST_INSERT_HEAD(&queries, query, list);
847                         ast_custom_function_register(query->acf);
848                 }
849         }
850
851         ast_config_destroy(cfg);
852 reload_out:
853         AST_LIST_UNLOCK(&queries);
854         return res;
855 }
856
857 /* XXX need to revise usecount - set if query_lock is set */
858
859 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
860                 .load = load_module,
861                 .unload = unload_module,
862                 .reload = reload,
863                );
864