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