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