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