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