astobj2: Add backtrace to log_bad_ao2.
[asterisk/asterisk.git] / funcs / func_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (c) 2005, 2006 Tilghman Lesher
5  * Copyright (c) 2008, 2009 Digium, Inc.
6  *
7  * Tilghman Lesher <func_odbc__200508@the-tilghman.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*!
21  * \file
22  *
23  * \brief ODBC lookups
24  *
25  * \author Tilghman Lesher <func_odbc__200508@the-tilghman.com>
26  *
27  * \ingroup functions
28  */
29
30 /*** MODULEINFO
31         <depend>res_odbc</depend>
32         <support_level>core</support_level>
33  ***/
34
35 #include "asterisk.h"
36
37 ASTERISK_REGISTER_FILE()
38
39 #include "asterisk/module.h"
40 #include "asterisk/file.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/config.h"
44 #include "asterisk/res_odbc.h"
45 #include "asterisk/res_odbc_transaction.h"
46 #include "asterisk/app.h"
47 #include "asterisk/cli.h"
48 #include "asterisk/strings.h"
49
50 /*** DOCUMENTATION
51         <function name="ODBC_FETCH" language="en_US">
52                 <synopsis>
53                         Fetch a row from a multirow query.
54                 </synopsis>
55                 <syntax>
56                         <parameter name="result-id" required="true" />
57                 </syntax>
58                 <description>
59                         <para>For queries which are marked as mode=multirow, the original 
60                         query returns a <replaceable>result-id</replaceable> from which results 
61                         may be fetched.  This function implements the actual fetch of the results.</para>
62                         <para>This also sets <variable>ODBC_FETCH_STATUS</variable>.</para>
63                         <variablelist>
64                                 <variable name="ODBC_FETCH_STATUS">
65                                         <value name="SUCESS">
66                                                 If rows are available.
67                                         </value>
68                                         <value name="FAILURE">
69                                                 If no rows are available.
70                                         </value>
71                                 </variable>
72                         </variablelist>
73                 </description>
74         </function>
75         <application name="ODBCFinish" language="en_US">
76                 <synopsis>
77                         Clear the resultset of a sucessful multirow query.
78                 </synopsis>
79                 <syntax>
80                         <parameter name="result-id" required="true" />
81                 </syntax>
82                 <description>
83                         <para>For queries which are marked as mode=multirow, this will clear 
84                         any remaining rows of the specified resultset.</para>
85                 </description>
86         </application>
87         <function name="SQL_ESC" language="en_US">
88                 <synopsis>
89                         Escapes single ticks for use in SQL statements.
90                 </synopsis>
91                 <syntax>
92                         <parameter name="string" required="true" />
93                 </syntax>
94                 <description>
95                         <para>Used in SQL templates to escape data which may contain single ticks 
96                         <literal>'</literal> which are otherwise used to delimit data.</para>
97                         <para>Example: SELECT foo FROM bar WHERE baz='${SQL_ESC(${ARG1})}'</para>
98                 </description>
99         </function>
100  ***/
101
102 static char *config = "func_odbc.conf";
103
104 #define DEFAULT_SINGLE_DB_CONNECTION 0
105
106 static int single_db_connection;
107
108 AST_RWLOCK_DEFINE_STATIC(single_db_connection_lock);
109
110 enum odbc_option_flags {
111         OPT_ESCAPECOMMAS =      (1 << 0),
112         OPT_MULTIROW     =      (1 << 1),
113 };
114
115 struct acf_odbc_query {
116         AST_RWLIST_ENTRY(acf_odbc_query) list;
117         char readhandle[5][30];
118         char writehandle[5][30];
119         char *sql_read;
120         char *sql_write;
121         char *sql_insert;
122         unsigned int flags;
123         int rowlimit;
124         struct ast_custom_function *acf;
125 };
126
127 static void odbc_datastore_free(void *data);
128
129 static const struct ast_datastore_info odbc_info = {
130         .type = "FUNC_ODBC",
131         .destroy = odbc_datastore_free,
132 };
133
134 /* For storing each result row */
135 struct odbc_datastore_row {
136         AST_LIST_ENTRY(odbc_datastore_row) list;
137         char data[0];
138 };
139
140 /* For storing each result set */
141 struct odbc_datastore {
142         AST_LIST_HEAD(, odbc_datastore_row);
143         char names[0];
144 };
145
146 /* \brief Data source name
147  *
148  * This holds data that pertains to a DSN
149  */
150 struct dsn {
151         /*! A connection to the database */
152         struct odbc_obj *connection;
153         /*! The name of the DSN as defined in res_odbc.conf */
154         char name[0];
155 };
156
157 #define DSN_BUCKETS 37
158
159 struct ao2_container *dsns;
160
161 static int dsn_hash(const void *obj, const int flags)
162 {
163         const struct dsn *object;
164         const char *key;
165
166         switch (flags & OBJ_SEARCH_MASK) {
167         case OBJ_SEARCH_KEY:
168                 key = obj;
169                 break;
170         case OBJ_SEARCH_OBJECT:
171                 object = obj;
172                 key = object->name;
173                 break;
174         default:
175                 ast_assert(0);
176                 return 0;
177         }
178         return ast_str_hash(key);
179 }
180
181 static int dsn_cmp(void *obj, void *arg, int flags)
182 {
183         const struct dsn *object_left = obj;
184         const struct dsn *object_right = arg;
185         const char *right_key = arg;
186         int cmp;
187
188         switch (flags & OBJ_SEARCH_MASK) {
189         case OBJ_SEARCH_OBJECT:
190                 right_key = object_right->name;
191                 /* Fall through */
192         case OBJ_SEARCH_KEY:
193                 cmp = strcmp(object_left->name, right_key);
194                 break;
195         case OBJ_SEARCH_PARTIAL_KEY:
196                 cmp = strncmp(object_left->name, right_key, strlen(right_key));
197                 break;
198         default:
199                 cmp = 0;
200                 break;
201         }
202
203         if (cmp) {
204                 return 0;
205         }
206
207         return CMP_MATCH;
208 }
209
210 static void dsn_destructor(void *obj)
211 {
212         struct dsn *dsn = obj;
213
214         if (dsn->connection) {
215                 ast_odbc_release_obj(dsn->connection);
216         }
217 }
218
219 /*!
220  * \brief Create a DSN and connect to the database
221  *
222  * \param name The name of the DSN as found in res_odbc.conf
223  * \retval NULL Fail
224  * \retval non-NULL The newly-created structure
225  */
226 static struct dsn *create_dsn(const char *name)
227 {
228         struct dsn *dsn;
229
230         if (!dsns) {
231                 return NULL;
232         }
233
234         dsn = ao2_alloc(sizeof(*dsn) + strlen(name) + 1, dsn_destructor);
235         if (!dsn) {
236                 return NULL;
237         }
238
239         /* Safe */
240         strcpy(dsn->name, name);
241
242         dsn->connection = ast_odbc_request_obj(name, 0);
243         if (!dsn->connection) {
244                 ao2_ref(dsn, -1);
245                 return NULL;
246         }
247
248         if (!ao2_link_flags(dsns, dsn, OBJ_NOLOCK)) {
249                 ao2_ref(dsn, -1);
250                 return NULL;
251         }
252
253         return dsn;
254 }
255
256 static SQLHSTMT silent_execute(struct odbc_obj *obj, void *data);
257
258 /*!
259  * \brief Determine if the connection has died.
260  *
261  * \param connection The connection to check
262  * \retval 1 Yep, it's dead
263  * \retval 0 It's alive and well
264  */
265 static int connection_dead(struct odbc_obj *connection)
266 {
267         SQLINTEGER dead;
268         SQLRETURN res;
269         SQLHSTMT stmt;
270
271         if (!connection) {
272                 return 1;
273         }
274
275         res = SQLGetConnectAttr(connection->con, SQL_ATTR_CONNECTION_DEAD, &dead, 0, 0);
276         if (SQL_SUCCEEDED(res)) {
277                 return dead == SQL_CD_TRUE ? 1 : 0;
278         }
279
280         /* If the Driver doesn't support SQL_ATTR_CONNECTION_DEAD do a direct
281          * execute of a probing statement and see if that succeeds instead
282          */
283         stmt = ast_odbc_direct_execute(connection, silent_execute, "SELECT 1");
284         if (!stmt) {
285                 return 1;
286         }
287
288         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
289         return 0;
290 }
291
292 /*!
293  * \brief Retrieve a DSN, or create it if it does not exist.
294  *
295  * The created DSN is returned locked. This should be inconsequential
296  * to callers in most cases.
297  *
298  * When finished with the returned structure, the caller must call
299  * \ref release_dsn
300  *
301  * \param name Name of the DSN as found in res_odbc.conf
302  * \retval NULL Unable to retrieve or create the DSN
303  * \retval non-NULL The retrieved/created locked DSN
304  */
305 static struct dsn *get_dsn(const char *name)
306 {
307         struct dsn *dsn;
308
309         if (!dsns) {
310                 return NULL;
311         }
312
313         ao2_lock(dsns);
314         dsn = ao2_find(dsns, name, OBJ_SEARCH_KEY | OBJ_NOLOCK);
315         if (!dsn) {
316                 dsn = create_dsn(name);
317         }
318         ao2_unlock(dsns);
319
320         if (!dsn) {
321                 return NULL;
322         }
323
324         ao2_lock(dsn);
325         if (!dsn->connection) {
326                 dsn->connection = ast_odbc_request_obj(name, 0);
327                 if (!dsn->connection) {
328                         ao2_unlock(dsn);
329                         ao2_ref(dsn, -1);
330                         return NULL;
331                 }
332                 return dsn;
333         }
334
335         if (connection_dead(dsn->connection)) {
336                 ast_odbc_release_obj(dsn->connection);
337                 dsn->connection = ast_odbc_request_obj(name, 0);
338                 if (!dsn->connection) {
339                         ao2_unlock(dsn);
340                         ao2_ref(dsn, -1);
341                         return NULL;
342                 }
343         }
344
345         return dsn;
346 }
347
348 /*!
349  * \brief Get a DB handle via a DSN or directly
350  *
351  * If single db connection then get the DB handle via DSN
352  * else by requesting a connection directly
353  *
354  * \param dsn_name Name of the DSN as found in res_odbc.conf
355  * \param dsn The pointer to the DSN
356  * \retval NULL Unable to retrieve the DB handle
357  * \retval non-NULL The retrieved DB handle
358  */
359 static struct odbc_obj *get_odbc_obj(const char *dsn_name, struct dsn **dsn)
360 {
361         struct odbc_obj *obj = NULL;
362
363         ast_rwlock_rdlock(&single_db_connection_lock);
364         if (single_db_connection) {
365                 if (dsn) {
366                         *dsn = get_dsn(dsn_name);
367                         if (*dsn) {
368                                 obj = (*dsn)->connection;
369                         }
370                 }
371         } else {
372                 obj = ast_odbc_request_obj(dsn_name, 0);
373         }
374         ast_rwlock_unlock(&single_db_connection_lock);
375
376         return obj;
377 }
378
379 /*!
380  * \brief Release an ODBC obj or a DSN
381  *
382  * If single db connection then unlock and unreference the DSN
383  * else release the ODBC obj
384  *
385  * \param obj The pointer to the ODBC obj to release
386  * \param dsn The pointer to the dsn to unlock and unreference
387  */
388 static inline void release_obj_or_dsn(struct odbc_obj **obj, struct dsn **dsn)
389 {
390         if (dsn && *dsn) {
391                 /* If multiple connections are not enabled then the guarantee
392                  * of a single connection already exists and holding on to the
393                  * connection would prevent any other user from acquiring it
394                  * indefinitely.
395                  */
396                 if (ast_odbc_get_max_connections((*dsn)->name) < 2) {
397                         ast_odbc_release_obj((*dsn)->connection);
398                         (*dsn)->connection = NULL;
399                 }
400                 ao2_unlock(*dsn);
401                 ao2_ref(*dsn, -1);
402                 *dsn = NULL;
403                 /* Some callers may provide both an obj and dsn. To ensure that
404                  * the connection is not released twice we set it to NULL here if
405                  * present.
406                  */
407                 if (obj) {
408                         *obj = NULL;
409                 }
410         } else if (obj && *obj) {
411                 ast_odbc_release_obj(*obj);
412                 *obj = NULL;
413         }
414 }
415
416 static AST_RWLIST_HEAD_STATIC(queries, acf_odbc_query);
417
418 static int resultcount = 0;
419
420 AST_THREADSTORAGE(sql_buf);
421 AST_THREADSTORAGE(sql2_buf);
422 AST_THREADSTORAGE(coldata_buf);
423 AST_THREADSTORAGE(colnames_buf);
424
425 static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len);
426
427 static void odbc_datastore_free(void *data)
428 {
429         struct odbc_datastore *result = data;
430         struct odbc_datastore_row *row;
431
432         if (!result) {
433                 return;
434         }
435
436         AST_LIST_LOCK(result);
437         while ((row = AST_LIST_REMOVE_HEAD(result, list))) {
438                 ast_free(row);
439         }
440         AST_LIST_UNLOCK(result);
441         AST_LIST_HEAD_DESTROY(result);
442         ast_free(result);
443 }
444
445 /*!
446  * \brief Common execution function for SQL queries.
447  *
448  * \param obj DB connection
449  * \param data The query to execute
450  * \param silent If true, do not print warnings on failure
451  * \retval NULL Failed to execute query
452  * \retval non-NULL The executed statement
453  */
454 static SQLHSTMT execute(struct odbc_obj *obj, void *data, int silent)
455 {
456         int res;
457         char *sql = data;
458         SQLHSTMT stmt;
459
460         res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
461         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
462                 ast_log(LOG_WARNING, "SQL Alloc Handle failed (%d)!\n", res);
463                 return NULL;
464         }
465
466         res = SQLExecDirect(stmt, (unsigned char *)sql, SQL_NTS);
467         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
468                 if (res == SQL_ERROR && !silent) {
469                         int i;
470                         SQLINTEGER nativeerror=0, numfields=0;
471                         SQLSMALLINT diagbytes=0;
472                         unsigned char state[10], diagnostic[256];
473
474                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
475                         for (i = 0; i < numfields; i++) {
476                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
477                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
478                                 if (i > 10) {
479                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
480                                         break;
481                                 }
482                         }
483                 }
484
485                 if (!silent) {
486                         ast_log(LOG_WARNING, "SQL Exec Direct failed (%d)![%s]\n", res, sql);
487                 }
488                 SQLCloseCursor(stmt);
489                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
490                 return NULL;
491         }
492
493         return stmt;
494 }
495
496 static SQLHSTMT generic_execute(struct odbc_obj *obj, void *data)
497 {
498         return execute(obj, data, 0);
499 }
500
501 static SQLHSTMT silent_execute(struct odbc_obj *obj, void *data)
502 {
503         return execute(obj, data, 1);
504 }
505
506 /*
507  * Master control routine
508  */
509 static int acf_odbc_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
510 {
511         struct odbc_obj *obj = NULL;
512         struct acf_odbc_query *query;
513         char *t, varname[15];
514         int i, dsn_num, bogus_chan = 0;
515         int transactional = 0;
516         AST_DECLARE_APP_ARGS(values,
517                 AST_APP_ARG(field)[100];
518         );
519         AST_DECLARE_APP_ARGS(args,
520                 AST_APP_ARG(field)[100];
521         );
522         SQLHSTMT stmt = NULL;
523         SQLLEN rows=0;
524         struct ast_str *buf = ast_str_thread_get(&sql_buf, 16);
525         struct ast_str *insertbuf = ast_str_thread_get(&sql2_buf, 16);
526         const char *status = "FAILURE";
527         struct dsn *dsn = NULL;
528
529         if (!buf || !insertbuf) {
530                 return -1;
531         }
532
533         AST_RWLIST_RDLOCK(&queries);
534         AST_RWLIST_TRAVERSE(&queries, query, list) {
535                 if (!strcmp(query->acf->name, cmd)) {
536                         break;
537                 }
538         }
539
540         if (!query) {
541                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
542                 AST_RWLIST_UNLOCK(&queries);
543                 if (chan) {
544                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
545                 }
546                 return -1;
547         }
548
549         if (!chan) {
550                 if (!(chan = ast_dummy_channel_alloc())) {
551                         AST_RWLIST_UNLOCK(&queries);
552                         return -1;
553                 }
554                 bogus_chan = 1;
555         }
556
557         if (!bogus_chan) {
558                 ast_autoservice_start(chan);
559         }
560
561         ast_str_make_space(&buf, strlen(query->sql_write) * 2 + 300);
562         /* We only get here if sql_write is set. sql_insert is optional however. */
563         if (query->sql_insert) {
564                 ast_str_make_space(&insertbuf, strlen(query->sql_insert) * 2 + 300);
565         }
566
567         /* Parse our arguments */
568         t = value ? ast_strdupa(value) : "";
569
570         if (!s || !t) {
571                 ast_log(LOG_ERROR, "Out of memory\n");
572                 AST_RWLIST_UNLOCK(&queries);
573                 if (!bogus_chan) {
574                         ast_autoservice_stop(chan);
575                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
576                 } else {
577                         ast_channel_unref(chan);
578                 }
579                 return -1;
580         }
581
582         AST_STANDARD_APP_ARGS(args, s);
583         for (i = 0; i < args.argc; i++) {
584                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
585                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
586         }
587
588         /* Parse values, just like arguments */
589         AST_STANDARD_APP_ARGS(values, t);
590         for (i = 0; i < values.argc; i++) {
591                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
592                 pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
593         }
594
595         /* Additionally set the value as a whole (but push an empty string if value is NULL) */
596         pbx_builtin_pushvar_helper(chan, "VALUE", value ? value : "");
597
598         ast_str_substitute_variables(&buf, 0, chan, query->sql_write);
599         if (query->sql_insert) {
600                 ast_str_substitute_variables(&insertbuf, 0, chan, query->sql_insert);
601         }
602
603         if (bogus_chan) {
604                 chan = ast_channel_unref(chan);
605         } else {
606                 /* Restore prior values */
607                 for (i = 0; i < args.argc; i++) {
608                         snprintf(varname, sizeof(varname), "ARG%d", i + 1);
609                         pbx_builtin_setvar_helper(chan, varname, NULL);
610                 }
611
612                 for (i = 0; i < values.argc; i++) {
613                         snprintf(varname, sizeof(varname), "VAL%d", i + 1);
614                         pbx_builtin_setvar_helper(chan, varname, NULL);
615                 }
616                 pbx_builtin_setvar_helper(chan, "VALUE", NULL);
617         }
618
619         /*!\note
620          * Okay, this part is confusing.  Transactions belong to a single database
621          * handle.  Therefore, when working with transactions, we CANNOT failover
622          * to multiple DSNs.  We MUST have a single handle all the way through the
623          * transaction, or else we CANNOT enforce atomicity.
624          */
625         for (dsn_num = 0; dsn_num < 5; dsn_num++) {
626                 if (!ast_strlen_zero(query->writehandle[dsn_num])) {
627                         if (transactional) {
628                                 /* This can only happen second time through or greater. */
629                                 ast_log(LOG_WARNING, "Transactions do not work well with multiple DSNs for 'writehandle'\n");
630                         }
631
632                         if ((obj = ast_odbc_retrieve_transaction_obj(chan, query->writehandle[dsn_num]))) {
633                                 transactional = 1;
634                         } else {
635                                 obj = get_odbc_obj(query->writehandle[dsn_num], &dsn);
636                                 transactional = 0;
637                         }
638
639                         if (obj && (stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(buf)))) {
640                                 break;
641                         }
642                         if (!transactional) {
643                                 release_obj_or_dsn (&obj, &dsn);
644                         }
645                 }
646         }
647
648         if (stmt) {
649                 SQLRowCount(stmt, &rows);
650                 SQLCloseCursor(stmt);
651                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
652
653                 if (rows != 0) {
654                         status = "SUCCESS";
655
656                 } else if (query->sql_insert) {
657                         if (!transactional) {
658                                 release_obj_or_dsn (&obj, &dsn);
659                         }
660
661                         for (transactional = 0, dsn_num = 0; dsn_num < 5; dsn_num++) {
662                                 if (!ast_strlen_zero(query->writehandle[dsn_num])) {
663                                         if (transactional) {
664                                                 /* This can only happen second time through or greater. */
665                                                 ast_log(LOG_WARNING, "Transactions do not work well with multiple DSNs for 'writehandle'\n");
666                                         } else {
667                                                 release_obj_or_dsn (&obj, &dsn);
668                                         }
669
670                                         if ((obj = ast_odbc_retrieve_transaction_obj(chan, query->writehandle[dsn_num]))) {
671                                                 transactional = 1;
672                                         } else {
673                                                 obj = get_odbc_obj(query->writehandle[dsn_num], &dsn);
674                                                 transactional = 0;
675                                         }
676                                         if (obj) {
677                                                 stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(insertbuf));
678                                         }
679                                 }
680                                 if (stmt) {
681                                         status = "FAILOVER";
682                                         SQLRowCount(stmt, &rows);
683                                         SQLCloseCursor(stmt);
684                                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
685                                         break;
686                                 }
687                         }
688                 }
689         }
690
691         AST_RWLIST_UNLOCK(&queries);
692
693         /* Output the affected rows, for all cases.  In the event of failure, we
694          * flag this as -1 rows.  Note that this is different from 0 affected rows
695          * which would be the case if we succeeded in our query, but the values did
696          * not change. */
697         if (!bogus_chan) {
698                 snprintf(varname, sizeof(varname), "%d", (int)rows);
699                 pbx_builtin_setvar_helper(chan, "ODBCROWS", varname);
700                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
701         }
702
703         if (!transactional) {
704                 release_obj_or_dsn (&obj, &dsn);
705         }
706
707         if (!bogus_chan) {
708                 ast_autoservice_stop(chan);
709         }
710
711         return 0;
712 }
713
714 static int acf_odbc_read(struct ast_channel *chan, const char *cmd, char *s, char *buf, size_t len)
715 {
716         struct odbc_obj *obj = NULL;
717         struct acf_odbc_query *query;
718         char varname[15], rowcount[12] = "-1";
719         struct ast_str *colnames = ast_str_thread_get(&colnames_buf, 16);
720         int res, x, y, buflen = 0, escapecommas, rowlimit = 1, multirow = 0, dsn_num, bogus_chan = 0;
721         AST_DECLARE_APP_ARGS(args,
722                 AST_APP_ARG(field)[100];
723         );
724         SQLHSTMT stmt = NULL;
725         SQLSMALLINT colcount=0;
726         SQLLEN indicator;
727         SQLSMALLINT collength;
728         struct odbc_datastore *resultset = NULL;
729         struct odbc_datastore_row *row = NULL;
730         struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
731         const char *status = "FAILURE";
732         struct dsn *dsn = NULL;
733
734         if (!sql || !colnames) {
735                 if (chan) {
736                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
737                 }
738                 return -1;
739         }
740
741         ast_str_reset(colnames);
742
743         AST_RWLIST_RDLOCK(&queries);
744         AST_RWLIST_TRAVERSE(&queries, query, list) {
745                 if (!strcmp(query->acf->name, cmd)) {
746                         break;
747                 }
748         }
749
750         if (!query) {
751                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
752                 AST_RWLIST_UNLOCK(&queries);
753                 if (chan) {
754                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
755                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
756                 }
757                 return -1;
758         }
759
760         if (!chan) {
761                 if (!(chan = ast_dummy_channel_alloc())) {
762                         AST_RWLIST_UNLOCK(&queries);
763                         return -1;
764                 }
765                 bogus_chan = 1;
766         }
767
768         if (!bogus_chan) {
769                 ast_autoservice_start(chan);
770         }
771
772         AST_STANDARD_APP_ARGS(args, s);
773         for (x = 0; x < args.argc; x++) {
774                 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
775                 pbx_builtin_pushvar_helper(chan, varname, args.field[x]);
776         }
777
778         ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
779
780         if (bogus_chan) {
781                 chan = ast_channel_unref(chan);
782         } else {
783                 /* Restore prior values */
784                 for (x = 0; x < args.argc; x++) {
785                         snprintf(varname, sizeof(varname), "ARG%d", x + 1);
786                         pbx_builtin_setvar_helper(chan, varname, NULL);
787                 }
788         }
789
790         /* Save these flags, so we can release the lock */
791         escapecommas = ast_test_flag(query, OPT_ESCAPECOMMAS);
792         if (!bogus_chan && ast_test_flag(query, OPT_MULTIROW)) {
793                 if (!(resultset = ast_calloc(1, sizeof(*resultset)))) {
794                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
795                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
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_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                         return a->n == 0 ? ast_strdup("exec") : NULL;
1423                 } else {
1424                         return NULL;
1425                 }
1426         }
1427
1428         if (a->argc < 4 || a->argc > 5) {
1429                 return CLI_SHOWUSAGE;
1430         }
1431
1432         sql = ast_str_thread_get(&sql_buf, 16);
1433         if (!sql) {
1434                 return CLI_FAILURE;
1435         }
1436
1437         AST_RWLIST_RDLOCK(&queries);
1438         AST_RWLIST_TRAVERSE(&queries, query, list) {
1439                 if (!strcmp(query->acf->name, a->argv[2])) {
1440                         break;
1441                 }
1442         }
1443
1444         if (!query) {
1445                 ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
1446                 AST_RWLIST_UNLOCK(&queries);
1447                 return CLI_SHOWUSAGE;
1448         }
1449
1450         if (!query->sql_read) {
1451                 ast_cli(a->fd, "The function %s has no readsql parameter.\n", a->argv[2]);
1452                 AST_RWLIST_UNLOCK(&queries);
1453                 return CLI_SUCCESS;
1454         }
1455
1456         ast_str_make_space(&sql, strlen(query->sql_read) * 2 + 300);
1457
1458         /* Evaluate function */
1459         char_args = ast_strdupa(a->argv[3]);
1460
1461         chan = ast_dummy_channel_alloc();
1462         if (!chan) {
1463                 AST_RWLIST_UNLOCK(&queries);
1464                 return CLI_FAILURE;
1465         }
1466
1467         AST_STANDARD_APP_ARGS(args, char_args);
1468         for (i = 0; i < args.argc; i++) {
1469                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
1470                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
1471         }
1472
1473         ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
1474         chan = ast_channel_unref(chan);
1475
1476         if (a->argc == 5 && !strcmp(a->argv[4], "exec")) {
1477                 /* Execute the query */
1478                 struct odbc_obj *obj = NULL;
1479                 struct dsn *dsn = NULL;
1480                 int dsn_num, executed = 0;
1481                 SQLHSTMT stmt;
1482                 int rows = 0, res, x;
1483                 SQLSMALLINT colcount = 0, collength;
1484                 SQLLEN indicator;
1485                 struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
1486                 char colname[256];
1487                 SQLULEN maxcol;
1488
1489                 if (!coldata) {
1490                         AST_RWLIST_UNLOCK(&queries);
1491                         return CLI_SUCCESS;
1492                 }
1493
1494                 for (dsn_num = 0; dsn_num < 5; dsn_num++) {
1495                         if (ast_strlen_zero(query->readhandle[dsn_num])) {
1496                                 continue;
1497                         }
1498                         obj = get_odbc_obj(query->readhandle[dsn_num], &dsn);
1499                         if (!obj) {
1500                                 continue;
1501                         }
1502                         ast_debug(1, "Found handle %s\n", query->readhandle[dsn_num]);
1503
1504                         if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
1505                                 release_obj_or_dsn (&obj, &dsn);
1506                                 continue;
1507                         }
1508
1509                         executed = 1;
1510
1511                         res = SQLNumResultCols(stmt, &colcount);
1512                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1513                                 ast_cli(a->fd, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
1514                                 SQLCloseCursor(stmt);
1515                                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1516                                 release_obj_or_dsn (&obj, &dsn);
1517                                 AST_RWLIST_UNLOCK(&queries);
1518                                 return CLI_SUCCESS;
1519                         }
1520
1521                         res = SQLFetch(stmt);
1522                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1523                                 SQLCloseCursor(stmt);
1524                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1525                                 release_obj_or_dsn (&obj, &dsn);
1526                                 if (res == SQL_NO_DATA) {
1527                                         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));
1528                                         break;
1529                                 } else {
1530                                         ast_cli(a->fd, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
1531                                 }
1532                                 AST_RWLIST_UNLOCK(&queries);
1533                                 return CLI_SUCCESS;
1534                         }
1535                         for (;;) {
1536                                 for (x = 0; x < colcount; x++) {
1537                                         maxcol = 0;
1538
1539                                         res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
1540                                         if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
1541                                                 snprintf(colname, sizeof(colname), "field%d", x);
1542                                         }
1543
1544                                         res = ast_odbc_ast_str_SQLGetData(&coldata, maxcol, stmt, x + 1, SQL_CHAR, &indicator);
1545                                         if (indicator == SQL_NULL_DATA) {
1546                                                 ast_str_set(&coldata, 0, "(nil)");
1547                                                 res = SQL_SUCCESS;
1548                                         }
1549
1550                                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1551                                                 ast_cli(a->fd, "SQL Get Data error %d!\n[%s]\n\n", res, ast_str_buffer(sql));
1552                                                 SQLCloseCursor(stmt);
1553                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1554                                                 release_obj_or_dsn (&obj, &dsn);
1555                                                 AST_RWLIST_UNLOCK(&queries);
1556                                                 return CLI_SUCCESS;
1557                                         }
1558
1559                                         ast_cli(a->fd, "%-20.20s  %s\n", colname, ast_str_buffer(coldata));
1560                                 }
1561                                 rows++;
1562
1563                                 /* Get next row */
1564                                 res = SQLFetch(stmt);
1565                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1566                                         break;
1567                                 }
1568                                 ast_cli(a->fd, "%-20.20s  %s\n", "----------", "----------");
1569                         }
1570                         SQLCloseCursor(stmt);
1571                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1572                         release_obj_or_dsn (&obj, &dsn);
1573                         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]);
1574                         break;
1575                 }
1576                 release_obj_or_dsn (&obj, &dsn);
1577
1578                 if (!executed) {
1579                         ast_cli(a->fd, "Failed to execute query. [%s]\n", ast_str_buffer(sql));
1580                 }
1581         } else { /* No execution, just print out the resulting SQL */
1582                 ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
1583         }
1584         AST_RWLIST_UNLOCK(&queries);
1585         return CLI_SUCCESS;
1586 }
1587
1588 static char *cli_odbc_write(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1589 {
1590         AST_DECLARE_APP_ARGS(values,
1591                 AST_APP_ARG(field)[100];
1592         );
1593         AST_DECLARE_APP_ARGS(args,
1594                 AST_APP_ARG(field)[100];
1595         );
1596         struct ast_str *sql;
1597         char *char_args, *char_values, varname[10];
1598         struct acf_odbc_query *query;
1599         struct ast_channel *chan;
1600         int i;
1601
1602         switch (cmd) {
1603         case CLI_INIT:
1604                 e->command = "odbc write";
1605                 e->usage =
1606                         "Usage: odbc write <name> <args> <value> [exec]\n"
1607                         "       Evaluates the SQL provided in the ODBC function <name>, and\n"
1608                         "       optionally executes the function.  This function is intended for\n"
1609                         "       testing purposes.  Remember to quote arguments containing spaces.\n";
1610                 return NULL;
1611         case CLI_GENERATE:
1612                 if (a->pos == 2) {
1613                         int wordlen = strlen(a->word), which = 0;
1614                         /* Complete function name */
1615                         AST_RWLIST_RDLOCK(&queries);
1616                         AST_RWLIST_TRAVERSE(&queries, query, list) {
1617                                 if (!strncasecmp(query->acf->name, a->word, wordlen)) {
1618                                         if (++which > a->n) {
1619                                                 char *res = ast_strdup(query->acf->name);
1620                                                 AST_RWLIST_UNLOCK(&queries);
1621                                                 return res;
1622                                         }
1623                                 }
1624                         }
1625                         AST_RWLIST_UNLOCK(&queries);
1626                         return NULL;
1627                 } else if (a->pos == 5) {
1628                         return a->n == 0 ? ast_strdup("exec") : NULL;
1629                 } else {
1630                         return NULL;
1631                 }
1632         }
1633
1634         if (a->argc < 5 || a->argc > 6) {
1635                 return CLI_SHOWUSAGE;
1636         }
1637
1638         sql = ast_str_thread_get(&sql_buf, 16);
1639         if (!sql) {
1640                 return CLI_FAILURE;
1641         }
1642
1643         AST_RWLIST_RDLOCK(&queries);
1644         AST_RWLIST_TRAVERSE(&queries, query, list) {
1645                 if (!strcmp(query->acf->name, a->argv[2])) {
1646                         break;
1647                 }
1648         }
1649
1650         if (!query) {
1651                 ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
1652                 AST_RWLIST_UNLOCK(&queries);
1653                 return CLI_SHOWUSAGE;
1654         }
1655
1656         if (!query->sql_write) {
1657                 ast_cli(a->fd, "The function %s has no writesql parameter.\n", a->argv[2]);
1658                 AST_RWLIST_UNLOCK(&queries);
1659                 return CLI_SUCCESS;
1660         }
1661
1662         /* FIXME: The code below duplicates code found in acf_odbc_write but
1663          * lacks the newer sql_insert additions. */
1664
1665         ast_str_make_space(&sql, strlen(query->sql_write) * 2 + 300);
1666
1667         /* Evaluate function */
1668         char_args = ast_strdupa(a->argv[3]);
1669         char_values = ast_strdupa(a->argv[4]);
1670
1671         chan = ast_dummy_channel_alloc();
1672         if (!chan) {
1673                 AST_RWLIST_UNLOCK(&queries);
1674                 return CLI_FAILURE;
1675         }
1676
1677         AST_STANDARD_APP_ARGS(args, char_args);
1678         for (i = 0; i < args.argc; i++) {
1679                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
1680                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
1681         }
1682
1683         /* Parse values, just like arguments */
1684         AST_STANDARD_APP_ARGS(values, char_values);
1685         for (i = 0; i < values.argc; i++) {
1686                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
1687                 pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
1688         }
1689
1690         /* Additionally set the value as a whole (but push an empty string if value is NULL) */
1691         pbx_builtin_pushvar_helper(chan, "VALUE", S_OR(a->argv[4], ""));
1692         ast_str_substitute_variables(&sql, 0, chan, query->sql_write);
1693         ast_debug(1, "SQL is %s\n", ast_str_buffer(sql));
1694
1695         chan = ast_channel_unref(chan);
1696
1697         if (a->argc == 6 && !strcmp(a->argv[5], "exec")) {
1698                 /* Execute the query */
1699                 struct odbc_obj *obj = NULL;
1700                 struct dsn *dsn = NULL;
1701                 int dsn_num, executed = 0;
1702                 SQLHSTMT stmt;
1703                 SQLLEN rows = -1;
1704
1705                 for (dsn_num = 0; dsn_num < 5; dsn_num++) {
1706                         if (ast_strlen_zero(query->writehandle[dsn_num])) {
1707                                 continue;
1708                         }
1709                         obj = get_odbc_obj(query->writehandle[dsn_num], &dsn);
1710                         if (!obj) {
1711                                 continue;
1712                         }
1713                         if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
1714                                 release_obj_or_dsn (&obj, &dsn);
1715                                 continue;
1716                         }
1717
1718                         SQLRowCount(stmt, &rows);
1719                         SQLCloseCursor(stmt);
1720                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1721                         release_obj_or_dsn (&obj, &dsn);
1722                         ast_cli(a->fd, "Affected %d rows.  Query executed on handle %d [%s]\n", (int)rows, dsn_num, query->writehandle[dsn_num]);
1723                         executed = 1;
1724                         break;
1725                 }
1726
1727                 if (!executed) {
1728                         ast_cli(a->fd, "Failed to execute query.\n");
1729                 }
1730         } else { /* No execution, just print out the resulting SQL */
1731                 ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
1732         }
1733         AST_RWLIST_UNLOCK(&queries);
1734         return CLI_SUCCESS;
1735 }
1736
1737 static struct ast_cli_entry cli_func_odbc[] = {
1738         AST_CLI_DEFINE(cli_odbc_write, "Test setting a func_odbc function"),
1739         AST_CLI_DEFINE(cli_odbc_read, "Test reading a func_odbc function"),
1740 };
1741
1742 static int load_module(void)
1743 {
1744         int res = 0;
1745         struct ast_config *cfg;
1746         char *catg;
1747         const char *s;
1748         struct ast_flags config_flags = { 0 };
1749
1750         res |= ast_custom_function_register(&fetch_function);
1751         res |= ast_register_application_xml(app_odbcfinish, exec_odbcfinish);
1752
1753         cfg = ast_config_load(config, config_flags);
1754         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
1755                 ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
1756                 return AST_MODULE_LOAD_DECLINE;
1757         }
1758
1759         ast_rwlock_wrlock(&single_db_connection_lock);
1760         if ((s = ast_variable_retrieve(cfg, "general", "single_db_connection"))) {
1761                 single_db_connection = ast_true(s);
1762         } else {
1763                 single_db_connection = DEFAULT_SINGLE_DB_CONNECTION;
1764         }
1765
1766         dsns = NULL;
1767
1768         if (single_db_connection) {
1769                 dsns = ao2_container_alloc(DSN_BUCKETS, dsn_hash, dsn_cmp);
1770                 if (!dsns) {
1771                         ast_log(LOG_ERROR, "Could not initialize DSN container\n");
1772                         ast_rwlock_unlock(&single_db_connection_lock);
1773                         return AST_MODULE_LOAD_DECLINE;
1774                 }
1775         }
1776         ast_rwlock_unlock(&single_db_connection_lock);
1777
1778         AST_RWLIST_WRLOCK(&queries);
1779         for (catg = ast_category_browse(cfg, NULL);
1780              catg;
1781              catg = ast_category_browse(cfg, catg)) {
1782                 struct acf_odbc_query *query = NULL;
1783                 int err;
1784
1785                 if (!strcasecmp(catg, "general")) {
1786                         continue;
1787                 }
1788
1789                 if ((err = init_acf_query(cfg, catg, &query))) {
1790                         if (err == ENOMEM)
1791                                 ast_log(LOG_ERROR, "Out of memory\n");
1792                         else if (err == EINVAL)
1793                                 ast_log(LOG_ERROR, "Invalid parameters for category %s\n", catg);
1794                         else
1795                                 ast_log(LOG_ERROR, "%s (%d)\n", strerror(err), err);
1796                 } else {
1797                         AST_RWLIST_INSERT_HEAD(&queries, query, list);
1798                         ast_custom_function_register(query->acf);
1799                 }
1800         }
1801
1802         ast_config_destroy(cfg);
1803         res |= ast_custom_function_register(&escape_function);
1804         ast_cli_register_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
1805
1806         AST_RWLIST_UNLOCK(&queries);
1807         return res;
1808 }
1809
1810 static int unload_module(void)
1811 {
1812         struct acf_odbc_query *query;
1813         int res = 0;
1814
1815         AST_RWLIST_WRLOCK(&queries);
1816         while (!AST_RWLIST_EMPTY(&queries)) {
1817                 query = AST_RWLIST_REMOVE_HEAD(&queries, list);
1818                 ast_custom_function_unregister(query->acf);
1819                 free_acf_query(query);
1820         }
1821
1822         res |= ast_custom_function_unregister(&escape_function);
1823         res |= ast_custom_function_unregister(&fetch_function);
1824         res |= ast_unregister_application(app_odbcfinish);
1825         ast_cli_unregister_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
1826
1827         /* Allow any threads waiting for this lock to pass (avoids a race) */
1828         AST_RWLIST_UNLOCK(&queries);
1829         usleep(1);
1830         AST_RWLIST_WRLOCK(&queries);
1831
1832         AST_RWLIST_UNLOCK(&queries);
1833
1834         if (dsns) {
1835                 ao2_ref(dsns, -1);
1836         }
1837         return res;
1838 }
1839
1840 static int reload(void)
1841 {
1842         int res = 0;
1843         struct ast_config *cfg;
1844         struct acf_odbc_query *oldquery;
1845         char *catg;
1846         const char *s;
1847         struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
1848
1849         cfg = ast_config_load(config, config_flags);
1850         if (cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
1851                 return 0;
1852
1853         ast_rwlock_wrlock(&single_db_connection_lock);
1854
1855         if (dsns) {
1856                 ao2_ref(dsns, -1);
1857                 dsns = NULL;
1858         }
1859
1860         if (cfg && (s = ast_variable_retrieve(cfg, "general", "single_db_connection"))) {
1861                 single_db_connection = ast_true(s);
1862         } else {
1863                 single_db_connection = DEFAULT_SINGLE_DB_CONNECTION;
1864         }
1865
1866         if (single_db_connection) {
1867                 dsns = ao2_container_alloc(DSN_BUCKETS, dsn_hash, dsn_cmp);
1868                 if (!dsns) {
1869                         ast_log(LOG_ERROR, "Could not initialize DSN container\n");
1870                         ast_rwlock_unlock(&single_db_connection_lock);
1871                         return 0;
1872                 }
1873         }
1874         ast_rwlock_unlock(&single_db_connection_lock);
1875
1876         AST_RWLIST_WRLOCK(&queries);
1877
1878         while (!AST_RWLIST_EMPTY(&queries)) {
1879                 oldquery = AST_RWLIST_REMOVE_HEAD(&queries, list);
1880                 ast_custom_function_unregister(oldquery->acf);
1881                 free_acf_query(oldquery);
1882         }
1883
1884         if (!cfg) {
1885                 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
1886                 goto reload_out;
1887         }
1888
1889         for (catg = ast_category_browse(cfg, NULL);
1890              catg;
1891              catg = ast_category_browse(cfg, catg)) {
1892                 struct acf_odbc_query *query = NULL;
1893
1894                 if (!strcasecmp(catg, "general")) {
1895                         continue;
1896                 }
1897
1898                 if (init_acf_query(cfg, catg, &query)) {
1899                         ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
1900                 } else {
1901                         AST_RWLIST_INSERT_HEAD(&queries, query, list);
1902                         ast_custom_function_register(query->acf);
1903                 }
1904         }
1905
1906         ast_config_destroy(cfg);
1907 reload_out:
1908         AST_RWLIST_UNLOCK(&queries);
1909         return res;
1910 }
1911
1912 /* XXX need to revise usecount - set if query_lock is set */
1913
1914 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
1915         .support_level = AST_MODULE_SUPPORT_CORE,
1916         .load = load_module,
1917         .unload = unload_module,
1918         .reload = reload,
1919 );
1920