Janitor, use ARRAY_LEN() when possible.
[asterisk/asterisk.git] / res / res_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * res_odbc.c <ODBC resource manager>
9  * Copyright (C) 2004 - 2005 Anthony Minessale II <anthmct@yahoo.com>
10  *
11  * See http://www.asterisk.org for more information about
12  * the Asterisk project. Please do not directly contact
13  * any of the maintainers of this project for assistance;
14  * the project provides a web site, mailing lists and IRC
15  * channels for your use.
16  *
17  * This program is free software, distributed under the terms of
18  * the GNU General Public License Version 2. See the LICENSE file
19  * at the top of the source tree.
20  */
21
22 /*! \file
23  *
24  * \brief ODBC resource manager
25  * 
26  * \author Mark Spencer <markster@digium.com>
27  * \author Anthony Minessale II <anthmct@yahoo.com>
28  *
29  * \arg See also: \ref cdr_odbc
30  */
31
32 /*** MODULEINFO
33         <depend>odbc</depend>
34         <depend>ltdl</depend>
35         <use>unixodbc</use>
36         <use>iodbc</use>
37  ***/
38
39 #include "asterisk.h"
40
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42
43 #include "asterisk/file.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/config.h"
46 #include "asterisk/pbx.h"
47 #include "asterisk/module.h"
48 #include "asterisk/cli.h"
49 #include "asterisk/lock.h"
50 #include "asterisk/res_odbc.h"
51 #include "asterisk/time.h"
52 #include "asterisk/astobj2.h"
53
54 struct odbc_class
55 {
56         AST_LIST_ENTRY(odbc_class) list;
57         char name[80];
58         char dsn[80];
59         char *username;
60         char *password;
61         char *sanitysql;
62         SQLHENV env;
63         unsigned int haspool:1;              /* Boolean - TDS databases need this */
64         unsigned int delme:1;                /* Purge the class */
65         unsigned int backslash_is_escape:1;  /* On this database, the backslash is a native escape sequence */
66         unsigned int limit;                  /* 1023 wasn't enough for some people */
67         unsigned int count;                  /* Running count of pooled connections */
68         unsigned int idlecheck;              /* Recheck the connection if it is idle for this long */
69         struct ao2_container *obj_container;
70 };
71
72 struct ao2_container *class_container;
73
74 static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
75
76 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
77 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
78 static int odbc_register_class(struct odbc_class *class, int connect);
79
80 static void odbc_class_destructor(void *data)
81 {
82         struct odbc_class *class = data;
83         /* Due to refcounts, we can safely assume that any objects with a reference
84          * to us will prevent our destruction, so we don't need to worry about them.
85          */
86         if (class->username)
87                 ast_free(class->username);
88         if (class->password)
89                 ast_free(class->password);
90         if (class->sanitysql)
91                 ast_free(class->sanitysql);
92         ao2_ref(class->obj_container, -1);
93         SQLFreeHandle(SQL_HANDLE_ENV, class->env);
94 }
95
96 static int null_hash_fn(const void *obj, const int flags)
97 {
98         return 0;
99 }
100
101 static void odbc_obj_destructor(void *data)
102 {
103         struct odbc_obj *obj = data;
104         odbc_obj_disconnect(obj);
105         ast_mutex_destroy(&obj->lock);
106         ao2_ref(obj->parent, -1);
107 }
108
109 static void destroy_table_cache(struct odbc_cache_tables *table) {
110         struct odbc_cache_columns *col;
111         ast_debug(1, "Destroying table cache for %s\n", table->table);
112         AST_RWLIST_WRLOCK(&table->columns);
113         while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
114                 ast_free(col);
115         }
116         AST_RWLIST_UNLOCK(&table->columns);
117         AST_RWLIST_HEAD_DESTROY(&table->columns);
118         ast_free(table);
119 }
120
121 /*!
122  * \brief Find or create an entry describing the table specified.
123  * \param obj An active ODBC handle on which to query the table
124  * \param table Tablename to describe
125  * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
126  * When a structure is returned, the contained columns list will be
127  * rdlock'ed, to ensure that it will be retained in memory.
128  */
129 struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
130 {
131         struct odbc_cache_tables *tableptr;
132         struct odbc_cache_columns *entry;
133         char columnname[80];
134         SQLLEN sqlptr;
135         SQLHSTMT stmt = NULL;
136         int res = 0, error = 0, try = 0;
137         struct odbc_obj *obj = ast_odbc_request_obj(database, 0);
138
139         AST_RWLIST_RDLOCK(&odbc_tables);
140         AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
141                 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
142                         break;
143                 }
144         }
145         if (tableptr) {
146                 AST_RWLIST_RDLOCK(&tableptr->columns);
147                 AST_RWLIST_UNLOCK(&odbc_tables);
148                 if (obj) {
149                         ast_odbc_release_obj(obj);
150                 }
151                 return tableptr;
152         }
153
154         if (!obj) {
155                 ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
156                 return NULL;
157         }
158
159         /* Table structure not already cached; build it now. */
160         do {
161 retry:
162                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
163                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
164                         if (try == 0) {
165                                 try = 1;
166                                 ast_odbc_sanity_check(obj);
167                                 goto retry;
168                         }
169                         ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
170                         break;
171                 }
172
173                 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
174                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
175                         if (try == 0) {
176                                 try = 1;
177                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
178                                 ast_odbc_sanity_check(obj);
179                                 goto retry;
180                         }
181                         ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
182                         break;
183                 }
184
185                 if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
186                         ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
187                         break;
188                 }
189
190                 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
191                 tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
192                 strcpy(tableptr->connection, database); /* SAFE */
193                 strcpy(tableptr->table, tablename); /* SAFE */
194                 AST_RWLIST_HEAD_INIT(&(tableptr->columns));
195
196                 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
197                         SQLGetData(stmt,  4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
198
199                         if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
200                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
201                                 error = 1;
202                                 break;
203                         }
204                         entry->name = (char *)entry + sizeof(*entry);
205                         strcpy(entry->name, columnname);
206
207                         SQLGetData(stmt,  5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
208                         SQLGetData(stmt,  7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
209                         SQLGetData(stmt,  9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
210                         SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
211                         SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
212                         SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
213
214                         /* Specification states that the octenlen should be the maximum number of bytes
215                          * returned in a char or binary column, but it seems that some drivers just set
216                          * it to NULL. (Bad Postgres! No biscuit!) */
217                         if (entry->octetlen == 0) {
218                                 entry->octetlen = entry->size;
219                         }
220
221                         ast_verb(10, "Found %s column with type %hd with len %ld, octetlen %ld, and numlen (%hd,%hd)\n", entry->name, entry->type, (long) entry->size, (long) entry->octetlen, entry->decimals, entry->radix);
222                         /* Insert column info into column list */
223                         AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
224                 }
225                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
226
227                 AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
228                 AST_RWLIST_RDLOCK(&(tableptr->columns));
229         } while (0);
230
231         AST_RWLIST_UNLOCK(&odbc_tables);
232
233         if (error) {
234                 destroy_table_cache(tableptr);
235                 tableptr = NULL;
236         }
237         if (obj) {
238                 ast_odbc_release_obj(obj);
239         }
240         return tableptr;
241 }
242
243 struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
244 {
245         struct odbc_cache_columns *col;
246         AST_RWLIST_TRAVERSE(&table->columns, col, list) {
247                 if (strcasecmp(col->name, colname) == 0) {
248                         return col;
249                 }
250         }
251         return NULL;
252 }
253
254 int ast_odbc_clear_cache(const char *database, const char *tablename)
255 {
256         struct odbc_cache_tables *tableptr;
257
258         AST_RWLIST_WRLOCK(&odbc_tables);
259         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
260                 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
261                         AST_LIST_REMOVE_CURRENT(list);
262                         destroy_table_cache(tableptr);
263                         break;
264                 }
265         }
266         AST_RWLIST_TRAVERSE_SAFE_END
267         AST_RWLIST_UNLOCK(&odbc_tables);
268         return tableptr ? 0 : -1;
269 }
270
271 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
272 {
273         int attempt;
274         SQLHSTMT stmt;
275
276         for (attempt = 0; attempt < 2; attempt++) {
277                 stmt = exec_cb(obj, data);
278
279                 if (stmt) {
280                         break;
281                 } else {
282                         obj->up = 0;
283                         ast_log(LOG_WARNING, "SQL Exec Direct failed.  Attempting a reconnect...\n");
284
285                         odbc_obj_disconnect(obj);
286                         odbc_obj_connect(obj);
287                 }
288         }
289
290         return stmt;
291 }
292
293 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
294 {
295         int res = 0, i, attempt;
296         SQLINTEGER nativeerror=0, numfields=0;
297         SQLSMALLINT diagbytes=0;
298         unsigned char state[10], diagnostic[256];
299         SQLHSTMT stmt;
300
301         for (attempt = 0; attempt < 2; attempt++) {
302                 /* This prepare callback may do more than just prepare -- it may also
303                  * bind parameters, bind results, etc.  The real key, here, is that
304                  * when we disconnect, all handles become invalid for most databases.
305                  * We must therefore redo everything when we establish a new
306                  * connection. */
307                 stmt = prepare_cb(obj, data);
308
309                 if (stmt) {
310                         res = SQLExecute(stmt);
311                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
312                                 if (res == SQL_ERROR) {
313                                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
314                                         for (i = 0; i < numfields; i++) {
315                                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
316                                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
317                                                 if (i > 10) {
318                                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
319                                                         break;
320                                                 }
321                                         }
322                                 }
323
324                                 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
325                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
326                                 stmt = NULL;
327
328                                 obj->up = 0;
329                                 /*
330                                  * While this isn't the best way to try to correct an error, this won't automatically
331                                  * fail when the statement handle invalidates.
332                                  */
333                                 ast_odbc_sanity_check(obj);
334                                 continue;
335                         } else
336                                 obj->last_used = ast_tvnow();
337                         break;
338                 } else if (attempt == 0)
339                         ast_odbc_sanity_check(obj);
340         }
341
342         return stmt;
343 }
344
345 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt) 
346 {
347         int res = 0, i;
348         SQLINTEGER nativeerror=0, numfields=0;
349         SQLSMALLINT diagbytes=0;
350         unsigned char state[10], diagnostic[256];
351
352         res = SQLExecute(stmt);
353         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
354                 if (res == SQL_ERROR) {
355                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
356                         for (i = 0; i < numfields; i++) {
357                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
358                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
359                                 if (i > 10) {
360                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
361                                         break;
362                                 }
363                         }
364                 }
365         } else
366                 obj->last_used = ast_tvnow();
367         
368         return res;
369 }
370
371
372 int ast_odbc_sanity_check(struct odbc_obj *obj) 
373 {
374         char *test_sql = "select 1";
375         SQLHSTMT stmt;
376         int res = 0;
377
378         if (!ast_strlen_zero(obj->parent->sanitysql))
379                 test_sql = obj->parent->sanitysql;
380
381         if (obj->up) {
382                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
383                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
384                         obj->up = 0;
385                 } else {
386                         res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
387                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
388                                 obj->up = 0;
389                         } else {
390                                 res = SQLExecute(stmt);
391                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
392                                         obj->up = 0;
393                                 }
394                         }
395                 }
396                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
397         }
398
399         if (!obj->up) { /* Try to reconnect! */
400                 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
401                 odbc_obj_disconnect(obj);
402                 odbc_obj_connect(obj);
403         }
404         return obj->up;
405 }
406
407 static int load_odbc_config(void)
408 {
409         static char *cfg = "res_odbc.conf";
410         struct ast_config *config;
411         struct ast_variable *v;
412         char *cat;
413         const char *dsn, *username, *password, *sanitysql;
414         int enabled, pooling, limit, bse;
415         unsigned int idlecheck;
416         int preconnect = 0, res = 0;
417         struct ast_flags config_flags = { 0 };
418
419         struct odbc_class *new;
420
421         config = ast_config_load(cfg, config_flags);
422         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
423                 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
424                 return -1;
425         }
426         for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
427                 if (!strcasecmp(cat, "ENV")) {
428                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
429                                 setenv(v->name, v->value, 1);
430                                 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
431                         }
432                 } else {
433                         /* Reset all to defaults for each class of odbc connections */
434                         dsn = username = password = sanitysql = NULL;
435                         enabled = 1;
436                         preconnect = idlecheck = 0;
437                         pooling = 0;
438                         limit = 0;
439                         bse = 1;
440                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
441                                 if (!strcasecmp(v->name, "pooling")) {
442                                         if (ast_true(v->value))
443                                                 pooling = 1;
444                                 } else if (!strncasecmp(v->name, "share", 5)) {
445                                         /* "shareconnections" is a little clearer in meaning than "pooling" */
446                                         if (ast_false(v->value))
447                                                 pooling = 1;
448                                 } else if (!strcasecmp(v->name, "limit")) {
449                                         sscanf(v->value, "%d", &limit);
450                                         if (ast_true(v->value) && !limit) {
451                                                 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Setting limit to 1023 for ODBC class '%s'.\n", v->value, cat);
452                                                 limit = 1023;
453                                         } else if (ast_false(v->value)) {
454                                                 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
455                                                 enabled = 0;
456                                                 break;
457                                         }
458                                 } else if (!strcasecmp(v->name, "idlecheck")) {
459                                         sscanf(v->value, "%d", &idlecheck);
460                                 } else if (!strcasecmp(v->name, "enabled")) {
461                                         enabled = ast_true(v->value);
462                                 } else if (!strcasecmp(v->name, "pre-connect")) {
463                                         preconnect = ast_true(v->value);
464                                 } else if (!strcasecmp(v->name, "dsn")) {
465                                         dsn = v->value;
466                                 } else if (!strcasecmp(v->name, "username")) {
467                                         username = v->value;
468                                 } else if (!strcasecmp(v->name, "password")) {
469                                         password = v->value;
470                                 } else if (!strcasecmp(v->name, "sanitysql")) {
471                                         sanitysql = v->value;
472                                 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
473                                         bse = ast_true(v->value);
474                                 }
475                         }
476
477                         if (enabled && !ast_strlen_zero(dsn)) {
478                                 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
479
480                                 if (!new) {
481                                         res = -1;
482                                         break;
483                                 }
484
485                                 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
486                                 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
487
488                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
489                                         ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
490                                         ao2_ref(new, -1);
491                                         return res;
492                                 }
493
494                                 new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
495
496                                 if (pooling) {
497                                         new->haspool = pooling;
498                                         if (limit) {
499                                                 new->limit = limit;
500                                         } else {
501                                                 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
502                                                 new->limit = 5;
503                                         }
504                                 }
505
506                                 new->backslash_is_escape = bse ? 1 : 0;
507                                 new->idlecheck = idlecheck;
508
509                                 if (cat)
510                                         ast_copy_string(new->name, cat, sizeof(new->name));
511                                 if (dsn)
512                                         ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
513                                 if (username && !(new->username = ast_strdup(username))) {
514                                         ao2_ref(new, -1);
515                                         break;
516                                 }
517                                 if (password && !(new->password = ast_strdup(password))) {
518                                         ao2_ref(new, -1);
519                                         break;
520                                 }
521                                 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
522                                         ao2_ref(new, -1);
523                                         break;
524                                 }
525
526                                 odbc_register_class(new, preconnect);
527                                 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
528                                 ao2_ref(new, -1);
529                                 new = NULL;
530                         }
531                 }
532         }
533         ast_config_destroy(config);
534         return res;
535 }
536
537 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
538 {
539         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
540         struct odbc_class *class;
541         struct odbc_obj *current;
542         int length = 0;
543         int which = 0;
544         char *ret = NULL;
545
546         switch (cmd) {
547         case CLI_INIT:
548                 e->command = "odbc show";
549                 e->usage =
550                                 "Usage: odbc show [class]\n"
551                                 "       List settings of a particular ODBC class or,\n"
552                                 "       if not specified, all classes.\n";
553                 return NULL;
554         case CLI_GENERATE:
555                 if (a->pos != 2)
556                         return NULL;
557                 length = strlen(a->word);
558                 while ((class = ao2_iterator_next(&aoi))) {
559                         if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
560                                 ret = ast_strdup(class->name);
561                                 ao2_ref(class, -1);
562                                 break;
563                         }
564                         ao2_ref(class, -1);
565                 }
566                 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
567                         ret = ast_strdup("all");
568                 }
569                 return ret;
570         }
571
572         ast_cli(a->fd, "\nODBC DSN Settings\n");
573         ast_cli(a->fd,   "-----------------\n\n");
574         aoi = ao2_iterator_init(class_container, 0);
575         while ((class = ao2_iterator_next(&aoi))) {
576                 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
577                         int count = 0;
578                         ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
579
580                         if (class->haspool) {
581                                 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
582
583                                 ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);
584
585                                 while ((current = ao2_iterator_next(&aoi2))) {
586                                         ast_mutex_lock(&current->lock);
587 #ifdef DEBUG_THREADS
588                                         ast_cli(a->fd, "    - Connection %d: %s (%s:%d %s)\n", ++count,
589                                                 current->used ? "in use" :
590                                                 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
591                                                 current->file, current->lineno, current->function);
592 #else
593                                         ast_cli(a->fd, "    - Connection %d: %s\n", ++count,
594                                                 current->used ? "in use" :
595                                                 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
596 #endif
597                                         ast_mutex_unlock(&current->lock);
598                                         ao2_ref(current, -1);
599                                 }
600                         } else {
601                                 /* Should only ever be one of these */
602                                 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
603                                 while ((current = ao2_iterator_next(&aoi2))) {
604                                         ast_cli(a->fd, "  Pooled: No\n  Connected: %s\n", current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
605                                         ao2_ref(current, -1);
606                                 }
607                         }
608                         ast_cli(a->fd, "\n");
609                 }
610                 ao2_ref(class, -1);
611         }
612
613         return CLI_SUCCESS;
614 }
615
616 static struct ast_cli_entry cli_odbc[] = {
617         AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
618 };
619
620 static int odbc_register_class(struct odbc_class *class, int preconnect)
621 {
622         struct odbc_obj *obj;
623         if (class) {
624                 ao2_link(class_container, class);
625                 /* I still have a reference in the caller, so a deref is NOT missing here. */
626
627                 if (preconnect) {
628                         /* Request and release builds a connection */
629                         obj = ast_odbc_request_obj(class->name, 0);
630                         if (obj)
631                                 ast_odbc_release_obj(obj);
632                 }
633
634                 return 0;
635         } else {
636                 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
637                 return -1;
638         }
639 }
640
641 void ast_odbc_release_obj(struct odbc_obj *obj)
642 {
643         /* For pooled connections, this frees the connection to be
644          * reused.  For non-pooled connections, it does nothing. */
645         obj->used = 0;
646 #ifdef DEBUG_THREADS
647         obj->file[0] = '\0';
648         obj->function[0] = '\0';
649         obj->lineno = 0;
650 #endif
651         ao2_ref(obj, -1);
652 }
653
654 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
655 {
656         return obj->parent->backslash_is_escape;
657 }
658
659 #ifdef DEBUG_THREADS
660 struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
661 #else
662 struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
663 #endif
664 {
665         struct odbc_obj *obj = NULL;
666         struct odbc_class *class;
667         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
668
669         while ((class = ao2_iterator_next(&aoi))) {
670                 if (!strcmp(class->name, name) && !class->delme) {
671                         break;
672                 }
673                 ao2_ref(class, -1);
674         }
675
676         if (!class)
677                 return NULL;
678
679         if (class->haspool) {
680                 /* Recycle connections before building another */
681                 aoi = ao2_iterator_init(class->obj_container, 0);
682                 while ((obj = ao2_iterator_next(&aoi))) {
683                         if (! obj->used) {
684                                 ast_mutex_lock(&obj->lock);
685                                 obj->used = 1;
686                                 ast_mutex_unlock(&obj->lock);
687                                 break;
688                         }
689                         ao2_ref(obj, -1);
690                 }
691
692                 if (!obj && (class->count < class->limit)) {
693                         class->count++;
694                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
695                         if (!obj) {
696                                 ao2_ref(class, -1);
697                                 return NULL;
698                         }
699                         ast_mutex_init(&obj->lock);
700                         /* obj inherits the outstanding reference to class */
701                         obj->parent = class;
702                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
703                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
704                                 ao2_ref(obj, -1);
705                                 obj = NULL;
706                                 class->count--;
707                         } else {
708                                 obj->used = 1;
709                                 ao2_link(class->obj_container, obj);
710                         }
711                 }
712         } else {
713                 /* Non-pooled connection: multiple modules can use the same connection. */
714                 aoi = ao2_iterator_init(class->obj_container, 0);
715                 while ((obj = ao2_iterator_next(&aoi))) {
716                         /* Non-pooled connection: if there is an entry, return it */
717                         break;
718                 }
719
720                 if (!obj) {
721                         /* No entry: build one */
722                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
723                         if (!obj) {
724                                 ao2_ref(class, -1);
725                                 return NULL;
726                         }
727                         ast_mutex_init(&obj->lock);
728                         /* obj inherits the outstanding reference to class */
729                         obj->parent = class;
730                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
731                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
732                                 ao2_ref(obj, -1);
733                                 obj = NULL;
734                         } else {
735                                 ao2_link(class->obj_container, obj);
736                         }
737                 }
738         }
739
740         if (obj && check) {
741                 ast_odbc_sanity_check(obj);
742         } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck)
743                 odbc_obj_connect(obj);
744
745 #ifdef DEBUG_THREADS
746         if (obj) {
747                 ast_copy_string(obj->file, file, sizeof(obj->file));
748                 ast_copy_string(obj->function, function, sizeof(obj->function));
749                 obj->lineno = lineno;
750         }
751 #endif
752
753         return obj;
754 }
755
756 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
757 {
758         int res;
759         SQLINTEGER err;
760         short int mlen;
761         unsigned char msg[200], state[10];
762
763         /* Nothing to disconnect */
764         if (!obj->con) {
765                 return ODBC_SUCCESS;
766         }
767
768         ast_mutex_lock(&obj->lock);
769
770         res = SQLDisconnect(obj->con);
771
772         if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
773                 ast_log(LOG_DEBUG, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
774         } else {
775                 ast_log(LOG_DEBUG, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
776         }
777
778         if ((res = SQLFreeHandle(SQL_HANDLE_DBC, obj->con) == SQL_SUCCESS)) {
779                 obj->con = NULL;
780                 ast_log(LOG_DEBUG, "Database handle deallocated\n");
781         } else {
782                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
783                 ast_log(LOG_WARNING, "Unable to deallocate database handle? %d errno=%d %s\n", res, (int)err, msg);
784         }
785
786         obj->up = 0;
787         ast_mutex_unlock(&obj->lock);
788         return ODBC_SUCCESS;
789 }
790
791 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
792 {
793         int res;
794         SQLINTEGER err;
795         short int mlen;
796         unsigned char msg[200], state[10];
797 #ifdef NEEDTRACE
798         SQLINTEGER enable = 1;
799         char *tracefile = "/tmp/odbc.trace";
800 #endif
801         ast_mutex_lock(&obj->lock);
802
803         if (obj->up) {
804                 odbc_obj_disconnect(obj);
805                 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
806         } else {
807                 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
808         }
809
810         res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
811
812         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
813                 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
814                 ast_mutex_unlock(&obj->lock);
815                 return ODBC_FAIL;
816         }
817         SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
818         SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *) 10, 0);
819 #ifdef NEEDTRACE
820         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
821         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
822 #endif
823
824         res = SQLConnect(obj->con,
825                    (SQLCHAR *) obj->parent->dsn, SQL_NTS,
826                    (SQLCHAR *) obj->parent->username, SQL_NTS,
827                    (SQLCHAR *) obj->parent->password, SQL_NTS);
828
829         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
830                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
831                 ast_mutex_unlock(&obj->lock);
832                 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
833                 return ODBC_FAIL;
834         } else {
835                 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
836                 obj->up = 1;
837                 obj->last_used = ast_tvnow();
838         }
839
840         ast_mutex_unlock(&obj->lock);
841         return ODBC_SUCCESS;
842 }
843
844 static int reload(void)
845 {
846         struct odbc_cache_tables *table;
847         struct odbc_class *class;
848         struct odbc_obj *current;
849         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
850
851         /* First, mark all to be purged */
852         while ((class = ao2_iterator_next(&aoi))) {
853                 class->delme = 1;
854                 ao2_ref(class, -1);
855         }
856
857         load_odbc_config();
858
859         /* Purge remaining classes */
860
861         /* Note on how this works; this is a case of circular references, so we
862          * explicitly do NOT want to use a callback here (or we wind up in
863          * recursive hell).
864          *
865          * 1. Iterate through all the classes.  Note that the classes will currently
866          * contain two classes of the same name, one of which is marked delme and
867          * will be purged when all remaining objects of the class are released, and
868          * the other, which was created above when we re-parsed the config file.
869          * 2. On each class, there is a reference held by the master container and
870          * a reference held by each connection object.  There are two cases for
871          * destruction of the class, noted below.  However, in all cases, all O-refs
872          * (references to objects) will first be freed, which will cause the C-refs
873          * (references to classes) to be decremented (but never to 0, because the
874          * class container still has a reference).
875          *    a) If the class has outstanding objects, the C-ref by the class
876          *    container will then be freed, which leaves only C-refs by any
877          *    outstanding objects.  When the final outstanding object is released
878          *    (O-refs held by applications and dialplan functions), it will in turn
879          *    free the final C-ref, causing class destruction.
880          *    b) If the class has no outstanding objects, when the class container
881          *    removes the final C-ref, the class will be destroyed.
882          */
883         aoi = ao2_iterator_init(class_container, 0);
884         while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
885                 if (class->delme) {
886                         struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
887                         while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
888                                 ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
889                                 ao2_ref(current, -1); /* O-ref-- (by iterator) */
890                                 /* At this point, either
891                                  * a) there's an outstanding O-ref, or
892                                  * b) the object has already been destroyed.
893                                  */
894                         }
895                         ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
896                         /* At this point, either
897                          * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
898                          * b) the last remaining C-ref is held by the iterator, which will be
899                          * destroyed in the next step.
900                          */
901                 }
902                 ao2_ref(class, -1); /* C-ref-- (by iterator) */
903         }
904
905         /* Empty the cache; it will get rebuilt the next time the tables are needed. */
906         AST_RWLIST_WRLOCK(&odbc_tables);
907         while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
908                 destroy_table_cache(table);
909         }
910         AST_RWLIST_UNLOCK(&odbc_tables);
911
912         return 0;
913 }
914
915 static int unload_module(void)
916 {
917         /* Prohibit unloading */
918         return -1;
919 }
920
921 static int load_module(void)
922 {
923         if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
924                 return AST_MODULE_LOAD_DECLINE;
925         if (load_odbc_config() == -1)
926                 return AST_MODULE_LOAD_DECLINE;
927         ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
928         ast_log(LOG_NOTICE, "res_odbc loaded.\n");
929         return 0;
930 }
931
932 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
933                 .load = load_module,
934                 .unload = unload_module,
935                 .reload = reload,
936                );