Fix checking for CONFIG_STATUS_FILEINVALID so that modules don't crash upon trying...
[asterisk/asterisk.git] / cdr / cdr_tds.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2004 - 2006, Digium, Inc.
5  *
6  * See http://www.asterisk.org for more information about
7  * the Asterisk project. Please do not directly contact
8  * any of the maintainers of this project for assistance;
9  * the project provides a web site, mailing lists and IRC
10  * channels for your use.
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License Version 2. See the LICENSE file
14  * at the top of the source tree.
15  */
16
17 /*! \file
18  *
19  * \brief FreeTDS CDR logger
20  *
21  * See also
22  * \arg \ref Config_cdr
23  * \arg http://www.freetds.org/
24  * \ingroup cdr_drivers
25  */
26
27 /*! \verbatim
28  *
29  * Table Structure for `cdr`
30  *
31  * Created on: 05/20/2004 16:16
32  * Last changed on: 07/27/2004 20:01
33
34 CREATE TABLE [dbo].[cdr] (
35         [accountcode] [varchar] (20) NULL ,
36         [src] [varchar] (80) NULL ,
37         [dst] [varchar] (80) NULL ,
38         [dcontext] [varchar] (80) NULL ,
39         [clid] [varchar] (80) NULL ,
40         [channel] [varchar] (80) NULL ,
41         [dstchannel] [varchar] (80) NULL ,
42         [lastapp] [varchar] (80) NULL ,
43         [lastdata] [varchar] (80) NULL ,
44         [start] [datetime] NULL ,
45         [answer] [datetime] NULL ,
46         [end] [datetime] NULL ,
47         [duration] [int] NULL ,
48         [billsec] [int] NULL ,
49         [disposition] [varchar] (20) NULL ,
50         [amaflags] [varchar] (16) NULL ,
51         [uniqueid] [varchar] (32) NULL ,
52         [userfield] [varchar] (256) NULL
53 ) ON [PRIMARY]
54
55 \endverbatim
56
57 */
58
59 /*** MODULEINFO
60         <depend>freetds</depend>
61  ***/
62
63 #include "asterisk.h"
64
65 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
66
67 #include <time.h>
68 #include <math.h>
69
70 #include "asterisk/config.h"
71 #include "asterisk/channel.h"
72 #include "asterisk/cdr.h"
73 #include "asterisk/module.h"
74
75 #include <sqlfront.h>
76 #include <sybdb.h>
77
78 #define DATE_FORMAT "%Y/%m/%d %T"
79
80 static char *name = "FreeTDS (MSSQL)";
81 static char *config = "cdr_tds.conf";
82
83 struct cdr_tds_config {
84         AST_DECLARE_STRING_FIELDS(
85                 AST_STRING_FIELD(hostname);
86                 AST_STRING_FIELD(database);
87                 AST_STRING_FIELD(username);
88                 AST_STRING_FIELD(password);
89                 AST_STRING_FIELD(table);
90                 AST_STRING_FIELD(charset);
91                 AST_STRING_FIELD(language);
92         );
93         DBPROCESS *dbproc;
94         unsigned int connected:1;
95         unsigned int has_userfield:1;
96 };
97
98 AST_MUTEX_DEFINE_STATIC(tds_lock);
99
100 static struct cdr_tds_config *settings;
101
102 static char *anti_injection(const char *, int);
103 static void get_date(char *, size_t len, struct timeval);
104
105 static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
106         __attribute__ ((format (printf, 2, 3)));
107
108 static int mssql_connect(void);
109 static int mssql_disconnect(void);
110
111 static int tds_log(struct ast_cdr *cdr)
112 {
113         char start[80], answer[80], end[80];
114         char *accountcode, *src, *dst, *dcontext, *clid, *channel, *dstchannel, *lastapp, *lastdata, *uniqueid, *userfield = NULL;
115         RETCODE erc;
116         int res = -1;
117         int attempt = 1;
118
119         accountcode = anti_injection(cdr->accountcode, 20);
120         src         = anti_injection(cdr->src, 80);
121         dst         = anti_injection(cdr->dst, 80);
122         dcontext    = anti_injection(cdr->dcontext, 80);
123         clid        = anti_injection(cdr->clid, 80);
124         channel     = anti_injection(cdr->channel, 80);
125         dstchannel  = anti_injection(cdr->dstchannel, 80);
126         lastapp     = anti_injection(cdr->lastapp, 80);
127         lastdata    = anti_injection(cdr->lastdata, 80);
128         uniqueid    = anti_injection(cdr->uniqueid, 32);
129
130         get_date(start, sizeof(start), cdr->start);
131         get_date(answer, sizeof(answer), cdr->answer);
132         get_date(end, sizeof(end), cdr->end);
133
134         ast_mutex_lock(&tds_lock);
135
136         if (settings->has_userfield) {
137                 userfield = anti_injection(cdr->userfield, AST_MAX_USER_FIELD);
138         }
139
140 retry:
141         /* Ensure that we are connected */
142         if (!settings->connected) {
143                 ast_log(LOG_NOTICE, "Attempting to reconnect to %s (Attempt %d)\n", settings->hostname, attempt);
144                 if (mssql_connect()) {
145                         /* Connect failed */
146                         if (attempt++ < 3) {
147                                 goto retry;
148                         }
149                         goto done;
150                 }
151         }
152
153         if (settings->has_userfield) {
154                 erc = dbfcmd(settings->dbproc,
155                                          "INSERT INTO %s "
156                                          "("
157                                          "accountcode, src, dst, dcontext, clid, channel, "
158                                          "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
159                                          "billsec, disposition, amaflags, uniqueid, userfield"
160                                          ") "
161                                          "VALUES "
162                                          "("
163                                          "'%s', '%s', '%s', '%s', '%s', '%s', "
164                                          "'%s', '%s', '%s', %s, %s, %s, %ld, "
165                                          "%ld, '%s', '%s', '%s', '%s'"
166                                          ")",
167                                          settings->table,
168                                          accountcode, src, dst, dcontext, clid, channel,
169                                          dstchannel, lastapp, lastdata, start, answer, end, cdr->duration,
170                                          cdr->billsec, ast_cdr_disp2str(cdr->disposition), ast_cdr_flags2str(cdr->amaflags), uniqueid,
171                                          userfield
172                         );
173         } else {
174                 erc = dbfcmd(settings->dbproc,
175                                          "INSERT INTO %s "
176                                          "("
177                                          "accountcode, src, dst, dcontext, clid, channel, "
178                                          "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
179                                          "billsec, disposition, amaflags, uniqueid"
180                                          ") "
181                                          "VALUES "
182                                          "("
183                                          "'%s', '%s', '%s', '%s', '%s', '%s', "
184                                          "'%s', '%s', '%s', %s, %s, %s, %ld, "
185                                          "%ld, '%s', '%s', '%s'"
186                                          ")",
187                                          settings->table,
188                                          accountcode, src, dst, dcontext, clid, channel,
189                                          dstchannel, lastapp, lastdata, start, answer, end, cdr->duration,
190                                          cdr->billsec, ast_cdr_disp2str(cdr->disposition), ast_cdr_flags2str(cdr->amaflags), uniqueid
191                         );
192         }
193
194         if (erc == FAIL) {
195                 if (attempt++ < 3) {
196                         ast_log(LOG_NOTICE, "Failed to build INSERT statement, retrying...\n");
197                         mssql_disconnect();
198                         goto retry;
199                 } else {
200                         ast_log(LOG_ERROR, "Failed to build INSERT statement, no CDR was logged.\n");
201                         goto done;
202                 }
203         }
204
205         if (dbsqlexec(settings->dbproc) == FAIL) {
206                 if (attempt++ < 3) {
207                         ast_log(LOG_NOTICE, "Failed to execute INSERT statement, retrying...\n");
208                         mssql_disconnect();
209                         goto retry;
210                 } else {
211                         ast_log(LOG_ERROR, "Failed to execute INSERT statement, no CDR was logged.\n");
212                         goto done;
213                 }
214         }
215
216         /* Consume any results we might get back (this is more of a sanity check than
217          * anything else, since an INSERT shouldn't return results). */
218         while (dbresults(settings->dbproc) != NO_MORE_RESULTS) {
219                 while (dbnextrow(settings->dbproc) != NO_MORE_ROWS);
220         }
221
222         res = 0;
223
224 done:
225         ast_mutex_unlock(&tds_lock);
226
227         ast_free(accountcode);
228         ast_free(src);
229         ast_free(dst);
230         ast_free(dcontext);
231         ast_free(clid);
232         ast_free(channel);
233         ast_free(dstchannel);
234         ast_free(lastapp);
235         ast_free(lastdata);
236         ast_free(uniqueid);
237
238         if (userfield) {
239                 ast_free(userfield);
240         }
241
242         return res;
243 }
244
245 static char *anti_injection(const char *str, int len)
246 {
247         /* Reference to http://www.nextgenss.com/papers/advanced_sql_injection.pdf */
248         char *buf;
249         char *buf_ptr, *srh_ptr;
250         char *known_bad[] = {"select", "insert", "update", "delete", "drop", ";", "--", "\0"};
251         int idx;
252
253         if (!(buf = ast_calloc(1, len + 1))) {
254                 ast_log(LOG_ERROR, "Out of memory\n");
255                 return NULL;
256         }
257
258         buf_ptr = buf;
259
260         /* Escape single quotes */
261         for (; *str && strlen(buf) < len; str++) {
262                 if (*str == '\'') {
263                         *buf_ptr++ = '\'';
264                 }
265                 *buf_ptr++ = *str;
266         }
267         *buf_ptr = '\0';
268
269         /* Erase known bad input */
270         for (idx = 0; *known_bad[idx]; idx++) {
271                 while ((srh_ptr = strcasestr(buf, known_bad[idx]))) {
272                         memmove(srh_ptr, srh_ptr + strlen(known_bad[idx]), strlen(srh_ptr + strlen(known_bad[idx])) + 1);
273                 }
274         }
275
276         return buf;
277 }
278
279 static void get_date(char *dateField, size_t len, struct timeval when)
280 {
281         /* To make sure we have date variable if not insert null to SQL */
282         if (!ast_tvzero(when)) {
283                 struct ast_tm tm;
284                 ast_localtime(&when, &tm, NULL);
285                 ast_strftime(dateField, len, "'" DATE_FORMAT "'", &tm);
286         } else {
287                 ast_copy_string(dateField, "null", len);
288         }
289 }
290
291 static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
292 {
293         va_list ap;
294         char *buffer;
295
296         va_start(ap, fmt);
297         if (ast_vasprintf(&buffer, fmt, ap) < 0) {
298                 va_end(ap);
299                 return 1;
300         }
301         va_end(ap);
302
303         if (dbfcmd(dbproc, buffer) == FAIL) {
304                 free(buffer);
305                 return 1;
306         }
307
308         free(buffer);
309
310         if (dbsqlexec(dbproc) == FAIL) {
311                 return 1;
312         }
313
314         /* Consume the result set (we don't really care about the result, though) */
315         while (dbresults(dbproc) != NO_MORE_RESULTS) {
316                 while (dbnextrow(dbproc) != NO_MORE_ROWS);
317         }
318
319         return 0;
320 }
321
322 static int mssql_disconnect(void)
323 {
324         if (settings->dbproc) {
325                 dbclose(settings->dbproc);
326                 settings->dbproc = NULL;
327         }
328
329         settings->connected = 0;
330
331         return 0;
332 }
333
334 static int mssql_connect(void)
335 {
336         LOGINREC *login;
337
338         if ((login = dblogin()) == NULL) {
339                 ast_log(LOG_ERROR, "Unable to allocate login structure for db-lib\n");
340                 return -1;
341         }
342
343         DBSETLAPP(login,     "TSQL");
344         DBSETLUSER(login,    (char *) settings->username);
345         DBSETLPWD(login,     (char *) settings->password);
346         DBSETLCHARSET(login, (char *) settings->charset);
347         DBSETLNATLANG(login, (char *) settings->language);
348
349         if ((settings->dbproc = dbopen(login, (char *) settings->hostname)) == NULL) {
350                 ast_log(LOG_ERROR, "Unable to connect to %s\n", settings->hostname);
351                 dbloginfree(login);
352                 return -1;
353         }
354
355         dbloginfree(login);
356
357         if (dbuse(settings->dbproc, (char *) settings->database) == FAIL) {
358                 ast_log(LOG_ERROR, "Unable to select database %s\n", settings->database);
359                 goto failed;
360         }
361
362         if (execute_and_consume(settings->dbproc, "SELECT 1 FROM [%s]", settings->table)) {
363                 ast_log(LOG_ERROR, "Unable to find table '%s'\n", settings->table);
364                 goto failed;
365         }
366
367         /* Check to see if we have a userfield column in the table */
368         if (execute_and_consume(settings->dbproc, "SELECT userfield FROM [%s] WHERE 1 = 0", settings->table)) {
369                 ast_log(LOG_NOTICE, "Unable to find 'userfield' column in table '%s'\n", settings->table);
370                 settings->has_userfield = 0;
371         } else {
372                 settings->has_userfield = 1;
373         }
374
375         settings->connected = 1;
376
377         return 0;
378
379 failed:
380         dbclose(settings->dbproc);
381         settings->dbproc = NULL;
382         return -1;
383 }
384
385 static int tds_unload_module(void)
386 {
387         if (settings) {
388                 ast_mutex_lock(&tds_lock);
389                 mssql_disconnect();
390                 ast_mutex_unlock(&tds_lock);
391
392                 ast_string_field_free_memory(settings);
393                 ast_free(settings);
394         }
395
396         ast_cdr_unregister(name);
397
398         dbexit();
399
400         return 0;
401 }
402
403 static int tds_error_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
404 {
405         ast_log(LOG_ERROR, "%s (%d)\n", dberrstr, dberr);
406
407         if (oserr != DBNOERR) {
408                 ast_log(LOG_ERROR, "%s (%d)\n", oserrstr, oserr);
409         }
410
411         return INT_CANCEL;
412 }
413
414 static int tds_message_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line)
415 {
416         ast_debug(1, "Msg %d, Level %d, State %d, Line %d\n", msgno, severity, msgstate, line);
417         ast_log(LOG_NOTICE, "%s\n", msgtext);
418
419         return 0;
420 }
421
422 static int tds_load_module(int reload)
423 {
424         struct ast_config *cfg;
425         const char *ptr = NULL;
426         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
427
428         cfg = ast_config_load(config, config_flags);
429         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
430                 ast_log(LOG_NOTICE, "Unable to load TDS config for CDRs: %s\n", config);
431                 return 0;
432         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
433                 return 0;
434
435         if (!ast_variable_browse(cfg, "global")) {
436                 /* nothing configured */
437                 ast_config_destroy(cfg);
438                 return 0;
439         }
440
441         ast_mutex_lock(&tds_lock);
442
443         /* Clear out any existing settings */
444         ast_string_field_init(settings, 0);
445
446         ptr = ast_variable_retrieve(cfg, "global", "hostname");
447         if (ptr) {
448                 ast_string_field_set(settings, hostname, ptr);
449         } else {
450                 ast_log(LOG_ERROR, "Failed to connect: Database server hostname not specified.\n");
451                 goto failed;
452         }
453
454         ptr = ast_variable_retrieve(cfg, "global", "dbname");
455         if (ptr) {
456                 ast_string_field_set(settings, database, ptr);
457         } else {
458                 ast_log(LOG_ERROR, "Failed to connect: Database dbname not specified.\n");
459                 goto failed;
460         }
461
462         ptr = ast_variable_retrieve(cfg, "global", "user");
463         if (ptr) {
464                 ast_string_field_set(settings, username, ptr);
465         } else {
466                 ast_log(LOG_ERROR, "Failed to connect: Database dbuser not specified.\n");
467                 goto failed;
468         }
469
470         ptr = ast_variable_retrieve(cfg, "global", "password");
471         if (ptr) {
472                 ast_string_field_set(settings, password, ptr);
473         } else {
474                 ast_log(LOG_ERROR, "Failed to connect: Database password not specified.\n");
475                 goto failed;
476         }
477
478         ptr = ast_variable_retrieve(cfg, "global", "charset");
479         if (ptr) {
480                 ast_string_field_set(settings, charset, ptr);
481         } else {
482                 ast_string_field_set(settings, charset, "iso_1");
483         }
484
485         ptr = ast_variable_retrieve(cfg, "global", "language");
486         if (ptr) {
487                 ast_string_field_set(settings, language, ptr);
488         } else {
489                 ast_string_field_set(settings, language, "us_english");
490         }
491
492         ptr = ast_variable_retrieve(cfg, "global", "table");
493         if (ptr) {
494                 ast_string_field_set(settings, table, ptr);
495         } else {
496                 ast_log(LOG_NOTICE, "Table name not specified, using 'cdr' by default.\n");
497                 ast_string_field_set(settings, table, "cdr");
498         }
499
500         mssql_disconnect();
501
502         if (mssql_connect()) {
503                 /* We failed to connect (mssql_connect takes care of logging it) */
504                 goto failed;
505         }
506
507         ast_mutex_unlock(&tds_lock);
508         ast_config_destroy(cfg);
509
510         return 1;
511
512 failed:
513         ast_mutex_unlock(&tds_lock);
514         ast_config_destroy(cfg);
515
516         return 0;
517 }
518
519 static int reload(void)
520 {
521         return tds_load_module(1);
522 }
523
524 static int load_module(void)
525 {
526         if (dbinit() == FAIL) {
527                 ast_log(LOG_ERROR, "Failed to initialize FreeTDS db-lib\n");
528                 return AST_MODULE_LOAD_DECLINE;
529         }
530
531         dberrhandle(tds_error_handler);
532         dbmsghandle(tds_message_handler);
533
534         settings = ast_calloc(1, sizeof(*settings));
535
536         if (!settings || ast_string_field_init(settings, 256)) {
537                 if (settings) {
538                         ast_free(settings);
539                         settings = NULL;
540                 }
541                 dbexit();
542                 return AST_MODULE_LOAD_DECLINE;
543         }
544
545         if (!tds_load_module(0)) {
546                 ast_string_field_free_memory(settings);
547                 ast_free(settings);
548                 settings = NULL;
549                 dbexit();
550                 return AST_MODULE_LOAD_DECLINE;
551         }
552
553         ast_cdr_register(name, ast_module_info->description, tds_log);
554
555         return AST_MODULE_LOAD_SUCCESS;
556 }
557
558 static int unload_module(void)
559 {
560         return tds_unload_module();
561 }
562
563 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "FreeTDS CDR Backend",
564                 .load = load_module,
565                 .unload = unload_module,
566                 .reload = reload,
567                );