2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * res_odbc.c <ODBC resource manager>
9 * Copyright (C) 2004 - 2005 Anthony Minessale II <anthmct@yahoo.com>
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.
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.
24 * \brief ODBC resource manager
26 * \author Mark Spencer <markster@digium.com>
27 * \author Anthony Minessale II <anthmct@yahoo.com>
29 * \arg See also: \ref cdr_odbc
33 <depend>unixodbc</depend>
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
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"
52 AST_LIST_ENTRY(odbc_class) list;
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;
67 AST_LIST_HEAD_STATIC(odbc_list, odbc_class);
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);
74 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
79 for (attempt = 0; attempt < 2; attempt++) {
80 stmt = exec_cb(obj, data);
86 ast_log(LOG_WARNING, "SQL Exec Direct failed. Attempting a reconnect...\n");
88 odbc_obj_disconnect(obj);
89 odbc_obj_connect(obj);
96 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
98 int res = 0, i, attempt;
99 SQLINTEGER nativeerror=0, numfields=0;
100 SQLSMALLINT diagbytes=0;
101 unsigned char state[10], diagnostic[256];
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
110 stmt = prepare_cb(obj, data);
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);
121 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
127 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
128 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
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.
136 ast_odbc_sanity_check(obj);
140 } else if (attempt == 0)
141 ast_odbc_sanity_check(obj);
147 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
150 SQLINTEGER nativeerror=0, numfields=0;
151 SQLSMALLINT diagbytes=0;
152 unsigned char state[10], diagnostic[256];
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);
162 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
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.
175 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
176 ast_mutex_lock(&obj->lock);
178 ast_mutex_unlock(&obj->lock);
179 odbc_obj_disconnect(obj);
180 odbc_obj_connect(obj);
181 res = SQLExecute(stmt);
189 int ast_odbc_sanity_check(struct odbc_obj *obj)
191 char *test_sql = "select 1";
195 if (!ast_strlen_zero(obj->parent->sanitysql))
196 test_sql = obj->parent->sanitysql;
199 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
200 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
203 res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
204 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
207 res = SQLExecute(stmt);
208 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
213 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
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);
224 static int load_odbc_config(void)
226 static char *cfg = "res_odbc.conf";
227 struct ast_config *config;
228 struct ast_variable *v;
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 };
235 struct odbc_class *new;
237 config = ast_config_load(cfg, config_flags);
239 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
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);
249 /* Reset all to defaults for each class of odbc connections */
250 dsn = username = password = sanitysql = NULL;
256 for (v = ast_variable_browse(config, cat); v; v = v->next) {
257 if (!strcasecmp(v->name, "pooling")) {
258 if (ast_true(v->value))
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);
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);
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")) {
276 } else if (!strcasecmp(v->name, "username")) {
278 } else if (!strcasecmp(v->name, "password")) {
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);
287 if (enabled && !ast_strlen_zero(dsn)) {
288 new = ast_calloc(1, sizeof(*new));
296 ast_copy_string(new->name, cat, sizeof(new->name));
298 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
300 new->username = ast_strdup(username);
302 new->password = ast_strdup(password);
304 ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
306 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
307 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
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);
316 new->haspool = pooling;
320 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
325 new->backslash_is_escape = bse ? 1 : 0;
327 odbc_register_class(new, connect);
328 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
332 ast_config_destroy(config);
336 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
338 struct odbc_class *class;
339 struct odbc_obj *current;
346 e->command = "odbc show";
348 "Usage: odbc show [class]\n"
349 " List settings of a particular ODBC class or,\n"
350 " if not specified, all classes.\n";
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);
363 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
364 ret = ast_strdup("all");
366 AST_LIST_UNLOCK(&odbc_list);
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))) {
376 ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
378 if (class->haspool) {
379 ast_cli(a->fd, " Pooled: Yes\n Limit: %d\n Connections in use: %d\n", class->limit, class->count);
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");
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");
390 ast_cli(a->fd, "\n");
393 AST_LIST_UNLOCK(&odbc_list);
398 static struct ast_cli_entry cli_odbc[] = {
399 AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
402 static int odbc_register_class(struct odbc_class *class, int connect)
404 struct odbc_obj *obj;
406 AST_LIST_LOCK(&odbc_list);
407 AST_LIST_INSERT_HEAD(&odbc_list, class, list);
408 AST_LIST_UNLOCK(&odbc_list);
411 /* Request and release builds a connection */
412 obj = ast_odbc_request_obj(class->name, 0);
414 ast_odbc_release_obj(obj);
419 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
424 void ast_odbc_release_obj(struct odbc_obj *obj)
426 /* For pooled connections, this frees the connection to be
427 * reused. For non-pooled connections, it does nothing. */
431 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
433 return obj->parent->backslash_is_escape;
436 struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
438 struct odbc_obj *obj = NULL;
439 struct odbc_class *class;
441 AST_LIST_LOCK(&odbc_list);
442 AST_LIST_TRAVERSE(&odbc_list, class, list) {
443 if (!strcmp(class->name, name))
446 AST_LIST_UNLOCK(&odbc_list);
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) {
461 if (!obj && (class->count < class->limit)) {
463 obj = ast_calloc(1, sizeof(*obj));
465 AST_LIST_UNLOCK(&class->odbc_obj);
468 ast_mutex_init(&obj->lock);
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);
478 AST_LIST_INSERT_TAIL(&class->odbc_obj, obj, list);
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 */
489 /* No entry: build one */
490 obj = ast_calloc(1, sizeof(*obj));
492 AST_LIST_UNLOCK(&class->odbc_obj);
495 ast_mutex_init(&obj->lock);
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);
503 AST_LIST_INSERT_HEAD(&class->odbc_obj, obj, list);
507 AST_LIST_UNLOCK(&class->odbc_obj);
510 ast_odbc_sanity_check(obj);
515 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
518 ast_mutex_lock(&obj->lock);
520 res = SQLDisconnect(obj->con);
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);
525 ast_log(LOG_WARNING, "res_odbc: %s [%s] already disconnected\n",
526 obj->parent->name, obj->parent->dsn);
529 ast_mutex_unlock(&obj->lock);
533 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
538 unsigned char msg[200], stat[10];
540 SQLINTEGER enable = 1;
541 char *tracefile = "/tmp/odbc.trace";
543 ast_mutex_lock(&obj->lock);
545 res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
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);
552 SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
553 SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *) 10, 0);
555 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
556 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
560 odbc_obj_disconnect(obj);
561 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
563 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
566 res = SQLConnect(obj->con,
567 (SQLCHAR *) obj->parent->dsn, SQL_NTS,
568 (SQLCHAR *) obj->parent->username, SQL_NTS,
569 (SQLCHAR *) obj->parent->password, SQL_NTS);
571 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
572 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
573 ast_mutex_unlock(&obj->lock);
574 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
577 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
581 ast_mutex_unlock(&obj->lock);
585 static int reload(void)
587 static char *cfg = "res_odbc.conf";
588 struct ast_config *config;
589 struct ast_variable *v;
591 const char *dsn, *username, *password, *sanitysql;
592 int enabled, pooling, limit, bse;
593 int connect = 0, res = 0;
594 struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
596 struct odbc_class *new, *class;
597 struct odbc_obj *current;
599 /* First, mark all to be purged */
600 AST_LIST_LOCK(&odbc_list);
601 AST_LIST_TRAVERSE(&odbc_list, class, list) {
605 config = ast_config_load(cfg, config_flags);
606 if (config != NULL && config != CONFIG_STATUS_FILEUNCHANGED) {
607 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
608 if (!strcasecmp(cat, "ENV")) {
609 for (v = ast_variable_browse(config, cat); v; v = v->next) {
610 setenv(v->name, v->value, 1);
611 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
615 /* Reset all to defaults for each class of odbc connections */
616 dsn = username = password = sanitysql = NULL;
622 for (v = ast_variable_browse(config, cat); v; v = v->next) {
623 if (!strcasecmp(v->name, "pooling")) {
625 } else if (!strcasecmp(v->name, "limit")) {
626 sscanf(v->value, "%d", &limit);
627 if (ast_true(v->value) && !limit) {
628 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);
630 } else if (ast_false(v->value)) {
631 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
635 } else if (!strcasecmp(v->name, "enabled")) {
636 enabled = ast_true(v->value);
637 } else if (!strcasecmp(v->name, "pre-connect")) {
638 connect = ast_true(v->value);
639 } else if (!strcasecmp(v->name, "dsn")) {
641 } else if (!strcasecmp(v->name, "username")) {
643 } else if (!strcasecmp(v->name, "password")) {
645 } else if (!strcasecmp(v->name, "sanitysql")) {
646 sanitysql = v->value;
647 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
648 bse = ast_true(v->value);
652 if (enabled && !ast_strlen_zero(dsn)) {
653 /* First, check the list to see if it already exists */
654 AST_LIST_TRAVERSE(&odbc_list, class, list) {
655 if (!strcmp(class->name, cat)) {
664 new = ast_calloc(1, sizeof(*new));
673 ast_copy_string(new->name, cat, sizeof(new->name));
675 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
677 /* Safely replace username */
678 if (class && class->username)
679 freeme = class->username;
681 new->username = ast_strdup(username);
687 /* Safely replace password */
688 if (class && class->password)
689 freeme = class->password;
691 new->password = ast_strdup(password);
698 ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
701 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
702 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
704 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
705 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
706 SQLFreeHandle(SQL_HANDLE_ENV, new->env);
707 AST_LIST_UNLOCK(&odbc_list);
713 new->haspool = pooling;
717 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
722 new->backslash_is_escape = bse;
725 ast_log(LOG_NOTICE, "Refreshing ODBC class '%s' dsn->[%s]\n", cat, dsn);
727 odbc_register_class(new, connect);
728 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
733 ast_config_destroy(config);
736 /* Purge classes that we know can go away (pooled with 0, only) */
737 AST_LIST_TRAVERSE_SAFE_BEGIN(&odbc_list, class, list) {
738 if (class->delme && class->haspool && class->count == 0) {
739 while ((current = AST_LIST_REMOVE_HEAD(&class->odbc_obj, list))) {
740 odbc_obj_disconnect(current);
741 ast_mutex_destroy(¤t->lock);
745 AST_LIST_REMOVE_CURRENT(list);
747 ast_free(class->username);
749 ast_free(class->password);
753 AST_LIST_TRAVERSE_SAFE_END;
754 AST_LIST_UNLOCK(&odbc_list);
759 static int unload_module(void)
761 /* Prohibit unloading */
765 static int load_module(void)
767 if (load_odbc_config() == -1)
768 return AST_MODULE_LOAD_DECLINE;
769 ast_cli_register_multiple(cli_odbc, sizeof(cli_odbc) / sizeof(struct ast_cli_entry));
770 ast_log(LOG_NOTICE, "res_odbc loaded.\n");
774 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
776 .unload = unload_module,