a66115b713a4d93c13fe7218d43ce9c9bf6f2ca6
[asterisk/asterisk.git] / cel / cel_tds.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008, 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 CEL logger
20  *
21  * See also
22  * \arg \ref Config_cel
23  * \arg http://www.freetds.org/
24  * \ingroup cel_drivers
25  */
26
27 /*! \verbatim
28  *
29  * Table Structure for `cel`
30  *
31
32 CREATE TABLE [dbo].[cel] (
33         [accountcode] [varchar] (20) NULL ,
34         [cidname] [varchar] (80) NULL ,
35         [cidnum] [varchar] (80) NULL ,
36         [cidani] [varchar] (80) NULL ,
37         [cidrdnis] [varchar] (80) NULL ,
38         [ciddnid] [varchar] (80) NULL ,
39         [exten] [varchar] (80) NULL ,
40         [context] [varchar] (80) NULL ,
41         [channame] [varchar] (80) NULL ,
42         [appname] [varchar] (80) NULL ,
43         [appdata] [varchar] (80) NULL ,
44         [eventtime] [datetime] NULL ,
45         [eventtype] [varchar] (32) NULL ,
46         [uniqueid] [varchar] (32) NULL ,
47         [linkedid] [varchar] (32) NULL ,
48         [amaflags] [varchar] (16) NULL ,
49         [userfield] [varchar] (32) NULL ,
50         [peer] [varchar] (32) NULL
51 ) ON [PRIMARY]
52
53 \endverbatim
54
55 */
56
57 /*** MODULEINFO
58         <depend>freetds</depend>
59         <support_level>extended</support_level>
60  ***/
61
62 #include "asterisk.h"
63
64 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
65
66 #include <time.h>
67 #include <math.h>
68
69 #include "asterisk/config.h"
70 #include "asterisk/channel.h"
71 #include "asterisk/cel.h"
72 #include "asterisk/module.h"
73 #include "asterisk/logger.h"
74
75 #include <sqlfront.h>
76 #include <sybdb.h>
77
78 #ifdef FREETDS_PRE_0_62
79 #warning "You have older TDS, you should upgrade!"
80 #endif
81
82 #define DATE_FORMAT "%Y/%m/%d %T"
83
84 #define TDS_BACKEND_NAME "CEL TDS logging backend"
85
86 static char *config = "cel_tds.conf";
87
88 struct cel_tds_config {
89         AST_DECLARE_STRING_FIELDS(
90                 AST_STRING_FIELD(connection);
91                 AST_STRING_FIELD(database);
92                 AST_STRING_FIELD(username);
93                 AST_STRING_FIELD(password);
94                 AST_STRING_FIELD(table);
95                 AST_STRING_FIELD(charset);
96                 AST_STRING_FIELD(language);
97         );
98         DBPROCESS *dbproc;
99         unsigned int connected:1;
100 };
101
102 AST_MUTEX_DEFINE_STATIC(tds_lock);
103
104 static struct cel_tds_config *settings;
105
106 static char *anti_injection(const char *, int);
107 static void get_date(char *, size_t len, struct timeval);
108
109 static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
110         __attribute__((format(printf, 2, 3)));
111
112 static int mssql_connect(void);
113 static int mssql_disconnect(void);
114
115 static void tds_log(struct ast_event *event)
116 {
117         char start[80];
118         char *accountcode_ai, *clidnum_ai, *exten_ai, *context_ai, *clid_ai, *channel_ai, *app_ai, *appdata_ai, *uniqueid_ai, *linkedid_ai, *cidani_ai, *cidrdnis_ai, *ciddnid_ai, *peer_ai, *userfield_ai;
119         RETCODE erc;
120         int attempt = 1;
121         struct ast_cel_event_record record = {
122                 .version = AST_CEL_EVENT_RECORD_VERSION,
123         };
124
125         if (ast_cel_fill_record(event, &record)) {
126                 return;
127         }
128
129         ast_mutex_lock(&tds_lock);
130
131         accountcode_ai = anti_injection(record.account_code, 20);
132         clidnum_ai     = anti_injection(record.caller_id_num, 80);
133         clid_ai        = anti_injection(record.caller_id_name, 80);
134         cidani_ai      = anti_injection(record.caller_id_ani, 80);
135         cidrdnis_ai    = anti_injection(record.caller_id_rdnis, 80);
136         ciddnid_ai     = anti_injection(record.caller_id_dnid, 80);
137         exten_ai       = anti_injection(record.extension, 80);
138         context_ai     = anti_injection(record.context, 80);
139         channel_ai     = anti_injection(record.channel_name, 80);
140         app_ai         = anti_injection(record.application_name, 80);
141         appdata_ai     = anti_injection(record.application_data, 80);
142         uniqueid_ai    = anti_injection(record.unique_id, 32);
143         linkedid_ai    = anti_injection(record.linked_id, 32);
144         userfield_ai   = anti_injection(record.user_field, 32);
145         peer_ai        = anti_injection(record.peer, 32);
146
147         get_date(start, sizeof(start), record.event_time);
148
149 retry:
150         /* Ensure that we are connected */
151         if (!settings->connected) {
152                 ast_log(LOG_NOTICE, "Attempting to reconnect to %s (Attempt %d)\n", settings->connection, attempt);
153                 if (mssql_connect()) {
154                         /* Connect failed */
155                         if (attempt++ < 3) {
156                                 goto retry;
157                         }
158                         goto done;
159                 }
160         }
161
162         erc = dbfcmd(settings->dbproc,
163                 "INSERT INTO %s "
164                 "("
165                 "accountcode,"
166                 "cidnum,"
167                 "cidname,"
168                 "cidani,"
169                 "cidrdnis,"
170                 "ciddnid,"
171                 "exten,"
172                 "context,"
173                 "channel,"
174                 "appname,"
175                 "appdata,"
176                 "eventtime,"
177                 "eventtype,"
178                 "amaflags, "
179                 "uniqueid,"
180                 "linkedid,"
181                 "userfield,"
182                 "peer"
183                 ") "
184                 "VALUES "
185                 "("
186                 "'%s'," /* accountcode */
187                 "'%s'," /* clidnum */
188                 "'%s'," /* clid */
189                 "'%s'," /* cid-ani */
190                 "'%s'," /* cid-rdnis */
191                 "'%s'," /* cid-dnid */
192                 "'%s'," /* exten */
193                 "'%s'," /* context */
194                 "'%s'," /* channel */
195                 "'%s'," /* app */
196                 "'%s'," /* appdata */
197                 "%s, "  /* eventtime */
198                 "'%s'," /* eventtype */
199                 "'%s'," /* amaflags */
200                 "'%s'," /* uniqueid */
201                 "'%s'," /* linkedid */
202                 "'%s'," /* userfield */
203                 "'%s'"  /* peer */
204                 ")",
205                 settings->table, accountcode_ai, clidnum_ai, clid_ai, cidani_ai, cidrdnis_ai,
206                 ciddnid_ai, exten_ai, context_ai, channel_ai, app_ai, appdata_ai, start,
207                 (record.event_type == AST_CEL_USER_DEFINED)
208                         ? record.user_defined_name : record.event_name,
209                                         ast_channel_amaflags2string(record.amaflag), uniqueid_ai, linkedid_ai,
210                 userfield_ai, peer_ai);
211
212         if (erc == FAIL) {
213                 if (attempt++ < 3) {
214                         ast_log(LOG_NOTICE, "Failed to build INSERT statement, retrying...\n");
215                         mssql_disconnect();
216                         goto retry;
217                 } else {
218                         ast_log(LOG_ERROR, "Failed to build INSERT statement, no CEL was logged.\n");
219                         goto done;
220                 }
221         }
222
223         if (dbsqlexec(settings->dbproc) == FAIL) {
224                 if (attempt++ < 3) {
225                         ast_log(LOG_NOTICE, "Failed to execute INSERT statement, retrying...\n");
226                         mssql_disconnect();
227                         goto retry;
228                 } else {
229                         ast_log(LOG_ERROR, "Failed to execute INSERT statement, no CEL was logged.\n");
230                         goto done;
231                 }
232         }
233
234         /* Consume any results we might get back (this is more of a sanity check than
235          * anything else, since an INSERT shouldn't return results). */
236         while (dbresults(settings->dbproc) != NO_MORE_RESULTS) {
237                 while (dbnextrow(settings->dbproc) != NO_MORE_ROWS);
238         }
239
240 done:
241         ast_mutex_unlock(&tds_lock);
242
243         ast_free(accountcode_ai);
244         ast_free(clidnum_ai);
245         ast_free(clid_ai);
246         ast_free(cidani_ai);
247         ast_free(cidrdnis_ai);
248         ast_free(ciddnid_ai);
249         ast_free(exten_ai);
250         ast_free(context_ai);
251         ast_free(channel_ai);
252         ast_free(app_ai);
253         ast_free(appdata_ai);
254         ast_free(uniqueid_ai);
255         ast_free(linkedid_ai);
256         ast_free(userfield_ai);
257         ast_free(peer_ai);
258
259         return;
260 }
261
262 static char *anti_injection(const char *str, int len)
263 {
264         /* Reference to http://www.nextgenss.com/papers/advanced_sql_injection.pdf */
265         char *buf;
266         char *buf_ptr, *srh_ptr;
267         char *known_bad[] = {"select", "insert", "update", "delete", "drop", ";", "--", "\0"};
268         int idx;
269
270         if (!(buf = ast_calloc(1, len + 1))) {
271                 ast_log(LOG_ERROR, "Out of memory\n");
272                 return NULL;
273         }
274
275         buf_ptr = buf;
276
277         /* Escape single quotes */
278         for (; *str && strlen(buf) < len; str++) {
279                 if (*str == '\'') {
280                         *buf_ptr++ = '\'';
281                 }
282                 *buf_ptr++ = *str;
283         }
284         *buf_ptr = '\0';
285
286         /* Erase known bad input */
287         for (idx = 0; *known_bad[idx]; idx++) {
288                 while ((srh_ptr = strcasestr(buf, known_bad[idx]))) {
289                         memmove(srh_ptr, srh_ptr + strlen(known_bad[idx]), strlen(srh_ptr + strlen(known_bad[idx])) + 1);
290                 }
291         }
292         return buf;
293 }
294
295 static void get_date(char *dateField, size_t len, struct timeval when)
296 {
297         /* To make sure we have date variable if not insert null to SQL */
298         if (!ast_tvzero(when)) {
299                 struct ast_tm tm;
300                 ast_localtime(&when, &tm, NULL);
301                 ast_strftime(dateField, len, "'" DATE_FORMAT "'", &tm);
302         } else {
303                 ast_copy_string(dateField, "null", len);
304         }
305 }
306
307 static int execute_and_consume(DBPROCESS *dbproc, const char *fmt, ...)
308 {
309         va_list ap;
310         char *buffer;
311
312         va_start(ap, fmt);
313         if (ast_vasprintf(&buffer, fmt, ap) < 0) {
314                 va_end(ap);
315                 return 1;
316         }
317         va_end(ap);
318
319         if (dbfcmd(dbproc, buffer) == FAIL) {
320                 ast_free(buffer);
321                 return 1;
322         }
323
324         ast_free(buffer);
325
326         if (dbsqlexec(dbproc) == FAIL) {
327                 return 1;
328         }
329
330         /* Consume the result set (we don't really care about the result, though) */
331         while (dbresults(dbproc) != NO_MORE_RESULTS) {
332                 while (dbnextrow(dbproc) != NO_MORE_ROWS);
333         }
334
335         return 0;
336 }
337
338 static int mssql_disconnect(void)
339 {
340         if (settings->dbproc) {
341                 dbclose(settings->dbproc);
342                 settings->dbproc = NULL;
343         }
344         settings->connected = 0;
345
346         return 0;
347 }
348
349 static int mssql_connect(void)
350 {
351         LOGINREC *login;
352
353         if ((login = dblogin()) == NULL) {
354                 ast_log(LOG_ERROR, "Unable to allocate login structure for db-lib\n");
355                 return -1;
356         }
357
358         DBSETLAPP(login,  "TSQL");
359         DBSETLUSER(login, (char *) settings->username);
360         DBSETLPWD(login,  (char *) settings->password);
361
362         if (!ast_strlen_zero(settings->charset)) {
363                 DBSETLCHARSET(login, (char *) settings->charset);
364         }
365
366         if (!ast_strlen_zero(settings->language)) {
367                 DBSETLNATLANG(login, (char *) settings->language);
368         }
369
370         if ((settings->dbproc = dbopen(login, (char *) settings->connection)) == NULL) {
371                 ast_log(LOG_ERROR, "Unable to connect to %s\n", settings->connection);
372                 dbloginfree(login);
373                 return -1;
374         }
375
376         dbloginfree(login);
377
378         if (dbuse(settings->dbproc, (char *) settings->database) == FAIL) {
379                 ast_log(LOG_ERROR, "Unable to select database %s\n", settings->database);
380                 goto failed;
381         }
382
383         if (execute_and_consume(settings->dbproc, "SELECT 1 FROM [%s]", settings->table)) {
384                 ast_log(LOG_ERROR, "Unable to find table '%s'\n", settings->table);
385                 goto failed;
386         }
387
388         settings->connected = 1;
389
390         return 0;
391
392 failed:
393         dbclose(settings->dbproc);
394         settings->dbproc = NULL;
395         return -1;
396 }
397
398 static int tds_unload_module(void)
399 {
400         ast_cel_backend_unregister(TDS_BACKEND_NAME);
401
402         if (settings) {
403                 ast_mutex_lock(&tds_lock);
404                 mssql_disconnect();
405                 ast_mutex_unlock(&tds_lock);
406
407                 ast_string_field_free_memory(settings);
408                 ast_free(settings);
409         }
410
411         dbexit();
412
413         return 0;
414 }
415
416 static int tds_error_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
417 {
418         ast_log(LOG_ERROR, "%s (%d)\n", dberrstr, dberr);
419
420         if (oserr != DBNOERR) {
421                 ast_log(LOG_ERROR, "%s (%d)\n", oserrstr, oserr);
422         }
423
424         return INT_CANCEL;
425 }
426
427 static int tds_message_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line)
428 {
429         ast_debug(1, "Msg %d, Level %d, State %d, Line %d\n", msgno, severity, msgstate, line);
430         ast_log(LOG_NOTICE, "%s\n", msgtext);
431
432         return 0;
433 }
434
435 static int tds_load_module(int reload)
436 {
437         struct ast_config *cfg;
438         const char *ptr = NULL;
439         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
440
441         cfg = ast_config_load(config, config_flags);
442         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
443                 ast_log(LOG_NOTICE, "Unable to load TDS config for CELs: %s\n", config);
444                 return 0;
445         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
446                 return 0;
447         }
448
449         if (!ast_variable_browse(cfg, "global")) {
450                 /* nothing configured */
451                 ast_config_destroy(cfg);
452                 ast_log(LOG_NOTICE, "cel_tds has no global category, nothing to configure.\n");
453                 return 0;
454         }
455
456         ast_mutex_lock(&tds_lock);
457
458         /* Clear out any existing settings */
459         ast_string_field_init(settings, 0);
460
461         ptr = ast_variable_retrieve(cfg, "global", "connection");
462         if (ptr) {
463                 ast_string_field_set(settings, connection, ptr);
464         } else {
465                 ast_log(LOG_ERROR, "Failed to connect: Database connection name not specified.\n");
466                 goto failed;
467         }
468
469         ptr = ast_variable_retrieve(cfg, "global", "dbname");
470         if (ptr) {
471                 ast_string_field_set(settings, database, ptr);
472         } else {
473                 ast_log(LOG_ERROR, "Failed to connect: Database dbname not specified.\n");
474                 goto failed;
475         }
476
477         ptr = ast_variable_retrieve(cfg, "global", "user");
478         if (ptr) {
479                 ast_string_field_set(settings, username, ptr);
480         } else {
481                 ast_log(LOG_ERROR, "Failed to connect: Database dbuser not specified.\n");
482                 goto failed;
483         }
484
485         ptr = ast_variable_retrieve(cfg, "global", "password");
486         if (ptr) {
487                 ast_string_field_set(settings, password, ptr);
488         } else {
489                 ast_log(LOG_ERROR, "Failed to connect: Database password not specified.\n");
490                 goto failed;
491         }
492
493         ptr = ast_variable_retrieve(cfg, "global", "charset");
494         if (ptr) {
495                 ast_string_field_set(settings, charset, ptr);
496         }
497
498         ptr = ast_variable_retrieve(cfg, "global", "language");
499         if (ptr) {
500                 ast_string_field_set(settings, language, ptr);
501         }
502
503         ptr = ast_variable_retrieve(cfg, "global", "table");
504         if (ptr) {
505                 ast_string_field_set(settings, table, ptr);
506         } else {
507                 ast_log(LOG_NOTICE, "Table name not specified, using 'cel' by default.\n");
508                 ast_string_field_set(settings, table, "cel");
509         }
510
511         mssql_disconnect();
512
513         if (mssql_connect()) {
514                 /* We failed to connect (mssql_connect takes care of logging it) */
515                 goto failed;
516         }
517
518         ast_mutex_unlock(&tds_lock);
519         ast_config_destroy(cfg);
520
521         return 1;
522
523 failed:
524         ast_mutex_unlock(&tds_lock);
525         ast_config_destroy(cfg);
526
527         return 0;
528 }
529
530 static int reload(void)
531 {
532         return tds_load_module(1);
533 }
534
535 static int load_module(void)
536 {
537         if (dbinit() == FAIL) {
538                 ast_log(LOG_ERROR, "Failed to initialize FreeTDS db-lib\n");
539                 return AST_MODULE_LOAD_DECLINE;
540         }
541
542         dberrhandle(tds_error_handler);
543         dbmsghandle(tds_message_handler);
544
545         settings = ast_calloc_with_stringfields(1, struct cel_tds_config, 256);
546
547         if (!settings) {
548                 dbexit();
549                 return AST_MODULE_LOAD_DECLINE;
550         }
551
552         if (!tds_load_module(0)) {
553                 ast_string_field_free_memory(settings);
554                 ast_free(settings);
555                 settings = NULL;
556                 dbexit();
557                 ast_log(LOG_WARNING,"cel_tds module had config problems; declining load\n");
558                 return AST_MODULE_LOAD_DECLINE;
559         }
560
561         /* Register MSSQL CEL handler */
562         if (ast_cel_backend_register(TDS_BACKEND_NAME, tds_log)) {
563                 ast_log(LOG_ERROR, "Unable to register MSSQL CEL handling\n");
564                 ast_string_field_free_memory(settings);
565                 ast_free(settings);
566                 settings = NULL;
567                 dbexit();
568                 return AST_MODULE_LOAD_DECLINE;
569         }
570
571         return AST_MODULE_LOAD_SUCCESS;
572 }
573
574 static int unload_module(void)
575 {
576         return tds_unload_module();
577 }
578
579 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "FreeTDS CEL Backend",
580         .support_level = AST_MODULE_SUPPORT_EXTENDED,
581         .load = load_module,
582         .unload = unload_module,
583         .reload = reload,
584         .load_pri = AST_MODPRI_CDR_DRIVER,
585 );