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