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