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