2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2008, 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>
28 * \author Tilghman Lesher <tilghman@digium.com>
30 * \arg See also: \ref cdr_odbc
34 <depend>generic_odbc</depend>
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42 #include "asterisk/file.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/config.h"
45 #include "asterisk/pbx.h"
46 #include "asterisk/module.h"
47 #include "asterisk/cli.h"
48 #include "asterisk/lock.h"
49 #include "asterisk/res_odbc.h"
50 #include "asterisk/time.h"
51 #include "asterisk/astobj2.h"
52 #include "asterisk/app.h"
53 #include "asterisk/strings.h"
54 #include "asterisk/threadstorage.h"
55 #include "asterisk/data.h"
58 <function name="ODBC" language="en_US">
60 Controls ODBC transaction properties.
63 <parameter name="property" required="true">
65 <enum name="transaction">
66 <para>Gets or sets the active transaction ID. If set, and the transaction ID does not
67 exist and a <replaceable>database name</replaceable> is specified as an argument, it will be created.</para>
69 <enum name="forcecommit">
70 <para>Controls whether a transaction will be automatically committed when the channel
71 hangs up. Defaults to false. If a <replaceable>transaction ID</replaceable> is specified in the optional argument,
72 the property will be applied to that ID, otherwise to the current active ID.</para>
74 <enum name="isolation">
75 <para>Controls the data isolation on uncommitted transactions. May be one of the
76 following: <literal>read_committed</literal>, <literal>read_uncommitted</literal>,
77 <literal>repeatable_read</literal>, or <literal>serializable</literal>. Defaults to the
78 database setting in <filename>res_odbc.conf</filename> or <literal>read_committed</literal>
79 if not specified. If a <replaceable>transaction ID</replaceable> is specified as an optional argument, it will be
80 applied to that ID, otherwise the current active ID.</para>
84 <parameter name="argument" required="false" />
87 <para>The ODBC() function allows setting several properties to influence how a connected
88 database processes transactions.</para>
91 <application name="ODBC_Commit" language="en_US">
93 Commits a currently open database transaction.
96 <parameter name="transaction ID" required="no" />
99 <para>Commits the database transaction specified by <replaceable>transaction ID</replaceable>
100 or the current active transaction, if not specified.</para>
103 <application name="ODBC_Rollback" language="en_US">
105 Rollback a currently open database transaction.
108 <parameter name="transaction ID" required="no" />
111 <para>Rolls back the database transaction specified by <replaceable>transaction ID</replaceable>
112 or the current active transaction, if not specified.</para>
119 AST_LIST_ENTRY(odbc_class) list;
126 unsigned int haspool:1; /*!< Boolean - TDS databases need this */
127 unsigned int delme:1; /*!< Purge the class */
128 unsigned int backslash_is_escape:1; /*!< On this database, the backslash is a native escape sequence */
129 unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
130 unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
131 unsigned int limit; /*!< Maximum number of database handles we will allow */
132 int count; /*!< Running count of pooled connections */
133 unsigned int idlecheck; /*!< Recheck the connection if it is idle for this long (in seconds) */
134 struct ao2_container *obj_container;
137 static struct ao2_container *class_container;
139 static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
141 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
142 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
143 static int odbc_register_class(struct odbc_class *class, int connect);
144 static void odbc_txn_free(void *data);
145 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx);
147 AST_THREADSTORAGE(errors_buf);
149 static struct ast_datastore_info txn_info = {
150 .type = "ODBC_Transaction",
151 .destroy = odbc_txn_free,
154 struct odbc_txn_frame {
155 AST_LIST_ENTRY(odbc_txn_frame) list;
156 struct ast_channel *owner;
157 struct odbc_obj *obj; /*!< Database handle within which transacted statements are run */
158 /*!\brief Is this record the current active transaction within the channel?
159 * Note that the active flag is really only necessary for statements which
160 * are triggered from the dialplan, as there isn't a direct correlation
161 * between multiple statements. Applications wishing to use transactions
162 * may simply perform each statement on the same odbc_obj, which keeps the
163 * transaction persistent.
165 unsigned int active:1;
166 unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
167 unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
168 char name[0]; /*!< Name of this transaction ID */
171 #define DATA_EXPORT_ODBC_CLASS(MEMBER) \
172 MEMBER(odbc_class, name, AST_DATA_STRING) \
173 MEMBER(odbc_class, dsn, AST_DATA_STRING) \
174 MEMBER(odbc_class, username, AST_DATA_STRING) \
175 MEMBER(odbc_class, password, AST_DATA_PASSWORD) \
176 MEMBER(odbc_class, limit, AST_DATA_INTEGER) \
177 MEMBER(odbc_class, count, AST_DATA_INTEGER) \
178 MEMBER(odbc_class, forcecommit, AST_DATA_BOOLEAN)
180 AST_DATA_STRUCTURE(odbc_class, DATA_EXPORT_ODBC_CLASS);
182 static const char *isolation2text(int iso)
184 if (iso == SQL_TXN_READ_COMMITTED) {
185 return "read_committed";
186 } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
187 return "read_uncommitted";
188 } else if (iso == SQL_TXN_SERIALIZABLE) {
189 return "serializable";
190 } else if (iso == SQL_TXN_REPEATABLE_READ) {
191 return "repeatable_read";
197 static int text2isolation(const char *txt)
199 if (strncasecmp(txt, "read_", 5) == 0) {
200 if (strncasecmp(txt + 5, "c", 1) == 0) {
201 return SQL_TXN_READ_COMMITTED;
202 } else if (strncasecmp(txt + 5, "u", 1) == 0) {
203 return SQL_TXN_READ_UNCOMMITTED;
207 } else if (strncasecmp(txt, "ser", 3) == 0) {
208 return SQL_TXN_SERIALIZABLE;
209 } else if (strncasecmp(txt, "rep", 3) == 0) {
210 return SQL_TXN_REPEATABLE_READ;
216 static struct odbc_txn_frame *find_transaction(struct ast_channel *chan, struct odbc_obj *obj, const char *name, int active)
218 struct ast_datastore *txn_store;
219 AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
220 struct odbc_txn_frame *txn = NULL;
222 if (!chan && obj && obj->txf && obj->txf->owner) {
223 chan = obj->txf->owner;
225 /* No channel == no transaction */
229 ast_channel_lock(chan);
230 if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
231 oldlist = txn_store->data;
233 /* Need to create a new datastore */
234 if (!(txn_store = ast_datastore_alloc(&txn_info, NULL))) {
235 ast_log(LOG_ERROR, "Unable to allocate a new datastore. Cannot create a new transaction.\n");
236 ast_channel_unlock(chan);
240 if (!(oldlist = ast_calloc(1, sizeof(*oldlist)))) {
241 ast_log(LOG_ERROR, "Unable to allocate datastore list head. Cannot create a new transaction.\n");
242 ast_datastore_free(txn_store);
243 ast_channel_unlock(chan);
247 txn_store->data = oldlist;
248 AST_LIST_HEAD_INIT(oldlist);
249 ast_channel_datastore_add(chan, txn_store);
252 AST_LIST_LOCK(oldlist);
253 ast_channel_unlock(chan);
255 /* Scanning for an object is *fast*. Scanning for a name is much slower. */
256 if (obj != NULL || active == 1) {
257 AST_LIST_TRAVERSE(oldlist, txn, list) {
258 if (txn->obj == obj || txn->active) {
259 AST_LIST_UNLOCK(oldlist);
266 AST_LIST_TRAVERSE(oldlist, txn, list) {
267 if (!strcasecmp(txn->name, name)) {
268 AST_LIST_UNLOCK(oldlist);
274 /* Nothing found, create one */
275 if (name && obj && (txn = ast_calloc(1, sizeof(*txn) + strlen(name) + 1))) {
276 struct odbc_txn_frame *otxn;
278 strcpy(txn->name, name); /* SAFE */
280 txn->isolation = obj->parent->isolation;
281 txn->forcecommit = obj->parent->forcecommit;
285 /* On creation, the txn becomes active, and all others inactive */
286 AST_LIST_TRAVERSE(oldlist, otxn, list) {
289 AST_LIST_INSERT_TAIL(oldlist, txn, list);
294 AST_LIST_UNLOCK(oldlist);
299 static struct odbc_txn_frame *release_transaction(struct odbc_txn_frame *tx)
305 ast_debug(2, "release_transaction(%p) called (tx->obj = %p, tx->obj->txf = %p)\n", tx, tx->obj, tx->obj ? tx->obj->txf : NULL);
307 /* If we have an owner, disassociate */
309 struct ast_datastore *txn_store;
310 AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
312 ast_channel_lock(tx->owner);
313 if ((txn_store = ast_channel_datastore_find(tx->owner, &txn_info, NULL))) {
314 oldlist = txn_store->data;
315 AST_LIST_LOCK(oldlist);
316 AST_LIST_REMOVE(oldlist, tx, list);
317 AST_LIST_UNLOCK(oldlist);
319 ast_channel_unlock(tx->owner);
324 /* If we have any uncommitted transactions, they are handled when we release the object */
325 struct odbc_obj *obj = tx->obj;
326 /* Prevent recursion during destruction */
329 odbc_release_obj2(obj, tx);
335 static void odbc_txn_free(void *vdata)
337 struct odbc_txn_frame *tx;
338 AST_LIST_HEAD(, odbc_txn_frame) *oldlist = vdata;
340 ast_debug(2, "odbc_txn_free(%p) called\n", vdata);
342 AST_LIST_LOCK(oldlist);
343 while ((tx = AST_LIST_REMOVE_HEAD(oldlist, list))) {
344 release_transaction(tx);
346 AST_LIST_UNLOCK(oldlist);
347 AST_LIST_HEAD_DESTROY(oldlist);
351 static int mark_transaction_active(struct ast_channel *chan, struct odbc_txn_frame *tx)
353 struct ast_datastore *txn_store;
354 AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
355 struct odbc_txn_frame *active = NULL, *txn;
357 if (!chan && tx && tx->owner) {
361 ast_channel_lock(chan);
362 if (!(txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
363 ast_channel_unlock(chan);
367 oldlist = txn_store->data;
368 AST_LIST_LOCK(oldlist);
369 AST_LIST_TRAVERSE(oldlist, txn, list) {
377 AST_LIST_UNLOCK(oldlist);
378 ast_channel_unlock(chan);
379 return active ? 0 : -1;
382 static void odbc_class_destructor(void *data)
384 struct odbc_class *class = data;
385 /* Due to refcounts, we can safely assume that any objects with a reference
386 * to us will prevent our destruction, so we don't need to worry about them.
388 if (class->username) {
389 ast_free(class->username);
391 if (class->password) {
392 ast_free(class->password);
394 if (class->sanitysql) {
395 ast_free(class->sanitysql);
397 ao2_ref(class->obj_container, -1);
398 SQLFreeHandle(SQL_HANDLE_ENV, class->env);
401 static int null_hash_fn(const void *obj, const int flags)
406 static void odbc_obj_destructor(void *data)
408 struct odbc_obj *obj = data;
409 struct odbc_class *class = obj->parent;
411 odbc_obj_disconnect(obj);
412 ast_mutex_destroy(&obj->lock);
416 static void destroy_table_cache(struct odbc_cache_tables *table) {
417 struct odbc_cache_columns *col;
418 ast_debug(1, "Destroying table cache for %s\n", table->table);
419 AST_RWLIST_WRLOCK(&table->columns);
420 while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
423 AST_RWLIST_UNLOCK(&table->columns);
424 AST_RWLIST_HEAD_DESTROY(&table->columns);
429 * \brief Find or create an entry describing the table specified.
430 * \param database Name of an ODBC class on which to query the table
431 * \param tablename Tablename to describe
432 * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
433 * When a structure is returned, the contained columns list will be
434 * rdlock'ed, to ensure that it will be retained in memory.
437 struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
439 struct odbc_cache_tables *tableptr;
440 struct odbc_cache_columns *entry;
443 SQLHSTMT stmt = NULL;
444 int res = 0, error = 0, try = 0;
445 struct odbc_obj *obj = ast_odbc_request_obj(database, 0);
447 AST_RWLIST_RDLOCK(&odbc_tables);
448 AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
449 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
454 AST_RWLIST_RDLOCK(&tableptr->columns);
455 AST_RWLIST_UNLOCK(&odbc_tables);
457 ast_odbc_release_obj(obj);
463 ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
464 AST_RWLIST_UNLOCK(&odbc_tables);
468 /* Table structure not already cached; build it now. */
470 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
471 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
474 ast_odbc_sanity_check(obj);
477 ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
481 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
482 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
485 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
486 ast_odbc_sanity_check(obj);
489 ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
493 if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
494 ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
498 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
499 tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
500 strcpy(tableptr->connection, database); /* SAFE */
501 strcpy(tableptr->table, tablename); /* SAFE */
502 AST_RWLIST_HEAD_INIT(&(tableptr->columns));
504 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
505 SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
507 if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
508 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
512 entry->name = (char *)entry + sizeof(*entry);
513 strcpy(entry->name, columnname);
515 SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
516 SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
517 SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
518 SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
519 SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
520 SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
522 /* Specification states that the octenlen should be the maximum number of bytes
523 * returned in a char or binary column, but it seems that some drivers just set
524 * it to NULL. (Bad Postgres! No biscuit!) */
525 if (entry->octetlen == 0) {
526 entry->octetlen = entry->size;
529 ast_verb(10, "Found %s column with type %hd with len %ld, octetlen %ld, and numlen (%hd,%hd)\n", entry->name, entry->type, (long) entry->size, (long) entry->octetlen, entry->decimals, entry->radix);
530 /* Insert column info into column list */
531 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
533 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
535 AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
536 AST_RWLIST_RDLOCK(&(tableptr->columns));
540 AST_RWLIST_UNLOCK(&odbc_tables);
543 destroy_table_cache(tableptr);
547 ast_odbc_release_obj(obj);
552 struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
554 struct odbc_cache_columns *col;
555 AST_RWLIST_TRAVERSE(&table->columns, col, list) {
556 if (strcasecmp(col->name, colname) == 0) {
563 int ast_odbc_clear_cache(const char *database, const char *tablename)
565 struct odbc_cache_tables *tableptr;
567 AST_RWLIST_WRLOCK(&odbc_tables);
568 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
569 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
570 AST_LIST_REMOVE_CURRENT(list);
571 destroy_table_cache(tableptr);
575 AST_RWLIST_TRAVERSE_SAFE_END
576 AST_RWLIST_UNLOCK(&odbc_tables);
577 return tableptr ? 0 : -1;
580 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
585 for (attempt = 0; attempt < 2; attempt++) {
586 stmt = exec_cb(obj, data);
590 } else if (obj->tx) {
591 ast_log(LOG_WARNING, "Failed to execute, but unable to reconnect, as we're transactional.\n");
595 ast_log(LOG_WARNING, "SQL Exec Direct failed. Attempting a reconnect...\n");
597 odbc_obj_disconnect(obj);
598 odbc_obj_connect(obj);
605 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
607 int res = 0, i, attempt;
608 SQLINTEGER nativeerror=0, numfields=0;
609 SQLSMALLINT diagbytes=0;
610 unsigned char state[10], diagnostic[256];
613 for (attempt = 0; attempt < 2; attempt++) {
614 /* This prepare callback may do more than just prepare -- it may also
615 * bind parameters, bind results, etc. The real key, here, is that
616 * when we disconnect, all handles become invalid for most databases.
617 * We must therefore redo everything when we establish a new
619 stmt = prepare_cb(obj, data);
622 res = SQLExecute(stmt);
623 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
624 if (res == SQL_ERROR) {
625 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
626 for (i = 0; i < numfields; i++) {
627 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
628 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
630 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
637 ast_log(LOG_WARNING, "SQL Execute error, but unable to reconnect, as we're transactional.\n");
640 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
641 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
646 * While this isn't the best way to try to correct an error, this won't automatically
647 * fail when the statement handle invalidates.
649 ast_odbc_sanity_check(obj);
653 obj->last_used = ast_tvnow();
656 } else if (attempt == 0) {
657 ast_odbc_sanity_check(obj);
664 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
667 SQLINTEGER nativeerror=0, numfields=0;
668 SQLSMALLINT diagbytes=0;
669 unsigned char state[10], diagnostic[256];
671 res = SQLExecute(stmt);
672 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
673 if (res == SQL_ERROR) {
674 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
675 for (i = 0; i < numfields; i++) {
676 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
677 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
679 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
685 obj->last_used = ast_tvnow();
690 SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
695 if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
696 ast_str_make_space(buf, *StrLen_or_Ind + 1);
698 } else if (pmaxlen > 0) {
699 ast_str_make_space(buf, pmaxlen);
701 res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
702 ast_str_update(*buf);
707 int ast_odbc_sanity_check(struct odbc_obj *obj)
709 char *test_sql = "select 1";
713 if (!ast_strlen_zero(obj->parent->sanitysql))
714 test_sql = obj->parent->sanitysql;
717 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
718 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
721 res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
722 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
725 res = SQLExecute(stmt);
726 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
731 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
734 if (!obj->up && !obj->tx) { /* Try to reconnect! */
735 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
736 odbc_obj_disconnect(obj);
737 odbc_obj_connect(obj);
742 static int load_odbc_config(void)
744 static char *cfg = "res_odbc.conf";
745 struct ast_config *config;
746 struct ast_variable *v;
748 const char *dsn, *username, *password, *sanitysql;
749 int enabled, pooling, limit, bse, forcecommit, isolation;
750 unsigned int idlecheck;
751 int preconnect = 0, res = 0;
752 struct ast_flags config_flags = { 0 };
754 struct odbc_class *new;
756 config = ast_config_load(cfg, config_flags);
757 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
758 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
761 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
762 if (!strcasecmp(cat, "ENV")) {
763 for (v = ast_variable_browse(config, cat); v; v = v->next) {
764 setenv(v->name, v->value, 1);
765 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
768 /* Reset all to defaults for each class of odbc connections */
769 dsn = username = password = sanitysql = NULL;
771 preconnect = idlecheck = 0;
776 isolation = SQL_TXN_READ_COMMITTED;
777 for (v = ast_variable_browse(config, cat); v; v = v->next) {
778 if (!strcasecmp(v->name, "pooling")) {
779 if (ast_true(v->value))
781 } else if (!strncasecmp(v->name, "share", 5)) {
782 /* "shareconnections" is a little clearer in meaning than "pooling" */
783 if (ast_false(v->value))
785 } else if (!strcasecmp(v->name, "limit")) {
786 sscanf(v->value, "%30d", &limit);
787 if (ast_true(v->value) && !limit) {
788 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);
790 } else if (ast_false(v->value)) {
791 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
795 } else if (!strcasecmp(v->name, "idlecheck")) {
796 sscanf(v->value, "%30u", &idlecheck);
797 } else if (!strcasecmp(v->name, "enabled")) {
798 enabled = ast_true(v->value);
799 } else if (!strcasecmp(v->name, "pre-connect")) {
800 preconnect = ast_true(v->value);
801 } else if (!strcasecmp(v->name, "dsn")) {
803 } else if (!strcasecmp(v->name, "username")) {
805 } else if (!strcasecmp(v->name, "password")) {
807 } else if (!strcasecmp(v->name, "sanitysql")) {
808 sanitysql = v->value;
809 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
810 bse = ast_true(v->value);
811 } else if (!strcasecmp(v->name, "forcecommit")) {
812 forcecommit = ast_true(v->value);
813 } else if (!strcasecmp(v->name, "isolation")) {
814 if ((isolation = text2isolation(v->value)) == 0) {
815 ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
816 isolation = SQL_TXN_READ_COMMITTED;
821 if (enabled && !ast_strlen_zero(dsn)) {
822 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
829 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
830 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
832 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
833 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
838 new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
841 new->haspool = pooling;
845 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
850 new->backslash_is_escape = bse ? 1 : 0;
851 new->forcecommit = forcecommit ? 1 : 0;
852 new->isolation = isolation;
853 new->idlecheck = idlecheck;
856 ast_copy_string(new->name, cat, sizeof(new->name));
858 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
859 if (username && !(new->username = ast_strdup(username))) {
863 if (password && !(new->password = ast_strdup(password))) {
867 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
872 odbc_register_class(new, preconnect);
873 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
879 ast_config_destroy(config);
883 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
885 struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
886 struct odbc_class *class;
887 struct odbc_obj *current;
894 e->command = "odbc show";
896 "Usage: odbc show [class]\n"
897 " List settings of a particular ODBC class or,\n"
898 " if not specified, all classes.\n";
903 length = strlen(a->word);
904 while ((class = ao2_iterator_next(&aoi))) {
905 if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
906 ret = ast_strdup(class->name);
913 ao2_iterator_destroy(&aoi);
914 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
915 ret = ast_strdup("all");
920 ast_cli(a->fd, "\nODBC DSN Settings\n");
921 ast_cli(a->fd, "-----------------\n\n");
922 aoi = ao2_iterator_init(class_container, 0);
923 while ((class = ao2_iterator_next(&aoi))) {
924 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
926 ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
928 if (class->haspool) {
929 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
931 ast_cli(a->fd, " Pooled: Yes\n Limit: %d\n Connections in use: %d\n", class->limit, class->count);
933 while ((current = ao2_iterator_next(&aoi2))) {
934 ast_mutex_lock(¤t->lock);
936 ast_cli(a->fd, " - Connection %d: %s (%s:%d %s)\n", ++count,
937 current->used ? "in use" :
938 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
939 current->file, current->lineno, current->function);
941 ast_cli(a->fd, " - Connection %d: %s\n", ++count,
942 current->used ? "in use" :
943 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
945 ast_mutex_unlock(¤t->lock);
946 ao2_ref(current, -1);
948 ao2_iterator_destroy(&aoi2);
950 /* Should only ever be one of these (unless there are transactions) */
951 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
952 while ((current = ao2_iterator_next(&aoi2))) {
953 ast_cli(a->fd, " Pooled: No\n Connected: %s\n", current->used ? "In use" :
954 current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
955 ao2_ref(current, -1);
957 ao2_iterator_destroy(&aoi2);
959 ast_cli(a->fd, "\n");
963 ao2_iterator_destroy(&aoi);
968 static struct ast_cli_entry cli_odbc[] = {
969 AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
972 static int odbc_register_class(struct odbc_class *class, int preconnect)
974 struct odbc_obj *obj;
976 ao2_link(class_container, class);
977 /* I still have a reference in the caller, so a deref is NOT missing here. */
980 /* Request and release builds a connection */
981 obj = ast_odbc_request_obj(class->name, 0);
983 ast_odbc_release_obj(obj);
989 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
994 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx)
996 SQLINTEGER nativeerror=0, numfields=0;
997 SQLSMALLINT diagbytes=0, i;
998 unsigned char state[10], diagnostic[256];
1000 ast_debug(2, "odbc_release_obj2(%p) called (obj->txf = %p)\n", obj, obj->txf);
1002 ast_debug(1, "called on a transactional handle with %s\n", tx->forcecommit ? "COMMIT" : "ROLLBACK");
1003 if (SQLEndTran(SQL_HANDLE_DBC, obj->con, tx->forcecommit ? SQL_COMMIT : SQL_ROLLBACK) == SQL_ERROR) {
1004 /* Handle possible transaction commit failure */
1005 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1006 for (i = 0; i < numfields; i++) {
1007 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1008 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1009 if (!strcmp((char *)state, "25S02") || !strcmp((char *)state, "08007")) {
1010 /* These codes mean that a commit failed and a transaction
1011 * is still active. We must rollback, or things will get
1012 * very, very weird for anybody using the handle next. */
1013 SQLEndTran(SQL_HANDLE_DBC, obj->con, SQL_ROLLBACK);
1016 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1022 /* Transaction is done, reset autocommit */
1023 if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1024 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1025 for (i = 0; i < numfields; i++) {
1026 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1027 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1029 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1036 #ifdef DEBUG_THREADS
1037 obj->file[0] = '\0';
1038 obj->function[0] = '\0';
1042 /* For pooled connections, this frees the connection to be
1043 * reused. For non-pooled connections, it does nothing. */
1046 /* Prevent recursion -- transaction is already closed out. */
1047 obj->txf->obj = NULL;
1048 obj->txf = release_transaction(obj->txf);
1053 void ast_odbc_release_obj(struct odbc_obj *obj)
1055 struct odbc_txn_frame *tx = find_transaction(NULL, obj, NULL, 0);
1056 odbc_release_obj2(obj, tx);
1059 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
1061 return obj->parent->backslash_is_escape;
1064 static int commit_exec(struct ast_channel *chan, const char *data)
1066 struct odbc_txn_frame *tx;
1067 SQLINTEGER nativeerror=0, numfields=0;
1068 SQLSMALLINT diagbytes=0, i;
1069 unsigned char state[10], diagnostic[256];
1071 if (ast_strlen_zero(data)) {
1072 tx = find_transaction(chan, NULL, NULL, 1);
1074 tx = find_transaction(chan, NULL, data, 0);
1077 pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", "OK");
1080 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_COMMIT) == SQL_ERROR) {
1081 struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1082 ast_str_reset(errors);
1084 /* Handle possible transaction commit failure */
1085 SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1086 for (i = 0; i < numfields; i++) {
1087 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1088 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1089 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1091 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1095 pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", ast_str_buffer(errors));
1101 static int rollback_exec(struct ast_channel *chan, const char *data)
1103 struct odbc_txn_frame *tx;
1104 SQLINTEGER nativeerror=0, numfields=0;
1105 SQLSMALLINT diagbytes=0, i;
1106 unsigned char state[10], diagnostic[256];
1108 if (ast_strlen_zero(data)) {
1109 tx = find_transaction(chan, NULL, NULL, 1);
1111 tx = find_transaction(chan, NULL, data, 0);
1114 pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", "OK");
1117 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_ROLLBACK) == SQL_ERROR) {
1118 struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1119 ast_str_reset(errors);
1121 /* Handle possible transaction commit failure */
1122 SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1123 for (i = 0; i < numfields; i++) {
1124 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1125 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1126 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1128 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1132 pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", ast_str_buffer(errors));
1138 static int aoro2_class_cb(void *obj, void *arg, int flags)
1140 struct odbc_class *class = obj;
1142 if (!strcmp(class->name, name) && !class->delme) {
1143 return CMP_MATCH | CMP_STOP;
1148 #define USE_TX (void *)(long)1
1149 #define NO_TX (void *)(long)2
1150 #define EOR_TX (void *)(long)3
1152 static int aoro2_obj_cb(void *vobj, void *arg, int flags)
1154 struct odbc_obj *obj = vobj;
1155 ast_mutex_lock(&obj->lock);
1156 if ((arg == NO_TX && !obj->tx) || (arg == EOR_TX && !obj->used) || (arg == USE_TX && obj->tx && !obj->used)) {
1158 ast_mutex_unlock(&obj->lock);
1159 return CMP_MATCH | CMP_STOP;
1161 ast_mutex_unlock(&obj->lock);
1165 struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
1167 struct odbc_obj *obj = NULL;
1168 struct odbc_class *class;
1169 SQLINTEGER nativeerror=0, numfields=0;
1170 SQLSMALLINT diagbytes=0, i;
1171 unsigned char state[10], diagnostic[256];
1173 if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
1177 ast_assert(ao2_ref(class, 0) > 1);
1179 if (class->haspool) {
1180 /* Recycle connections before building another */
1181 obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, EOR_TX);
1184 ast_assert(ao2_ref(obj, 0) > 1);
1187 if (!obj && (class->count < class->limit)) {
1188 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1193 ast_assert(ao2_ref(obj, 0) == 1);
1194 ast_mutex_init(&obj->lock);
1195 /* obj inherits the outstanding reference to class */
1196 obj->parent = class;
1198 if (odbc_obj_connect(obj) == ODBC_FAIL) {
1199 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1201 ast_assert(ao2_ref(class, 0) > 0);
1205 ao2_link(obj->parent->obj_container, obj);
1206 ast_atomic_fetchadd_int(&obj->parent->count, +1);
1209 /* Object is not constructed, so delete outstanding reference to class. */
1214 if (obj && ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1215 /* Ensure this connection has autocommit turned off. */
1216 if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1217 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1218 for (i = 0; i < numfields; i++) {
1219 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1220 ast_log(LOG_WARNING, "SQLSetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1222 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1228 } else if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1229 /* Non-pooled connections -- but must use a separate connection handle */
1230 if (!(obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, USE_TX))) {
1231 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1236 ast_mutex_init(&obj->lock);
1237 /* obj inherits the outstanding reference to class */
1238 obj->parent = class;
1240 if (odbc_obj_connect(obj) == ODBC_FAIL) {
1241 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1246 ao2_link(obj->parent->obj_container, obj);
1247 ast_atomic_fetchadd_int(&obj->parent->count, +1);
1251 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1252 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1253 for (i = 0; i < numfields; i++) {
1254 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1255 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1257 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1263 /* Non-pooled connection: multiple modules can use the same connection. */
1264 if ((obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, NO_TX))) {
1265 /* Object is not constructed, so delete outstanding reference to class. */
1266 ast_assert(ao2_ref(class, 0) > 1);
1270 /* No entry: build one */
1271 if (!(obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor))) {
1272 ast_assert(ao2_ref(class, 0) > 1);
1276 ast_mutex_init(&obj->lock);
1277 /* obj inherits the outstanding reference to class */
1278 obj->parent = class;
1280 if (odbc_obj_connect(obj) == ODBC_FAIL) {
1281 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1285 ao2_link(obj->parent->obj_container, obj);
1286 ast_assert(ao2_ref(obj, 0) > 1);
1290 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1291 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1292 for (i = 0; i < numfields; i++) {
1293 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1294 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1296 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1303 /* Set the isolation property */
1304 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)obj->parent->isolation, 0) == SQL_ERROR) {
1305 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1306 for (i = 0; i < numfields; i++) {
1307 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1308 ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1310 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1316 if (obj && ast_test_flag(&flags, RES_ODBC_SANITY_CHECK)) {
1317 ast_odbc_sanity_check(obj);
1318 } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck)
1319 odbc_obj_connect(obj);
1321 #ifdef DEBUG_THREADS
1323 ast_copy_string(obj->file, file, sizeof(obj->file));
1324 ast_copy_string(obj->function, function, sizeof(obj->function));
1325 obj->lineno = lineno;
1328 ast_assert(class == NULL);
1331 ast_assert(ao2_ref(obj, 0) > 1);
1336 struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
1338 struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
1339 return _ast_odbc_request_obj2(name, flags, file, function, lineno);
1342 struct odbc_obj *ast_odbc_retrieve_transaction_obj(struct ast_channel *chan, const char *objname)
1344 struct ast_datastore *txn_store;
1345 AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
1346 struct odbc_txn_frame *txn = NULL;
1349 /* No channel == no transaction */
1353 ast_channel_lock(chan);
1354 if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
1355 oldlist = txn_store->data;
1357 ast_channel_unlock(chan);
1361 AST_LIST_LOCK(oldlist);
1362 ast_channel_unlock(chan);
1364 AST_LIST_TRAVERSE(oldlist, txn, list) {
1365 if (txn->obj && txn->obj->parent && !strcmp(txn->obj->parent->name, objname)) {
1366 AST_LIST_UNLOCK(oldlist);
1370 AST_LIST_UNLOCK(oldlist);
1374 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
1379 unsigned char msg[200], state[10];
1381 /* Nothing to disconnect */
1383 return ODBC_SUCCESS;
1386 ast_mutex_lock(&obj->lock);
1388 res = SQLDisconnect(obj->con);
1391 if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
1392 ast_log(LOG_DEBUG, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
1394 ast_log(LOG_DEBUG, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
1398 if ((res = SQLFreeHandle(SQL_HANDLE_DBC, obj->con) == SQL_SUCCESS)) {
1400 ast_log(LOG_DEBUG, "Database handle deallocated\n");
1402 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
1403 ast_log(LOG_WARNING, "Unable to deallocate database handle? %d errno=%d %s\n", res, (int)err, msg);
1407 ast_mutex_unlock(&obj->lock);
1408 return ODBC_SUCCESS;
1411 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
1416 unsigned char msg[200], state[10];
1418 SQLINTEGER enable = 1;
1419 char *tracefile = "/tmp/odbc.trace";
1421 ast_mutex_lock(&obj->lock);
1424 odbc_obj_disconnect(obj);
1425 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
1427 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
1430 res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
1432 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1433 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
1434 ast_mutex_unlock(&obj->lock);
1437 SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
1438 SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *) 10, 0);
1440 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
1441 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
1444 res = SQLConnect(obj->con,
1445 (SQLCHAR *) obj->parent->dsn, SQL_NTS,
1446 (SQLCHAR *) obj->parent->username, SQL_NTS,
1447 (SQLCHAR *) obj->parent->password, SQL_NTS);
1449 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1450 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
1451 ast_mutex_unlock(&obj->lock);
1452 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
1455 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
1457 obj->last_used = ast_tvnow();
1460 ast_mutex_unlock(&obj->lock);
1461 return ODBC_SUCCESS;
1464 static int acf_transaction_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1466 AST_DECLARE_APP_ARGS(args,
1467 AST_APP_ARG(property);
1470 struct odbc_txn_frame *tx;
1472 AST_STANDARD_APP_ARGS(args, data);
1473 if (strcasecmp(args.property, "transaction") == 0) {
1474 if ((tx = find_transaction(chan, NULL, NULL, 1))) {
1475 ast_copy_string(buf, tx->name, len);
1478 } else if (strcasecmp(args.property, "isolation") == 0) {
1479 if (!ast_strlen_zero(args.opt)) {
1480 tx = find_transaction(chan, NULL, args.opt, 0);
1482 tx = find_transaction(chan, NULL, NULL, 1);
1485 ast_copy_string(buf, isolation2text(tx->isolation), len);
1488 } else if (strcasecmp(args.property, "forcecommit") == 0) {
1489 if (!ast_strlen_zero(args.opt)) {
1490 tx = find_transaction(chan, NULL, args.opt, 0);
1492 tx = find_transaction(chan, NULL, NULL, 1);
1495 ast_copy_string(buf, tx->forcecommit ? "1" : "0", len);
1502 static int acf_transaction_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
1504 AST_DECLARE_APP_ARGS(args,
1505 AST_APP_ARG(property);
1508 struct odbc_txn_frame *tx;
1509 SQLINTEGER nativeerror=0, numfields=0;
1510 SQLSMALLINT diagbytes=0, i;
1511 unsigned char state[10], diagnostic[256];
1513 AST_STANDARD_APP_ARGS(args, s);
1514 if (strcasecmp(args.property, "transaction") == 0) {
1515 /* Set active transaction */
1516 struct odbc_obj *obj;
1517 if ((tx = find_transaction(chan, NULL, value, 0))) {
1518 mark_transaction_active(chan, tx);
1520 /* No such transaction, create one */
1521 struct ast_flags flags = { RES_ODBC_INDEPENDENT_CONNECTION };
1522 if (ast_strlen_zero(args.opt) || !(obj = ast_odbc_request_obj2(args.opt, flags))) {
1523 ast_log(LOG_ERROR, "Could not create transaction: invalid database specification '%s'\n", S_OR(args.opt, ""));
1524 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_DB");
1527 if (!(tx = find_transaction(chan, obj, value, 0))) {
1528 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1533 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1535 } else if (strcasecmp(args.property, "forcecommit") == 0) {
1536 /* Set what happens when an uncommitted transaction ends without explicit Commit or Rollback */
1537 if (ast_strlen_zero(args.opt)) {
1538 tx = find_transaction(chan, NULL, NULL, 1);
1540 tx = find_transaction(chan, NULL, args.opt, 0);
1543 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1546 if (ast_true(value)) {
1547 tx->forcecommit = 1;
1548 } else if (ast_false(value)) {
1549 tx->forcecommit = 0;
1551 ast_log(LOG_ERROR, "Invalid value for forcecommit: '%s'\n", S_OR(value, ""));
1552 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1556 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1558 } else if (strcasecmp(args.property, "isolation") == 0) {
1559 /* How do uncommitted transactions affect reads? */
1560 int isolation = text2isolation(value);
1561 if (ast_strlen_zero(args.opt)) {
1562 tx = find_transaction(chan, NULL, NULL, 1);
1564 tx = find_transaction(chan, NULL, args.opt, 0);
1567 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1570 if (isolation == 0) {
1571 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1572 ast_log(LOG_ERROR, "Invalid isolation specification: '%s'\n", S_OR(value, ""));
1573 } else if (SQLSetConnectAttr(tx->obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)isolation, 0) == SQL_ERROR) {
1574 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "SQL_ERROR");
1575 SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1576 for (i = 0; i < numfields; i++) {
1577 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1578 ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1580 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1585 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1586 tx->isolation = isolation;
1590 ast_log(LOG_ERROR, "Unknown property: '%s'\n", args.property);
1595 static struct ast_custom_function odbc_function = {
1597 .read = acf_transaction_read,
1598 .write = acf_transaction_write,
1601 static const char * const app_commit = "ODBC_Commit";
1602 static const char * const app_rollback = "ODBC_Rollback";
1606 * \brief Implements the channels provider.
1608 static int data_odbc_provider_handler(const struct ast_data_search *search,
1609 struct ast_data *root)
1611 struct ao2_iterator aoi, aoi2;
1612 struct odbc_class *class;
1613 struct odbc_obj *current;
1614 struct ast_data *data_odbc_class, *data_odbc_connections, *data_odbc_connection;
1615 struct ast_data *enum_node;
1618 aoi = ao2_iterator_init(class_container, 0);
1619 while ((class = ao2_iterator_next(&aoi))) {
1620 data_odbc_class = ast_data_add_node(root, "class");
1621 if (!data_odbc_class) {
1626 ast_data_add_structure(odbc_class, data_odbc_class, class);
1628 if (!ao2_container_count(class->obj_container)) {
1633 data_odbc_connections = ast_data_add_node(data_odbc_class, "connections");
1634 if (!data_odbc_connections) {
1639 ast_data_add_bool(data_odbc_class, "shared", !class->haspool);
1641 enum_node = ast_data_add_node(data_odbc_class, "isolation");
1646 ast_data_add_int(enum_node, "value", class->isolation);
1647 ast_data_add_str(enum_node, "text", isolation2text(class->isolation));
1650 aoi2 = ao2_iterator_init(class->obj_container, 0);
1651 while ((current = ao2_iterator_next(&aoi2))) {
1652 data_odbc_connection = ast_data_add_node(data_odbc_connections, "connection");
1653 if (!data_odbc_connection) {
1654 ao2_ref(current, -1);
1658 ast_mutex_lock(¤t->lock);
1659 ast_data_add_str(data_odbc_connection, "status", current->used ? "in use" :
1660 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
1661 ast_data_add_bool(data_odbc_connection, "transactional", current->tx);
1662 ast_mutex_unlock(¤t->lock);
1664 if (class->haspool) {
1665 ast_data_add_int(data_odbc_connection, "number", ++count);
1668 ao2_ref(current, -1);
1672 if (!ast_data_search_match(search, data_odbc_class)) {
1673 ast_data_remove_node(root, data_odbc_class);
1681 * \brief /asterisk/res/odbc/listprovider.
1683 static const struct ast_data_handler odbc_provider = {
1684 .version = AST_DATA_HANDLER_VERSION,
1685 .get = data_odbc_provider_handler
1688 static const struct ast_data_entry odbc_providers[] = {
1689 AST_DATA_ENTRY("/asterisk/res/odbc", &odbc_provider),
1692 static int reload(void)
1694 struct odbc_cache_tables *table;
1695 struct odbc_class *class;
1696 struct odbc_obj *current;
1697 struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
1699 /* First, mark all to be purged */
1700 while ((class = ao2_iterator_next(&aoi))) {
1704 ao2_iterator_destroy(&aoi);
1708 /* Purge remaining classes */
1710 /* Note on how this works; this is a case of circular references, so we
1711 * explicitly do NOT want to use a callback here (or we wind up in
1714 * 1. Iterate through all the classes. Note that the classes will currently
1715 * contain two classes of the same name, one of which is marked delme and
1716 * will be purged when all remaining objects of the class are released, and
1717 * the other, which was created above when we re-parsed the config file.
1718 * 2. On each class, there is a reference held by the master container and
1719 * a reference held by each connection object. There are two cases for
1720 * destruction of the class, noted below. However, in all cases, all O-refs
1721 * (references to objects) will first be freed, which will cause the C-refs
1722 * (references to classes) to be decremented (but never to 0, because the
1723 * class container still has a reference).
1724 * a) If the class has outstanding objects, the C-ref by the class
1725 * container will then be freed, which leaves only C-refs by any
1726 * outstanding objects. When the final outstanding object is released
1727 * (O-refs held by applications and dialplan functions), it will in turn
1728 * free the final C-ref, causing class destruction.
1729 * b) If the class has no outstanding objects, when the class container
1730 * removes the final C-ref, the class will be destroyed.
1732 aoi = ao2_iterator_init(class_container, 0);
1733 while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
1735 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
1736 while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
1737 ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
1738 ao2_ref(current, -1); /* O-ref-- (by iterator) */
1739 /* At this point, either
1740 * a) there's an outstanding O-ref, or
1741 * b) the object has already been destroyed.
1744 ao2_iterator_destroy(&aoi2);
1745 ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
1746 /* At this point, either
1747 * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
1748 * b) the last remaining C-ref is held by the iterator, which will be
1749 * destroyed in the next step.
1752 ao2_ref(class, -1); /* C-ref-- (by iterator) */
1754 ao2_iterator_destroy(&aoi);
1756 /* Empty the cache; it will get rebuilt the next time the tables are needed. */
1757 AST_RWLIST_WRLOCK(&odbc_tables);
1758 while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
1759 destroy_table_cache(table);
1761 AST_RWLIST_UNLOCK(&odbc_tables);
1766 static int unload_module(void)
1768 /* Prohibit unloading */
1772 static int load_module(void)
1774 if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
1775 return AST_MODULE_LOAD_DECLINE;
1776 if (load_odbc_config() == -1)
1777 return AST_MODULE_LOAD_DECLINE;
1778 ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
1779 ast_data_register_multiple(odbc_providers, ARRAY_LEN(odbc_providers));
1780 ast_register_application_xml(app_commit, commit_exec);
1781 ast_register_application_xml(app_rollback, rollback_exec);
1782 ast_custom_function_register(&odbc_function);
1783 ast_log(LOG_NOTICE, "res_odbc loaded.\n");
1787 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
1788 .load = load_module,
1789 .unload = unload_module,