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