Resolve FORWARD_NULL static analysis warnings
[asterisk/asterisk.git] / res / res_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2012, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * res_odbc.c <ODBC resource manager>
9  * Copyright (C) 2004 - 2005 Anthony Minessale II <anthmct@yahoo.com>
10  *
11  * See http://www.asterisk.org for more information about
12  * the Asterisk project. Please do not directly contact
13  * any of the maintainers of this project for assistance;
14  * the project provides a web site, mailing lists and IRC
15  * channels for your use.
16  *
17  * This program is free software, distributed under the terms of
18  * the GNU General Public License Version 2. See the LICENSE file
19  * at the top of the source tree.
20  */
21
22 /*! \file
23  *
24  * \brief ODBC resource manager
25  * 
26  * \author Mark Spencer <markster@digium.com>
27  * \author Anthony Minessale II <anthmct@yahoo.com>
28  * \author Tilghman Lesher <tilghman@digium.com>
29  *
30  * \arg See also: \ref cdr_odbc
31  */
32
33 /*** MODULEINFO
34         <depend>generic_odbc</depend>
35         <depend>ltdl</depend>
36         <support_level>core</support_level>
37  ***/
38
39 #include "asterisk.h"
40
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42
43 #include "asterisk/file.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/config.h"
46 #include "asterisk/pbx.h"
47 #include "asterisk/module.h"
48 #include "asterisk/cli.h"
49 #include "asterisk/lock.h"
50 #include "asterisk/res_odbc.h"
51 #include "asterisk/time.h"
52 #include "asterisk/astobj2.h"
53 #include "asterisk/app.h"
54 #include "asterisk/strings.h"
55 #include "asterisk/threadstorage.h"
56 #include "asterisk/data.h"
57
58 /*** DOCUMENTATION
59         <function name="ODBC" language="en_US">
60                 <synopsis>
61                         Controls ODBC transaction properties.
62                 </synopsis>
63                 <syntax>
64                         <parameter name="property" required="true">
65                                 <enumlist>
66                                         <enum name="transaction">
67                                                 <para>Gets or sets the active transaction ID.  If set, and the transaction ID does not
68                                                 exist and a <replaceable>database name</replaceable> is specified as an argument, it will be created.</para>
69                                         </enum>
70                                         <enum name="forcecommit">
71                                                 <para>Controls whether a transaction will be automatically committed when the channel
72                                                 hangs up.  Defaults to false.  If a <replaceable>transaction ID</replaceable> is specified in the optional argument,
73                                                 the property will be applied to that ID, otherwise to the current active ID.</para>
74                                         </enum>
75                                         <enum name="isolation">
76                                                 <para>Controls the data isolation on uncommitted transactions.  May be one of the
77                                                 following: <literal>read_committed</literal>, <literal>read_uncommitted</literal>,
78                                                 <literal>repeatable_read</literal>, or <literal>serializable</literal>.  Defaults to the
79                                                 database setting in <filename>res_odbc.conf</filename> or <literal>read_committed</literal>
80                                                 if not specified.  If a <replaceable>transaction ID</replaceable> is specified as an optional argument, it will be
81                                                 applied to that ID, otherwise the current active ID.</para>
82                                         </enum>
83                                 </enumlist>
84                         </parameter>
85                         <parameter name="argument" required="false" />
86                 </syntax>
87                 <description>
88                         <para>The ODBC() function allows setting several properties to influence how a connected
89                         database processes transactions.</para>
90                 </description>
91         </function>
92         <application name="ODBC_Commit" language="en_US">
93                 <synopsis>
94                         Commits a currently open database transaction.
95                 </synopsis>
96                 <syntax>
97                         <parameter name="transaction ID" required="no" />
98                 </syntax>
99                 <description>
100                         <para>Commits the database transaction specified by <replaceable>transaction ID</replaceable>
101                         or the current active transaction, if not specified.</para>
102                 </description>
103         </application>
104         <application name="ODBC_Rollback" language="en_US">
105                 <synopsis>
106                         Rollback a currently open database transaction.
107                 </synopsis>
108                 <syntax>
109                         <parameter name="transaction ID" required="no" />
110                 </syntax>
111                 <description>
112                         <para>Rolls back the database transaction specified by <replaceable>transaction ID</replaceable>
113                         or the current active transaction, if not specified.</para>
114                 </description>
115         </application>
116  ***/
117
118 struct odbc_class
119 {
120         AST_LIST_ENTRY(odbc_class) list;
121         char name[80];
122         char dsn[80];
123         char *username;
124         char *password;
125         char *sanitysql;
126         SQLHENV env;
127         unsigned int haspool:1;              /*!< Boolean - TDS databases need this */
128         unsigned int delme:1;                /*!< Purge the class */
129         unsigned int backslash_is_escape:1;  /*!< On this database, the backslash is a native escape sequence */
130         unsigned int forcecommit:1;          /*!< Should uncommitted transactions be auto-committed on handle release? */
131         unsigned int isolation;              /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
132         unsigned int limit;                  /*!< Maximum number of database handles we will allow */
133         int count;                           /*!< Running count of pooled connections */
134         unsigned int idlecheck;              /*!< Recheck the connection if it is idle for this long (in seconds) */
135         unsigned int conntimeout;            /*!< Maximum time the connection process should take */
136         /*! When a connection fails, cache that failure for how long? */
137         struct timeval negative_connection_cache;
138         /*! When a connection fails, when did that last occur? */
139         struct timeval last_negative_connect;
140         /*! List of handles associated with this class */
141         struct ao2_container *obj_container;
142 };
143
144 static struct ao2_container *class_container;
145
146 static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
147
148 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
149 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
150 static int odbc_register_class(struct odbc_class *class, int connect);
151 static void odbc_txn_free(void *data);
152 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx);
153
154 AST_THREADSTORAGE(errors_buf);
155
156 static struct ast_datastore_info txn_info = {
157         .type = "ODBC_Transaction",
158         .destroy = odbc_txn_free,
159 };
160
161 struct odbc_txn_frame {
162         AST_LIST_ENTRY(odbc_txn_frame) list;
163         struct ast_channel *owner;
164         struct odbc_obj *obj;        /*!< Database handle within which transacted statements are run */
165         /*!\brief Is this record the current active transaction within the channel?
166          * Note that the active flag is really only necessary for statements which
167          * are triggered from the dialplan, as there isn't a direct correlation
168          * between multiple statements.  Applications wishing to use transactions
169          * may simply perform each statement on the same odbc_obj, which keeps the
170          * transaction persistent.
171          */
172         unsigned int active:1;
173         unsigned int forcecommit:1;     /*!< Should uncommitted transactions be auto-committed on handle release? */
174         unsigned int isolation;         /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
175         char name[0];                   /*!< Name of this transaction ID */
176 };
177
178 #define DATA_EXPORT_ODBC_CLASS(MEMBER)                          \
179         MEMBER(odbc_class, name, AST_DATA_STRING)               \
180         MEMBER(odbc_class, dsn, AST_DATA_STRING)                \
181         MEMBER(odbc_class, username, AST_DATA_STRING)           \
182         MEMBER(odbc_class, password, AST_DATA_PASSWORD)         \
183         MEMBER(odbc_class, limit, AST_DATA_INTEGER)             \
184         MEMBER(odbc_class, count, AST_DATA_INTEGER)             \
185         MEMBER(odbc_class, forcecommit, AST_DATA_BOOLEAN)
186
187 AST_DATA_STRUCTURE(odbc_class, DATA_EXPORT_ODBC_CLASS);
188
189 static const char *isolation2text(int iso)
190 {
191         if (iso == SQL_TXN_READ_COMMITTED) {
192                 return "read_committed";
193         } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
194                 return "read_uncommitted";
195         } else if (iso == SQL_TXN_SERIALIZABLE) {
196                 return "serializable";
197         } else if (iso == SQL_TXN_REPEATABLE_READ) {
198                 return "repeatable_read";
199         } else {
200                 return "unknown";
201         }
202 }
203
204 static int text2isolation(const char *txt)
205 {
206         if (strncasecmp(txt, "read_", 5) == 0) {
207                 if (strncasecmp(txt + 5, "c", 1) == 0) {
208                         return SQL_TXN_READ_COMMITTED;
209                 } else if (strncasecmp(txt + 5, "u", 1) == 0) {
210                         return SQL_TXN_READ_UNCOMMITTED;
211                 } else {
212                         return 0;
213                 }
214         } else if (strncasecmp(txt, "ser", 3) == 0) {
215                 return SQL_TXN_SERIALIZABLE;
216         } else if (strncasecmp(txt, "rep", 3) == 0) {
217                 return SQL_TXN_REPEATABLE_READ;
218         } else {
219                 return 0;
220         }
221 }
222
223 static struct odbc_txn_frame *find_transaction(struct ast_channel *chan, struct odbc_obj *obj, const char *name, int active)
224 {
225         struct ast_datastore *txn_store;
226         AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
227         struct odbc_txn_frame *txn = NULL;
228
229         if (!chan && obj && obj->txf && obj->txf->owner) {
230                 chan = obj->txf->owner;
231         } else if (!chan) {
232                 /* No channel == no transaction */
233                 return NULL;
234         }
235
236         ast_channel_lock(chan);
237         if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
238                 oldlist = txn_store->data;
239         } else {
240                 /* Need to create a new datastore */
241                 if (!(txn_store = ast_datastore_alloc(&txn_info, NULL))) {
242                         ast_log(LOG_ERROR, "Unable to allocate a new datastore.  Cannot create a new transaction.\n");
243                         ast_channel_unlock(chan);
244                         return NULL;
245                 }
246
247                 if (!(oldlist = ast_calloc(1, sizeof(*oldlist)))) {
248                         ast_log(LOG_ERROR, "Unable to allocate datastore list head.  Cannot create a new transaction.\n");
249                         ast_datastore_free(txn_store);
250                         ast_channel_unlock(chan);
251                         return NULL;
252                 }
253
254                 txn_store->data = oldlist;
255                 AST_LIST_HEAD_INIT(oldlist);
256                 ast_channel_datastore_add(chan, txn_store);
257         }
258
259         AST_LIST_LOCK(oldlist);
260         ast_channel_unlock(chan);
261
262         /* Scanning for an object is *fast*.  Scanning for a name is much slower. */
263         if (obj != NULL || active == 1) {
264                 AST_LIST_TRAVERSE(oldlist, txn, list) {
265                         if (txn->obj == obj || txn->active) {
266                                 AST_LIST_UNLOCK(oldlist);
267                                 return txn;
268                         }
269                 }
270         }
271
272         if (name != NULL) {
273                 AST_LIST_TRAVERSE(oldlist, txn, list) {
274                         if (!strcasecmp(txn->name, name)) {
275                                 AST_LIST_UNLOCK(oldlist);
276                                 return txn;
277                         }
278                 }
279         }
280
281         /* Nothing found, create one */
282         if (name && obj && (txn = ast_calloc(1, sizeof(*txn) + strlen(name) + 1))) {
283                 struct odbc_txn_frame *otxn;
284
285                 strcpy(txn->name, name); /* SAFE */
286                 txn->obj = obj;
287                 txn->isolation = obj->parent->isolation;
288                 txn->forcecommit = obj->parent->forcecommit;
289                 txn->owner = chan;
290                 txn->active = 1;
291
292                 /* On creation, the txn becomes active, and all others inactive */
293                 AST_LIST_TRAVERSE(oldlist, otxn, list) {
294                         otxn->active = 0;
295                 }
296                 AST_LIST_INSERT_TAIL(oldlist, txn, list);
297
298                 obj->txf = txn;
299                 obj->tx = 1;
300         }
301         AST_LIST_UNLOCK(oldlist);
302
303         return txn;
304 }
305
306 static struct odbc_txn_frame *release_transaction(struct odbc_txn_frame *tx)
307 {
308         if (!tx) {
309                 return NULL;
310         }
311
312         ast_debug(2, "release_transaction(%p) called (tx->obj = %p, tx->obj->txf = %p)\n", tx, tx->obj, tx->obj ? tx->obj->txf : NULL);
313
314         /* If we have an owner, disassociate */
315         if (tx->owner) {
316                 struct ast_datastore *txn_store;
317                 AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
318
319                 ast_channel_lock(tx->owner);
320                 if ((txn_store = ast_channel_datastore_find(tx->owner, &txn_info, NULL))) {
321                         oldlist = txn_store->data;
322                         AST_LIST_LOCK(oldlist);
323                         AST_LIST_REMOVE(oldlist, tx, list);
324                         AST_LIST_UNLOCK(oldlist);
325                 }
326                 ast_channel_unlock(tx->owner);
327                 tx->owner = NULL;
328         }
329
330         if (tx->obj) {
331                 /* If we have any uncommitted transactions, they are handled when we release the object */
332                 struct odbc_obj *obj = tx->obj;
333                 /* Prevent recursion during destruction */
334                 tx->obj->txf = NULL;
335                 tx->obj = NULL;
336                 odbc_release_obj2(obj, tx);
337         }
338         ast_free(tx);
339         return NULL;
340 }
341
342 static void odbc_txn_free(void *vdata)
343 {
344         struct odbc_txn_frame *tx;
345         AST_LIST_HEAD(, odbc_txn_frame) *oldlist = vdata;
346
347         ast_debug(2, "odbc_txn_free(%p) called\n", vdata);
348
349         AST_LIST_LOCK(oldlist);
350         while ((tx = AST_LIST_REMOVE_HEAD(oldlist, list))) {
351                 release_transaction(tx);
352         }
353         AST_LIST_UNLOCK(oldlist);
354         AST_LIST_HEAD_DESTROY(oldlist);
355         ast_free(oldlist);
356 }
357
358 static int mark_transaction_active(struct ast_channel *chan, struct odbc_txn_frame *tx)
359 {
360         struct ast_datastore *txn_store;
361         AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
362         struct odbc_txn_frame *active = NULL, *txn;
363
364         if (!chan && tx && tx->owner) {
365                 chan = tx->owner;
366         }
367
368         if (!chan) {
369                 return -1;
370         }
371
372         ast_channel_lock(chan);
373         if (!(txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
374                 ast_channel_unlock(chan);
375                 return -1;
376         }
377
378         oldlist = txn_store->data;
379         AST_LIST_LOCK(oldlist);
380         AST_LIST_TRAVERSE(oldlist, txn, list) {
381                 if (txn == tx) {
382                         txn->active = 1;
383                         active = txn;
384                 } else {
385                         txn->active = 0;
386                 }
387         }
388         AST_LIST_UNLOCK(oldlist);
389         ast_channel_unlock(chan);
390         return active ? 0 : -1;
391 }
392
393 static void odbc_class_destructor(void *data)
394 {
395         struct odbc_class *class = data;
396         /* Due to refcounts, we can safely assume that any objects with a reference
397          * to us will prevent our destruction, so we don't need to worry about them.
398          */
399         if (class->username) {
400                 ast_free(class->username);
401         }
402         if (class->password) {
403                 ast_free(class->password);
404         }
405         if (class->sanitysql) {
406                 ast_free(class->sanitysql);
407         }
408         ao2_ref(class->obj_container, -1);
409         SQLFreeHandle(SQL_HANDLE_ENV, class->env);
410 }
411
412 static int null_hash_fn(const void *obj, const int flags)
413 {
414         return 0;
415 }
416
417 static void odbc_obj_destructor(void *data)
418 {
419         struct odbc_obj *obj = data;
420         struct odbc_class *class = obj->parent;
421         obj->parent = NULL;
422         odbc_obj_disconnect(obj);
423         ao2_ref(class, -1);
424 }
425
426 static void destroy_table_cache(struct odbc_cache_tables *table) {
427         struct odbc_cache_columns *col;
428         ast_debug(1, "Destroying table cache for %s\n", table->table);
429         AST_RWLIST_WRLOCK(&table->columns);
430         while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
431                 ast_free(col);
432         }
433         AST_RWLIST_UNLOCK(&table->columns);
434         AST_RWLIST_HEAD_DESTROY(&table->columns);
435         ast_free(table);
436 }
437
438 /*!
439  * \brief Find or create an entry describing the table specified.
440  * \param database Name of an ODBC class on which to query the table
441  * \param tablename Tablename to describe
442  * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
443  * When a structure is returned, the contained columns list will be
444  * rdlock'ed, to ensure that it will be retained in memory.
445  * \since 1.6.1
446  */
447 struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
448 {
449         struct odbc_cache_tables *tableptr;
450         struct odbc_cache_columns *entry;
451         char columnname[80];
452         SQLLEN sqlptr;
453         SQLHSTMT stmt = NULL;
454         int res = 0, error = 0, try = 0;
455         struct odbc_obj *obj = ast_odbc_request_obj(database, 0);
456
457         AST_RWLIST_RDLOCK(&odbc_tables);
458         AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
459                 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
460                         break;
461                 }
462         }
463         if (tableptr) {
464                 AST_RWLIST_RDLOCK(&tableptr->columns);
465                 AST_RWLIST_UNLOCK(&odbc_tables);
466                 if (obj) {
467                         ast_odbc_release_obj(obj);
468                 }
469                 return tableptr;
470         }
471
472         if (!obj) {
473                 ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
474                 AST_RWLIST_UNLOCK(&odbc_tables);
475                 return NULL;
476         }
477
478         /* Table structure not already cached; build it now. */
479         ao2_lock(obj);
480         do {
481                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
482                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
483                         if (try == 0) {
484                                 try = 1;
485                                 ast_odbc_sanity_check(obj);
486                                 continue;
487                         }
488                         ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
489                         break;
490                 }
491
492                 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
493                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
494                         if (try == 0) {
495                                 try = 1;
496                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
497                                 ast_odbc_sanity_check(obj);
498                                 continue;
499                         }
500                         ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
501                         break;
502                 }
503
504                 if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
505                         ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
506                         break;
507                 }
508
509                 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
510                 tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
511                 strcpy(tableptr->connection, database); /* SAFE */
512                 strcpy(tableptr->table, tablename); /* SAFE */
513                 AST_RWLIST_HEAD_INIT(&(tableptr->columns));
514
515                 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
516                         SQLGetData(stmt,  4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
517
518                         if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
519                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
520                                 error = 1;
521                                 break;
522                         }
523                         entry->name = (char *)entry + sizeof(*entry);
524                         strcpy(entry->name, columnname);
525
526                         SQLGetData(stmt,  5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
527                         SQLGetData(stmt,  7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
528                         SQLGetData(stmt,  9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
529                         SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
530                         SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
531                         SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
532
533                         /* Specification states that the octenlen should be the maximum number of bytes
534                          * returned in a char or binary column, but it seems that some drivers just set
535                          * it to NULL. (Bad Postgres! No biscuit!) */
536                         if (entry->octetlen == 0) {
537                                 entry->octetlen = entry->size;
538                         }
539
540                         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);
541                         /* Insert column info into column list */
542                         AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
543                 }
544                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
545
546                 AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
547                 AST_RWLIST_RDLOCK(&(tableptr->columns));
548                 break;
549         } while (1);
550         ao2_unlock(obj);
551
552         AST_RWLIST_UNLOCK(&odbc_tables);
553
554         if (error) {
555                 destroy_table_cache(tableptr);
556                 tableptr = NULL;
557         }
558         if (obj) {
559                 ast_odbc_release_obj(obj);
560         }
561         return tableptr;
562 }
563
564 struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
565 {
566         struct odbc_cache_columns *col;
567         AST_RWLIST_TRAVERSE(&table->columns, col, list) {
568                 if (strcasecmp(col->name, colname) == 0) {
569                         return col;
570                 }
571         }
572         return NULL;
573 }
574
575 int ast_odbc_clear_cache(const char *database, const char *tablename)
576 {
577         struct odbc_cache_tables *tableptr;
578
579         AST_RWLIST_WRLOCK(&odbc_tables);
580         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
581                 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
582                         AST_LIST_REMOVE_CURRENT(list);
583                         destroy_table_cache(tableptr);
584                         break;
585                 }
586         }
587         AST_RWLIST_TRAVERSE_SAFE_END
588         AST_RWLIST_UNLOCK(&odbc_tables);
589         return tableptr ? 0 : -1;
590 }
591
592 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
593 {
594         int attempt;
595         SQLHSTMT stmt;
596
597         ao2_lock(obj);
598
599         for (attempt = 0; attempt < 2; attempt++) {
600                 stmt = exec_cb(obj, data);
601
602                 if (stmt) {
603                         break;
604                 } else if (obj->tx) {
605                         ast_log(LOG_WARNING, "Failed to execute, but unable to reconnect, as we're transactional.\n");
606                         break;
607                 } else if (attempt == 0) {
608                         ast_log(LOG_WARNING, "SQL Execute error! Verifying connection to %s [%s]...\n", obj->parent->name, obj->parent->dsn);
609                 }
610                 if (!ast_odbc_sanity_check(obj)) {
611                         break;
612                 }
613         }
614
615         ao2_unlock(obj);
616
617         return stmt;
618 }
619
620 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
621 {
622         int res = 0, i, attempt;
623         SQLINTEGER nativeerror=0, numfields=0;
624         SQLSMALLINT diagbytes=0;
625         unsigned char state[10], diagnostic[256];
626         SQLHSTMT stmt;
627
628         ao2_lock(obj);
629
630         for (attempt = 0; attempt < 2; attempt++) {
631                 /* This prepare callback may do more than just prepare -- it may also
632                  * bind parameters, bind results, etc.  The real key, here, is that
633                  * when we disconnect, all handles become invalid for most databases.
634                  * We must therefore redo everything when we establish a new
635                  * connection. */
636                 stmt = prepare_cb(obj, data);
637
638                 if (stmt) {
639                         res = SQLExecute(stmt);
640                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
641                                 if (res == SQL_ERROR) {
642                                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
643                                         for (i = 0; i < numfields; i++) {
644                                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
645                                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
646                                                 if (i > 10) {
647                                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
648                                                         break;
649                                                 }
650                                         }
651                                 }
652
653                                 if (obj->tx) {
654                                         ast_log(LOG_WARNING, "SQL Execute error, but unable to reconnect, as we're transactional.\n");
655                                         break;
656                                 } else {
657                                         ast_log(LOG_WARNING, "SQL Execute error %d! Verifying connection to %s [%s]...\n", res, obj->parent->name, obj->parent->dsn);
658                                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
659                                         stmt = NULL;
660
661                                         obj->up = 0;
662                                         /*
663                                          * While this isn't the best way to try to correct an error, this won't automatically
664                                          * fail when the statement handle invalidates.
665                                          */
666                                         if (!ast_odbc_sanity_check(obj)) {
667                                                 break;
668                                         }
669                                         continue;
670                                 }
671                         } else {
672                                 obj->last_used = ast_tvnow();
673                         }
674                         break;
675                 } else if (attempt == 0) {
676                         ast_odbc_sanity_check(obj);
677                 }
678         }
679
680         ao2_unlock(obj);
681
682         return stmt;
683 }
684
685 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
686 {
687         int res = 0, i;
688         SQLINTEGER nativeerror=0, numfields=0;
689         SQLSMALLINT diagbytes=0;
690         unsigned char state[10], diagnostic[256];
691
692         ao2_lock(obj);
693
694         res = SQLExecute(stmt);
695         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
696                 if (res == SQL_ERROR) {
697                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
698                         for (i = 0; i < numfields; i++) {
699                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
700                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
701                                 if (i > 10) {
702                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
703                                         break;
704                                 }
705                         }
706                 }
707         } else {
708                 obj->last_used = ast_tvnow();
709         }
710
711         ao2_unlock(obj);
712
713         return res;
714 }
715
716 SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
717 {
718         SQLRETURN res;
719
720         if (pmaxlen == 0) {
721                 if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
722                         ast_str_make_space(buf, *StrLen_or_Ind + 1);
723                 }
724         } else if (pmaxlen > 0) {
725                 ast_str_make_space(buf, pmaxlen);
726         }
727         res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
728         ast_str_update(*buf);
729
730         return res;
731 }
732
733 int ast_odbc_sanity_check(struct odbc_obj *obj) 
734 {
735         char *test_sql = "select 1";
736         SQLHSTMT stmt;
737         int res = 0;
738
739         if (!ast_strlen_zero(obj->parent->sanitysql))
740                 test_sql = obj->parent->sanitysql;
741
742         if (obj->up) {
743                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
744                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
745                         obj->up = 0;
746                 } else {
747                         res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
748                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
749                                 obj->up = 0;
750                         } else {
751                                 res = SQLExecute(stmt);
752                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
753                                         obj->up = 0;
754                                 }
755                         }
756                 }
757                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
758         }
759
760         if (!obj->up && !obj->tx) { /* Try to reconnect! */
761                 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
762                 odbc_obj_disconnect(obj);
763                 odbc_obj_connect(obj);
764         }
765         return obj->up;
766 }
767
768 static int load_odbc_config(void)
769 {
770         static char *cfg = "res_odbc.conf";
771         struct ast_config *config;
772         struct ast_variable *v;
773         char *cat;
774         const char *dsn, *username, *password, *sanitysql;
775         int enabled, pooling, limit, bse, conntimeout, forcecommit, isolation;
776         struct timeval ncache = { 0, 0 };
777         unsigned int idlecheck;
778         int preconnect = 0, res = 0;
779         struct ast_flags config_flags = { 0 };
780
781         struct odbc_class *new;
782
783         config = ast_config_load(cfg, config_flags);
784         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
785                 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
786                 return -1;
787         }
788         for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
789                 if (!strcasecmp(cat, "ENV")) {
790                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
791                                 setenv(v->name, v->value, 1);
792                                 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
793                         }
794                 } else {
795                         /* Reset all to defaults for each class of odbc connections */
796                         dsn = username = password = sanitysql = NULL;
797                         enabled = 1;
798                         preconnect = idlecheck = 0;
799                         pooling = 0;
800                         limit = 0;
801                         bse = 1;
802                         conntimeout = 10;
803                         forcecommit = 0;
804                         isolation = SQL_TXN_READ_COMMITTED;
805                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
806                                 if (!strcasecmp(v->name, "pooling")) {
807                                         if (ast_true(v->value))
808                                                 pooling = 1;
809                                 } else if (!strncasecmp(v->name, "share", 5)) {
810                                         /* "shareconnections" is a little clearer in meaning than "pooling" */
811                                         if (ast_false(v->value))
812                                                 pooling = 1;
813                                 } else if (!strcasecmp(v->name, "limit")) {
814                                         sscanf(v->value, "%30d", &limit);
815                                         if (ast_true(v->value) && !limit) {
816                                                 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);
817                                                 limit = 1023;
818                                         } else if (ast_false(v->value)) {
819                                                 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
820                                                 enabled = 0;
821                                                 break;
822                                         }
823                                 } else if (!strcasecmp(v->name, "idlecheck")) {
824                                         sscanf(v->value, "%30u", &idlecheck);
825                                 } else if (!strcasecmp(v->name, "enabled")) {
826                                         enabled = ast_true(v->value);
827                                 } else if (!strcasecmp(v->name, "pre-connect")) {
828                                         preconnect = ast_true(v->value);
829                                 } else if (!strcasecmp(v->name, "dsn")) {
830                                         dsn = v->value;
831                                 } else if (!strcasecmp(v->name, "username")) {
832                                         username = v->value;
833                                 } else if (!strcasecmp(v->name, "password")) {
834                                         password = v->value;
835                                 } else if (!strcasecmp(v->name, "sanitysql")) {
836                                         sanitysql = v->value;
837                                 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
838                                         bse = ast_true(v->value);
839                                 } else if (!strcasecmp(v->name, "connect_timeout")) {
840                                         if (sscanf(v->value, "%d", &conntimeout) != 1 || conntimeout < 1) {
841                                                 ast_log(LOG_WARNING, "connect_timeout must be a positive integer\n");
842                                                 conntimeout = 10;
843                                         }
844                                 } else if (!strcasecmp(v->name, "negative_connection_cache")) {
845                                         double dncache;
846                                         if (sscanf(v->value, "%lf", &dncache) != 1 || dncache < 0) {
847                                                 ast_log(LOG_WARNING, "negative_connection_cache must be a non-negative integer\n");
848                                                 /* 5 minutes sounds like a reasonable default */
849                                                 ncache.tv_sec = 300;
850                                                 ncache.tv_usec = 0;
851                                         } else {
852                                                 ncache.tv_sec = (int)dncache;
853                                                 ncache.tv_usec = (dncache - ncache.tv_sec) * 1000000;
854                                         }
855                                 } else if (!strcasecmp(v->name, "forcecommit")) {
856                                         forcecommit = ast_true(v->value);
857                                 } else if (!strcasecmp(v->name, "isolation")) {
858                                         if ((isolation = text2isolation(v->value)) == 0) {
859                                                 ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
860                                                 isolation = SQL_TXN_READ_COMMITTED;
861                                         }
862                                 }
863                         }
864
865                         if (enabled && !ast_strlen_zero(dsn)) {
866                                 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
867
868                                 if (!new) {
869                                         res = -1;
870                                         break;
871                                 }
872
873                                 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
874                                 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
875
876                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
877                                         ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
878                                         ao2_ref(new, -1);
879                                         return res;
880                                 }
881
882                                 new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
883
884                                 if (pooling) {
885                                         new->haspool = pooling;
886                                         if (limit) {
887                                                 new->limit = limit;
888                                         } else {
889                                                 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
890                                                 new->limit = 5;
891                                         }
892                                 }
893
894                                 new->backslash_is_escape = bse ? 1 : 0;
895                                 new->forcecommit = forcecommit ? 1 : 0;
896                                 new->isolation = isolation;
897                                 new->idlecheck = idlecheck;
898                                 new->conntimeout = conntimeout;
899                                 new->negative_connection_cache = ncache;
900
901                                 if (cat)
902                                         ast_copy_string(new->name, cat, sizeof(new->name));
903                                 if (dsn)
904                                         ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
905                                 if (username && !(new->username = ast_strdup(username))) {
906                                         ao2_ref(new, -1);
907                                         break;
908                                 }
909                                 if (password && !(new->password = ast_strdup(password))) {
910                                         ao2_ref(new, -1);
911                                         break;
912                                 }
913                                 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
914                                         ao2_ref(new, -1);
915                                         break;
916                                 }
917
918                                 odbc_register_class(new, preconnect);
919                                 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
920                                 ao2_ref(new, -1);
921                                 new = NULL;
922                         }
923                 }
924         }
925         ast_config_destroy(config);
926         return res;
927 }
928
929 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
930 {
931         struct ao2_iterator aoi;
932         struct odbc_class *class;
933         struct odbc_obj *current;
934         int length = 0;
935         int which = 0;
936         char *ret = NULL;
937
938         switch (cmd) {
939         case CLI_INIT:
940                 e->command = "odbc show";
941                 e->usage =
942                                 "Usage: odbc show [class]\n"
943                                 "       List settings of a particular ODBC class or,\n"
944                                 "       if not specified, all classes.\n";
945                 return NULL;
946         case CLI_GENERATE:
947                 if (a->pos != 2)
948                         return NULL;
949                 length = strlen(a->word);
950                 aoi = ao2_iterator_init(class_container, 0);
951                 while ((class = ao2_iterator_next(&aoi))) {
952                         if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
953                                 ret = ast_strdup(class->name);
954                         }
955                         ao2_ref(class, -1);
956                         if (ret) {
957                                 break;
958                         }
959                 }
960                 ao2_iterator_destroy(&aoi);
961                 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
962                         ret = ast_strdup("all");
963                 }
964                 return ret;
965         }
966
967         ast_cli(a->fd, "\nODBC DSN Settings\n");
968         ast_cli(a->fd,   "-----------------\n\n");
969         aoi = ao2_iterator_init(class_container, 0);
970         while ((class = ao2_iterator_next(&aoi))) {
971                 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
972                         int count = 0;
973                         char timestr[80];
974                         struct ast_tm tm;
975
976                         ast_localtime(&class->last_negative_connect, &tm, NULL);
977                         ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
978                         ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
979                         ast_cli(a->fd, "    Last connection attempt: %s\n", timestr);
980
981                         if (class->haspool) {
982                                 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
983
984                                 ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);
985
986                                 while ((current = ao2_iterator_next(&aoi2))) {
987                                         ao2_lock(current);
988 #ifdef DEBUG_THREADS
989                                         ast_cli(a->fd, "    - Connection %d: %s (%s:%d %s)\n", ++count,
990                                                 current->used ? "in use" :
991                                                 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
992                                                 current->file, current->lineno, current->function);
993 #else
994                                         ast_cli(a->fd, "    - Connection %d: %s\n", ++count,
995                                                 current->used ? "in use" :
996                                                 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
997 #endif
998                                         ao2_unlock(current);
999                                         ao2_ref(current, -1);
1000                                 }
1001                                 ao2_iterator_destroy(&aoi2);
1002                         } else {
1003                                 /* Should only ever be one of these (unless there are transactions) */
1004                                 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
1005                                 while ((current = ao2_iterator_next(&aoi2))) {
1006                                         ast_cli(a->fd, "  Pooled: No\n  Connected: %s\n", current->used ? "In use" :
1007                                                 current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
1008                                         ao2_ref(current, -1);
1009                                 }
1010                                 ao2_iterator_destroy(&aoi2);
1011                         }
1012                         ast_cli(a->fd, "\n");
1013                 }
1014                 ao2_ref(class, -1);
1015         }
1016         ao2_iterator_destroy(&aoi);
1017
1018         return CLI_SUCCESS;
1019 }
1020
1021 static struct ast_cli_entry cli_odbc[] = {
1022         AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
1023 };
1024
1025 static int odbc_register_class(struct odbc_class *class, int preconnect)
1026 {
1027         struct odbc_obj *obj;
1028         if (class) {
1029                 ao2_link(class_container, class);
1030                 /* I still have a reference in the caller, so a deref is NOT missing here. */
1031
1032                 if (preconnect) {
1033                         /* Request and release builds a connection */
1034                         obj = ast_odbc_request_obj(class->name, 0);
1035                         if (obj) {
1036                                 ast_odbc_release_obj(obj);
1037                         }
1038                 }
1039
1040                 return 0;
1041         } else {
1042                 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
1043                 return -1;
1044         }
1045 }
1046
1047 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx)
1048 {
1049         SQLINTEGER nativeerror=0, numfields=0;
1050         SQLSMALLINT diagbytes=0, i;
1051         unsigned char state[10], diagnostic[256];
1052
1053         ast_debug(2, "odbc_release_obj2(%p) called (obj->txf = %p)\n", obj, obj->txf);
1054         if (tx) {
1055                 ast_debug(1, "called on a transactional handle with %s\n", tx->forcecommit ? "COMMIT" : "ROLLBACK");
1056                 if (SQLEndTran(SQL_HANDLE_DBC, obj->con, tx->forcecommit ? SQL_COMMIT : SQL_ROLLBACK) == SQL_ERROR) {
1057                         /* Handle possible transaction commit failure */
1058                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1059                         for (i = 0; i < numfields; i++) {
1060                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1061                                 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1062                                 if (!strcmp((char *)state, "25S02") || !strcmp((char *)state, "08007")) {
1063                                         /* These codes mean that a commit failed and a transaction
1064                                          * is still active. We must rollback, or things will get
1065                                          * very, very weird for anybody using the handle next. */
1066                                         SQLEndTran(SQL_HANDLE_DBC, obj->con, SQL_ROLLBACK);
1067                                 }
1068                                 if (i > 10) {
1069                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1070                                         break;
1071                                 }
1072                         }
1073                 }
1074
1075                 /* Transaction is done, reset autocommit */
1076                 if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1077                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1078                         for (i = 0; i < numfields; i++) {
1079                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1080                                 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1081                                 if (i > 10) {
1082                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1083                                         break;
1084                                 }
1085                         }
1086                 }
1087         }
1088
1089 #ifdef DEBUG_THREADS
1090         obj->file[0] = '\0';
1091         obj->function[0] = '\0';
1092         obj->lineno = 0;
1093 #endif
1094
1095         /* For pooled connections, this frees the connection to be
1096          * reused.  For non-pooled connections, it does nothing. */
1097         obj->used = 0;
1098         if (obj->txf) {
1099                 /* Prevent recursion -- transaction is already closed out. */
1100                 obj->txf->obj = NULL;
1101                 obj->txf = release_transaction(obj->txf);
1102         }
1103         ao2_ref(obj, -1);
1104 }
1105
1106 void ast_odbc_release_obj(struct odbc_obj *obj)
1107 {
1108         struct odbc_txn_frame *tx = find_transaction(NULL, obj, NULL, 0);
1109         odbc_release_obj2(obj, tx);
1110 }
1111
1112 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
1113 {
1114         return obj->parent->backslash_is_escape;
1115 }
1116
1117 static int commit_exec(struct ast_channel *chan, const char *data)
1118 {
1119         struct odbc_txn_frame *tx;
1120         SQLINTEGER nativeerror=0, numfields=0;
1121         SQLSMALLINT diagbytes=0, i;
1122         unsigned char state[10], diagnostic[256];
1123
1124         if (ast_strlen_zero(data)) {
1125                 tx = find_transaction(chan, NULL, NULL, 1);
1126         } else {
1127                 tx = find_transaction(chan, NULL, data, 0);
1128         }
1129
1130         pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", "OK");
1131
1132         if (tx) {
1133                 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_COMMIT) == SQL_ERROR) {
1134                         struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1135                         ast_str_reset(errors);
1136
1137                         /* Handle possible transaction commit failure */
1138                         SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1139                         for (i = 0; i < numfields; i++) {
1140                                 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1141                                 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1142                                 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1143                                 if (i > 10) {
1144                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1145                                         break;
1146                                 }
1147                         }
1148                         pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", ast_str_buffer(errors));
1149                 }
1150         }
1151         return 0;
1152 }
1153
1154 static int rollback_exec(struct ast_channel *chan, const char *data)
1155 {
1156         struct odbc_txn_frame *tx;
1157         SQLINTEGER nativeerror=0, numfields=0;
1158         SQLSMALLINT diagbytes=0, i;
1159         unsigned char state[10], diagnostic[256];
1160
1161         if (ast_strlen_zero(data)) {
1162                 tx = find_transaction(chan, NULL, NULL, 1);
1163         } else {
1164                 tx = find_transaction(chan, NULL, data, 0);
1165         }
1166
1167         pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", "OK");
1168
1169         if (tx) {
1170                 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_ROLLBACK) == SQL_ERROR) {
1171                         struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1172                         ast_str_reset(errors);
1173
1174                         /* Handle possible transaction commit failure */
1175                         SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1176                         for (i = 0; i < numfields; i++) {
1177                                 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1178                                 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1179                                 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1180                                 if (i > 10) {
1181                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1182                                         break;
1183                                 }
1184                         }
1185                         pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", ast_str_buffer(errors));
1186                 }
1187         }
1188         return 0;
1189 }
1190
1191 static int aoro2_class_cb(void *obj, void *arg, int flags)
1192 {
1193         struct odbc_class *class = obj;
1194         char *name = arg;
1195         if (!strcmp(class->name, name) && !class->delme) {
1196                 return CMP_MATCH | CMP_STOP;
1197         }
1198         return 0;
1199 }
1200
1201 #define USE_TX (void *)(long)1
1202 #define NO_TX  (void *)(long)2
1203 #define EOR_TX (void *)(long)3
1204
1205 static int aoro2_obj_cb(void *vobj, void *arg, int flags)
1206 {
1207         struct odbc_obj *obj = vobj;
1208         ao2_lock(obj);
1209         if ((arg == NO_TX && !obj->tx) || (arg == EOR_TX && !obj->used) || (arg == USE_TX && obj->tx && !obj->used)) {
1210                 obj->used = 1;
1211                 ao2_unlock(obj);
1212                 return CMP_MATCH | CMP_STOP;
1213         }
1214         ao2_unlock(obj);
1215         return 0;
1216 }
1217
1218 /* This function should only be called for shared connections. Otherwise, the lack of
1219  * setting vobj->used breaks EOR_TX searching. For nonshared connections, use
1220  * aoro2_obj_cb instead. */
1221 static int aoro2_obj_notx_cb(void *vobj, void *arg, int flags)
1222 {
1223         struct odbc_obj *obj = vobj;
1224         if (!obj->tx) {
1225                 return CMP_MATCH | CMP_STOP;
1226         }
1227         return 0;
1228 }
1229
1230 struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
1231 {
1232         struct odbc_obj *obj = NULL;
1233         struct odbc_class *class;
1234         SQLINTEGER nativeerror=0, numfields=0;
1235         SQLSMALLINT diagbytes=0, i;
1236         unsigned char state[10], diagnostic[256];
1237
1238         if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
1239                 ast_debug(1, "Class '%s' not found!\n", name);
1240                 return NULL;
1241         }
1242
1243         ast_assert(ao2_ref(class, 0) > 1);
1244
1245         if (class->haspool) {
1246                 /* Recycle connections before building another */
1247                 obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, EOR_TX);
1248
1249                 if (obj) {
1250                         ast_assert(ao2_ref(obj, 0) > 1);
1251                 }
1252                 if (!obj && (ast_atomic_fetchadd_int(&class->count, +1) < class->limit) &&
1253                                 (time(NULL) > class->last_negative_connect.tv_sec + class->negative_connection_cache.tv_sec)) {
1254                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1255                         if (!obj) {
1256                                 class->count--;
1257                                 ao2_ref(class, -1);
1258                                 ast_debug(3, "Unable to allocate object\n");
1259                                 ast_atomic_fetchadd_int(&class->count, -1);
1260                                 return NULL;
1261                         }
1262                         ast_assert(ao2_ref(obj, 0) == 1);
1263                         /* obj inherits the outstanding reference to class */
1264                         obj->parent = class;
1265                         class = NULL;
1266                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
1267                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1268                                 ast_assert(ao2_ref(obj->parent, 0) > 0);
1269                                 /* Because it was never within the container, we have to manually decrement the count here */
1270                                 ast_atomic_fetchadd_int(&obj->parent->count, -1);
1271                                 ao2_ref(obj, -1);
1272                                 obj = NULL;
1273                         } else {
1274                                 obj->used = 1;
1275                                 ao2_link(obj->parent->obj_container, obj);
1276                         }
1277                 } else {
1278                         /* If construction fails due to the limit (or negative timecache), reverse our increment. */
1279                         if (!obj) {
1280                                 ast_atomic_fetchadd_int(&class->count, -1);
1281                         }
1282                         /* Object is not constructed, so delete outstanding reference to class. */
1283                         ao2_ref(class, -1);
1284                         class = NULL;
1285                 }
1286
1287                 if (!obj) {
1288                         return NULL;
1289                 }
1290
1291                 ao2_lock(obj);
1292
1293                 if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1294                         /* Ensure this connection has autocommit turned off. */
1295                         if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1296                                 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1297                                 for (i = 0; i < numfields; i++) {
1298                                         SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1299                                         ast_log(LOG_WARNING, "SQLSetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1300                                         if (i > 10) {
1301                                                 ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1302                                                 break;
1303                                         }
1304                                 }
1305                         }
1306                 }
1307         } else if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1308                 /* Non-pooled connections -- but must use a separate connection handle */
1309                 if (!(obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, USE_TX))) {
1310                         ast_debug(1, "Object not found\n");
1311                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1312                         if (!obj) {
1313                                 ao2_ref(class, -1);
1314                                 ast_debug(3, "Unable to allocate object\n");
1315                                 return NULL;
1316                         }
1317                         /* obj inherits the outstanding reference to class */
1318                         obj->parent = class;
1319                         class = NULL;
1320                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
1321                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1322                                 ao2_ref(obj, -1);
1323                                 obj = NULL;
1324                         } else {
1325                                 obj->used = 1;
1326                                 ao2_link(obj->parent->obj_container, obj);
1327                                 ast_atomic_fetchadd_int(&obj->parent->count, +1);
1328                         }
1329                 }
1330
1331                 if (!obj) {
1332                         return NULL;
1333                 }
1334
1335                 ao2_lock(obj);
1336
1337                 if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1338                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1339                         for (i = 0; i < numfields; i++) {
1340                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1341                                 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1342                                 if (i > 10) {
1343                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1344                                         break;
1345                                 }
1346                         }
1347                 }
1348         } else {
1349                 /* Non-pooled connection: multiple modules can use the same connection. */
1350                 if ((obj = ao2_callback(class->obj_container, 0, aoro2_obj_notx_cb, NO_TX))) {
1351                         /* Object is not constructed, so delete outstanding reference to class. */
1352                         ast_assert(ao2_ref(class, 0) > 1);
1353                         ao2_ref(class, -1);
1354                         class = NULL;
1355                 } else {
1356                         /* No entry: build one */
1357                         if (!(obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor))) {
1358                                 ast_assert(ao2_ref(class, 0) > 1);
1359                                 ao2_ref(class, -1);
1360                                 ast_debug(3, "Unable to allocate object\n");
1361                                 return NULL;
1362                         }
1363                         /* obj inherits the outstanding reference to class */
1364                         obj->parent = class;
1365                         class = NULL;
1366                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
1367                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1368                                 ao2_ref(obj, -1);
1369                                 obj = NULL;
1370                         } else {
1371                                 ao2_link(obj->parent->obj_container, obj);
1372                                 ast_assert(ao2_ref(obj, 0) > 1);
1373                         }
1374                 }
1375
1376                 if (!obj) {
1377                         return NULL;
1378                 }
1379
1380                 ao2_lock(obj);
1381
1382                 if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1383                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1384                         for (i = 0; i < numfields; i++) {
1385                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1386                                 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1387                                 if (i > 10) {
1388                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1389                                         break;
1390                                 }
1391                         }
1392                 }
1393         }
1394
1395         ast_assert(obj != NULL);
1396
1397         /* Set the isolation property */
1398         if (SQLSetConnectAttr(obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)obj->parent->isolation, 0) == SQL_ERROR) {
1399                 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1400                 for (i = 0; i < numfields; i++) {
1401                         SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1402                         ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1403                         if (i > 10) {
1404                                 ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1405                                 break;
1406                         }
1407                 }
1408         }
1409
1410         if (ast_test_flag(&flags, RES_ODBC_CONNECTED) && !obj->up) {
1411                 /* Check if this connection qualifies for reconnection, with negative connection cache time */
1412                 if (time(NULL) > obj->parent->last_negative_connect.tv_sec + obj->parent->negative_connection_cache.tv_sec) {
1413                         odbc_obj_connect(obj);
1414                 }
1415         } else if (ast_test_flag(&flags, RES_ODBC_SANITY_CHECK)) {
1416                 ast_odbc_sanity_check(obj);
1417         } else if (obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck) {
1418                 odbc_obj_connect(obj);
1419         }
1420
1421 #ifdef DEBUG_THREADS
1422         ast_copy_string(obj->file, file, sizeof(obj->file));
1423         ast_copy_string(obj->function, function, sizeof(obj->function));
1424         obj->lineno = lineno;
1425 #endif
1426
1427         /* We had it locked because of the obj_connects we see here. */
1428         ao2_unlock(obj);
1429
1430         ast_assert(class == NULL);
1431
1432         ast_assert(ao2_ref(obj, 0) > 1);
1433         return obj;
1434 }
1435
1436 struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
1437 {
1438         struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
1439         return _ast_odbc_request_obj2(name, flags, file, function, lineno);
1440 }
1441
1442 struct odbc_obj *ast_odbc_retrieve_transaction_obj(struct ast_channel *chan, const char *objname)
1443 {
1444         struct ast_datastore *txn_store;
1445         AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
1446         struct odbc_txn_frame *txn = NULL;
1447
1448         if (!chan) {
1449                 /* No channel == no transaction */
1450                 return NULL;
1451         }
1452
1453         ast_channel_lock(chan);
1454         if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
1455                 oldlist = txn_store->data;
1456         } else {
1457                 ast_channel_unlock(chan);
1458                 return NULL;
1459         }
1460
1461         AST_LIST_LOCK(oldlist);
1462         ast_channel_unlock(chan);
1463
1464         AST_LIST_TRAVERSE(oldlist, txn, list) {
1465                 if (txn->obj && txn->obj->parent && !strcmp(txn->obj->parent->name, objname)) {
1466                         AST_LIST_UNLOCK(oldlist);
1467                         return txn->obj;
1468                 }
1469         }
1470         AST_LIST_UNLOCK(oldlist);
1471         return NULL;
1472 }
1473
1474 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
1475 {
1476         int res;
1477         SQLINTEGER err;
1478         short int mlen;
1479         unsigned char msg[200], state[10];
1480         SQLHDBC con;
1481
1482         /* Nothing to disconnect */
1483         if (!obj->con) {
1484                 return ODBC_SUCCESS;
1485         }
1486
1487         con = obj->con;
1488         obj->con = NULL;
1489         res = SQLDisconnect(con);
1490
1491         if (obj->parent) {
1492                 if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
1493                         ast_debug(1, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
1494                 } else {
1495                         ast_debug(1, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
1496                 }
1497         }
1498
1499         if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con)) == SQL_SUCCESS) {
1500                 ast_debug(1, "Database handle %p deallocated\n", con);
1501         } else {
1502                 SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
1503                 ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
1504         }
1505
1506         obj->up = 0;
1507         return ODBC_SUCCESS;
1508 }
1509
1510 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
1511 {
1512         int res;
1513         SQLINTEGER err;
1514         short int mlen;
1515         unsigned char msg[200], state[10];
1516 #ifdef NEEDTRACE
1517         SQLINTEGER enable = 1;
1518         char *tracefile = "/tmp/odbc.trace";
1519 #endif
1520         SQLHDBC con;
1521
1522         if (obj->up) {
1523                 odbc_obj_disconnect(obj);
1524                 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
1525         } else {
1526                 ast_assert(obj->con == NULL);
1527                 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
1528         }
1529
1530         res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &con);
1531
1532         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1533                 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
1534                 obj->parent->last_negative_connect = ast_tvnow();
1535                 return ODBC_FAIL;
1536         }
1537         SQLSetConnectAttr(con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1538         SQLSetConnectAttr(con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1539 #ifdef NEEDTRACE
1540         SQLSetConnectAttr(con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
1541         SQLSetConnectAttr(con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
1542 #endif
1543
1544         res = SQLConnect(con,
1545                    (SQLCHAR *) obj->parent->dsn, SQL_NTS,
1546                    (SQLCHAR *) obj->parent->username, SQL_NTS,
1547                    (SQLCHAR *) obj->parent->password, SQL_NTS);
1548
1549         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1550                 SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
1551                 obj->parent->last_negative_connect = ast_tvnow();
1552                 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
1553                 if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con)) != SQL_SUCCESS) {
1554                         SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
1555                         ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
1556                 }
1557                 return ODBC_FAIL;
1558         } else {
1559                 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
1560                 obj->up = 1;
1561                 obj->last_used = ast_tvnow();
1562         }
1563
1564         obj->con = con;
1565         return ODBC_SUCCESS;
1566 }
1567
1568 static int acf_transaction_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1569 {
1570         AST_DECLARE_APP_ARGS(args,
1571                 AST_APP_ARG(property);
1572                 AST_APP_ARG(opt);
1573         );
1574         struct odbc_txn_frame *tx;
1575
1576         AST_STANDARD_APP_ARGS(args, data);
1577         if (strcasecmp(args.property, "transaction") == 0) {
1578                 if ((tx = find_transaction(chan, NULL, NULL, 1))) {
1579                         ast_copy_string(buf, tx->name, len);
1580                         return 0;
1581                 }
1582         } else if (strcasecmp(args.property, "isolation") == 0) {
1583                 if (!ast_strlen_zero(args.opt)) {
1584                         tx = find_transaction(chan, NULL, args.opt, 0);
1585                 } else {
1586                         tx = find_transaction(chan, NULL, NULL, 1);
1587                 }
1588                 if (tx) {
1589                         ast_copy_string(buf, isolation2text(tx->isolation), len);
1590                         return 0;
1591                 }
1592         } else if (strcasecmp(args.property, "forcecommit") == 0) {
1593                 if (!ast_strlen_zero(args.opt)) {
1594                         tx = find_transaction(chan, NULL, args.opt, 0);
1595                 } else {
1596                         tx = find_transaction(chan, NULL, NULL, 1);
1597                 }
1598                 if (tx) {
1599                         ast_copy_string(buf, tx->forcecommit ? "1" : "0", len);
1600                         return 0;
1601                 }
1602         }
1603         return -1;
1604 }
1605
1606 static int acf_transaction_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
1607 {
1608         AST_DECLARE_APP_ARGS(args,
1609                 AST_APP_ARG(property);
1610                 AST_APP_ARG(opt);
1611         );
1612         struct odbc_txn_frame *tx;
1613         SQLINTEGER nativeerror=0, numfields=0;
1614         SQLSMALLINT diagbytes=0, i;
1615         unsigned char state[10], diagnostic[256];
1616
1617         AST_STANDARD_APP_ARGS(args, s);
1618         if (strcasecmp(args.property, "transaction") == 0) {
1619                 /* Set active transaction */
1620                 struct odbc_obj *obj;
1621                 if ((tx = find_transaction(chan, NULL, value, 0))) {
1622                         mark_transaction_active(chan, tx);
1623                 } else {
1624                         /* No such transaction, create one */
1625                         struct ast_flags flags = { RES_ODBC_INDEPENDENT_CONNECTION };
1626                         if (ast_strlen_zero(args.opt) || !(obj = ast_odbc_request_obj2(args.opt, flags))) {
1627                                 ast_log(LOG_ERROR, "Could not create transaction: invalid database specification '%s'\n", S_OR(args.opt, ""));
1628                                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_DB");
1629                                 return -1;
1630                         }
1631                         if (!(tx = find_transaction(chan, obj, value, 0))) {
1632                                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1633                                 return -1;
1634                         }
1635                         obj->tx = 1;
1636                 }
1637                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1638                 return 0;
1639         } else if (strcasecmp(args.property, "forcecommit") == 0) {
1640                 /* Set what happens when an uncommitted transaction ends without explicit Commit or Rollback */
1641                 if (ast_strlen_zero(args.opt)) {
1642                         tx = find_transaction(chan, NULL, NULL, 1);
1643                 } else {
1644                         tx = find_transaction(chan, NULL, args.opt, 0);
1645                 }
1646                 if (!tx) {
1647                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1648                         return -1;
1649                 }
1650                 if (ast_true(value)) {
1651                         tx->forcecommit = 1;
1652                 } else if (ast_false(value)) {
1653                         tx->forcecommit = 0;
1654                 } else {
1655                         ast_log(LOG_ERROR, "Invalid value for forcecommit: '%s'\n", S_OR(value, ""));
1656                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1657                         return -1;
1658                 }
1659
1660                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1661                 return 0;
1662         } else if (strcasecmp(args.property, "isolation") == 0) {
1663                 /* How do uncommitted transactions affect reads? */
1664                 int isolation = text2isolation(value);
1665                 if (ast_strlen_zero(args.opt)) {
1666                         tx = find_transaction(chan, NULL, NULL, 1);
1667                 } else {
1668                         tx = find_transaction(chan, NULL, args.opt, 0);
1669                 }
1670                 if (!tx) {
1671                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1672                         return -1;
1673                 }
1674                 if (isolation == 0) {
1675                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1676                         ast_log(LOG_ERROR, "Invalid isolation specification: '%s'\n", S_OR(value, ""));
1677                 } else if (SQLSetConnectAttr(tx->obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)isolation, 0) == SQL_ERROR) {
1678                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "SQL_ERROR");
1679                         SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1680                         for (i = 0; i < numfields; i++) {
1681                                 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1682                                 ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1683                                 if (i > 10) {
1684                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1685                                         break;
1686                                 }
1687                         }
1688                 } else {
1689                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1690                         tx->isolation = isolation;
1691                 }
1692                 return 0;
1693         } else {
1694                 ast_log(LOG_ERROR, "Unknown property: '%s'\n", args.property);
1695                 return -1;
1696         }
1697 }
1698
1699 static struct ast_custom_function odbc_function = {
1700         .name = "ODBC",
1701         .read = acf_transaction_read,
1702         .write = acf_transaction_write,
1703 };
1704
1705 static const char * const app_commit = "ODBC_Commit";
1706 static const char * const app_rollback = "ODBC_Rollback";
1707
1708 /*!
1709  * \internal
1710  * \brief Implements the channels provider.
1711  */
1712 static int data_odbc_provider_handler(const struct ast_data_search *search,
1713                 struct ast_data *root)
1714 {
1715         struct ao2_iterator aoi, aoi2;
1716         struct odbc_class *class;
1717         struct odbc_obj *current;
1718         struct ast_data *data_odbc_class, *data_odbc_connections, *data_odbc_connection;
1719         struct ast_data *enum_node;
1720         int count;
1721
1722         aoi = ao2_iterator_init(class_container, 0);
1723         while ((class = ao2_iterator_next(&aoi))) {
1724                 data_odbc_class = ast_data_add_node(root, "class");
1725                 if (!data_odbc_class) {
1726                         ao2_ref(class, -1);
1727                         continue;
1728                 }
1729
1730                 ast_data_add_structure(odbc_class, data_odbc_class, class);
1731
1732                 if (!ao2_container_count(class->obj_container)) {
1733                         ao2_ref(class, -1);
1734                         continue;
1735                 }
1736
1737                 data_odbc_connections = ast_data_add_node(data_odbc_class, "connections");
1738                 if (!data_odbc_connections) {
1739                         ao2_ref(class, -1);
1740                         continue;
1741                 }
1742
1743                 ast_data_add_bool(data_odbc_class, "shared", !class->haspool);
1744                 /* isolation */
1745                 enum_node = ast_data_add_node(data_odbc_class, "isolation");
1746                 if (!enum_node) {
1747                         ao2_ref(class, -1);
1748                         continue;
1749                 }
1750                 ast_data_add_int(enum_node, "value", class->isolation);
1751                 ast_data_add_str(enum_node, "text", isolation2text(class->isolation));
1752
1753                 count = 0;
1754                 aoi2 = ao2_iterator_init(class->obj_container, 0);
1755                 while ((current = ao2_iterator_next(&aoi2))) {
1756                         data_odbc_connection = ast_data_add_node(data_odbc_connections, "connection");
1757                         if (!data_odbc_connection) {
1758                                 ao2_ref(current, -1);
1759                                 continue;
1760                         }
1761
1762                         ao2_lock(current);
1763                         ast_data_add_str(data_odbc_connection, "status", current->used ? "in use" :
1764                                         current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
1765                         ast_data_add_bool(data_odbc_connection, "transactional", current->tx);
1766                         ao2_unlock(current);
1767
1768                         if (class->haspool) {
1769                                 ast_data_add_int(data_odbc_connection, "number", ++count);
1770                         }
1771
1772                         ao2_ref(current, -1);
1773                 }
1774                 ao2_iterator_destroy(&aoi2);
1775                 ao2_ref(class, -1);
1776
1777                 if (!ast_data_search_match(search, data_odbc_class)) {
1778                         ast_data_remove_node(root, data_odbc_class);
1779                 }
1780         }
1781         ao2_iterator_destroy(&aoi);
1782         return 0;
1783 }
1784
1785 /*!
1786  * \internal
1787  * \brief /asterisk/res/odbc/listprovider.
1788  */
1789 static const struct ast_data_handler odbc_provider = {
1790         .version = AST_DATA_HANDLER_VERSION,
1791         .get = data_odbc_provider_handler
1792 };
1793
1794 static const struct ast_data_entry odbc_providers[] = {
1795         AST_DATA_ENTRY("/asterisk/res/odbc", &odbc_provider),
1796 };
1797
1798 static int reload(void)
1799 {
1800         struct odbc_cache_tables *table;
1801         struct odbc_class *class;
1802         struct odbc_obj *current;
1803         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
1804
1805         /* First, mark all to be purged */
1806         while ((class = ao2_iterator_next(&aoi))) {
1807                 class->delme = 1;
1808                 ao2_ref(class, -1);
1809         }
1810         ao2_iterator_destroy(&aoi);
1811
1812         load_odbc_config();
1813
1814         /* Purge remaining classes */
1815
1816         /* Note on how this works; this is a case of circular references, so we
1817          * explicitly do NOT want to use a callback here (or we wind up in
1818          * recursive hell).
1819          *
1820          * 1. Iterate through all the classes.  Note that the classes will currently
1821          * contain two classes of the same name, one of which is marked delme and
1822          * will be purged when all remaining objects of the class are released, and
1823          * the other, which was created above when we re-parsed the config file.
1824          * 2. On each class, there is a reference held by the master container and
1825          * a reference held by each connection object.  There are two cases for
1826          * destruction of the class, noted below.  However, in all cases, all O-refs
1827          * (references to objects) will first be freed, which will cause the C-refs
1828          * (references to classes) to be decremented (but never to 0, because the
1829          * class container still has a reference).
1830          *    a) If the class has outstanding objects, the C-ref by the class
1831          *    container will then be freed, which leaves only C-refs by any
1832          *    outstanding objects.  When the final outstanding object is released
1833          *    (O-refs held by applications and dialplan functions), it will in turn
1834          *    free the final C-ref, causing class destruction.
1835          *    b) If the class has no outstanding objects, when the class container
1836          *    removes the final C-ref, the class will be destroyed.
1837          */
1838         aoi = ao2_iterator_init(class_container, 0);
1839         while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
1840                 if (class->delme) {
1841                         struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
1842                         while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
1843                                 ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
1844                                 ao2_ref(current, -1); /* O-ref-- (by iterator) */
1845                                 /* At this point, either
1846                                  * a) there's an outstanding O-ref, or
1847                                  * b) the object has already been destroyed.
1848                                  */
1849                         }
1850                         ao2_iterator_destroy(&aoi2);
1851                         ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
1852                         /* At this point, either
1853                          * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
1854                          * b) the last remaining C-ref is held by the iterator, which will be
1855                          * destroyed in the next step.
1856                          */
1857                 }
1858                 ao2_ref(class, -1); /* C-ref-- (by iterator) */
1859         }
1860         ao2_iterator_destroy(&aoi);
1861
1862         /* Empty the cache; it will get rebuilt the next time the tables are needed. */
1863         AST_RWLIST_WRLOCK(&odbc_tables);
1864         while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
1865                 destroy_table_cache(table);
1866         }
1867         AST_RWLIST_UNLOCK(&odbc_tables);
1868
1869         return 0;
1870 }
1871
1872 static int unload_module(void)
1873 {
1874         /* Prohibit unloading */
1875         return -1;
1876 }
1877
1878 static int load_module(void)
1879 {
1880         if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
1881                 return AST_MODULE_LOAD_DECLINE;
1882         if (load_odbc_config() == -1)
1883                 return AST_MODULE_LOAD_DECLINE;
1884         ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
1885         ast_data_register_multiple(odbc_providers, ARRAY_LEN(odbc_providers));
1886         ast_register_application_xml(app_commit, commit_exec);
1887         ast_register_application_xml(app_rollback, rollback_exec);
1888         ast_custom_function_register(&odbc_function);
1889         ast_log(LOG_NOTICE, "res_odbc loaded.\n");
1890         return 0;
1891 }
1892
1893 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "ODBC resource",
1894                 .load = load_module,
1895                 .unload = unload_module,
1896                 .reload = reload,
1897                 .load_pri = AST_MODPRI_REALTIME_DEPEND,
1898                );