aboutsummaryrefslogtreecommitdiffstats
path: root/cdr/cdr_tds.c
blob: 69866a3ae78ecdd8ecbb88b01205c224b85d6564 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/*
 * Asterisk -- A telephony toolkit for Linux.
 *
 * FreeTDS CDR logger
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License.
 *
 *
 * Table Structure for `cdr`
 *
 * Created on: 05/20/2004 16:16
 * Last changed on: 07/27/2004 20:01

CREATE TABLE [dbo].[cdr] (
	[accountcode] [varchar] (20) NULL ,
	[src] [varchar] (80) NULL ,
	[dst] [varchar] (80) NULL ,
	[dcontext] [varchar] (80) NULL ,
	[clid] [varchar] (80) NULL ,
	[channel] [varchar] (80) NULL ,
	[dstchannel] [varchar] (80) NULL ,
	[lastapp] [varchar] (80) NULL ,
	[lastdata] [varchar] (80) NULL ,
	[start] [datetime] NULL ,
	[answer] [datetime] NULL ,
	[end] [datetime] NULL ,
	[duration] [int] NULL ,
	[billsec] [int] NULL ,
	[disposition] [varchar] (20) NULL ,
	[amaflags] [varchar] (16) NULL ,
	[uniqueid] [varchar] (32) NULL
) ON [PRIMARY]

*/

#include <sys/types.h>
#include <asterisk/config.h>
#include <asterisk/options.h>
#include <asterisk/channel.h>
#include <asterisk/cdr.h>
#include <asterisk/module.h>
#include <asterisk/logger.h>
#include "../asterisk.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <math.h>

#include <tds.h>
#include <tdsconvert.h>
#include <ctype.h>

#if !defined(TDS_INT_EXIT) 
#define TDS_PRE_0_62
#warning "You have older TDS, you should upgrade!"
#endif

#define DATE_FORMAT "%Y/%m/%d %T"

static char *desc = "MSSQL CDR Backend";
static char *name = "mssql";
static char *config = "cdr_tds.conf";

static char *hostname = NULL, *dbname = NULL, *dbuser = NULL, *password = NULL, *charset = NULL, *language = NULL;

static int connected = 0;

AST_MUTEX_DEFINE_STATIC(tds_lock);

static TDSSOCKET *tds;
static TDSLOGIN *login;
static TDSCONTEXT *context;

static char *stristr(const char*, const char*);
static char *anti_injection(const char *, int);
static void get_date(char *, struct timeval);

static int mssql_connect(void);
static int mssql_disconnect(void);

static int tds_log(struct ast_cdr *cdr)
{
	char sqlcmd[2048], start[80], answer[80], end[80];
	char *accountcode, *src, *dst, *dcontext, *clid, *channel, *dstchannel, *lastapp, *lastdata, *uniqueid;
	int res = 0;
	int retried = 0;
#ifdef TDS_PRE_0_62
	TDS_INT result_type;
#endif

	ast_mutex_lock(&tds_lock);

	memset(sqlcmd, 0, 2048);

	accountcode = anti_injection(cdr->accountcode, 20);
	src = anti_injection(cdr->src, 80);
	dst = anti_injection(cdr->dst, 80);
	dcontext = anti_injection(cdr->dcontext, 80);
	clid = anti_injection(cdr->clid, 80);
	channel = anti_injection(cdr->channel, 80);
	dstchannel = anti_injection(cdr->dstchannel, 80);
	lastapp = anti_injection(cdr->lastapp, 80);
	lastdata = anti_injection(cdr->lastdata, 80);
	uniqueid = anti_injection(cdr->uniqueid, 32);

	get_date(start, cdr->start);
	get_date(answer, cdr->answer);
	get_date(end, cdr->end);

	sprintf(
		sqlcmd,
		"INSERT INTO cdr "
		"("
			"accountcode, "
			"src, "
			"dst, "
			"dcontext, "
			"clid, "
			"channel, "
			"dstchannel, "
			"lastapp, "
			"lastdata, "
			"start, "
			"answer, "
			"[end], "
			"duration, "
			"billsec, "
			"disposition, "
			"amaflags, "
			"uniqueid"
		") "
		"VALUES "
		"("
			"'%s', "	/* accountcode */
			"'%s', "	/* src */
			"'%s', "	/* dst */
			"'%s', "	/* dcontext */
			"'%s', "	/* clid */
			"'%s', "	/* channel */
			"'%s', "	/* dstchannel */
			"'%s', "	/* lastapp */
			"'%s', "	/* lastdata */
			"%s, "		/* start */
			"%s, "		/* answer */
			"%s, "		/* end */
			"%i, "		/* duration */
			"%i, "		/* billsec */
			"'%s', "	/* disposition */
			"'%s', "	/* amaflags */
			"'%s'"		/* uniqueid */
		")",
		accountcode,
		src,
		dst,
		dcontext,
		clid,
		channel,
		dstchannel,
		lastapp,
		lastdata,
		start,
		answer,
		end,
		cdr->duration,
		cdr->billsec,
		ast_cdr_disp2str(cdr->disposition),
		ast_cdr_flags2str(cdr->amaflags),
		uniqueid
	);

	do {
		if (!connected) {
			if (mssql_connect())
				ast_log(LOG_ERROR, "Failed to reconnect to SQL database.\n");
			else
				ast_log(LOG_WARNING, "Reconnected to SQL database.\n");

			retried = 1;	/* note that we have now tried */
		}

#ifdef TDS_PRE_0_62
		if (!connected || (tds_submit_query(tds, sqlcmd) != TDS_SUCCEED) || (tds_process_simple_query(tds, &result_type) != TDS_SUCCEED || result_type != TDS_CMD_SUCCEED))
#else
		if (!connected || (tds_submit_query(tds, sqlcmd) != TDS_SUCCEED) || (tds_process_simple_query(tds) != TDS_SUCCEED))
#endif
		{
			ast_log(LOG_ERROR, "Failed to insert Call Data Record into SQL database.\n");

			mssql_disconnect();	/* this is ok even if we are already disconnected */
		}
	} while (!connected && !retried);

	free(accountcode);
	free(src);
	free(dst);
	free(dcontext);
	free(clid);
	free(channel);
	free(dstchannel);
	free(lastapp);
	free(lastdata);
	free(uniqueid);

	ast_mutex_unlock(&tds_lock);

	return res;
}

/* Return the offset of one string within another.
   Copyright (C) 1994, 1996, 1997, 2000, 2001 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA.  */

/*
 * My personal strstr() implementation that beats most other algorithms.
 * Until someone tells me otherwise, I assume that this is the
 * fastest implementation of strstr() in C.
 * I deliberately chose not to comment it.  You should have at least
 * as much fun trying to understand it, as I had to write it :-).
 *
 * Stephen R. van den Berg, berg@pool.informatik.rwth-aachen.de	*/

static char *
stristr (phaystack, pneedle)
     const char *phaystack;
     const char *pneedle;
{
  typedef unsigned chartype;

  const unsigned char *haystack, *needle;
  chartype b;
  const unsigned char *rneedle;

  haystack = (const unsigned char *) phaystack;

  if ((b = toupper(*(needle = (const unsigned char *) pneedle))))
    {
      chartype c;
      haystack--;		/* possible ANSI violation */

      {
	chartype a;
	do
	  if (!(a = toupper(*++haystack)))
	    goto ret0;
	while (a != b);
      }

      if (!(c = toupper(*++needle)))
	goto foundneedle;
      ++needle;
      goto jin;

      for (;;)
	{
	  {
	    chartype a;
	    if (0)
	    jin:{
		if ((a = toupper(*++haystack)) == c)
		  goto crest;
	      }
	    else
	      a = toupper(*++haystack);
	    do
	      {
		for (; a != b; a = toupper(*++haystack))
		  {
		    if (!a)
		      goto ret0;
		    if ((a = toupper(*++haystack)) == b)
		      break;
		    if (!a)
		      goto ret0;
		  }
	      }
	    while ((a = toupper(*++haystack)) != c);
	  }
	crest:
	  {
	    chartype a;
	    {
	      const unsigned char *rhaystack;
	      if (toupper(*(rhaystack = haystack-- + 1)) == (a = toupper(*(rneedle = needle))))
		do
		  {
		    if (!a)
		      goto foundneedle;
		    if (toupper(*++rhaystack) != (a = toupper(*++needle)))
		      break;
		    if (!a)
		      goto foundneedle;
		  }
		while (toupper(*++rhaystack) == (a = toupper(*++needle)));
	      needle = rneedle;	/* took the register-poor aproach */
	    }
	    if (!a)
	      break;
	  }
	}
    }
foundneedle:
  return (char *) haystack;
ret0:
  return 0;
}

static char *anti_injection(const char *str, int len)
{
	/* Reference to http://www.nextgenss.com/papers/advanced_sql_injection.pdf */

	char *buf;
	char *buf_ptr, *srh_ptr;
	char *known_bad[] = {"select", "insert", "update", "delete", "drop", ";", "--", "\0"};
	int idx;

	if ((buf = malloc(len + 1)) == NULL)
	{
		ast_log(LOG_ERROR, "cdr_tds:  Out of memory error\n");
		return NULL;
	}
	memset(buf, 0, len);

	buf_ptr = buf;

	/* Escape single quotes */
	for (; *str && strlen(buf) < len; str++)
	{
		if (*str == '\'')
			*buf_ptr++ = '\'';
		*buf_ptr++ = *str;
	}
	*buf_ptr = '\0';

	/* Erase known bad input */
	for (idx=0; *known_bad[idx]; idx++)
	{
		while((srh_ptr = stristr(buf, known_bad[idx]))) /* fix me! */
		{
			memmove(srh_ptr, srh_ptr+strlen(known_bad[idx]), strlen(srh_ptr+strlen(known_bad[idx]))+1);
		}
	}

	return buf;
}

static void get_date(char *dateField, struct timeval tv)
{
	struct tm tm;
	time_t t;
	char buf[80];

	/* To make sure we have date variable if not insert null to SQL */
	if (tv.tv_sec && tv.tv_usec)
	{
		t = tv.tv_sec;
		localtime_r(&t, &tm);
		strftime(buf, 80, DATE_FORMAT, &tm);
		sprintf(dateField, "'%s'", buf);
	}
	else
	{
		strcpy(dateField, "null");
	}
}

char *description(void)
{
	return desc;
}

static int mssql_disconnect(void)
{
	if (tds) {
		tds_free_socket(tds);
		tds = NULL;
	}

	if (context) {
		tds_free_context(context);
		context = NULL;
	}

	if (login) {
		tds_free_login(login);
		login = NULL;
	}

	connected = 0;

	return 0;
}

static int mssql_connect(void)
{
	TDSCONNECTINFO *connection = NULL;
	char query[128];

	/* Connect to M$SQL Server */
	if (!(login = tds_alloc_login()))
	{
		ast_log(LOG_ERROR, "tds_alloc_login() failed.\n");
		return -1;
	}
	
	tds_set_server(login, hostname);
	tds_set_user(login, dbuser);
	tds_set_passwd(login, password);
	tds_set_app(login, "TSQL");
	tds_set_library(login, "TDS-Library");
#ifndef TDS_PRE_0_62
	tds_set_client_charset(login, charset);
#endif
	tds_set_language(login, language);
	tds_set_packet(login, 512);
	tds_set_version(login, 7, 0);

	if (!(context = tds_alloc_context()))
	{
		ast_log(LOG_ERROR, "tds_alloc_context() failed.\n");
		goto connect_fail;
	}

	if (!(tds = tds_alloc_socket(context, 512))) {
		ast_log(LOG_ERROR, "tds_alloc_socket() failed.\n");
		goto connect_fail;
	}

	tds_set_parent(tds, NULL);
	connection = tds_read_config_info(tds, login, context->locale);
	if (!connection)
	{
		ast_log(LOG_ERROR, "tds_read_config() failed.\n");
		goto connect_fail;
	}

	if (tds_connect(tds, connection) == TDS_FAIL)
	{
		ast_log(LOG_ERROR, "Failed to connect to MSSQL server.\n");
		tds = NULL;	/* freed by tds_connect() on error */
		tds_free_connect(connection);
		connection = NULL;
		goto connect_fail;
	}
	tds_free_connect(connection);
	connection = NULL;

	sprintf(query, "USE %s", dbname);
#ifdef TDS_PRE_0_62
	if ((tds_submit_query(tds, query) != TDS_SUCCEED) || (tds_process_simple_query(tds, &result_type) != TDS_SUCCEED || result_type != TDS_CMD_SUCCEED))
#else
	if ((tds_submit_query(tds, query) != TDS_SUCCEED) || (tds_process_simple_query(tds) != TDS_SUCCEED))
#endif
	{
		ast_log(LOG_ERROR, "Could not change database (%s)\n", dbname);
		goto connect_fail;
	}

	connected = 1;
	return 0;

connect_fail:
	mssql_disconnect();
	return -1;
}

static int tds_unload_module(void)
{
	mssql_disconnect();

	ast_cdr_unregister(name);

	if (hostname) free(hostname);
	if (dbname) free(dbname);
	if (dbuser) free(dbuser);
	if (password) free(password);
	if (charset) free(charset);
	if (language) free(language);

	return 0;
}

static int tds_load_module(void)
{
	int res = 0;
	struct ast_config *cfg;
	struct ast_variable *var;
	char *ptr = NULL;
#ifdef TDS_PRE_0_62
	TDS_INT result_type;
#endif

	cfg = ast_config_load(config);
	if (!cfg) {
		ast_log(LOG_NOTICE, "Unable to load config for MSSQL CDR's: %s\n", config);
		return 0;
	}

	var = ast_variable_browse(cfg, "global");
	if (!var) /* nothing configured */
		return 0;

	ptr = ast_variable_retrieve(cfg, "global", "hostname");
	if (ptr)
		hostname = strdup(ptr);
	else
		ast_log(LOG_ERROR,"Database server hostname not specified.\n");

	ptr = ast_variable_retrieve(cfg, "global", "dbname");
	if (ptr)
		dbname = strdup(ptr);
	else
		ast_log(LOG_ERROR,"Database dbname not specified.\n");

	ptr = ast_variable_retrieve(cfg, "global", "user");
	if (ptr)
		dbuser = strdup(ptr);
	else
		ast_log(LOG_ERROR,"Database dbuser not specified.\n");

	ptr = ast_variable_retrieve(cfg, "global", "password");
	if (ptr)
		password = strdup(ptr);
	else
		ast_log(LOG_ERROR,"Database password not specified.\n");

	ptr = ast_variable_retrieve(cfg, "global", "charset");
	if (ptr)
		charset = strdup(ptr);
	else
		charset = strdup("iso_1");

	ptr = ast_variable_retrieve(cfg, "global", "language");
	if (ptr)
		language = strdup(ptr);
	else
		language = strdup("us_english");

	ast_config_destroy(cfg);

	mssql_connect();

	/* Register MSSQL CDR handler */
	res = ast_cdr_register(name, desc, tds_log);
	if (res)
	{
		ast_log(LOG_ERROR, "Unable to register MSSQL CDR handling\n");
	}

	return res;
}

int reload(void)
{
	tds_unload_module();
	return tds_load_module();
}

int load_module(void)
{
	return tds_load_module();
}

int unload_module(void)
{
	return tds_unload_module();
}

int usecount(void)
{
	/* Simplistic use count */
	if (ast_mutex_trylock(&tds_lock)) {
		return 1;
	} else {
		ast_mutex_unlock(&tds_lock);
		return 0;
	}
}

char *key()
{
	return ASTERISK_GPL_KEY;
}