res_pjsip_session: properly handle SDP from a forked call with early media
[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 /*! \li \ref res_odbc.c uses the configuration file \ref res_odbc.conf
34  * \addtogroup configuration_file Configuration Files
35  */
36
37 /*!
38  * \page res_odbc.conf res_odbc.conf
39  * \verbinclude res_odbc.conf.sample
40  */
41
42 /*** MODULEINFO
43         <depend>generic_odbc</depend>
44         <depend>res_odbc_transaction</depend>
45         <depend>ltdl</depend>
46         <support_level>core</support_level>
47  ***/
48
49 #include "asterisk.h"
50
51 #include "asterisk/file.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/config.h"
54 #include "asterisk/pbx.h"
55 #include "asterisk/module.h"
56 #include "asterisk/cli.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/res_odbc.h"
59 #include "asterisk/time.h"
60 #include "asterisk/astobj2.h"
61 #include "asterisk/app.h"
62 #include "asterisk/strings.h"
63 #include "asterisk/threadstorage.h"
64
65 struct odbc_class
66 {
67         AST_LIST_ENTRY(odbc_class) list;
68         char name[80];
69         char dsn[80];
70         char *username;
71         char *password;
72         char *sanitysql;
73         SQLHENV env;
74         unsigned int delme:1;                /*!< Purge the class */
75         unsigned int backslash_is_escape:1;  /*!< On this database, the backslash is a native escape sequence */
76         unsigned int forcecommit:1;          /*!< Should uncommitted transactions be auto-committed on handle release? */
77         unsigned int isolation;              /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
78         unsigned int conntimeout;            /*!< Maximum time the connection process should take */
79         unsigned int maxconnections;         /*!< Maximum number of allowed connections */
80         /*! When a connection fails, cache that failure for how long? */
81         struct timeval negative_connection_cache;
82         /*! When a connection fails, when did that last occur? */
83         struct timeval last_negative_connect;
84         /*! A pool of available connections */
85         AST_LIST_HEAD_NOLOCK(, odbc_obj) connections;
86         /*! Lock to protect the connections */
87         ast_mutex_t lock;
88         /*! Condition to notify any pending connection requesters */
89         ast_cond_t cond;
90         /*! The total number of current connections */
91         size_t connection_cnt;
92 };
93
94 static struct ao2_container *class_container;
95
96 static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
97
98 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
99 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
100 static void odbc_register_class(struct odbc_class *class, int connect);
101
102 AST_THREADSTORAGE(errors_buf);
103
104 struct odbc_txn_frame {
105         AST_LIST_ENTRY(odbc_txn_frame) list;
106         struct ast_channel *owner;
107         struct odbc_obj *obj;        /*!< Database handle within which transacted statements are run */
108         /*!\brief Is this record the current active transaction within the channel?
109          * Note that the active flag is really only necessary for statements which
110          * are triggered from the dialplan, as there isn't a direct correlation
111          * between multiple statements.  Applications wishing to use transactions
112          * may simply perform each statement on the same odbc_obj, which keeps the
113          * transaction persistent.
114          */
115         unsigned int active:1;
116         unsigned int forcecommit:1;     /*!< Should uncommitted transactions be auto-committed on handle release? */
117         unsigned int isolation;         /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
118         char name[0];                   /*!< Name of this transaction ID */
119 };
120
121 const char *ast_odbc_isolation2text(int iso)
122 {
123         if (iso == SQL_TXN_READ_COMMITTED) {
124                 return "read_committed";
125         } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
126                 return "read_uncommitted";
127         } else if (iso == SQL_TXN_SERIALIZABLE) {
128                 return "serializable";
129         } else if (iso == SQL_TXN_REPEATABLE_READ) {
130                 return "repeatable_read";
131         } else {
132                 return "unknown";
133         }
134 }
135
136 int ast_odbc_text2isolation(const char *txt)
137 {
138         if (strncasecmp(txt, "read_", 5) == 0) {
139                 if (strncasecmp(txt + 5, "c", 1) == 0) {
140                         return SQL_TXN_READ_COMMITTED;
141                 } else if (strncasecmp(txt + 5, "u", 1) == 0) {
142                         return SQL_TXN_READ_UNCOMMITTED;
143                 } else {
144                         return 0;
145                 }
146         } else if (strncasecmp(txt, "ser", 3) == 0) {
147                 return SQL_TXN_SERIALIZABLE;
148         } else if (strncasecmp(txt, "rep", 3) == 0) {
149                 return SQL_TXN_REPEATABLE_READ;
150         } else {
151                 return 0;
152         }
153 }
154
155 static void odbc_class_destructor(void *data)
156 {
157         struct odbc_class *class = data;
158         struct odbc_obj *obj;
159
160         /* Due to refcounts, we can safely assume that any objects with a reference
161          * to us will prevent our destruction, so we don't need to worry about them.
162          */
163         if (class->username) {
164                 ast_free(class->username);
165         }
166         if (class->password) {
167                 ast_free(class->password);
168         }
169         if (class->sanitysql) {
170                 ast_free(class->sanitysql);
171         }
172
173         while ((obj = AST_LIST_REMOVE_HEAD(&class->connections, list))) {
174                 ao2_ref(obj, -1);
175         }
176
177         SQLFreeHandle(SQL_HANDLE_ENV, class->env);
178         ast_mutex_destroy(&class->lock);
179         ast_cond_destroy(&class->cond);
180 }
181
182 static int null_hash_fn(const void *obj, const int flags)
183 {
184         return 0;
185 }
186
187 static void odbc_obj_destructor(void *data)
188 {
189         struct odbc_obj *obj = data;
190
191         odbc_obj_disconnect(obj);
192 }
193
194 static void destroy_table_cache(struct odbc_cache_tables *table)
195 {
196         struct odbc_cache_columns *col;
197
198         ast_debug(1, "Destroying table cache for %s\n", table->table);
199
200         AST_RWLIST_WRLOCK(&table->columns);
201         while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
202                 ast_free(col);
203         }
204         AST_RWLIST_UNLOCK(&table->columns);
205         AST_RWLIST_HEAD_DESTROY(&table->columns);
206
207         ast_free(table);
208 }
209
210 /*!
211  * \brief Find or create an entry describing the table specified.
212  * \param database Name of an ODBC class on which to query the table
213  * \param tablename Tablename to describe
214  * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
215  * When a structure is returned, the contained columns list will be
216  * rdlock'ed, to ensure that it will be retained in memory.
217  *
218  * XXX This creates a connection and disconnects it. In some situations, the caller of
219  * this function has its own connection and could donate it to this function instead of
220  * needing to create another one.
221  *
222  * XXX The automatic readlock of the columns is awkward. It's done because it's possible for
223  * multiple threads to have references to the table, and the table is not refcounted. Possible
224  * changes here would be
225  * * Eliminate the table cache entirely. The use of ast_odbc_find_table() is generally
226  *   questionable. The only real good use right now is from ast_realtime_require_field() in
227  *   order to make sure the DB has the expected columns in it. Since that is only used sparingly,
228  *   the need to cache tables is questionable. Instead, the table structure can be fetched from
229  *   the DB directly each time, resulting in a single owner of the data.
230  * * Make odbc_cache_tables a refcounted object.
231  *
232  * \since 1.6.1
233  */
234 struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
235 {
236         struct odbc_cache_tables *tableptr;
237         struct odbc_cache_columns *entry;
238         char columnname[80];
239         SQLLEN sqlptr;
240         SQLHSTMT stmt = NULL;
241         int res = 0, error = 0;
242         struct odbc_obj *obj;
243
244         AST_RWLIST_RDLOCK(&odbc_tables);
245         AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
246                 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
247                         break;
248                 }
249         }
250         if (tableptr) {
251                 AST_RWLIST_RDLOCK(&tableptr->columns);
252                 AST_RWLIST_UNLOCK(&odbc_tables);
253                 return tableptr;
254         }
255
256         if (!(obj = ast_odbc_request_obj(database, 0))) {
257                 ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
258                 AST_RWLIST_UNLOCK(&odbc_tables);
259                 return NULL;
260         }
261
262         /* Table structure not already cached; build it now. */
263         do {
264                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
265                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
266                         ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
267                         break;
268                 }
269
270                 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
271                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
272                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
273                         ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
274                         break;
275                 }
276
277                 if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
278                         ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
279                         break;
280                 }
281
282                 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
283                 tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
284                 strcpy(tableptr->connection, database); /* SAFE */
285                 strcpy(tableptr->table, tablename); /* SAFE */
286                 AST_RWLIST_HEAD_INIT(&(tableptr->columns));
287
288                 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
289                         SQLGetData(stmt,  4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
290
291                         if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
292                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
293                                 error = 1;
294                                 break;
295                         }
296                         entry->name = (char *)entry + sizeof(*entry);
297                         strcpy(entry->name, columnname);
298
299                         SQLGetData(stmt,  5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
300                         SQLGetData(stmt,  7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
301                         SQLGetData(stmt,  9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
302                         SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
303                         SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
304                         SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
305
306                         /* Specification states that the octenlen should be the maximum number of bytes
307                          * returned in a char or binary column, but it seems that some drivers just set
308                          * it to NULL. (Bad Postgres! No biscuit!) */
309                         if (entry->octetlen == 0) {
310                                 entry->octetlen = entry->size;
311                         }
312
313                         ast_debug(3, "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);
314                         /* Insert column info into column list */
315                         AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
316                 }
317                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
318
319                 AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
320                 AST_RWLIST_RDLOCK(&(tableptr->columns));
321                 break;
322         } while (1);
323
324         AST_RWLIST_UNLOCK(&odbc_tables);
325
326         if (error) {
327                 destroy_table_cache(tableptr);
328                 tableptr = NULL;
329         }
330         ast_odbc_release_obj(obj);
331         return tableptr;
332 }
333
334 struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
335 {
336         struct odbc_cache_columns *col;
337         AST_RWLIST_TRAVERSE(&table->columns, col, list) {
338                 if (strcasecmp(col->name, colname) == 0) {
339                         return col;
340                 }
341         }
342         return NULL;
343 }
344
345 int ast_odbc_clear_cache(const char *database, const char *tablename)
346 {
347         struct odbc_cache_tables *tableptr;
348
349         AST_RWLIST_WRLOCK(&odbc_tables);
350         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
351                 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
352                         AST_LIST_REMOVE_CURRENT(list);
353                         destroy_table_cache(tableptr);
354                         break;
355                 }
356         }
357         AST_RWLIST_TRAVERSE_SAFE_END
358         AST_RWLIST_UNLOCK(&odbc_tables);
359         return tableptr ? 0 : -1;
360 }
361
362 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
363 {
364         SQLHSTMT stmt;
365
366         stmt = exec_cb(obj, data);
367
368         return stmt;
369 }
370
371 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
372 {
373         int res = 0;
374         SQLHSTMT stmt;
375
376         /* This prepare callback may do more than just prepare -- it may also
377          * bind parameters, bind results, etc.  The real key, here, is that
378          * when we disconnect, all handles become invalid for most databases.
379          * We must therefore redo everything when we establish a new
380          * connection. */
381         stmt = prepare_cb(obj, data);
382         if (!stmt) {
383                 return NULL;
384         }
385
386         res = SQLExecute(stmt);
387         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
388                 if (res == SQL_ERROR) {
389                         ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
390                 }
391
392                 ast_log(LOG_WARNING, "SQL Execute error %d!\n", res);
393                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
394                 stmt = NULL;
395         }
396
397         return stmt;
398 }
399
400 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
401 {
402         int res = 0;
403
404         res = SQLExecute(stmt);
405         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
406                 if (res == SQL_ERROR) {
407                         ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
408                 }
409         }
410
411         return res;
412 }
413
414 SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
415 {
416         SQLRETURN res;
417
418         if (pmaxlen == 0) {
419                 if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
420                         ast_str_make_space(buf, *StrLen_or_Ind + 1);
421                 }
422         } else if (pmaxlen > 0) {
423                 ast_str_make_space(buf, pmaxlen);
424         }
425         res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
426         ast_str_update(*buf);
427
428         return res;
429 }
430
431 struct ast_str *ast_odbc_print_errors(SQLSMALLINT handle_type, SQLHANDLE handle, const char *operation)
432 {
433         struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
434         SQLINTEGER nativeerror = 0;
435         SQLINTEGER numfields = 0;
436         SQLSMALLINT diagbytes = 0;
437         SQLSMALLINT i;
438         unsigned char state[10];
439         unsigned char diagnostic[256];
440
441         ast_str_reset(errors);
442         SQLGetDiagField(handle_type, handle, 1, SQL_DIAG_NUMBER, &numfields,
443                         SQL_IS_INTEGER, &diagbytes);
444         for (i = 0; i < numfields; i++) {
445                 SQLGetDiagRec(handle_type, handle, i + 1, state, &nativeerror,
446                                 diagnostic, sizeof(diagnostic), &diagbytes);
447                 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
448                 ast_log(LOG_WARNING, "%s returned an error: %s: %s\n", operation, state, diagnostic);
449                 /* XXX Why is this here? */
450                 if (i > 10) {
451                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
452                         break;
453                 }
454         }
455
456         return errors;
457 }
458
459 unsigned int ast_odbc_class_get_isolation(struct odbc_class *class)
460 {
461         return class->isolation;
462 }
463
464 unsigned int ast_odbc_class_get_forcecommit(struct odbc_class *class)
465 {
466         return class->forcecommit;
467 }
468
469 const char *ast_odbc_class_get_name(struct odbc_class *class)
470 {
471         return class->name;
472 }
473
474 static int load_odbc_config(void)
475 {
476         static char *cfg = "res_odbc.conf";
477         struct ast_config *config;
478         struct ast_variable *v;
479         char *cat;
480         const char *dsn, *username, *password, *sanitysql;
481         int enabled, bse, conntimeout, forcecommit, isolation, maxconnections;
482         struct timeval ncache = { 0, 0 };
483         int preconnect = 0, res = 0;
484         struct ast_flags config_flags = { 0 };
485
486         struct odbc_class *new;
487
488         config = ast_config_load(cfg, config_flags);
489         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
490                 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
491                 return -1;
492         }
493         for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
494                 if (!strcasecmp(cat, "ENV")) {
495                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
496                                 setenv(v->name, v->value, 1);
497                                 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
498                         }
499                 } else {
500                         /* Reset all to defaults for each class of odbc connections */
501                         dsn = username = password = sanitysql = NULL;
502                         enabled = 1;
503                         preconnect = 0;
504                         bse = 1;
505                         conntimeout = 10;
506                         forcecommit = 0;
507                         isolation = SQL_TXN_READ_COMMITTED;
508                         maxconnections = 1;
509                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
510                                 if (!strcasecmp(v->name, "pooling") ||
511                                                 !strncasecmp(v->name, "share", 5) ||
512                                                 !strcasecmp(v->name, "limit") ||
513                                                 !strcasecmp(v->name, "idlecheck")) {
514                                         ast_log(LOG_WARNING, "The 'pooling', 'shared_connections', 'limit', and 'idlecheck' options were replaced by 'max_connections'.  See res_odbc.conf.sample.\n");
515                                 } else if (!strcasecmp(v->name, "enabled")) {
516                                         enabled = ast_true(v->value);
517                                 } else if (!strcasecmp(v->name, "pre-connect")) {
518                                         preconnect = ast_true(v->value);
519                                 } else if (!strcasecmp(v->name, "dsn")) {
520                                         dsn = v->value;
521                                 } else if (!strcasecmp(v->name, "username")) {
522                                         username = v->value;
523                                 } else if (!strcasecmp(v->name, "password")) {
524                                         password = v->value;
525                                 } else if (!strcasecmp(v->name, "sanitysql")) {
526                                         sanitysql = v->value;
527                                 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
528                                         bse = ast_true(v->value);
529                                 } else if (!strcasecmp(v->name, "connect_timeout")) {
530                                         if (sscanf(v->value, "%d", &conntimeout) != 1 || conntimeout < 1) {
531                                                 ast_log(LOG_WARNING, "connect_timeout must be a positive integer\n");
532                                                 conntimeout = 10;
533                                         }
534                                 } else if (!strcasecmp(v->name, "negative_connection_cache")) {
535                                         double dncache;
536                                         if (sscanf(v->value, "%lf", &dncache) != 1 || dncache < 0) {
537                                                 ast_log(LOG_WARNING, "negative_connection_cache must be a non-negative integer\n");
538                                                 /* 5 minutes sounds like a reasonable default */
539                                                 ncache.tv_sec = 300;
540                                                 ncache.tv_usec = 0;
541                                         } else {
542                                                 ncache.tv_sec = (int)dncache;
543                                                 ncache.tv_usec = (dncache - ncache.tv_sec) * 1000000;
544                                         }
545                                 } else if (!strcasecmp(v->name, "forcecommit")) {
546                                         forcecommit = ast_true(v->value);
547                                 } else if (!strcasecmp(v->name, "isolation")) {
548                                         if ((isolation = ast_odbc_text2isolation(v->value)) == 0) {
549                                                 ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
550                                                 isolation = SQL_TXN_READ_COMMITTED;
551                                         }
552                                 } else if (!strcasecmp(v->name, "max_connections")) {
553                                         if (sscanf(v->value, "%30d", &maxconnections) != 1 || maxconnections < 1) {
554                                                 ast_log(LOG_WARNING, "max_connections must be a positive integer\n");
555                                                 maxconnections = 1;
556                                         }
557                                 }
558                         }
559
560                         if (enabled && !ast_strlen_zero(dsn)) {
561                                 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
562
563                                 if (!new) {
564                                         res = -1;
565                                         break;
566                                 }
567
568                                 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
569                                 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
570
571                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
572                                         ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
573                                         ao2_ref(new, -1);
574                                         return res;
575                                 }
576
577                                 new->backslash_is_escape = bse ? 1 : 0;
578                                 new->forcecommit = forcecommit ? 1 : 0;
579                                 new->isolation = isolation;
580                                 new->conntimeout = conntimeout;
581                                 new->negative_connection_cache = ncache;
582                                 new->maxconnections = maxconnections;
583
584                                 if (cat)
585                                         ast_copy_string(new->name, cat, sizeof(new->name));
586                                 if (dsn)
587                                         ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
588                                 if (username && !(new->username = ast_strdup(username))) {
589                                         ao2_ref(new, -1);
590                                         break;
591                                 }
592                                 if (password && !(new->password = ast_strdup(password))) {
593                                         ao2_ref(new, -1);
594                                         break;
595                                 }
596                                 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
597                                         ao2_ref(new, -1);
598                                         break;
599                                 }
600
601                                 ast_mutex_init(&new->lock);
602                                 ast_cond_init(&new->cond, NULL);
603
604                                 odbc_register_class(new, preconnect);
605                                 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
606                                 ao2_ref(new, -1);
607                                 new = NULL;
608                         }
609                 }
610         }
611         ast_config_destroy(config);
612         return res;
613 }
614
615 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
616 {
617         struct ao2_iterator aoi;
618         struct odbc_class *class;
619         int length = 0;
620         int which = 0;
621         char *ret = NULL;
622
623         switch (cmd) {
624         case CLI_INIT:
625                 e->command = "odbc show";
626                 e->usage =
627                                 "Usage: odbc show [class]\n"
628                                 "       List settings of a particular ODBC class or,\n"
629                                 "       if not specified, all classes.\n";
630                 return NULL;
631         case CLI_GENERATE:
632                 if (a->pos != 2)
633                         return NULL;
634                 length = strlen(a->word);
635                 aoi = ao2_iterator_init(class_container, 0);
636                 while ((class = ao2_iterator_next(&aoi))) {
637                         if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
638                                 ret = ast_strdup(class->name);
639                         }
640                         ao2_ref(class, -1);
641                         if (ret) {
642                                 break;
643                         }
644                 }
645                 ao2_iterator_destroy(&aoi);
646                 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
647                         ret = ast_strdup("all");
648                 }
649                 return ret;
650         }
651
652         ast_cli(a->fd, "\nODBC DSN Settings\n");
653         ast_cli(a->fd,   "-----------------\n\n");
654         aoi = ao2_iterator_init(class_container, 0);
655         while ((class = ao2_iterator_next(&aoi))) {
656                 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
657                         char timestr[80];
658                         struct ast_tm tm;
659
660                         ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
661
662                         if (class->last_negative_connect.tv_sec > 0) {
663                                 ast_localtime(&class->last_negative_connect, &tm, NULL);
664                                 ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
665                                 ast_cli(a->fd, "    Last fail connection attempt: %s\n", timestr);
666                         }
667
668                         ast_cli(a->fd, "    Number of active connections: %zd (out of %d)\n", class->connection_cnt, class->maxconnections);
669                         ast_cli(a->fd, "\n");
670                 }
671                 ao2_ref(class, -1);
672         }
673         ao2_iterator_destroy(&aoi);
674
675         return CLI_SUCCESS;
676 }
677
678 static struct ast_cli_entry cli_odbc[] = {
679         AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
680 };
681
682 static void odbc_register_class(struct odbc_class *class, int preconnect)
683 {
684         struct odbc_obj *obj;
685
686         ao2_link(class_container, class);
687         /* I still have a reference in the caller, so a deref is NOT missing here. */
688
689         if (!preconnect) {
690                 return;
691         }
692
693         /* Request and release builds a connection */
694         obj = ast_odbc_request_obj(class->name, 0);
695         if (obj) {
696                 ast_odbc_release_obj(obj);
697         }
698
699         return;
700 }
701
702 void ast_odbc_release_obj(struct odbc_obj *obj)
703 {
704         struct odbc_class *class = obj->parent;
705
706         ast_debug(2, "Releasing ODBC handle %p into pool\n", obj);
707
708         /* The odbc_obj only holds a reference to the class when it is
709          * actively being used. This guarantees no circular reference
710          * between odbc_class and odbc_obj. Since it is being released
711          * we also release our class reference. If a reload occurred before
712          * the class will go away automatically once all odbc_obj are
713          * released back.
714          */
715         obj->parent = NULL;
716
717         ast_mutex_lock(&class->lock);
718         AST_LIST_INSERT_HEAD(&class->connections, obj, list);
719         ast_cond_signal(&class->cond);
720         ast_mutex_unlock(&class->lock);
721
722         ao2_ref(class, -1);
723 }
724
725 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
726 {
727         return obj->parent->backslash_is_escape;
728 }
729
730 static int aoro2_class_cb(void *obj, void *arg, int flags)
731 {
732         struct odbc_class *class = obj;
733         char *name = arg;
734         if (!strcmp(class->name, name) && !class->delme) {
735                 return CMP_MATCH | CMP_STOP;
736         }
737         return 0;
738 }
739
740 unsigned int ast_odbc_get_max_connections(const char *name)
741 {
742         struct odbc_class *class;
743         unsigned int max_connections;
744
745         class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name);
746         if (!class) {
747                 return 0;
748         }
749
750         max_connections = class->maxconnections;
751         ao2_ref(class, -1);
752
753         return max_connections;
754 }
755
756 /*
757  * \brief Determine if the connection has died.
758  *
759  * \param connection The connection to check
760  * \param class The ODBC class
761  * \retval 1 Yep, it's dead
762  * \retval 0 It's alive and well
763  */
764 static int connection_dead(struct odbc_obj *connection, struct odbc_class *class)
765 {
766         char *test_sql = "select 1";
767         SQLINTEGER dead;
768         SQLRETURN res;
769         SQLHSTMT stmt;
770
771         res = SQLGetConnectAttr(connection->con, SQL_ATTR_CONNECTION_DEAD, &dead, 0, 0);
772         if (SQL_SUCCEEDED(res)) {
773                 return dead == SQL_CD_TRUE ? 1 : 0;
774         }
775
776         /* If the Driver doesn't support SQL_ATTR_CONNECTION_DEAD do a
777          * probing query instead
778          */
779         res = SQLAllocHandle(SQL_HANDLE_STMT, connection->con, &stmt);
780         if (!SQL_SUCCEEDED(res)) {
781                 return 1;
782         }
783
784         if (!ast_strlen_zero(class->sanitysql)) {
785                 test_sql = class->sanitysql;
786         }
787
788         res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
789         if (!SQL_SUCCEEDED(res)) {
790                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
791                 return 1;
792         }
793
794         res = SQLExecute(stmt);
795         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
796
797         return SQL_SUCCEEDED(res) ? 0 : 1;
798 }
799
800 struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
801 {
802         struct odbc_obj *obj = NULL;
803         struct odbc_class *class;
804
805         if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
806                 ast_debug(1, "Class '%s' not found!\n", name);
807                 return NULL;
808         }
809
810         ast_mutex_lock(&class->lock);
811
812         while (!obj) {
813                 obj = AST_LIST_REMOVE_HEAD(&class->connections, list);
814
815                 if (!obj) {
816                         if (class->connection_cnt < class->maxconnections) {
817                                 /* If no connection is immediately available establish a new
818                                  * one if allowed. If we try and fail we give up completely as
819                                  * we could go into an infinite loop otherwise.
820                                  */
821                                 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
822                                 if (!obj) {
823                                         break;
824                                 }
825
826                                 obj->parent = ao2_bump(class);
827                                 if (odbc_obj_connect(obj) == ODBC_FAIL) {
828                                         ao2_ref(obj->parent, -1);
829                                         ao2_ref(obj, -1);
830                                         obj = NULL;
831                                         break;
832                                 }
833
834                                 class->connection_cnt++;
835                                 ast_debug(2, "Created ODBC handle %p on class '%s', new count is %zd\n", obj,
836                                         name, class->connection_cnt);
837                         } else {
838                                 /* Otherwise if we're not allowed to create a new one we
839                                  * wait for another thread to give up the connection they
840                                  * own.
841                                  */
842                                 ast_cond_wait(&class->cond, &class->lock);
843                         }
844                 } else if (connection_dead(obj, class)) {
845                         /* If the connection is dead try to grab another functional one from the
846                          * pool instead of trying to resurrect this one.
847                          */
848                         ao2_ref(obj, -1);
849                         obj = NULL;
850                         class->connection_cnt--;
851                         ast_debug(2, "ODBC handle %p dead - removing from class '%s', new count is %zd\n",
852                                 obj, name, class->connection_cnt);
853                 } else {
854                         /* We successfully grabbed a connection from the pool and all is well!
855                          */
856                         obj->parent = ao2_bump(class);
857                         ast_debug(2, "Reusing ODBC handle %p from class '%s'\n", obj, name);
858                 }
859         }
860
861         ast_mutex_unlock(&class->lock);
862         ao2_ref(class, -1);
863
864         return obj;
865 }
866
867 struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
868 {
869         struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
870         /* XXX New flow means that the "check" parameter doesn't do anything. We're requesting
871          * a connection from ODBC. We'll either get a new one, which obviously is already connected, or
872          * we'll get one from the ODBC connection pool. In that case, it will ensure to only give us a
873          * live connection
874          */
875         return _ast_odbc_request_obj2(name, flags, file, function, lineno);
876 }
877
878 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
879 {
880         int res;
881         SQLINTEGER err;
882         short int mlen;
883         unsigned char msg[200], state[10];
884         SQLHDBC con;
885
886         /* Nothing to disconnect */
887         if (!obj->con) {
888                 return ODBC_SUCCESS;
889         }
890
891         con = obj->con;
892         obj->con = NULL;
893         res = SQLDisconnect(con);
894
895         if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con)) == SQL_SUCCESS) {
896                 ast_debug(3, "Database handle %p (connection %p) deallocated\n", obj, con);
897         } else {
898                 SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
899                 ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
900         }
901
902         return ODBC_SUCCESS;
903 }
904
905 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
906 {
907         int res;
908         SQLINTEGER err;
909         short int mlen;
910         unsigned char msg[200], state[10];
911 #ifdef NEEDTRACE
912         SQLINTEGER enable = 1;
913         char *tracefile = "/tmp/odbc.trace";
914 #endif
915         SQLHDBC con;
916         long int negative_cache_expiration;
917
918         ast_assert(obj->con == NULL);
919         ast_debug(3, "Connecting %s(%p)\n", obj->parent->name, obj);
920
921         /* Dont connect while server is marked as unreachable via negative_connection_cache */
922         negative_cache_expiration = obj->parent->last_negative_connect.tv_sec + obj->parent->negative_connection_cache.tv_sec;
923         if (time(NULL) < negative_cache_expiration) {
924                 ast_log(LOG_WARNING, "Not connecting to %s. Negative connection cache for %ld seconds\n", obj->parent->name, negative_cache_expiration - time(NULL));
925                 return ODBC_FAIL;
926         }
927
928         res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &con);
929
930         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
931                 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
932                 obj->parent->last_negative_connect = ast_tvnow();
933                 return ODBC_FAIL;
934         }
935         SQLSetConnectAttr(con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
936         SQLSetConnectAttr(con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
937 #ifdef NEEDTRACE
938         SQLSetConnectAttr(con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
939         SQLSetConnectAttr(con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
940 #endif
941
942         res = SQLConnect(con,
943                    (SQLCHAR *) obj->parent->dsn, SQL_NTS,
944                    (SQLCHAR *) obj->parent->username, SQL_NTS,
945                    (SQLCHAR *) obj->parent->password, SQL_NTS);
946
947         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
948                 SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
949                 obj->parent->last_negative_connect = ast_tvnow();
950                 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
951                 if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con)) != SQL_SUCCESS) {
952                         SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
953                         ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
954                 }
955                 return ODBC_FAIL;
956         } else {
957                 ast_debug(3, "res_odbc: Connected to %s [%s (%p)]\n", obj->parent->name, obj->parent->dsn, obj);
958         }
959
960         obj->con = con;
961         return ODBC_SUCCESS;
962 }
963
964 static int reload(void)
965 {
966         struct odbc_cache_tables *table;
967         struct odbc_class *class;
968         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
969
970         /* First, mark all to be purged */
971         while ((class = ao2_iterator_next(&aoi))) {
972                 class->delme = 1;
973                 ao2_ref(class, -1);
974         }
975         ao2_iterator_destroy(&aoi);
976
977         load_odbc_config();
978
979         aoi = ao2_iterator_init(class_container, 0);
980         while ((class = ao2_iterator_next(&aoi))) {
981                 if (class->delme) {
982                         ao2_unlink(class_container, class);
983                 }
984                 ao2_ref(class, -1);
985         }
986         ao2_iterator_destroy(&aoi);
987
988         /* Empty the cache; it will get rebuilt the next time the tables are needed. */
989         AST_RWLIST_WRLOCK(&odbc_tables);
990         while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
991                 destroy_table_cache(table);
992         }
993         AST_RWLIST_UNLOCK(&odbc_tables);
994
995         return 0;
996 }
997
998 static int unload_module(void)
999 {
1000         /* Prohibit unloading */
1001         return -1;
1002 }
1003
1004 static int load_module(void)
1005 {
1006         if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
1007                 return AST_MODULE_LOAD_DECLINE;
1008         if (load_odbc_config() == -1)
1009                 return AST_MODULE_LOAD_DECLINE;
1010         ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
1011         return AST_MODULE_LOAD_SUCCESS;
1012 }
1013
1014 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "ODBC resource",
1015         .support_level = AST_MODULE_SUPPORT_CORE,
1016         .load = load_module,
1017         .unload = unload_module,
1018         .reload = reload,
1019         .load_pri = AST_MODPRI_REALTIME_DEPEND,
1020 );