remove the PBX_ODBC logic from the configure script, and add GENERIC_ODCB logic that...
[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>res_odbc</depend>
31  ***/
32
33 #define USE_ODBC
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include "asterisk/module.h"
39 #include "asterisk/file.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/config.h"
43 #include "asterisk/res_odbc.h"
44 #include "asterisk/app.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/strings.h"
47
48 /*** DOCUMENTATION
49         <function name="ODBC_FETCH" language="en_US">
50                 <synopsis>
51                         Fetch a row from a multirow query.
52                 </synopsis>
53                 <syntax>
54                         <parameter name="result-id" required="true" />
55                 </syntax>
56                 <description>
57                         <para>For queries which are marked as mode=multirow, the original 
58                         query returns a <replaceable>result-id</replaceable> from which results 
59                         may be fetched.  This function implements the actual fetch of the results.</para>
60                         <para>This also sets <variable>ODBC_FETCH_STATUS</variable>.</para>
61                         <variablelist>
62                                 <variable name="ODBC_FETCH_STATUS">
63                                         <value name="SUCESS">
64                                                 If rows are available.
65                                         </value>
66                                         <value name="FAILURE">
67                                                 If no rows are available.
68                                         </value>
69                                 </variable>
70                         </variablelist>
71                 </description>
72         </function>
73         <application name="ODBCFinish" language="en_US">
74                 <synopsis>
75                         Clear the resultset of a sucessful multirow query.
76                 </synopsis>
77                 <syntax>
78                         <parameter name="result-id" required="true" />
79                 </syntax>
80                 <description>
81                         <para>For queries which are marked as mode=multirow, this will clear 
82                         any remaining rows of the specified resultset.</para>
83                 </description>
84         </application>
85         <function name="SQL_ESC" language="en_US">
86                 <synopsis>
87                         Escapes single ticks for use in SQL statements.
88                 </synopsis>
89                 <syntax>
90                         <parameter name="string" required="true" />
91                 </syntax>
92                 <description>
93                         <para>Used in SQL templates to escape data which may contain single ticks 
94                         <literal>'</literal> which are otherwise used to delimit data.</para>
95                         <para>Example: SELECT foo FROM bar WHERE baz='${SQL_ESC(${ARG1})}'</para>
96                 </description>
97         </function>
98  ***/
99
100 static char *config = "func_odbc.conf";
101
102 enum {
103         OPT_ESCAPECOMMAS =      (1 << 0),
104         OPT_MULTIROW     =      (1 << 1),
105 } odbc_option_flags;
106
107 struct acf_odbc_query {
108         AST_RWLIST_ENTRY(acf_odbc_query) list;
109         char readhandle[5][30];
110         char writehandle[5][30];
111         char sql_read[2048];
112         char sql_write[2048];
113         char sql_insert[2048];
114         unsigned int flags;
115         int rowlimit;
116         struct ast_custom_function *acf;
117 };
118
119 static void odbc_datastore_free(void *data);
120
121 struct ast_datastore_info odbc_info = {
122         .type = "FUNC_ODBC",
123         .destroy = odbc_datastore_free,
124 };
125
126 /* For storing each result row */
127 struct odbc_datastore_row {
128         AST_LIST_ENTRY(odbc_datastore_row) list;
129         char data[0];
130 };
131
132 /* For storing each result set */
133 struct odbc_datastore {
134         AST_LIST_HEAD(, odbc_datastore_row);
135         char names[0];
136 };
137
138 AST_RWLIST_HEAD_STATIC(queries, acf_odbc_query);
139
140 static int resultcount = 0;
141
142 AST_THREADSTORAGE(sql_buf);
143 AST_THREADSTORAGE(sql2_buf);
144 AST_THREADSTORAGE(coldata_buf);
145 AST_THREADSTORAGE(colnames_buf);
146
147 static void odbc_datastore_free(void *data)
148 {
149         struct odbc_datastore *result = data;
150         struct odbc_datastore_row *row;
151         AST_LIST_LOCK(result);
152         while ((row = AST_LIST_REMOVE_HEAD(result, list))) {
153                 ast_free(row);
154         }
155         AST_LIST_UNLOCK(result);
156         AST_LIST_HEAD_DESTROY(result);
157         ast_free(result);
158 }
159
160 static SQLHSTMT generic_execute(struct odbc_obj *obj, void *data)
161 {
162         int res;
163         char *sql = data;
164         SQLHSTMT stmt;
165
166         res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
167         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
168                 ast_log(LOG_WARNING, "SQL Alloc Handle failed (%d)!\n", res);
169                 return NULL;
170         }
171
172         res = SQLExecDirect(stmt, (unsigned char *)sql, SQL_NTS);
173         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
174                 if (res == SQL_ERROR) {
175                         int i;
176                         SQLINTEGER nativeerror=0, numfields=0;
177                         SQLSMALLINT diagbytes=0;
178                         unsigned char state[10], diagnostic[256];
179
180                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
181                         for (i = 0; i < numfields; i++) {
182                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
183                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
184                                 if (i > 10) {
185                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
186                                         break;
187                                 }
188                         }
189                 }
190
191                 ast_log(LOG_WARNING, "SQL Exec Direct failed (%d)![%s]\n", res, sql);
192                 SQLCloseCursor(stmt);
193                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
194                 return NULL;
195         }
196
197         return stmt;
198 }
199
200 /*
201  * Master control routine
202  */
203 static int acf_odbc_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
204 {
205         struct odbc_obj *obj = NULL;
206         struct acf_odbc_query *query;
207         char *t, varname[15];
208         int i, dsn, bogus_chan = 0;
209         AST_DECLARE_APP_ARGS(values,
210                 AST_APP_ARG(field)[100];
211         );
212         AST_DECLARE_APP_ARGS(args,
213                 AST_APP_ARG(field)[100];
214         );
215         SQLHSTMT stmt = NULL;
216         SQLLEN rows=0;
217         struct ast_str *buf = ast_str_thread_get(&sql_buf, 16);
218         struct ast_str *insertbuf = ast_str_thread_get(&sql2_buf, 16);
219         const char *status = "FAILURE";
220
221         if (!buf) {
222                 return -1;
223         }
224
225         AST_RWLIST_RDLOCK(&queries);
226         AST_RWLIST_TRAVERSE(&queries, query, list) {
227                 if (!strcmp(query->acf->name, cmd)) {
228                         break;
229                 }
230         }
231
232         if (!query) {
233                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
234                 AST_RWLIST_UNLOCK(&queries);
235                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
236                 return -1;
237         }
238
239         if (!chan) {
240                 if ((chan = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/func_odbc")))
241                         bogus_chan = 1;
242         }
243
244         if (chan)
245                 ast_autoservice_start(chan);
246
247         ast_str_make_space(&buf, strlen(query->sql_write) * 2 + 300);
248         ast_str_make_space(&insertbuf, strlen(query->sql_insert) * 2 + 300);
249
250         /* Parse our arguments */
251         t = value ? ast_strdupa(value) : "";
252
253         if (!s || !t) {
254                 ast_log(LOG_ERROR, "Out of memory\n");
255                 AST_RWLIST_UNLOCK(&queries);
256                 if (chan)
257                         ast_autoservice_stop(chan);
258                 if (bogus_chan) {
259                         ast_channel_free(chan);
260                 } else {
261                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
262                 }
263                 return -1;
264         }
265
266         AST_STANDARD_APP_ARGS(args, s);
267         for (i = 0; i < args.argc; i++) {
268                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
269                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
270         }
271
272         /* Parse values, just like arguments */
273         AST_STANDARD_APP_ARGS(values, t);
274         for (i = 0; i < values.argc; i++) {
275                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
276                 pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
277         }
278
279         /* Additionally set the value as a whole (but push an empty string if value is NULL) */
280         pbx_builtin_pushvar_helper(chan, "VALUE", value ? value : "");
281
282         ast_str_substitute_variables(&buf, 0, chan, query->sql_write);
283         ast_str_substitute_variables(&insertbuf, 0, chan, query->sql_insert);
284
285         /* Restore prior values */
286         for (i = 0; i < args.argc; i++) {
287                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
288                 pbx_builtin_setvar_helper(chan, varname, NULL);
289         }
290
291         for (i = 0; i < values.argc; i++) {
292                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
293                 pbx_builtin_setvar_helper(chan, varname, NULL);
294         }
295         pbx_builtin_setvar_helper(chan, "VALUE", NULL);
296
297         for (dsn = 0; dsn < 5; dsn++) {
298                 if (!ast_strlen_zero(query->writehandle[dsn])) {
299                         obj = ast_odbc_request_obj(query->writehandle[dsn], 0);
300                         if (obj)
301                                 stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(buf));
302                 }
303                 if (stmt) {
304                         status = "SUCCESS";
305                         SQLRowCount(stmt, &rows);
306                         break;
307                 }
308         }
309
310         if (stmt && rows == 0 && ast_str_strlen(insertbuf) != 0) {
311                 SQLCloseCursor(stmt);
312                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
313                 for (dsn = 0; dsn < 5; dsn++) {
314                         if (!ast_strlen_zero(query->writehandle[dsn])) {
315                                 obj = ast_odbc_request_obj(query->writehandle[dsn], 0);
316                                 if (obj) {
317                                         stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(insertbuf));
318                                 }
319                         }
320                         if (stmt) {
321                                 status = "FAILOVER";
322                                 SQLRowCount(stmt, &rows);
323                                 break;
324                         }
325                 }
326         }
327
328         AST_RWLIST_UNLOCK(&queries);
329
330         /* Output the affected rows, for all cases.  In the event of failure, we
331          * flag this as -1 rows.  Note that this is different from 0 affected rows
332          * which would be the case if we succeeded in our query, but the values did
333          * not change. */
334         snprintf(varname, sizeof(varname), "%d", (int)rows);
335         pbx_builtin_setvar_helper(chan, "ODBCROWS", varname);
336         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
337
338         if (stmt) {
339                 SQLCloseCursor(stmt);
340                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
341         }
342         if (obj)
343                 ast_odbc_release_obj(obj);
344
345         if (chan)
346                 ast_autoservice_stop(chan);
347         if (bogus_chan)
348                 ast_channel_free(chan);
349
350         return 0;
351 }
352
353 static int acf_odbc_read(struct ast_channel *chan, const char *cmd, char *s, char *buf, size_t len)
354 {
355         struct odbc_obj *obj = NULL;
356         struct acf_odbc_query *query;
357         char varname[15], rowcount[12] = "-1";
358         struct ast_str *colnames = ast_str_thread_get(&colnames_buf, 16);
359         int res, x, y, buflen = 0, escapecommas, rowlimit = 1, dsn, bogus_chan = 0;
360         AST_DECLARE_APP_ARGS(args,
361                 AST_APP_ARG(field)[100];
362         );
363         SQLHSTMT stmt = NULL;
364         SQLSMALLINT colcount=0;
365         SQLLEN indicator;
366         SQLSMALLINT collength;
367         struct odbc_datastore *resultset = NULL;
368         struct odbc_datastore_row *row = NULL;
369         struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
370         const char *status = "FAILURE";
371
372         if (!sql) {
373                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
374                 return -1;
375         }
376
377         ast_str_reset(colnames);
378
379         AST_RWLIST_RDLOCK(&queries);
380         AST_RWLIST_TRAVERSE(&queries, query, list) {
381                 if (!strcmp(query->acf->name, cmd)) {
382                         break;
383                 }
384         }
385
386         if (!query) {
387                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
388                 AST_RWLIST_UNLOCK(&queries);
389                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
390                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
391                 return -1;
392         }
393
394         if (!chan) {
395                 if ((chan = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/func_odbc"))) {
396                         bogus_chan = 1;
397                 }
398         }
399
400         if (chan) {
401                 ast_autoservice_start(chan);
402         }
403
404         AST_STANDARD_APP_ARGS(args, s);
405         for (x = 0; x < args.argc; x++) {
406                 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
407                 pbx_builtin_pushvar_helper(chan, varname, args.field[x]);
408         }
409
410         ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
411
412         /* Restore prior values */
413         for (x = 0; x < args.argc; x++) {
414                 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
415                 pbx_builtin_setvar_helper(chan, varname, NULL);
416         }
417
418         /* Save these flags, so we can release the lock */
419         escapecommas = ast_test_flag(query, OPT_ESCAPECOMMAS);
420         if (ast_test_flag(query, OPT_MULTIROW)) {
421                 resultset = ast_calloc(1, sizeof(*resultset));
422                 AST_LIST_HEAD_INIT(resultset);
423                 if (query->rowlimit) {
424                         rowlimit = query->rowlimit;
425                 } else {
426                         rowlimit = INT_MAX;
427                 }
428         }
429         AST_RWLIST_UNLOCK(&queries);
430
431         for (dsn = 0; dsn < 5; dsn++) {
432                 if (!ast_strlen_zero(query->readhandle[dsn])) {
433                         obj = ast_odbc_request_obj(query->readhandle[dsn], 0);
434                         if (obj) {
435                                 stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql));
436                         }
437                 }
438                 if (stmt) {
439                         break;
440                 }
441         }
442
443         if (!stmt) {
444                 ast_log(LOG_ERROR, "Unable to execute query [%s]\n", ast_str_buffer(sql));
445                 if (obj) {
446                         ast_odbc_release_obj(obj);
447                 }
448                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
449                 if (chan) {
450                         ast_autoservice_stop(chan);
451                 }
452                 if (bogus_chan) {
453                         ast_channel_free(chan);
454                 }
455                 return -1;
456         }
457
458         res = SQLNumResultCols(stmt, &colcount);
459         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
460                 ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
461                 SQLCloseCursor(stmt);
462                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
463                 ast_odbc_release_obj(obj);
464                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
465                 if (chan) {
466                         ast_autoservice_stop(chan);
467                 }
468                 if (bogus_chan) {
469                         ast_channel_free(chan);
470                 }
471                 return -1;
472         }
473
474         res = SQLFetch(stmt);
475         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
476                 int res1 = -1;
477                 if (res == SQL_NO_DATA) {
478                         ast_verb(4, "Found no rows [%s]\n", ast_str_buffer(sql));
479                         res1 = 0;
480                         buf[0] = '\0';
481                         ast_copy_string(rowcount, "0", sizeof(rowcount));
482                         status = "NODATA";
483                 } else {
484                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
485                         status = "FETCHERROR";
486                 }
487                 SQLCloseCursor(stmt);
488                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
489                 ast_odbc_release_obj(obj);
490                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
491                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
492                 if (chan)
493                         ast_autoservice_stop(chan);
494                 if (bogus_chan)
495                         ast_channel_free(chan);
496                 return res1;
497         }
498
499         status = "SUCCESS";
500
501         for (y = 0; y < rowlimit; y++) {
502                 for (x = 0; x < colcount; x++) {
503                         int i;
504                         struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
505                         char *ptrcoldata;
506
507                         if (y == 0) {
508                                 char colname[256];
509                                 SQLULEN maxcol;
510
511                                 res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
512                                 ast_debug(3, "Got collength of %d and maxcol of %d for column '%s' (offset %d)\n", (int)collength, (int)maxcol, colname, x);
513                                 if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
514                                         snprintf(colname, sizeof(colname), "field%d", x);
515                                 }
516
517                                 ast_str_make_space(&coldata, maxcol + 1);
518
519                                 if (ast_str_strlen(colnames)) {
520                                         ast_str_append(&colnames, 0, ",");
521                                 }
522                                 ast_str_append_escapecommas(&colnames, 0, colname, sizeof(colname));
523
524                                 if (resultset) {
525                                         void *tmp = ast_realloc(resultset, sizeof(*resultset) + ast_str_strlen(colnames) + 1);
526                                         if (!tmp) {
527                                                 ast_log(LOG_ERROR, "No space for a new resultset?\n");
528                                                 ast_free(resultset);
529                                                 SQLCloseCursor(stmt);
530                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
531                                                 ast_odbc_release_obj(obj);
532                                                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
533                                                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
534                                                 if (chan)
535                                                         ast_autoservice_stop(chan);
536                                                 if (bogus_chan)
537                                                         ast_channel_free(chan);
538                                                 return -1;
539                                         }
540                                         resultset = tmp;
541                                         strcpy((char *)resultset + sizeof(*resultset), ast_str_buffer(colnames));
542                                 }
543                         }
544
545                         buflen = strlen(buf);
546                         res = ast_str_SQLGetData(&coldata, -1, stmt, x + 1, SQL_CHAR, &indicator);
547                         if (indicator == SQL_NULL_DATA) {
548                                 ast_debug(3, "Got NULL data\n");
549                                 ast_str_reset(coldata);
550                                 res = SQL_SUCCESS;
551                         }
552
553                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
554                                 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", ast_str_buffer(sql));
555                                 y = -1;
556                                 buf[0] = '\0';
557                                 goto end_acf_read;
558                         }
559
560                         ast_debug(2, "Got coldata of '%s'\n", ast_str_buffer(coldata));
561
562                         if (buflen) {
563                                 buf[buflen++] = ',';
564                         }
565
566                         /* Copy data, encoding '\' and ',' for the argument parser */
567                         ptrcoldata = ast_str_buffer(coldata);
568                         for (i = 0; i < ast_str_strlen(coldata); i++) {
569                                 if (escapecommas && (ptrcoldata[i] == '\\' || ptrcoldata[i] == ',')) {
570                                         buf[buflen++] = '\\';
571                                 }
572                                 buf[buflen++] = ptrcoldata[i];
573
574                                 if (buflen >= len - 2) {
575                                         break;
576                                 }
577
578                                 if (ptrcoldata[i] == '\0') {
579                                         break;
580                                 }
581                         }
582
583                         buf[buflen] = '\0';
584                         ast_debug(2, "buf is now set to '%s'\n", buf);
585                 }
586                 ast_debug(2, "buf is now set to '%s'\n", buf);
587
588                 if (resultset) {
589                         row = ast_calloc(1, sizeof(*row) + buflen + 1);
590                         if (!row) {
591                                 ast_log(LOG_ERROR, "Unable to allocate space for more rows in this resultset.\n");
592                                 status = "MEMERROR";
593                                 goto end_acf_read;
594                         }
595                         strcpy((char *)row + sizeof(*row), buf);
596                         AST_LIST_INSERT_TAIL(resultset, row, list);
597
598                         /* Get next row */
599                         res = SQLFetch(stmt);
600                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
601                                 if (res != SQL_NO_DATA) {
602                                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
603                                 }
604                                 /* Number of rows in the resultset */
605                                 y++;
606                                 break;
607                         }
608                 }
609         }
610
611 end_acf_read:
612         snprintf(rowcount, sizeof(rowcount), "%d", y);
613         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
614         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
615         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", ast_str_buffer(colnames));
616         if (resultset) {
617                 int uid;
618                 struct ast_datastore *odbc_store;
619                 uid = ast_atomic_fetchadd_int(&resultcount, +1) + 1;
620                 snprintf(buf, len, "%d", uid);
621                 odbc_store = ast_datastore_alloc(&odbc_info, buf);
622                 if (!odbc_store) {
623                         ast_log(LOG_ERROR, "Rows retrieved, but unable to store it in the channel.  Results fail.\n");
624                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
625                         odbc_datastore_free(resultset);
626                         SQLCloseCursor(stmt);
627                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
628                         ast_odbc_release_obj(obj);
629                         if (chan)
630                                 ast_autoservice_stop(chan);
631                         if (bogus_chan)
632                                 ast_channel_free(chan);
633                         return -1;
634                 }
635                 odbc_store->data = resultset;
636                 ast_channel_datastore_add(chan, odbc_store);
637         }
638         SQLCloseCursor(stmt);
639         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
640         ast_odbc_release_obj(obj);
641         if (chan)
642                 ast_autoservice_stop(chan);
643         if (bogus_chan)
644                 ast_channel_free(chan);
645         return 0;
646 }
647
648 static int acf_escape(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
649 {
650         char *out = buf;
651
652         for (; *data && out - buf < len; data++) {
653                 if (*data == '\'') {
654                         *out = '\'';
655                         out++;
656                 }
657                 *out++ = *data;
658         }
659         *out = '\0';
660
661         return 0;
662 }
663
664 static struct ast_custom_function escape_function = {
665         .name = "SQL_ESC",
666         .read = acf_escape,
667         .write = NULL,
668 };
669
670 static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
671 {
672         struct ast_datastore *store;
673         struct odbc_datastore *resultset;
674         struct odbc_datastore_row *row;
675         store = ast_channel_datastore_find(chan, &odbc_info, data);
676         if (!store) {
677                 pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
678                 return -1;
679         }
680         resultset = store->data;
681         AST_LIST_LOCK(resultset);
682         row = AST_LIST_REMOVE_HEAD(resultset, list);
683         AST_LIST_UNLOCK(resultset);
684         if (!row) {
685                 /* Cleanup datastore */
686                 ast_channel_datastore_remove(chan, store);
687                 ast_datastore_free(store);
688                 pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
689                 return -1;
690         }
691         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", resultset->names);
692         ast_copy_string(buf, row->data, len);
693         ast_free(row);
694         pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "SUCCESS");
695         return 0;
696 }
697
698 static struct ast_custom_function fetch_function = {
699         .name = "ODBC_FETCH",
700         .read = acf_fetch,
701         .write = NULL,
702 };
703
704 static char *app_odbcfinish = "ODBCFinish";
705
706 static int exec_odbcfinish(struct ast_channel *chan, void *data)
707 {
708         struct ast_datastore *store = ast_channel_datastore_find(chan, &odbc_info, data);
709         if (!store) /* Already freed; no big deal. */
710                 return 0;
711         ast_channel_datastore_remove(chan, store);
712         ast_datastore_free(store);
713         return 0;
714 }
715
716 static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
717 {
718         const char *tmp;
719         int i;
720
721         if (!cfg || !catg) {
722                 return EINVAL;
723         }
724
725         *query = ast_calloc(1, sizeof(struct acf_odbc_query));
726         if (! (*query))
727                 return ENOMEM;
728
729         if (((tmp = ast_variable_retrieve(cfg, catg, "writehandle"))) || ((tmp = ast_variable_retrieve(cfg, catg, "dsn")))) {
730                 char *tmp2 = ast_strdupa(tmp);
731                 AST_DECLARE_APP_ARGS(writeconf,
732                         AST_APP_ARG(dsn)[5];
733                 );
734                 AST_STANDARD_APP_ARGS(writeconf, tmp2);
735                 for (i = 0; i < 5; i++) {
736                         if (!ast_strlen_zero(writeconf.dsn[i]))
737                                 ast_copy_string((*query)->writehandle[i], writeconf.dsn[i], sizeof((*query)->writehandle[i]));
738                 }
739         }
740
741         if ((tmp = ast_variable_retrieve(cfg, catg, "readhandle"))) {
742                 char *tmp2 = ast_strdupa(tmp);
743                 AST_DECLARE_APP_ARGS(readconf,
744                         AST_APP_ARG(dsn)[5];
745                 );
746                 AST_STANDARD_APP_ARGS(readconf, tmp2);
747                 for (i = 0; i < 5; i++) {
748                         if (!ast_strlen_zero(readconf.dsn[i]))
749                                 ast_copy_string((*query)->readhandle[i], readconf.dsn[i], sizeof((*query)->readhandle[i]));
750                 }
751         } else {
752                 /* If no separate readhandle, then use the writehandle for reading */
753                 for (i = 0; i < 5; i++) {
754                         if (!ast_strlen_zero((*query)->writehandle[i]))
755                                 ast_copy_string((*query)->readhandle[i], (*query)->writehandle[i], sizeof((*query)->readhandle[i]));
756                 }
757         }
758
759         if ((tmp = ast_variable_retrieve(cfg, catg, "readsql")))
760                 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
761         else if ((tmp = ast_variable_retrieve(cfg, catg, "read"))) {
762                 ast_log(LOG_WARNING, "Parameter 'read' is deprecated for category %s.  Please use 'readsql' instead.\n", catg);
763                 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
764         }
765
766         if (!ast_strlen_zero((*query)->sql_read) && ast_strlen_zero((*query)->readhandle[0])) {
767                 ast_free(*query);
768                 *query = NULL;
769                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for reading: %s\n", catg);
770                 return EINVAL;
771         }
772
773         if ((tmp = ast_variable_retrieve(cfg, catg, "writesql")))
774                 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
775         else if ((tmp = ast_variable_retrieve(cfg, catg, "write"))) {
776                 ast_log(LOG_WARNING, "Parameter 'write' is deprecated for category %s.  Please use 'writesql' instead.\n", catg);
777                 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
778         }
779
780         if (!ast_strlen_zero((*query)->sql_write) && ast_strlen_zero((*query)->writehandle[0])) {
781                 ast_free(*query);
782                 *query = NULL;
783                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for writing: %s\n", catg);
784                 return EINVAL;
785         }
786
787         if ((tmp = ast_variable_retrieve(cfg, catg, "insertsql"))) {
788                 ast_copy_string((*query)->sql_insert, tmp, sizeof((*query)->sql_insert));
789         }
790
791         /* Allow escaping of embedded commas in fields to be turned off */
792         ast_set_flag((*query), OPT_ESCAPECOMMAS);
793         if ((tmp = ast_variable_retrieve(cfg, catg, "escapecommas"))) {
794                 if (ast_false(tmp))
795                         ast_clear_flag((*query), OPT_ESCAPECOMMAS);
796         }
797
798         if ((tmp = ast_variable_retrieve(cfg, catg, "mode"))) {
799                 if (strcasecmp(tmp, "multirow") == 0)
800                         ast_set_flag((*query), OPT_MULTIROW);
801                 if ((tmp = ast_variable_retrieve(cfg, catg, "rowlimit")))
802                         sscanf(tmp, "%d", &((*query)->rowlimit));
803         }
804
805         (*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
806         if (! (*query)->acf) {
807                 ast_free(*query);
808                 *query = NULL;
809                 return ENOMEM;
810         }
811         if (ast_string_field_init((*query)->acf, 128)) {
812                 ast_free((*query)->acf);
813                 ast_free(*query);
814                 *query = NULL;
815                 return ENOMEM;
816         }
817
818         if ((tmp = ast_variable_retrieve(cfg, catg, "prefix")) && !ast_strlen_zero(tmp)) {
819                 if (asprintf((char **)&((*query)->acf->name), "%s_%s", tmp, catg) < 0) {
820                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
821                 }
822         } else {
823                 if (asprintf((char **)&((*query)->acf->name), "ODBC_%s", catg) < 0) {
824                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
825                 }
826         }
827
828         if (!((*query)->acf->name)) {
829                 ast_string_field_free_memory((*query)->acf);
830                 ast_free((*query)->acf);
831                 ast_free(*query);
832                 *query = NULL;
833                 return ENOMEM;
834         }
835
836         if ((tmp = ast_variable_retrieve(cfg, catg, "syntax")) && !ast_strlen_zero(tmp)) {
837                 ast_string_field_build((*query)->acf, syntax, "%s(%s)", (*query)->acf->name, tmp);
838         } else {
839                 ast_string_field_build((*query)->acf, syntax, "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
840         }
841
842         if (ast_strlen_zero((*query)->acf->syntax)) {
843                 ast_free((char *)(*query)->acf->name);
844                 ast_string_field_free_memory((*query)->acf);
845                 ast_free((*query)->acf);
846                 ast_free(*query);
847                 *query = NULL;
848                 return ENOMEM;
849         }
850
851         if ((tmp = ast_variable_retrieve(cfg, catg, "synopsis")) && !ast_strlen_zero(tmp)) {
852                 ast_string_field_set((*query)->acf, synopsis, tmp);
853         } else {
854                 ast_string_field_set((*query)->acf, synopsis, "Runs the referenced query with the specified arguments");
855         }
856
857         if (ast_strlen_zero((*query)->acf->synopsis)) {
858                 ast_free((char *)(*query)->acf->name);
859                 ast_string_field_free_memory((*query)->acf);
860                 ast_free((*query)->acf);
861                 ast_free(*query);
862                 *query = NULL;
863                 return ENOMEM;
864         }
865
866         if (!ast_strlen_zero((*query)->sql_read) && !ast_strlen_zero((*query)->sql_write)) {
867                 ast_string_field_build((*query)->acf, desc,
868                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
869                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
870                                         "${ARG2}, ... ${ARGn}.  When setting the function, the values are provided\n"
871                                         "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
872                                         "%s"
873                                         "\nRead:\n%s\n\nWrite:\n%s\n%s%s%s",
874                                         ast_strlen_zero((*query)->sql_insert) ? "" :
875                                                 "If the write query affects no rows, the insert query will be\n"
876                                                 "performed.\n",
877                                         (*query)->sql_read,
878                                         (*query)->sql_write,
879                                         ast_strlen_zero((*query)->sql_insert) ? "" : "Insert:\n",
880                                         ast_strlen_zero((*query)->sql_insert) ? "" : (*query)->sql_insert,
881                                         ast_strlen_zero((*query)->sql_insert) ? "" : "\n");
882         } else if (!ast_strlen_zero((*query)->sql_read)) {
883                 ast_string_field_build((*query)->acf, desc,
884                                                 "Runs the following query, as defined in func_odbc.conf, performing\n"
885                                                 "substitution of the arguments into the query as specified by ${ARG1},\n"
886                                                 "${ARG2}, ... ${ARGn}.  This function may only be read, not set.\n\nSQL:\n%s\n",
887                                                 (*query)->sql_read);
888         } else if (!ast_strlen_zero((*query)->sql_write)) {
889                 ast_string_field_build((*query)->acf, desc,     
890                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
891                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
892                                         "${ARG2}, ... ${ARGn}.  The values are provided either in whole as\n"
893                                         "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
894                                         "This function may only be set.\n%sSQL:\n%s\n%s%s%s",
895                                         ast_strlen_zero((*query)->sql_insert) ? "" :
896                                                 "If the write query affects no rows, the insert query will be\n"
897                                                 "performed.\n",
898                                         (*query)->sql_write,
899                                         ast_strlen_zero((*query)->sql_insert) ? "" : "Insert:\n",
900                                         ast_strlen_zero((*query)->sql_insert) ? "" : (*query)->sql_insert,
901                                         ast_strlen_zero((*query)->sql_insert) ? "" : "\n");
902         } else {
903                 ast_string_field_free_memory((*query)->acf);
904                 ast_free((char *)(*query)->acf->name);
905                 ast_free((*query)->acf);
906                 ast_free(*query);
907                 ast_log(LOG_WARNING, "Section '%s' was found, but there was no SQL to execute.  Ignoring.\n", catg);
908                 return EINVAL;
909         }
910
911         if (ast_strlen_zero((*query)->acf->desc)) {
912                 ast_string_field_free_memory((*query)->acf);
913                 ast_free((char *)(*query)->acf->name);
914                 ast_free((*query)->acf);
915                 ast_free(*query);
916                 *query = NULL;
917                 return ENOMEM;
918         }
919
920         if (ast_strlen_zero((*query)->sql_read)) {
921                 (*query)->acf->read = NULL;
922         } else {
923                 (*query)->acf->read = acf_odbc_read;
924         }
925
926         if (ast_strlen_zero((*query)->sql_write)) {
927                 (*query)->acf->write = NULL;
928         } else {
929                 (*query)->acf->write = acf_odbc_write;
930         }
931
932         return 0;
933 }
934
935 static int free_acf_query(struct acf_odbc_query *query)
936 {
937         if (query) {
938                 if (query->acf) {
939                         if (query->acf->name)
940                                 ast_free((char *)query->acf->name);
941                         ast_string_field_free_memory(query->acf);
942                         ast_free(query->acf);
943                 }
944                 ast_free(query);
945         }
946         return 0;
947 }
948
949 static char *cli_odbc_read(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
950 {
951         AST_DECLARE_APP_ARGS(args,
952                 AST_APP_ARG(field)[100];
953         );
954         struct ast_str *sql;
955         char *char_args, varname[10];
956         struct acf_odbc_query *query;
957         struct ast_channel *chan;
958         int i;
959
960         switch (cmd) {
961         case CLI_INIT:
962                 e->command = "odbc read";
963                 e->usage =
964                         "Usage: odbc read <name> <args> [exec]\n"
965                         "       Evaluates the SQL provided in the ODBC function <name>, and\n"
966                         "       optionally executes the function.  This function is intended for\n"
967                         "       testing purposes.  Remember to quote arguments containing spaces.\n";
968                 return NULL;
969         case CLI_GENERATE:
970                 if (a->pos == 2) {
971                         int wordlen = strlen(a->word), which = 0;
972                         /* Complete function name */
973                         AST_RWLIST_RDLOCK(&queries);
974                         AST_RWLIST_TRAVERSE(&queries, query, list) {
975                                 if (!strncasecmp(query->acf->name, a->word, wordlen)) {
976                                         if (++which > a->n) {
977                                                 char *res = ast_strdup(query->acf->name);
978                                                 AST_RWLIST_UNLOCK(&queries);
979                                                 return res;
980                                         }
981                                 }
982                         }
983                         AST_RWLIST_UNLOCK(&queries);
984                         return NULL;
985                 } else if (a->pos == 4) {
986                         return a->n == 0 ? ast_strdup("exec") : NULL;
987                 } else {
988                         return NULL;
989                 }
990         }
991
992         if (a->argc < 4 || a->argc > 5) {
993                 return CLI_SHOWUSAGE;
994         }
995
996         sql = ast_str_thread_get(&sql_buf, 16);
997         if (!sql) {
998                 return CLI_FAILURE;
999         }
1000
1001         AST_RWLIST_RDLOCK(&queries);
1002         AST_RWLIST_TRAVERSE(&queries, query, list) {
1003                 if (!strcmp(query->acf->name, a->argv[2])) {
1004                         break;
1005                 }
1006         }
1007
1008         if (!query) {
1009                 ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
1010                 AST_RWLIST_UNLOCK(&queries);
1011                 return CLI_SHOWUSAGE;
1012         }
1013
1014         if (ast_strlen_zero(query->sql_read)) {
1015                 ast_cli(a->fd, "The function %s has no writesql parameter.\n", a->argv[2]);
1016                 AST_RWLIST_UNLOCK(&queries);
1017                 return CLI_SUCCESS;
1018         }
1019
1020         ast_str_make_space(&sql, strlen(query->sql_read) * 2 + 300);
1021
1022         /* Evaluate function */
1023         char_args = ast_strdupa(a->argv[3]);
1024
1025         chan = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/func_odbc");
1026
1027         AST_STANDARD_APP_ARGS(args, char_args);
1028         for (i = 0; i < args.argc; i++) {
1029                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
1030                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
1031         }
1032
1033         ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
1034         ast_channel_free(chan);
1035
1036         if (a->argc == 5 && !strcmp(a->argv[4], "exec")) {
1037                 /* Execute the query */
1038                 struct odbc_obj *obj = NULL;
1039                 int dsn, executed = 0;
1040                 SQLHSTMT stmt;
1041                 int rows = 0, res, x;
1042                 SQLSMALLINT colcount = 0, collength;
1043                 SQLLEN indicator;
1044                 struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
1045                 char colname[256];
1046                 SQLULEN maxcol;
1047
1048                 for (dsn = 0; dsn < 5; dsn++) {
1049                         if (ast_strlen_zero(query->readhandle[dsn])) {
1050                                 continue;
1051                         }
1052                         ast_debug(1, "Found handle %s\n", query->readhandle[dsn]);
1053                         if (!(obj = ast_odbc_request_obj(query->readhandle[dsn], 0))) {
1054                                 continue;
1055                         }
1056
1057                         ast_debug(1, "Got obj\n");
1058                         if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
1059                                 ast_odbc_release_obj(obj);
1060                                 continue;
1061                         }
1062
1063                         executed = 1;
1064
1065                         res = SQLNumResultCols(stmt, &colcount);
1066                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1067                                 ast_cli(a->fd, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
1068                                 SQLCloseCursor(stmt);
1069                                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1070                                 ast_odbc_release_obj(obj);
1071                                 AST_RWLIST_UNLOCK(&queries);
1072                                 return CLI_SUCCESS;
1073                         }
1074
1075                         res = SQLFetch(stmt);
1076                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1077                                 SQLCloseCursor(stmt);
1078                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1079                                 ast_odbc_release_obj(obj);
1080                                 if (res == SQL_NO_DATA) {
1081                                         ast_cli(a->fd, "Returned %d rows.  Query executed on handle %d:%s [%s]\n", rows, dsn, query->readhandle[dsn], ast_str_buffer(sql));
1082                                         break;
1083                                 } else {
1084                                         ast_cli(a->fd, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
1085                                 }
1086                                 AST_RWLIST_UNLOCK(&queries);
1087                                 return CLI_SUCCESS;
1088                         }
1089                         for (;;) {
1090                                 for (x = 0; x < colcount; x++) {
1091                                         res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
1092                                         if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
1093                                                 snprintf(colname, sizeof(colname), "field%d", x);
1094                                         }
1095
1096                                         res = ast_str_SQLGetData(&coldata, maxcol, stmt, x + 1, SQL_CHAR, &indicator);
1097                                         if (indicator == SQL_NULL_DATA) {
1098                                                 ast_str_set(&coldata, 0, "(nil)");
1099                                                 res = SQL_SUCCESS;
1100                                         }
1101
1102                                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1103                                                 ast_cli(a->fd, "SQL Get Data error %d!\n[%s]\n\n", res, ast_str_buffer(sql));
1104                                                 SQLCloseCursor(stmt);
1105                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1106                                                 ast_odbc_release_obj(obj);
1107                                                 AST_RWLIST_UNLOCK(&queries);
1108                                                 return CLI_SUCCESS;
1109                                         }
1110
1111                                         ast_cli(a->fd, "%-20.20s  %s\n", colname, ast_str_buffer(coldata));
1112                                 }
1113                                 /* Get next row */
1114                                 res = SQLFetch(stmt);
1115                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1116                                         break;
1117                                 }
1118                                 ast_cli(a->fd, "%-20.20s  %s\n", "----------", "----------");
1119                                 rows++;
1120                         }
1121                         SQLCloseCursor(stmt);
1122                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1123                         ast_odbc_release_obj(obj);
1124                         ast_cli(a->fd, "Returned %d rows.  Query executed on handle %d [%s]\n", rows, dsn, query->readhandle[dsn]);
1125                         break;
1126                 }
1127                 ast_odbc_release_obj(obj);
1128
1129                 if (!executed) {
1130                         ast_cli(a->fd, "Failed to execute query. [%s]\n", ast_str_buffer(sql));
1131                 }
1132         } else { /* No execution, just print out the resulting SQL */
1133                 ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
1134         }
1135         AST_RWLIST_UNLOCK(&queries);
1136         return CLI_SUCCESS;
1137 }
1138
1139 static char *cli_odbc_write(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1140 {
1141         AST_DECLARE_APP_ARGS(values,
1142                 AST_APP_ARG(field)[100];
1143         );
1144         AST_DECLARE_APP_ARGS(args,
1145                 AST_APP_ARG(field)[100];
1146         );
1147         struct ast_str *sql;
1148         char *char_args, *char_values, varname[10];
1149         struct acf_odbc_query *query;
1150         struct ast_channel *chan;
1151         int i;
1152
1153         switch (cmd) {
1154         case CLI_INIT:
1155                 e->command = "odbc write";
1156                 e->usage =
1157                         "Usage: odbc write <name> <args> <value> [exec]\n"
1158                         "       Evaluates the SQL provided in the ODBC function <name>, and\n"
1159                         "       optionally executes the function.  This function is intended for\n"
1160                         "       testing purposes.  Remember to quote arguments containing spaces.\n";
1161                 return NULL;
1162         case CLI_GENERATE:
1163                 if (a->pos == 2) {
1164                         int wordlen = strlen(a->word), which = 0;
1165                         /* Complete function name */
1166                         AST_RWLIST_RDLOCK(&queries);
1167                         AST_RWLIST_TRAVERSE(&queries, query, list) {
1168                                 if (!strncasecmp(query->acf->name, a->word, wordlen)) {
1169                                         if (++which > a->n) {
1170                                                 char *res = ast_strdup(query->acf->name);
1171                                                 AST_RWLIST_UNLOCK(&queries);
1172                                                 return res;
1173                                         }
1174                                 }
1175                         }
1176                         AST_RWLIST_UNLOCK(&queries);
1177                         return NULL;
1178                 } else if (a->pos == 5) {
1179                         return a->n == 0 ? ast_strdup("exec") : NULL;
1180                 } else {
1181                         return NULL;
1182                 }
1183         }
1184
1185         if (a->argc < 5 || a->argc > 6) {
1186                 return CLI_SHOWUSAGE;
1187         }
1188
1189         sql = ast_str_thread_get(&sql_buf, 16);
1190         if (!sql) {
1191                 return CLI_FAILURE;
1192         }
1193
1194         AST_RWLIST_RDLOCK(&queries);
1195         AST_RWLIST_TRAVERSE(&queries, query, list) {
1196                 if (!strcmp(query->acf->name, a->argv[2])) {
1197                         break;
1198                 }
1199         }
1200
1201         if (!query) {
1202                 ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
1203                 AST_RWLIST_UNLOCK(&queries);
1204                 return CLI_SHOWUSAGE;
1205         }
1206
1207         if (ast_strlen_zero(query->sql_write)) {
1208                 ast_cli(a->fd, "The function %s has no writesql parameter.\n", a->argv[2]);
1209                 AST_RWLIST_UNLOCK(&queries);
1210                 return CLI_SUCCESS;
1211         }
1212
1213         ast_str_make_space(&sql, strlen(query->sql_write) * 2 + 300);
1214
1215         /* Evaluate function */
1216         char_args = ast_strdupa(a->argv[3]);
1217         char_values = ast_strdupa(a->argv[4]);
1218
1219         chan = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/func_odbc");
1220
1221         AST_STANDARD_APP_ARGS(args, char_args);
1222         for (i = 0; i < args.argc; i++) {
1223                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
1224                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
1225         }
1226
1227         /* Parse values, just like arguments */
1228         AST_STANDARD_APP_ARGS(values, char_values);
1229         for (i = 0; i < values.argc; i++) {
1230                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
1231                 pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
1232         }
1233
1234         /* Additionally set the value as a whole (but push an empty string if value is NULL) */
1235         pbx_builtin_pushvar_helper(chan, "VALUE", S_OR(a->argv[4], ""));
1236         ast_str_substitute_variables(&sql, 0, chan, query->sql_write);
1237         ast_debug(1, "SQL is %s\n", ast_str_buffer(sql));
1238         ast_channel_free(chan);
1239
1240         if (a->argc == 6 && !strcmp(a->argv[5], "exec")) {
1241                 /* Execute the query */
1242                 struct odbc_obj *obj = NULL;
1243                 int dsn, executed = 0;
1244                 SQLHSTMT stmt;
1245                 SQLLEN rows = -1;
1246
1247                 for (dsn = 0; dsn < 5; dsn++) {
1248                         if (ast_strlen_zero(query->writehandle[dsn])) {
1249                                 continue;
1250                         }
1251                         if (!(obj = ast_odbc_request_obj(query->writehandle[dsn], 0))) {
1252                                 continue;
1253                         }
1254                         if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
1255                                 ast_odbc_release_obj(obj);
1256                                 continue;
1257                         }
1258
1259                         SQLRowCount(stmt, &rows);
1260                         SQLCloseCursor(stmt);
1261                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1262                         ast_odbc_release_obj(obj);
1263                         ast_cli(a->fd, "Affected %d rows.  Query executed on handle %d [%s]\n", (int)rows, dsn, query->writehandle[dsn]);
1264                         executed = 1;
1265                         break;
1266                 }
1267
1268                 if (!executed) {
1269                         ast_cli(a->fd, "Failed to execute query.\n");
1270                 }
1271         } else { /* No execution, just print out the resulting SQL */
1272                 ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
1273         }
1274         AST_RWLIST_UNLOCK(&queries);
1275         return CLI_SUCCESS;
1276 }
1277
1278 static struct ast_cli_entry cli_func_odbc[] = {
1279         AST_CLI_DEFINE(cli_odbc_write, "Test setting a func_odbc function"),
1280         AST_CLI_DEFINE(cli_odbc_read, "Test reading a func_odbc function"),
1281 };
1282
1283 static int load_module(void)
1284 {
1285         int res = 0;
1286         struct ast_config *cfg;
1287         char *catg;
1288         struct ast_flags config_flags = { 0 };
1289
1290         res |= ast_custom_function_register(&fetch_function);
1291         res |= ast_register_application_xml(app_odbcfinish, exec_odbcfinish);
1292         AST_RWLIST_WRLOCK(&queries);
1293
1294         cfg = ast_config_load(config, config_flags);
1295         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
1296                 ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
1297                 AST_RWLIST_UNLOCK(&queries);
1298                 return AST_MODULE_LOAD_DECLINE;
1299         }
1300
1301         for (catg = ast_category_browse(cfg, NULL);
1302              catg;
1303              catg = ast_category_browse(cfg, catg)) {
1304                 struct acf_odbc_query *query = NULL;
1305                 int err;
1306
1307                 if ((err = init_acf_query(cfg, catg, &query))) {
1308                         if (err == ENOMEM)
1309                                 ast_log(LOG_ERROR, "Out of memory\n");
1310                         else if (err == EINVAL)
1311                                 ast_log(LOG_ERROR, "Invalid parameters for category %s\n", catg);
1312                         else
1313                                 ast_log(LOG_ERROR, "%s (%d)\n", strerror(err), err);
1314                 } else {
1315                         AST_RWLIST_INSERT_HEAD(&queries, query, list);
1316                         ast_custom_function_register(query->acf);
1317                 }
1318         }
1319
1320         ast_config_destroy(cfg);
1321         res |= ast_custom_function_register(&escape_function);
1322         ast_cli_register_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
1323
1324         AST_RWLIST_UNLOCK(&queries);
1325         return res;
1326 }
1327
1328 static int unload_module(void)
1329 {
1330         struct acf_odbc_query *query;
1331         int res = 0;
1332
1333         AST_RWLIST_WRLOCK(&queries);
1334         while (!AST_RWLIST_EMPTY(&queries)) {
1335                 query = AST_RWLIST_REMOVE_HEAD(&queries, list);
1336                 ast_custom_function_unregister(query->acf);
1337                 free_acf_query(query);
1338         }
1339
1340         res |= ast_custom_function_unregister(&escape_function);
1341         res |= ast_custom_function_unregister(&fetch_function);
1342         res |= ast_unregister_application(app_odbcfinish);
1343         ast_cli_unregister_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
1344
1345         /* Allow any threads waiting for this lock to pass (avoids a race) */
1346         AST_RWLIST_UNLOCK(&queries);
1347         usleep(1);
1348         AST_RWLIST_WRLOCK(&queries);
1349
1350         AST_RWLIST_UNLOCK(&queries);
1351         return 0;
1352 }
1353
1354 static int reload(void)
1355 {
1356         int res = 0;
1357         struct ast_config *cfg;
1358         struct acf_odbc_query *oldquery;
1359         char *catg;
1360         struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
1361
1362         cfg = ast_config_load(config, config_flags);
1363         if (cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
1364                 return 0;
1365
1366         AST_RWLIST_WRLOCK(&queries);
1367
1368         while (!AST_RWLIST_EMPTY(&queries)) {
1369                 oldquery = AST_RWLIST_REMOVE_HEAD(&queries, list);
1370                 ast_custom_function_unregister(oldquery->acf);
1371                 free_acf_query(oldquery);
1372         }
1373
1374         if (!cfg) {
1375                 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
1376                 goto reload_out;
1377         }
1378
1379         for (catg = ast_category_browse(cfg, NULL);
1380              catg;
1381              catg = ast_category_browse(cfg, catg)) {
1382                 struct acf_odbc_query *query = NULL;
1383
1384                 if (init_acf_query(cfg, catg, &query)) {
1385                         ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
1386                 } else {
1387                         AST_RWLIST_INSERT_HEAD(&queries, query, list);
1388                         ast_custom_function_register(query->acf);
1389                 }
1390         }
1391
1392         ast_config_destroy(cfg);
1393 reload_out:
1394         AST_RWLIST_UNLOCK(&queries);
1395         return res;
1396 }
1397
1398 /* XXX need to revise usecount - set if query_lock is set */
1399
1400 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
1401                 .load = load_module,
1402                 .unload = unload_module,
1403                 .reload = reload,
1404                );
1405