Sat Mar 26 11:08:09 2011

Asterisk developer's documentation


res_odbc.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2008, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * res_odbc.c <ODBC resource manager>
00009  * Copyright (C) 2004 - 2005 Anthony Minessale II <anthmct@yahoo.com>
00010  *
00011  * See http://www.asterisk.org for more information about
00012  * the Asterisk project. Please do not directly contact
00013  * any of the maintainers of this project for assistance;
00014  * the project provides a web site, mailing lists and IRC
00015  * channels for your use.
00016  *
00017  * This program is free software, distributed under the terms of
00018  * the GNU General Public License Version 2. See the LICENSE file
00019  * at the top of the source tree.
00020  */
00021 
00022 /*! \file
00023  *
00024  * \brief ODBC resource manager
00025  * 
00026  * \author Mark Spencer <markster@digium.com>
00027  * \author Anthony Minessale II <anthmct@yahoo.com>
00028  * \author Tilghman Lesher <tilghman@digium.com>
00029  *
00030  * \arg See also: \ref cdr_odbc
00031  */
00032 
00033 /*** MODULEINFO
00034    <depend>generic_odbc</depend>
00035    <depend>ltdl</depend>
00036  ***/
00037 
00038 #include "asterisk.h"
00039 
00040 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 283659 $")
00041 
00042 #include "asterisk/file.h"
00043 #include "asterisk/channel.h"
00044 #include "asterisk/config.h"
00045 #include "asterisk/pbx.h"
00046 #include "asterisk/module.h"
00047 #include "asterisk/cli.h"
00048 #include "asterisk/lock.h"
00049 #include "asterisk/res_odbc.h"
00050 #include "asterisk/time.h"
00051 #include "asterisk/astobj2.h"
00052 #include "asterisk/app.h"
00053 #include "asterisk/strings.h"
00054 #include "asterisk/threadstorage.h"
00055 #include "asterisk/data.h"
00056 
00057 /*** DOCUMENTATION
00058    <function name="ODBC" language="en_US">
00059       <synopsis>
00060          Controls ODBC transaction properties.
00061       </synopsis>
00062       <syntax>
00063          <parameter name="property" required="true">
00064             <enumlist>
00065                <enum name="transaction">
00066                   <para>Gets or sets the active transaction ID.  If set, and the transaction ID does not
00067                   exist and a <replaceable>database name</replaceable> is specified as an argument, it will be created.</para>
00068                </enum>
00069                <enum name="forcecommit">
00070                   <para>Controls whether a transaction will be automatically committed when the channel
00071                   hangs up.  Defaults to false.  If a <replaceable>transaction ID</replaceable> is specified in the optional argument,
00072                   the property will be applied to that ID, otherwise to the current active ID.</para>
00073                </enum>
00074                <enum name="isolation">
00075                   <para>Controls the data isolation on uncommitted transactions.  May be one of the
00076                   following: <literal>read_committed</literal>, <literal>read_uncommitted</literal>,
00077                   <literal>repeatable_read</literal>, or <literal>serializable</literal>.  Defaults to the
00078                   database setting in <filename>res_odbc.conf</filename> or <literal>read_committed</literal>
00079                   if not specified.  If a <replaceable>transaction ID</replaceable> is specified as an optional argument, it will be
00080                   applied to that ID, otherwise the current active ID.</para>
00081                </enum>
00082             </enumlist>
00083          </parameter>
00084          <parameter name="argument" required="false" />
00085       </syntax>
00086       <description>
00087          <para>The ODBC() function allows setting several properties to influence how a connected
00088          database processes transactions.</para>
00089       </description>
00090    </function>
00091    <application name="ODBC_Commit" language="en_US">
00092       <synopsis>
00093          Commits a currently open database transaction.
00094       </synopsis>
00095       <syntax>
00096          <parameter name="transaction ID" required="no" />
00097       </syntax>
00098       <description>
00099          <para>Commits the database transaction specified by <replaceable>transaction ID</replaceable>
00100          or the current active transaction, if not specified.</para>
00101       </description>
00102    </application>
00103    <application name="ODBC_Rollback" language="en_US">
00104       <synopsis>
00105          Rollback a currently open database transaction.
00106       </synopsis>
00107       <syntax>
00108          <parameter name="transaction ID" required="no" />
00109       </syntax>
00110       <description>
00111          <para>Rolls back the database transaction specified by <replaceable>transaction ID</replaceable>
00112          or the current active transaction, if not specified.</para>
00113       </description>
00114    </application>
00115  ***/
00116 
00117 struct odbc_class
00118 {
00119    AST_LIST_ENTRY(odbc_class) list;
00120    char name[80];
00121    char dsn[80];
00122    char *username;
00123    char *password;
00124    char *sanitysql;
00125    SQLHENV env;
00126    unsigned int haspool:1;              /*!< Boolean - TDS databases need this */
00127    unsigned int delme:1;                /*!< Purge the class */
00128    unsigned int backslash_is_escape:1;  /*!< On this database, the backslash is a native escape sequence */
00129    unsigned int forcecommit:1;          /*!< Should uncommitted transactions be auto-committed on handle release? */
00130    unsigned int isolation;              /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
00131    unsigned int limit;                  /*!< Maximum number of database handles we will allow */
00132    int count;                           /*!< Running count of pooled connections */
00133    unsigned int idlecheck;              /*!< Recheck the connection if it is idle for this long (in seconds) */
00134    unsigned int conntimeout;            /*!< Maximum time the connection process should take */
00135    /*! When a connection fails, cache that failure for how long? */
00136    struct timeval negative_connection_cache;
00137    /*! When a connection fails, when did that last occur? */
00138    struct timeval last_negative_connect;
00139    /*! List of handles associated with this class */
00140    struct ao2_container *obj_container;
00141 };
00142 
00143 static struct ao2_container *class_container;
00144 
00145 static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
00146 
00147 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
00148 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
00149 static int odbc_register_class(struct odbc_class *class, int connect);
00150 static void odbc_txn_free(void *data);
00151 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx);
00152 
00153 AST_THREADSTORAGE(errors_buf);
00154 
00155 static struct ast_datastore_info txn_info = {
00156    .type = "ODBC_Transaction",
00157    .destroy = odbc_txn_free,
00158 };
00159 
00160 struct odbc_txn_frame {
00161    AST_LIST_ENTRY(odbc_txn_frame) list;
00162    struct ast_channel *owner;
00163    struct odbc_obj *obj;        /*!< Database handle within which transacted statements are run */
00164    /*!\brief Is this record the current active transaction within the channel?
00165     * Note that the active flag is really only necessary for statements which
00166     * are triggered from the dialplan, as there isn't a direct correlation
00167     * between multiple statements.  Applications wishing to use transactions
00168     * may simply perform each statement on the same odbc_obj, which keeps the
00169     * transaction persistent.
00170     */
00171    unsigned int active:1;
00172    unsigned int forcecommit:1;     /*!< Should uncommitted transactions be auto-committed on handle release? */
00173    unsigned int isolation;         /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
00174    char name[0];                   /*!< Name of this transaction ID */
00175 };
00176 
00177 #define DATA_EXPORT_ODBC_CLASS(MEMBER)          \
00178    MEMBER(odbc_class, name, AST_DATA_STRING)    \
00179    MEMBER(odbc_class, dsn, AST_DATA_STRING)     \
00180    MEMBER(odbc_class, username, AST_DATA_STRING)      \
00181    MEMBER(odbc_class, password, AST_DATA_PASSWORD)    \
00182    MEMBER(odbc_class, limit, AST_DATA_INTEGER)     \
00183    MEMBER(odbc_class, count, AST_DATA_INTEGER)     \
00184    MEMBER(odbc_class, forcecommit, AST_DATA_BOOLEAN)
00185 
00186 AST_DATA_STRUCTURE(odbc_class, DATA_EXPORT_ODBC_CLASS);
00187 
00188 static const char *isolation2text(int iso)
00189 {
00190    if (iso == SQL_TXN_READ_COMMITTED) {
00191       return "read_committed";
00192    } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
00193       return "read_uncommitted";
00194    } else if (iso == SQL_TXN_SERIALIZABLE) {
00195       return "serializable";
00196    } else if (iso == SQL_TXN_REPEATABLE_READ) {
00197       return "repeatable_read";
00198    } else {
00199       return "unknown";
00200    }
00201 }
00202 
00203 static int text2isolation(const char *txt)
00204 {
00205    if (strncasecmp(txt, "read_", 5) == 0) {
00206       if (strncasecmp(txt + 5, "c", 1) == 0) {
00207          return SQL_TXN_READ_COMMITTED;
00208       } else if (strncasecmp(txt + 5, "u", 1) == 0) {
00209          return SQL_TXN_READ_UNCOMMITTED;
00210       } else {
00211          return 0;
00212       }
00213    } else if (strncasecmp(txt, "ser", 3) == 0) {
00214       return SQL_TXN_SERIALIZABLE;
00215    } else if (strncasecmp(txt, "rep", 3) == 0) {
00216       return SQL_TXN_REPEATABLE_READ;
00217    } else {
00218       return 0;
00219    }
00220 }
00221 
00222 static struct odbc_txn_frame *find_transaction(struct ast_channel *chan, struct odbc_obj *obj, const char *name, int active)
00223 {
00224    struct ast_datastore *txn_store;
00225    AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
00226    struct odbc_txn_frame *txn = NULL;
00227 
00228    if (!chan && obj && obj->txf && obj->txf->owner) {
00229       chan = obj->txf->owner;
00230    } else if (!chan) {
00231       /* No channel == no transaction */
00232       return NULL;
00233    }
00234 
00235    ast_channel_lock(chan);
00236    if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
00237       oldlist = txn_store->data;
00238    } else {
00239       /* Need to create a new datastore */
00240       if (!(txn_store = ast_datastore_alloc(&txn_info, NULL))) {
00241          ast_log(LOG_ERROR, "Unable to allocate a new datastore.  Cannot create a new transaction.\n");
00242          ast_channel_unlock(chan);
00243          return NULL;
00244       }
00245 
00246       if (!(oldlist = ast_calloc(1, sizeof(*oldlist)))) {
00247          ast_log(LOG_ERROR, "Unable to allocate datastore list head.  Cannot create a new transaction.\n");
00248          ast_datastore_free(txn_store);
00249          ast_channel_unlock(chan);
00250          return NULL;
00251       }
00252 
00253       txn_store->data = oldlist;
00254       AST_LIST_HEAD_INIT(oldlist);
00255       ast_channel_datastore_add(chan, txn_store);
00256    }
00257 
00258    AST_LIST_LOCK(oldlist);
00259    ast_channel_unlock(chan);
00260 
00261    /* Scanning for an object is *fast*.  Scanning for a name is much slower. */
00262    if (obj != NULL || active == 1) {
00263       AST_LIST_TRAVERSE(oldlist, txn, list) {
00264          if (txn->obj == obj || txn->active) {
00265             AST_LIST_UNLOCK(oldlist);
00266             return txn;
00267          }
00268       }
00269    }
00270 
00271    if (name != NULL) {
00272       AST_LIST_TRAVERSE(oldlist, txn, list) {
00273          if (!strcasecmp(txn->name, name)) {
00274             AST_LIST_UNLOCK(oldlist);
00275             return txn;
00276          }
00277       }
00278    }
00279 
00280    /* Nothing found, create one */
00281    if (name && obj && (txn = ast_calloc(1, sizeof(*txn) + strlen(name) + 1))) {
00282       struct odbc_txn_frame *otxn;
00283 
00284       strcpy(txn->name, name); /* SAFE */
00285       txn->obj = obj;
00286       txn->isolation = obj->parent->isolation;
00287       txn->forcecommit = obj->parent->forcecommit;
00288       txn->owner = chan;
00289       txn->active = 1;
00290 
00291       /* On creation, the txn becomes active, and all others inactive */
00292       AST_LIST_TRAVERSE(oldlist, otxn, list) {
00293          otxn->active = 0;
00294       }
00295       AST_LIST_INSERT_TAIL(oldlist, txn, list);
00296 
00297       obj->txf = txn;
00298       obj->tx = 1;
00299    }
00300    AST_LIST_UNLOCK(oldlist);
00301 
00302    return txn;
00303 }
00304 
00305 static struct odbc_txn_frame *release_transaction(struct odbc_txn_frame *tx)
00306 {
00307    if (!tx) {
00308       return NULL;
00309    }
00310 
00311    ast_debug(2, "release_transaction(%p) called (tx->obj = %p, tx->obj->txf = %p)\n", tx, tx->obj, tx->obj ? tx->obj->txf : NULL);
00312 
00313    /* If we have an owner, disassociate */
00314    if (tx->owner) {
00315       struct ast_datastore *txn_store;
00316       AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
00317 
00318       ast_channel_lock(tx->owner);
00319       if ((txn_store = ast_channel_datastore_find(tx->owner, &txn_info, NULL))) {
00320          oldlist = txn_store->data;
00321          AST_LIST_LOCK(oldlist);
00322          AST_LIST_REMOVE(oldlist, tx, list);
00323          AST_LIST_UNLOCK(oldlist);
00324       }
00325       ast_channel_unlock(tx->owner);
00326       tx->owner = NULL;
00327    }
00328 
00329    if (tx->obj) {
00330       /* If we have any uncommitted transactions, they are handled when we release the object */
00331       struct odbc_obj *obj = tx->obj;
00332       /* Prevent recursion during destruction */
00333       tx->obj->txf = NULL;
00334       tx->obj = NULL;
00335       odbc_release_obj2(obj, tx);
00336    }
00337    ast_free(tx);
00338    return NULL;
00339 }
00340 
00341 static void odbc_txn_free(void *vdata)
00342 {
00343    struct odbc_txn_frame *tx;
00344    AST_LIST_HEAD(, odbc_txn_frame) *oldlist = vdata;
00345 
00346    ast_debug(2, "odbc_txn_free(%p) called\n", vdata);
00347 
00348    AST_LIST_LOCK(oldlist);
00349    while ((tx = AST_LIST_REMOVE_HEAD(oldlist, list))) {
00350       release_transaction(tx);
00351    }
00352    AST_LIST_UNLOCK(oldlist);
00353    AST_LIST_HEAD_DESTROY(oldlist);
00354    ast_free(oldlist);
00355 }
00356 
00357 static int mark_transaction_active(struct ast_channel *chan, struct odbc_txn_frame *tx)
00358 {
00359    struct ast_datastore *txn_store;
00360    AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
00361    struct odbc_txn_frame *active = NULL, *txn;
00362 
00363    if (!chan && tx && tx->owner) {
00364       chan = tx->owner;
00365    }
00366 
00367    ast_channel_lock(chan);
00368    if (!(txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
00369       ast_channel_unlock(chan);
00370       return -1;
00371    }
00372 
00373    oldlist = txn_store->data;
00374    AST_LIST_LOCK(oldlist);
00375    AST_LIST_TRAVERSE(oldlist, txn, list) {
00376       if (txn == tx) {
00377          txn->active = 1;
00378          active = txn;
00379       } else {
00380          txn->active = 0;
00381       }
00382    }
00383    AST_LIST_UNLOCK(oldlist);
00384    ast_channel_unlock(chan);
00385    return active ? 0 : -1;
00386 }
00387 
00388 static void odbc_class_destructor(void *data)
00389 {
00390    struct odbc_class *class = data;
00391    /* Due to refcounts, we can safely assume that any objects with a reference
00392     * to us will prevent our destruction, so we don't need to worry about them.
00393     */
00394    if (class->username) {
00395       ast_free(class->username);
00396    }
00397    if (class->password) {
00398       ast_free(class->password);
00399    }
00400    if (class->sanitysql) {
00401       ast_free(class->sanitysql);
00402    }
00403    ao2_ref(class->obj_container, -1);
00404    SQLFreeHandle(SQL_HANDLE_ENV, class->env);
00405 }
00406 
00407 static int null_hash_fn(const void *obj, const int flags)
00408 {
00409    return 0;
00410 }
00411 
00412 static void odbc_obj_destructor(void *data)
00413 {
00414    struct odbc_obj *obj = data;
00415    struct odbc_class *class = obj->parent;
00416    obj->parent = NULL;
00417    odbc_obj_disconnect(obj);
00418    ast_mutex_destroy(&obj->lock);
00419    ao2_ref(class, -1);
00420 }
00421 
00422 static void destroy_table_cache(struct odbc_cache_tables *table) {
00423    struct odbc_cache_columns *col;
00424    ast_debug(1, "Destroying table cache for %s\n", table->table);
00425    AST_RWLIST_WRLOCK(&table->columns);
00426    while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
00427       ast_free(col);
00428    }
00429    AST_RWLIST_UNLOCK(&table->columns);
00430    AST_RWLIST_HEAD_DESTROY(&table->columns);
00431    ast_free(table);
00432 }
00433 
00434 /*!
00435  * \brief Find or create an entry describing the table specified.
00436  * \param database Name of an ODBC class on which to query the table
00437  * \param tablename Tablename to describe
00438  * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
00439  * When a structure is returned, the contained columns list will be
00440  * rdlock'ed, to ensure that it will be retained in memory.
00441  * \since 1.6.1
00442  */
00443 struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
00444 {
00445    struct odbc_cache_tables *tableptr;
00446    struct odbc_cache_columns *entry;
00447    char columnname[80];
00448    SQLLEN sqlptr;
00449    SQLHSTMT stmt = NULL;
00450    int res = 0, error = 0, try = 0;
00451    struct odbc_obj *obj = ast_odbc_request_obj(database, 0);
00452 
00453    AST_RWLIST_RDLOCK(&odbc_tables);
00454    AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
00455       if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
00456          break;
00457       }
00458    }
00459    if (tableptr) {
00460       AST_RWLIST_RDLOCK(&tableptr->columns);
00461       AST_RWLIST_UNLOCK(&odbc_tables);
00462       if (obj) {
00463          ast_odbc_release_obj(obj);
00464       }
00465       return tableptr;
00466    }
00467 
00468    if (!obj) {
00469       ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
00470       AST_RWLIST_UNLOCK(&odbc_tables);
00471       return NULL;
00472    }
00473 
00474    /* Table structure not already cached; build it now. */
00475    do {
00476       res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
00477       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00478          if (try == 0) {
00479             try = 1;
00480             ast_odbc_sanity_check(obj);
00481             continue;
00482          }
00483          ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
00484          break;
00485       }
00486 
00487       res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
00488       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00489          if (try == 0) {
00490             try = 1;
00491             SQLFreeHandle(SQL_HANDLE_STMT, stmt);
00492             ast_odbc_sanity_check(obj);
00493             continue;
00494          }
00495          ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
00496          break;
00497       }
00498 
00499       if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
00500          ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
00501          break;
00502       }
00503 
00504       tableptr->connection = (char *)tableptr + sizeof(*tableptr);
00505       tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
00506       strcpy(tableptr->connection, database); /* SAFE */
00507       strcpy(tableptr->table, tablename); /* SAFE */
00508       AST_RWLIST_HEAD_INIT(&(tableptr->columns));
00509 
00510       while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
00511          SQLGetData(stmt,  4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
00512 
00513          if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
00514             ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
00515             error = 1;
00516             break;
00517          }
00518          entry->name = (char *)entry + sizeof(*entry);
00519          strcpy(entry->name, columnname);
00520 
00521          SQLGetData(stmt,  5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
00522          SQLGetData(stmt,  7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
00523          SQLGetData(stmt,  9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
00524          SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
00525          SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
00526          SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
00527 
00528          /* Specification states that the octenlen should be the maximum number of bytes
00529           * returned in a char or binary column, but it seems that some drivers just set
00530           * it to NULL. (Bad Postgres! No biscuit!) */
00531          if (entry->octetlen == 0) {
00532             entry->octetlen = entry->size;
00533          }
00534 
00535          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);
00536          /* Insert column info into column list */
00537          AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
00538       }
00539       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
00540 
00541       AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
00542       AST_RWLIST_RDLOCK(&(tableptr->columns));
00543       break;
00544    } while (1);
00545 
00546    AST_RWLIST_UNLOCK(&odbc_tables);
00547 
00548    if (error) {
00549       destroy_table_cache(tableptr);
00550       tableptr = NULL;
00551    }
00552    if (obj) {
00553       ast_odbc_release_obj(obj);
00554    }
00555    return tableptr;
00556 }
00557 
00558 struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
00559 {
00560    struct odbc_cache_columns *col;
00561    AST_RWLIST_TRAVERSE(&table->columns, col, list) {
00562       if (strcasecmp(col->name, colname) == 0) {
00563          return col;
00564       }
00565    }
00566    return NULL;
00567 }
00568 
00569 int ast_odbc_clear_cache(const char *database, const char *tablename)
00570 {
00571    struct odbc_cache_tables *tableptr;
00572 
00573    AST_RWLIST_WRLOCK(&odbc_tables);
00574    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
00575       if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
00576          AST_LIST_REMOVE_CURRENT(list);
00577          destroy_table_cache(tableptr);
00578          break;
00579       }
00580    }
00581    AST_RWLIST_TRAVERSE_SAFE_END
00582    AST_RWLIST_UNLOCK(&odbc_tables);
00583    return tableptr ? 0 : -1;
00584 }
00585 
00586 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
00587 {
00588    int attempt;
00589    SQLHSTMT stmt;
00590 
00591    for (attempt = 0; attempt < 2; attempt++) {
00592       stmt = exec_cb(obj, data);
00593 
00594       if (stmt) {
00595          break;
00596       } else if (obj->tx) {
00597          ast_log(LOG_WARNING, "Failed to execute, but unable to reconnect, as we're transactional.\n");
00598          break;
00599       } else {
00600          obj->up = 0;
00601          ast_log(LOG_WARNING, "SQL Exec Direct failed.  Attempting a reconnect...\n");
00602 
00603          odbc_obj_disconnect(obj);
00604          odbc_obj_connect(obj);
00605       }
00606    }
00607 
00608    return stmt;
00609 }
00610 
00611 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
00612 {
00613    int res = 0, i, attempt;
00614    SQLINTEGER nativeerror=0, numfields=0;
00615    SQLSMALLINT diagbytes=0;
00616    unsigned char state[10], diagnostic[256];
00617    SQLHSTMT stmt;
00618 
00619    for (attempt = 0; attempt < 2; attempt++) {
00620       /* This prepare callback may do more than just prepare -- it may also
00621        * bind parameters, bind results, etc.  The real key, here, is that
00622        * when we disconnect, all handles become invalid for most databases.
00623        * We must therefore redo everything when we establish a new
00624        * connection. */
00625       stmt = prepare_cb(obj, data);
00626 
00627       if (stmt) {
00628          res = SQLExecute(stmt);
00629          if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
00630             if (res == SQL_ERROR) {
00631                SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
00632                for (i = 0; i < numfields; i++) {
00633                   SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
00634                   ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
00635                   if (i > 10) {
00636                      ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
00637                      break;
00638                   }
00639                }
00640             }
00641 
00642             if (obj->tx) {
00643                ast_log(LOG_WARNING, "SQL Execute error, but unable to reconnect, as we're transactional.\n");
00644                break;
00645             } else {
00646                ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
00647                SQLFreeHandle(SQL_HANDLE_STMT, stmt);
00648                stmt = NULL;
00649 
00650                obj->up = 0;
00651                /*
00652                 * While this isn't the best way to try to correct an error, this won't automatically
00653                 * fail when the statement handle invalidates.
00654                 */
00655                ast_odbc_sanity_check(obj);
00656                continue;
00657             }
00658          } else {
00659             obj->last_used = ast_tvnow();
00660          }
00661          break;
00662       } else if (attempt == 0) {
00663          ast_odbc_sanity_check(obj);
00664       }
00665    }
00666 
00667    return stmt;
00668 }
00669 
00670 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
00671 {
00672    int res = 0, i;
00673    SQLINTEGER nativeerror=0, numfields=0;
00674    SQLSMALLINT diagbytes=0;
00675    unsigned char state[10], diagnostic[256];
00676 
00677    res = SQLExecute(stmt);
00678    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
00679       if (res == SQL_ERROR) {
00680          SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
00681          for (i = 0; i < numfields; i++) {
00682             SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
00683             ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
00684             if (i > 10) {
00685                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
00686                break;
00687             }
00688          }
00689       }
00690    } else {
00691       obj->last_used = ast_tvnow();
00692    }
00693 
00694    return res;
00695 }
00696 
00697 SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
00698 {
00699    SQLRETURN res;
00700 
00701    if (pmaxlen == 0) {
00702       if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
00703          ast_str_make_space(buf, *StrLen_or_Ind + 1);
00704       }
00705    } else if (pmaxlen > 0) {
00706       ast_str_make_space(buf, pmaxlen);
00707    }
00708    res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
00709    ast_str_update(*buf);
00710 
00711    return res;
00712 }
00713 
00714 int ast_odbc_sanity_check(struct odbc_obj *obj) 
00715 {
00716    char *test_sql = "select 1";
00717    SQLHSTMT stmt;
00718    int res = 0;
00719 
00720    if (!ast_strlen_zero(obj->parent->sanitysql))
00721       test_sql = obj->parent->sanitysql;
00722 
00723    if (obj->up) {
00724       res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
00725       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00726          obj->up = 0;
00727       } else {
00728          res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
00729          if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00730             obj->up = 0;
00731          } else {
00732             res = SQLExecute(stmt);
00733             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00734                obj->up = 0;
00735             }
00736          }
00737       }
00738       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
00739    }
00740 
00741    if (!obj->up && !obj->tx) { /* Try to reconnect! */
00742       ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
00743       odbc_obj_disconnect(obj);
00744       odbc_obj_connect(obj);
00745    }
00746    return obj->up;
00747 }
00748 
00749 static int load_odbc_config(void)
00750 {
00751    static char *cfg = "res_odbc.conf";
00752    struct ast_config *config;
00753    struct ast_variable *v;
00754    char *cat;
00755    const char *dsn, *username, *password, *sanitysql;
00756    int enabled, pooling, limit, bse, conntimeout, forcecommit, isolation;
00757    struct timeval ncache = { 0, 0 };
00758    unsigned int idlecheck;
00759    int preconnect = 0, res = 0;
00760    struct ast_flags config_flags = { 0 };
00761 
00762    struct odbc_class *new;
00763 
00764    config = ast_config_load(cfg, config_flags);
00765    if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
00766       ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
00767       return -1;
00768    }
00769    for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
00770       if (!strcasecmp(cat, "ENV")) {
00771          for (v = ast_variable_browse(config, cat); v; v = v->next) {
00772             setenv(v->name, v->value, 1);
00773             ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
00774          }
00775       } else {
00776          /* Reset all to defaults for each class of odbc connections */
00777          dsn = username = password = sanitysql = NULL;
00778          enabled = 1;
00779          preconnect = idlecheck = 0;
00780          pooling = 0;
00781          limit = 0;
00782          bse = 1;
00783          conntimeout = 10;
00784          forcecommit = 0;
00785          isolation = SQL_TXN_READ_COMMITTED;
00786          for (v = ast_variable_browse(config, cat); v; v = v->next) {
00787             if (!strcasecmp(v->name, "pooling")) {
00788                if (ast_true(v->value))
00789                   pooling = 1;
00790             } else if (!strncasecmp(v->name, "share", 5)) {
00791                /* "shareconnections" is a little clearer in meaning than "pooling" */
00792                if (ast_false(v->value))
00793                   pooling = 1;
00794             } else if (!strcasecmp(v->name, "limit")) {
00795                sscanf(v->value, "%30d", &limit);
00796                if (ast_true(v->value) && !limit) {
00797                   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);
00798                   limit = 1023;
00799                } else if (ast_false(v->value)) {
00800                   ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
00801                   enabled = 0;
00802                   break;
00803                }
00804             } else if (!strcasecmp(v->name, "idlecheck")) {
00805                sscanf(v->value, "%30u", &idlecheck);
00806             } else if (!strcasecmp(v->name, "enabled")) {
00807                enabled = ast_true(v->value);
00808             } else if (!strcasecmp(v->name, "pre-connect")) {
00809                preconnect = ast_true(v->value);
00810             } else if (!strcasecmp(v->name, "dsn")) {
00811                dsn = v->value;
00812             } else if (!strcasecmp(v->name, "username")) {
00813                username = v->value;
00814             } else if (!strcasecmp(v->name, "password")) {
00815                password = v->value;
00816             } else if (!strcasecmp(v->name, "sanitysql")) {
00817                sanitysql = v->value;
00818             } else if (!strcasecmp(v->name, "backslash_is_escape")) {
00819                bse = ast_true(v->value);
00820             } else if (!strcasecmp(v->name, "connect_timeout")) {
00821                if (sscanf(v->value, "%d", &conntimeout) != 1 || conntimeout < 1) {
00822                   ast_log(LOG_WARNING, "connect_timeout must be a positive integer\n");
00823                   conntimeout = 10;
00824                }
00825             } else if (!strcasecmp(v->name, "negative_connection_cache")) {
00826                double dncache;
00827                if (sscanf(v->value, "%lf", &dncache) != 1 || dncache < 0) {
00828                   ast_log(LOG_WARNING, "negative_connection_cache must be a non-negative integer\n");
00829                   /* 5 minutes sounds like a reasonable default */
00830                   ncache.tv_sec = 300;
00831                   ncache.tv_usec = 0;
00832                } else {
00833                   ncache.tv_sec = (int)dncache;
00834                   ncache.tv_usec = (dncache - ncache.tv_sec) * 1000000;
00835                }
00836             } else if (!strcasecmp(v->name, "forcecommit")) {
00837                forcecommit = ast_true(v->value);
00838             } else if (!strcasecmp(v->name, "isolation")) {
00839                if ((isolation = text2isolation(v->value)) == 0) {
00840                   ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
00841                   isolation = SQL_TXN_READ_COMMITTED;
00842                }
00843             }
00844          }
00845 
00846          if (enabled && !ast_strlen_zero(dsn)) {
00847             new = ao2_alloc(sizeof(*new), odbc_class_destructor);
00848 
00849             if (!new) {
00850                res = -1;
00851                break;
00852             }
00853 
00854             SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
00855             res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
00856 
00857             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00858                ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
00859                ao2_ref(new, -1);
00860                return res;
00861             }
00862 
00863             new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
00864 
00865             if (pooling) {
00866                new->haspool = pooling;
00867                if (limit) {
00868                   new->limit = limit;
00869                } else {
00870                   ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
00871                   new->limit = 5;
00872                }
00873             }
00874 
00875             new->backslash_is_escape = bse ? 1 : 0;
00876             new->forcecommit = forcecommit ? 1 : 0;
00877             new->isolation = isolation;
00878             new->idlecheck = idlecheck;
00879             new->conntimeout = conntimeout;
00880             new->negative_connection_cache = ncache;
00881 
00882             if (cat)
00883                ast_copy_string(new->name, cat, sizeof(new->name));
00884             if (dsn)
00885                ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
00886             if (username && !(new->username = ast_strdup(username))) {
00887                ao2_ref(new, -1);
00888                break;
00889             }
00890             if (password && !(new->password = ast_strdup(password))) {
00891                ao2_ref(new, -1);
00892                break;
00893             }
00894             if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
00895                ao2_ref(new, -1);
00896                break;
00897             }
00898 
00899             odbc_register_class(new, preconnect);
00900             ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
00901             ao2_ref(new, -1);
00902             new = NULL;
00903          }
00904       }
00905    }
00906    ast_config_destroy(config);
00907    return res;
00908 }
00909 
00910 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00911 {
00912    struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
00913    struct odbc_class *class;
00914    struct odbc_obj *current;
00915    int length = 0;
00916    int which = 0;
00917    char *ret = NULL;
00918 
00919    switch (cmd) {
00920    case CLI_INIT:
00921       e->command = "odbc show";
00922       e->usage =
00923             "Usage: odbc show [class]\n"
00924             "       List settings of a particular ODBC class or,\n"
00925             "       if not specified, all classes.\n";
00926       return NULL;
00927    case CLI_GENERATE:
00928       if (a->pos != 2)
00929          return NULL;
00930       length = strlen(a->word);
00931       while ((class = ao2_iterator_next(&aoi))) {
00932          if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
00933             ret = ast_strdup(class->name);
00934          }
00935          ao2_ref(class, -1);
00936          if (ret) {
00937             break;
00938          }
00939       }
00940       ao2_iterator_destroy(&aoi);
00941       if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
00942          ret = ast_strdup("all");
00943       }
00944       return ret;
00945    }
00946 
00947    ast_cli(a->fd, "\nODBC DSN Settings\n");
00948    ast_cli(a->fd,   "-----------------\n\n");
00949    aoi = ao2_iterator_init(class_container, 0);
00950    while ((class = ao2_iterator_next(&aoi))) {
00951       if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
00952          int count = 0;
00953          char timestr[80];
00954          struct ast_tm tm;
00955 
00956          ast_localtime(&class->last_negative_connect, &tm, NULL);
00957          ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
00958          ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
00959          ast_cli(a->fd, "    Last connection attempt: %s\n", timestr);
00960 
00961          if (class->haspool) {
00962             struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
00963 
00964             ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);
00965 
00966             while ((current = ao2_iterator_next(&aoi2))) {
00967                ast_mutex_lock(&current->lock);
00968 #ifdef DEBUG_THREADS
00969                ast_cli(a->fd, "    - Connection %d: %s (%s:%d %s)\n", ++count,
00970                   current->used ? "in use" :
00971                   current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
00972                   current->file, current->lineno, current->function);
00973 #else
00974                ast_cli(a->fd, "    - Connection %d: %s\n", ++count,
00975                   current->used ? "in use" :
00976                   current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
00977 #endif
00978                ast_mutex_unlock(&current->lock);
00979                ao2_ref(current, -1);
00980             }
00981             ao2_iterator_destroy(&aoi2);
00982          } else {
00983             /* Should only ever be one of these (unless there are transactions) */
00984             struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
00985             while ((current = ao2_iterator_next(&aoi2))) {
00986                ast_cli(a->fd, "  Pooled: No\n  Connected: %s\n", current->used ? "In use" :
00987                   current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
00988                ao2_ref(current, -1);
00989             }
00990             ao2_iterator_destroy(&aoi2);
00991          }
00992          ast_cli(a->fd, "\n");
00993       }
00994       ao2_ref(class, -1);
00995    }
00996    ao2_iterator_destroy(&aoi);
00997 
00998    return CLI_SUCCESS;
00999 }
01000 
01001 static struct ast_cli_entry cli_odbc[] = {
01002    AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
01003 };
01004 
01005 static int odbc_register_class(struct odbc_class *class, int preconnect)
01006 {
01007    struct odbc_obj *obj;
01008    if (class) {
01009       ao2_link(class_container, class);
01010       /* I still have a reference in the caller, so a deref is NOT missing here. */
01011 
01012       if (preconnect) {
01013          /* Request and release builds a connection */
01014          obj = ast_odbc_request_obj(class->name, 0);
01015          if (obj) {
01016             ast_odbc_release_obj(obj);
01017          }
01018       }
01019 
01020       return 0;
01021    } else {
01022       ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
01023       return -1;
01024    }
01025 }
01026 
01027 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx)
01028 {
01029    SQLINTEGER nativeerror=0, numfields=0;
01030    SQLSMALLINT diagbytes=0, i;
01031    unsigned char state[10], diagnostic[256];
01032 
01033    ast_debug(2, "odbc_release_obj2(%p) called (obj->txf = %p)\n", obj, obj->txf);
01034    if (tx) {
01035       ast_debug(1, "called on a transactional handle with %s\n", tx->forcecommit ? "COMMIT" : "ROLLBACK");
01036       if (SQLEndTran(SQL_HANDLE_DBC, obj->con, tx->forcecommit ? SQL_COMMIT : SQL_ROLLBACK) == SQL_ERROR) {
01037          /* Handle possible transaction commit failure */
01038          SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01039          for (i = 0; i < numfields; i++) {
01040             SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01041             ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
01042             if (!strcmp((char *)state, "25S02") || !strcmp((char *)state, "08007")) {
01043                /* These codes mean that a commit failed and a transaction
01044                 * is still active. We must rollback, or things will get
01045                 * very, very weird for anybody using the handle next. */
01046                SQLEndTran(SQL_HANDLE_DBC, obj->con, SQL_ROLLBACK);
01047             }
01048             if (i > 10) {
01049                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01050                break;
01051             }
01052          }
01053       }
01054 
01055       /* Transaction is done, reset autocommit */
01056       if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
01057          SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01058          for (i = 0; i < numfields; i++) {
01059             SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01060             ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
01061             if (i > 10) {
01062                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01063                break;
01064             }
01065          }
01066       }
01067    }
01068 
01069 #ifdef DEBUG_THREADS
01070    obj->file[0] = '\0';
01071    obj->function[0] = '\0';
01072    obj->lineno = 0;
01073 #endif
01074 
01075    /* For pooled connections, this frees the connection to be
01076     * reused.  For non-pooled connections, it does nothing. */
01077    obj->used = 0;
01078    if (obj->txf) {
01079       /* Prevent recursion -- transaction is already closed out. */
01080       obj->txf->obj = NULL;
01081       obj->txf = release_transaction(obj->txf);
01082    }
01083    ao2_ref(obj, -1);
01084 }
01085 
01086 void ast_odbc_release_obj(struct odbc_obj *obj)
01087 {
01088    struct odbc_txn_frame *tx = find_transaction(NULL, obj, NULL, 0);
01089    odbc_release_obj2(obj, tx);
01090 }
01091 
01092 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
01093 {
01094    return obj->parent->backslash_is_escape;
01095 }
01096 
01097 static int commit_exec(struct ast_channel *chan, const char *data)
01098 {
01099    struct odbc_txn_frame *tx;
01100    SQLINTEGER nativeerror=0, numfields=0;
01101    SQLSMALLINT diagbytes=0, i;
01102    unsigned char state[10], diagnostic[256];
01103 
01104    if (ast_strlen_zero(data)) {
01105       tx = find_transaction(chan, NULL, NULL, 1);
01106    } else {
01107       tx = find_transaction(chan, NULL, data, 0);
01108    }
01109 
01110    pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", "OK");
01111 
01112    if (tx) {
01113       if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_COMMIT) == SQL_ERROR) {
01114          struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
01115          ast_str_reset(errors);
01116 
01117          /* Handle possible transaction commit failure */
01118          SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01119          for (i = 0; i < numfields; i++) {
01120             SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01121             ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
01122             ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
01123             if (i > 10) {
01124                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01125                break;
01126             }
01127          }
01128          pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", ast_str_buffer(errors));
01129       }
01130    }
01131    return 0;
01132 }
01133 
01134 static int rollback_exec(struct ast_channel *chan, const char *data)
01135 {
01136    struct odbc_txn_frame *tx;
01137    SQLINTEGER nativeerror=0, numfields=0;
01138    SQLSMALLINT diagbytes=0, i;
01139    unsigned char state[10], diagnostic[256];
01140 
01141    if (ast_strlen_zero(data)) {
01142       tx = find_transaction(chan, NULL, NULL, 1);
01143    } else {
01144       tx = find_transaction(chan, NULL, data, 0);
01145    }
01146 
01147    pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", "OK");
01148 
01149    if (tx) {
01150       if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_ROLLBACK) == SQL_ERROR) {
01151          struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
01152          ast_str_reset(errors);
01153 
01154          /* Handle possible transaction commit failure */
01155          SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01156          for (i = 0; i < numfields; i++) {
01157             SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01158             ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
01159             ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
01160             if (i > 10) {
01161                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01162                break;
01163             }
01164          }
01165          pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", ast_str_buffer(errors));
01166       }
01167    }
01168    return 0;
01169 }
01170 
01171 static int aoro2_class_cb(void *obj, void *arg, int flags)
01172 {
01173    struct odbc_class *class = obj;
01174    char *name = arg;
01175    if (!strcmp(class->name, name) && !class->delme) {
01176       return CMP_MATCH | CMP_STOP;
01177    }
01178    return 0;
01179 }
01180 
01181 #define USE_TX (void *)(long)1
01182 #define NO_TX  (void *)(long)2
01183 #define EOR_TX (void *)(long)3
01184 
01185 static int aoro2_obj_cb(void *vobj, void *arg, int flags)
01186 {
01187    struct odbc_obj *obj = vobj;
01188    ast_mutex_lock(&obj->lock);
01189    if ((arg == NO_TX && !obj->tx) || (arg == EOR_TX && !obj->used) || (arg == USE_TX && obj->tx && !obj->used)) {
01190       obj->used = 1;
01191       ast_mutex_unlock(&obj->lock);
01192       return CMP_MATCH | CMP_STOP;
01193    }
01194    ast_mutex_unlock(&obj->lock);
01195    return 0;
01196 }
01197 
01198 struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
01199 {
01200    struct odbc_obj *obj = NULL;
01201    struct odbc_class *class;
01202    SQLINTEGER nativeerror=0, numfields=0;
01203    SQLSMALLINT diagbytes=0, i;
01204    unsigned char state[10], diagnostic[256];
01205 
01206    if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
01207       ast_debug(1, "Class '%s' not found!\n", name);
01208       return NULL;
01209    }
01210 
01211    ast_assert(ao2_ref(class, 0) > 1);
01212 
01213    if (class->haspool) {
01214       /* Recycle connections before building another */
01215       obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, EOR_TX);
01216 
01217       if (obj) {
01218          ast_assert(ao2_ref(obj, 0) > 1);
01219       }
01220       if (!obj && (class->count < class->limit) &&
01221             (time(NULL) > class->last_negative_connect.tv_sec + class->negative_connection_cache.tv_sec)) {
01222          obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
01223          if (!obj) {
01224             class->count--;
01225             ao2_ref(class, -1);
01226             ast_debug(3, "Unable to allocate object\n");
01227             return NULL;
01228          }
01229          ast_assert(ao2_ref(obj, 0) == 1);
01230          ast_mutex_init(&obj->lock);
01231          /* obj inherits the outstanding reference to class */
01232          obj->parent = class;
01233          class = NULL;
01234          if (odbc_obj_connect(obj) == ODBC_FAIL) {
01235             ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
01236             ao2_ref(obj, -1);
01237             ast_assert(ao2_ref(class, 0) > 0);
01238             obj = NULL;
01239          } else {
01240             obj->used = 1;
01241             ao2_link(obj->parent->obj_container, obj);
01242             ast_atomic_fetchadd_int(&obj->parent->count, +1);
01243          }
01244       } else {
01245          /* Object is not constructed, so delete outstanding reference to class. */
01246          ao2_ref(class, -1);
01247          class = NULL;
01248       }
01249 
01250       if (obj && ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
01251          /* Ensure this connection has autocommit turned off. */
01252          if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
01253             SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01254             for (i = 0; i < numfields; i++) {
01255                SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01256                ast_log(LOG_WARNING, "SQLSetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
01257                if (i > 10) {
01258                   ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01259                   break;
01260                }
01261             }
01262          }
01263       }
01264    } else if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
01265       /* Non-pooled connections -- but must use a separate connection handle */
01266       if (!(obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, USE_TX))) {
01267          ast_debug(1, "Object not found\n");
01268          obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
01269          if (!obj) {
01270             ao2_ref(class, -1);
01271             ast_debug(3, "Unable to allocate object\n");
01272             return NULL;
01273          }
01274          ast_mutex_init(&obj->lock);
01275          /* obj inherits the outstanding reference to class */
01276          obj->parent = class;
01277          class = NULL;
01278          if (odbc_obj_connect(obj) == ODBC_FAIL) {
01279             ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
01280             ao2_ref(obj, -1);
01281             obj = NULL;
01282          } else {
01283             obj->used = 1;
01284             ao2_link(obj->parent->obj_container, obj);
01285             ast_atomic_fetchadd_int(&obj->parent->count, +1);
01286          }
01287       }
01288 
01289       if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
01290          SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01291          for (i = 0; i < numfields; i++) {
01292             SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01293             ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
01294             if (i > 10) {
01295                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01296                break;
01297             }
01298          }
01299       }
01300    } else {
01301       /* Non-pooled connection: multiple modules can use the same connection. */
01302       if ((obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, NO_TX))) {
01303          /* Object is not constructed, so delete outstanding reference to class. */
01304          ast_assert(ao2_ref(class, 0) > 1);
01305          ao2_ref(class, -1);
01306          class = NULL;
01307       } else {
01308          /* No entry: build one */
01309          if (!(obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor))) {
01310             ast_assert(ao2_ref(class, 0) > 1);
01311             ao2_ref(class, -1);
01312             ast_debug(3, "Unable to allocate object\n");
01313             return NULL;
01314          }
01315          ast_mutex_init(&obj->lock);
01316          /* obj inherits the outstanding reference to class */
01317          obj->parent = class;
01318          class = NULL;
01319          if (odbc_obj_connect(obj) == ODBC_FAIL) {
01320             ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
01321             ao2_ref(obj, -1);
01322             obj = NULL;
01323          } else {
01324             ao2_link(obj->parent->obj_container, obj);
01325             ast_assert(ao2_ref(obj, 0) > 1);
01326          }
01327       }
01328 
01329       if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
01330          SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01331          for (i = 0; i < numfields; i++) {
01332             SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01333             ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
01334             if (i > 10) {
01335                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01336                break;
01337             }
01338          }
01339       }
01340    }
01341 
01342    /* Set the isolation property */
01343    if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)obj->parent->isolation, 0) == SQL_ERROR) {
01344       SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01345       for (i = 0; i < numfields; i++) {
01346          SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01347          ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
01348          if (i > 10) {
01349             ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01350             break;
01351          }
01352       }
01353    }
01354 
01355    if (obj && ast_test_flag(&flags, RES_ODBC_CONNECTED) && !obj->up) {
01356       /* Check if this connection qualifies for reconnection, with negative connection cache time */
01357       if (time(NULL) > class->last_negative_connect.tv_sec + class->negative_connection_cache.tv_sec) {
01358          odbc_obj_connect(obj);
01359       }
01360    } else if (obj && ast_test_flag(&flags, RES_ODBC_SANITY_CHECK)) {
01361       ast_odbc_sanity_check(obj);
01362    } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck) {
01363       odbc_obj_connect(obj);
01364    }
01365 
01366 #ifdef DEBUG_THREADS
01367    if (obj) {
01368       ast_copy_string(obj->file, file, sizeof(obj->file));
01369       ast_copy_string(obj->function, function, sizeof(obj->function));
01370       obj->lineno = lineno;
01371    }
01372 #endif
01373    ast_assert(class == NULL);
01374 
01375    if (obj) {
01376       ast_assert(ao2_ref(obj, 0) > 1);
01377    }
01378    return obj;
01379 }
01380 
01381 struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
01382 {
01383    struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
01384    return _ast_odbc_request_obj2(name, flags, file, function, lineno);
01385 }
01386 
01387 struct odbc_obj *ast_odbc_retrieve_transaction_obj(struct ast_channel *chan, const char *objname)
01388 {
01389    struct ast_datastore *txn_store;
01390    AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
01391    struct odbc_txn_frame *txn = NULL;
01392 
01393    if (!chan) {
01394       /* No channel == no transaction */
01395       return NULL;
01396    }
01397 
01398    ast_channel_lock(chan);
01399    if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
01400       oldlist = txn_store->data;
01401    } else {
01402       ast_channel_unlock(chan);
01403       return NULL;
01404    }
01405 
01406    AST_LIST_LOCK(oldlist);
01407    ast_channel_unlock(chan);
01408 
01409    AST_LIST_TRAVERSE(oldlist, txn, list) {
01410       if (txn->obj && txn->obj->parent && !strcmp(txn->obj->parent->name, objname)) {
01411          AST_LIST_UNLOCK(oldlist);
01412          return txn->obj;
01413       }
01414    }
01415    AST_LIST_UNLOCK(oldlist);
01416    return NULL;
01417 }
01418 
01419 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
01420 {
01421    int res;
01422    SQLINTEGER err;
01423    short int mlen;
01424    unsigned char msg[200], state[10];
01425 
01426    /* Nothing to disconnect */
01427    if (!obj->con) {
01428       return ODBC_SUCCESS;
01429    }
01430 
01431    ast_mutex_lock(&obj->lock);
01432 
01433    res = SQLDisconnect(obj->con);
01434 
01435    if (obj->parent) {
01436       if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
01437          ast_log(LOG_DEBUG, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
01438       } else {
01439          ast_log(LOG_DEBUG, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
01440       }
01441    }
01442 
01443    if ((res = SQLFreeHandle(SQL_HANDLE_DBC, obj->con) == SQL_SUCCESS)) {
01444       obj->con = NULL;
01445       ast_log(LOG_DEBUG, "Database handle deallocated\n");
01446    } else {
01447       SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
01448       ast_log(LOG_WARNING, "Unable to deallocate database handle? %d errno=%d %s\n", res, (int)err, msg);
01449    }
01450 
01451    obj->up = 0;
01452    ast_mutex_unlock(&obj->lock);
01453    return ODBC_SUCCESS;
01454 }
01455 
01456 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
01457 {
01458    int res;
01459    SQLINTEGER err;
01460    short int mlen;
01461    unsigned char msg[200], state[10];
01462 #ifdef NEEDTRACE
01463    SQLINTEGER enable = 1;
01464    char *tracefile = "/tmp/odbc.trace";
01465 #endif
01466    ast_mutex_lock(&obj->lock);
01467 
01468    if (obj->up) {
01469       odbc_obj_disconnect(obj);
01470       ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
01471    } else {
01472       ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
01473    }
01474 
01475    res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
01476 
01477    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
01478       ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
01479       obj->parent->last_negative_connect = ast_tvnow();
01480       ast_mutex_unlock(&obj->lock);
01481       return ODBC_FAIL;
01482    }
01483    SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
01484    SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
01485 #ifdef NEEDTRACE
01486    SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
01487    SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
01488 #endif
01489 
01490    res = SQLConnect(obj->con,
01491          (SQLCHAR *) obj->parent->dsn, SQL_NTS,
01492          (SQLCHAR *) obj->parent->username, SQL_NTS,
01493          (SQLCHAR *) obj->parent->password, SQL_NTS);
01494 
01495    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
01496       SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
01497       obj->parent->last_negative_connect = ast_tvnow();
01498       ast_mutex_unlock(&obj->lock);
01499       ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
01500       return ODBC_FAIL;
01501    } else {
01502       ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
01503       obj->up = 1;
01504       obj->last_used = ast_tvnow();
01505    }
01506 
01507    ast_mutex_unlock(&obj->lock);
01508    return ODBC_SUCCESS;
01509 }
01510 
01511 static int acf_transaction_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
01512 {
01513    AST_DECLARE_APP_ARGS(args,
01514       AST_APP_ARG(property);
01515       AST_APP_ARG(opt);
01516    );
01517    struct odbc_txn_frame *tx;
01518 
01519    AST_STANDARD_APP_ARGS(args, data);
01520    if (strcasecmp(args.property, "transaction") == 0) {
01521       if ((tx = find_transaction(chan, NULL, NULL, 1))) {
01522          ast_copy_string(buf, tx->name, len);
01523          return 0;
01524       }
01525    } else if (strcasecmp(args.property, "isolation") == 0) {
01526       if (!ast_strlen_zero(args.opt)) {
01527          tx = find_transaction(chan, NULL, args.opt, 0);
01528       } else {
01529          tx = find_transaction(chan, NULL, NULL, 1);
01530       }
01531       if (tx) {
01532          ast_copy_string(buf, isolation2text(tx->isolation), len);
01533          return 0;
01534       }
01535    } else if (strcasecmp(args.property, "forcecommit") == 0) {
01536       if (!ast_strlen_zero(args.opt)) {
01537          tx = find_transaction(chan, NULL, args.opt, 0);
01538       } else {
01539          tx = find_transaction(chan, NULL, NULL, 1);
01540       }
01541       if (tx) {
01542          ast_copy_string(buf, tx->forcecommit ? "1" : "0", len);
01543          return 0;
01544       }
01545    }
01546    return -1;
01547 }
01548 
01549 static int acf_transaction_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
01550 {
01551    AST_DECLARE_APP_ARGS(args,
01552       AST_APP_ARG(property);
01553       AST_APP_ARG(opt);
01554    );
01555    struct odbc_txn_frame *tx;
01556    SQLINTEGER nativeerror=0, numfields=0;
01557    SQLSMALLINT diagbytes=0, i;
01558    unsigned char state[10], diagnostic[256];
01559 
01560    AST_STANDARD_APP_ARGS(args, s);
01561    if (strcasecmp(args.property, "transaction") == 0) {
01562       /* Set active transaction */
01563       struct odbc_obj *obj;
01564       if ((tx = find_transaction(chan, NULL, value, 0))) {
01565          mark_transaction_active(chan, tx);
01566       } else {
01567          /* No such transaction, create one */
01568          struct ast_flags flags = { RES_ODBC_INDEPENDENT_CONNECTION };
01569          if (ast_strlen_zero(args.opt) || !(obj = ast_odbc_request_obj2(args.opt, flags))) {
01570             ast_log(LOG_ERROR, "Could not create transaction: invalid database specification '%s'\n", S_OR(args.opt, ""));
01571             pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_DB");
01572             return -1;
01573          }
01574          if (!(tx = find_transaction(chan, obj, value, 0))) {
01575             pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
01576             return -1;
01577          }
01578          obj->tx = 1;
01579       }
01580       pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
01581       return 0;
01582    } else if (strcasecmp(args.property, "forcecommit") == 0) {
01583       /* Set what happens when an uncommitted transaction ends without explicit Commit or Rollback */
01584       if (ast_strlen_zero(args.opt)) {
01585          tx = find_transaction(chan, NULL, NULL, 1);
01586       } else {
01587          tx = find_transaction(chan, NULL, args.opt, 0);
01588       }
01589       if (!tx) {
01590          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
01591          return -1;
01592       }
01593       if (ast_true(value)) {
01594          tx->forcecommit = 1;
01595       } else if (ast_false(value)) {
01596          tx->forcecommit = 0;
01597       } else {
01598          ast_log(LOG_ERROR, "Invalid value for forcecommit: '%s'\n", S_OR(value, ""));
01599          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
01600          return -1;
01601       }
01602 
01603       pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
01604       return 0;
01605    } else if (strcasecmp(args.property, "isolation") == 0) {
01606       /* How do uncommitted transactions affect reads? */
01607       int isolation = text2isolation(value);
01608       if (ast_strlen_zero(args.opt)) {
01609          tx = find_transaction(chan, NULL, NULL, 1);
01610       } else {
01611          tx = find_transaction(chan, NULL, args.opt, 0);
01612       }
01613       if (!tx) {
01614          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
01615          return -1;
01616       }
01617       if (isolation == 0) {
01618          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
01619          ast_log(LOG_ERROR, "Invalid isolation specification: '%s'\n", S_OR(value, ""));
01620       } else if (SQLSetConnectAttr(tx->obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)isolation, 0) == SQL_ERROR) {
01621          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "SQL_ERROR");
01622          SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01623          for (i = 0; i < numfields; i++) {
01624             SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01625             ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
01626             if (i > 10) {
01627                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01628                break;
01629             }
01630          }
01631       } else {
01632          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
01633          tx->isolation = isolation;
01634       }
01635       return 0;
01636    } else {
01637       ast_log(LOG_ERROR, "Unknown property: '%s'\n", args.property);
01638       return -1;
01639    }
01640 }
01641 
01642 static struct ast_custom_function odbc_function = {
01643    .name = "ODBC",
01644    .read = acf_transaction_read,
01645    .write = acf_transaction_write,
01646 };
01647 
01648 static const char * const app_commit = "ODBC_Commit";
01649 static const char * const app_rollback = "ODBC_Rollback";
01650 
01651 /*!
01652  * \internal
01653  * \brief Implements the channels provider.
01654  */
01655 static int data_odbc_provider_handler(const struct ast_data_search *search,
01656       struct ast_data *root)
01657 {
01658    struct ao2_iterator aoi, aoi2;
01659    struct odbc_class *class;
01660    struct odbc_obj *current;
01661    struct ast_data *data_odbc_class, *data_odbc_connections, *data_odbc_connection;
01662    struct ast_data *enum_node;
01663    int count;
01664 
01665    aoi = ao2_iterator_init(class_container, 0);
01666    while ((class = ao2_iterator_next(&aoi))) {
01667       data_odbc_class = ast_data_add_node(root, "class");
01668       if (!data_odbc_class) {
01669          ao2_ref(class, -1);
01670          continue;
01671       }
01672 
01673       ast_data_add_structure(odbc_class, data_odbc_class, class);
01674 
01675       if (!ao2_container_count(class->obj_container)) {
01676          ao2_ref(class, -1);
01677          continue;
01678       }
01679 
01680       data_odbc_connections = ast_data_add_node(data_odbc_class, "connections");
01681       if (!data_odbc_connections) {
01682          ao2_ref(class, -1);
01683          continue;
01684       }
01685 
01686       ast_data_add_bool(data_odbc_class, "shared", !class->haspool);
01687       /* isolation */
01688       enum_node = ast_data_add_node(data_odbc_class, "isolation");
01689       if (!enum_node) {
01690          ao2_ref(class, -1);
01691          continue;
01692       }
01693       ast_data_add_int(enum_node, "value", class->isolation);
01694       ast_data_add_str(enum_node, "text", isolation2text(class->isolation));
01695 
01696       count = 0;
01697       aoi2 = ao2_iterator_init(class->obj_container, 0);
01698       while ((current = ao2_iterator_next(&aoi2))) {
01699          data_odbc_connection = ast_data_add_node(data_odbc_connections, "connection");
01700          if (!data_odbc_connection) {
01701             ao2_ref(current, -1);
01702             continue;
01703          }
01704 
01705          ast_mutex_lock(&current->lock);
01706          ast_data_add_str(data_odbc_connection, "status", current->used ? "in use" :
01707                current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
01708          ast_data_add_bool(data_odbc_connection, "transactional", current->tx);
01709          ast_mutex_unlock(&current->lock);
01710 
01711          if (class->haspool) {
01712             ast_data_add_int(data_odbc_connection, "number", ++count);
01713          }
01714 
01715          ao2_ref(current, -1);
01716       }
01717       ao2_ref(class, -1);
01718 
01719       if (!ast_data_search_match(search, data_odbc_class)) {
01720          ast_data_remove_node(root, data_odbc_class);
01721       }
01722    }
01723    return 0;
01724 }
01725 
01726 /*!
01727  * \internal
01728  * \brief /asterisk/res/odbc/listprovider.
01729  */
01730 static const struct ast_data_handler odbc_provider = {
01731    .version = AST_DATA_HANDLER_VERSION,
01732    .get = data_odbc_provider_handler
01733 };
01734 
01735 static const struct ast_data_entry odbc_providers[] = {
01736    AST_DATA_ENTRY("/asterisk/res/odbc", &odbc_provider),
01737 };
01738 
01739 static int reload(void)
01740 {
01741    struct odbc_cache_tables *table;
01742    struct odbc_class *class;
01743    struct odbc_obj *current;
01744    struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
01745 
01746    /* First, mark all to be purged */
01747    while ((class = ao2_iterator_next(&aoi))) {
01748       class->delme = 1;
01749       ao2_ref(class, -1);
01750    }
01751    ao2_iterator_destroy(&aoi);
01752 
01753    load_odbc_config();
01754 
01755    /* Purge remaining classes */
01756 
01757    /* Note on how this works; this is a case of circular references, so we
01758     * explicitly do NOT want to use a callback here (or we wind up in
01759     * recursive hell).
01760     *
01761     * 1. Iterate through all the classes.  Note that the classes will currently
01762     * contain two classes of the same name, one of which is marked delme and
01763     * will be purged when all remaining objects of the class are released, and
01764     * the other, which was created above when we re-parsed the config file.
01765     * 2. On each class, there is a reference held by the master container and
01766     * a reference held by each connection object.  There are two cases for
01767     * destruction of the class, noted below.  However, in all cases, all O-refs
01768     * (references to objects) will first be freed, which will cause the C-refs
01769     * (references to classes) to be decremented (but never to 0, because the
01770     * class container still has a reference).
01771     *    a) If the class has outstanding objects, the C-ref by the class
01772     *    container will then be freed, which leaves only C-refs by any
01773     *    outstanding objects.  When the final outstanding object is released
01774     *    (O-refs held by applications and dialplan functions), it will in turn
01775     *    free the final C-ref, causing class destruction.
01776     *    b) If the class has no outstanding objects, when the class container
01777     *    removes the final C-ref, the class will be destroyed.
01778     */
01779    aoi = ao2_iterator_init(class_container, 0);
01780    while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
01781       if (class->delme) {
01782          struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
01783          while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
01784             ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
01785             ao2_ref(current, -1); /* O-ref-- (by iterator) */
01786             /* At this point, either
01787              * a) there's an outstanding O-ref, or
01788              * b) the object has already been destroyed.
01789              */
01790          }
01791          ao2_iterator_destroy(&aoi2);
01792          ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
01793          /* At this point, either
01794           * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
01795           * b) the last remaining C-ref is held by the iterator, which will be
01796           * destroyed in the next step.
01797           */
01798       }
01799       ao2_ref(class, -1); /* C-ref-- (by iterator) */
01800    }
01801    ao2_iterator_destroy(&aoi);
01802 
01803    /* Empty the cache; it will get rebuilt the next time the tables are needed. */
01804    AST_RWLIST_WRLOCK(&odbc_tables);
01805    while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
01806       destroy_table_cache(table);
01807    }
01808    AST_RWLIST_UNLOCK(&odbc_tables);
01809 
01810    return 0;
01811 }
01812 
01813 static int unload_module(void)
01814 {
01815    /* Prohibit unloading */
01816    return -1;
01817 }
01818 
01819 static int load_module(void)
01820 {
01821    if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
01822       return AST_MODULE_LOAD_DECLINE;
01823    if (load_odbc_config() == -1)
01824       return AST_MODULE_LOAD_DECLINE;
01825    ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
01826    ast_data_register_multiple(odbc_providers, ARRAY_LEN(odbc_providers));
01827    ast_register_application_xml(app_commit, commit_exec);
01828    ast_register_application_xml(app_rollback, rollback_exec);
01829    ast_custom_function_register(&odbc_function);
01830    ast_log(LOG_NOTICE, "res_odbc loaded.\n");
01831    return 0;
01832 }
01833 
01834 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "ODBC resource",
01835       .load = load_module,
01836       .unload = unload_module,
01837       .reload = reload,
01838       .load_pri = AST_MODPRI_REALTIME_DEPEND,
01839           );

Generated on Sat Mar 26 11:08:10 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9