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