Audit of ao2_iterator_init() usage for v1.8.
[asterisk/asterisk.git] / res / res_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, 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         ast_channel_lock(chan);
369         if (!(txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
370                 ast_channel_unlock(chan);
371                 return -1;
372         }
373
374         oldlist = txn_store->data;
375         AST_LIST_LOCK(oldlist);
376         AST_LIST_TRAVERSE(oldlist, txn, list) {
377                 if (txn == tx) {
378                         txn->active = 1;
379                         active = txn;
380                 } else {
381                         txn->active = 0;
382                 }
383         }
384         AST_LIST_UNLOCK(oldlist);
385         ast_channel_unlock(chan);
386         return active ? 0 : -1;
387 }
388
389 static void odbc_class_destructor(void *data)
390 {
391         struct odbc_class *class = data;
392         /* Due to refcounts, we can safely assume that any objects with a reference
393          * to us will prevent our destruction, so we don't need to worry about them.
394          */
395         if (class->username) {
396                 ast_free(class->username);
397         }
398         if (class->password) {
399                 ast_free(class->password);
400         }
401         if (class->sanitysql) {
402                 ast_free(class->sanitysql);
403         }
404         ao2_ref(class->obj_container, -1);
405         SQLFreeHandle(SQL_HANDLE_ENV, class->env);
406 }
407
408 static int null_hash_fn(const void *obj, const int flags)
409 {
410         return 0;
411 }
412
413 static void odbc_obj_destructor(void *data)
414 {
415         struct odbc_obj *obj = data;
416         struct odbc_class *class = obj->parent;
417         obj->parent = NULL;
418         odbc_obj_disconnect(obj);
419         ast_mutex_destroy(&obj->lock);
420         ao2_ref(class, -1);
421 }
422
423 static void destroy_table_cache(struct odbc_cache_tables *table) {
424         struct odbc_cache_columns *col;
425         ast_debug(1, "Destroying table cache for %s\n", table->table);
426         AST_RWLIST_WRLOCK(&table->columns);
427         while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
428                 ast_free(col);
429         }
430         AST_RWLIST_UNLOCK(&table->columns);
431         AST_RWLIST_HEAD_DESTROY(&table->columns);
432         ast_free(table);
433 }
434
435 /*!
436  * \brief Find or create an entry describing the table specified.
437  * \param database Name of an ODBC class on which to query the table
438  * \param tablename Tablename to describe
439  * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
440  * When a structure is returned, the contained columns list will be
441  * rdlock'ed, to ensure that it will be retained in memory.
442  * \since 1.6.1
443  */
444 struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
445 {
446         struct odbc_cache_tables *tableptr;
447         struct odbc_cache_columns *entry;
448         char columnname[80];
449         SQLLEN sqlptr;
450         SQLHSTMT stmt = NULL;
451         int res = 0, error = 0, try = 0;
452         struct odbc_obj *obj = ast_odbc_request_obj(database, 0);
453
454         AST_RWLIST_RDLOCK(&odbc_tables);
455         AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
456                 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
457                         break;
458                 }
459         }
460         if (tableptr) {
461                 AST_RWLIST_RDLOCK(&tableptr->columns);
462                 AST_RWLIST_UNLOCK(&odbc_tables);
463                 if (obj) {
464                         ast_odbc_release_obj(obj);
465                 }
466                 return tableptr;
467         }
468
469         if (!obj) {
470                 ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
471                 AST_RWLIST_UNLOCK(&odbc_tables);
472                 return NULL;
473         }
474
475         /* Table structure not already cached; build it now. */
476         do {
477                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
478                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
479                         if (try == 0) {
480                                 try = 1;
481                                 ast_odbc_sanity_check(obj);
482                                 continue;
483                         }
484                         ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
485                         break;
486                 }
487
488                 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
489                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
490                         if (try == 0) {
491                                 try = 1;
492                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
493                                 ast_odbc_sanity_check(obj);
494                                 continue;
495                         }
496                         ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
497                         break;
498                 }
499
500                 if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
501                         ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
502                         break;
503                 }
504
505                 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
506                 tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
507                 strcpy(tableptr->connection, database); /* SAFE */
508                 strcpy(tableptr->table, tablename); /* SAFE */
509                 AST_RWLIST_HEAD_INIT(&(tableptr->columns));
510
511                 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
512                         SQLGetData(stmt,  4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
513
514                         if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
515                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
516                                 error = 1;
517                                 break;
518                         }
519                         entry->name = (char *)entry + sizeof(*entry);
520                         strcpy(entry->name, columnname);
521
522                         SQLGetData(stmt,  5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
523                         SQLGetData(stmt,  7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
524                         SQLGetData(stmt,  9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
525                         SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
526                         SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
527                         SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
528
529                         /* Specification states that the octenlen should be the maximum number of bytes
530                          * returned in a char or binary column, but it seems that some drivers just set
531                          * it to NULL. (Bad Postgres! No biscuit!) */
532                         if (entry->octetlen == 0) {
533                                 entry->octetlen = entry->size;
534                         }
535
536                         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);
537                         /* Insert column info into column list */
538                         AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
539                 }
540                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
541
542                 AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
543                 AST_RWLIST_RDLOCK(&(tableptr->columns));
544                 break;
545         } while (1);
546
547         AST_RWLIST_UNLOCK(&odbc_tables);
548
549         if (error) {
550                 destroy_table_cache(tableptr);
551                 tableptr = NULL;
552         }
553         if (obj) {
554                 ast_odbc_release_obj(obj);
555         }
556         return tableptr;
557 }
558
559 struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
560 {
561         struct odbc_cache_columns *col;
562         AST_RWLIST_TRAVERSE(&table->columns, col, list) {
563                 if (strcasecmp(col->name, colname) == 0) {
564                         return col;
565                 }
566         }
567         return NULL;
568 }
569
570 int ast_odbc_clear_cache(const char *database, const char *tablename)
571 {
572         struct odbc_cache_tables *tableptr;
573
574         AST_RWLIST_WRLOCK(&odbc_tables);
575         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
576                 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
577                         AST_LIST_REMOVE_CURRENT(list);
578                         destroy_table_cache(tableptr);
579                         break;
580                 }
581         }
582         AST_RWLIST_TRAVERSE_SAFE_END
583         AST_RWLIST_UNLOCK(&odbc_tables);
584         return tableptr ? 0 : -1;
585 }
586
587 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
588 {
589         int attempt;
590         SQLHSTMT stmt;
591
592         for (attempt = 0; attempt < 2; attempt++) {
593                 stmt = exec_cb(obj, data);
594
595                 if (stmt) {
596                         break;
597                 } else if (obj->tx) {
598                         ast_log(LOG_WARNING, "Failed to execute, but unable to reconnect, as we're transactional.\n");
599                         break;
600                 } else if (attempt == 0) {
601                         ast_log(LOG_WARNING, "SQL Execute error! Verifying connection to %s [%s]...\n", obj->parent->name, obj->parent->dsn);
602                 }
603                 if (!ast_odbc_sanity_check(obj)) {
604                         break;
605                 }
606         }
607
608         return stmt;
609 }
610
611 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
612 {
613         int res = 0, i, attempt;
614         SQLINTEGER nativeerror=0, numfields=0;
615         SQLSMALLINT diagbytes=0;
616         unsigned char state[10], diagnostic[256];
617         SQLHSTMT stmt;
618
619         for (attempt = 0; attempt < 2; attempt++) {
620                 /* This prepare callback may do more than just prepare -- it may also
621                  * bind parameters, bind results, etc.  The real key, here, is that
622                  * when we disconnect, all handles become invalid for most databases.
623                  * We must therefore redo everything when we establish a new
624                  * connection. */
625                 stmt = prepare_cb(obj, data);
626
627                 if (stmt) {
628                         res = SQLExecute(stmt);
629                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
630                                 if (res == SQL_ERROR) {
631                                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
632                                         for (i = 0; i < numfields; i++) {
633                                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
634                                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
635                                                 if (i > 10) {
636                                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
637                                                         break;
638                                                 }
639                                         }
640                                 }
641
642                                 if (obj->tx) {
643                                         ast_log(LOG_WARNING, "SQL Execute error, but unable to reconnect, as we're transactional.\n");
644                                         break;
645                                 } else {
646                                         ast_log(LOG_WARNING, "SQL Execute error %d! Verifying connection to %s [%s]...\n", res, obj->parent->name, obj->parent->dsn);
647                                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
648                                         stmt = NULL;
649
650                                         obj->up = 0;
651                                         /*
652                                          * While this isn't the best way to try to correct an error, this won't automatically
653                                          * fail when the statement handle invalidates.
654                                          */
655                                         if (!ast_odbc_sanity_check(obj)) {
656                                                 break;
657                                         }
658                                         continue;
659                                 }
660                         } else {
661                                 obj->last_used = ast_tvnow();
662                         }
663                         break;
664                 } else if (attempt == 0) {
665                         ast_odbc_sanity_check(obj);
666                 }
667         }
668
669         return stmt;
670 }
671
672 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
673 {
674         int res = 0, i;
675         SQLINTEGER nativeerror=0, numfields=0;
676         SQLSMALLINT diagbytes=0;
677         unsigned char state[10], diagnostic[256];
678
679         res = SQLExecute(stmt);
680         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
681                 if (res == SQL_ERROR) {
682                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
683                         for (i = 0; i < numfields; i++) {
684                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
685                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
686                                 if (i > 10) {
687                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
688                                         break;
689                                 }
690                         }
691                 }
692         } else {
693                 obj->last_used = ast_tvnow();
694         }
695
696         return res;
697 }
698
699 SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
700 {
701         SQLRETURN res;
702
703         if (pmaxlen == 0) {
704                 if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
705                         ast_str_make_space(buf, *StrLen_or_Ind + 1);
706                 }
707         } else if (pmaxlen > 0) {
708                 ast_str_make_space(buf, pmaxlen);
709         }
710         res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
711         ast_str_update(*buf);
712
713         return res;
714 }
715
716 int ast_odbc_sanity_check(struct odbc_obj *obj) 
717 {
718         char *test_sql = "select 1";
719         SQLHSTMT stmt;
720         int res = 0;
721
722         if (!ast_strlen_zero(obj->parent->sanitysql))
723                 test_sql = obj->parent->sanitysql;
724
725         if (obj->up) {
726                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
727                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
728                         obj->up = 0;
729                 } else {
730                         res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
731                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
732                                 obj->up = 0;
733                         } else {
734                                 res = SQLExecute(stmt);
735                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
736                                         obj->up = 0;
737                                 }
738                         }
739                 }
740                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
741         }
742
743         if (!obj->up && !obj->tx) { /* Try to reconnect! */
744                 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
745                 odbc_obj_disconnect(obj);
746                 odbc_obj_connect(obj);
747         }
748         return obj->up;
749 }
750
751 static int load_odbc_config(void)
752 {
753         static char *cfg = "res_odbc.conf";
754         struct ast_config *config;
755         struct ast_variable *v;
756         char *cat;
757         const char *dsn, *username, *password, *sanitysql;
758         int enabled, pooling, limit, bse, conntimeout, forcecommit, isolation;
759         struct timeval ncache = { 0, 0 };
760         unsigned int idlecheck;
761         int preconnect = 0, res = 0;
762         struct ast_flags config_flags = { 0 };
763
764         struct odbc_class *new;
765
766         config = ast_config_load(cfg, config_flags);
767         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
768                 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
769                 return -1;
770         }
771         for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
772                 if (!strcasecmp(cat, "ENV")) {
773                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
774                                 setenv(v->name, v->value, 1);
775                                 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
776                         }
777                 } else {
778                         /* Reset all to defaults for each class of odbc connections */
779                         dsn = username = password = sanitysql = NULL;
780                         enabled = 1;
781                         preconnect = idlecheck = 0;
782                         pooling = 0;
783                         limit = 0;
784                         bse = 1;
785                         conntimeout = 10;
786                         forcecommit = 0;
787                         isolation = SQL_TXN_READ_COMMITTED;
788                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
789                                 if (!strcasecmp(v->name, "pooling")) {
790                                         if (ast_true(v->value))
791                                                 pooling = 1;
792                                 } else if (!strncasecmp(v->name, "share", 5)) {
793                                         /* "shareconnections" is a little clearer in meaning than "pooling" */
794                                         if (ast_false(v->value))
795                                                 pooling = 1;
796                                 } else if (!strcasecmp(v->name, "limit")) {
797                                         sscanf(v->value, "%30d", &limit);
798                                         if (ast_true(v->value) && !limit) {
799                                                 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);
800                                                 limit = 1023;
801                                         } else if (ast_false(v->value)) {
802                                                 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
803                                                 enabled = 0;
804                                                 break;
805                                         }
806                                 } else if (!strcasecmp(v->name, "idlecheck")) {
807                                         sscanf(v->value, "%30u", &idlecheck);
808                                 } else if (!strcasecmp(v->name, "enabled")) {
809                                         enabled = ast_true(v->value);
810                                 } else if (!strcasecmp(v->name, "pre-connect")) {
811                                         preconnect = ast_true(v->value);
812                                 } else if (!strcasecmp(v->name, "dsn")) {
813                                         dsn = v->value;
814                                 } else if (!strcasecmp(v->name, "username")) {
815                                         username = v->value;
816                                 } else if (!strcasecmp(v->name, "password")) {
817                                         password = v->value;
818                                 } else if (!strcasecmp(v->name, "sanitysql")) {
819                                         sanitysql = v->value;
820                                 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
821                                         bse = ast_true(v->value);
822                                 } else if (!strcasecmp(v->name, "connect_timeout")) {
823                                         if (sscanf(v->value, "%d", &conntimeout) != 1 || conntimeout < 1) {
824                                                 ast_log(LOG_WARNING, "connect_timeout must be a positive integer\n");
825                                                 conntimeout = 10;
826                                         }
827                                 } else if (!strcasecmp(v->name, "negative_connection_cache")) {
828                                         double dncache;
829                                         if (sscanf(v->value, "%lf", &dncache) != 1 || dncache < 0) {
830                                                 ast_log(LOG_WARNING, "negative_connection_cache must be a non-negative integer\n");
831                                                 /* 5 minutes sounds like a reasonable default */
832                                                 ncache.tv_sec = 300;
833                                                 ncache.tv_usec = 0;
834                                         } else {
835                                                 ncache.tv_sec = (int)dncache;
836                                                 ncache.tv_usec = (dncache - ncache.tv_sec) * 1000000;
837                                         }
838                                 } else if (!strcasecmp(v->name, "forcecommit")) {
839                                         forcecommit = ast_true(v->value);
840                                 } else if (!strcasecmp(v->name, "isolation")) {
841                                         if ((isolation = text2isolation(v->value)) == 0) {
842                                                 ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
843                                                 isolation = SQL_TXN_READ_COMMITTED;
844                                         }
845                                 }
846                         }
847
848                         if (enabled && !ast_strlen_zero(dsn)) {
849                                 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
850
851                                 if (!new) {
852                                         res = -1;
853                                         break;
854                                 }
855
856                                 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
857                                 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
858
859                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
860                                         ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
861                                         ao2_ref(new, -1);
862                                         return res;
863                                 }
864
865                                 new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
866
867                                 if (pooling) {
868                                         new->haspool = pooling;
869                                         if (limit) {
870                                                 new->limit = limit;
871                                         } else {
872                                                 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
873                                                 new->limit = 5;
874                                         }
875                                 }
876
877                                 new->backslash_is_escape = bse ? 1 : 0;
878                                 new->forcecommit = forcecommit ? 1 : 0;
879                                 new->isolation = isolation;
880                                 new->idlecheck = idlecheck;
881                                 new->conntimeout = conntimeout;
882                                 new->negative_connection_cache = ncache;
883
884                                 if (cat)
885                                         ast_copy_string(new->name, cat, sizeof(new->name));
886                                 if (dsn)
887                                         ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
888                                 if (username && !(new->username = ast_strdup(username))) {
889                                         ao2_ref(new, -1);
890                                         break;
891                                 }
892                                 if (password && !(new->password = ast_strdup(password))) {
893                                         ao2_ref(new, -1);
894                                         break;
895                                 }
896                                 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
897                                         ao2_ref(new, -1);
898                                         break;
899                                 }
900
901                                 odbc_register_class(new, preconnect);
902                                 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
903                                 ao2_ref(new, -1);
904                                 new = NULL;
905                         }
906                 }
907         }
908         ast_config_destroy(config);
909         return res;
910 }
911
912 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
913 {
914         struct ao2_iterator aoi;
915         struct odbc_class *class;
916         struct odbc_obj *current;
917         int length = 0;
918         int which = 0;
919         char *ret = NULL;
920
921         switch (cmd) {
922         case CLI_INIT:
923                 e->command = "odbc show";
924                 e->usage =
925                                 "Usage: odbc show [class]\n"
926                                 "       List settings of a particular ODBC class or,\n"
927                                 "       if not specified, all classes.\n";
928                 return NULL;
929         case CLI_GENERATE:
930                 if (a->pos != 2)
931                         return NULL;
932                 length = strlen(a->word);
933                 aoi = ao2_iterator_init(class_container, 0);
934                 while ((class = ao2_iterator_next(&aoi))) {
935                         if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
936                                 ret = ast_strdup(class->name);
937                         }
938                         ao2_ref(class, -1);
939                         if (ret) {
940                                 break;
941                         }
942                 }
943                 ao2_iterator_destroy(&aoi);
944                 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
945                         ret = ast_strdup("all");
946                 }
947                 return ret;
948         }
949
950         ast_cli(a->fd, "\nODBC DSN Settings\n");
951         ast_cli(a->fd,   "-----------------\n\n");
952         aoi = ao2_iterator_init(class_container, 0);
953         while ((class = ao2_iterator_next(&aoi))) {
954                 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
955                         int count = 0;
956                         char timestr[80];
957                         struct ast_tm tm;
958
959                         ast_localtime(&class->last_negative_connect, &tm, NULL);
960                         ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
961                         ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
962                         ast_cli(a->fd, "    Last connection attempt: %s\n", timestr);
963
964                         if (class->haspool) {
965                                 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
966
967                                 ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);
968
969                                 while ((current = ao2_iterator_next(&aoi2))) {
970                                         ast_mutex_lock(&current->lock);
971 #ifdef DEBUG_THREADS
972                                         ast_cli(a->fd, "    - Connection %d: %s (%s:%d %s)\n", ++count,
973                                                 current->used ? "in use" :
974                                                 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
975                                                 current->file, current->lineno, current->function);
976 #else
977                                         ast_cli(a->fd, "    - Connection %d: %s\n", ++count,
978                                                 current->used ? "in use" :
979                                                 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
980 #endif
981                                         ast_mutex_unlock(&current->lock);
982                                         ao2_ref(current, -1);
983                                 }
984                                 ao2_iterator_destroy(&aoi2);
985                         } else {
986                                 /* Should only ever be one of these (unless there are transactions) */
987                                 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
988                                 while ((current = ao2_iterator_next(&aoi2))) {
989                                         ast_cli(a->fd, "  Pooled: No\n  Connected: %s\n", current->used ? "In use" :
990                                                 current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
991                                         ao2_ref(current, -1);
992                                 }
993                                 ao2_iterator_destroy(&aoi2);
994                         }
995                         ast_cli(a->fd, "\n");
996                 }
997                 ao2_ref(class, -1);
998         }
999         ao2_iterator_destroy(&aoi);
1000
1001         return CLI_SUCCESS;
1002 }
1003
1004 static struct ast_cli_entry cli_odbc[] = {
1005         AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
1006 };
1007
1008 static int odbc_register_class(struct odbc_class *class, int preconnect)
1009 {
1010         struct odbc_obj *obj;
1011         if (class) {
1012                 ao2_link(class_container, class);
1013                 /* I still have a reference in the caller, so a deref is NOT missing here. */
1014
1015                 if (preconnect) {
1016                         /* Request and release builds a connection */
1017                         obj = ast_odbc_request_obj(class->name, 0);
1018                         if (obj) {
1019                                 ast_odbc_release_obj(obj);
1020                         }
1021                 }
1022
1023                 return 0;
1024         } else {
1025                 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
1026                 return -1;
1027         }
1028 }
1029
1030 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx)
1031 {
1032         SQLINTEGER nativeerror=0, numfields=0;
1033         SQLSMALLINT diagbytes=0, i;
1034         unsigned char state[10], diagnostic[256];
1035
1036         ast_debug(2, "odbc_release_obj2(%p) called (obj->txf = %p)\n", obj, obj->txf);
1037         if (tx) {
1038                 ast_debug(1, "called on a transactional handle with %s\n", tx->forcecommit ? "COMMIT" : "ROLLBACK");
1039                 if (SQLEndTran(SQL_HANDLE_DBC, obj->con, tx->forcecommit ? SQL_COMMIT : SQL_ROLLBACK) == SQL_ERROR) {
1040                         /* Handle possible transaction commit failure */
1041                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1042                         for (i = 0; i < numfields; i++) {
1043                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1044                                 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1045                                 if (!strcmp((char *)state, "25S02") || !strcmp((char *)state, "08007")) {
1046                                         /* These codes mean that a commit failed and a transaction
1047                                          * is still active. We must rollback, or things will get
1048                                          * very, very weird for anybody using the handle next. */
1049                                         SQLEndTran(SQL_HANDLE_DBC, obj->con, SQL_ROLLBACK);
1050                                 }
1051                                 if (i > 10) {
1052                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1053                                         break;
1054                                 }
1055                         }
1056                 }
1057
1058                 /* Transaction is done, reset autocommit */
1059                 if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1060                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1061                         for (i = 0; i < numfields; i++) {
1062                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1063                                 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1064                                 if (i > 10) {
1065                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1066                                         break;
1067                                 }
1068                         }
1069                 }
1070         }
1071
1072 #ifdef DEBUG_THREADS
1073         obj->file[0] = '\0';
1074         obj->function[0] = '\0';
1075         obj->lineno = 0;
1076 #endif
1077
1078         /* For pooled connections, this frees the connection to be
1079          * reused.  For non-pooled connections, it does nothing. */
1080         obj->used = 0;
1081         if (obj->txf) {
1082                 /* Prevent recursion -- transaction is already closed out. */
1083                 obj->txf->obj = NULL;
1084                 obj->txf = release_transaction(obj->txf);
1085         }
1086         ao2_ref(obj, -1);
1087 }
1088
1089 void ast_odbc_release_obj(struct odbc_obj *obj)
1090 {
1091         struct odbc_txn_frame *tx = find_transaction(NULL, obj, NULL, 0);
1092         odbc_release_obj2(obj, tx);
1093 }
1094
1095 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
1096 {
1097         return obj->parent->backslash_is_escape;
1098 }
1099
1100 static int commit_exec(struct ast_channel *chan, const char *data)
1101 {
1102         struct odbc_txn_frame *tx;
1103         SQLINTEGER nativeerror=0, numfields=0;
1104         SQLSMALLINT diagbytes=0, i;
1105         unsigned char state[10], diagnostic[256];
1106
1107         if (ast_strlen_zero(data)) {
1108                 tx = find_transaction(chan, NULL, NULL, 1);
1109         } else {
1110                 tx = find_transaction(chan, NULL, data, 0);
1111         }
1112
1113         pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", "OK");
1114
1115         if (tx) {
1116                 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_COMMIT) == SQL_ERROR) {
1117                         struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1118                         ast_str_reset(errors);
1119
1120                         /* Handle possible transaction commit failure */
1121                         SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1122                         for (i = 0; i < numfields; i++) {
1123                                 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1124                                 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1125                                 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1126                                 if (i > 10) {
1127                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1128                                         break;
1129                                 }
1130                         }
1131                         pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", ast_str_buffer(errors));
1132                 }
1133         }
1134         return 0;
1135 }
1136
1137 static int rollback_exec(struct ast_channel *chan, const char *data)
1138 {
1139         struct odbc_txn_frame *tx;
1140         SQLINTEGER nativeerror=0, numfields=0;
1141         SQLSMALLINT diagbytes=0, i;
1142         unsigned char state[10], diagnostic[256];
1143
1144         if (ast_strlen_zero(data)) {
1145                 tx = find_transaction(chan, NULL, NULL, 1);
1146         } else {
1147                 tx = find_transaction(chan, NULL, data, 0);
1148         }
1149
1150         pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", "OK");
1151
1152         if (tx) {
1153                 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_ROLLBACK) == SQL_ERROR) {
1154                         struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1155                         ast_str_reset(errors);
1156
1157                         /* Handle possible transaction commit failure */
1158                         SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1159                         for (i = 0; i < numfields; i++) {
1160                                 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1161                                 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1162                                 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1163                                 if (i > 10) {
1164                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1165                                         break;
1166                                 }
1167                         }
1168                         pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", ast_str_buffer(errors));
1169                 }
1170         }
1171         return 0;
1172 }
1173
1174 static int aoro2_class_cb(void *obj, void *arg, int flags)
1175 {
1176         struct odbc_class *class = obj;
1177         char *name = arg;
1178         if (!strcmp(class->name, name) && !class->delme) {
1179                 return CMP_MATCH | CMP_STOP;
1180         }
1181         return 0;
1182 }
1183
1184 #define USE_TX (void *)(long)1
1185 #define NO_TX  (void *)(long)2
1186 #define EOR_TX (void *)(long)3
1187
1188 static int aoro2_obj_cb(void *vobj, void *arg, int flags)
1189 {
1190         struct odbc_obj *obj = vobj;
1191         ast_mutex_lock(&obj->lock);
1192         if ((arg == NO_TX && !obj->tx) || (arg == EOR_TX && !obj->used) || (arg == USE_TX && obj->tx && !obj->used)) {
1193                 obj->used = 1;
1194                 ast_mutex_unlock(&obj->lock);
1195                 return CMP_MATCH | CMP_STOP;
1196         }
1197         ast_mutex_unlock(&obj->lock);
1198         return 0;
1199 }
1200
1201 struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
1202 {
1203         struct odbc_obj *obj = NULL;
1204         struct odbc_class *class;
1205         SQLINTEGER nativeerror=0, numfields=0;
1206         SQLSMALLINT diagbytes=0, i;
1207         unsigned char state[10], diagnostic[256];
1208
1209         if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
1210                 ast_debug(1, "Class '%s' not found!\n", name);
1211                 return NULL;
1212         }
1213
1214         ast_assert(ao2_ref(class, 0) > 1);
1215
1216         if (class->haspool) {
1217                 /* Recycle connections before building another */
1218                 obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, EOR_TX);
1219
1220                 if (obj) {
1221                         ast_assert(ao2_ref(obj, 0) > 1);
1222                 }
1223                 if (!obj && (ast_atomic_fetchadd_int(&class->count, +1) < class->limit) &&
1224                                 (time(NULL) > class->last_negative_connect.tv_sec + class->negative_connection_cache.tv_sec)) {
1225                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1226                         if (!obj) {
1227                                 class->count--;
1228                                 ao2_ref(class, -1);
1229                                 ast_debug(3, "Unable to allocate object\n");
1230                                 ast_atomic_fetchadd_int(&class->count, -1);
1231                                 return NULL;
1232                         }
1233                         ast_assert(ao2_ref(obj, 0) == 1);
1234                         ast_mutex_init(&obj->lock);
1235                         /* obj inherits the outstanding reference to class */
1236                         obj->parent = class;
1237                         class = NULL;
1238                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
1239                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1240                                 ast_assert(ao2_ref(obj->parent, 0) > 0);
1241                                 /* Because it was never within the container, we have to manually decrement the count here */
1242                                 ast_atomic_fetchadd_int(&obj->parent->count, -1);
1243                                 ao2_ref(obj, -1);
1244                                 obj = NULL;
1245                         } else {
1246                                 obj->used = 1;
1247                                 ao2_link(obj->parent->obj_container, obj);
1248                         }
1249                 } else {
1250                         /* If construction fails due to the limit (or negative timecache), reverse our increment. */
1251                         if (!obj) {
1252                                 ast_atomic_fetchadd_int(&class->count, -1);
1253                         }
1254                         /* Object is not constructed, so delete outstanding reference to class. */
1255                         ao2_ref(class, -1);
1256                         class = NULL;
1257                 }
1258
1259                 if (obj && ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1260                         /* Ensure this connection has autocommit turned off. */
1261                         if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1262                                 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1263                                 for (i = 0; i < numfields; i++) {
1264                                         SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1265                                         ast_log(LOG_WARNING, "SQLSetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1266                                         if (i > 10) {
1267                                                 ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1268                                                 break;
1269                                         }
1270                                 }
1271                         }
1272                 }
1273         } else if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1274                 /* Non-pooled connections -- but must use a separate connection handle */
1275                 if (!(obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, USE_TX))) {
1276                         ast_debug(1, "Object not found\n");
1277                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1278                         if (!obj) {
1279                                 ao2_ref(class, -1);
1280                                 ast_debug(3, "Unable to allocate object\n");
1281                                 return NULL;
1282                         }
1283                         ast_mutex_init(&obj->lock);
1284                         /* obj inherits the outstanding reference to class */
1285                         obj->parent = class;
1286                         class = NULL;
1287                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
1288                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1289                                 ao2_ref(obj, -1);
1290                                 obj = NULL;
1291                         } else {
1292                                 obj->used = 1;
1293                                 ao2_link(obj->parent->obj_container, obj);
1294                                 ast_atomic_fetchadd_int(&obj->parent->count, +1);
1295                         }
1296                 }
1297
1298                 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1299                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1300                         for (i = 0; i < numfields; i++) {
1301                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1302                                 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1303                                 if (i > 10) {
1304                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1305                                         break;
1306                                 }
1307                         }
1308                 }
1309         } else {
1310                 /* Non-pooled connection: multiple modules can use the same connection. */
1311                 if ((obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, NO_TX))) {
1312                         /* Object is not constructed, so delete outstanding reference to class. */
1313                         ast_assert(ao2_ref(class, 0) > 1);
1314                         ao2_ref(class, -1);
1315                         class = NULL;
1316                 } else {
1317                         /* No entry: build one */
1318                         if (!(obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor))) {
1319                                 ast_assert(ao2_ref(class, 0) > 1);
1320                                 ao2_ref(class, -1);
1321                                 ast_debug(3, "Unable to allocate object\n");
1322                                 return NULL;
1323                         }
1324                         ast_mutex_init(&obj->lock);
1325                         /* obj inherits the outstanding reference to class */
1326                         obj->parent = class;
1327                         class = NULL;
1328                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
1329                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1330                                 ao2_ref(obj, -1);
1331                                 obj = NULL;
1332                         } else {
1333                                 ao2_link(obj->parent->obj_container, obj);
1334                                 ast_assert(ao2_ref(obj, 0) > 1);
1335                         }
1336                 }
1337
1338                 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1339                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1340                         for (i = 0; i < numfields; i++) {
1341                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1342                                 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1343                                 if (i > 10) {
1344                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1345                                         break;
1346                                 }
1347                         }
1348                 }
1349         }
1350
1351         /* Set the isolation property */
1352         if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)obj->parent->isolation, 0) == SQL_ERROR) {
1353                 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1354                 for (i = 0; i < numfields; i++) {
1355                         SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1356                         ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1357                         if (i > 10) {
1358                                 ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1359                                 break;
1360                         }
1361                 }
1362         }
1363
1364         if (obj && ast_test_flag(&flags, RES_ODBC_CONNECTED) && !obj->up) {
1365                 /* Check if this connection qualifies for reconnection, with negative connection cache time */
1366                 if (time(NULL) > obj->parent->last_negative_connect.tv_sec + obj->parent->negative_connection_cache.tv_sec) {
1367                         odbc_obj_connect(obj);
1368                 }
1369         } else if (obj && ast_test_flag(&flags, RES_ODBC_SANITY_CHECK)) {
1370                 ast_odbc_sanity_check(obj);
1371         } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck) {
1372                 odbc_obj_connect(obj);
1373         }
1374
1375 #ifdef DEBUG_THREADS
1376         if (obj) {
1377                 ast_copy_string(obj->file, file, sizeof(obj->file));
1378                 ast_copy_string(obj->function, function, sizeof(obj->function));
1379                 obj->lineno = lineno;
1380         }
1381 #endif
1382         ast_assert(class == NULL);
1383
1384         if (obj) {
1385                 ast_assert(ao2_ref(obj, 0) > 1);
1386         }
1387         return obj;
1388 }
1389
1390 struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
1391 {
1392         struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
1393         return _ast_odbc_request_obj2(name, flags, file, function, lineno);
1394 }
1395
1396 struct odbc_obj *ast_odbc_retrieve_transaction_obj(struct ast_channel *chan, const char *objname)
1397 {
1398         struct ast_datastore *txn_store;
1399         AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
1400         struct odbc_txn_frame *txn = NULL;
1401
1402         if (!chan) {
1403                 /* No channel == no transaction */
1404                 return NULL;
1405         }
1406
1407         ast_channel_lock(chan);
1408         if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
1409                 oldlist = txn_store->data;
1410         } else {
1411                 ast_channel_unlock(chan);
1412                 return NULL;
1413         }
1414
1415         AST_LIST_LOCK(oldlist);
1416         ast_channel_unlock(chan);
1417
1418         AST_LIST_TRAVERSE(oldlist, txn, list) {
1419                 if (txn->obj && txn->obj->parent && !strcmp(txn->obj->parent->name, objname)) {
1420                         AST_LIST_UNLOCK(oldlist);
1421                         return txn->obj;
1422                 }
1423         }
1424         AST_LIST_UNLOCK(oldlist);
1425         return NULL;
1426 }
1427
1428 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
1429 {
1430         int res;
1431         SQLINTEGER err;
1432         short int mlen;
1433         unsigned char msg[200], state[10];
1434
1435         /* Nothing to disconnect */
1436         if (!obj->con) {
1437                 return ODBC_SUCCESS;
1438         }
1439
1440         ast_mutex_lock(&obj->lock);
1441
1442         res = SQLDisconnect(obj->con);
1443
1444         if (obj->parent) {
1445                 if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
1446                         ast_debug(1, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
1447                 } else {
1448                         ast_debug(1, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
1449                 }
1450         }
1451
1452         if ((res = SQLFreeHandle(SQL_HANDLE_DBC, obj->con) == SQL_SUCCESS)) {
1453                 obj->con = NULL;
1454                 ast_debug(1, "Database handle deallocated\n");
1455         } else {
1456                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
1457                 ast_log(LOG_WARNING, "Unable to deallocate database handle? %d errno=%d %s\n", res, (int)err, msg);
1458         }
1459
1460         obj->up = 0;
1461         ast_mutex_unlock(&obj->lock);
1462         return ODBC_SUCCESS;
1463 }
1464
1465 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
1466 {
1467         int res;
1468         SQLINTEGER err;
1469         short int mlen;
1470         unsigned char msg[200], state[10];
1471 #ifdef NEEDTRACE
1472         SQLINTEGER enable = 1;
1473         char *tracefile = "/tmp/odbc.trace";
1474 #endif
1475         ast_mutex_lock(&obj->lock);
1476
1477         if (obj->up) {
1478                 odbc_obj_disconnect(obj);
1479                 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
1480         } else {
1481                 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
1482         }
1483
1484         res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
1485
1486         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1487                 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
1488                 obj->parent->last_negative_connect = ast_tvnow();
1489                 ast_mutex_unlock(&obj->lock);
1490                 return ODBC_FAIL;
1491         }
1492         SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1493         SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1494 #ifdef NEEDTRACE
1495         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
1496         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
1497 #endif
1498
1499         res = SQLConnect(obj->con,
1500                    (SQLCHAR *) obj->parent->dsn, SQL_NTS,
1501                    (SQLCHAR *) obj->parent->username, SQL_NTS,
1502                    (SQLCHAR *) obj->parent->password, SQL_NTS);
1503
1504         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1505                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
1506                 obj->parent->last_negative_connect = ast_tvnow();
1507                 ast_mutex_unlock(&obj->lock);
1508                 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
1509                 return ODBC_FAIL;
1510         } else {
1511                 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
1512                 obj->up = 1;
1513                 obj->last_used = ast_tvnow();
1514         }
1515
1516         ast_mutex_unlock(&obj->lock);
1517         return ODBC_SUCCESS;
1518 }
1519
1520 static int acf_transaction_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1521 {
1522         AST_DECLARE_APP_ARGS(args,
1523                 AST_APP_ARG(property);
1524                 AST_APP_ARG(opt);
1525         );
1526         struct odbc_txn_frame *tx;
1527
1528         AST_STANDARD_APP_ARGS(args, data);
1529         if (strcasecmp(args.property, "transaction") == 0) {
1530                 if ((tx = find_transaction(chan, NULL, NULL, 1))) {
1531                         ast_copy_string(buf, tx->name, len);
1532                         return 0;
1533                 }
1534         } else if (strcasecmp(args.property, "isolation") == 0) {
1535                 if (!ast_strlen_zero(args.opt)) {
1536                         tx = find_transaction(chan, NULL, args.opt, 0);
1537                 } else {
1538                         tx = find_transaction(chan, NULL, NULL, 1);
1539                 }
1540                 if (tx) {
1541                         ast_copy_string(buf, isolation2text(tx->isolation), len);
1542                         return 0;
1543                 }
1544         } else if (strcasecmp(args.property, "forcecommit") == 0) {
1545                 if (!ast_strlen_zero(args.opt)) {
1546                         tx = find_transaction(chan, NULL, args.opt, 0);
1547                 } else {
1548                         tx = find_transaction(chan, NULL, NULL, 1);
1549                 }
1550                 if (tx) {
1551                         ast_copy_string(buf, tx->forcecommit ? "1" : "0", len);
1552                         return 0;
1553                 }
1554         }
1555         return -1;
1556 }
1557
1558 static int acf_transaction_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
1559 {
1560         AST_DECLARE_APP_ARGS(args,
1561                 AST_APP_ARG(property);
1562                 AST_APP_ARG(opt);
1563         );
1564         struct odbc_txn_frame *tx;
1565         SQLINTEGER nativeerror=0, numfields=0;
1566         SQLSMALLINT diagbytes=0, i;
1567         unsigned char state[10], diagnostic[256];
1568
1569         AST_STANDARD_APP_ARGS(args, s);
1570         if (strcasecmp(args.property, "transaction") == 0) {
1571                 /* Set active transaction */
1572                 struct odbc_obj *obj;
1573                 if ((tx = find_transaction(chan, NULL, value, 0))) {
1574                         mark_transaction_active(chan, tx);
1575                 } else {
1576                         /* No such transaction, create one */
1577                         struct ast_flags flags = { RES_ODBC_INDEPENDENT_CONNECTION };
1578                         if (ast_strlen_zero(args.opt) || !(obj = ast_odbc_request_obj2(args.opt, flags))) {
1579                                 ast_log(LOG_ERROR, "Could not create transaction: invalid database specification '%s'\n", S_OR(args.opt, ""));
1580                                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_DB");
1581                                 return -1;
1582                         }
1583                         if (!(tx = find_transaction(chan, obj, value, 0))) {
1584                                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1585                                 return -1;
1586                         }
1587                         obj->tx = 1;
1588                 }
1589                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1590                 return 0;
1591         } else if (strcasecmp(args.property, "forcecommit") == 0) {
1592                 /* Set what happens when an uncommitted transaction ends without explicit Commit or Rollback */
1593                 if (ast_strlen_zero(args.opt)) {
1594                         tx = find_transaction(chan, NULL, NULL, 1);
1595                 } else {
1596                         tx = find_transaction(chan, NULL, args.opt, 0);
1597                 }
1598                 if (!tx) {
1599                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1600                         return -1;
1601                 }
1602                 if (ast_true(value)) {
1603                         tx->forcecommit = 1;
1604                 } else if (ast_false(value)) {
1605                         tx->forcecommit = 0;
1606                 } else {
1607                         ast_log(LOG_ERROR, "Invalid value for forcecommit: '%s'\n", S_OR(value, ""));
1608                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1609                         return -1;
1610                 }
1611
1612                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1613                 return 0;
1614         } else if (strcasecmp(args.property, "isolation") == 0) {
1615                 /* How do uncommitted transactions affect reads? */
1616                 int isolation = text2isolation(value);
1617                 if (ast_strlen_zero(args.opt)) {
1618                         tx = find_transaction(chan, NULL, NULL, 1);
1619                 } else {
1620                         tx = find_transaction(chan, NULL, args.opt, 0);
1621                 }
1622                 if (!tx) {
1623                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1624                         return -1;
1625                 }
1626                 if (isolation == 0) {
1627                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1628                         ast_log(LOG_ERROR, "Invalid isolation specification: '%s'\n", S_OR(value, ""));
1629                 } else if (SQLSetConnectAttr(tx->obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)isolation, 0) == SQL_ERROR) {
1630                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "SQL_ERROR");
1631                         SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1632                         for (i = 0; i < numfields; i++) {
1633                                 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1634                                 ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1635                                 if (i > 10) {
1636                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1637                                         break;
1638                                 }
1639                         }
1640                 } else {
1641                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1642                         tx->isolation = isolation;
1643                 }
1644                 return 0;
1645         } else {
1646                 ast_log(LOG_ERROR, "Unknown property: '%s'\n", args.property);
1647                 return -1;
1648         }
1649 }
1650
1651 static struct ast_custom_function odbc_function = {
1652         .name = "ODBC",
1653         .read = acf_transaction_read,
1654         .write = acf_transaction_write,
1655 };
1656
1657 static const char * const app_commit = "ODBC_Commit";
1658 static const char * const app_rollback = "ODBC_Rollback";
1659
1660 /*!
1661  * \internal
1662  * \brief Implements the channels provider.
1663  */
1664 static int data_odbc_provider_handler(const struct ast_data_search *search,
1665                 struct ast_data *root)
1666 {
1667         struct ao2_iterator aoi, aoi2;
1668         struct odbc_class *class;
1669         struct odbc_obj *current;
1670         struct ast_data *data_odbc_class, *data_odbc_connections, *data_odbc_connection;
1671         struct ast_data *enum_node;
1672         int count;
1673
1674         aoi = ao2_iterator_init(class_container, 0);
1675         while ((class = ao2_iterator_next(&aoi))) {
1676                 data_odbc_class = ast_data_add_node(root, "class");
1677                 if (!data_odbc_class) {
1678                         ao2_ref(class, -1);
1679                         continue;
1680                 }
1681
1682                 ast_data_add_structure(odbc_class, data_odbc_class, class);
1683
1684                 if (!ao2_container_count(class->obj_container)) {
1685                         ao2_ref(class, -1);
1686                         continue;
1687                 }
1688
1689                 data_odbc_connections = ast_data_add_node(data_odbc_class, "connections");
1690                 if (!data_odbc_connections) {
1691                         ao2_ref(class, -1);
1692                         continue;
1693                 }
1694
1695                 ast_data_add_bool(data_odbc_class, "shared", !class->haspool);
1696                 /* isolation */
1697                 enum_node = ast_data_add_node(data_odbc_class, "isolation");
1698                 if (!enum_node) {
1699                         ao2_ref(class, -1);
1700                         continue;
1701                 }
1702                 ast_data_add_int(enum_node, "value", class->isolation);
1703                 ast_data_add_str(enum_node, "text", isolation2text(class->isolation));
1704
1705                 count = 0;
1706                 aoi2 = ao2_iterator_init(class->obj_container, 0);
1707                 while ((current = ao2_iterator_next(&aoi2))) {
1708                         data_odbc_connection = ast_data_add_node(data_odbc_connections, "connection");
1709                         if (!data_odbc_connection) {
1710                                 ao2_ref(current, -1);
1711                                 continue;
1712                         }
1713
1714                         ast_mutex_lock(&current->lock);
1715                         ast_data_add_str(data_odbc_connection, "status", current->used ? "in use" :
1716                                         current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
1717                         ast_data_add_bool(data_odbc_connection, "transactional", current->tx);
1718                         ast_mutex_unlock(&current->lock);
1719
1720                         if (class->haspool) {
1721                                 ast_data_add_int(data_odbc_connection, "number", ++count);
1722                         }
1723
1724                         ao2_ref(current, -1);
1725                 }
1726                 ao2_iterator_destroy(&aoi2);
1727                 ao2_ref(class, -1);
1728
1729                 if (!ast_data_search_match(search, data_odbc_class)) {
1730                         ast_data_remove_node(root, data_odbc_class);
1731                 }
1732         }
1733         ao2_iterator_destroy(&aoi);
1734         return 0;
1735 }
1736
1737 /*!
1738  * \internal
1739  * \brief /asterisk/res/odbc/listprovider.
1740  */
1741 static const struct ast_data_handler odbc_provider = {
1742         .version = AST_DATA_HANDLER_VERSION,
1743         .get = data_odbc_provider_handler
1744 };
1745
1746 static const struct ast_data_entry odbc_providers[] = {
1747         AST_DATA_ENTRY("/asterisk/res/odbc", &odbc_provider),
1748 };
1749
1750 static int reload(void)
1751 {
1752         struct odbc_cache_tables *table;
1753         struct odbc_class *class;
1754         struct odbc_obj *current;
1755         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
1756
1757         /* First, mark all to be purged */
1758         while ((class = ao2_iterator_next(&aoi))) {
1759                 class->delme = 1;
1760                 ao2_ref(class, -1);
1761         }
1762         ao2_iterator_destroy(&aoi);
1763
1764         load_odbc_config();
1765
1766         /* Purge remaining classes */
1767
1768         /* Note on how this works; this is a case of circular references, so we
1769          * explicitly do NOT want to use a callback here (or we wind up in
1770          * recursive hell).
1771          *
1772          * 1. Iterate through all the classes.  Note that the classes will currently
1773          * contain two classes of the same name, one of which is marked delme and
1774          * will be purged when all remaining objects of the class are released, and
1775          * the other, which was created above when we re-parsed the config file.
1776          * 2. On each class, there is a reference held by the master container and
1777          * a reference held by each connection object.  There are two cases for
1778          * destruction of the class, noted below.  However, in all cases, all O-refs
1779          * (references to objects) will first be freed, which will cause the C-refs
1780          * (references to classes) to be decremented (but never to 0, because the
1781          * class container still has a reference).
1782          *    a) If the class has outstanding objects, the C-ref by the class
1783          *    container will then be freed, which leaves only C-refs by any
1784          *    outstanding objects.  When the final outstanding object is released
1785          *    (O-refs held by applications and dialplan functions), it will in turn
1786          *    free the final C-ref, causing class destruction.
1787          *    b) If the class has no outstanding objects, when the class container
1788          *    removes the final C-ref, the class will be destroyed.
1789          */
1790         aoi = ao2_iterator_init(class_container, 0);
1791         while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
1792                 if (class->delme) {
1793                         struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
1794                         while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
1795                                 ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
1796                                 ao2_ref(current, -1); /* O-ref-- (by iterator) */
1797                                 /* At this point, either
1798                                  * a) there's an outstanding O-ref, or
1799                                  * b) the object has already been destroyed.
1800                                  */
1801                         }
1802                         ao2_iterator_destroy(&aoi2);
1803                         ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
1804                         /* At this point, either
1805                          * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
1806                          * b) the last remaining C-ref is held by the iterator, which will be
1807                          * destroyed in the next step.
1808                          */
1809                 }
1810                 ao2_ref(class, -1); /* C-ref-- (by iterator) */
1811         }
1812         ao2_iterator_destroy(&aoi);
1813
1814         /* Empty the cache; it will get rebuilt the next time the tables are needed. */
1815         AST_RWLIST_WRLOCK(&odbc_tables);
1816         while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
1817                 destroy_table_cache(table);
1818         }
1819         AST_RWLIST_UNLOCK(&odbc_tables);
1820
1821         return 0;
1822 }
1823
1824 static int unload_module(void)
1825 {
1826         /* Prohibit unloading */
1827         return -1;
1828 }
1829
1830 static int load_module(void)
1831 {
1832         if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
1833                 return AST_MODULE_LOAD_DECLINE;
1834         if (load_odbc_config() == -1)
1835                 return AST_MODULE_LOAD_DECLINE;
1836         ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
1837         ast_data_register_multiple(odbc_providers, ARRAY_LEN(odbc_providers));
1838         ast_register_application_xml(app_commit, commit_exec);
1839         ast_register_application_xml(app_rollback, rollback_exec);
1840         ast_custom_function_register(&odbc_function);
1841         ast_log(LOG_NOTICE, "res_odbc loaded.\n");
1842         return 0;
1843 }
1844
1845 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "ODBC resource",
1846                 .load = load_module,
1847                 .unload = unload_module,
1848                 .reload = reload,
1849                 .load_pri = AST_MODPRI_REALTIME_DEPEND,
1850                );