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