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