00a07ef10df8849b912f3cd63a1bf47673fbb971
[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>unixodbc</depend>
34         <depend>ltdl</depend>
35  ***/
36
37 #include "asterisk.h"
38
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40
41 #include "asterisk/file.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/config.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/module.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/lock.h"
48 #include "asterisk/res_odbc.h"
49
50 struct odbc_class
51 {
52         AST_LIST_ENTRY(odbc_class) list;
53         char name[80];
54         char dsn[80];
55         char username[80];
56         char password[80];
57         char sanitysql[256];
58         SQLHENV env;
59         unsigned int haspool:1;         /* Boolean - TDS databases need this */
60         unsigned int limit:10;          /* Gives a limit of 1023 maximum */
61         unsigned int count:10;          /* Running count of pooled connections */
62         unsigned int delme:1;                   /* Purge the class */
63         AST_LIST_HEAD(, odbc_obj) odbc_obj;
64 };
65
66 AST_LIST_HEAD_STATIC(odbc_list, odbc_class);
67
68 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
69 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
70 static int odbc_register_class(struct odbc_class *class, int connect);
71
72
73 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
74 {
75         int attempt;
76         SQLHSTMT stmt;
77
78         for (attempt = 0; attempt < 2; attempt++) {
79                 stmt = exec_cb(obj, data);
80
81                 if (stmt) {
82                         break;
83                 } else {
84                         obj->up = 0;
85                         ast_log(LOG_WARNING, "SQL Exec Direct failed.  Attempting a reconnect...\n");
86
87                         odbc_obj_disconnect(obj);
88                         odbc_obj_connect(obj);
89                 }
90         }
91
92         return stmt;
93 }
94
95 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
96 {
97         int res = 0, i, attempt;
98         SQLINTEGER nativeerror=0, numfields=0;
99         SQLSMALLINT diagbytes=0;
100         unsigned char state[10], diagnostic[256];
101         SQLHSTMT stmt;
102
103         for (attempt = 0; attempt < 2; attempt++) {
104                 /* This prepare callback may do more than just prepare -- it may also
105                  * bind parameters, bind results, etc.  The real key, here, is that
106                  * when we disconnect, all handles become invalid for most databases.
107                  * We must therefore redo everything when we establish a new
108                  * connection. */
109                 stmt = prepare_cb(obj, data);
110
111                 if (stmt) {
112                         res = SQLExecute(stmt);
113                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
114                                 if (res == SQL_ERROR) {
115                                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
116                                         for (i = 0; i < numfields; i++) {
117                                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
118                                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
119                                                 if (i > 10) {
120                                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
121                                                         break;
122                                                 }
123                                         }
124                                 }
125
126                                 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
127                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
128                                 stmt = NULL;
129
130                                 obj->up = 0;
131                                 /*
132                                  * While this isn't the best way to try to correct an error, this won't automatically
133                                  * fail when the statement handle invalidates.
134                                  */
135                                 ast_odbc_sanity_check(obj);
136                                 continue;
137                         }
138                         break;
139                 } else if (attempt == 0)
140                         ast_odbc_sanity_check(obj);
141         }
142
143         return stmt;
144 }
145
146 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt) 
147 {
148         int res = 0, i;
149         SQLINTEGER nativeerror=0, numfields=0;
150         SQLSMALLINT diagbytes=0;
151         unsigned char state[10], diagnostic[256];
152
153         res = SQLExecute(stmt);
154         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
155                 if (res == SQL_ERROR) {
156                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
157                         for (i = 0; i < numfields; i++) {
158                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
159                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
160                                 if (i > 10) {
161                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
162                                         break;
163                                 }
164                         }
165                 }
166 #if 0
167                 /* This is a really bad method of trying to correct a dead connection.  It
168                  * only ever really worked with MySQL.  It will not work with any other
169                  * database, since most databases prepare their statements on the server,
170                  * and if you disconnect, you invalidate the statement handle.  Hence, if
171                  * you disconnect, you're going to fail anyway, whether you try to execute
172                  * a second time or not.
173                  */
174                 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
175                 ast_mutex_lock(&obj->lock);
176                 obj->up = 0;
177                 ast_mutex_unlock(&obj->lock);
178                 odbc_obj_disconnect(obj);
179                 odbc_obj_connect(obj);
180                 res = SQLExecute(stmt);
181 #endif
182         }
183         
184         return res;
185 }
186
187
188 int ast_odbc_sanity_check(struct odbc_obj *obj) 
189 {
190         char *test_sql = "select 1";
191         SQLHSTMT stmt;
192         int res = 0;
193
194         if (!ast_strlen_zero(obj->parent->sanitysql))
195                 test_sql = obj->parent->sanitysql;
196
197         if (obj->up) {
198                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
199                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
200                         obj->up = 0;
201                 } else {
202                         res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
203                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
204                                 obj->up = 0;
205                         } else {
206                                 res = SQLExecute(stmt);
207                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
208                                         obj->up = 0;
209                                 }
210                         }
211                 }
212                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
213         }
214
215         if (!obj->up) { /* Try to reconnect! */
216                 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
217                 odbc_obj_disconnect(obj);
218                 odbc_obj_connect(obj);
219         }
220         return obj->up;
221 }
222
223 static int load_odbc_config(void)
224 {
225         static char *cfg = "res_odbc.conf";
226         struct ast_config *config;
227         struct ast_variable *v;
228         char *cat;
229         const char *dsn, *username, *password, *sanitysql;
230         int enabled, pooling, limit;
231         int connect = 0, res = 0;
232         struct ast_flags config_flags = { 0 };
233
234         struct odbc_class *new;
235
236         config = ast_config_load(cfg, config_flags);
237         if (!config) {
238                 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
239                 return -1;
240         }
241         for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
242                 if (!strcasecmp(cat, "ENV")) {
243                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
244                                 setenv(v->name, v->value, 1);
245                                 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
246                         }
247                 } else {
248                         /* Reset all to defaults for each class of odbc connections */
249                         dsn = username = password = sanitysql = NULL;
250                         enabled = 1;
251                         connect = 0;
252                         pooling = 0;
253                         limit = 0;
254                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
255                                 if (!strcasecmp(v->name, "pooling")) {
256                                         if (ast_true(v->value))
257                                                 pooling = 1;
258                                 } else if (!strcasecmp(v->name, "limit")) {
259                                         sscanf(v->value, "%d", &limit);
260                                         if (ast_true(v->value) && !limit) {
261                                                 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);
262                                                 limit = 1023;
263                                         } else if (ast_false(v->value)) {
264                                                 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
265                                                 enabled = 0;
266                                                 break;
267                                         }
268                                 } else if (!strcasecmp(v->name, "enabled")) {
269                                         enabled = ast_true(v->value);
270                                 } else if (!strcasecmp(v->name, "pre-connect")) {
271                                         connect = ast_true(v->value);
272                                 } else if (!strcasecmp(v->name, "dsn")) {
273                                         dsn = v->value;
274                                 } else if (!strcasecmp(v->name, "username")) {
275                                         username = v->value;
276                                 } else if (!strcasecmp(v->name, "password")) {
277                                         password = v->value;
278                                 } else if (!strcasecmp(v->name, "sanitysql")) {
279                                         sanitysql = v->value;
280                                 }
281                         }
282
283                         if (enabled && !ast_strlen_zero(dsn)) {
284                                 new = ast_calloc(1, sizeof(*new));
285
286                                 if (!new) {
287                                         res = -1;
288                                         break;
289                                 }
290
291                                 if (cat)
292                                         ast_copy_string(new->name, cat, sizeof(new->name));
293                                 if (dsn)
294                                         ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
295                                 if (username)
296                                         ast_copy_string(new->username, username, sizeof(new->username));
297                                 if (password)
298                                         ast_copy_string(new->password, password, sizeof(new->password));
299                                 if (sanitysql)
300                                         ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
301
302                                 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
303                                 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
304
305                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
306                                         ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
307                                         SQLFreeHandle(SQL_HANDLE_ENV, new->env);
308                                         return res;
309                                 }
310
311                                 if (pooling) {
312                                         new->haspool = pooling;
313                                         if (limit) {
314                                                 new->limit = limit;
315                                         } else {
316                                                 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
317                                                 new->limit = 5;
318                                         }
319                                 }
320
321                                 odbc_register_class(new, connect);
322                                 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
323                         }
324                 }
325         }
326         ast_config_destroy(config);
327         return res;
328 }
329
330 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
331 {
332         struct odbc_class *class;
333         struct odbc_obj *current;
334         int length = 0;
335         int which = 0;
336         char *ret = NULL;
337
338         switch (cmd) {
339         case CLI_INIT:
340                 e->command = "odbc show";
341                 e->usage =
342                                 "Usage: odbc show [class]\n"
343                                 "       List settings of a particular ODBC class or,\n"
344                                 "       if not specified, all classes.\n";
345                 return NULL;
346         case CLI_GENERATE:
347                 if (a->pos != 2)
348                         return NULL;
349                 length = strlen(a->word);
350                 AST_LIST_LOCK(&odbc_list);
351                 AST_LIST_TRAVERSE(&odbc_list, class, list) {
352                         if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
353                                 ret = ast_strdup(class->name);
354                                 break;
355                         }
356                 }
357                 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
358                         ret = ast_strdup("all");
359                 }
360                 AST_LIST_UNLOCK(&odbc_list);
361                 return ret;
362         }
363
364         ast_cli(a->fd, "\nODBC DSN Settings\n");
365         ast_cli(a->fd, "-----------------\n\n");
366         AST_LIST_LOCK(&odbc_list);
367         AST_LIST_TRAVERSE(&odbc_list, class, list) {
368                 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
369                         int count = 0;
370                         ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
371
372                         if (class->haspool) {
373                                 ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);
374
375                                 AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
376                                         ast_cli(a->fd, "    - Connection %d: %s\n", ++count, current->used ? "in use" : current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
377                                 }
378                         } else {
379                                 /* Should only ever be one of these */
380                                 AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
381                                         ast_cli(a->fd, "  Pooled: No\n  Connected: %s\n", current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
382                                 }
383                         }
384                         ast_cli(a->fd, "\n");
385                 }
386         }
387         AST_LIST_UNLOCK(&odbc_list);
388
389         return CLI_SUCCESS;
390 }
391
392 static struct ast_cli_entry cli_odbc[] = {
393         AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
394 };
395
396 static int odbc_register_class(struct odbc_class *class, int connect)
397 {
398         struct odbc_obj *obj;
399         if (class) {
400                 AST_LIST_LOCK(&odbc_list);
401                 AST_LIST_INSERT_HEAD(&odbc_list, class, list);
402                 AST_LIST_UNLOCK(&odbc_list);
403
404                 if (connect) {
405                         /* Request and release builds a connection */
406                         obj = ast_odbc_request_obj(class->name, 0);
407                         if (obj)
408                                 ast_odbc_release_obj(obj);
409                 }
410
411                 return 0;
412         } else {
413                 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
414                 return -1;
415         }
416 }
417
418 void ast_odbc_release_obj(struct odbc_obj *obj)
419 {
420         /* For pooled connections, this frees the connection to be
421          * reused.  For non-pooled connections, it does nothing. */
422         obj->used = 0;
423 }
424
425 struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
426 {
427         struct odbc_obj *obj = NULL;
428         struct odbc_class *class;
429
430         AST_LIST_LOCK(&odbc_list);
431         AST_LIST_TRAVERSE(&odbc_list, class, list) {
432                 if (!strcmp(class->name, name))
433                         break;
434         }
435         AST_LIST_UNLOCK(&odbc_list);
436
437         if (!class)
438                 return NULL;
439
440         AST_LIST_LOCK(&class->odbc_obj);
441         if (class->haspool) {
442                 /* Recycle connections before building another */
443                 AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
444                         if (! obj->used) {
445                                 obj->used = 1;
446                                 break;
447                         }
448                 }
449
450                 if (!obj && (class->count < class->limit)) {
451                         class->count++;
452                         obj = ast_calloc(1, sizeof(*obj));
453                         if (!obj) {
454                                 AST_LIST_UNLOCK(&class->odbc_obj);
455                                 return NULL;
456                         }
457                         ast_mutex_init(&obj->lock);
458                         obj->parent = class;
459                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
460                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
461                                 ast_mutex_destroy(&obj->lock);
462                                 free(obj);
463                                 obj = NULL;
464                                 class->count--;
465                         } else {
466                                 obj->used = 1;
467                                 AST_LIST_INSERT_TAIL(&class->odbc_obj, obj, list);
468                         }
469                 }
470         } else {
471                 /* Non-pooled connection: multiple modules can use the same connection. */
472                 AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
473                         /* Non-pooled connection: if there is an entry, return it */
474                         break;
475                 }
476
477                 if (!obj) {
478                         /* No entry: build one */
479                         obj = ast_calloc(1, sizeof(*obj));
480                         if (!obj) {
481                                 AST_LIST_UNLOCK(&class->odbc_obj);
482                                 return NULL;
483                         }
484                         ast_mutex_init(&obj->lock);
485                         obj->parent = class;
486                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
487                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
488                                 ast_mutex_destroy(&obj->lock);
489                                 ast_free(obj);
490                                 obj = NULL;
491                         } else {
492                                 AST_LIST_INSERT_HEAD(&class->odbc_obj, obj, list);
493                         }
494                 }
495         }
496         AST_LIST_UNLOCK(&class->odbc_obj);
497
498         if (obj && check) {
499                 ast_odbc_sanity_check(obj);
500         }
501         return obj;
502 }
503
504 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
505 {
506         int res;
507         ast_mutex_lock(&obj->lock);
508
509         res = SQLDisconnect(obj->con);
510
511         if (res == ODBC_SUCCESS) {
512                 ast_log(LOG_WARNING, "res_odbc: disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
513         } else {
514                 ast_log(LOG_WARNING, "res_odbc: %s [%s] already disconnected\n",
515                 obj->parent->name, obj->parent->dsn);
516         }
517         obj->up = 0;
518         ast_mutex_unlock(&obj->lock);
519         return ODBC_SUCCESS;
520 }
521
522 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
523 {
524         int res;
525         SQLINTEGER err;
526         short int mlen;
527         unsigned char msg[200], stat[10];
528 #ifdef NEEDTRACE
529         SQLINTEGER enable = 1;
530         char *tracefile = "/tmp/odbc.trace";
531 #endif
532         ast_mutex_lock(&obj->lock);
533
534         res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
535
536         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
537                 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
538                 ast_mutex_unlock(&obj->lock);
539                 return ODBC_FAIL;
540         }
541         SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
542 #ifdef NEEDTRACE
543         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
544         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
545 #endif
546
547         if (obj->up) {
548                 odbc_obj_disconnect(obj);
549                 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
550         } else {
551                 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
552         }
553
554         res = SQLConnect(obj->con,
555                    (SQLCHAR *) obj->parent->dsn, SQL_NTS,
556                    (SQLCHAR *) obj->parent->username, SQL_NTS,
557                    (SQLCHAR *) obj->parent->password, SQL_NTS);
558
559         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
560                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
561                 ast_mutex_unlock(&obj->lock);
562                 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
563                 return ODBC_FAIL;
564         } else {
565                 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
566                 obj->up = 1;
567         }
568
569         ast_mutex_unlock(&obj->lock);
570         return ODBC_SUCCESS;
571 }
572
573 static int reload(void)
574 {
575         static char *cfg = "res_odbc.conf";
576         struct ast_config *config;
577         struct ast_variable *v;
578         char *cat;
579         const char *dsn, *username, *password, *sanitysql;
580         int enabled, pooling, limit;
581         int connect = 0, res = 0;
582         struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
583
584         struct odbc_class *new, *class;
585         struct odbc_obj *current;
586
587         /* First, mark all to be purged */
588         AST_LIST_LOCK(&odbc_list);
589         AST_LIST_TRAVERSE(&odbc_list, class, list) {
590                 class->delme = 1;
591         }
592
593         config = ast_config_load(cfg, config_flags);
594         if (config != NULL && config != CONFIG_STATUS_FILEUNCHANGED) {
595                 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
596                         if (!strcasecmp(cat, "ENV")) {
597                                 for (v = ast_variable_browse(config, cat); v; v = v->next) {
598                                         setenv(v->name, v->value, 1);
599                                         ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
600                                 }
601                         } else {
602                                 /* Reset all to defaults for each class of odbc connections */
603                                 dsn = username = password = sanitysql = NULL;
604                                 enabled = 1;
605                                 connect = 0;
606                                 pooling = 0;
607                                 limit = 0;
608                                 for (v = ast_variable_browse(config, cat); v; v = v->next) {
609                                         if (!strcasecmp(v->name, "pooling")) {
610                                                 pooling = 1;
611                                         } else if (!strcasecmp(v->name, "limit")) {
612                                                 sscanf(v->value, "%d", &limit);
613                                                 if (ast_true(v->value) && !limit) {
614                                                         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);
615                                                         limit = 1023;
616                                                 } else if (ast_false(v->value)) {
617                                                         ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
618                                                         enabled = 0;
619                                                         break;
620                                                 }
621                                         } else if (!strcasecmp(v->name, "enabled")) {
622                                                 enabled = ast_true(v->value);
623                                         } else if (!strcasecmp(v->name, "pre-connect")) {
624                                                 connect = ast_true(v->value);
625                                         } else if (!strcasecmp(v->name, "dsn")) {
626                                                 dsn = v->value;
627                                         } else if (!strcasecmp(v->name, "username")) {
628                                                 username = v->value;
629                                         } else if (!strcasecmp(v->name, "password")) {
630                                                 password = v->value;
631                                         } else if (!strcasecmp(v->name, "sanitysql")) {
632                                                 sanitysql = v->value;
633                                         }
634                                 }
635
636                                 if (enabled && !ast_strlen_zero(dsn)) {
637                                         /* First, check the list to see if it already exists */
638                                         AST_LIST_TRAVERSE(&odbc_list, class, list) {
639                                                 if (!strcmp(class->name, cat)) {
640                                                         class->delme = 0;
641                                                         break;
642                                                 }
643                                         }
644
645                                         if (class) {
646                                                 new = class;
647                                         } else {
648                                                 new = ast_calloc(1, sizeof(*new));
649                                         }
650
651                                         if (!new) {
652                                                 res = -1;
653                                                 break;
654                                         }
655
656                                         if (cat)
657                                                 ast_copy_string(new->name, cat, sizeof(new->name));
658                                         if (dsn)
659                                                 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
660                                         if (username)
661                                                 ast_copy_string(new->username, username, sizeof(new->username));
662                                         if (password)
663                                                 ast_copy_string(new->password, password, sizeof(new->password));
664                                         if (sanitysql)
665                                                 ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
666
667                                         if (!class) {
668                                                 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
669                                                 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
670
671                                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
672                                                         ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
673                                                         SQLFreeHandle(SQL_HANDLE_ENV, new->env);
674                                                         AST_LIST_UNLOCK(&odbc_list);
675                                                         return res;
676                                                 }
677                                         }
678
679                                         if (pooling) {
680                                                 new->haspool = pooling;
681                                                 if (limit) {
682                                                         new->limit = limit;
683                                                 } else {
684                                                         ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
685                                                         new->limit = 5;
686                                                 }
687                                         }
688
689                                         if (class) {
690                                                 ast_log(LOG_NOTICE, "Refreshing ODBC class '%s' dsn->[%s]\n", cat, dsn);
691                                         } else {
692                                                 odbc_register_class(new, connect);
693                                                 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
694                                         }
695                                 }
696                         }
697                 }
698                 ast_config_destroy(config);
699         }
700
701         /* Purge classes that we know can go away (pooled with 0, only) */
702         AST_LIST_TRAVERSE_SAFE_BEGIN(&odbc_list, class, list) {
703                 if (class->delme && class->haspool && class->count == 0) {
704                         while ((current = AST_LIST_REMOVE_HEAD(&class->odbc_obj, list))) {
705                                 odbc_obj_disconnect(current);
706                                 ast_mutex_destroy(&current->lock);
707                                 ast_free(current);
708                         }
709
710                         AST_LIST_REMOVE_CURRENT(list);
711                         ast_free(class);
712                 }
713         }
714         AST_LIST_TRAVERSE_SAFE_END;
715         AST_LIST_UNLOCK(&odbc_list);
716
717         return 0;
718 }
719
720 static int unload_module(void)
721 {
722         /* Prohibit unloading */
723         return -1;
724 }
725
726 static int load_module(void)
727 {
728         if(load_odbc_config() == -1)
729                 return AST_MODULE_LOAD_DECLINE;
730         ast_cli_register_multiple(cli_odbc, sizeof(cli_odbc) / sizeof(struct ast_cli_entry));
731         ast_log(LOG_NOTICE, "res_odbc loaded.\n");
732         return 0;
733 }
734
735 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
736                 .load = load_module,
737                 .unload = unload_module,
738                 .reload = reload,
739                );