Use the ast_vasprintf macro instead of vasprintf directly.
[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
118         accountcode = anti_injection(cdr->accountcode, 20);
119         src         = anti_injection(cdr->src, 80);
120         dst         = anti_injection(cdr->dst, 80);
121         dcontext    = anti_injection(cdr->dcontext, 80);
122         clid        = anti_injection(cdr->clid, 80);
123         channel     = anti_injection(cdr->channel, 80);
124         dstchannel  = anti_injection(cdr->dstchannel, 80);
125         lastapp     = anti_injection(cdr->lastapp, 80);
126         lastdata    = anti_injection(cdr->lastdata, 80);
127         uniqueid    = anti_injection(cdr->uniqueid, 32);
128
129         get_date(start, sizeof(start), cdr->start);
130         get_date(answer, sizeof(answer), cdr->answer);
131         get_date(end, sizeof(end), cdr->end);
132
133         ast_mutex_lock(&tds_lock);
134
135         if (settings->has_userfield) {
136                 userfield = anti_injection(cdr->userfield, AST_MAX_USER_FIELD);
137         }
138
139         /* Ensure that we are connected */
140         if (!settings->connected) {
141                 if (mssql_connect()) {
142                         /* Connect failed */
143                         goto done;
144                 }
145         }
146
147         if (settings->has_userfield) {
148                 erc = dbfcmd(settings->dbproc,
149                                          "INSERT INTO %s "
150                                          "("
151                                          "accountcode, src, dst, dcontext, clid, channel, "
152                                          "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
153                                          "billsec, disposition, amaflags, uniqueid, userfield"
154                                          ") "
155                                          "VALUES "
156                                          "("
157                                          "'%s', '%s', '%s', '%s', '%s', '%s', "
158                                          "'%s', '%s', '%s', %s, %s, %s, %ld, "
159                                          "%ld, '%s', '%s', '%s', '%s'"
160                                          ")",
161                                          settings->table,
162                                          accountcode, src, dst, dcontext, clid, channel,
163                                          dstchannel, lastapp, lastdata, start, answer, end, cdr->duration,
164                                          cdr->billsec, ast_cdr_disp2str(cdr->disposition), ast_cdr_flags2str(cdr->amaflags), uniqueid,
165                                          userfield
166                         );
167         } else {
168                 erc = dbfcmd(settings->dbproc,
169                                          "INSERT INTO %s "
170                                          "("
171                                          "accountcode, src, dst, dcontext, clid, channel, "
172                                          "dstchannel, lastapp, lastdata, start, answer, [end], duration, "
173                                          "billsec, disposition, amaflags, uniqueid"
174                                          ") "
175                                          "VALUES "
176                                          "("
177                                          "'%s', '%s', '%s', '%s', '%s', '%s', "
178                                          "'%s', '%s', '%s', %s, %s, %s, %ld, "
179                                          "%ld, '%s', '%s', '%s'"
180                                          ")",
181                                          settings->table,
182                                          accountcode, src, dst, dcontext, clid, channel,
183                                          dstchannel, lastapp, lastdata, start, answer, end, cdr->duration,
184                                          cdr->billsec, ast_cdr_disp2str(cdr->disposition), ast_cdr_flags2str(cdr->amaflags), uniqueid
185                         );
186         }
187
188         if (erc == FAIL) {
189                 ast_log(LOG_ERROR, "Failed to build INSERT statement, no CDR was logged.\n");
190                 goto done;
191         }
192
193         if (dbsqlexec(settings->dbproc) == FAIL) {
194                 ast_log(LOG_ERROR, "Failed to execute INSERT statement, no CDR was logged.\n");
195                 goto done;
196         }
197
198         /* Consume any results we might get back (this is more of a sanity check than
199          * anything else, since an INSERT shouldn't return results). */
200         while (dbresults(settings->dbproc) != NO_MORE_RESULTS) {
201                 while (dbnextrow(settings->dbproc) != NO_MORE_ROWS);
202         }
203
204         res = 0;
205
206 done:
207         ast_mutex_unlock(&tds_lock);
208
209         ast_free(accountcode);
210         ast_free(src);
211         ast_free(dst);
212         ast_free(dcontext);
213         ast_free(clid);
214         ast_free(channel);
215         ast_free(dstchannel);
216         ast_free(lastapp);
217         ast_free(lastdata);
218         ast_free(uniqueid);
219
220         if (userfield) {
221                 ast_free(userfield);
222         }
223
224         return res;
225 }
226
227 static char *anti_injection(const char *str, int len)
228 {
229         /* Reference to http://www.nextgenss.com/papers/advanced_sql_injection.pdf */
230         char *buf;
231         char *buf_ptr, *srh_ptr;
232         char *known_bad[] = {"select", "insert", "update", "delete", "drop", ";", "--", "\0"};
233         int idx;
234
235         if (!(buf = ast_calloc(1, len + 1))) {
236                 ast_log(LOG_ERROR, "Out of memory\n");
237                 return NULL;
238         }
239
240         buf_ptr = buf;
241
242         /* Escape single quotes */
243         for (; *str && strlen(buf) < len; str++) {
244                 if (*str == '\'') {
245                         *buf_ptr++ = '\'';
246                 }
247                 *buf_ptr++ = *str;
248         }
249         *buf_ptr = '\0';
250
251         /* Erase known bad input */
252         for (idx = 0; *known_bad[idx]; idx++) {
253                 while ((srh_ptr = strcasestr(buf, known_bad[idx]))) {
254                         memmove(srh_ptr, srh_ptr + strlen(known_bad[idx]), strlen(srh_ptr + strlen(known_bad[idx])) + 1);
255                 }
256         }
257
258         return buf;
259 }
260
261 static void get_date(char *dateField, size_t len, struct timeval when)
262 {
263         /* To make sure we have date variable if not insert null to SQL */
264         if (!ast_tvzero(when)) {
265                 struct ast_tm tm;
266                 ast_localtime(&when, &tm, NULL);
267                 ast_strftime(dateField, len, "'" DATE_FORMAT "'", &tm);
268         } else {
269                 ast_copy_string(dateField, "null", len);
270         }
271 }
272
273 static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
274 {
275         va_list ap;
276         char *buffer;
277
278         va_start(ap, fmt);
279         if (ast_vasprintf(&buffer, fmt, ap) < 0) {
280                 va_end(ap);
281                 return 1;
282         }
283         va_end(ap);
284
285         if (dbfcmd(dbproc, buffer) == FAIL) {
286                 free(buffer);
287                 return 1;
288         }
289
290         free(buffer);
291
292         if (dbsqlexec(dbproc) == FAIL) {
293                 return 1;
294         }
295
296         /* Consume the result set (we don't really care about the result, though) */
297         while (dbresults(dbproc) != NO_MORE_RESULTS) {
298                 while (dbnextrow(dbproc) != NO_MORE_ROWS);
299         }
300
301         return 0;
302 }
303
304 static int mssql_disconnect(void)
305 {
306         if (settings->dbproc) {
307                 dbclose(settings->dbproc);
308                 settings->dbproc = NULL;
309         }
310
311         settings->connected = 0;
312
313         return 0;
314 }
315
316 static int mssql_connect(void)
317 {
318         LOGINREC *login;
319
320         if ((login = dblogin()) == NULL) {
321                 ast_log(LOG_ERROR, "Unable to allocate login structure for db-lib\n");
322                 return -1;
323         }
324
325         DBSETLAPP(login,     "TSQL");
326         DBSETLUSER(login,    (char *) settings->username);
327         DBSETLPWD(login,     (char *) settings->password);
328         DBSETLCHARSET(login, (char *) settings->charset);
329         DBSETLNATLANG(login, (char *) settings->language);
330
331         if ((settings->dbproc = dbopen(login, (char *) settings->hostname)) == NULL) {
332                 ast_log(LOG_ERROR, "Unable to connect to %s\n", settings->hostname);
333                 dbloginfree(login);
334                 return -1;
335         }
336
337         dbloginfree(login);
338
339         if (dbuse(settings->dbproc, (char *) settings->database) == FAIL) {
340                 ast_log(LOG_ERROR, "Unable to select database %s\n", settings->database);
341                 goto failed;
342         }
343
344         if (execute_and_consume(settings->dbproc, "SELECT 1 FROM [%s]", settings->table)) {
345                 ast_log(LOG_ERROR, "Unable to find table '%s'\n", settings->table);
346                 goto failed;
347         }
348
349         /* Check to see if we have a userfield column in the table */
350         if (execute_and_consume(settings->dbproc, "SELECT userfield FROM [%s] WHERE 1 = 0", settings->table)) {
351                 ast_log(LOG_NOTICE, "Unable to find 'userfield' column in table '%s'\n", settings->table);
352                 settings->has_userfield = 0;
353         } else {
354                 settings->has_userfield = 1;
355         }
356
357         settings->connected = 1;
358
359         return 0;
360
361 failed:
362         dbclose(settings->dbproc);
363         settings->dbproc = NULL;
364         return -1;
365 }
366
367 static int tds_unload_module(void)
368 {
369         if (settings) {
370                 ast_mutex_lock(&tds_lock);
371                 mssql_disconnect();
372                 ast_mutex_unlock(&tds_lock);
373
374                 ast_string_field_free_memory(settings);
375                 ast_free(settings);
376         }
377
378         ast_cdr_unregister(name);
379
380         dbexit();
381
382         return 0;
383 }
384
385 static int tds_error_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
386 {
387         ast_log(LOG_ERROR, "%s (%d)\n", dberrstr, dberr);
388
389         if (oserr != DBNOERR) {
390                 ast_log(LOG_ERROR, "%s (%d)\n", oserrstr, oserr);
391         }
392
393         return INT_CANCEL;
394 }
395
396 static int tds_message_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line)
397 {
398         ast_debug(1, "Msg %d, Level %d, State %d, Line %d\n", msgno, severity, msgstate, line);
399         ast_log(LOG_NOTICE, "%s\n", msgtext);
400
401         return 0;
402 }
403
404 static int tds_load_module(int reload)
405 {
406         struct ast_config *cfg;
407         const char *ptr = NULL;
408         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
409
410         cfg = ast_config_load(config, config_flags);
411         if (!cfg) {
412                 ast_log(LOG_NOTICE, "Unable to load TDS config for CDRs: %s\n", config);
413                 return 0;
414         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
415                 return 0;
416
417         if (!ast_variable_browse(cfg, "global")) {
418                 /* nothing configured */
419                 ast_config_destroy(cfg);
420                 return 0;
421         }
422
423         ast_mutex_lock(&tds_lock);
424
425         /* Clear out any existing settings */
426         ast_string_field_init(settings, 0);
427
428         ptr = ast_variable_retrieve(cfg, "global", "hostname");
429         if (ptr) {
430                 ast_string_field_set(settings, hostname, ptr);
431         } else {
432                 ast_log(LOG_ERROR, "Failed to connect: Database server hostname not specified.\n");
433                 goto failed;
434         }
435
436         ptr = ast_variable_retrieve(cfg, "global", "dbname");
437         if (ptr) {
438                 ast_string_field_set(settings, database, ptr);
439         } else {
440                 ast_log(LOG_ERROR, "Failed to connect: Database dbname not specified.\n");
441                 goto failed;
442         }
443
444         ptr = ast_variable_retrieve(cfg, "global", "user");
445         if (ptr) {
446                 ast_string_field_set(settings, username, ptr);
447         } else {
448                 ast_log(LOG_ERROR, "Failed to connect: Database dbuser not specified.\n");
449                 goto failed;
450         }
451
452         ptr = ast_variable_retrieve(cfg, "global", "password");
453         if (ptr) {
454                 ast_string_field_set(settings, password, ptr);
455         } else {
456                 ast_log(LOG_ERROR, "Failed to connect: Database password not specified.\n");
457                 goto failed;
458         }
459
460         ptr = ast_variable_retrieve(cfg, "global", "charset");
461         if (ptr) {
462                 ast_string_field_set(settings, charset, ptr);
463         } else {
464                 ast_string_field_set(settings, charset, "iso_1");
465         }
466
467         ptr = ast_variable_retrieve(cfg, "global", "language");
468         if (ptr) {
469                 ast_string_field_set(settings, language, ptr);
470         } else {
471                 ast_string_field_set(settings, language, "us_english");
472         }
473
474         ptr = ast_variable_retrieve(cfg, "global", "table");
475         if (ptr) {
476                 ast_string_field_set(settings, table, ptr);
477         } else {
478                 ast_log(LOG_NOTICE, "Table name not specified, using 'cdr' by default.\n");
479                 ast_string_field_set(settings, table, "cdr");
480         }
481
482         mssql_disconnect();
483
484         if (mssql_connect()) {
485                 /* We failed to connect (mssql_connect takes care of logging it) */
486                 goto failed;
487         }
488
489         ast_mutex_unlock(&tds_lock);
490         ast_config_destroy(cfg);
491
492         return 1;
493
494 failed:
495         ast_mutex_unlock(&tds_lock);
496         ast_config_destroy(cfg);
497
498         return 0;
499 }
500
501 static int reload(void)
502 {
503         return tds_load_module(1);
504 }
505
506 static int load_module(void)
507 {
508         if (dbinit() == FAIL) {
509                 ast_log(LOG_ERROR, "Failed to initialize FreeTDS db-lib\n");
510                 return AST_MODULE_LOAD_DECLINE;
511         }
512
513         dberrhandle(tds_error_handler);
514         dbmsghandle(tds_message_handler);
515
516         settings = ast_calloc(1, sizeof(*settings));
517
518         if (!settings || ast_string_field_init(settings, 256)) {
519                 if (settings) {
520                         ast_free(settings);
521                         settings = NULL;
522                 }
523                 dbexit();
524                 return AST_MODULE_LOAD_DECLINE;
525         }
526
527         if (!tds_load_module(0)) {
528                 ast_string_field_free_memory(settings);
529                 ast_free(settings);
530                 settings = NULL;
531                 dbexit();
532                 return AST_MODULE_LOAD_DECLINE;
533         }
534
535         ast_cdr_register(name, ast_module_info->description, tds_log);
536
537         return AST_MODULE_LOAD_SUCCESS;
538 }
539
540 static int unload_module(void)
541 {
542         return tds_unload_module();
543 }
544
545 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "FreeTDS CDR Backend",
546                 .load = load_module,
547                 .unload = unload_module,
548                 .reload = reload,
549                );