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