Merged revisions 99775 via svnmerge from
[asterisk/asterisk.git] / res / res_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, 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  *
29  * \arg See also: \ref cdr_odbc
30  */
31
32 /*** MODULEINFO
33         <depend>unixodbc</depend>
34         <depend>ltdl</depend>
35  ***/
36
37 #include "asterisk.h"
38
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40
41 #include "asterisk/file.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/config.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/module.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/lock.h"
48 #include "asterisk/res_odbc.h"
49 #include "asterisk/time.h"
50
51 struct odbc_class
52 {
53         AST_LIST_ENTRY(odbc_class) list;
54         char name[80];
55         char dsn[80];
56         char *username;
57         char *password;
58         char sanitysql[256];
59         SQLHENV env;
60         unsigned int haspool:1;         /* Boolean - TDS databases need this */
61         unsigned int limit:10;          /* Gives a limit of 1023 maximum */
62         unsigned int count:10;          /* Running count of pooled connections */
63         unsigned int delme:1;                   /* Purge the class */
64         unsigned int backslash_is_escape:1;     /* On this database, the backslash is a native escape sequence */
65         unsigned int idlecheck;                 /* Recheck the connection if it is idle for this long */
66         AST_LIST_HEAD(, odbc_obj) odbc_obj;
67 };
68
69 AST_LIST_HEAD_STATIC(odbc_list, odbc_class);
70
71 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
72 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
73 static int odbc_register_class(struct odbc_class *class, int connect);
74
75
76 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
77 {
78         int attempt;
79         SQLHSTMT stmt;
80
81         for (attempt = 0; attempt < 2; attempt++) {
82                 stmt = exec_cb(obj, data);
83
84                 if (stmt) {
85                         break;
86                 } else {
87                         obj->up = 0;
88                         ast_log(LOG_WARNING, "SQL Exec Direct failed.  Attempting a reconnect...\n");
89
90                         odbc_obj_disconnect(obj);
91                         odbc_obj_connect(obj);
92                 }
93         }
94
95         return stmt;
96 }
97
98 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
99 {
100         int res = 0, i, attempt;
101         SQLINTEGER nativeerror=0, numfields=0;
102         SQLSMALLINT diagbytes=0;
103         unsigned char state[10], diagnostic[256];
104         SQLHSTMT stmt;
105
106         for (attempt = 0; attempt < 2; attempt++) {
107                 /* This prepare callback may do more than just prepare -- it may also
108                  * bind parameters, bind results, etc.  The real key, here, is that
109                  * when we disconnect, all handles become invalid for most databases.
110                  * We must therefore redo everything when we establish a new
111                  * connection. */
112                 stmt = prepare_cb(obj, data);
113
114                 if (stmt) {
115                         res = SQLExecute(stmt);
116                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
117                                 if (res == SQL_ERROR) {
118                                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
119                                         for (i = 0; i < numfields; i++) {
120                                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
121                                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
122                                                 if (i > 10) {
123                                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
124                                                         break;
125                                                 }
126                                         }
127                                 }
128
129                                 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
130                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
131                                 stmt = NULL;
132
133                                 obj->up = 0;
134                                 /*
135                                  * While this isn't the best way to try to correct an error, this won't automatically
136                                  * fail when the statement handle invalidates.
137                                  */
138                                 ast_odbc_sanity_check(obj);
139                                 continue;
140                         } else
141                                 obj->last_used = ast_tvnow();
142                         break;
143                 } else if (attempt == 0)
144                         ast_odbc_sanity_check(obj);
145         }
146
147         return stmt;
148 }
149
150 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt) 
151 {
152         int res = 0, i;
153         SQLINTEGER nativeerror=0, numfields=0;
154         SQLSMALLINT diagbytes=0;
155         unsigned char state[10], diagnostic[256];
156
157         res = SQLExecute(stmt);
158         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
159                 if (res == SQL_ERROR) {
160                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
161                         for (i = 0; i < numfields; i++) {
162                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
163                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
164                                 if (i > 10) {
165                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
166                                         break;
167                                 }
168                         }
169                 }
170 #if 0
171                 /* This is a really bad method of trying to correct a dead connection.  It
172                  * only ever really worked with MySQL.  It will not work with any other
173                  * database, since most databases prepare their statements on the server,
174                  * and if you disconnect, you invalidate the statement handle.  Hence, if
175                  * you disconnect, you're going to fail anyway, whether you try to execute
176                  * a second time or not.
177                  */
178                 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
179                 ast_mutex_lock(&obj->lock);
180                 obj->up = 0;
181                 ast_mutex_unlock(&obj->lock);
182                 odbc_obj_disconnect(obj);
183                 odbc_obj_connect(obj);
184                 res = SQLExecute(stmt);
185 #endif
186         } else
187                 obj->last_used = ast_tvnow();
188         
189         return res;
190 }
191
192
193 int ast_odbc_sanity_check(struct odbc_obj *obj) 
194 {
195         char *test_sql = "select 1";
196         SQLHSTMT stmt;
197         int res = 0;
198
199         if (!ast_strlen_zero(obj->parent->sanitysql))
200                 test_sql = obj->parent->sanitysql;
201
202         if (obj->up) {
203                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
204                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
205                         obj->up = 0;
206                 } else {
207                         res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
208                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
209                                 obj->up = 0;
210                         } else {
211                                 res = SQLExecute(stmt);
212                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
213                                         obj->up = 0;
214                                 }
215                         }
216                 }
217                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
218         }
219
220         if (!obj->up) { /* Try to reconnect! */
221                 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
222                 odbc_obj_disconnect(obj);
223                 odbc_obj_connect(obj);
224         }
225         return obj->up;
226 }
227
228 static int load_odbc_config(void)
229 {
230         static char *cfg = "res_odbc.conf";
231         struct ast_config *config;
232         struct ast_variable *v;
233         char *cat;
234         const char *dsn, *username, *password, *sanitysql;
235         int enabled, pooling, limit, bse;
236         unsigned int idlecheck;
237         int connect = 0, res = 0;
238         struct ast_flags config_flags = { 0 };
239
240         struct odbc_class *new;
241
242         config = ast_config_load(cfg, config_flags);
243         if (!config) {
244                 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
245                 return -1;
246         }
247         for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
248                 if (!strcasecmp(cat, "ENV")) {
249                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
250                                 setenv(v->name, v->value, 1);
251                                 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
252                         }
253                 } else {
254                         /* Reset all to defaults for each class of odbc connections */
255                         dsn = username = password = sanitysql = NULL;
256                         enabled = 1;
257                         connect = idlecheck = 0;
258                         pooling = 0;
259                         limit = 0;
260                         bse = 1;
261                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
262                                 if (!strcasecmp(v->name, "pooling")) {
263                                         if (ast_true(v->value))
264                                                 pooling = 1;
265                                 } else if (!strcasecmp(v->name, "limit")) {
266                                         sscanf(v->value, "%d", &limit);
267                                         if (ast_true(v->value) && !limit) {
268                                                 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);
269                                                 limit = 1023;
270                                         } else if (ast_false(v->value)) {
271                                                 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
272                                                 enabled = 0;
273                                                 break;
274                                         }
275                                 } else if (!strcasecmp(v->name, "idlecheck")) {
276                                         sscanf(v->value, "%d", &idlecheck);
277                                 } else if (!strcasecmp(v->name, "enabled")) {
278                                         enabled = ast_true(v->value);
279                                 } else if (!strcasecmp(v->name, "pre-connect")) {
280                                         connect = ast_true(v->value);
281                                 } else if (!strcasecmp(v->name, "dsn")) {
282                                         dsn = v->value;
283                                 } else if (!strcasecmp(v->name, "username")) {
284                                         username = v->value;
285                                 } else if (!strcasecmp(v->name, "password")) {
286                                         password = v->value;
287                                 } else if (!strcasecmp(v->name, "sanitysql")) {
288                                         sanitysql = v->value;
289                                 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
290                                         bse = ast_true(v->value);
291                                 }
292                         }
293
294                         if (enabled && !ast_strlen_zero(dsn)) {
295                                 new = ast_calloc(1, sizeof(*new));
296
297                                 if (!new) {
298                                         res = -1;
299                                         break;
300                                 }
301
302                                 if (cat)
303                                         ast_copy_string(new->name, cat, sizeof(new->name));
304                                 if (dsn)
305                                         ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
306                                 if (username)
307                                         new->username = ast_strdup(username);
308                                 if (password)
309                                         new->password = ast_strdup(password);
310                                 if (sanitysql)
311                                         ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
312
313                                 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
314                                 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
315
316                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
317                                         ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
318                                         SQLFreeHandle(SQL_HANDLE_ENV, new->env);
319                                         return res;
320                                 }
321
322                                 if (pooling) {
323                                         new->haspool = pooling;
324                                         if (limit) {
325                                                 new->limit = limit;
326                                         } else {
327                                                 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
328                                                 new->limit = 5;
329                                         }
330                                 }
331
332                                 new->backslash_is_escape = bse ? 1 : 0;
333                                 new->idlecheck = idlecheck;
334
335                                 odbc_register_class(new, connect);
336                                 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
337                         }
338                 }
339         }
340         ast_config_destroy(config);
341         return res;
342 }
343
344 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
345 {
346         struct odbc_class *class;
347         struct odbc_obj *current;
348         int length = 0;
349         int which = 0;
350         char *ret = NULL;
351
352         switch (cmd) {
353         case CLI_INIT:
354                 e->command = "odbc show";
355                 e->usage =
356                                 "Usage: odbc show [class]\n"
357                                 "       List settings of a particular ODBC class or,\n"
358                                 "       if not specified, all classes.\n";
359                 return NULL;
360         case CLI_GENERATE:
361                 if (a->pos != 2)
362                         return NULL;
363                 length = strlen(a->word);
364                 AST_LIST_LOCK(&odbc_list);
365                 AST_LIST_TRAVERSE(&odbc_list, class, list) {
366                         if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
367                                 ret = ast_strdup(class->name);
368                                 break;
369                         }
370                 }
371                 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
372                         ret = ast_strdup("all");
373                 }
374                 AST_LIST_UNLOCK(&odbc_list);
375                 return ret;
376         }
377
378         ast_cli(a->fd, "\nODBC DSN Settings\n");
379         ast_cli(a->fd, "-----------------\n\n");
380         AST_LIST_LOCK(&odbc_list);
381         AST_LIST_TRAVERSE(&odbc_list, class, list) {
382                 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
383                         int count = 0;
384                         ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
385
386                         if (class->haspool) {
387                                 ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);
388
389                                 AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
390                                         ast_cli(a->fd, "    - Connection %d: %s\n", ++count, current->used ? "in use" : current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
391                                 }
392                         } else {
393                                 /* Should only ever be one of these */
394                                 AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
395                                         ast_cli(a->fd, "  Pooled: No\n  Connected: %s\n", current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
396                                 }
397                         }
398                         ast_cli(a->fd, "\n");
399                 }
400         }
401         AST_LIST_UNLOCK(&odbc_list);
402
403         return CLI_SUCCESS;
404 }
405
406 static struct ast_cli_entry cli_odbc[] = {
407         AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
408 };
409
410 static int odbc_register_class(struct odbc_class *class, int connect)
411 {
412         struct odbc_obj *obj;
413         if (class) {
414                 AST_LIST_LOCK(&odbc_list);
415                 AST_LIST_INSERT_HEAD(&odbc_list, class, list);
416                 AST_LIST_UNLOCK(&odbc_list);
417
418                 if (connect) {
419                         /* Request and release builds a connection */
420                         obj = ast_odbc_request_obj(class->name, 0);
421                         if (obj)
422                                 ast_odbc_release_obj(obj);
423                 }
424
425                 return 0;
426         } else {
427                 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
428                 return -1;
429         }
430 }
431
432 void ast_odbc_release_obj(struct odbc_obj *obj)
433 {
434         /* For pooled connections, this frees the connection to be
435          * reused.  For non-pooled connections, it does nothing. */
436         obj->used = 0;
437 }
438
439 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
440 {
441         return obj->parent->backslash_is_escape;
442 }
443
444 struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
445 {
446         struct odbc_obj *obj = NULL;
447         struct odbc_class *class;
448
449         AST_LIST_LOCK(&odbc_list);
450         AST_LIST_TRAVERSE(&odbc_list, class, list) {
451                 if (!strcmp(class->name, name))
452                         break;
453         }
454         AST_LIST_UNLOCK(&odbc_list);
455
456         if (!class)
457                 return NULL;
458
459         AST_LIST_LOCK(&class->odbc_obj);
460         if (class->haspool) {
461                 /* Recycle connections before building another */
462                 AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
463                         if (! obj->used) {
464                                 obj->used = 1;
465                                 break;
466                         }
467                 }
468
469                 if (!obj && (class->count < class->limit)) {
470                         class->count++;
471                         obj = ast_calloc(1, sizeof(*obj));
472                         if (!obj) {
473                                 AST_LIST_UNLOCK(&class->odbc_obj);
474                                 return NULL;
475                         }
476                         ast_mutex_init(&obj->lock);
477                         obj->parent = class;
478                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
479                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
480                                 ast_mutex_destroy(&obj->lock);
481                                 ast_free(obj);
482                                 obj = NULL;
483                                 class->count--;
484                         } else {
485                                 obj->used = 1;
486                                 AST_LIST_INSERT_TAIL(&class->odbc_obj, obj, list);
487                         }
488                 }
489         } else {
490                 /* Non-pooled connection: multiple modules can use the same connection. */
491                 AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
492                         /* Non-pooled connection: if there is an entry, return it */
493                         break;
494                 }
495
496                 if (!obj) {
497                         /* No entry: build one */
498                         obj = ast_calloc(1, sizeof(*obj));
499                         if (!obj) {
500                                 AST_LIST_UNLOCK(&class->odbc_obj);
501                                 return NULL;
502                         }
503                         ast_mutex_init(&obj->lock);
504                         obj->parent = class;
505                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
506                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
507                                 ast_mutex_destroy(&obj->lock);
508                                 ast_free(obj);
509                                 obj = NULL;
510                         } else {
511                                 AST_LIST_INSERT_HEAD(&class->odbc_obj, obj, list);
512                         }
513                 }
514         }
515         AST_LIST_UNLOCK(&class->odbc_obj);
516
517         if (obj && check) {
518                 ast_odbc_sanity_check(obj);
519         } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck)
520                 odbc_obj_connect(obj);
521
522         return obj;
523 }
524
525 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
526 {
527         int res;
528         ast_mutex_lock(&obj->lock);
529
530         res = SQLDisconnect(obj->con);
531
532         if (res == ODBC_SUCCESS) {
533                 ast_log(LOG_WARNING, "res_odbc: disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
534         } else {
535                 ast_log(LOG_WARNING, "res_odbc: %s [%s] already disconnected\n",
536                 obj->parent->name, obj->parent->dsn);
537         }
538         obj->up = 0;
539         ast_mutex_unlock(&obj->lock);
540         return ODBC_SUCCESS;
541 }
542
543 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
544 {
545         int res;
546         SQLINTEGER err;
547         short int mlen;
548         unsigned char msg[200], stat[10];
549 #ifdef NEEDTRACE
550         SQLINTEGER enable = 1;
551         char *tracefile = "/tmp/odbc.trace";
552 #endif
553         ast_mutex_lock(&obj->lock);
554
555         res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
556
557         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
558                 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
559                 ast_mutex_unlock(&obj->lock);
560                 return ODBC_FAIL;
561         }
562         SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
563         SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *) 10, 0);
564 #ifdef NEEDTRACE
565         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
566         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
567 #endif
568
569         if (obj->up) {
570                 odbc_obj_disconnect(obj);
571                 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
572         } else {
573                 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
574         }
575
576         res = SQLConnect(obj->con,
577                    (SQLCHAR *) obj->parent->dsn, SQL_NTS,
578                    (SQLCHAR *) obj->parent->username, SQL_NTS,
579                    (SQLCHAR *) obj->parent->password, SQL_NTS);
580
581         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
582                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
583                 ast_mutex_unlock(&obj->lock);
584                 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
585                 return ODBC_FAIL;
586         } else {
587                 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
588                 obj->up = 1;
589                 obj->last_used = ast_tvnow();
590         }
591
592         ast_mutex_unlock(&obj->lock);
593         return ODBC_SUCCESS;
594 }
595
596 static int reload(void)
597 {
598         static char *cfg = "res_odbc.conf";
599         struct ast_config *config;
600         struct ast_variable *v;
601         char *cat;
602         const char *dsn, *username, *password, *sanitysql;
603         int enabled, pooling, limit, bse;
604         unsigned int idlecheck;
605         int connect = 0, res = 0;
606         struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
607
608         struct odbc_class *new, *class;
609         struct odbc_obj *current;
610
611         /* First, mark all to be purged */
612         AST_LIST_LOCK(&odbc_list);
613         AST_LIST_TRAVERSE(&odbc_list, class, list) {
614                 class->delme = 1;
615         }
616
617         config = ast_config_load(cfg, config_flags);
618         if (config != NULL && config != CONFIG_STATUS_FILEUNCHANGED) {
619                 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
620                         if (!strcasecmp(cat, "ENV")) {
621                                 for (v = ast_variable_browse(config, cat); v; v = v->next) {
622                                         setenv(v->name, v->value, 1);
623                                         ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
624                                 }
625                         } else {
626                                 char *freeme = NULL;
627                                 /* Reset all to defaults for each class of odbc connections */
628                                 dsn = username = password = sanitysql = NULL;
629                                 enabled = 1;
630                                 connect = idlecheck = 0;
631                                 pooling = 0;
632                                 limit = 0;
633                                 bse = 1;
634                                 for (v = ast_variable_browse(config, cat); v; v = v->next) {
635                                         if (!strcasecmp(v->name, "pooling")) {
636                                                 pooling = 1;
637                                         } else if (!strcasecmp(v->name, "limit")) {
638                                                 sscanf(v->value, "%d", &limit);
639                                                 if (ast_true(v->value) && !limit) {
640                                                         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);
641                                                         limit = 1023;
642                                                 } else if (ast_false(v->value)) {
643                                                         ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
644                                                         enabled = 0;
645                                                         break;
646                                                 }
647                                         } else if (!strcasecmp(v->name, "idlecheck")) {
648                                                 sscanf(v->value, "%ud", &idlecheck);
649                                         } else if (!strcasecmp(v->name, "enabled")) {
650                                                 enabled = ast_true(v->value);
651                                         } else if (!strcasecmp(v->name, "pre-connect")) {
652                                                 connect = ast_true(v->value);
653                                         } else if (!strcasecmp(v->name, "dsn")) {
654                                                 dsn = v->value;
655                                         } else if (!strcasecmp(v->name, "username")) {
656                                                 username = v->value;
657                                         } else if (!strcasecmp(v->name, "password")) {
658                                                 password = v->value;
659                                         } else if (!strcasecmp(v->name, "sanitysql")) {
660                                                 sanitysql = v->value;
661                                         } else if (!strcasecmp(v->name, "backslash_is_escape")) {
662                                                 bse = ast_true(v->value);
663                                         }
664                                 }
665
666                                 if (enabled && !ast_strlen_zero(dsn)) {
667                                         /* First, check the list to see if it already exists */
668                                         AST_LIST_TRAVERSE(&odbc_list, class, list) {
669                                                 if (!strcmp(class->name, cat)) {
670                                                         class->delme = 0;
671                                                         break;
672                                                 }
673                                         }
674
675                                         if (class) {
676                                                 new = class;
677                                         } else {
678                                                 new = ast_calloc(1, sizeof(*new));
679                                         }
680
681                                         if (!new) {
682                                                 res = -1;
683                                                 break;
684                                         }
685
686                                         if (cat)
687                                                 ast_copy_string(new->name, cat, sizeof(new->name));
688                                         if (dsn)
689                                                 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
690
691                                         /* Safely replace username */
692                                         if (class && class->username)
693                                                 freeme = class->username;
694                                         if (username)
695                                                 new->username = ast_strdup(username);
696                                         if (freeme) {
697                                                 ast_free(freeme);
698                                                 freeme = NULL;
699                                         }
700
701                                         /* Safely replace password */
702                                         if (class && class->password)
703                                                  freeme = class->password;
704                                         if (password)
705                                                 new->password = ast_strdup(password);
706                                         if (freeme) {
707                                                 ast_free(freeme);
708                                                 freeme = NULL;
709                                         }
710
711                                         if (sanitysql)
712                                                 ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
713
714                                         if (!class) {
715                                                 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
716                                                 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
717
718                                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
719                                                         ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
720                                                         SQLFreeHandle(SQL_HANDLE_ENV, new->env);
721                                                         AST_LIST_UNLOCK(&odbc_list);
722                                                         return res;
723                                                 }
724                                         }
725
726                                         if (pooling) {
727                                                 new->haspool = pooling;
728                                                 if (limit) {
729                                                         new->limit = limit;
730                                                 } else {
731                                                         ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
732                                                         new->limit = 5;
733                                                 }
734                                         }
735
736                                         new->backslash_is_escape = bse;
737                                         new->idlecheck = idlecheck;
738
739                                         if (class) {
740                                                 ast_log(LOG_NOTICE, "Refreshing ODBC class '%s' dsn->[%s]\n", cat, dsn);
741                                         } else {
742                                                 odbc_register_class(new, connect);
743                                                 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
744                                         }
745                                 }
746                         }
747                 }
748                 ast_config_destroy(config);
749         }
750
751         /* Purge classes that we know can go away (pooled with 0, only) */
752         AST_LIST_TRAVERSE_SAFE_BEGIN(&odbc_list, class, list) {
753                 if (class->delme && class->haspool && class->count == 0) {
754                         while ((current = AST_LIST_REMOVE_HEAD(&class->odbc_obj, list))) {
755                                 odbc_obj_disconnect(current);
756                                 ast_mutex_destroy(&current->lock);
757                                 ast_free(current);
758                         }
759
760                         AST_LIST_REMOVE_CURRENT(list);
761                         if (class->username)
762                                 ast_free(class->username);
763                         if (class->password)
764                                 ast_free(class->password);
765                         ast_free(class);
766                 }
767         }
768         AST_LIST_TRAVERSE_SAFE_END;
769         AST_LIST_UNLOCK(&odbc_list);
770
771         return 0;
772 }
773
774 static int unload_module(void)
775 {
776         /* Prohibit unloading */
777         return -1;
778 }
779
780 static int load_module(void)
781 {
782         if (load_odbc_config() == -1)
783                 return AST_MODULE_LOAD_DECLINE;
784         ast_cli_register_multiple(cli_odbc, sizeof(cli_odbc) / sizeof(struct ast_cli_entry));
785         ast_log(LOG_NOTICE, "res_odbc loaded.\n");
786         return 0;
787 }
788
789 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
790                 .load = load_module,
791                 .unload = unload_module,
792                 .reload = reload,
793                );