forked from willamowius/gnugk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gkacct.cxx
1069 lines (933 loc) · 33.6 KB
/
gkacct.cxx
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* gkacct.cxx
*
* Accounting modules for GNU Gatekeeper. Provides generic
* support for accounting to the gatekeeper.
*
* Copyright (c) 2003, Quarcom FHU, Michal Zygmuntowicz
* Copyright (c) 2005-2019, Jan Willamowius
*
* This work is published under the GNU Public License version 2 (GPLv2)
* see file COPYING for details.
* We also explicitly grant the right to link this code
* with the OpenH323/H323Plus and OpenSSL library.
*
*/
// avoid warning in PTLib object.h
#if (!_WIN32)
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if (GCC_VERSION >= 40400)
#pragma GCC diagnostic ignored "-Wstrict-overflow"
#endif
#endif
#include <ptlib.h>
#include <h225.h>
#include "gk_const.h"
#include "h323util.h"
#include "stl_supp.h"
#include "Toolkit.h"
#include "gktimer.h"
#include "snmp.h"
#include "gkacct.h"
using std::find;
using std::vector;
/// Name of the config file section for accounting configuration
namespace {
const char* GkAcctSectionName = "Gatekeeper::Acct";
}
extern const char* CallTableSection;
GkAcctLogger::GkAcctLogger(const char* moduleName, const char* cfgSecName)
: NamedObject(moduleName), m_controlFlag(Required), m_defaultStatus(Fail),
m_enabledEvents(AcctAll), m_supportedEvents(AcctNone), m_config(GkConfig()),
m_configSectionName(cfgSecName)
{
if (m_configSectionName.IsEmpty())
m_configSectionName = moduleName;
const PStringArray control(m_config->GetString(GkAcctSectionName, moduleName, "").Tokenise(";,"));
if (control.GetSize() < 1) {
PTRACE(1, "GKACCT\tEmpty config entry for module " << moduleName);
} else if (strcasecmp(moduleName, "default") == 0) {
m_controlFlag = Required;
m_defaultStatus = Toolkit::AsBool(control[0]) ? Ok : Fail;
m_supportedEvents = AcctAll;
} else if (control[0] *= "optional") {
m_controlFlag = Optional;
} else if (control[0] *= "sufficient") {
m_controlFlag = Sufficient;
} else if (control[0] *= "alternative") {
m_controlFlag = Alternative;
}
if (control.GetSize() > 1)
m_enabledEvents = GetEvents(control);
PTRACE(1, "GKACCT\tCreated module " << moduleName << " with event mask "
<< PString(PString::Unsigned, (long)m_enabledEvents, 16));
}
GkAcctLogger::~GkAcctLogger()
{
PTRACE(1, "GKACCT\tDestroyed module " << GetName());
}
int GkAcctLogger::GetEvents(const PStringArray & tokens) const
{
int mask = 0;
for (PINDEX i = 1; i < tokens.GetSize(); i++) {
const PString & token = tokens[i];
if (token *= "start")
mask |= AcctStart;
else if (token *= "stop")
mask |= AcctStop;
else if (token *= "update")
mask |= AcctUpdate;
else if (token *= "alert")
mask |= AcctAlert;
else if (token *= "connect")
mask |= AcctConnect;
else if (token *= "register")
mask |= AcctRegister;
else if (token *= "unregister")
mask |= AcctUnregister;
else if (token *= "on")
mask |= AcctOn;
else if (token *= "off")
mask |= AcctOff;
else if (token *= "reject")
mask |= AcctReject;
else if (token *= "mediafail")
mask |= AcctMediaFail;
}
return mask;
}
GkAcctLogger::Status GkAcctLogger::Log(
AcctEvent evt, /// accounting event to log
const callptr & /*call*/ /// a call associated with the event (if any)
)
{
return (evt & m_enabledEvents & m_supportedEvents) ? m_defaultStatus : Next;
}
GkAcctLogger::Status GkAcctLogger::Log(
AcctEvent evt, /// accounting event to log
const endptr & /*ep*/ /// endpoint associated with the event (if any)
)
{
return (evt & m_enabledEvents & m_supportedEvents) ? m_defaultStatus : Next;
}
void GkAcctLogger::SetupAcctParams(
/// CDR parameters (name => value) associations
std::map<PString, PString> & params,
/// call (if any) associated with an accounting event being logged
const callptr & call,
/// timestamp formatting string
const PString & timestampFormat
) const
{
OpalGloballyUniqueID eventID;
PIPSocket::Address addr;
WORD port = 0;
time_t t;
vector<PIPSocket::Address> interfaces;
Toolkit* const toolkit = Toolkit::Instance();
toolkit->GetGKHome(interfaces);
params["event-uuid"] = eventID.AsString();
params["event-time"] = toolkit->AsString(PTime(), timestampFormat);
params["g"] = toolkit->GKName();
if (interfaces.empty())
params["gkip"] = "";
else
params["gkip"] = interfaces.front().AsString();
if (!call)
return;
params["n"] = PString(call->GetCallNumber());
params["u"] = GetUsername(call);
params["d"] = call->GetDuration();
params["c"] = call->GetDisconnectCause();
params["cause-translated"] = call->GetDisconnectCauseTranslated();
params["s"] = call->GetAcctSessionId();
params["p"] = call->GetPostDialDelay();
params["r"] = call->GetReleaseSource();
params["t"] = call->GetTotalCallDuration();
params["CallId"] = ::AsString(call->GetCallIdentifier());
params["ConfId"] = ::AsString(call->GetConferenceIdentifier());
params["CallLink"] = call->GetCallLinkage();
t = call->GetSetupTime();
params["setup-time"] = t ? toolkit->AsString(PTime(t), timestampFormat) : "";
t = call->GetAlertingTime();
params["alerting-time"] = t ? toolkit->AsString(PTime(t), timestampFormat) : "";
t = call->GetConnectTime();
params["connect-time"] = t ? toolkit->AsString(PTime(t), timestampFormat) : "";
t = call->GetDisconnectTime();
params["disconnect-time"] = t ? toolkit->AsString(PTime(t), timestampFormat) : "";
params["ring-time"] = call->GetRingTime();
if (call->GetSrcSignalAddr(addr, port)) {
params["caller-ip"] = addr.AsString();
params["caller-port"] = port;
} else {
params["caller-ip"] = "";
params["caller-port"] = 0;
}
params["src-info"] = call->GetSrcInfo();
params["Calling-Station-Id"] = GetCallingStationId(call);
addr = (DWORD)0;
port = 0;
if (call->GetDestSignalAddr(addr, port)) {
params["callee-ip"] = addr.AsString();
params["callee-port"] = port;
} else {
params["callee-ip"] = "";
params["callee-port"] = 0;
}
params["dest-info"] = call->GetDestInfo();
params["Called-Station-Id"] = GetCalledStationId(call);
params["Dialed-Number"] = GetDialedNumber(call);
if (GetConfig()->GetBoolean(CallTableSection, "SetCalledStationIdToDialedIP", false)
&& IsIPAddress(params["Dialed-Number"])) {
params["Called-Station-Id"] = params["Dialed-Number"];
}
endptr caller;
if ((caller = call->GetCallingParty())) {
params["caller-epid"] = caller->GetEndpointIdentifier().GetValue();
} else {
params["caller-epid"] = "";
}
endptr callee;
if ((callee = call->GetCalledParty())) {
params["callee-epid"] = callee->GetEndpointIdentifier().GetValue();
} else {
params["callee-epid"] = "";
}
params["call-attempts"] = PString(call->GetNoCallAttempts());
params["last-cdr"] = call->GetNoRemainingRoutes() > 0 ? "0" : "1";
if ((call->GetCallerAudioIP(addr, port))) {
params["caller-media-ip"] = addr.AsString();
} else {
params["caller-media-ip"] = "";
}
if ((call->GetCalledAudioIP(addr, port))) {
params["callee-media-ip"] = addr.AsString();
} else {
params["callee-media-ip"] = "";
}
params["bandwidth"] = call->GetBandwidth();
params["client-auth-id"] = call->GetClientAuthId();
PString vendor, version;
call->GetCallingVendor(vendor, version);
params["caller-vendor"] = vendor + " " + version;
call->GetCalledVendor(vendor, version);
params["callee-vendor"] = vendor + " " + version;
params["sinfo-ip"] = call->GetSInfoIP();
params["bandwidth-kbps"] = PString(call->GetBandwidth() / 10); // in kbps
params["caller-audio-codec"] = call->GetCallerAudioCodec();
params["callee-audio-codec"] = call->GetCalledAudioCodec();
params["caller-video-codec"] = call->GetCallerVideoCodec();
params["callee-video-codec"] = call->GetCalledVideoCodec();
params["caller-audio-bitrate"] = PString(call->GetCallerAudioBitrate() / 10); // in kbps
params["callee-audio-bitrate"] = PString(call->GetCalledAudioBitrate() / 10); // in kbps
params["caller-video-bitrate"] = PString(call->GetCallerVideoBitrate() / 10); // in kbps
params["callee-video-bitrate"] = PString(call->GetCalledVideoBitrate() / 10); // in kbps
PString encryption = "On";
if (!params["caller-audio-codec"].IsEmpty() && params["caller-audio-codec"].Find("H.235") == P_MAX_INDEX)
encryption = "Off";
if (!params["callee-audio-codec"].IsEmpty() && params["callee-audio-codec"].Find("H.235") == P_MAX_INDEX)
encryption = "Off";
if (!params["caller-video-codec"].IsEmpty() && params["caller-video-codec"].Find("H.235") == P_MAX_INDEX)
encryption = "Off";
if (!params["callee-video-codec"].IsEmpty() && params["callee-video-codec"].Find("H.235") == P_MAX_INDEX)
encryption = "Off";
if (params["caller-audio-codec"].IsEmpty() && params["callee-audio-codec"].IsEmpty()
&& params["caller-video-codec"].IsEmpty() && params["callee-video-codec"].IsEmpty())
encryption = "Off";
params["encryption"] = encryption;
params["codec"] = call->GetCallerAudioCodec(); // deprecated
params["media-oip"] = addr.AsString(); // deprecated
}
void GkAcctLogger::SetupAcctEndpointParams(
/// parameter (name => value) associations
std::map<PString, PString> & params,
/// endpoint associated with an accounting event being logged
const endptr & ep,
/// timestamp formatting string
const PString & timestampFormat
) const
{
OpalGloballyUniqueID eventID;
PIPSocket::Address addr;
WORD port = 0;
vector<PIPSocket::Address> interfaces;
Toolkit::Instance()->GetGKHome(interfaces);
params["event-uuid"] = eventID.AsString();
params["event-time"] = Toolkit::Instance()->AsString(PTime(), timestampFormat);
params["g"] = Toolkit::GKName();
if (interfaces.empty())
params["gkip"] = "";
else
params["gkip"] = interfaces.front().AsString();
if (!ep)
return;
H225_TransportAddress sigip = ep->GetCallSignalAddress();
if (GetIPAndPortFromTransportAddr(sigip, addr, port)) {
params["endpoint-ip"] = addr.AsString();
params["endpoint-port"] = port;
} else {
params["endpoint-ip"] = "";
params["endpoint-port"] = 0;
}
PString vendor, version;
ep->GetEndpointInfo(vendor, version);
params["endpoint-vendor"] = vendor + " " + version;
PString aliasString = AsString(ep->GetAliases(), false);
aliasString.Replace(PString("="), PString(","), true); // make list comma separated
params["aliases"] = aliasString;
// The username is always the last in the Alias List
PStringArray aliasList = aliasString.Tokenise(",");
if (aliasList.GetSize() > 0) {
params["u"] = aliasList[aliasList.GetSize()-1];
} else {
params["u"] = "";
}
params["Calling-Station-Id"] = GetBestAliasAddressString(ep->GetAliases(), false,
AliasAddressTagMask(H225_AliasAddress::e_dialedDigits) | AliasAddressTagMask(H225_AliasAddress::e_partyNumber));
params["epid"] = ep->GetEndpointIdentifier().GetValue();
}
void GkAcctLogger::SetupAcctParams(
/// CDR parameters (name => value) associations
std::map<PString, PString> & params
) const
{
PIPSocket::Address addr;
vector<PIPSocket::Address> interfaces;
Toolkit* const toolkit = Toolkit::Instance();
toolkit->GetGKHome(interfaces);
params["g"] = toolkit->GKName();
if (interfaces.empty())
params["gkip"] = "";
else
params["gkip"] = interfaces.front().AsString();
}
PString GkAcctLogger::ReplaceAcctParams(
/// parametrized CDR string
const PString & cdrStr,
/// parameter values
const std::map<PString, PString> & params
) const
{
PString finalCDR((const char*)cdrStr);
PINDEX len = finalCDR.GetLength();
PINDEX pos = 0;
while (pos != P_MAX_INDEX && pos < len) {
pos = finalCDR.Find('%', pos);
if (pos++ == P_MAX_INDEX)
break;
if (pos >= len) // strings ending with '%' - special case
break;
const char c = finalCDR[pos]; // char next after '%'
if (c == '%') { // replace %% with %
finalCDR.Delete(pos, 1);
len--;
} else if (c == '{') { // escaped syntax (%{Name})
const PINDEX closingBrace = finalCDR.Find('}', ++pos);
if (closingBrace != P_MAX_INDEX) {
const PINDEX paramLen = closingBrace - pos;
std::map<PString, PString>::const_iterator i = params.find(finalCDR.Mid(pos, paramLen));
if (i != params.end()) {
const PINDEX escapedLen = EscapeAcctParam(i->second).GetLength();
finalCDR.Splice(EscapeAcctParam(i->second), pos - 2, paramLen + 3);
len = len + escapedLen - paramLen - 3;
pos = pos - 2 + escapedLen;
} else {
// leave unknown placeholders intact so a 2nd stage can replace them
}
}
} else { // simple syntax (%c)
std::map<PString, PString>::const_iterator i = params.find(c);
if (i != params.end()) {
const PINDEX escapedLen = EscapeAcctParam(i->second).GetLength();
finalCDR.Splice(EscapeAcctParam(i->second), pos - 1, 2);
len = len + escapedLen - 2;
pos = pos - 1 + escapedLen;
} else {
// leave unknown placeholders intact so a 2nd stage can replace them
}
}
}
return finalCDR;
}
PString GkAcctLogger::EscapeAcctParam(const PString & param) const
{
return param; // default implementation: don't escape anything
}
PString GkAcctLogger::GetUsername(
/// call (if any) associated with the RAS message
const callptr & call
) const
{
if (!call)
return PString::Empty();
const endptr callingEP = call->GetCallingParty();
PString username;
username = GetBestAliasAddressString(call->GetSourceAddress(), true,
AliasAddressTagMask(H225_AliasAddress::e_h323_ID),
AliasAddressTagMask(H225_AliasAddress::e_email_ID)
| AliasAddressTagMask(H225_AliasAddress::e_url_ID)
);
if (callingEP && (username.IsEmpty()
|| FindAlias(callingEP->GetAliases(), username) == P_MAX_INDEX))
username = GetBestAliasAddressString(callingEP->GetAliases(), false,
AliasAddressTagMask(H225_AliasAddress::e_h323_ID),
AliasAddressTagMask(H225_AliasAddress::e_email_ID)
| AliasAddressTagMask(H225_AliasAddress::e_url_ID)
);
if (username.IsEmpty())
username = GetBestAliasAddressString(call->GetSourceAddress(), false,
AliasAddressTagMask(H225_AliasAddress::e_h323_ID),
AliasAddressTagMask(H225_AliasAddress::e_email_ID)
| AliasAddressTagMask(H225_AliasAddress::e_url_ID)
);
if (username.IsEmpty())
username = call->GetCallingStationId();
if (username.IsEmpty()) {
PIPSocket::Address callingSigAddr;
WORD callingSigPort;
if (call->GetSrcSignalAddr(callingSigAddr, callingSigPort)
&& callingSigAddr.IsValid())
username = callingSigAddr.AsString();
}
return username;
}
PString GkAcctLogger::GetCallingStationId(
/// call associated with the accounting event
const callptr & call
) const
{
if (!call)
return PString::Empty();
PString id = call->GetCallingStationId();
if (!id)
return id;
if (id.IsEmpty())
id = GetBestAliasAddressString(call->GetSourceAddress(), false,
AliasAddressTagMask(H225_AliasAddress::e_dialedDigits)
| AliasAddressTagMask(H225_AliasAddress::e_partyNumber)
);
if (id.IsEmpty()) {
const endptr callingEP = call->GetCallingParty();
if (callingEP)
id = GetBestAliasAddressString(callingEP->GetAliases(), false,
AliasAddressTagMask(H225_AliasAddress::e_dialedDigits)
| AliasAddressTagMask(H225_AliasAddress::e_partyNumber)
);
}
if (id.IsEmpty()) {
PIPSocket::Address callingSigAddr;
WORD callingSigPort = 0;
if (call->GetSrcSignalAddr(callingSigAddr, callingSigPort)
&& callingSigAddr.IsValid())
id = ::AsString(callingSigAddr, callingSigPort);
}
return id;
}
PString GkAcctLogger::GetCalledStationId(
/// call associated with the accounting event
const callptr & call
) const
{
if (!call)
return PString::Empty();
PString id = call->GetCalledStationId();
if (!id)
return id;
if (id.IsEmpty())
id = GetBestAliasAddressString(call->GetDestinationAddress(), false,
AliasAddressTagMask(H225_AliasAddress::e_dialedDigits)
| AliasAddressTagMask(H225_AliasAddress::e_partyNumber)
);
if (id.IsEmpty()) {
const endptr calledEP = call->GetCalledParty();
if (calledEP)
id = GetBestAliasAddressString(calledEP->GetAliases(), false,
AliasAddressTagMask(H225_AliasAddress::e_dialedDigits)
| AliasAddressTagMask(H225_AliasAddress::e_partyNumber)
);
}
if (id.IsEmpty()) {
PIPSocket::Address calledSigAddr;
WORD calledSigPort = 0;
if (call->GetDestSignalAddr(calledSigAddr, calledSigPort)
&& calledSigAddr.IsValid())
id = ::AsString(calledSigAddr, calledSigPort);
}
return id;
}
PString GkAcctLogger::GetDialedNumber(
/// call associated with the accounting event
const callptr & call
) const
{
if (!call)
return PString::Empty();
PString id = call->GetDialedNumber();
if (!id)
return id;
if (id.IsEmpty())
id = GetBestAliasAddressString(call->GetDestinationAddress(), false,
AliasAddressTagMask(H225_AliasAddress::e_dialedDigits)
| AliasAddressTagMask(H225_AliasAddress::e_partyNumber)
);
if (id.IsEmpty()) {
const endptr calledEP = call->GetCalledParty();
if (calledEP)
id = GetBestAliasAddressString(calledEP->GetAliases(), false,
AliasAddressTagMask(H225_AliasAddress::e_dialedDigits)
| AliasAddressTagMask(H225_AliasAddress::e_partyNumber)
);
}
if (id.IsEmpty()) {
PIPSocket::Address calledSigAddr;
WORD calledSigPort = 0;
if (call->GetDestSignalAddr(calledSigAddr, calledSigPort)
&& calledSigAddr.IsValid())
id = ::AsString(calledSigAddr, calledSigPort);
}
return id;
}
PString GkAcctLogger::GetInfo()
{
return "No information available\r\n";
}
const char* const FileAcct::m_intervalNames[] =
{
"Hourly", "Daily", "Weekly", "Monthly"
};
FileAcct::FileAcct(const char* moduleName, const char* cfgSecName)
: GkAcctLogger(moduleName, cfgSecName),
m_cdrFile(NULL), m_rotateLines(-1), m_rotateSize(-1), m_rotateInterval(-1),
m_rotateMinute(-1), m_rotateHour(-1), m_rotateDay(-1),
m_rotateTimer(GkTimerManager::INVALID_HANDLE), m_cdrLines(0),
m_standardCDRFormat(true)
{
SetSupportedEvents(FileAcctEvents);
m_cdrString = GetConfig()->GetString(GetConfigSectionName(), "CDRString", "");
m_standardCDRFormat = GetConfig()->GetBoolean(GetConfigSectionName(), "StandardCDRFormat", m_cdrString.IsEmpty() ? true : false);
m_timestampFormat = GetConfig()->GetString(GetConfigSectionName(), "TimestampFormat", "");
// determine rotation type (by lines, by size, by time)
const PString rotateCondition = GetConfig()->GetString(GetConfigSectionName(), "Rotate", "").Trim();
if (!rotateCondition) {
const char suffix = rotateCondition[rotateCondition.GetLength()-1];
if (rotateCondition[0] == 'L' || rotateCondition[0] == 'l') {
// rotate per number of lines
m_rotateLines = rotateCondition.Mid(1).AsInteger();
if (suffix == 'k' || suffix == 'K')
m_rotateLines *= 1000;
else if (suffix == 'm' || suffix == 'M')
m_rotateLines *= 1000*1000;
} else if (rotateCondition[0] == 'S' || rotateCondition[0] == 's') {
// rotate per CDR file size
m_rotateSize = rotateCondition.Mid(1).AsInteger();
if (suffix == 'k' || suffix == 'K')
m_rotateSize *= 1024;
else if (suffix == 'm' || suffix == 'M')
m_rotateSize *= 1024*1024;
} else {
for (int i = 0; i < RotationIntervalMax; i++)
if (strcasecmp(rotateCondition, m_intervalNames[i]) == 0)
m_rotateInterval = i;
if (m_rotateInterval < 0 || m_rotateInterval >= RotationIntervalMax)
PTRACE(1, "GKACCT\t" << GetName() << " unsupported rotation method: " << rotateCondition << " - rotation disabled");
else {
// time based rotation
GetRotateInterval(*GetConfig(), GetConfigSectionName());
}
}
}
m_cdrFilename = GetConfig()->GetString(GetConfigSectionName(), "DetailFile", "");
m_cdrFile = OpenCDRFile(m_cdrFilename);
if (m_cdrFile && m_cdrFile->IsOpen()) {
PTRACE(2, "GKACCT\t" << GetName() << " CDR file: " << m_cdrFile->GetFilePath());
// count an initial number of CDR lines
if (m_rotateLines > 0) {
PString s;
m_cdrFile->SetPosition(0);
while (m_cdrFile->ReadLine(s))
m_cdrLines++;
m_cdrFile->SetPosition(m_cdrFile->GetLength());
}
}
// setup rotation timer in case of time based rotation
PTime now, rotateTime;
switch (m_rotateInterval)
{
case Hourly:
rotateTime = PTime(0, m_rotateMinute, now.GetHour(), now.GetDay(),
now.GetMonth(), now.GetYear(), now.GetTimeZone()
);
if (rotateTime <= now)
rotateTime += PTimeInterval(0, 0, 0, 1); // 1 hour
m_rotateTimer = Toolkit::Instance()->GetTimerManager()->RegisterTimer(
this, &FileAcct::RotateOnTimer, rotateTime, 60*60
);
PTRACE(5, "GKACCT\t" << GetName() << " hourly rotation enabled (first "
"rotation scheduled at " << rotateTime);
break;
case Daily:
rotateTime = PTime(0, m_rotateMinute, m_rotateHour, now.GetDay(),
now.GetMonth(), now.GetYear(), now.GetTimeZone());
if (rotateTime <= now)
rotateTime += PTimeInterval(0, 0, 0, 0, 1); // 1 day
m_rotateTimer = Toolkit::Instance()->GetTimerManager()->RegisterTimer(
this, &FileAcct::RotateOnTimer, rotateTime, 60*60*24);
PTRACE(5, "GKACCT\t" << GetName() << " daily rotation enabled (first rotation scheduled at " << rotateTime);
break;
case Weekly:
rotateTime = PTime(0, m_rotateMinute, m_rotateHour, now.GetDay(), now.GetMonth(), now.GetYear(), now.GetTimeZone());
if (rotateTime.GetDayOfWeek() < m_rotateDay)
rotateTime += PTimeInterval(0, 0, 0, 0, m_rotateDay - rotateTime.GetDayOfWeek());
else if (rotateTime.GetDayOfWeek() > m_rotateDay)
rotateTime -= PTimeInterval(0, 0, 0, 0, rotateTime.GetDayOfWeek() - m_rotateDay);
if (rotateTime <= now)
rotateTime += PTimeInterval(0, 0, 0, 0, 7); // 1 week
m_rotateTimer = Toolkit::Instance()->GetTimerManager()->RegisterTimer(this, &FileAcct::RotateOnTimer, rotateTime, 60*60*24*7);
PTRACE(5, "GKACCT\t" << GetName() << " weekly rotation enabled (first rotation scheduled at " << rotateTime);
break;
case Monthly:
rotateTime = PTime(0, m_rotateMinute, m_rotateHour, 1, now.GetMonth(), now.GetYear(), now.GetTimeZone());
rotateTime += PTimeInterval(0, 0, 0, 0, m_rotateDay - 1);
while (rotateTime.GetMonth() != now.GetMonth())
rotateTime -= PTimeInterval(0, 0, 0, 0, 1); // 1 day
if (rotateTime <= now) {
rotateTime = PTime(0, m_rotateMinute, m_rotateHour, 1,
now.GetMonth() + (now.GetMonth() == 12 ? -11 : 1),
now.GetYear() + (now.GetMonth() == 12 ? 1 : 0),
now.GetTimeZone());
const int month = rotateTime.GetMonth();
rotateTime += PTimeInterval(0, 0, 0, 0, m_rotateDay - 1);
while (rotateTime.GetMonth() != month)
rotateTime -= PTimeInterval(0, 0, 0, 0, 1); // 1 day
}
m_rotateTimer = Toolkit::Instance()->GetTimerManager()->RegisterTimer( this, &FileAcct::RotateOnTimer, rotateTime);
PTRACE(5, "GKACCT\t" << GetName() << " monthly rotation enabled (first rotation scheduled at " << rotateTime);
break;
}
}
FileAcct::~FileAcct()
{
if (m_rotateTimer != GkTimerManager::INVALID_HANDLE)
Toolkit::Instance()->GetTimerManager()->UnregisterTimer(m_rotateTimer);
PWaitAndSignal lock(m_cdrFileMutex);
if (m_cdrFile) {
m_cdrFile->Close();
delete m_cdrFile;
}
}
void FileAcct::GetRotateInterval(PConfig & cfg, const PString & section)
{
PString s;
if (m_rotateInterval == Hourly)
m_rotateMinute = cfg.GetInteger(section, "RotateTime", 59);
else {
s = cfg.GetString(section, "RotateTime", "00:59");
m_rotateHour = s.AsInteger();
m_rotateMinute = 0;
if (s.Find(':') != P_MAX_INDEX)
m_rotateMinute = s.Mid(s.Find(':') + 1).AsInteger();
if (m_rotateHour < 0 || m_rotateHour > 23 || m_rotateMinute < 0 || m_rotateMinute > 59) {
PTRACE(1, "GKACCT\t" << GetName() << " invalid RotateTime specified: " << s);
m_rotateMinute = 59;
m_rotateHour = 0;
}
}
if (m_rotateInterval == Weekly) {
s = cfg.GetString(section, "RotateDay", "Sun");
if (strspn(s, "0123456") == (size_t)s.GetLength()) {
m_rotateDay = s.AsInteger();
} else {
std::map<PCaselessString, int> dayNames;
dayNames["sun"] = 0; dayNames["sunday"] = 0;
dayNames["mon"] = 1; dayNames["monday"] = 1;
dayNames["tue"] = 2; dayNames["tuesday"] = 2;
dayNames["wed"] = 3; dayNames["wednesday"] = 3;
dayNames["thu"] = 4; dayNames["thursday"] = 4;
dayNames["fri"] = 5; dayNames["friday"] = 5;
dayNames["sat"] = 6; dayNames["saturday"] = 6;
std::map<PCaselessString, int>::const_iterator i = dayNames.find(s);
m_rotateDay = (i != dayNames.end()) ? i->second : -1;
}
if (m_rotateDay < 0 || m_rotateDay > 6) {
PTRACE(1, "GKACCT\t" << GetName() << " invalid RotateDay specified: " << s);
m_rotateDay = 0;
}
} else if (m_rotateInterval == Monthly) {
m_rotateDay = cfg.GetInteger(section, "RotateDay", 1);
if (m_rotateDay < 1 || m_rotateDay > 31) {
PTRACE(1, "GKACCT\t" << GetName() << " invalid RotateDay specified: " << cfg.GetString(section, "RotateDay", ""));
m_rotateDay = 1;
}
}
}
GkAcctLogger::Status FileAcct::Log(GkAcctLogger::AcctEvent evt, const callptr & call)
{
if ((evt & GetEnabledEvents() & GetSupportedEvents()) == 0)
return Next;
if (!call) {
PTRACE(1, "GKACCT\t" << GetName() << " - missing call info for event " << evt);
return Fail;
}
PString cdrString;
if (!GetCDRText(cdrString, evt, call)) {
PTRACE(2, "GKACCT\t" << GetName() << " - unable to get CDR text for "
"event " << evt << ", call no. " << call->GetCallNumber());
return Fail;
}
PWaitAndSignal lock(m_cdrFileMutex);
if (m_cdrFile && m_cdrFile->IsOpen()) {
if (m_cdrFile->WriteLine(PString(cdrString))) {
PTRACE(5, "GKACCT\t" << GetName() << " - CDR string for event "
<< evt << ", call no. " << call->GetCallNumber() << ": " << cdrString);
m_cdrLines++;
if (IsRotationNeeded())
Rotate();
return Ok;
} else
PTRACE(1, "GKACCT\t" << GetName() << " - write CDR text for event "
<< evt << ", call no. " << call->GetCallNumber()
<< " failed: " << m_cdrFile->GetErrorText());
} else
PTRACE(1, "GKACCT\t" << GetName() << " - write CDR text for event "
<< evt << ", for call no. " << call->GetCallNumber()
<< " failed: CDR file is closed");
SNMP_TRAP(6, SNMPError, Accounting, GetName() + " failed");
return Fail;
}
bool FileAcct::GetCDRText(PString & cdrString, AcctEvent evt, const callptr & call)
{
if ((evt & AcctStop) != AcctStop || !call)
return false;
if (m_standardCDRFormat)
cdrString = call->GenerateCDR(m_timestampFormat);
else {
std::map<PString, PString> params;
SetupAcctParams(params, call, m_timestampFormat);
cdrString = ReplaceAcctParams(m_cdrString, params);
}
return !cdrString;
}
bool FileAcct::IsRotationNeeded()
{
if (m_rotateLines > 0 && m_cdrLines >= m_rotateLines)
return true;
if (m_rotateSize > 0 && m_cdrFile && m_cdrFile->GetLength() >= m_rotateSize)
return true;
return false;
}
void FileAcct::RotateOnTimer(GkTimer * timer)
{
if (m_rotateInterval == Monthly) {
// setup next time for one-shot timer
const PTime& rotateTime = timer->GetExpirationTime();
PTime newRotateTime(rotateTime.GetSecond(), rotateTime.GetMinute(),
rotateTime.GetHour(), 1,
rotateTime.GetMonth() < 12 ? rotateTime.GetMonth() + 1 : 1,
rotateTime.GetMonth() < 12 ? rotateTime.GetYear() : rotateTime.GetYear() + 1,
rotateTime.GetTimeZone());
const int month = newRotateTime.GetMonth();
newRotateTime += PTimeInterval(0, 0, 0, 0, m_rotateDay - 1);
while (newRotateTime.GetMonth() != month)
newRotateTime -= PTimeInterval(0, 0, 0, 0, 1);
timer->SetExpirationTime(newRotateTime);
timer->SetFired(false);
}
PWaitAndSignal lock(m_cdrFileMutex);
Rotate();
}
void FileAcct::Rotate()
{
if (m_cdrFile) {
if (m_cdrFile->IsOpen())
m_cdrFile->Close();
delete m_cdrFile;
m_cdrFile = NULL;
}
const PFilePath fn = m_cdrFilename;
if (PFile::Exists(fn)) {
if (!PFile::Rename(fn, fn.GetFileName() + PTime().AsString(".yyyyMMdd-hhmmss"))) {
PTRACE(1, "GKACCT\t" << GetName() << " rotate failed - could not rename the log file");
SNMP_TRAP(6, SNMPError, Accounting, GetName() + " rotate failed");
}
}
m_cdrFile = OpenCDRFile(fn);
m_cdrLines = 0;
}
PTextFile* FileAcct::OpenCDRFile(const PFilePath & fn)
{
PTextFile* cdrFile = new PTextFile(fn, PFile::ReadWrite,
PFile::Create | PFile::DenySharedWrite
);
if (!cdrFile->IsOpen()) {
PTRACE(1, "GKACCT\t" << GetName() << " could not open file required for plain text accounting \""
<< fn << "\" :" << cdrFile->GetErrorText());
delete cdrFile;
return NULL;
}
cdrFile->SetPermissions(PFileInfo::UserRead | PFileInfo::UserWrite);
cdrFile->SetPosition(cdrFile->GetLength());
return cdrFile;
}
GkAcctLoggerList::GkAcctLoggerList()
: m_acctUpdateInterval(GkConfig()->GetInteger(CallTableSection, "AcctUpdateInterval", 0))
{
// should not be less than 10 seconds
if (m_acctUpdateInterval)
m_acctUpdateInterval = PMAX((long)10, m_acctUpdateInterval);
}
GkAcctLoggerList::~GkAcctLoggerList()
{
DeleteObjectsInContainer(m_loggers);
m_loggers.clear();
}
void GkAcctLoggerList::OnReload()
{
m_acctUpdateInterval = GkConfig()->GetInteger(CallTableSection, "AcctUpdateInterval", 0);
// should not be less than 10 seconds
if (m_acctUpdateInterval)
m_acctUpdateInterval = PMAX((long)10, m_acctUpdateInterval);
DeleteObjectsInContainer(m_loggers);
m_loggers.clear();
const PStringArray modules = GkConfig()->GetKeys(GkAcctSectionName);
for (PINDEX i = 0; i < modules.GetSize(); i++) {
GkAcctLogger* logger = Factory<GkAcctLogger>::Create(modules[i]);
if (logger)
m_loggers.push_back(logger);
}
}
bool GkAcctLoggerList::LogAcctEvent(
GkAcctLogger::AcctEvent evt, /// the accounting event to be logged
const callptr & call, /// a call associated with the event (if any)
time_t now /// "now" timestamp for accounting update events
)
{
// if this is an accounting update, check the interval
if (evt & GkAcctLogger::AcctUpdate) {
if ((!call) || m_acctUpdateInterval == 0
|| (now - call->GetLastAcctUpdateTime()) < m_acctUpdateInterval) {
return true;
} else {
call->SetLastAcctUpdateTime(now);
}
}
bool finalResult = true;
GkAcctLogger::Status status = GkAcctLogger::Ok;
std::list<GkAcctLogger*>::const_iterator iter = m_loggers.begin();
while (iter != m_loggers.end()) {
GkAcctLogger* logger = *iter++;
if ((evt & logger->GetEnabledEvents() & logger->GetSupportedEvents()) == 0)
continue;
status = logger->Log(evt, call);
switch (status)
{
case GkAcctLogger::Ok:
if (PTrace::CanTrace(3)) {
ostream& strm = PTrace::Begin(3,__FILE__,__LINE__);
strm << "GKACCT\t" << logger->GetName() << " logged event " << evt;
if (call)
strm << " for call no. " << call->GetCallNumber();
PTrace::End(strm);
}
break;
default:
if (PTrace::CanTrace(3)) {
ostream& strm = PTrace::Begin(3, __FILE__, __LINE__);
strm << "GKACCT\t" << logger->GetName() << " failed to log event " << evt;
SNMP_TRAP(7, SNMPError, Accounting, logger->GetName() + " failed");
if (call)
strm << " for call no. " << call->GetCallNumber();
PTrace::End(strm);
}
// required and sufficient rules always determine
// status of the request
if (logger->GetControlFlag() == GkAcctLogger::Required
|| logger->GetControlFlag() == GkAcctLogger::Sufficient)
finalResult = false;
}
// sufficient and alternative are terminal rules (on log success)
if (status == GkAcctLogger::Ok
&& (logger->GetControlFlag() == GkAcctLogger::Sufficient
|| logger->GetControlFlag() == GkAcctLogger::Alternative))
break;
}
// a last rule determine status of the the request
if (finalResult && status != GkAcctLogger::Ok)
finalResult = false;
if (PTrace::CanTrace(2)) {
ostream & strm = PTrace::Begin(2, __FILE__, __LINE__);
strm << "GKACCT\t" << (finalResult ? "Successfully logged event " : "Failed to log event ") << evt;
if (call)
strm << " for call no. " << call->GetCallNumber();
PTrace::End(strm);
#ifdef HAS_SNMP
if (!finalResult)
SNMP_TRAP(7, SNMPError, Accounting, "Failed to log event " + PString(PString::Unsigned, evt));
#endif
}
return finalResult;
}
bool GkAcctLoggerList::LogAcctEvent(
GkAcctLogger::AcctEvent evt, /// the accounting event to be logged
const endptr & ep /// endpoint associated with the event
)