aboutsummaryrefslogtreecommitdiffstats
path: root/res/res_odbc.c
blob: b458d602d4b223bba128f515053b7fa4dcc1be1b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 1999 - 2005, Digium, Inc.
 *
 * Mark Spencer <markster@digium.com>
 *
 * res_odbc.c <ODBC resource manager>
 * Copyright (C) 2004 - 2005 Anthony Minessale II <anthmct@yahoo.com>
 *
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 */

/*! \file
 *
 * \brief ODBC resource manager
 * 
 * \author Mark Spencer <markster@digium.com>
 * \author Anthony Minessale II <anthmct@yahoo.com>
 *
 * \arg See also: \ref cdr_odbc
 */

/*** MODULEINFO
	<depend>unixodbc</depend>
	<depend>ltdl</depend>
 ***/

#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision$")

#include "asterisk/file.h"
#include "asterisk/logger.h"
#include "asterisk/channel.h"
#include "asterisk/config.h"
#include "asterisk/options.h"
#include "asterisk/pbx.h"
#include "asterisk/module.h"
#include "asterisk/cli.h"
#include "asterisk/lock.h"
#include "asterisk/res_odbc.h"

struct odbc_class
{
	AST_LIST_ENTRY(odbc_class) list;
	char name[80];
	char dsn[80];
	char username[80];
	char password[80];
	char sanitysql[256];
	SQLHENV env;
	unsigned int haspool:1;         /* Boolean - TDS databases need this */
	unsigned int limit:10;          /* Gives a limit of 1023 maximum */
	unsigned int count:10;          /* Running count of pooled connections */
	unsigned int delme:1;			/* Purge the class */
	AST_LIST_HEAD(, odbc_obj) odbc_obj;
};

AST_LIST_HEAD_STATIC(odbc_list, odbc_class);

static odbc_status odbc_obj_connect(struct odbc_obj *obj);
static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
static int odbc_register_class(struct odbc_class *class, int connect);


SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
{
	int attempt;
	SQLHSTMT stmt;

	for (attempt = 0; attempt < 2; attempt++) {
		stmt = exec_cb(obj, data);

		if (stmt) {
			break;
		} else {
			obj->up = 0;
			ast_log(LOG_WARNING, "SQL Exec Direct failed.  Attempting a reconnect...\n");

			odbc_obj_disconnect(obj);
			odbc_obj_connect(obj);
		}
	}

	return stmt;
}

SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
{
	int res = 0, i, attempt;
	SQLINTEGER nativeerror=0, numfields=0;
	SQLSMALLINT diagbytes=0;
	unsigned char state[10], diagnostic[256];
	SQLHSTMT stmt;

	for (attempt = 0; attempt < 2; attempt++) {
		/* This prepare callback may do more than just prepare -- it may also
		 * bind parameters, bind results, etc.  The real key, here, is that
		 * when we disconnect, all handles become invalid for most databases.
		 * We must therefore redo everything when we establish a new
		 * connection. */
		stmt = prepare_cb(obj, data);

		if (stmt) {
			res = SQLExecute(stmt);
			if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
				if (res == SQL_ERROR) {
					SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
					for (i = 0; i < numfields; i++) {
						SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
						ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
						if (i > 10) {
							ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
							break;
						}
					}
				}

				ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
				SQLFreeHandle(SQL_HANDLE_STMT, stmt);
				stmt = NULL;

				obj->up = 0;
				/*
				 * While this isn't the best way to try to correct an error, this won't automatically
				 * fail when the statement handle invalidates.
				 */
				ast_odbc_sanity_check(obj);
				continue;
			}
			break;
		} else if (attempt == 0)
			ast_odbc_sanity_check(obj);
	}

	return stmt;
}

int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt) 
{
	int res = 0, i;
	SQLINTEGER nativeerror=0, numfields=0;
	SQLSMALLINT diagbytes=0;
	unsigned char state[10], diagnostic[256];

	res = SQLExecute(stmt);
	if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
		if (res == SQL_ERROR) {
			SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
			for (i = 0; i < numfields; i++) {
				SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
				ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
				if (i > 10) {
					ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
					break;
				}
			}
		}
#if 0
		/* This is a really bad method of trying to correct a dead connection.  It
		 * only ever really worked with MySQL.  It will not work with any other
		 * database, since most databases prepare their statements on the server,
		 * and if you disconnect, you invalidate the statement handle.  Hence, if
		 * you disconnect, you're going to fail anyway, whether you try to execute
		 * a second time or not.
		 */
		ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
		ast_mutex_lock(&obj->lock);
		obj->up = 0;
		ast_mutex_unlock(&obj->lock);
		odbc_obj_disconnect(obj);
		odbc_obj_connect(obj);
		res = SQLExecute(stmt);
#endif
	}
	
	return res;
}


int ast_odbc_sanity_check(struct odbc_obj *obj) 
{
	char *test_sql = "select 1";
	SQLHSTMT stmt;
	int res = 0;

	if (!ast_strlen_zero(obj->parent->sanitysql))
		test_sql = obj->parent->sanitysql;

	if (obj->up) {
		res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
		if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
			obj->up = 0;
		} else {
			res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
			if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
				obj->up = 0;
			} else {
				res = SQLExecute(stmt);
				if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
					obj->up = 0;
				}
			}
		}
		SQLFreeHandle (SQL_HANDLE_STMT, stmt);
	}

	if (!obj->up) { /* Try to reconnect! */
		ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
		odbc_obj_disconnect(obj);
		odbc_obj_connect(obj);
	}
	return obj->up;
}

static int load_odbc_config(void)
{
	static char *cfg = "res_odbc.conf";
	struct ast_config *config;
	struct ast_variable *v;
	char *cat;
	const char *dsn, *username, *password, *sanitysql;
	int enabled, pooling, limit;
	int connect = 0, res = 0;
	struct ast_flags config_flags = { 0 };

	struct odbc_class *new;

	config = ast_config_load(cfg, config_flags);
	if (!config) {
		ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
		return -1;
	}
	for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
		if (!strcasecmp(cat, "ENV")) {
			for (v = ast_variable_browse(config, cat); v; v = v->next) {
				setenv(v->name, v->value, 1);
				ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
			}
		} else {
			/* Reset all to defaults for each class of odbc connections */
			dsn = username = password = sanitysql = NULL;
			enabled = 1;
			connect = 0;
			pooling = 0;
			limit = 0;
			for (v = ast_variable_browse(config, cat); v; v = v->next) {
				if (!strcasecmp(v->name, "pooling")) {
					if (ast_true(v->value))
						pooling = 1;
				} else if (!strcasecmp(v->name, "limit")) {
					sscanf(v->value, "%d", &limit);
					if (ast_true(v->value) && !limit) {
						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);
						limit = 1023;
					} else if (ast_false(v->value)) {
						ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
						enabled = 0;
						break;
					}
				} else if (!strcasecmp(v->name, "enabled")) {
					enabled = ast_true(v->value);
				} else if (!strcasecmp(v->name, "pre-connect")) {
					connect = ast_true(v->value);
				} else if (!strcasecmp(v->name, "dsn")) {
					dsn = v->value;
				} else if (!strcasecmp(v->name, "username")) {
					username = v->value;
				} else if (!strcasecmp(v->name, "password")) {
					password = v->value;
				} else if (!strcasecmp(v->name, "sanitysql")) {
					sanitysql = v->value;
				}
			}

			if (enabled && !ast_strlen_zero(dsn)) {
				new = ast_calloc(1, sizeof(*new));

				if (!new) {
					res = -1;
					break;
				}

				if (cat)
					ast_copy_string(new->name, cat, sizeof(new->name));
				if (dsn)
					ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
				if (username)
					ast_copy_string(new->username, username, sizeof(new->username));
				if (password)
					ast_copy_string(new->password, password, sizeof(new->password));
				if (sanitysql)
					ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));

				SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
				res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

				if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
					ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
					SQLFreeHandle(SQL_HANDLE_ENV, new->env);
					return res;
				}

				if (pooling) {
					new->haspool = pooling;
					if (limit) {
						new->limit = limit;
					} else {
						ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
						new->limit = 5;
					}
				}

				odbc_register_class(new, connect);
				ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
			}
		}
	}
	ast_config_destroy(config);
	return res;
}

static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct odbc_class *class;
	struct odbc_obj *current;
	int length = 0;
	int which = 0;
	char *ret = NULL;

	switch (cmd) {
	case CLI_INIT:
		e->command = "odbc show";
		e->usage =
				"Usage: odbc show [class]\n"
				"       List settings of a particular ODBC class or,\n"
				"       if not specified, all classes.\n";
		return NULL;
	case CLI_GENERATE:
		if (a->pos != 2)
			return NULL;
		length = strlen(a->word);
		AST_LIST_LOCK(&odbc_list);
		AST_LIST_TRAVERSE(&odbc_list, class, list) {
			if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
				ret = ast_strdup(class->name);
				break;
			}
		}
		if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
			ret = ast_strdup("all");
		}
		AST_LIST_UNLOCK(&odbc_list);
		return ret;
	}

	ast_cli(a->fd, "\nODBC DSN Settings\n");
	ast_cli(a->fd, "-----------------\n\n");
	AST_LIST_LOCK(&odbc_list);
	AST_LIST_TRAVERSE(&odbc_list, class, list) {
		if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
			int count = 0;
			ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);

			if (class->haspool) {
				ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);

				AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
					ast_cli(a->fd, "    - Connection %d: %s\n", ++count, current->used ? "in use" : current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
				}
			} else {
				/* Should only ever be one of these */
				AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
					ast_cli(a->fd, "  Pooled: No\n  Connected: %s\n", current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
				}
			}
			ast_cli(a->fd, "\n");
		}
	}
	AST_LIST_UNLOCK(&odbc_list);

	return CLI_SUCCESS;
}

static struct ast_cli_entry cli_odbc[] = {
	AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
};

static int odbc_register_class(struct odbc_class *class, int connect)
{
	struct odbc_obj *obj;
	if (class) {
		AST_LIST_LOCK(&odbc_list);
		AST_LIST_INSERT_HEAD(&odbc_list, class, list);
		AST_LIST_UNLOCK(&odbc_list);

		if (connect) {
			/* Request and release builds a connection */
			obj = ast_odbc_request_obj(class->name, 0);
			if (obj)
				ast_odbc_release_obj(obj);
		}

		return 0;
	} else {
		ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
		return -1;
	}
}

void ast_odbc_release_obj(struct odbc_obj *obj)
{
	/* For pooled connections, this frees the connection to be
	 * reused.  For non-pooled connections, it does nothing. */
	obj->used = 0;
}

struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
{
	struct odbc_obj *obj = NULL;
	struct odbc_class *class;

	AST_LIST_LOCK(&odbc_list);
	AST_LIST_TRAVERSE(&odbc_list, class, list) {
		if (!strcmp(class->name, name))
			break;
	}
	AST_LIST_UNLOCK(&odbc_list);

	if (!class)
		return NULL;

	AST_LIST_LOCK(&class->odbc_obj);
	if (class->haspool) {
		/* Recycle connections before building another */
		AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
			if (! obj->used) {
				obj->used = 1;
				break;
			}
		}

		if (!obj && (class->count < class->limit)) {
			class->count++;
			obj = ast_calloc(1, sizeof(*obj));
			if (!obj) {
				AST_LIST_UNLOCK(&class->odbc_obj);
				return NULL;
			}
			ast_mutex_init(&obj->lock);
			obj->parent = class;
			if (odbc_obj_connect(obj) == ODBC_FAIL) {
				ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
				ast_mutex_destroy(&obj->lock);
				free(obj);
				obj = NULL;
				class->count--;
			} else {
				obj->used = 1;
				AST_LIST_INSERT_TAIL(&class->odbc_obj, obj, list);
			}
		}
	} else {
		/* Non-pooled connection: multiple modules can use the same connection. */
		AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
			/* Non-pooled connection: if there is an entry, return it */
			break;
		}

		if (!obj) {
			/* No entry: build one */
			obj = ast_calloc(1, sizeof(*obj));
			if (!obj) {
				AST_LIST_UNLOCK(&class->odbc_obj);
				return NULL;
			}
			ast_mutex_init(&obj->lock);
			obj->parent = class;
			if (odbc_obj_connect(obj) == ODBC_FAIL) {
				ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
				ast_mutex_destroy(&obj->lock);
				ast_free(obj);
				obj = NULL;
			} else {
				AST_LIST_INSERT_HEAD(&class->odbc_obj, obj, list);
			}
		}
	}
	AST_LIST_UNLOCK(&class->odbc_obj);

	if (obj && check) {
		ast_odbc_sanity_check(obj);
	}
	return obj;
}

static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
{
	int res;
	ast_mutex_lock(&obj->lock);

	res = SQLDisconnect(obj->con);

	if (res == ODBC_SUCCESS) {
		ast_log(LOG_WARNING, "res_odbc: disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
	} else {
		ast_log(LOG_WARNING, "res_odbc: %s [%s] already disconnected\n",
		obj->parent->name, obj->parent->dsn);
	}
	obj->up = 0;
	ast_mutex_unlock(&obj->lock);
	return ODBC_SUCCESS;
}

static odbc_status odbc_obj_connect(struct odbc_obj *obj)
{
	int res;
	SQLINTEGER err;
	short int mlen;
	unsigned char msg[200], stat[10];
#ifdef NEEDTRACE
	SQLINTEGER enable = 1;
	char *tracefile = "/tmp/odbc.trace";
#endif
	ast_mutex_lock(&obj->lock);

	res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);

	if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
		ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
		ast_mutex_unlock(&obj->lock);
		return ODBC_FAIL;
	}
	SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
#ifdef NEEDTRACE
	SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
	SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
#endif

	if (obj->up) {
		odbc_obj_disconnect(obj);
		ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
	} else {
		ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
	}

	res = SQLConnect(obj->con,
		   (SQLCHAR *) obj->parent->dsn, SQL_NTS,
		   (SQLCHAR *) obj->parent->username, SQL_NTS,
		   (SQLCHAR *) obj->parent->password, SQL_NTS);

	if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
		SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
		ast_mutex_unlock(&obj->lock);
		ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
		return ODBC_FAIL;
	} else {
		ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
		obj->up = 1;
	}

	ast_mutex_unlock(&obj->lock);
	return ODBC_SUCCESS;
}

static int reload(void)
{
	static char *cfg = "res_odbc.conf";
	struct ast_config *config;
	struct ast_variable *v;
	char *cat;
	const char *dsn, *username, *password, *sanitysql;
	int enabled, pooling, limit;
	int connect = 0, res = 0;
	struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };

	struct odbc_class *new, *class;
	struct odbc_obj *current;

	/* First, mark all to be purged */
	AST_LIST_LOCK(&odbc_list);
	AST_LIST_TRAVERSE(&odbc_list, class, list) {
		class->delme = 1;
	}

	config = ast_config_load(cfg, config_flags);
	if (config != NULL && config != CONFIG_STATUS_FILEUNCHANGED) {
		for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
			if (!strcasecmp(cat, "ENV")) {
				for (v = ast_variable_browse(config, cat); v; v = v->next) {
					setenv(v->name, v->value, 1);
					ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
				}
			} else {
				/* Reset all to defaults for each class of odbc connections */
				dsn = username = password = sanitysql = NULL;
				enabled = 1;
				connect = 0;
				pooling = 0;
				limit = 0;
				for (v = ast_variable_browse(config, cat); v; v = v->next) {
					if (!strcasecmp(v->name, "pooling")) {
						pooling = 1;
					} else if (!strcasecmp(v->name, "limit")) {
						sscanf(v->value, "%d", &limit);
						if (ast_true(v->value) && !limit) {
							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);
							limit = 1023;
						} else if (ast_false(v->value)) {
							ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
							enabled = 0;
							break;
						}
					} else if (!strcasecmp(v->name, "enabled")) {
						enabled = ast_true(v->value);
					} else if (!strcasecmp(v->name, "pre-connect")) {
						connect = ast_true(v->value);
					} else if (!strcasecmp(v->name, "dsn")) {
						dsn = v->value;
					} else if (!strcasecmp(v->name, "username")) {
						username = v->value;
					} else if (!strcasecmp(v->name, "password")) {
						password = v->value;
					} else if (!strcasecmp(v->name, "sanitysql")) {
						sanitysql = v->value;
					}
				}

				if (enabled && !ast_strlen_zero(dsn)) {
					/* First, check the list to see if it already exists */
					AST_LIST_TRAVERSE(&odbc_list, class, list) {
						if (!strcmp(class->name, cat)) {
							class->delme = 0;
							break;
						}
					}

					if (class) {
						new = class;
					} else {
						new = ast_calloc(1, sizeof(*new));
					}

					if (!new) {
						res = -1;
						break;
					}

					if (cat)
						ast_copy_string(new->name, cat, sizeof(new->name));
					if (dsn)
						ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
					if (username)
						ast_copy_string(new->username, username, sizeof(new->username));
					if (password)
						ast_copy_string(new->password, password, sizeof(new->password));
					if (sanitysql)
						ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));

					if (!class) {
						SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
						res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

						if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
							ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
							SQLFreeHandle(SQL_HANDLE_ENV, new->env);
							AST_LIST_UNLOCK(&odbc_list);
							return res;
						}
					}

					if (pooling) {
						new->haspool = pooling;
						if (limit) {
							new->limit = limit;
						} else {
							ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
							new->limit = 5;
						}
					}

					if (class) {
						ast_log(LOG_NOTICE, "Refreshing ODBC class '%s' dsn->[%s]\n", cat, dsn);
					} else {
						odbc_register_class(new, connect);
						ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
					}
				}
			}
		}
		ast_config_destroy(config);
	}

	/* Purge classes that we know can go away (pooled with 0, only) */
	AST_LIST_TRAVERSE_SAFE_BEGIN(&odbc_list, class, list) {
		if (class->delme && class->haspool && class->count == 0) {
			while ((current = AST_LIST_REMOVE_HEAD(&class->odbc_obj, list))) {
				odbc_obj_disconnect(current);
				ast_mutex_destroy(&current->lock);
				ast_free(current);
			}

			AST_LIST_REMOVE_CURRENT(list);
			ast_free(class);
		}
	}
	AST_LIST_TRAVERSE_SAFE_END;
	AST_LIST_UNLOCK(&odbc_list);

	return 0;
}

static int unload_module(void)
{
	/* Prohibit unloading */
	return -1;
}

static int load_module(void)
{
	if(load_odbc_config() == -1)
		return AST_MODULE_LOAD_DECLINE;
	ast_cli_register_multiple(cli_odbc, sizeof(cli_odbc) / sizeof(struct ast_cli_entry));
	ast_log(LOG_NOTICE, "res_odbc loaded.\n");
	return 0;
}

AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
		.load = load_module,
		.unload = unload_module,
		.reload = reload,
	       );