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