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