BuildSystem: Depend not implicitly but explicitly on external libraries.
[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         <depend>generic_odbc</depend>
33         <support_level>core</support_level>
34  ***/
35
36 #include "asterisk.h"
37
38 #include "asterisk/module.h"
39 #include "asterisk/file.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/config.h"
43 #include "asterisk/res_odbc.h"
44 #include "asterisk/res_odbc_transaction.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 #define DEFAULT_SINGLE_DB_CONNECTION 0
104
105 static int single_db_connection;
106
107 AST_RWLOCK_DEFINE_STATIC(single_db_connection_lock);
108
109 enum odbc_option_flags {
110         OPT_ESCAPECOMMAS =      (1 << 0),
111         OPT_MULTIROW     =      (1 << 1),
112 };
113
114 struct acf_odbc_query {
115         AST_RWLIST_ENTRY(acf_odbc_query) list;
116         char readhandle[5][30];
117         char writehandle[5][30];
118         char *sql_read;
119         char *sql_write;
120         char *sql_insert;
121         unsigned int flags;
122         int rowlimit;
123         struct ast_custom_function *acf;
124 };
125
126 static void odbc_datastore_free(void *data);
127
128 static const struct ast_datastore_info odbc_info = {
129         .type = "FUNC_ODBC",
130         .destroy = odbc_datastore_free,
131 };
132
133 /* For storing each result row */
134 struct odbc_datastore_row {
135         AST_LIST_ENTRY(odbc_datastore_row) list;
136         char data[0];
137 };
138
139 /* For storing each result set */
140 struct odbc_datastore {
141         AST_LIST_HEAD(, odbc_datastore_row);
142         char names[0];
143 };
144
145 /* \brief Data source name
146  *
147  * This holds data that pertains to a DSN
148  */
149 struct dsn {
150         /*! A connection to the database */
151         struct odbc_obj *connection;
152         /*! The name of the DSN as defined in res_odbc.conf */
153         char name[0];
154 };
155
156 #define DSN_BUCKETS 37
157
158 struct ao2_container *dsns;
159
160 static int dsn_hash(const void *obj, const int flags)
161 {
162         const struct dsn *object;
163         const char *key;
164
165         switch (flags & OBJ_SEARCH_MASK) {
166         case OBJ_SEARCH_KEY:
167                 key = obj;
168                 break;
169         case OBJ_SEARCH_OBJECT:
170                 object = obj;
171                 key = object->name;
172                 break;
173         default:
174                 ast_assert(0);
175                 return 0;
176         }
177         return ast_str_hash(key);
178 }
179
180 static int dsn_cmp(void *obj, void *arg, int flags)
181 {
182         const struct dsn *object_left = obj;
183         const struct dsn *object_right = arg;
184         const char *right_key = arg;
185         int cmp;
186
187         switch (flags & OBJ_SEARCH_MASK) {
188         case OBJ_SEARCH_OBJECT:
189                 right_key = object_right->name;
190                 /* Fall through */
191         case OBJ_SEARCH_KEY:
192                 cmp = strcmp(object_left->name, right_key);
193                 break;
194         case OBJ_SEARCH_PARTIAL_KEY:
195                 cmp = strncmp(object_left->name, right_key, strlen(right_key));
196                 break;
197         default:
198                 cmp = 0;
199                 break;
200         }
201
202         if (cmp) {
203                 return 0;
204         }
205
206         return CMP_MATCH;
207 }
208
209 static void dsn_destructor(void *obj)
210 {
211         struct dsn *dsn = obj;
212
213         if (dsn->connection) {
214                 ast_odbc_release_obj(dsn->connection);
215         }
216 }
217
218 /*!
219  * \brief Create a DSN and connect to the database
220  *
221  * \param name The name of the DSN as found in res_odbc.conf
222  * \retval NULL Fail
223  * \retval non-NULL The newly-created structure
224  */
225 static struct dsn *create_dsn(const char *name)
226 {
227         struct dsn *dsn;
228
229         if (!dsns) {
230                 return NULL;
231         }
232
233         dsn = ao2_alloc(sizeof(*dsn) + strlen(name) + 1, dsn_destructor);
234         if (!dsn) {
235                 return NULL;
236         }
237
238         /* Safe */
239         strcpy(dsn->name, name);
240
241         dsn->connection = ast_odbc_request_obj(name, 0);
242         if (!dsn->connection) {
243                 ao2_ref(dsn, -1);
244                 return NULL;
245         }
246
247         if (!ao2_link_flags(dsns, dsn, OBJ_NOLOCK)) {
248                 ao2_ref(dsn, -1);
249                 return NULL;
250         }
251
252         return dsn;
253 }
254
255 static SQLHSTMT silent_execute(struct odbc_obj *obj, void *data);
256
257 /*!
258  * \brief Determine if the connection has died.
259  *
260  * \param connection The connection to check
261  * \retval 1 Yep, it's dead
262  * \retval 0 It's alive and well
263  */
264 static int connection_dead(struct odbc_obj *connection)
265 {
266         SQLINTEGER dead;
267         SQLRETURN res;
268         SQLHSTMT stmt;
269
270         if (!connection) {
271                 return 1;
272         }
273
274         res = SQLGetConnectAttr(connection->con, SQL_ATTR_CONNECTION_DEAD, &dead, 0, 0);
275         if (SQL_SUCCEEDED(res)) {
276                 return dead == SQL_CD_TRUE ? 1 : 0;
277         }
278
279         /* If the Driver doesn't support SQL_ATTR_CONNECTION_DEAD do a direct
280          * execute of a probing statement and see if that succeeds instead
281          */
282         stmt = ast_odbc_direct_execute(connection, silent_execute, "SELECT 1");
283         if (!stmt) {
284                 return 1;
285         }
286
287         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
288         return 0;
289 }
290
291 /*!
292  * \brief Retrieve a DSN, or create it if it does not exist.
293  *
294  * The created DSN is returned locked. This should be inconsequential
295  * to callers in most cases.
296  *
297  * When finished with the returned structure, the caller must call
298  * \ref release_dsn
299  *
300  * \param name Name of the DSN as found in res_odbc.conf
301  * \retval NULL Unable to retrieve or create the DSN
302  * \retval non-NULL The retrieved/created locked DSN
303  */
304 static struct dsn *get_dsn(const char *name)
305 {
306         struct dsn *dsn;
307
308         if (!dsns) {
309                 return NULL;
310         }
311
312         ao2_lock(dsns);
313         dsn = ao2_find(dsns, name, OBJ_SEARCH_KEY | OBJ_NOLOCK);
314         if (!dsn) {
315                 dsn = create_dsn(name);
316         }
317         ao2_unlock(dsns);
318
319         if (!dsn) {
320                 return NULL;
321         }
322
323         ao2_lock(dsn);
324         if (!dsn->connection) {
325                 dsn->connection = ast_odbc_request_obj(name, 0);
326                 if (!dsn->connection) {
327                         ao2_unlock(dsn);
328                         ao2_ref(dsn, -1);
329                         return NULL;
330                 }
331                 return dsn;
332         }
333
334         if (connection_dead(dsn->connection)) {
335                 ast_odbc_release_obj(dsn->connection);
336                 dsn->connection = ast_odbc_request_obj(name, 0);
337                 if (!dsn->connection) {
338                         ao2_unlock(dsn);
339                         ao2_ref(dsn, -1);
340                         return NULL;
341                 }
342         }
343
344         return dsn;
345 }
346
347 /*!
348  * \brief Get a DB handle via a DSN or directly
349  *
350  * If single db connection then get the DB handle via DSN
351  * else by requesting a connection directly
352  *
353  * \param dsn_name Name of the DSN as found in res_odbc.conf
354  * \param dsn The pointer to the DSN
355  * \retval NULL Unable to retrieve the DB handle
356  * \retval non-NULL The retrieved DB handle
357  */
358 static struct odbc_obj *get_odbc_obj(const char *dsn_name, struct dsn **dsn)
359 {
360         struct odbc_obj *obj = NULL;
361
362         ast_rwlock_rdlock(&single_db_connection_lock);
363         if (single_db_connection) {
364                 if (dsn) {
365                         *dsn = get_dsn(dsn_name);
366                         if (*dsn) {
367                                 obj = (*dsn)->connection;
368                         }
369                 }
370         } else {
371                 obj = ast_odbc_request_obj(dsn_name, 0);
372         }
373         ast_rwlock_unlock(&single_db_connection_lock);
374
375         return obj;
376 }
377
378 /*!
379  * \brief Release an ODBC obj or a DSN
380  *
381  * If single db connection then unlock and unreference the DSN
382  * else release the ODBC obj
383  *
384  * \param obj The pointer to the ODBC obj to release
385  * \param dsn The pointer to the dsn to unlock and unreference
386  */
387 static inline void release_obj_or_dsn(struct odbc_obj **obj, struct dsn **dsn)
388 {
389         if (dsn && *dsn) {
390                 /* If multiple connections are not enabled then the guarantee
391                  * of a single connection already exists and holding on to the
392                  * connection would prevent any other user from acquiring it
393                  * indefinitely.
394                  */
395                 if (ast_odbc_get_max_connections((*dsn)->name) < 2) {
396                         ast_odbc_release_obj((*dsn)->connection);
397                         (*dsn)->connection = NULL;
398                 }
399                 ao2_unlock(*dsn);
400                 ao2_ref(*dsn, -1);
401                 *dsn = NULL;
402                 /* Some callers may provide both an obj and dsn. To ensure that
403                  * the connection is not released twice we set it to NULL here if
404                  * present.
405                  */
406                 if (obj) {
407                         *obj = NULL;
408                 }
409         } else if (obj && *obj) {
410                 ast_odbc_release_obj(*obj);
411                 *obj = NULL;
412         }
413 }
414
415 static AST_RWLIST_HEAD_STATIC(queries, acf_odbc_query);
416
417 static int resultcount = 0;
418
419 AST_THREADSTORAGE(sql_buf);
420 AST_THREADSTORAGE(sql2_buf);
421 AST_THREADSTORAGE(coldata_buf);
422 AST_THREADSTORAGE(colnames_buf);
423
424 static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len);
425
426 static void odbc_datastore_free(void *data)
427 {
428         struct odbc_datastore *result = data;
429         struct odbc_datastore_row *row;
430
431         if (!result) {
432                 return;
433         }
434
435         AST_LIST_LOCK(result);
436         while ((row = AST_LIST_REMOVE_HEAD(result, list))) {
437                 ast_free(row);
438         }
439         AST_LIST_UNLOCK(result);
440         AST_LIST_HEAD_DESTROY(result);
441         ast_free(result);
442 }
443
444 /*!
445  * \brief Common execution function for SQL queries.
446  *
447  * \param obj DB connection
448  * \param data The query to execute
449  * \param silent If true, do not print warnings on failure
450  * \retval NULL Failed to execute query
451  * \retval non-NULL The executed statement
452  */
453 static SQLHSTMT execute(struct odbc_obj *obj, void *data, int silent)
454 {
455         int res;
456         char *sql = data;
457         SQLHSTMT stmt;
458
459         res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
460         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
461                 ast_log(LOG_WARNING, "SQL Alloc Handle failed (%d)!\n", res);
462                 return NULL;
463         }
464
465         res = SQLExecDirect(stmt, (unsigned char *)sql, SQL_NTS);
466         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
467                 if (res == SQL_ERROR && !silent) {
468                         int i;
469                         SQLINTEGER nativeerror=0, numfields=0;
470                         SQLSMALLINT diagbytes=0;
471                         unsigned char state[10], diagnostic[256];
472
473                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
474                         for (i = 0; i < numfields; i++) {
475                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
476                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
477                                 if (i > 10) {
478                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
479                                         break;
480                                 }
481                         }
482                 }
483
484                 if (!silent) {
485                         ast_log(LOG_WARNING, "SQL Exec Direct failed (%d)![%s]\n", res, sql);
486                 }
487                 SQLCloseCursor(stmt);
488                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
489                 return NULL;
490         }
491
492         return stmt;
493 }
494
495 static SQLHSTMT generic_execute(struct odbc_obj *obj, void *data)
496 {
497         return execute(obj, data, 0);
498 }
499
500 static SQLHSTMT silent_execute(struct odbc_obj *obj, void *data)
501 {
502         return execute(obj, data, 1);
503 }
504
505 /*
506  * Master control routine
507  */
508 static int acf_odbc_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
509 {
510         struct odbc_obj *obj = NULL;
511         struct acf_odbc_query *query;
512         char *t, varname[15];
513         int i, dsn_num, bogus_chan = 0;
514         int transactional = 0;
515         AST_DECLARE_APP_ARGS(values,
516                 AST_APP_ARG(field)[100];
517         );
518         AST_DECLARE_APP_ARGS(args,
519                 AST_APP_ARG(field)[100];
520         );
521         SQLHSTMT stmt = NULL;
522         SQLLEN rows=0;
523         struct ast_str *buf = ast_str_thread_get(&sql_buf, 16);
524         struct ast_str *insertbuf = ast_str_thread_get(&sql2_buf, 16);
525         const char *status = "FAILURE";
526         struct dsn *dsn = NULL;
527
528         if (!buf || !insertbuf) {
529                 return -1;
530         }
531
532         AST_RWLIST_RDLOCK(&queries);
533         AST_RWLIST_TRAVERSE(&queries, query, list) {
534                 if (!strcmp(query->acf->name, cmd)) {
535                         break;
536                 }
537         }
538
539         if (!query) {
540                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
541                 AST_RWLIST_UNLOCK(&queries);
542                 if (chan) {
543                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
544                 }
545                 return -1;
546         }
547
548         if (!chan) {
549                 if (!(chan = ast_dummy_channel_alloc())) {
550                         AST_RWLIST_UNLOCK(&queries);
551                         return -1;
552                 }
553                 bogus_chan = 1;
554         }
555
556         if (!bogus_chan) {
557                 ast_autoservice_start(chan);
558         }
559
560         ast_str_make_space(&buf, strlen(query->sql_write) * 2 + 300);
561         /* We only get here if sql_write is set. sql_insert is optional however. */
562         if (query->sql_insert) {
563                 ast_str_make_space(&insertbuf, strlen(query->sql_insert) * 2 + 300);
564         }
565
566         /* Parse our arguments */
567         t = value ? ast_strdupa(value) : "";
568
569         if (!s || !t) {
570                 ast_log(LOG_ERROR, "Out of memory\n");
571                 AST_RWLIST_UNLOCK(&queries);
572                 if (!bogus_chan) {
573                         ast_autoservice_stop(chan);
574                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
575                 } else {
576                         ast_channel_unref(chan);
577                 }
578                 return -1;
579         }
580
581         AST_STANDARD_APP_ARGS(args, s);
582         for (i = 0; i < args.argc; i++) {
583                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
584                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
585         }
586
587         /* Parse values, just like arguments */
588         AST_STANDARD_APP_ARGS(values, t);
589         for (i = 0; i < values.argc; i++) {
590                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
591                 pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
592         }
593
594         /* Additionally set the value as a whole (but push an empty string if value is NULL) */
595         pbx_builtin_pushvar_helper(chan, "VALUE", value ? value : "");
596
597         ast_str_substitute_variables(&buf, 0, chan, query->sql_write);
598         if (query->sql_insert) {
599                 ast_str_substitute_variables(&insertbuf, 0, chan, query->sql_insert);
600         }
601
602         if (bogus_chan) {
603                 chan = ast_channel_unref(chan);
604         } else {
605                 /* Restore prior values */
606                 for (i = 0; i < args.argc; i++) {
607                         snprintf(varname, sizeof(varname), "ARG%d", i + 1);
608                         pbx_builtin_setvar_helper(chan, varname, NULL);
609                 }
610
611                 for (i = 0; i < values.argc; i++) {
612                         snprintf(varname, sizeof(varname), "VAL%d", i + 1);
613                         pbx_builtin_setvar_helper(chan, varname, NULL);
614                 }
615                 pbx_builtin_setvar_helper(chan, "VALUE", NULL);
616         }
617
618         /*!\note
619          * Okay, this part is confusing.  Transactions belong to a single database
620          * handle.  Therefore, when working with transactions, we CANNOT failover
621          * to multiple DSNs.  We MUST have a single handle all the way through the
622          * transaction, or else we CANNOT enforce atomicity.
623          */
624         for (dsn_num = 0; dsn_num < 5; dsn_num++) {
625                 if (!ast_strlen_zero(query->writehandle[dsn_num])) {
626                         if (transactional) {
627                                 /* This can only happen second time through or greater. */
628                                 ast_log(LOG_WARNING, "Transactions do not work well with multiple DSNs for 'writehandle'\n");
629                         }
630
631                         if ((obj = ast_odbc_retrieve_transaction_obj(chan, query->writehandle[dsn_num]))) {
632                                 transactional = 1;
633                         } else {
634                                 obj = get_odbc_obj(query->writehandle[dsn_num], &dsn);
635                                 transactional = 0;
636                         }
637
638                         if (obj && (stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(buf)))) {
639                                 break;
640                         }
641                         if (!transactional) {
642                                 release_obj_or_dsn (&obj, &dsn);
643                         }
644                 }
645         }
646
647         if (stmt) {
648                 SQLRowCount(stmt, &rows);
649                 SQLCloseCursor(stmt);
650                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
651
652                 if (rows != 0) {
653                         status = "SUCCESS";
654
655                 } else if (query->sql_insert) {
656                         if (!transactional) {
657                                 release_obj_or_dsn (&obj, &dsn);
658                         }
659
660                         for (transactional = 0, dsn_num = 0; dsn_num < 5; dsn_num++) {
661                                 if (!ast_strlen_zero(query->writehandle[dsn_num])) {
662                                         if (transactional) {
663                                                 /* This can only happen second time through or greater. */
664                                                 ast_log(LOG_WARNING, "Transactions do not work well with multiple DSNs for 'writehandle'\n");
665                                         } else {
666                                                 release_obj_or_dsn (&obj, &dsn);
667                                         }
668
669                                         if ((obj = ast_odbc_retrieve_transaction_obj(chan, query->writehandle[dsn_num]))) {
670                                                 transactional = 1;
671                                         } else {
672                                                 obj = get_odbc_obj(query->writehandle[dsn_num], &dsn);
673                                                 transactional = 0;
674                                         }
675                                         if (obj) {
676                                                 stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(insertbuf));
677                                         }
678                                 }
679                                 if (stmt) {
680                                         status = "FAILOVER";
681                                         SQLRowCount(stmt, &rows);
682                                         SQLCloseCursor(stmt);
683                                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
684                                         break;
685                                 }
686                         }
687                 }
688         }
689
690         AST_RWLIST_UNLOCK(&queries);
691
692         /* Output the affected rows, for all cases.  In the event of failure, we
693          * flag this as -1 rows.  Note that this is different from 0 affected rows
694          * which would be the case if we succeeded in our query, but the values did
695          * not change. */
696         if (!bogus_chan) {
697                 snprintf(varname, sizeof(varname), "%d", (int)rows);
698                 pbx_builtin_setvar_helper(chan, "ODBCROWS", varname);
699                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
700         }
701
702         if (!transactional) {
703                 release_obj_or_dsn (&obj, &dsn);
704         }
705
706         if (!bogus_chan) {
707                 ast_autoservice_stop(chan);
708         }
709
710         return 0;
711 }
712
713 static int acf_odbc_read(struct ast_channel *chan, const char *cmd, char *s, char *buf, size_t len)
714 {
715         struct odbc_obj *obj = NULL;
716         struct acf_odbc_query *query;
717         char varname[15], rowcount[12] = "-1";
718         struct ast_str *colnames = ast_str_thread_get(&colnames_buf, 16);
719         int res, x, y, buflen = 0, escapecommas, rowlimit = 1, multirow = 0, dsn_num, bogus_chan = 0;
720         AST_DECLARE_APP_ARGS(args,
721                 AST_APP_ARG(field)[100];
722         );
723         SQLHSTMT stmt = NULL;
724         SQLSMALLINT colcount=0;
725         SQLLEN indicator;
726         SQLSMALLINT collength;
727         struct odbc_datastore *resultset = NULL;
728         struct odbc_datastore_row *row = NULL;
729         struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
730         const char *status = "FAILURE";
731         struct dsn *dsn = NULL;
732
733         if (!sql || !colnames) {
734                 if (chan) {
735                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
736                 }
737                 return -1;
738         }
739
740         ast_str_reset(colnames);
741
742         AST_RWLIST_RDLOCK(&queries);
743         AST_RWLIST_TRAVERSE(&queries, query, list) {
744                 if (!strcmp(query->acf->name, cmd)) {
745                         break;
746                 }
747         }
748
749         if (!query) {
750                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
751                 AST_RWLIST_UNLOCK(&queries);
752                 if (chan) {
753                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
754                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
755                 }
756                 return -1;
757         }
758
759         if (!chan) {
760                 if (!(chan = ast_dummy_channel_alloc())) {
761                         AST_RWLIST_UNLOCK(&queries);
762                         return -1;
763                 }
764                 bogus_chan = 1;
765         }
766
767         if (!bogus_chan) {
768                 ast_autoservice_start(chan);
769         }
770
771         AST_STANDARD_APP_ARGS(args, s);
772         for (x = 0; x < args.argc; x++) {
773                 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
774                 pbx_builtin_pushvar_helper(chan, varname, args.field[x]);
775         }
776
777         ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
778
779         if (bogus_chan) {
780                 chan = ast_channel_unref(chan);
781         } else {
782                 /* Restore prior values */
783                 for (x = 0; x < args.argc; x++) {
784                         snprintf(varname, sizeof(varname), "ARG%d", x + 1);
785                         pbx_builtin_setvar_helper(chan, varname, NULL);
786                 }
787         }
788
789         /* Save these flags, so we can release the lock */
790         escapecommas = ast_test_flag(query, OPT_ESCAPECOMMAS);
791         if (!bogus_chan && ast_test_flag(query, OPT_MULTIROW)) {
792                 if (!(resultset = ast_calloc(1, sizeof(*resultset)))) {
793                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
794                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
795                         AST_RWLIST_UNLOCK(&queries);
796                         ast_autoservice_stop(chan);
797                         return -1;
798                 }
799                 AST_LIST_HEAD_INIT(resultset);
800                 if (query->rowlimit) {
801                         rowlimit = query->rowlimit;
802                 } else {
803                         rowlimit = INT_MAX;
804                 }
805                 multirow = 1;
806         } else if (!bogus_chan) {
807                 if (query->rowlimit > 1) {
808                         rowlimit = query->rowlimit;
809                         if (!(resultset = ast_calloc(1, sizeof(*resultset)))) {
810                                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
811                                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
812                                 AST_RWLIST_UNLOCK(&queries);
813                                 ast_autoservice_stop(chan);
814                                 return -1;
815                         }
816                         AST_LIST_HEAD_INIT(resultset);
817                 }
818         }
819         AST_RWLIST_UNLOCK(&queries);
820
821         for (dsn_num = 0; dsn_num < 5; dsn_num++) {
822                 if (!ast_strlen_zero(query->readhandle[dsn_num])) {
823                         obj = get_odbc_obj(query->readhandle[dsn_num], &dsn);
824                         if (!obj) {
825                                 continue;
826                         }
827                         stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql));
828                 }
829                 if (stmt) {
830                         break;
831                 }
832                 release_obj_or_dsn (&obj, &dsn);
833         }
834
835         if (!stmt) {
836                 ast_log(LOG_ERROR, "Unable to execute query [%s]\n", ast_str_buffer(sql));
837                 release_obj_or_dsn (&obj, &dsn);
838                 if (!bogus_chan) {
839                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
840                         ast_autoservice_stop(chan);
841                 }
842                 odbc_datastore_free(resultset);
843                 return -1;
844         }
845
846         res = SQLNumResultCols(stmt, &colcount);
847         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
848                 ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
849                 SQLCloseCursor(stmt);
850                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
851                 release_obj_or_dsn (&obj, &dsn);
852                 if (!bogus_chan) {
853                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
854                         ast_autoservice_stop(chan);
855                 }
856                 odbc_datastore_free(resultset);
857                 return -1;
858         }
859
860         res = SQLFetch(stmt);
861         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
862                 int res1 = -1;
863                 if (res == SQL_NO_DATA) {
864                         ast_verb(4, "Found no rows [%s]\n", ast_str_buffer(sql));
865                         res1 = 0;
866                         buf[0] = '\0';
867                         ast_copy_string(rowcount, "0", sizeof(rowcount));
868                         status = "NODATA";
869                 } else {
870                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
871                         status = "FETCHERROR";
872                 }
873                 SQLCloseCursor(stmt);
874                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
875                 release_obj_or_dsn (&obj, &dsn);
876                 if (!bogus_chan) {
877                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
878                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
879                         ast_autoservice_stop(chan);
880                 }
881                 odbc_datastore_free(resultset);
882                 return res1;
883         }
884
885         status = "SUCCESS";
886
887         for (y = 0; y < rowlimit; y++) {
888                 buf[0] = '\0';
889                 for (x = 0; x < colcount; x++) {
890                         int i;
891                         struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
892                         char *ptrcoldata;
893
894                         if (!coldata) {
895                                 odbc_datastore_free(resultset);
896                                 SQLCloseCursor(stmt);
897                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
898                                 release_obj_or_dsn (&obj, &dsn);
899                                 if (!bogus_chan) {
900                                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
901                                         ast_autoservice_stop(chan);
902                                 }
903                                 return -1;
904                         }
905
906                         if (y == 0) {
907                                 char colname[256];
908                                 SQLULEN maxcol = 0;
909
910                                 res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
911                                 ast_debug(3, "Got collength of %d and maxcol of %d for column '%s' (offset %d)\n", (int)collength, (int)maxcol, colname, x);
912                                 if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
913                                         snprintf(colname, sizeof(colname), "field%d", x);
914                                 }
915
916                                 ast_str_make_space(&coldata, maxcol + 1);
917
918                                 if (ast_str_strlen(colnames)) {
919                                         ast_str_append(&colnames, 0, ",");
920                                 }
921                                 ast_str_append_escapecommas(&colnames, 0, colname, sizeof(colname));
922
923                                 if (resultset) {
924                                         void *tmp = ast_realloc(resultset, sizeof(*resultset) + ast_str_strlen(colnames) + 1);
925                                         if (!tmp) {
926                                                 ast_log(LOG_ERROR, "No space for a new resultset?\n");
927                                                 odbc_datastore_free(resultset);
928                                                 SQLCloseCursor(stmt);
929                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
930                                                 release_obj_or_dsn (&obj, &dsn);
931                                                 if (!bogus_chan) {
932                                                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
933                                                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
934                                                         ast_autoservice_stop(chan);
935                                                 }
936                                                 return -1;
937                                         }
938                                         resultset = tmp;
939                                         strcpy((char *)resultset + sizeof(*resultset), ast_str_buffer(colnames));
940                                 }
941                         }
942
943                         buflen = strlen(buf);
944                         res = ast_odbc_ast_str_SQLGetData(&coldata, -1, stmt, x + 1, SQL_CHAR, &indicator);
945                         if (indicator == SQL_NULL_DATA) {
946                                 ast_debug(3, "Got NULL data\n");
947                                 ast_str_reset(coldata);
948                                 res = SQL_SUCCESS;
949                         }
950
951                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
952                                 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", ast_str_buffer(sql));
953                                 y = -1;
954                                 buf[0] = '\0';
955                                 goto end_acf_read;
956                         }
957
958                         ast_debug(2, "Got coldata of '%s'\n", ast_str_buffer(coldata));
959
960                         if (x) {
961                                 buf[buflen++] = ',';
962                         }
963
964                         /* Copy data, encoding '\' and ',' for the argument parser */
965                         ptrcoldata = ast_str_buffer(coldata);
966                         for (i = 0; i < ast_str_strlen(coldata); i++) {
967                                 if (escapecommas && (ptrcoldata[i] == '\\' || ptrcoldata[i] == ',')) {
968                                         buf[buflen++] = '\\';
969                                 }
970                                 buf[buflen++] = ptrcoldata[i];
971
972                                 if (buflen >= len - 2) {
973                                         break;
974                                 }
975
976                                 if (ptrcoldata[i] == '\0') {
977                                         break;
978                                 }
979                         }
980
981                         buf[buflen] = '\0';
982                         ast_debug(2, "buf is now set to '%s'\n", buf);
983                 }
984                 ast_debug(2, "buf is now set to '%s'\n", buf);
985
986                 if (resultset) {
987                         row = ast_calloc(1, sizeof(*row) + buflen + 1);
988                         if (!row) {
989                                 ast_log(LOG_ERROR, "Unable to allocate space for more rows in this resultset.\n");
990                                 status = "MEMERROR";
991                                 goto end_acf_read;
992                         }
993                         strcpy((char *)row + sizeof(*row), buf);
994                         AST_LIST_INSERT_TAIL(resultset, row, list);
995
996                         /* Get next row */
997                         res = SQLFetch(stmt);
998                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
999                                 if (res != SQL_NO_DATA) {
1000                                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
1001                                 }
1002                                 /* Number of rows in the resultset */
1003                                 y++;
1004                                 break;
1005                         }
1006                 }
1007         }
1008
1009 end_acf_read:
1010         if (!bogus_chan) {
1011                 snprintf(rowcount, sizeof(rowcount), "%d", y);
1012                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
1013                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
1014                 pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", ast_str_buffer(colnames));
1015                 if (resultset) {
1016                         struct ast_datastore *odbc_store;
1017                         if (multirow) {
1018                                 int uid;
1019                                 uid = ast_atomic_fetchadd_int(&resultcount, +1) + 1;
1020                                 snprintf(buf, len, "%d", uid);
1021                         } else {
1022                                 /* Name of the query is name of the resultset */
1023                                 ast_copy_string(buf, cmd, len);
1024
1025                                 /* If there's one with the same name already, free it */
1026                                 ast_channel_lock(chan);
1027                                 if ((odbc_store = ast_channel_datastore_find(chan, &odbc_info, buf))) {
1028                                         ast_channel_datastore_remove(chan, odbc_store);
1029                                         ast_datastore_free(odbc_store);
1030                                 }
1031                                 ast_channel_unlock(chan);
1032                         }
1033                         odbc_store = ast_datastore_alloc(&odbc_info, buf);
1034                         if (!odbc_store) {
1035                                 ast_log(LOG_ERROR, "Rows retrieved, but unable to store it in the channel.  Results fail.\n");
1036                                 odbc_datastore_free(resultset);
1037                                 SQLCloseCursor(stmt);
1038                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1039                                 release_obj_or_dsn (&obj, &dsn);
1040                                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
1041                                 ast_autoservice_stop(chan);
1042                                 return -1;
1043                         }
1044                         odbc_store->data = resultset;
1045                         ast_channel_lock(chan);
1046                         ast_channel_datastore_add(chan, odbc_store);
1047                         ast_channel_unlock(chan);
1048                 }
1049         }
1050         SQLCloseCursor(stmt);
1051         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1052         release_obj_or_dsn (&obj, &dsn);
1053         if (resultset && !multirow) {
1054                 /* Fetch the first resultset */
1055                 if (!acf_fetch(chan, "", buf, buf, len)) {
1056                         buf[0] = '\0';
1057                 }
1058         }
1059         if (!bogus_chan) {
1060                 ast_autoservice_stop(chan);
1061         }
1062         return 0;
1063 }
1064
1065 static int acf_escape(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1066 {
1067         char *out = buf;
1068
1069         for (; *data && out - buf < len; data++) {
1070                 if (*data == '\'') {
1071                         *out = '\'';
1072                         out++;
1073                 }
1074                 *out++ = *data;
1075         }
1076         *out = '\0';
1077
1078         return 0;
1079 }
1080
1081 static struct ast_custom_function escape_function = {
1082         .name = "SQL_ESC",
1083         .read = acf_escape,
1084         .write = NULL,
1085 };
1086
1087 static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1088 {
1089         struct ast_datastore *store;
1090         struct odbc_datastore *resultset;
1091         struct odbc_datastore_row *row;
1092
1093         if (!chan) {
1094                 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
1095                 return -1;
1096         }
1097
1098         ast_channel_lock(chan);
1099         store = ast_channel_datastore_find(chan, &odbc_info, data);
1100         if (!store) {
1101                 ast_channel_unlock(chan);
1102                 pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
1103                 return -1;
1104         }
1105         resultset = store->data;
1106         AST_LIST_LOCK(resultset);
1107         row = AST_LIST_REMOVE_HEAD(resultset, list);
1108         AST_LIST_UNLOCK(resultset);
1109         if (!row) {
1110                 /* Cleanup datastore */
1111                 ast_channel_datastore_remove(chan, store);
1112                 ast_datastore_free(store);
1113                 ast_channel_unlock(chan);
1114                 pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
1115                 return -1;
1116         }
1117         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", resultset->names);
1118         ast_channel_unlock(chan);
1119         ast_copy_string(buf, row->data, len);
1120         ast_free(row);
1121         pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "SUCCESS");
1122         return 0;
1123 }
1124
1125 static struct ast_custom_function fetch_function = {
1126         .name = "ODBC_FETCH",
1127         .read = acf_fetch,
1128         .write = NULL,
1129 };
1130
1131 static char *app_odbcfinish = "ODBCFinish";
1132
1133 static int exec_odbcfinish(struct ast_channel *chan, const char *data)
1134 {
1135         struct ast_datastore *store;
1136
1137         ast_channel_lock(chan);
1138         store = ast_channel_datastore_find(chan, &odbc_info, data);
1139         if (store) {
1140                 ast_channel_datastore_remove(chan, store);
1141                 ast_datastore_free(store);
1142         }
1143         ast_channel_unlock(chan);
1144         return 0;
1145 }
1146
1147 static int free_acf_query(struct acf_odbc_query *query)
1148 {
1149         if (query) {
1150                 if (query->acf) {
1151                         if (query->acf->name)
1152                                 ast_free((char *)query->acf->name);
1153                         ast_string_field_free_memory(query->acf);
1154                         ast_free(query->acf);
1155                 }
1156                 ast_free(query->sql_read);
1157                 ast_free(query->sql_write);
1158                 ast_free(query->sql_insert);
1159                 ast_free(query);
1160         }
1161         return 0;
1162 }
1163
1164 static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
1165 {
1166         const char *tmp;
1167         const char *tmp2;
1168         int i;
1169
1170         if (!cfg || !catg) {
1171                 return EINVAL;
1172         }
1173
1174         if (!(*query = ast_calloc(1, sizeof(**query)))) {
1175                 return ENOMEM;
1176         }
1177
1178         if (((tmp = ast_variable_retrieve(cfg, catg, "writehandle"))) || ((tmp = ast_variable_retrieve(cfg, catg, "dsn")))) {
1179                 char *tmp2 = ast_strdupa(tmp);
1180                 AST_DECLARE_APP_ARGS(writeconf,
1181                         AST_APP_ARG(dsn)[5];
1182                 );
1183                 AST_STANDARD_APP_ARGS(writeconf, tmp2);
1184                 for (i = 0; i < 5; i++) {
1185                         if (!ast_strlen_zero(writeconf.dsn[i]))
1186                                 ast_copy_string((*query)->writehandle[i], writeconf.dsn[i], sizeof((*query)->writehandle[i]));
1187                 }
1188         }
1189
1190         if ((tmp = ast_variable_retrieve(cfg, catg, "readhandle"))) {
1191                 char *tmp2 = ast_strdupa(tmp);
1192                 AST_DECLARE_APP_ARGS(readconf,
1193                         AST_APP_ARG(dsn)[5];
1194                 );
1195                 AST_STANDARD_APP_ARGS(readconf, tmp2);
1196                 for (i = 0; i < 5; i++) {
1197                         if (!ast_strlen_zero(readconf.dsn[i]))
1198                                 ast_copy_string((*query)->readhandle[i], readconf.dsn[i], sizeof((*query)->readhandle[i]));
1199                 }
1200         } else {
1201                 /* If no separate readhandle, then use the writehandle for reading */
1202                 for (i = 0; i < 5; i++) {
1203                         if (!ast_strlen_zero((*query)->writehandle[i]))
1204                                 ast_copy_string((*query)->readhandle[i], (*query)->writehandle[i], sizeof((*query)->readhandle[i]));
1205                 }
1206         }
1207
1208         if ((tmp = ast_variable_retrieve(cfg, catg, "readsql")) ||
1209                         (tmp2 = ast_variable_retrieve(cfg, catg, "read"))) {
1210                 if (!tmp) {
1211                         ast_log(LOG_WARNING, "Parameter 'read' is deprecated for category %s.  Please use 'readsql' instead.\n", catg);
1212                         tmp = tmp2;
1213                 }
1214                 if (*tmp != '\0') { /* non-empty string */
1215                         if (!((*query)->sql_read = ast_strdup(tmp))) {
1216                                 free_acf_query(*query);
1217                                 *query = NULL;
1218                                 return ENOMEM;
1219                         }
1220                 }
1221         }
1222
1223         if ((*query)->sql_read && ast_strlen_zero((*query)->readhandle[0])) {
1224                 free_acf_query(*query);
1225                 *query = NULL;
1226                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for reading: %s\n", catg);
1227                 return EINVAL;
1228         }
1229
1230         if ((tmp = ast_variable_retrieve(cfg, catg, "writesql")) ||
1231                         (tmp2 = ast_variable_retrieve(cfg, catg, "write"))) {
1232                 if (!tmp) {
1233                         ast_log(LOG_WARNING, "Parameter 'write' is deprecated for category %s.  Please use 'writesql' instead.\n", catg);
1234                         tmp = tmp2;
1235                 }
1236                 if (*tmp != '\0') { /* non-empty string */
1237                         if (!((*query)->sql_write = ast_strdup(tmp))) {
1238                                 free_acf_query(*query);
1239                                 *query = NULL;
1240                                 return ENOMEM;
1241                         }
1242                 }
1243         }
1244
1245         if ((*query)->sql_write && ast_strlen_zero((*query)->writehandle[0])) {
1246                 free_acf_query(*query);
1247                 *query = NULL;
1248                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for writing: %s\n", catg);
1249                 return EINVAL;
1250         }
1251
1252         if ((tmp = ast_variable_retrieve(cfg, catg, "insertsql"))) {
1253                 if (*tmp != '\0') { /* non-empty string */
1254                         if (!((*query)->sql_insert = ast_strdup(tmp))) {
1255                                 free_acf_query(*query);
1256                                 *query = NULL;
1257                                 return ENOMEM;
1258                         }
1259                 }
1260         }
1261
1262         /* Allow escaping of embedded commas in fields to be turned off */
1263         ast_set_flag((*query), OPT_ESCAPECOMMAS);
1264         if ((tmp = ast_variable_retrieve(cfg, catg, "escapecommas"))) {
1265                 if (ast_false(tmp))
1266                         ast_clear_flag((*query), OPT_ESCAPECOMMAS);
1267         }
1268
1269         if ((tmp = ast_variable_retrieve(cfg, catg, "mode"))) {
1270                 if (strcasecmp(tmp, "multirow") == 0)
1271                         ast_set_flag((*query), OPT_MULTIROW);
1272                 if ((tmp = ast_variable_retrieve(cfg, catg, "rowlimit")))
1273                         sscanf(tmp, "%30d", &((*query)->rowlimit));
1274         }
1275
1276         (*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
1277         if (!(*query)->acf) {
1278                 free_acf_query(*query);
1279                 *query = NULL;
1280                 return ENOMEM;
1281         }
1282         if (ast_string_field_init((*query)->acf, 128)) {
1283                 free_acf_query(*query);
1284                 *query = NULL;
1285                 return ENOMEM;
1286         }
1287
1288         if ((tmp = ast_variable_retrieve(cfg, catg, "prefix")) && !ast_strlen_zero(tmp)) {
1289                 if (ast_asprintf((char **)&((*query)->acf->name), "%s_%s", tmp, catg) < 0) {
1290                         (*query)->acf->name = NULL;
1291                 }
1292         } else {
1293                 if (ast_asprintf((char **)&((*query)->acf->name), "ODBC_%s", catg) < 0) {
1294                         (*query)->acf->name = NULL;
1295                 }
1296         }
1297
1298         if (!(*query)->acf->name) {
1299                 free_acf_query(*query);
1300                 *query = NULL;
1301                 return ENOMEM;
1302         }
1303
1304         if ((tmp = ast_variable_retrieve(cfg, catg, "syntax")) && !ast_strlen_zero(tmp)) {
1305                 ast_string_field_build((*query)->acf, syntax, "%s(%s)", (*query)->acf->name, tmp);
1306         } else {
1307                 ast_string_field_build((*query)->acf, syntax, "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
1308         }
1309
1310         if (ast_strlen_zero((*query)->acf->syntax)) {
1311                 free_acf_query(*query);
1312                 *query = NULL;
1313                 return ENOMEM;
1314         }
1315
1316         if ((tmp = ast_variable_retrieve(cfg, catg, "synopsis")) && !ast_strlen_zero(tmp)) {
1317                 ast_string_field_set((*query)->acf, synopsis, tmp);
1318         } else {
1319                 ast_string_field_set((*query)->acf, synopsis, "Runs the referenced query with the specified arguments");
1320         }
1321
1322         if (ast_strlen_zero((*query)->acf->synopsis)) {
1323                 free_acf_query(*query);
1324                 *query = NULL;
1325                 return ENOMEM;
1326         }
1327
1328         if ((*query)->sql_read && (*query)->sql_write) {
1329                 ast_string_field_build((*query)->acf, desc,
1330                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
1331                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
1332                                         "${ARG2}, ... ${ARGn}.  When setting the function, the values are provided\n"
1333                                         "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
1334                                         "%s"
1335                                         "\nRead:\n%s\n\nWrite:\n%s%s%s",
1336                                         (*query)->sql_insert ?
1337                                                 "If the write query affects no rows, the insert query will be\n"
1338                                                 "performed.\n" : "",
1339                                         (*query)->sql_read,
1340                                         (*query)->sql_write,
1341                                         (*query)->sql_insert ? "\n\nInsert:\n" : "",
1342                                         (*query)->sql_insert ? (*query)->sql_insert : "");
1343         } else if ((*query)->sql_read) {
1344                 ast_string_field_build((*query)->acf, desc,
1345                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
1346                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
1347                                         "${ARG2}, ... ${ARGn}.  This function may only be read, not set.\n\nSQL:\n%s",
1348                                         (*query)->sql_read);
1349         } else if ((*query)->sql_write) {
1350                 ast_string_field_build((*query)->acf, desc,
1351                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
1352                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
1353                                         "${ARG2}, ... ${ARGn}.  The values are provided either in whole as\n"
1354                                         "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
1355                                         "This function may only be set.\n%s\nSQL:\n%s%s%s",
1356                                         (*query)->sql_insert ?
1357                                                 "If the write query affects no rows, the insert query will be\n"
1358                                                 "performed.\n" : "",
1359                                         (*query)->sql_write,
1360                                         (*query)->sql_insert ? "\n\nInsert:\n" : "",
1361                                         (*query)->sql_insert ? (*query)->sql_insert : "");
1362         } else {
1363                 free_acf_query(*query);
1364                 *query = NULL;
1365                 ast_log(LOG_WARNING, "Section '%s' was found, but there was no SQL to execute.  Ignoring.\n", catg);
1366                 return EINVAL;
1367         }
1368
1369         if (ast_strlen_zero((*query)->acf->desc)) {
1370                 free_acf_query(*query);
1371                 *query = NULL;
1372                 return ENOMEM;
1373         }
1374
1375         if ((*query)->sql_read) {
1376                 (*query)->acf->read = acf_odbc_read;
1377         }
1378
1379         if ((*query)->sql_write) {
1380                 (*query)->acf->write = acf_odbc_write;
1381         }
1382
1383         return 0;
1384 }
1385
1386 static char *cli_odbc_read(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1387 {
1388         AST_DECLARE_APP_ARGS(args,
1389                 AST_APP_ARG(field)[100];
1390         );
1391         struct ast_str *sql;
1392         char *char_args, varname[10];
1393         struct acf_odbc_query *query;
1394         struct ast_channel *chan;
1395         int i;
1396
1397         switch (cmd) {
1398         case CLI_INIT:
1399                 e->command = "odbc read";
1400                 e->usage =
1401                         "Usage: odbc read <name> <args> [exec]\n"
1402                         "       Evaluates the SQL provided in the ODBC function <name>, and\n"
1403                         "       optionally executes the function.  This function is intended for\n"
1404                         "       testing purposes.  Remember to quote arguments containing spaces.\n";
1405                 return NULL;
1406         case CLI_GENERATE:
1407                 if (a->pos == 2) {
1408                         int wordlen = strlen(a->word), which = 0;
1409                         /* Complete function name */
1410                         AST_RWLIST_RDLOCK(&queries);
1411                         AST_RWLIST_TRAVERSE(&queries, query, list) {
1412                                 if (!strncasecmp(query->acf->name, a->word, wordlen)) {
1413                                         if (++which > a->n) {
1414                                                 char *res = ast_strdup(query->acf->name);
1415                                                 AST_RWLIST_UNLOCK(&queries);
1416                                                 return res;
1417                                         }
1418                                 }
1419                         }
1420                         AST_RWLIST_UNLOCK(&queries);
1421                         return NULL;
1422                 } else if (a->pos == 4) {
1423                         static const char * const completions[] = { "exec", NULL };
1424                         return ast_cli_complete(a->word, completions, a->n);
1425                 } else {
1426                         return NULL;
1427                 }
1428         }
1429
1430         if (a->argc < 4 || a->argc > 5) {
1431                 return CLI_SHOWUSAGE;
1432         }
1433
1434         sql = ast_str_thread_get(&sql_buf, 16);
1435         if (!sql) {
1436                 return CLI_FAILURE;
1437         }
1438
1439         AST_RWLIST_RDLOCK(&queries);
1440         AST_RWLIST_TRAVERSE(&queries, query, list) {
1441                 if (!strcmp(query->acf->name, a->argv[2])) {
1442                         break;
1443                 }
1444         }
1445
1446         if (!query) {
1447                 ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
1448                 AST_RWLIST_UNLOCK(&queries);
1449                 return CLI_SHOWUSAGE;
1450         }
1451
1452         if (!query->sql_read) {
1453                 ast_cli(a->fd, "The function %s has no readsql parameter.\n", a->argv[2]);
1454                 AST_RWLIST_UNLOCK(&queries);
1455                 return CLI_SUCCESS;
1456         }
1457
1458         ast_str_make_space(&sql, strlen(query->sql_read) * 2 + 300);
1459
1460         /* Evaluate function */
1461         char_args = ast_strdupa(a->argv[3]);
1462
1463         chan = ast_dummy_channel_alloc();
1464         if (!chan) {
1465                 AST_RWLIST_UNLOCK(&queries);
1466                 return CLI_FAILURE;
1467         }
1468
1469         AST_STANDARD_APP_ARGS(args, char_args);
1470         for (i = 0; i < args.argc; i++) {
1471                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
1472                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
1473         }
1474
1475         ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
1476         chan = ast_channel_unref(chan);
1477
1478         if (a->argc == 5 && !strcmp(a->argv[4], "exec")) {
1479                 /* Execute the query */
1480                 struct odbc_obj *obj = NULL;
1481                 struct dsn *dsn = NULL;
1482                 int dsn_num, executed = 0;
1483                 SQLHSTMT stmt;
1484                 int rows = 0, res, x;
1485                 SQLSMALLINT colcount = 0, collength;
1486                 SQLLEN indicator;
1487                 struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
1488                 char colname[256];
1489                 SQLULEN maxcol;
1490
1491                 if (!coldata) {
1492                         AST_RWLIST_UNLOCK(&queries);
1493                         return CLI_SUCCESS;
1494                 }
1495
1496                 for (dsn_num = 0; dsn_num < 5; dsn_num++) {
1497                         if (ast_strlen_zero(query->readhandle[dsn_num])) {
1498                                 continue;
1499                         }
1500                         obj = get_odbc_obj(query->readhandle[dsn_num], &dsn);
1501                         if (!obj) {
1502                                 continue;
1503                         }
1504                         ast_debug(1, "Found handle %s\n", query->readhandle[dsn_num]);
1505
1506                         if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
1507                                 release_obj_or_dsn (&obj, &dsn);
1508                                 continue;
1509                         }
1510
1511                         executed = 1;
1512
1513                         res = SQLNumResultCols(stmt, &colcount);
1514                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1515                                 ast_cli(a->fd, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
1516                                 SQLCloseCursor(stmt);
1517                                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1518                                 release_obj_or_dsn (&obj, &dsn);
1519                                 AST_RWLIST_UNLOCK(&queries);
1520                                 return CLI_SUCCESS;
1521                         }
1522
1523                         res = SQLFetch(stmt);
1524                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1525                                 SQLCloseCursor(stmt);
1526                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1527                                 release_obj_or_dsn (&obj, &dsn);
1528                                 if (res == SQL_NO_DATA) {
1529                                         ast_cli(a->fd, "Returned %d rows.  Query executed on handle %d:%s [%s]\n", rows, dsn_num, query->readhandle[dsn_num], ast_str_buffer(sql));
1530                                         break;
1531                                 } else {
1532                                         ast_cli(a->fd, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
1533                                 }
1534                                 AST_RWLIST_UNLOCK(&queries);
1535                                 return CLI_SUCCESS;
1536                         }
1537                         for (;;) {
1538                                 for (x = 0; x < colcount; x++) {
1539                                         maxcol = 0;
1540
1541                                         res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
1542                                         if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
1543                                                 snprintf(colname, sizeof(colname), "field%d", x);
1544                                         }
1545
1546                                         res = ast_odbc_ast_str_SQLGetData(&coldata, maxcol, stmt, x + 1, SQL_CHAR, &indicator);
1547                                         if (indicator == SQL_NULL_DATA) {
1548                                                 ast_str_set(&coldata, 0, "(nil)");
1549                                                 res = SQL_SUCCESS;
1550                                         }
1551
1552                                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1553                                                 ast_cli(a->fd, "SQL Get Data error %d!\n[%s]\n\n", res, ast_str_buffer(sql));
1554                                                 SQLCloseCursor(stmt);
1555                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1556                                                 release_obj_or_dsn (&obj, &dsn);
1557                                                 AST_RWLIST_UNLOCK(&queries);
1558                                                 return CLI_SUCCESS;
1559                                         }
1560
1561                                         ast_cli(a->fd, "%-20.20s  %s\n", colname, ast_str_buffer(coldata));
1562                                 }
1563                                 rows++;
1564
1565                                 /* Get next row */
1566                                 res = SQLFetch(stmt);
1567                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1568                                         break;
1569                                 }
1570                                 ast_cli(a->fd, "%-20.20s  %s\n", "----------", "----------");
1571                         }
1572                         SQLCloseCursor(stmt);
1573                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1574                         release_obj_or_dsn (&obj, &dsn);
1575                         ast_cli(a->fd, "Returned %d row%s.  Query executed on handle %d [%s]\n", rows, rows == 1 ? "" : "s", dsn_num, query->readhandle[dsn_num]);
1576                         break;
1577                 }
1578                 release_obj_or_dsn (&obj, &dsn);
1579
1580                 if (!executed) {
1581                         ast_cli(a->fd, "Failed to execute query. [%s]\n", ast_str_buffer(sql));
1582                 }
1583         } else { /* No execution, just print out the resulting SQL */
1584                 ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
1585         }
1586         AST_RWLIST_UNLOCK(&queries);
1587         return CLI_SUCCESS;
1588 }
1589
1590 static char *cli_odbc_write(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1591 {
1592         AST_DECLARE_APP_ARGS(values,
1593                 AST_APP_ARG(field)[100];
1594         );
1595         AST_DECLARE_APP_ARGS(args,
1596                 AST_APP_ARG(field)[100];
1597         );
1598         struct ast_str *sql;
1599         char *char_args, *char_values, varname[10];
1600         struct acf_odbc_query *query;
1601         struct ast_channel *chan;
1602         int i;
1603
1604         switch (cmd) {
1605         case CLI_INIT:
1606                 e->command = "odbc write";
1607                 e->usage =
1608                         "Usage: odbc write <name> <args> <value> [exec]\n"
1609                         "       Evaluates the SQL provided in the ODBC function <name>, and\n"
1610                         "       optionally executes the function.  This function is intended for\n"
1611                         "       testing purposes.  Remember to quote arguments containing spaces.\n";
1612                 return NULL;
1613         case CLI_GENERATE:
1614                 if (a->pos == 2) {
1615                         int wordlen = strlen(a->word), which = 0;
1616                         /* Complete function name */
1617                         AST_RWLIST_RDLOCK(&queries);
1618                         AST_RWLIST_TRAVERSE(&queries, query, list) {
1619                                 if (!strncasecmp(query->acf->name, a->word, wordlen)) {
1620                                         if (++which > a->n) {
1621                                                 char *res = ast_strdup(query->acf->name);
1622                                                 AST_RWLIST_UNLOCK(&queries);
1623                                                 return res;
1624                                         }
1625                                 }
1626                         }
1627                         AST_RWLIST_UNLOCK(&queries);
1628                         return NULL;
1629                 } else if (a->pos == 5) {
1630                         static const char * const completions[] = { "exec", NULL };
1631                         return ast_cli_complete(a->word, completions, a->n);
1632                 } else {
1633                         return NULL;
1634                 }
1635         }
1636
1637         if (a->argc < 5 || a->argc > 6) {
1638                 return CLI_SHOWUSAGE;
1639         }
1640
1641         sql = ast_str_thread_get(&sql_buf, 16);
1642         if (!sql) {
1643                 return CLI_FAILURE;
1644         }
1645
1646         AST_RWLIST_RDLOCK(&queries);
1647         AST_RWLIST_TRAVERSE(&queries, query, list) {
1648                 if (!strcmp(query->acf->name, a->argv[2])) {
1649                         break;
1650                 }
1651         }
1652
1653         if (!query) {
1654                 ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
1655                 AST_RWLIST_UNLOCK(&queries);
1656                 return CLI_SHOWUSAGE;
1657         }
1658
1659         if (!query->sql_write) {
1660                 ast_cli(a->fd, "The function %s has no writesql parameter.\n", a->argv[2]);
1661                 AST_RWLIST_UNLOCK(&queries);
1662                 return CLI_SUCCESS;
1663         }
1664
1665         /* FIXME: The code below duplicates code found in acf_odbc_write but
1666          * lacks the newer sql_insert additions. */
1667
1668         ast_str_make_space(&sql, strlen(query->sql_write) * 2 + 300);
1669
1670         /* Evaluate function */
1671         char_args = ast_strdupa(a->argv[3]);
1672         char_values = ast_strdupa(a->argv[4]);
1673
1674         chan = ast_dummy_channel_alloc();
1675         if (!chan) {
1676                 AST_RWLIST_UNLOCK(&queries);
1677                 return CLI_FAILURE;
1678         }
1679
1680         AST_STANDARD_APP_ARGS(args, char_args);
1681         for (i = 0; i < args.argc; i++) {
1682                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
1683                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
1684         }
1685
1686         /* Parse values, just like arguments */
1687         AST_STANDARD_APP_ARGS(values, char_values);
1688         for (i = 0; i < values.argc; i++) {
1689                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
1690                 pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
1691         }
1692
1693         /* Additionally set the value as a whole (but push an empty string if value is NULL) */
1694         pbx_builtin_pushvar_helper(chan, "VALUE", S_OR(a->argv[4], ""));
1695         ast_str_substitute_variables(&sql, 0, chan, query->sql_write);
1696         ast_debug(1, "SQL is %s\n", ast_str_buffer(sql));
1697
1698         chan = ast_channel_unref(chan);
1699
1700         if (a->argc == 6 && !strcmp(a->argv[5], "exec")) {
1701                 /* Execute the query */
1702                 struct odbc_obj *obj = NULL;
1703                 struct dsn *dsn = NULL;
1704                 int dsn_num, executed = 0;
1705                 SQLHSTMT stmt;
1706                 SQLLEN rows = -1;
1707
1708                 for (dsn_num = 0; dsn_num < 5; dsn_num++) {
1709                         if (ast_strlen_zero(query->writehandle[dsn_num])) {
1710                                 continue;
1711                         }
1712                         obj = get_odbc_obj(query->writehandle[dsn_num], &dsn);
1713                         if (!obj) {
1714                                 continue;
1715                         }
1716                         if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
1717                                 release_obj_or_dsn (&obj, &dsn);
1718                                 continue;
1719                         }
1720
1721                         SQLRowCount(stmt, &rows);
1722                         SQLCloseCursor(stmt);
1723                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1724                         release_obj_or_dsn (&obj, &dsn);
1725                         ast_cli(a->fd, "Affected %d rows.  Query executed on handle %d [%s]\n", (int)rows, dsn_num, query->writehandle[dsn_num]);
1726                         executed = 1;
1727                         break;
1728                 }
1729
1730                 if (!executed) {
1731                         ast_cli(a->fd, "Failed to execute query.\n");
1732                 }
1733         } else { /* No execution, just print out the resulting SQL */
1734                 ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
1735         }
1736         AST_RWLIST_UNLOCK(&queries);
1737         return CLI_SUCCESS;
1738 }
1739
1740 static struct ast_cli_entry cli_func_odbc[] = {
1741         AST_CLI_DEFINE(cli_odbc_write, "Test setting a func_odbc function"),
1742         AST_CLI_DEFINE(cli_odbc_read, "Test reading a func_odbc function"),
1743 };
1744
1745 static int load_module(void)
1746 {
1747         int res = 0;
1748         struct ast_config *cfg;
1749         char *catg;
1750         const char *s;
1751         struct ast_flags config_flags = { 0 };
1752
1753         res |= ast_custom_function_register(&fetch_function);
1754         res |= ast_register_application_xml(app_odbcfinish, exec_odbcfinish);
1755
1756         cfg = ast_config_load(config, config_flags);
1757         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
1758                 ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
1759                 return AST_MODULE_LOAD_DECLINE;
1760         }
1761
1762         ast_rwlock_wrlock(&single_db_connection_lock);
1763         if ((s = ast_variable_retrieve(cfg, "general", "single_db_connection"))) {
1764                 single_db_connection = ast_true(s);
1765         } else {
1766                 single_db_connection = DEFAULT_SINGLE_DB_CONNECTION;
1767         }
1768
1769         dsns = NULL;
1770
1771         if (single_db_connection) {
1772                 dsns = ao2_container_alloc(DSN_BUCKETS, dsn_hash, dsn_cmp);
1773                 if (!dsns) {
1774                         ast_log(LOG_ERROR, "Could not initialize DSN container\n");
1775                         ast_rwlock_unlock(&single_db_connection_lock);
1776                         return AST_MODULE_LOAD_DECLINE;
1777                 }
1778         }
1779         ast_rwlock_unlock(&single_db_connection_lock);
1780
1781         AST_RWLIST_WRLOCK(&queries);
1782         for (catg = ast_category_browse(cfg, NULL);
1783              catg;
1784              catg = ast_category_browse(cfg, catg)) {
1785                 struct acf_odbc_query *query = NULL;
1786                 int err;
1787
1788                 if (!strcasecmp(catg, "general")) {
1789                         continue;
1790                 }
1791
1792                 if ((err = init_acf_query(cfg, catg, &query))) {
1793                         if (err == ENOMEM)
1794                                 ast_log(LOG_ERROR, "Out of memory\n");
1795                         else if (err == EINVAL)
1796                                 ast_log(LOG_ERROR, "Invalid parameters for category %s\n", catg);
1797                         else
1798                                 ast_log(LOG_ERROR, "%s (%d)\n", strerror(err), err);
1799                 } else {
1800                         AST_RWLIST_INSERT_HEAD(&queries, query, list);
1801                         ast_custom_function_register(query->acf);
1802                 }
1803         }
1804
1805         ast_config_destroy(cfg);
1806         res |= ast_custom_function_register(&escape_function);
1807         ast_cli_register_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
1808
1809         AST_RWLIST_UNLOCK(&queries);
1810         return res;
1811 }
1812
1813 static int unload_module(void)
1814 {
1815         struct acf_odbc_query *query;
1816         int res = 0;
1817
1818         AST_RWLIST_WRLOCK(&queries);
1819         while (!AST_RWLIST_EMPTY(&queries)) {
1820                 query = AST_RWLIST_REMOVE_HEAD(&queries, list);
1821                 ast_custom_function_unregister(query->acf);
1822                 free_acf_query(query);
1823         }
1824
1825         res |= ast_custom_function_unregister(&escape_function);
1826         res |= ast_custom_function_unregister(&fetch_function);
1827         res |= ast_unregister_application(app_odbcfinish);
1828         ast_cli_unregister_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
1829
1830         /* Allow any threads waiting for this lock to pass (avoids a race) */
1831         AST_RWLIST_UNLOCK(&queries);
1832         usleep(1);
1833         AST_RWLIST_WRLOCK(&queries);
1834
1835         AST_RWLIST_UNLOCK(&queries);
1836
1837         if (dsns) {
1838                 ao2_ref(dsns, -1);
1839         }
1840         return res;
1841 }
1842
1843 static int reload(void)
1844 {
1845         int res = 0;
1846         struct ast_config *cfg;
1847         struct acf_odbc_query *oldquery;
1848         char *catg;
1849         const char *s;
1850         struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
1851
1852         cfg = ast_config_load(config, config_flags);
1853         if (cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
1854                 return 0;
1855
1856         ast_rwlock_wrlock(&single_db_connection_lock);
1857
1858         if (dsns) {
1859                 ao2_ref(dsns, -1);
1860                 dsns = NULL;
1861         }
1862
1863         if (cfg && (s = ast_variable_retrieve(cfg, "general", "single_db_connection"))) {
1864                 single_db_connection = ast_true(s);
1865         } else {
1866                 single_db_connection = DEFAULT_SINGLE_DB_CONNECTION;
1867         }
1868
1869         if (single_db_connection) {
1870                 dsns = ao2_container_alloc(DSN_BUCKETS, dsn_hash, dsn_cmp);
1871                 if (!dsns) {
1872                         ast_log(LOG_ERROR, "Could not initialize DSN container\n");
1873                         ast_rwlock_unlock(&single_db_connection_lock);
1874                         return 0;
1875                 }
1876         }
1877         ast_rwlock_unlock(&single_db_connection_lock);
1878
1879         AST_RWLIST_WRLOCK(&queries);
1880
1881         while (!AST_RWLIST_EMPTY(&queries)) {
1882                 oldquery = AST_RWLIST_REMOVE_HEAD(&queries, list);
1883                 ast_custom_function_unregister(oldquery->acf);
1884                 free_acf_query(oldquery);
1885         }
1886
1887         if (!cfg) {
1888                 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
1889                 goto reload_out;
1890         }
1891
1892         for (catg = ast_category_browse(cfg, NULL);
1893              catg;
1894              catg = ast_category_browse(cfg, catg)) {
1895                 struct acf_odbc_query *query = NULL;
1896
1897                 if (!strcasecmp(catg, "general")) {
1898                         continue;
1899                 }
1900
1901                 if (init_acf_query(cfg, catg, &query)) {
1902                         ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
1903                 } else {
1904                         AST_RWLIST_INSERT_HEAD(&queries, query, list);
1905                         ast_custom_function_register(query->acf);
1906                 }
1907         }
1908
1909         ast_config_destroy(cfg);
1910 reload_out:
1911         AST_RWLIST_UNLOCK(&queries);
1912         return res;
1913 }
1914
1915 /* XXX need to revise usecount - set if query_lock is set */
1916
1917 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
1918         .support_level = AST_MODULE_SUPPORT_CORE,
1919         .load = load_module,
1920         .unload = unload_module,
1921         .reload = reload,
1922 );