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