1770bb303267abb08b0e74f797b247b9b5f5164b
[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 = ao2_iterator_init(class_container, 0);
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                 while ((class = ao2_iterator_next(&aoi))) {
934                         if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
935                                 ret = ast_strdup(class->name);
936                         }
937                         ao2_ref(class, -1);
938                         if (ret) {
939                                 break;
940                         }
941                 }
942                 ao2_iterator_destroy(&aoi);
943                 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
944                         ret = ast_strdup("all");
945                 }
946                 return ret;
947         }
948
949         ast_cli(a->fd, "\nODBC DSN Settings\n");
950         ast_cli(a->fd,   "-----------------\n\n");
951         aoi = ao2_iterator_init(class_container, 0);
952         while ((class = ao2_iterator_next(&aoi))) {
953                 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
954                         int count = 0;
955                         char timestr[80];
956                         struct ast_tm tm;
957
958                         ast_localtime(&class->last_negative_connect, &tm, NULL);
959                         ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
960                         ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
961                         ast_cli(a->fd, "    Last connection attempt: %s\n", timestr);
962
963                         if (class->haspool) {
964                                 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
965
966                                 ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);
967
968                                 while ((current = ao2_iterator_next(&aoi2))) {
969                                         ast_mutex_lock(&current->lock);
970 #ifdef DEBUG_THREADS
971                                         ast_cli(a->fd, "    - Connection %d: %s (%s:%d %s)\n", ++count,
972                                                 current->used ? "in use" :
973                                                 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
974                                                 current->file, current->lineno, current->function);
975 #else
976                                         ast_cli(a->fd, "    - Connection %d: %s\n", ++count,
977                                                 current->used ? "in use" :
978                                                 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
979 #endif
980                                         ast_mutex_unlock(&current->lock);
981                                         ao2_ref(current, -1);
982                                 }
983                                 ao2_iterator_destroy(&aoi2);
984                         } else {
985                                 /* Should only ever be one of these (unless there are transactions) */
986                                 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
987                                 while ((current = ao2_iterator_next(&aoi2))) {
988                                         ast_cli(a->fd, "  Pooled: No\n  Connected: %s\n", current->used ? "In use" :
989                                                 current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
990                                         ao2_ref(current, -1);
991                                 }
992                                 ao2_iterator_destroy(&aoi2);
993                         }
994                         ast_cli(a->fd, "\n");
995                 }
996                 ao2_ref(class, -1);
997         }
998         ao2_iterator_destroy(&aoi);
999
1000         return CLI_SUCCESS;
1001 }
1002
1003 static struct ast_cli_entry cli_odbc[] = {
1004         AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
1005 };
1006
1007 static int odbc_register_class(struct odbc_class *class, int preconnect)
1008 {
1009         struct odbc_obj *obj;
1010         if (class) {
1011                 ao2_link(class_container, class);
1012                 /* I still have a reference in the caller, so a deref is NOT missing here. */
1013
1014                 if (preconnect) {
1015                         /* Request and release builds a connection */
1016                         obj = ast_odbc_request_obj(class->name, 0);
1017                         if (obj) {
1018                                 ast_odbc_release_obj(obj);
1019                         }
1020                 }
1021
1022                 return 0;
1023         } else {
1024                 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
1025                 return -1;
1026         }
1027 }
1028
1029 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx)
1030 {
1031         SQLINTEGER nativeerror=0, numfields=0;
1032         SQLSMALLINT diagbytes=0, i;
1033         unsigned char state[10], diagnostic[256];
1034
1035         ast_debug(2, "odbc_release_obj2(%p) called (obj->txf = %p)\n", obj, obj->txf);
1036         if (tx) {
1037                 ast_debug(1, "called on a transactional handle with %s\n", tx->forcecommit ? "COMMIT" : "ROLLBACK");
1038                 if (SQLEndTran(SQL_HANDLE_DBC, obj->con, tx->forcecommit ? SQL_COMMIT : SQL_ROLLBACK) == SQL_ERROR) {
1039                         /* Handle possible transaction commit failure */
1040                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1041                         for (i = 0; i < numfields; i++) {
1042                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1043                                 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1044                                 if (!strcmp((char *)state, "25S02") || !strcmp((char *)state, "08007")) {
1045                                         /* These codes mean that a commit failed and a transaction
1046                                          * is still active. We must rollback, or things will get
1047                                          * very, very weird for anybody using the handle next. */
1048                                         SQLEndTran(SQL_HANDLE_DBC, obj->con, SQL_ROLLBACK);
1049                                 }
1050                                 if (i > 10) {
1051                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1052                                         break;
1053                                 }
1054                         }
1055                 }
1056
1057                 /* Transaction is done, reset autocommit */
1058                 if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1059                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1060                         for (i = 0; i < numfields; i++) {
1061                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1062                                 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1063                                 if (i > 10) {
1064                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1065                                         break;
1066                                 }
1067                         }
1068                 }
1069         }
1070
1071 #ifdef DEBUG_THREADS
1072         obj->file[0] = '\0';
1073         obj->function[0] = '\0';
1074         obj->lineno = 0;
1075 #endif
1076
1077         /* For pooled connections, this frees the connection to be
1078          * reused.  For non-pooled connections, it does nothing. */
1079         obj->used = 0;
1080         if (obj->txf) {
1081                 /* Prevent recursion -- transaction is already closed out. */
1082                 obj->txf->obj = NULL;
1083                 obj->txf = release_transaction(obj->txf);
1084         }
1085         ao2_ref(obj, -1);
1086 }
1087
1088 void ast_odbc_release_obj(struct odbc_obj *obj)
1089 {
1090         struct odbc_txn_frame *tx = find_transaction(NULL, obj, NULL, 0);
1091         odbc_release_obj2(obj, tx);
1092 }
1093
1094 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
1095 {
1096         return obj->parent->backslash_is_escape;
1097 }
1098
1099 static int commit_exec(struct ast_channel *chan, const char *data)
1100 {
1101         struct odbc_txn_frame *tx;
1102         SQLINTEGER nativeerror=0, numfields=0;
1103         SQLSMALLINT diagbytes=0, i;
1104         unsigned char state[10], diagnostic[256];
1105
1106         if (ast_strlen_zero(data)) {
1107                 tx = find_transaction(chan, NULL, NULL, 1);
1108         } else {
1109                 tx = find_transaction(chan, NULL, data, 0);
1110         }
1111
1112         pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", "OK");
1113
1114         if (tx) {
1115                 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_COMMIT) == SQL_ERROR) {
1116                         struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1117                         ast_str_reset(errors);
1118
1119                         /* Handle possible transaction commit failure */
1120                         SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1121                         for (i = 0; i < numfields; i++) {
1122                                 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1123                                 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1124                                 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1125                                 if (i > 10) {
1126                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1127                                         break;
1128                                 }
1129                         }
1130                         pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", ast_str_buffer(errors));
1131                 }
1132         }
1133         return 0;
1134 }
1135
1136 static int rollback_exec(struct ast_channel *chan, const char *data)
1137 {
1138         struct odbc_txn_frame *tx;
1139         SQLINTEGER nativeerror=0, numfields=0;
1140         SQLSMALLINT diagbytes=0, i;
1141         unsigned char state[10], diagnostic[256];
1142
1143         if (ast_strlen_zero(data)) {
1144                 tx = find_transaction(chan, NULL, NULL, 1);
1145         } else {
1146                 tx = find_transaction(chan, NULL, data, 0);
1147         }
1148
1149         pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", "OK");
1150
1151         if (tx) {
1152                 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_ROLLBACK) == SQL_ERROR) {
1153                         struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1154                         ast_str_reset(errors);
1155
1156                         /* Handle possible transaction commit failure */
1157                         SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1158                         for (i = 0; i < numfields; i++) {
1159                                 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1160                                 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1161                                 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1162                                 if (i > 10) {
1163                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1164                                         break;
1165                                 }
1166                         }
1167                         pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", ast_str_buffer(errors));
1168                 }
1169         }
1170         return 0;
1171 }
1172
1173 static int aoro2_class_cb(void *obj, void *arg, int flags)
1174 {
1175         struct odbc_class *class = obj;
1176         char *name = arg;
1177         if (!strcmp(class->name, name) && !class->delme) {
1178                 return CMP_MATCH | CMP_STOP;
1179         }
1180         return 0;
1181 }
1182
1183 #define USE_TX (void *)(long)1
1184 #define NO_TX  (void *)(long)2
1185 #define EOR_TX (void *)(long)3
1186
1187 static int aoro2_obj_cb(void *vobj, void *arg, int flags)
1188 {
1189         struct odbc_obj *obj = vobj;
1190         ast_mutex_lock(&obj->lock);
1191         if ((arg == NO_TX && !obj->tx) || (arg == EOR_TX && !obj->used) || (arg == USE_TX && obj->tx && !obj->used)) {
1192                 obj->used = 1;
1193                 ast_mutex_unlock(&obj->lock);
1194                 return CMP_MATCH | CMP_STOP;
1195         }
1196         ast_mutex_unlock(&obj->lock);
1197         return 0;
1198 }
1199
1200 struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
1201 {
1202         struct odbc_obj *obj = NULL;
1203         struct odbc_class *class;
1204         SQLINTEGER nativeerror=0, numfields=0;
1205         SQLSMALLINT diagbytes=0, i;
1206         unsigned char state[10], diagnostic[256];
1207
1208         if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
1209                 ast_debug(1, "Class '%s' not found!\n", name);
1210                 return NULL;
1211         }
1212
1213         ast_assert(ao2_ref(class, 0) > 1);
1214
1215         if (class->haspool) {
1216                 /* Recycle connections before building another */
1217                 obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, EOR_TX);
1218
1219                 if (obj) {
1220                         ast_assert(ao2_ref(obj, 0) > 1);
1221                 }
1222                 if (!obj && (ast_atomic_fetchadd_int(&class->count, +1) < class->limit) &&
1223                                 (time(NULL) > class->last_negative_connect.tv_sec + class->negative_connection_cache.tv_sec)) {
1224                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1225                         if (!obj) {
1226                                 class->count--;
1227                                 ao2_ref(class, -1);
1228                                 ast_debug(3, "Unable to allocate object\n");
1229                                 ast_atomic_fetchadd_int(&class->count, -1);
1230                                 return NULL;
1231                         }
1232                         ast_assert(ao2_ref(obj, 0) == 1);
1233                         ast_mutex_init(&obj->lock);
1234                         /* obj inherits the outstanding reference to class */
1235                         obj->parent = class;
1236                         class = NULL;
1237                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
1238                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1239                                 ast_assert(ao2_ref(obj->parent, 0) > 0);
1240                                 /* Because it was never within the container, we have to manually decrement the count here */
1241                                 ast_atomic_fetchadd_int(&obj->parent->count, -1);
1242                                 ao2_ref(obj, -1);
1243                                 obj = NULL;
1244                         } else {
1245                                 obj->used = 1;
1246                                 ao2_link(obj->parent->obj_container, obj);
1247                         }
1248                 } else {
1249                         /* If construction fails due to the limit (or negative timecache), reverse our increment. */
1250                         if (!obj) {
1251                                 ast_atomic_fetchadd_int(&class->count, -1);
1252                         }
1253                         /* Object is not constructed, so delete outstanding reference to class. */
1254                         ao2_ref(class, -1);
1255                         class = NULL;
1256                 }
1257
1258                 if (obj && ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1259                         /* Ensure this connection has autocommit turned off. */
1260                         if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1261                                 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1262                                 for (i = 0; i < numfields; i++) {
1263                                         SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1264                                         ast_log(LOG_WARNING, "SQLSetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1265                                         if (i > 10) {
1266                                                 ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1267                                                 break;
1268                                         }
1269                                 }
1270                         }
1271                 }
1272         } else if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1273                 /* Non-pooled connections -- but must use a separate connection handle */
1274                 if (!(obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, USE_TX))) {
1275                         ast_debug(1, "Object not found\n");
1276                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1277                         if (!obj) {
1278                                 ao2_ref(class, -1);
1279                                 ast_debug(3, "Unable to allocate object\n");
1280                                 return NULL;
1281                         }
1282                         ast_mutex_init(&obj->lock);
1283                         /* obj inherits the outstanding reference to class */
1284                         obj->parent = class;
1285                         class = NULL;
1286                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
1287                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1288                                 ao2_ref(obj, -1);
1289                                 obj = NULL;
1290                         } else {
1291                                 obj->used = 1;
1292                                 ao2_link(obj->parent->obj_container, obj);
1293                                 ast_atomic_fetchadd_int(&obj->parent->count, +1);
1294                         }
1295                 }
1296
1297                 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1298                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1299                         for (i = 0; i < numfields; i++) {
1300                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1301                                 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1302                                 if (i > 10) {
1303                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1304                                         break;
1305                                 }
1306                         }
1307                 }
1308         } else {
1309                 /* Non-pooled connection: multiple modules can use the same connection. */
1310                 if ((obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, NO_TX))) {
1311                         /* Object is not constructed, so delete outstanding reference to class. */
1312                         ast_assert(ao2_ref(class, 0) > 1);
1313                         ao2_ref(class, -1);
1314                         class = NULL;
1315                 } else {
1316                         /* No entry: build one */
1317                         if (!(obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor))) {
1318                                 ast_assert(ao2_ref(class, 0) > 1);
1319                                 ao2_ref(class, -1);
1320                                 ast_debug(3, "Unable to allocate object\n");
1321                                 return NULL;
1322                         }
1323                         ast_mutex_init(&obj->lock);
1324                         /* obj inherits the outstanding reference to class */
1325                         obj->parent = class;
1326                         class = NULL;
1327                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
1328                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1329                                 ao2_ref(obj, -1);
1330                                 obj = NULL;
1331                         } else {
1332                                 ao2_link(obj->parent->obj_container, obj);
1333                                 ast_assert(ao2_ref(obj, 0) > 1);
1334                         }
1335                 }
1336
1337                 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1338                         SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1339                         for (i = 0; i < numfields; i++) {
1340                                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1341                                 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1342                                 if (i > 10) {
1343                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1344                                         break;
1345                                 }
1346                         }
1347                 }
1348         }
1349
1350         /* Set the isolation property */
1351         if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)obj->parent->isolation, 0) == SQL_ERROR) {
1352                 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1353                 for (i = 0; i < numfields; i++) {
1354                         SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1355                         ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1356                         if (i > 10) {
1357                                 ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1358                                 break;
1359                         }
1360                 }
1361         }
1362
1363         if (obj && ast_test_flag(&flags, RES_ODBC_CONNECTED) && !obj->up) {
1364                 /* Check if this connection qualifies for reconnection, with negative connection cache time */
1365                 if (time(NULL) > obj->parent->last_negative_connect.tv_sec + obj->parent->negative_connection_cache.tv_sec) {
1366                         odbc_obj_connect(obj);
1367                 }
1368         } else if (obj && ast_test_flag(&flags, RES_ODBC_SANITY_CHECK)) {
1369                 ast_odbc_sanity_check(obj);
1370         } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck) {
1371                 odbc_obj_connect(obj);
1372         }
1373
1374 #ifdef DEBUG_THREADS
1375         if (obj) {
1376                 ast_copy_string(obj->file, file, sizeof(obj->file));
1377                 ast_copy_string(obj->function, function, sizeof(obj->function));
1378                 obj->lineno = lineno;
1379         }
1380 #endif
1381         ast_assert(class == NULL);
1382
1383         if (obj) {
1384                 ast_assert(ao2_ref(obj, 0) > 1);
1385         }
1386         return obj;
1387 }
1388
1389 struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
1390 {
1391         struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
1392         return _ast_odbc_request_obj2(name, flags, file, function, lineno);
1393 }
1394
1395 struct odbc_obj *ast_odbc_retrieve_transaction_obj(struct ast_channel *chan, const char *objname)
1396 {
1397         struct ast_datastore *txn_store;
1398         AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
1399         struct odbc_txn_frame *txn = NULL;
1400
1401         if (!chan) {
1402                 /* No channel == no transaction */
1403                 return NULL;
1404         }
1405
1406         ast_channel_lock(chan);
1407         if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
1408                 oldlist = txn_store->data;
1409         } else {
1410                 ast_channel_unlock(chan);
1411                 return NULL;
1412         }
1413
1414         AST_LIST_LOCK(oldlist);
1415         ast_channel_unlock(chan);
1416
1417         AST_LIST_TRAVERSE(oldlist, txn, list) {
1418                 if (txn->obj && txn->obj->parent && !strcmp(txn->obj->parent->name, objname)) {
1419                         AST_LIST_UNLOCK(oldlist);
1420                         return txn->obj;
1421                 }
1422         }
1423         AST_LIST_UNLOCK(oldlist);
1424         return NULL;
1425 }
1426
1427 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
1428 {
1429         int res;
1430         SQLINTEGER err;
1431         short int mlen;
1432         unsigned char msg[200], state[10];
1433
1434         /* Nothing to disconnect */
1435         if (!obj->con) {
1436                 return ODBC_SUCCESS;
1437         }
1438
1439         ast_mutex_lock(&obj->lock);
1440
1441         res = SQLDisconnect(obj->con);
1442
1443         if (obj->parent) {
1444                 if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
1445                         ast_debug(1, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
1446                 } else {
1447                         ast_debug(1, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
1448                 }
1449         }
1450
1451         if ((res = SQLFreeHandle(SQL_HANDLE_DBC, obj->con) == SQL_SUCCESS)) {
1452                 obj->con = NULL;
1453                 ast_debug(1, "Database handle deallocated\n");
1454         } else {
1455                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
1456                 ast_log(LOG_WARNING, "Unable to deallocate database handle? %d errno=%d %s\n", res, (int)err, msg);
1457         }
1458
1459         obj->up = 0;
1460         ast_mutex_unlock(&obj->lock);
1461         return ODBC_SUCCESS;
1462 }
1463
1464 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
1465 {
1466         int res;
1467         SQLINTEGER err;
1468         short int mlen;
1469         unsigned char msg[200], state[10];
1470 #ifdef NEEDTRACE
1471         SQLINTEGER enable = 1;
1472         char *tracefile = "/tmp/odbc.trace";
1473 #endif
1474         ast_mutex_lock(&obj->lock);
1475
1476         if (obj->up) {
1477                 odbc_obj_disconnect(obj);
1478                 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
1479         } else {
1480                 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
1481         }
1482
1483         res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
1484
1485         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1486                 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
1487                 obj->parent->last_negative_connect = ast_tvnow();
1488                 ast_mutex_unlock(&obj->lock);
1489                 return ODBC_FAIL;
1490         }
1491         SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1492         SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1493 #ifdef NEEDTRACE
1494         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
1495         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
1496 #endif
1497
1498         res = SQLConnect(obj->con,
1499                    (SQLCHAR *) obj->parent->dsn, SQL_NTS,
1500                    (SQLCHAR *) obj->parent->username, SQL_NTS,
1501                    (SQLCHAR *) obj->parent->password, SQL_NTS);
1502
1503         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1504                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
1505                 obj->parent->last_negative_connect = ast_tvnow();
1506                 ast_mutex_unlock(&obj->lock);
1507                 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
1508                 return ODBC_FAIL;
1509         } else {
1510                 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
1511                 obj->up = 1;
1512                 obj->last_used = ast_tvnow();
1513         }
1514
1515         ast_mutex_unlock(&obj->lock);
1516         return ODBC_SUCCESS;
1517 }
1518
1519 static int acf_transaction_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1520 {
1521         AST_DECLARE_APP_ARGS(args,
1522                 AST_APP_ARG(property);
1523                 AST_APP_ARG(opt);
1524         );
1525         struct odbc_txn_frame *tx;
1526
1527         AST_STANDARD_APP_ARGS(args, data);
1528         if (strcasecmp(args.property, "transaction") == 0) {
1529                 if ((tx = find_transaction(chan, NULL, NULL, 1))) {
1530                         ast_copy_string(buf, tx->name, len);
1531                         return 0;
1532                 }
1533         } else if (strcasecmp(args.property, "isolation") == 0) {
1534                 if (!ast_strlen_zero(args.opt)) {
1535                         tx = find_transaction(chan, NULL, args.opt, 0);
1536                 } else {
1537                         tx = find_transaction(chan, NULL, NULL, 1);
1538                 }
1539                 if (tx) {
1540                         ast_copy_string(buf, isolation2text(tx->isolation), len);
1541                         return 0;
1542                 }
1543         } else if (strcasecmp(args.property, "forcecommit") == 0) {
1544                 if (!ast_strlen_zero(args.opt)) {
1545                         tx = find_transaction(chan, NULL, args.opt, 0);
1546                 } else {
1547                         tx = find_transaction(chan, NULL, NULL, 1);
1548                 }
1549                 if (tx) {
1550                         ast_copy_string(buf, tx->forcecommit ? "1" : "0", len);
1551                         return 0;
1552                 }
1553         }
1554         return -1;
1555 }
1556
1557 static int acf_transaction_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
1558 {
1559         AST_DECLARE_APP_ARGS(args,
1560                 AST_APP_ARG(property);
1561                 AST_APP_ARG(opt);
1562         );
1563         struct odbc_txn_frame *tx;
1564         SQLINTEGER nativeerror=0, numfields=0;
1565         SQLSMALLINT diagbytes=0, i;
1566         unsigned char state[10], diagnostic[256];
1567
1568         AST_STANDARD_APP_ARGS(args, s);
1569         if (strcasecmp(args.property, "transaction") == 0) {
1570                 /* Set active transaction */
1571                 struct odbc_obj *obj;
1572                 if ((tx = find_transaction(chan, NULL, value, 0))) {
1573                         mark_transaction_active(chan, tx);
1574                 } else {
1575                         /* No such transaction, create one */
1576                         struct ast_flags flags = { RES_ODBC_INDEPENDENT_CONNECTION };
1577                         if (ast_strlen_zero(args.opt) || !(obj = ast_odbc_request_obj2(args.opt, flags))) {
1578                                 ast_log(LOG_ERROR, "Could not create transaction: invalid database specification '%s'\n", S_OR(args.opt, ""));
1579                                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_DB");
1580                                 return -1;
1581                         }
1582                         if (!(tx = find_transaction(chan, obj, value, 0))) {
1583                                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1584                                 return -1;
1585                         }
1586                         obj->tx = 1;
1587                 }
1588                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1589                 return 0;
1590         } else if (strcasecmp(args.property, "forcecommit") == 0) {
1591                 /* Set what happens when an uncommitted transaction ends without explicit Commit or Rollback */
1592                 if (ast_strlen_zero(args.opt)) {
1593                         tx = find_transaction(chan, NULL, NULL, 1);
1594                 } else {
1595                         tx = find_transaction(chan, NULL, args.opt, 0);
1596                 }
1597                 if (!tx) {
1598                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1599                         return -1;
1600                 }
1601                 if (ast_true(value)) {
1602                         tx->forcecommit = 1;
1603                 } else if (ast_false(value)) {
1604                         tx->forcecommit = 0;
1605                 } else {
1606                         ast_log(LOG_ERROR, "Invalid value for forcecommit: '%s'\n", S_OR(value, ""));
1607                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1608                         return -1;
1609                 }
1610
1611                 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1612                 return 0;
1613         } else if (strcasecmp(args.property, "isolation") == 0) {
1614                 /* How do uncommitted transactions affect reads? */
1615                 int isolation = text2isolation(value);
1616                 if (ast_strlen_zero(args.opt)) {
1617                         tx = find_transaction(chan, NULL, NULL, 1);
1618                 } else {
1619                         tx = find_transaction(chan, NULL, args.opt, 0);
1620                 }
1621                 if (!tx) {
1622                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1623                         return -1;
1624                 }
1625                 if (isolation == 0) {
1626                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1627                         ast_log(LOG_ERROR, "Invalid isolation specification: '%s'\n", S_OR(value, ""));
1628                 } else if (SQLSetConnectAttr(tx->obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)isolation, 0) == SQL_ERROR) {
1629                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "SQL_ERROR");
1630                         SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1631                         for (i = 0; i < numfields; i++) {
1632                                 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1633                                 ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1634                                 if (i > 10) {
1635                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
1636                                         break;
1637                                 }
1638                         }
1639                 } else {
1640                         pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1641                         tx->isolation = isolation;
1642                 }
1643                 return 0;
1644         } else {
1645                 ast_log(LOG_ERROR, "Unknown property: '%s'\n", args.property);
1646                 return -1;
1647         }
1648 }
1649
1650 static struct ast_custom_function odbc_function = {
1651         .name = "ODBC",
1652         .read = acf_transaction_read,
1653         .write = acf_transaction_write,
1654 };
1655
1656 static const char * const app_commit = "ODBC_Commit";
1657 static const char * const app_rollback = "ODBC_Rollback";
1658
1659 /*!
1660  * \internal
1661  * \brief Implements the channels provider.
1662  */
1663 static int data_odbc_provider_handler(const struct ast_data_search *search,
1664                 struct ast_data *root)
1665 {
1666         struct ao2_iterator aoi, aoi2;
1667         struct odbc_class *class;
1668         struct odbc_obj *current;
1669         struct ast_data *data_odbc_class, *data_odbc_connections, *data_odbc_connection;
1670         struct ast_data *enum_node;
1671         int count;
1672
1673         aoi = ao2_iterator_init(class_container, 0);
1674         while ((class = ao2_iterator_next(&aoi))) {
1675                 data_odbc_class = ast_data_add_node(root, "class");
1676                 if (!data_odbc_class) {
1677                         ao2_ref(class, -1);
1678                         continue;
1679                 }
1680
1681                 ast_data_add_structure(odbc_class, data_odbc_class, class);
1682
1683                 if (!ao2_container_count(class->obj_container)) {
1684                         ao2_ref(class, -1);
1685                         continue;
1686                 }
1687
1688                 data_odbc_connections = ast_data_add_node(data_odbc_class, "connections");
1689                 if (!data_odbc_connections) {
1690                         ao2_ref(class, -1);
1691                         continue;
1692                 }
1693
1694                 ast_data_add_bool(data_odbc_class, "shared", !class->haspool);
1695                 /* isolation */
1696                 enum_node = ast_data_add_node(data_odbc_class, "isolation");
1697                 if (!enum_node) {
1698                         ao2_ref(class, -1);
1699                         continue;
1700                 }
1701                 ast_data_add_int(enum_node, "value", class->isolation);
1702                 ast_data_add_str(enum_node, "text", isolation2text(class->isolation));
1703
1704                 count = 0;
1705                 aoi2 = ao2_iterator_init(class->obj_container, 0);
1706                 while ((current = ao2_iterator_next(&aoi2))) {
1707                         data_odbc_connection = ast_data_add_node(data_odbc_connections, "connection");
1708                         if (!data_odbc_connection) {
1709                                 ao2_ref(current, -1);
1710                                 continue;
1711                         }
1712
1713                         ast_mutex_lock(&current->lock);
1714                         ast_data_add_str(data_odbc_connection, "status", current->used ? "in use" :
1715                                         current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
1716                         ast_data_add_bool(data_odbc_connection, "transactional", current->tx);
1717                         ast_mutex_unlock(&current->lock);
1718
1719                         if (class->haspool) {
1720                                 ast_data_add_int(data_odbc_connection, "number", ++count);
1721                         }
1722
1723                         ao2_ref(current, -1);
1724                 }
1725                 ao2_ref(class, -1);
1726
1727                 if (!ast_data_search_match(search, data_odbc_class)) {
1728                         ast_data_remove_node(root, data_odbc_class);
1729                 }
1730         }
1731         return 0;
1732 }
1733
1734 /*!
1735  * \internal
1736  * \brief /asterisk/res/odbc/listprovider.
1737  */
1738 static const struct ast_data_handler odbc_provider = {
1739         .version = AST_DATA_HANDLER_VERSION,
1740         .get = data_odbc_provider_handler
1741 };
1742
1743 static const struct ast_data_entry odbc_providers[] = {
1744         AST_DATA_ENTRY("/asterisk/res/odbc", &odbc_provider),
1745 };
1746
1747 static int reload(void)
1748 {
1749         struct odbc_cache_tables *table;
1750         struct odbc_class *class;
1751         struct odbc_obj *current;
1752         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
1753
1754         /* First, mark all to be purged */
1755         while ((class = ao2_iterator_next(&aoi))) {
1756                 class->delme = 1;
1757                 ao2_ref(class, -1);
1758         }
1759         ao2_iterator_destroy(&aoi);
1760
1761         load_odbc_config();
1762
1763         /* Purge remaining classes */
1764
1765         /* Note on how this works; this is a case of circular references, so we
1766          * explicitly do NOT want to use a callback here (or we wind up in
1767          * recursive hell).
1768          *
1769          * 1. Iterate through all the classes.  Note that the classes will currently
1770          * contain two classes of the same name, one of which is marked delme and
1771          * will be purged when all remaining objects of the class are released, and
1772          * the other, which was created above when we re-parsed the config file.
1773          * 2. On each class, there is a reference held by the master container and
1774          * a reference held by each connection object.  There are two cases for
1775          * destruction of the class, noted below.  However, in all cases, all O-refs
1776          * (references to objects) will first be freed, which will cause the C-refs
1777          * (references to classes) to be decremented (but never to 0, because the
1778          * class container still has a reference).
1779          *    a) If the class has outstanding objects, the C-ref by the class
1780          *    container will then be freed, which leaves only C-refs by any
1781          *    outstanding objects.  When the final outstanding object is released
1782          *    (O-refs held by applications and dialplan functions), it will in turn
1783          *    free the final C-ref, causing class destruction.
1784          *    b) If the class has no outstanding objects, when the class container
1785          *    removes the final C-ref, the class will be destroyed.
1786          */
1787         aoi = ao2_iterator_init(class_container, 0);
1788         while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
1789                 if (class->delme) {
1790                         struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
1791                         while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
1792                                 ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
1793                                 ao2_ref(current, -1); /* O-ref-- (by iterator) */
1794                                 /* At this point, either
1795                                  * a) there's an outstanding O-ref, or
1796                                  * b) the object has already been destroyed.
1797                                  */
1798                         }
1799                         ao2_iterator_destroy(&aoi2);
1800                         ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
1801                         /* At this point, either
1802                          * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
1803                          * b) the last remaining C-ref is held by the iterator, which will be
1804                          * destroyed in the next step.
1805                          */
1806                 }
1807                 ao2_ref(class, -1); /* C-ref-- (by iterator) */
1808         }
1809         ao2_iterator_destroy(&aoi);
1810
1811         /* Empty the cache; it will get rebuilt the next time the tables are needed. */
1812         AST_RWLIST_WRLOCK(&odbc_tables);
1813         while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
1814                 destroy_table_cache(table);
1815         }
1816         AST_RWLIST_UNLOCK(&odbc_tables);
1817
1818         return 0;
1819 }
1820
1821 static int unload_module(void)
1822 {
1823         /* Prohibit unloading */
1824         return -1;
1825 }
1826
1827 static int load_module(void)
1828 {
1829         if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
1830                 return AST_MODULE_LOAD_DECLINE;
1831         if (load_odbc_config() == -1)
1832                 return AST_MODULE_LOAD_DECLINE;
1833         ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
1834         ast_data_register_multiple(odbc_providers, ARRAY_LEN(odbc_providers));
1835         ast_register_application_xml(app_commit, commit_exec);
1836         ast_register_application_xml(app_rollback, rollback_exec);
1837         ast_custom_function_register(&odbc_function);
1838         ast_log(LOG_NOTICE, "res_odbc loaded.\n");
1839         return 0;
1840 }
1841
1842 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "ODBC resource",
1843                 .load = load_module,
1844                 .unload = unload_module,
1845                 .reload = reload,
1846                 .load_pri = AST_MODPRI_REALTIME_DEPEND,
1847                );