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