res_smdi: Fix shutdown ref.
[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_autoservice_stop(chan);
795                         return -1;
796                 }
797                 AST_LIST_HEAD_INIT(resultset);
798                 if (query->rowlimit) {
799                         rowlimit = query->rowlimit;
800                 } else {
801                         rowlimit = INT_MAX;
802                 }
803                 multirow = 1;
804         } else if (!bogus_chan) {
805                 if (query->rowlimit > 1) {
806                         rowlimit = query->rowlimit;
807                         if (!(resultset = ast_calloc(1, sizeof(*resultset)))) {
808                                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
809                                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
810                                 ast_autoservice_stop(chan);
811                                 return -1;
812                         }
813                         AST_LIST_HEAD_INIT(resultset);
814                 }
815         }
816         AST_RWLIST_UNLOCK(&queries);
817
818         for (dsn_num = 0; dsn_num < 5; dsn_num++) {
819                 if (!ast_strlen_zero(query->readhandle[dsn_num])) {
820                         obj = get_odbc_obj(query->readhandle[dsn_num], &dsn);
821                         if (!obj) {
822                                 continue;
823                         }
824                         stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql));
825                 }
826                 if (stmt) {
827                         break;
828                 }
829                 release_obj_or_dsn (&obj, &dsn);
830         }
831
832         if (!stmt) {
833                 ast_log(LOG_ERROR, "Unable to execute query [%s]\n", ast_str_buffer(sql));
834                 release_obj_or_dsn (&obj, &dsn);
835                 if (!bogus_chan) {
836                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
837                         ast_autoservice_stop(chan);
838                 }
839                 odbc_datastore_free(resultset);
840                 return -1;
841         }
842
843         res = SQLNumResultCols(stmt, &colcount);
844         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
845                 ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
846                 SQLCloseCursor(stmt);
847                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
848                 release_obj_or_dsn (&obj, &dsn);
849                 if (!bogus_chan) {
850                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
851                         ast_autoservice_stop(chan);
852                 }
853                 odbc_datastore_free(resultset);
854                 return -1;
855         }
856
857         res = SQLFetch(stmt);
858         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
859                 int res1 = -1;
860                 if (res == SQL_NO_DATA) {
861                         ast_verb(4, "Found no rows [%s]\n", ast_str_buffer(sql));
862                         res1 = 0;
863                         buf[0] = '\0';
864                         ast_copy_string(rowcount, "0", sizeof(rowcount));
865                         status = "NODATA";
866                 } else {
867                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
868                         status = "FETCHERROR";
869                 }
870                 SQLCloseCursor(stmt);
871                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
872                 release_obj_or_dsn (&obj, &dsn);
873                 if (!bogus_chan) {
874                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
875                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
876                         ast_autoservice_stop(chan);
877                 }
878                 odbc_datastore_free(resultset);
879                 return res1;
880         }
881
882         status = "SUCCESS";
883
884         for (y = 0; y < rowlimit; y++) {
885                 buf[0] = '\0';
886                 for (x = 0; x < colcount; x++) {
887                         int i;
888                         struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
889                         char *ptrcoldata;
890
891                         if (!coldata) {
892                                 odbc_datastore_free(resultset);
893                                 SQLCloseCursor(stmt);
894                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
895                                 release_obj_or_dsn (&obj, &dsn);
896                                 if (!bogus_chan) {
897                                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
898                                         ast_autoservice_stop(chan);
899                                 }
900                                 return -1;
901                         }
902
903                         if (y == 0) {
904                                 char colname[256];
905                                 SQLULEN maxcol = 0;
906
907                                 res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
908                                 ast_debug(3, "Got collength of %d and maxcol of %d for column '%s' (offset %d)\n", (int)collength, (int)maxcol, colname, x);
909                                 if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
910                                         snprintf(colname, sizeof(colname), "field%d", x);
911                                 }
912
913                                 ast_str_make_space(&coldata, maxcol + 1);
914
915                                 if (ast_str_strlen(colnames)) {
916                                         ast_str_append(&colnames, 0, ",");
917                                 }
918                                 ast_str_append_escapecommas(&colnames, 0, colname, sizeof(colname));
919
920                                 if (resultset) {
921                                         void *tmp = ast_realloc(resultset, sizeof(*resultset) + ast_str_strlen(colnames) + 1);
922                                         if (!tmp) {
923                                                 ast_log(LOG_ERROR, "No space for a new resultset?\n");
924                                                 odbc_datastore_free(resultset);
925                                                 SQLCloseCursor(stmt);
926                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
927                                                 release_obj_or_dsn (&obj, &dsn);
928                                                 if (!bogus_chan) {
929                                                         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
930                                                         pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
931                                                         ast_autoservice_stop(chan);
932                                                 }
933                                                 return -1;
934                                         }
935                                         resultset = tmp;
936                                         strcpy((char *)resultset + sizeof(*resultset), ast_str_buffer(colnames));
937                                 }
938                         }
939
940                         buflen = strlen(buf);
941                         res = ast_odbc_ast_str_SQLGetData(&coldata, -1, stmt, x + 1, SQL_CHAR, &indicator);
942                         if (indicator == SQL_NULL_DATA) {
943                                 ast_debug(3, "Got NULL data\n");
944                                 ast_str_reset(coldata);
945                                 res = SQL_SUCCESS;
946                         }
947
948                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
949                                 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", ast_str_buffer(sql));
950                                 y = -1;
951                                 buf[0] = '\0';
952                                 goto end_acf_read;
953                         }
954
955                         ast_debug(2, "Got coldata of '%s'\n", ast_str_buffer(coldata));
956
957                         if (x) {
958                                 buf[buflen++] = ',';
959                         }
960
961                         /* Copy data, encoding '\' and ',' for the argument parser */
962                         ptrcoldata = ast_str_buffer(coldata);
963                         for (i = 0; i < ast_str_strlen(coldata); i++) {
964                                 if (escapecommas && (ptrcoldata[i] == '\\' || ptrcoldata[i] == ',')) {
965                                         buf[buflen++] = '\\';
966                                 }
967                                 buf[buflen++] = ptrcoldata[i];
968
969                                 if (buflen >= len - 2) {
970                                         break;
971                                 }
972
973                                 if (ptrcoldata[i] == '\0') {
974                                         break;
975                                 }
976                         }
977
978                         buf[buflen] = '\0';
979                         ast_debug(2, "buf is now set to '%s'\n", buf);
980                 }
981                 ast_debug(2, "buf is now set to '%s'\n", buf);
982
983                 if (resultset) {
984                         row = ast_calloc(1, sizeof(*row) + buflen + 1);
985                         if (!row) {
986                                 ast_log(LOG_ERROR, "Unable to allocate space for more rows in this resultset.\n");
987                                 status = "MEMERROR";
988                                 goto end_acf_read;
989                         }
990                         strcpy((char *)row + sizeof(*row), buf);
991                         AST_LIST_INSERT_TAIL(resultset, row, list);
992
993                         /* Get next row */
994                         res = SQLFetch(stmt);
995                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
996                                 if (res != SQL_NO_DATA) {
997                                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
998                                 }
999                                 /* Number of rows in the resultset */
1000                                 y++;
1001                                 break;
1002                         }
1003                 }
1004         }
1005
1006 end_acf_read:
1007         if (!bogus_chan) {
1008                 snprintf(rowcount, sizeof(rowcount), "%d", y);
1009                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
1010                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
1011                 pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", ast_str_buffer(colnames));
1012                 if (resultset) {
1013                         struct ast_datastore *odbc_store;
1014                         if (multirow) {
1015                                 int uid;
1016                                 uid = ast_atomic_fetchadd_int(&resultcount, +1) + 1;
1017                                 snprintf(buf, len, "%d", uid);
1018                         } else {
1019                                 /* Name of the query is name of the resultset */
1020                                 ast_copy_string(buf, cmd, len);
1021
1022                                 /* If there's one with the same name already, free it */
1023                                 ast_channel_lock(chan);
1024                                 if ((odbc_store = ast_channel_datastore_find(chan, &odbc_info, buf))) {
1025                                         ast_channel_datastore_remove(chan, odbc_store);
1026                                         ast_datastore_free(odbc_store);
1027                                 }
1028                                 ast_channel_unlock(chan);
1029                         }
1030                         odbc_store = ast_datastore_alloc(&odbc_info, buf);
1031                         if (!odbc_store) {
1032                                 ast_log(LOG_ERROR, "Rows retrieved, but unable to store it in the channel.  Results fail.\n");
1033                                 odbc_datastore_free(resultset);
1034                                 SQLCloseCursor(stmt);
1035                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1036                                 release_obj_or_dsn (&obj, &dsn);
1037                                 pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
1038                                 ast_autoservice_stop(chan);
1039                                 return -1;
1040                         }
1041                         odbc_store->data = resultset;
1042                         ast_channel_lock(chan);
1043                         ast_channel_datastore_add(chan, odbc_store);
1044                         ast_channel_unlock(chan);
1045                 }
1046         }
1047         SQLCloseCursor(stmt);
1048         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1049         release_obj_or_dsn (&obj, &dsn);
1050         if (resultset && !multirow) {
1051                 /* Fetch the first resultset */
1052                 if (!acf_fetch(chan, "", buf, buf, len)) {
1053                         buf[0] = '\0';
1054                 }
1055         }
1056         if (!bogus_chan) {
1057                 ast_autoservice_stop(chan);
1058         }
1059         return 0;
1060 }
1061
1062 static int acf_escape(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1063 {
1064         char *out = buf;
1065
1066         for (; *data && out - buf < len; data++) {
1067                 if (*data == '\'') {
1068                         *out = '\'';
1069                         out++;
1070                 }
1071                 *out++ = *data;
1072         }
1073         *out = '\0';
1074
1075         return 0;
1076 }
1077
1078 static struct ast_custom_function escape_function = {
1079         .name = "SQL_ESC",
1080         .read = acf_escape,
1081         .write = NULL,
1082 };
1083
1084 static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1085 {
1086         struct ast_datastore *store;
1087         struct odbc_datastore *resultset;
1088         struct odbc_datastore_row *row;
1089
1090         if (!chan) {
1091                 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
1092                 return -1;
1093         }
1094
1095         ast_channel_lock(chan);
1096         store = ast_channel_datastore_find(chan, &odbc_info, data);
1097         if (!store) {
1098                 ast_channel_unlock(chan);
1099                 pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
1100                 return -1;
1101         }
1102         resultset = store->data;
1103         AST_LIST_LOCK(resultset);
1104         row = AST_LIST_REMOVE_HEAD(resultset, list);
1105         AST_LIST_UNLOCK(resultset);
1106         if (!row) {
1107                 /* Cleanup datastore */
1108                 ast_channel_datastore_remove(chan, store);
1109                 ast_datastore_free(store);
1110                 ast_channel_unlock(chan);
1111                 pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
1112                 return -1;
1113         }
1114         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", resultset->names);
1115         ast_channel_unlock(chan);
1116         ast_copy_string(buf, row->data, len);
1117         ast_free(row);
1118         pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "SUCCESS");
1119         return 0;
1120 }
1121
1122 static struct ast_custom_function fetch_function = {
1123         .name = "ODBC_FETCH",
1124         .read = acf_fetch,
1125         .write = NULL,
1126 };
1127
1128 static char *app_odbcfinish = "ODBCFinish";
1129
1130 static int exec_odbcfinish(struct ast_channel *chan, const char *data)
1131 {
1132         struct ast_datastore *store;
1133
1134         ast_channel_lock(chan);
1135         store = ast_channel_datastore_find(chan, &odbc_info, data);
1136         if (store) {
1137                 ast_channel_datastore_remove(chan, store);
1138                 ast_datastore_free(store);
1139         }
1140         ast_channel_unlock(chan);
1141         return 0;
1142 }
1143
1144 static int free_acf_query(struct acf_odbc_query *query)
1145 {
1146         if (query) {
1147                 if (query->acf) {
1148                         if (query->acf->name)
1149                                 ast_free((char *)query->acf->name);
1150                         ast_string_field_free_memory(query->acf);
1151                         ast_free(query->acf);
1152                 }
1153                 ast_free(query->sql_read);
1154                 ast_free(query->sql_write);
1155                 ast_free(query->sql_insert);
1156                 ast_free(query);
1157         }
1158         return 0;
1159 }
1160
1161 static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
1162 {
1163         const char *tmp;
1164         const char *tmp2;
1165         int i;
1166
1167         if (!cfg || !catg) {
1168                 return EINVAL;
1169         }
1170
1171         if (!(*query = ast_calloc(1, sizeof(**query)))) {
1172                 return ENOMEM;
1173         }
1174
1175         if (((tmp = ast_variable_retrieve(cfg, catg, "writehandle"))) || ((tmp = ast_variable_retrieve(cfg, catg, "dsn")))) {
1176                 char *tmp2 = ast_strdupa(tmp);
1177                 AST_DECLARE_APP_ARGS(writeconf,
1178                         AST_APP_ARG(dsn)[5];
1179                 );
1180                 AST_STANDARD_APP_ARGS(writeconf, tmp2);
1181                 for (i = 0; i < 5; i++) {
1182                         if (!ast_strlen_zero(writeconf.dsn[i]))
1183                                 ast_copy_string((*query)->writehandle[i], writeconf.dsn[i], sizeof((*query)->writehandle[i]));
1184                 }
1185         }
1186
1187         if ((tmp = ast_variable_retrieve(cfg, catg, "readhandle"))) {
1188                 char *tmp2 = ast_strdupa(tmp);
1189                 AST_DECLARE_APP_ARGS(readconf,
1190                         AST_APP_ARG(dsn)[5];
1191                 );
1192                 AST_STANDARD_APP_ARGS(readconf, tmp2);
1193                 for (i = 0; i < 5; i++) {
1194                         if (!ast_strlen_zero(readconf.dsn[i]))
1195                                 ast_copy_string((*query)->readhandle[i], readconf.dsn[i], sizeof((*query)->readhandle[i]));
1196                 }
1197         } else {
1198                 /* If no separate readhandle, then use the writehandle for reading */
1199                 for (i = 0; i < 5; i++) {
1200                         if (!ast_strlen_zero((*query)->writehandle[i]))
1201                                 ast_copy_string((*query)->readhandle[i], (*query)->writehandle[i], sizeof((*query)->readhandle[i]));
1202                 }
1203         }
1204
1205         if ((tmp = ast_variable_retrieve(cfg, catg, "readsql")) ||
1206                         (tmp2 = ast_variable_retrieve(cfg, catg, "read"))) {
1207                 if (!tmp) {
1208                         ast_log(LOG_WARNING, "Parameter 'read' is deprecated for category %s.  Please use 'readsql' instead.\n", catg);
1209                         tmp = tmp2;
1210                 }
1211                 if (*tmp != '\0') { /* non-empty string */
1212                         if (!((*query)->sql_read = ast_strdup(tmp))) {
1213                                 free_acf_query(*query);
1214                                 *query = NULL;
1215                                 return ENOMEM;
1216                         }
1217                 }
1218         }
1219
1220         if ((*query)->sql_read && ast_strlen_zero((*query)->readhandle[0])) {
1221                 free_acf_query(*query);
1222                 *query = NULL;
1223                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for reading: %s\n", catg);
1224                 return EINVAL;
1225         }
1226
1227         if ((tmp = ast_variable_retrieve(cfg, catg, "writesql")) ||
1228                         (tmp2 = ast_variable_retrieve(cfg, catg, "write"))) {
1229                 if (!tmp) {
1230                         ast_log(LOG_WARNING, "Parameter 'write' is deprecated for category %s.  Please use 'writesql' instead.\n", catg);
1231                         tmp = tmp2;
1232                 }
1233                 if (*tmp != '\0') { /* non-empty string */
1234                         if (!((*query)->sql_write = ast_strdup(tmp))) {
1235                                 free_acf_query(*query);
1236                                 *query = NULL;
1237                                 return ENOMEM;
1238                         }
1239                 }
1240         }
1241
1242         if ((*query)->sql_write && ast_strlen_zero((*query)->writehandle[0])) {
1243                 free_acf_query(*query);
1244                 *query = NULL;
1245                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for writing: %s\n", catg);
1246                 return EINVAL;
1247         }
1248
1249         if ((tmp = ast_variable_retrieve(cfg, catg, "insertsql"))) {
1250                 if (*tmp != '\0') { /* non-empty string */
1251                         if (!((*query)->sql_insert = ast_strdup(tmp))) {
1252                                 free_acf_query(*query);
1253                                 *query = NULL;
1254                                 return ENOMEM;
1255                         }
1256                 }
1257         }
1258
1259         /* Allow escaping of embedded commas in fields to be turned off */
1260         ast_set_flag((*query), OPT_ESCAPECOMMAS);
1261         if ((tmp = ast_variable_retrieve(cfg, catg, "escapecommas"))) {
1262                 if (ast_false(tmp))
1263                         ast_clear_flag((*query), OPT_ESCAPECOMMAS);
1264         }
1265
1266         if ((tmp = ast_variable_retrieve(cfg, catg, "mode"))) {
1267                 if (strcasecmp(tmp, "multirow") == 0)
1268                         ast_set_flag((*query), OPT_MULTIROW);
1269                 if ((tmp = ast_variable_retrieve(cfg, catg, "rowlimit")))
1270                         sscanf(tmp, "%30d", &((*query)->rowlimit));
1271         }
1272
1273         (*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
1274         if (!(*query)->acf) {
1275                 free_acf_query(*query);
1276                 *query = NULL;
1277                 return ENOMEM;
1278         }
1279         if (ast_string_field_init((*query)->acf, 128)) {
1280                 free_acf_query(*query);
1281                 *query = NULL;
1282                 return ENOMEM;
1283         }
1284
1285         if ((tmp = ast_variable_retrieve(cfg, catg, "prefix")) && !ast_strlen_zero(tmp)) {
1286                 if (ast_asprintf((char **)&((*query)->acf->name), "%s_%s", tmp, catg) < 0) {
1287                         (*query)->acf->name = NULL;
1288                 }
1289         } else {
1290                 if (ast_asprintf((char **)&((*query)->acf->name), "ODBC_%s", catg) < 0) {
1291                         (*query)->acf->name = NULL;
1292                 }
1293         }
1294
1295         if (!(*query)->acf->name) {
1296                 free_acf_query(*query);
1297                 *query = NULL;
1298                 return ENOMEM;
1299         }
1300
1301         if ((tmp = ast_variable_retrieve(cfg, catg, "syntax")) && !ast_strlen_zero(tmp)) {
1302                 ast_string_field_build((*query)->acf, syntax, "%s(%s)", (*query)->acf->name, tmp);
1303         } else {
1304                 ast_string_field_build((*query)->acf, syntax, "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
1305         }
1306
1307         if (ast_strlen_zero((*query)->acf->syntax)) {
1308                 free_acf_query(*query);
1309                 *query = NULL;
1310                 return ENOMEM;
1311         }
1312
1313         if ((tmp = ast_variable_retrieve(cfg, catg, "synopsis")) && !ast_strlen_zero(tmp)) {
1314                 ast_string_field_set((*query)->acf, synopsis, tmp);
1315         } else {
1316                 ast_string_field_set((*query)->acf, synopsis, "Runs the referenced query with the specified arguments");
1317         }
1318
1319         if (ast_strlen_zero((*query)->acf->synopsis)) {
1320                 free_acf_query(*query);
1321                 *query = NULL;
1322                 return ENOMEM;
1323         }
1324
1325         if ((*query)->sql_read && (*query)->sql_write) {
1326                 ast_string_field_build((*query)->acf, desc,
1327                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
1328                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
1329                                         "${ARG2}, ... ${ARGn}.  When setting the function, the values are provided\n"
1330                                         "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
1331                                         "%s"
1332                                         "\nRead:\n%s\n\nWrite:\n%s%s%s",
1333                                         (*query)->sql_insert ?
1334                                                 "If the write query affects no rows, the insert query will be\n"
1335                                                 "performed.\n" : "",
1336                                         (*query)->sql_read,
1337                                         (*query)->sql_write,
1338                                         (*query)->sql_insert ? "\n\nInsert:\n" : "",
1339                                         (*query)->sql_insert ? (*query)->sql_insert : "");
1340         } else if ((*query)->sql_read) {
1341                 ast_string_field_build((*query)->acf, desc,
1342                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
1343                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
1344                                         "${ARG2}, ... ${ARGn}.  This function may only be read, not set.\n\nSQL:\n%s",
1345                                         (*query)->sql_read);
1346         } else if ((*query)->sql_write) {
1347                 ast_string_field_build((*query)->acf, desc,
1348                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
1349                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
1350                                         "${ARG2}, ... ${ARGn}.  The values are provided either in whole as\n"
1351                                         "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
1352                                         "This function may only be set.\n%s\nSQL:\n%s%s%s",
1353                                         (*query)->sql_insert ?
1354                                                 "If the write query affects no rows, the insert query will be\n"
1355                                                 "performed.\n" : "",
1356                                         (*query)->sql_write,
1357                                         (*query)->sql_insert ? "\n\nInsert:\n" : "",
1358                                         (*query)->sql_insert ? (*query)->sql_insert : "");
1359         } else {
1360                 free_acf_query(*query);
1361                 *query = NULL;
1362                 ast_log(LOG_WARNING, "Section '%s' was found, but there was no SQL to execute.  Ignoring.\n", catg);
1363                 return EINVAL;
1364         }
1365
1366         if (ast_strlen_zero((*query)->acf->desc)) {
1367                 free_acf_query(*query);
1368                 *query = NULL;
1369                 return ENOMEM;
1370         }
1371
1372         if ((*query)->sql_read) {
1373                 (*query)->acf->read = acf_odbc_read;
1374         }
1375
1376         if ((*query)->sql_write) {
1377                 (*query)->acf->write = acf_odbc_write;
1378         }
1379
1380         return 0;
1381 }
1382
1383 static char *cli_odbc_read(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1384 {
1385         AST_DECLARE_APP_ARGS(args,
1386                 AST_APP_ARG(field)[100];
1387         );
1388         struct ast_str *sql;
1389         char *char_args, varname[10];
1390         struct acf_odbc_query *query;
1391         struct ast_channel *chan;
1392         int i;
1393
1394         switch (cmd) {
1395         case CLI_INIT:
1396                 e->command = "odbc read";
1397                 e->usage =
1398                         "Usage: odbc read <name> <args> [exec]\n"
1399                         "       Evaluates the SQL provided in the ODBC function <name>, and\n"
1400                         "       optionally executes the function.  This function is intended for\n"
1401                         "       testing purposes.  Remember to quote arguments containing spaces.\n";
1402                 return NULL;
1403         case CLI_GENERATE:
1404                 if (a->pos == 2) {
1405                         int wordlen = strlen(a->word), which = 0;
1406                         /* Complete function name */
1407                         AST_RWLIST_RDLOCK(&queries);
1408                         AST_RWLIST_TRAVERSE(&queries, query, list) {
1409                                 if (!strncasecmp(query->acf->name, a->word, wordlen)) {
1410                                         if (++which > a->n) {
1411                                                 char *res = ast_strdup(query->acf->name);
1412                                                 AST_RWLIST_UNLOCK(&queries);
1413                                                 return res;
1414                                         }
1415                                 }
1416                         }
1417                         AST_RWLIST_UNLOCK(&queries);
1418                         return NULL;
1419                 } else if (a->pos == 4) {
1420                         static const char * const completions[] = { "exec", NULL };
1421                         return ast_cli_complete(a->word, completions, a->n);
1422                 } else {
1423                         return NULL;
1424                 }
1425         }
1426
1427         if (a->argc < 4 || a->argc > 5) {
1428                 return CLI_SHOWUSAGE;
1429         }
1430
1431         sql = ast_str_thread_get(&sql_buf, 16);
1432         if (!sql) {
1433                 return CLI_FAILURE;
1434         }
1435
1436         AST_RWLIST_RDLOCK(&queries);
1437         AST_RWLIST_TRAVERSE(&queries, query, list) {
1438                 if (!strcmp(query->acf->name, a->argv[2])) {
1439                         break;
1440                 }
1441         }
1442
1443         if (!query) {
1444                 ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
1445                 AST_RWLIST_UNLOCK(&queries);
1446                 return CLI_SHOWUSAGE;
1447         }
1448
1449         if (!query->sql_read) {
1450                 ast_cli(a->fd, "The function %s has no readsql parameter.\n", a->argv[2]);
1451                 AST_RWLIST_UNLOCK(&queries);
1452                 return CLI_SUCCESS;
1453         }
1454
1455         ast_str_make_space(&sql, strlen(query->sql_read) * 2 + 300);
1456
1457         /* Evaluate function */
1458         char_args = ast_strdupa(a->argv[3]);
1459
1460         chan = ast_dummy_channel_alloc();
1461         if (!chan) {
1462                 AST_RWLIST_UNLOCK(&queries);
1463                 return CLI_FAILURE;
1464         }
1465
1466         AST_STANDARD_APP_ARGS(args, char_args);
1467         for (i = 0; i < args.argc; i++) {
1468                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
1469                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
1470         }
1471
1472         ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
1473         chan = ast_channel_unref(chan);
1474
1475         if (a->argc == 5 && !strcmp(a->argv[4], "exec")) {
1476                 /* Execute the query */
1477                 struct odbc_obj *obj = NULL;
1478                 struct dsn *dsn = NULL;
1479                 int dsn_num, executed = 0;
1480                 SQLHSTMT stmt;
1481                 int rows = 0, res, x;
1482                 SQLSMALLINT colcount = 0, collength;
1483                 SQLLEN indicator;
1484                 struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
1485                 char colname[256];
1486                 SQLULEN maxcol;
1487
1488                 if (!coldata) {
1489                         AST_RWLIST_UNLOCK(&queries);
1490                         return CLI_SUCCESS;
1491                 }
1492
1493                 for (dsn_num = 0; dsn_num < 5; dsn_num++) {
1494                         if (ast_strlen_zero(query->readhandle[dsn_num])) {
1495                                 continue;
1496                         }
1497                         obj = get_odbc_obj(query->readhandle[dsn_num], &dsn);
1498                         if (!obj) {
1499                                 continue;
1500                         }
1501                         ast_debug(1, "Found handle %s\n", query->readhandle[dsn_num]);
1502
1503                         if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
1504                                 release_obj_or_dsn (&obj, &dsn);
1505                                 continue;
1506                         }
1507
1508                         executed = 1;
1509
1510                         res = SQLNumResultCols(stmt, &colcount);
1511                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1512                                 ast_cli(a->fd, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
1513                                 SQLCloseCursor(stmt);
1514                                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1515                                 release_obj_or_dsn (&obj, &dsn);
1516                                 AST_RWLIST_UNLOCK(&queries);
1517                                 return CLI_SUCCESS;
1518                         }
1519
1520                         res = SQLFetch(stmt);
1521                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1522                                 SQLCloseCursor(stmt);
1523                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1524                                 release_obj_or_dsn (&obj, &dsn);
1525                                 if (res == SQL_NO_DATA) {
1526                                         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));
1527                                         break;
1528                                 } else {
1529                                         ast_cli(a->fd, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
1530                                 }
1531                                 AST_RWLIST_UNLOCK(&queries);
1532                                 return CLI_SUCCESS;
1533                         }
1534                         for (;;) {
1535                                 for (x = 0; x < colcount; x++) {
1536                                         maxcol = 0;
1537
1538                                         res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
1539                                         if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
1540                                                 snprintf(colname, sizeof(colname), "field%d", x);
1541                                         }
1542
1543                                         res = ast_odbc_ast_str_SQLGetData(&coldata, maxcol, stmt, x + 1, SQL_CHAR, &indicator);
1544                                         if (indicator == SQL_NULL_DATA) {
1545                                                 ast_str_set(&coldata, 0, "(nil)");
1546                                                 res = SQL_SUCCESS;
1547                                         }
1548
1549                                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1550                                                 ast_cli(a->fd, "SQL Get Data error %d!\n[%s]\n\n", res, ast_str_buffer(sql));
1551                                                 SQLCloseCursor(stmt);
1552                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1553                                                 release_obj_or_dsn (&obj, &dsn);
1554                                                 AST_RWLIST_UNLOCK(&queries);
1555                                                 return CLI_SUCCESS;
1556                                         }
1557
1558                                         ast_cli(a->fd, "%-20.20s  %s\n", colname, ast_str_buffer(coldata));
1559                                 }
1560                                 rows++;
1561
1562                                 /* Get next row */
1563                                 res = SQLFetch(stmt);
1564                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1565                                         break;
1566                                 }
1567                                 ast_cli(a->fd, "%-20.20s  %s\n", "----------", "----------");
1568                         }
1569                         SQLCloseCursor(stmt);
1570                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1571                         release_obj_or_dsn (&obj, &dsn);
1572                         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]);
1573                         break;
1574                 }
1575                 release_obj_or_dsn (&obj, &dsn);
1576
1577                 if (!executed) {
1578                         ast_cli(a->fd, "Failed to execute query. [%s]\n", ast_str_buffer(sql));
1579                 }
1580         } else { /* No execution, just print out the resulting SQL */
1581                 ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
1582         }
1583         AST_RWLIST_UNLOCK(&queries);
1584         return CLI_SUCCESS;
1585 }
1586
1587 static char *cli_odbc_write(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1588 {
1589         AST_DECLARE_APP_ARGS(values,
1590                 AST_APP_ARG(field)[100];
1591         );
1592         AST_DECLARE_APP_ARGS(args,
1593                 AST_APP_ARG(field)[100];
1594         );
1595         struct ast_str *sql;
1596         char *char_args, *char_values, varname[10];
1597         struct acf_odbc_query *query;
1598         struct ast_channel *chan;
1599         int i;
1600
1601         switch (cmd) {
1602         case CLI_INIT:
1603                 e->command = "odbc write";
1604                 e->usage =
1605                         "Usage: odbc write <name> <args> <value> [exec]\n"
1606                         "       Evaluates the SQL provided in the ODBC function <name>, and\n"
1607                         "       optionally executes the function.  This function is intended for\n"
1608                         "       testing purposes.  Remember to quote arguments containing spaces.\n";
1609                 return NULL;
1610         case CLI_GENERATE:
1611                 if (a->pos == 2) {
1612                         int wordlen = strlen(a->word), which = 0;
1613                         /* Complete function name */
1614                         AST_RWLIST_RDLOCK(&queries);
1615                         AST_RWLIST_TRAVERSE(&queries, query, list) {
1616                                 if (!strncasecmp(query->acf->name, a->word, wordlen)) {
1617                                         if (++which > a->n) {
1618                                                 char *res = ast_strdup(query->acf->name);
1619                                                 AST_RWLIST_UNLOCK(&queries);
1620                                                 return res;
1621                                         }
1622                                 }
1623                         }
1624                         AST_RWLIST_UNLOCK(&queries);
1625                         return NULL;
1626                 } else if (a->pos == 5) {
1627                         static const char * const completions[] = { "exec", NULL };
1628                         return ast_cli_complete(a->word, completions, a->n);
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