remove the uses of the deprecated STANDARD_LOCAL_USER
[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
23 /*! \file
24  *
25  * \brief ODBC resource manager
26  * 
27  * \author Mark Spencer <markster@digium.com>
28  * \author Anthony Minessale II <anthmct@yahoo.com>
29  *
30  * \arg See also: \ref cdr_odbc
31  */
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <string.h>
37
38 #include "asterisk.h"
39
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41
42 #include "asterisk/file.h"
43 #include "asterisk/logger.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/config.h"
46 #include "asterisk/options.h"
47 #include "asterisk/pbx.h"
48 #include "asterisk/module.h"
49 #include "asterisk/cli.h"
50 #include "asterisk/lock.h"
51 #include "asterisk/res_odbc.h"
52 #define MAX_ODBC_HANDLES 25
53
54 struct odbc_list
55 {
56         char name[80];
57         odbc_obj *obj;
58         int used;
59 };
60
61 static struct odbc_list ODBC_REGISTRY[MAX_ODBC_HANDLES];
62
63
64 static void odbc_destroy(void)
65 {
66         int x = 0;
67
68         for (x = 0; x < MAX_ODBC_HANDLES; x++) {
69                 if (ODBC_REGISTRY[x].obj) {
70                         destroy_odbc_obj(&ODBC_REGISTRY[x].obj);
71                         ODBC_REGISTRY[x].obj = NULL;
72                 }
73         }
74 }
75
76 static odbc_obj *odbc_read(struct odbc_list *registry, const char *name)
77 {
78         int x = 0;
79         for (x = 0; x < MAX_ODBC_HANDLES; x++) {
80                 if (registry[x].used && !strcmp(registry[x].name, name)) {
81                         return registry[x].obj;
82                 }
83         }
84         return NULL;
85 }
86
87 static int odbc_write(struct odbc_list *registry, char *name, odbc_obj *obj)
88 {
89         int x = 0;
90         for (x = 0; x < MAX_ODBC_HANDLES; x++) {
91                 if (!registry[x].used) {
92                         ast_copy_string(registry[x].name, name, sizeof(registry[x].name));
93                         registry[x].obj = obj;
94                         registry[x].used = 1;
95                         return 1;
96                 }
97         }
98         return 0;
99 }
100
101 static void odbc_init(void)
102 {
103         int x = 0;
104         for (x = 0; x < MAX_ODBC_HANDLES; x++) {
105                 memset(&ODBC_REGISTRY[x], 0, sizeof(struct odbc_list));
106         }
107 }
108
109 static char *tdesc = "ODBC Resource";
110 /* internal stuff */
111
112 SQLHSTMT odbc_prepare_and_execute(odbc_obj *obj, SQLHSTMT (*prepare_cb)(odbc_obj *obj, void *data), void *data)
113 {
114         int res = 0, i, attempt;
115         SQLINTEGER nativeerror=0, numfields=0;
116         SQLSMALLINT diagbytes=0;
117         unsigned char state[10], diagnostic[256];
118         SQLHSTMT stmt;
119
120         for (attempt = 0; attempt < 2; attempt++) {
121                 /* This prepare callback may do more than just prepare -- it may also
122                  * bind parameters, bind results, etc.  The real key, here, is that
123                  * when we disconnect, all handles become invalid for most databases.
124                  * We must therefore redo everything when we establish a new
125                  * connection. */
126                 stmt = prepare_cb(obj, data);
127
128                 if (stmt) {
129                         res = SQLExecute(stmt);
130                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
131                                 if (res == SQL_ERROR) {
132                                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
133                                         for (i=0; i< numfields + 1; i++) {
134                                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
135                                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
136                                                 if (i > 10) {
137                                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
138                                                         break;
139                                                 }
140                                         }
141                                 }
142
143                                 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
144                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
145
146                                 ast_mutex_lock(&obj->lock);
147                                 obj->up = 0;
148                                 ast_mutex_unlock(&obj->lock);
149                                 odbc_obj_disconnect(obj);
150                                 odbc_obj_connect(obj);
151                                 continue;
152                         }
153                         break;
154                 }
155         }
156
157         return stmt;
158 }
159
160 int odbc_smart_execute(odbc_obj *obj, SQLHSTMT stmt) 
161 {
162         int res = 0, i;
163         SQLINTEGER nativeerror=0, numfields=0;
164         SQLSMALLINT diagbytes=0;
165         unsigned char state[10], diagnostic[256];
166
167         res = SQLExecute(stmt);
168         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
169                 if (res == SQL_ERROR) {
170                         SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
171                         for (i=0; i< numfields + 1; i++) {
172                                 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
173                                 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
174                                 if (i > 10) {
175                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
176                                         break;
177                                 }
178                         }
179                 }
180 /*
181                 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
182                 ast_mutex_lock(&obj->lock);
183                 obj->up = 0;
184                 ast_mutex_unlock(&obj->lock);
185                 odbc_obj_disconnect(obj);
186                 odbc_obj_connect(obj);
187                 res = SQLExecute(stmt);
188 */
189         }
190         
191         return res;
192 }
193
194
195 int odbc_smart_direct_execute(odbc_obj *obj, SQLHSTMT stmt, char *sql) 
196 {
197         int res = 0;
198
199         res = SQLExecDirect (stmt, (unsigned char *)sql, SQL_NTS);
200         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
201                 ast_log(LOG_WARNING, "SQL Execute error! Attempting a reconnect...\n");
202                 ast_mutex_lock(&obj->lock);
203                 obj->up = 0;
204                 ast_mutex_unlock(&obj->lock);
205                 odbc_obj_disconnect(obj);
206                 odbc_obj_connect(obj);
207                 res = SQLExecDirect (stmt, (unsigned char *)sql, SQL_NTS);
208         }
209         
210         return res;
211 }
212
213 int odbc_sanity_check(odbc_obj *obj) 
214 {
215         char *test_sql = "select 1";
216         SQLHSTMT stmt;
217         int res = 0;
218
219         ast_mutex_lock(&obj->lock);
220         if(obj->up) { /* so you say... let's make sure */
221                 res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
222                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
223                         obj->up = 0; /* Liar!*/
224                 } else {
225                         res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
226                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
227                                 obj->up = 0; /* Liar!*/
228                         } else {
229                                 res = SQLExecute(stmt);
230                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
231                                         obj->up = 0; /* Liar!*/
232                                 }
233                         }
234                 }
235                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
236         }
237         ast_mutex_unlock(&obj->lock);
238
239         if(!obj->up) { /* Try to reconnect! */
240                 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
241                 odbc_obj_disconnect(obj);
242                 odbc_obj_connect(obj);
243         }
244         return obj->up;
245 }
246
247 static int load_odbc_config(void)
248 {
249         static char *cfg = "res_odbc.conf";
250         struct ast_config *config;
251         struct ast_variable *v;
252         char *cat, *dsn, *username, *password;
253         int enabled;
254         int connect = 0;
255         char *env_var;
256
257         odbc_obj *obj;
258
259         config = ast_config_load(cfg);
260         if (config) {
261                 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
262                         if (!strcmp(cat, "ENV")) {
263                                 for (v = ast_variable_browse(config, cat); v; v = v->next) {
264                                         env_var = malloc(strlen(v->name) + strlen(v->value) + 2);
265                                         if (env_var) {
266                                                 sprintf(env_var, "%s=%s", v->name, v->value);
267                                                 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
268                                                 putenv(env_var);
269                                                 free(env_var);
270                                         }
271                                 }
272
273                         cat = ast_category_browse(config, cat);
274                         }
275
276                         dsn = username = password = NULL;
277                         enabled = 1;
278                         connect = 0;
279                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
280                                 if (!strcmp(v->name, "enabled"))
281                                         enabled = ast_true(v->value);
282                                 if (!strcmp(v->name, "pre-connect"))
283                                         connect = ast_true(v->value);
284                                 if (!strcmp(v->name, "dsn"))
285                                         dsn = v->value;
286                                 if (!strcmp(v->name, "username"))
287                                         username = v->value;
288                                 if (!strcmp(v->name, "password"))
289                                         password = v->value;
290                         }
291
292                         if (enabled && dsn) {
293                                 obj = new_odbc_obj(cat, dsn, username, password);
294                                 if (obj) {
295                                         register_odbc_obj(cat, obj);
296                                         ast_log(LOG_NOTICE, "registered database handle '%s' dsn->[%s]\n", cat, obj->dsn);
297                                         if (connect) {
298                                                 odbc_obj_connect(obj);
299                                         }
300                                 } else {
301                                         ast_log(LOG_WARNING, "Addition of obj %s failed.\n", cat);
302                                 }
303
304                         }
305                 }
306                 ast_config_destroy(config);
307         }
308         return 0;
309 }
310
311 int odbc_dump_fd(int fd, odbc_obj *obj)
312 {
313         /* make sure the connection is up before we lie to our master.*/
314         odbc_sanity_check(obj);
315         ast_cli(fd, "Name: %s\nDSN: %s\nConnected: %s\n\n", obj->name, obj->dsn, obj->up ? "yes" : "no");
316         return 0;
317 }
318
319 static int odbc_connect_usage(int fd)
320 {
321         ast_cli(fd, "usage odbc connect <DSN>\n");
322         return 0;
323 }
324
325 static int odbc_disconnect_usage(int fd)
326 {
327         ast_cli(fd, "usage odbc disconnect <DSN>\n");
328         return 0;
329 }
330
331 static int odbc_show_command(int fd, int argc, char **argv)
332 {
333         odbc_obj *obj;
334         int x = 0;
335         
336         if (!strcmp(argv[1], "show")) {
337                 if (!argv[2] || (argv[2] && !strcmp(argv[2], "all"))) {
338                         for (x = 0; x < MAX_ODBC_HANDLES; x++) {
339                                 if (!ODBC_REGISTRY[x].used)
340                                         break;
341                                 if (ODBC_REGISTRY[x].obj)
342                                         odbc_dump_fd(fd, ODBC_REGISTRY[x].obj);
343                         }
344                 } else {
345                         obj = odbc_read(ODBC_REGISTRY, argv[2]);
346                         if (obj)
347                                 odbc_dump_fd(fd, obj);
348                 }
349         }
350         return 0;
351 }
352
353 static int odbc_disconnect_command(int fd, int argc, char **argv)
354 {
355         odbc_obj *obj;
356         if (!strcmp(argv[1], "disconnect")) {
357                 if (!argv[2])
358                         return odbc_disconnect_usage(fd);
359
360                 obj = odbc_read(ODBC_REGISTRY, argv[2]);
361                 if (obj) {
362                         odbc_obj_disconnect(obj);
363                 }
364         } 
365         return 0;
366 }
367
368 static int odbc_connect_command(int fd, int argc, char **argv)
369 {
370         odbc_obj *obj;
371         if (!argv[1])
372                 return odbc_connect_usage(fd);
373
374         if (!strcmp(argv[1], "connect") || !strcmp(argv[1], "disconnect")) {
375                 if (!argv[2])
376                         return odbc_connect_usage(fd);
377
378                 obj = odbc_read(ODBC_REGISTRY, argv[2]);
379                 if (obj) {
380                         odbc_obj_connect(obj);
381                 }
382         }
383         return 0;
384 }
385
386
387 static char connect_usage[] =
388 "Usage: odbc connect <DSN>\n"
389 "       Connect to ODBC DSN\n";
390
391 static char disconnect_usage[] =
392 "Usage: odbc connect <DSN>\n"
393 "       Disconnect from ODBC DSN\n";
394
395 static char show_usage[] =
396 "Usage: odbc show {DSN}\n"
397 "       Show ODBC {DSN}\n"
398 "       Specifying DSN will show that DSN else, all DSNs are shown\n";
399
400 static struct ast_cli_entry odbc_connect_struct =
401         { { "odbc", "connect", NULL }, odbc_connect_command, "Connect to ODBC DSN", connect_usage };
402
403
404 static struct ast_cli_entry odbc_disconnect_struct =
405         { { "odbc", "disconnect", NULL }, odbc_disconnect_command, "Disconnect from ODBC DSN", disconnect_usage };
406
407 static struct ast_cli_entry odbc_show_struct =
408         { { "odbc", "show", NULL }, odbc_show_command, "Show ODBC DSN(s)", show_usage };
409
410 /* api calls */
411
412 int register_odbc_obj(char *name, odbc_obj *obj)
413 {
414         if (obj != NULL)
415                 return odbc_write(ODBC_REGISTRY, name, obj);
416         return 0;
417 }
418
419 odbc_obj *fetch_odbc_obj(const char *name, int check)
420 {
421         odbc_obj *obj = NULL;
422         if((obj = (odbc_obj *) odbc_read(ODBC_REGISTRY, name))) {
423                 if(check)
424                         odbc_sanity_check(obj);
425         }
426         return obj;
427 }
428
429 odbc_obj *new_odbc_obj(char *name, char *dsn, char *username, char *password)
430 {
431         static odbc_obj *new;
432
433         if (!(new = calloc(1, sizeof(*new))) || 
434             !(new->name = malloc(strlen(name) + 1)) || 
435             !(new->dsn = malloc(strlen(dsn) + 1)))
436                 goto cleanup;
437
438         if (username) {
439                 if (!(new->username = malloc(strlen(username) + 1)))
440                         goto cleanup;
441                 strcpy(new->username, username);
442         }
443
444         if (password) {
445                 if (!(new->password = malloc(strlen(password) + 1)))
446                         goto cleanup;
447                 strcpy(new->password, password);
448         }
449
450         strcpy(new->name, name);
451         strcpy(new->dsn, dsn);
452         new->env = SQL_NULL_HANDLE;
453         new->up = 0;
454         ast_mutex_init(&new->lock);
455         return new;
456
457 cleanup:
458         if (new) {
459                 free(new->name);
460                 free(new->dsn);
461                 free(new->username);
462                 free(new->password);
463
464                 free(new);      
465         }
466
467         return NULL;
468 }
469
470 void destroy_odbc_obj(odbc_obj **obj)
471 {
472         odbc_obj_disconnect(*obj);
473
474         ast_mutex_lock(&(*obj)->lock);
475         SQLFreeHandle(SQL_HANDLE_STMT, (*obj)->stmt);
476         SQLFreeHandle(SQL_HANDLE_DBC, (*obj)->con);
477         SQLFreeHandle(SQL_HANDLE_ENV, (*obj)->env);
478
479         free((*obj)->name);
480         free((*obj)->dsn);
481         if ((*obj)->username)
482                 free((*obj)->username);
483         if ((*obj)->password)
484                 free((*obj)->password);
485         ast_mutex_unlock(&(*obj)->lock);
486         ast_mutex_destroy(&(*obj)->lock);
487         free(*obj);
488 }
489
490 odbc_status odbc_obj_disconnect(odbc_obj *obj)
491 {
492         int res;
493         ast_mutex_lock(&obj->lock);
494
495         res = SQLDisconnect(obj->con);
496
497
498         if (res == ODBC_SUCCESS) {
499                 ast_log(LOG_WARNING, "res_odbc: disconnected %d from %s [%s]\n", res, obj->name, obj->dsn);
500         } else {
501                 ast_log(LOG_WARNING, "res_odbc: %s [%s] already disconnected\n",
502                 obj->name, obj->dsn);
503         }
504         obj->up = 0;
505         ast_mutex_unlock(&obj->lock);
506         return ODBC_SUCCESS;
507 }
508
509 odbc_status odbc_obj_connect(odbc_obj *obj)
510 {
511         int res;
512         SQLINTEGER err;
513         short int mlen;
514         unsigned char msg[200], stat[10];
515
516         ast_mutex_lock(&obj->lock);
517
518         if (obj->env == SQL_NULL_HANDLE) {
519                 res = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &obj->env);
520
521                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
522                         if (option_verbose > 3)
523                                 ast_log(LOG_WARNING, "res_odbc: Error AllocHandle\n");
524                         ast_mutex_unlock(&obj->lock);
525                         return ODBC_FAIL;
526                 }
527
528                 res = SQLSetEnvAttr(obj->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
529
530                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
531                         if (option_verbose > 3)
532                                 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
533                         SQLFreeHandle(SQL_HANDLE_ENV, obj->env);
534                         ast_mutex_unlock(&obj->lock);
535                         return ODBC_FAIL;
536                 }
537
538                 res = SQLAllocHandle(SQL_HANDLE_DBC, obj->env, &obj->con);
539
540                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
541
542                         if (option_verbose > 3)
543                                 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
544                         SQLFreeHandle(SQL_HANDLE_ENV, obj->env);
545
546                         ast_mutex_unlock(&obj->lock);
547                         return ODBC_FAIL;
548                 }
549                 SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
550         }
551         if(obj->up) {
552                 odbc_obj_disconnect(obj);
553                 ast_log(LOG_NOTICE,"Re-connecting %s\n", obj->name);
554         }
555
556         ast_log(LOG_NOTICE, "Connecting %s\n", obj->name);
557
558         res = SQLConnect(obj->con,
559                    (SQLCHAR *) obj->dsn, SQL_NTS,
560                    (SQLCHAR *) obj->username, SQL_NTS,
561                    (SQLCHAR *) obj->password, SQL_NTS);
562
563         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
564                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
565                 SQLFreeHandle(SQL_HANDLE_ENV, obj->env);
566                 ast_mutex_unlock(&obj->lock);
567                 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
568                 return ODBC_FAIL;
569         } else {
570
571                 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->name, obj->dsn);
572                 obj->up = 1;
573         }
574
575         ast_mutex_unlock(&obj->lock);
576         return ODBC_SUCCESS;
577 }
578
579 LOCAL_USER_DECL;
580
581 int unload_module(void)
582 {
583         STANDARD_HANGUP_LOCALUSERS;
584         odbc_destroy();
585         ast_cli_unregister(&odbc_disconnect_struct);
586         ast_cli_unregister(&odbc_connect_struct);
587         ast_cli_unregister(&odbc_show_struct);
588         ast_log(LOG_NOTICE, "res_odbc unloaded.\n");
589         return 0;
590 }
591
592 int load_module(void)
593 {
594         odbc_init();
595         load_odbc_config();
596         ast_cli_register(&odbc_disconnect_struct);
597         ast_cli_register(&odbc_connect_struct);
598         ast_cli_register(&odbc_show_struct);
599         ast_log(LOG_NOTICE, "res_odbc loaded.\n");
600         return 0;
601 }
602
603 char *description(void)
604 {
605         return tdesc;
606 }
607
608 int usecount(void)
609 {
610         int res;
611         STANDARD_USECOUNT(res);
612         return res;
613 }
614
615 char *key()
616 {
617         return ASTERISK_GPL_KEY;
618 }