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