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