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