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