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