Merged revisions 47352 via svnmerge from
[asterisk/asterisk.git] / cdr / cdr_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2003-2005, Digium, Inc.
5  *
6  * Brian K. West <brian@bkw.org>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief ODBC CDR Backend
22  * 
23  * \author Brian K. West <brian@bkw.org>
24  *
25  * See also:
26  * \arg http://www.unixodbc.org
27  * \arg \ref Config_cdr
28  * \ingroup cdr_drivers
29  */
30
31 /*** MODULEINFO
32         <depend>unixodbc</depend>
33  ***/
34
35 #include "asterisk.h"
36
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
38
39 #include <sys/types.h>
40 #include <stdio.h>
41 #include <string.h>
42
43 #include <stdlib.h>
44 #include <unistd.h>
45 #include <time.h>
46
47 #ifndef __CYGWIN__
48 #include <sql.h>
49 #include <sqlext.h>
50 #include <sqltypes.h>
51 #else
52 #include <windows.h>
53 #include <w32api/sql.h>
54 #include <w32api/sqlext.h>
55 #include <w32api/sqltypes.h>
56 #endif
57
58 #include "asterisk/config.h"
59 #include "asterisk/options.h"
60 #include "asterisk/channel.h"
61 #include "asterisk/cdr.h"
62 #include "asterisk/module.h"
63 #include "asterisk/logger.h"
64
65 #define DATE_FORMAT "%Y-%m-%d %T"
66
67 static char *name = "ODBC";
68 static char *config = "cdr_odbc.conf";
69 static char *dsn = NULL, *username = NULL, *password = NULL, *table = NULL;
70 static int loguniqueid = 0;
71 static int usegmtime = 0;
72 static int dispositionstring = 0;
73 static int connected = 0;
74
75 AST_MUTEX_DEFINE_STATIC(odbc_lock);
76
77 static int odbc_do_query(void);
78 static int odbc_init(void);
79
80 static SQLHENV  ODBC_env = SQL_NULL_HANDLE;     /* global ODBC Environment */
81 static SQLHDBC  ODBC_con;                       /* global ODBC Connection Handle */
82 static SQLHSTMT ODBC_stmt;                      /* global ODBC Statement Handle */
83
84 static void odbc_disconnect(void)
85 {
86         SQLDisconnect(ODBC_con);
87         SQLFreeHandle(SQL_HANDLE_DBC, ODBC_con);
88         SQLFreeHandle(SQL_HANDLE_ENV, ODBC_env);
89         connected = 0;
90 }
91
92 static int odbc_log(struct ast_cdr *cdr)
93 {
94         int ODBC_res;
95         char sqlcmd[2048] = "", timestr[128];
96         int res = 0;
97         struct tm tm;
98
99         if (usegmtime) 
100                 gmtime_r(&cdr->start.tv_sec,&tm);
101         else
102                 localtime_r(&cdr->start.tv_sec,&tm);
103
104         ast_mutex_lock(&odbc_lock);
105         strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
106         memset(sqlcmd,0,2048);
107         if (loguniqueid) {
108                 snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s "
109                 "(calldate,clid,src,dst,dcontext,channel,dstchannel,lastapp,"
110                 "lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) "
111                 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", table);
112         } else {
113                 snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s "
114                 "(calldate,clid,src,dst,dcontext,channel,dstchannel,lastapp,lastdata,"
115                 "duration,billsec,disposition,amaflags,accountcode) "
116                 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", table);
117         }
118
119         if (!connected) {
120                 res = odbc_init();
121                 if (res < 0) {
122                         odbc_disconnect();
123                         ast_mutex_unlock(&odbc_lock);
124                         return 0;
125                 }                               
126         }
127
128         ODBC_res = SQLAllocHandle(SQL_HANDLE_STMT, ODBC_con, &ODBC_stmt);
129
130         if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
131                 if (option_verbose > 10)
132                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Failure in AllocStatement %d\n", ODBC_res);
133                 SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
134                 odbc_disconnect();
135                 ast_mutex_unlock(&odbc_lock);
136                 return 0;
137         }
138
139         /* We really should only have to do this once.  But for some
140            strange reason if I don't it blows holes in memory like
141            like a shotgun.  So we just do this so its safe. */
142
143         ODBC_res = SQLPrepare(ODBC_stmt, (unsigned char *)sqlcmd, SQL_NTS);
144         
145         if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
146                 if (option_verbose > 10)
147                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Error in PREPARE %d\n", ODBC_res);
148                 SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
149                 odbc_disconnect();
150                 ast_mutex_unlock(&odbc_lock);
151                 return 0;
152         }
153
154         SQLBindParameter(ODBC_stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(timestr), 0, &timestr, 0, NULL);
155         SQLBindParameter(ODBC_stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->clid), 0, cdr->clid, 0, NULL);
156         SQLBindParameter(ODBC_stmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->src), 0, cdr->src, 0, NULL);
157         SQLBindParameter(ODBC_stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->dst), 0, cdr->dst, 0, NULL);
158         SQLBindParameter(ODBC_stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->dcontext), 0, cdr->dcontext, 0, NULL);
159         SQLBindParameter(ODBC_stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->channel), 0, cdr->channel, 0, NULL);
160         SQLBindParameter(ODBC_stmt, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->dstchannel), 0, cdr->dstchannel, 0, NULL);
161         SQLBindParameter(ODBC_stmt, 8, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->lastapp), 0, cdr->lastapp, 0, NULL);
162         SQLBindParameter(ODBC_stmt, 9, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->lastdata), 0, cdr->lastdata, 0, NULL);
163         SQLBindParameter(ODBC_stmt, 10, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->duration, 0, NULL);
164         SQLBindParameter(ODBC_stmt, 11, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->billsec, 0, NULL);
165         if (dispositionstring)
166                 SQLBindParameter(ODBC_stmt, 12, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(ast_cdr_disp2str(cdr->disposition)) + 1, 0, ast_cdr_disp2str(cdr->disposition), 0, NULL);
167         else
168                 SQLBindParameter(ODBC_stmt, 12, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->disposition, 0, NULL);
169         SQLBindParameter(ODBC_stmt, 13, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->amaflags, 0, NULL);
170         SQLBindParameter(ODBC_stmt, 14, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->accountcode), 0, cdr->accountcode, 0, NULL);
171
172         if (loguniqueid) {
173                 SQLBindParameter(ODBC_stmt, 15, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->uniqueid), 0, cdr->uniqueid, 0, NULL);
174                 SQLBindParameter(ODBC_stmt, 16, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->userfield), 0, cdr->userfield, 0, NULL);
175         }
176
177         if (connected) {
178                 res = odbc_do_query();
179                 if (res < 0) {
180                         if (option_verbose > 10)                
181                                 ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Query FAILED Call not logged!\n");
182                         if (option_verbose > 10)
183                                 ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Reconnecting to dsn %s\n", dsn);
184                         SQLDisconnect(ODBC_con);
185                         res = odbc_init();
186                         if (res < 0) {
187                                 if (option_verbose > 10)
188                                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: %s has gone away!\n", dsn);
189                                 odbc_disconnect();
190                         } else {
191                                 if (option_verbose > 10)
192                                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Trying Query again!\n");
193                                 res = odbc_do_query();
194                                 if (res < 0) {
195                                         if (option_verbose > 10)
196                                                 ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Query FAILED Call not logged!\n");
197                                 }
198                         }
199                 }
200         } else {
201                 if (option_verbose > 10)
202                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Query FAILED Call not logged!\n");
203         }
204         SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
205         ast_mutex_unlock(&odbc_lock);
206         return 0;
207 }
208
209 static int odbc_unload_module(void)
210 {
211         ast_mutex_lock(&odbc_lock);
212         if (connected) {
213                 if (option_verbose > 10)
214                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Disconnecting from %s\n", dsn);
215                 SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
216                 odbc_disconnect();
217         }
218         if (dsn) {
219                 if (option_verbose > 10)
220                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: free dsn\n");
221                 free(dsn);
222         }
223         if (username) {
224                 if (option_verbose > 10)
225                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: free username\n");
226                 free(username);
227         }
228         if (password) {
229                 if (option_verbose > 10)
230                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: free password\n");
231                 free(password);
232         }
233         if (table) {
234                 if (option_verbose > 10)
235                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: free table\n");
236                 free(table);
237         }
238
239         ast_cdr_unregister(name);
240         ast_mutex_unlock(&odbc_lock);
241         return 0;
242 }
243
244 static int odbc_load_module(void)
245 {
246         int res = 0;
247         struct ast_config *cfg;
248         struct ast_variable *var;
249         const char *tmp;
250
251         ast_mutex_lock(&odbc_lock);
252
253         cfg = ast_config_load(config);
254         if (!cfg) {
255                 ast_log(LOG_WARNING, "cdr_odbc: Unable to load config for ODBC CDR's: %s\n", config);
256                 res = AST_MODULE_LOAD_DECLINE;
257                 goto out;
258         }
259         
260         var = ast_variable_browse(cfg, "global");
261         if (!var) {
262                 /* nothing configured */
263                 goto out;
264         }
265
266         tmp = ast_variable_retrieve(cfg,"global","dsn");
267         if (tmp == NULL) {
268                 ast_log(LOG_WARNING,"cdr_odbc: dsn not specified.  Assuming asteriskdb\n");
269                 tmp = "asteriskdb";
270         }
271         dsn = strdup(tmp);
272         if (dsn == NULL) {
273                 ast_log(LOG_ERROR,"cdr_odbc: Out of memory error.\n");
274                 res = -1;
275                 goto out;
276         }
277
278         tmp = ast_variable_retrieve(cfg,"global","dispositionstring");
279         if (tmp) {
280                 dispositionstring = ast_true(tmp);
281         } else {
282                 dispositionstring = 0;
283         }
284                 
285         tmp = ast_variable_retrieve(cfg,"global","username");
286         if (tmp) {
287                 username = strdup(tmp);
288                 if (username == NULL) {
289                         ast_log(LOG_ERROR,"cdr_odbc: Out of memory error.\n");
290                         res = -1;
291                         goto out;
292                 }
293         }
294
295         tmp = ast_variable_retrieve(cfg,"global","password");
296         if (tmp) {
297                 password = strdup(tmp);
298                 if (password == NULL) {
299                         ast_log(LOG_ERROR,"cdr_odbc: Out of memory error.\n");
300                         res = -1;
301                         goto out;
302                 }
303         }
304
305         tmp = ast_variable_retrieve(cfg,"global","loguniqueid");
306         if (tmp) {
307                 loguniqueid = ast_true(tmp);
308                 if (loguniqueid) {
309                         if (option_debug)
310                                 ast_log(LOG_DEBUG,"cdr_odbc: Logging uniqueid\n");
311                 } else {
312                         if (option_debug)
313                                 ast_log(LOG_DEBUG,"cdr_odbc: Not logging uniqueid\n");
314                 }
315         } else {
316                 if (option_debug)
317                         ast_log(LOG_DEBUG,"cdr_odbc: Not logging uniqueid\n");
318                 loguniqueid = 0;
319         }
320
321         tmp = ast_variable_retrieve(cfg,"global","usegmtime");
322         if (tmp) {
323                 usegmtime = ast_true(tmp);
324                 if (usegmtime) {
325                         if (option_debug)
326                                 ast_log(LOG_DEBUG,"cdr_odbc: Logging in GMT\n");
327                 } else {
328                         if (option_debug)
329                                 ast_log(LOG_DEBUG,"cdr_odbc: Not logging in GMT\n");
330                 }
331         } else {
332                 if (option_debug)
333                         ast_log(LOG_DEBUG,"cdr_odbc: Not logging in GMT\n");
334                 usegmtime = 0;
335         }
336
337         tmp = ast_variable_retrieve(cfg,"global","table");
338         if (tmp == NULL) {
339                 ast_log(LOG_WARNING,"cdr_odbc: table not specified.  Assuming cdr\n");
340                 tmp = "cdr";
341         }
342         table = strdup(tmp);
343         if (table == NULL) {
344                 ast_log(LOG_ERROR,"cdr_odbc: Out of memory error.\n");
345                 res = -1;
346                 goto out;
347         }
348
349         if (option_verbose > 2) {
350                 ast_verbose( VERBOSE_PREFIX_3 "cdr_odbc: dsn is %s\n",dsn);
351                 if (username)
352                 {
353                         ast_verbose( VERBOSE_PREFIX_3 "cdr_odbc: username is %s\n",username);
354                         ast_verbose( VERBOSE_PREFIX_3 "cdr_odbc: password is [secret]\n");
355                 }
356                 else
357                         ast_verbose( VERBOSE_PREFIX_3 "cdr_odbc: retreiving username and password from odbc config\n");
358                 ast_verbose( VERBOSE_PREFIX_3 "cdr_odbc: table is %s\n",table);
359         }
360         
361         res = odbc_init();
362         if (res < 0) {
363                 ast_log(LOG_ERROR, "cdr_odbc: Unable to connect to datasource: %s\n", dsn);
364                 if (option_verbose > 2) {
365                         ast_verbose( VERBOSE_PREFIX_3 "cdr_odbc: Unable to connect to datasource: %s\n", dsn);
366                 }
367         }
368         res = ast_cdr_register(name, ast_module_info->description, odbc_log);
369         if (res) {
370                 ast_log(LOG_ERROR, "cdr_odbc: Unable to register ODBC CDR handling\n");
371         }
372 out:
373         if (cfg)
374                 ast_config_destroy(cfg);
375         ast_mutex_unlock(&odbc_lock);
376         return res;
377 }
378
379 static int odbc_do_query(void)
380 {
381         SQLINTEGER ODBC_err;
382         int ODBC_res;
383         short int ODBC_mlen;
384         char ODBC_msg[200], ODBC_stat[10];
385         
386         ODBC_res = SQLExecute(ODBC_stmt);
387         
388         if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
389                 if (option_verbose > 10)
390                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Error in Query %d\n", ODBC_res);
391                 SQLGetDiagRec(SQL_HANDLE_DBC, ODBC_con, 1, (unsigned char *)ODBC_stat, &ODBC_err, (unsigned char *)ODBC_msg, 100, &ODBC_mlen);
392                 SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
393                 odbc_disconnect();
394                 return -1;
395         } else {
396                 if (option_verbose > 10)
397                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Query Successful!\n");
398                 connected = 1;
399         }
400         return 0;
401 }
402
403 static int odbc_init(void)
404 {
405         int ODBC_res;
406
407         if (ODBC_env == SQL_NULL_HANDLE || connected == 0) {
408                 ODBC_res = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &ODBC_env);
409                 if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
410                         if (option_verbose > 10)
411                                 ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Error AllocHandle\n");
412                         connected = 0;
413                         return -1;
414                 }
415
416                 ODBC_res = SQLSetEnvAttr(ODBC_env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
417
418                 if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
419                         if (option_verbose > 10)
420                                 ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Error SetEnv\n");
421                         SQLFreeHandle(SQL_HANDLE_ENV, ODBC_env);
422                         connected = 0;
423                         return -1;
424                 }
425
426                 ODBC_res = SQLAllocHandle(SQL_HANDLE_DBC, ODBC_env, &ODBC_con);
427
428                 if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
429                         if (option_verbose > 10)
430                                 ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Error AllocHDB %d\n", ODBC_res);
431                         SQLFreeHandle(SQL_HANDLE_ENV, ODBC_env);
432                         connected = 0;
433                         return -1;
434                 }
435                 SQLSetConnectAttr(ODBC_con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)10, 0);    
436         }
437
438         /* Note that the username and password could be NULL here, but that is allowed in ODBC.
439            In this case, the default username and password will be used from odbc.conf */
440         ODBC_res = SQLConnect(ODBC_con, (SQLCHAR*)dsn, SQL_NTS, (SQLCHAR*)username, SQL_NTS, (SQLCHAR*)password, SQL_NTS);
441
442         if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
443                 if (option_verbose > 10)
444                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Error SQLConnect %d\n", ODBC_res);
445                 SQLFreeHandle(SQL_HANDLE_DBC, ODBC_con);
446                 SQLFreeHandle(SQL_HANDLE_ENV, ODBC_env);
447                 connected = 0;
448                 return -1;
449         } else {
450                 if (option_verbose > 10)
451                         ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Connected to %s\n", dsn);
452                 connected = 1;
453         }
454         return 0;
455 }
456
457 static int load_module(void)
458 {
459         return odbc_load_module();
460 }
461
462 static int unload_module(void)
463 {
464         return odbc_unload_module();
465 }
466
467 static int reload(void)
468 {
469         odbc_unload_module();
470         return odbc_load_module();
471 }
472
473 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC CDR Backend",
474                 .load = load_module,
475                 .unload = unload_module,
476                 .reload = reload,
477                );