forked from aiolos/sasc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cam.c
1767 lines (1631 loc) · 49.3 KB
/
cam.c
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
/*
* Softcam plugin to VDR (C++)
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This code 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* Or, point your browser to http://www.gnu.org/copyleft/gpl.html
*/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <vdr/channels.h>
#include <vdr/thread.h>
#include "cam.h"
#include "device.h"
#include "scsetup.h"
#include "filter.h"
#include "system.h"
#include "data.h"
#include "override.h"
#include "misc.h"
#include "log-core.h"
#define IDLE_SLEEP 0 // idleTime when sleeping
#define IDLE_GETCA 200 // idleTime when waiting for ca descriptors
#define IDLE_GETCA_SLOW 20000 // idleTime if no enc. system
#define IDLE_NO_SYNC 800 // idleTime when not in sync
#define IDLE_SYNC 2000 // idleTime when in sync
#define CW_REPEAT_TIME 2000 // rewrite CW after X ms
#define LOG_COUNT 3 // stop logging after X complete ECM cycles
#define CHAIN_HOLD 120000 // min. time to hold a logger chain
#define ECM_DATA_TIME 6000 // time to wait for ECM data updates
#define MAX_ECM_IDLE 300000 // delay before an idle handler can be removed
#define MAX_ECM_HOLD 15000 // delay before an idle handler stops processing
#define ECMCACHE_FILE "ecm.cache"
#define L_HEX 2
#define L_HEX_ECM LCLASS(L_HEX,2)
#define L_HEX_EMM LCLASS(L_HEX,4)
#define L_HEX_CAT LCLASS(L_HEX,8)
#define L_HEX_PMT LCLASS(L_HEX,16)
#define L_HEX_HOOK LCLASS(L_HEX,32)
#define L_HEX_ALL LALL(L_HEX_HOOK)
static const struct LogModule lm_hex = {
(LMOD_ENABLE|L_HEX_ALL)&LOPT_MASK,
(LMOD_ENABLE)&LOPT_MASK,
"hexdata",
{ "ecm","emm","cat","pmt","hook" }
};
ADD_MODULE(L_HEX,lm_hex)
static const char *typeNames[] = { "typ0","typ1","VIDEO","typ3","AUDIO","typ5","DOLBY","typ6+" };
#define TYPENAME(type) (typeNames[(type)<=7?(type):7])
// -- cLogStats ---------------------------------------------------------------
#define COUNTS 20
#define SAMPLE (30*1000)
#define AVR1 (60*1000)
#define AVR2 (4*60*1000)
#define AVR3 (10*60*1000)
#define REPORT (60*1000)
class cLogStats : public cThread {
private:
cTimeMs sTime, repTime;
int sCount, sIdx, sCounts[COUNTS][2];
protected:
virtual void Action(void);
public:
cLogStats(void);
~cLogStats();
void Count(void);
};
static cMutex logstatsMutex;
static cLogStats *logstats=0;
void LogStatsUp(void)
{
logstatsMutex.Lock();
if(LOG(L_CORE_AUSTATS) && !logstats) logstats=new cLogStats;
logstatsMutex.Unlock();
}
void LogStatsDown(void)
{
logstatsMutex.Lock();
if(logstats) { delete logstats; logstats=0; }
logstatsMutex.Unlock();
}
cLogStats::cLogStats(void)
{
sCount=sIdx=0;
for(int i=0; i<COUNTS; i++) { sCounts[i][0]=0; sCounts[i][1]=SAMPLE; }
SetDescription("logger stats");
Start();
}
cLogStats::~cLogStats()
{
Cancel(2);
}
void cLogStats::Count(void)
{
sCount++;
}
void cLogStats::Action(void)
{
while(Running()) {
cCondWait::SleepMs(50);
if(sTime.Elapsed()>SAMPLE) {
sCounts[sIdx][0]=sCount; sCount=0;
sCounts[sIdx][1]=sTime.Elapsed(); sTime.Set();
if(++sIdx >= COUNTS) sIdx=0;
}
if(repTime.Elapsed()>REPORT) {
repTime.Set();
if(sCounts[(sIdx+COUNTS-1)%COUNTS][0]>0) {
LBSTART(L_CORE_AUSTATS);
LBPUT("EMM packet load average (%d/%d/%dmin)",AVR1/60000,AVR2/60000,AVR3/60000);
int s=0, t=0;
for(int i=1; i<=COUNTS; i++) {
s+=sCounts[(sIdx+COUNTS-i)%COUNTS][0];
t+=sCounts[(sIdx+COUNTS-i)%COUNTS][1];
if(i==(AVR1/SAMPLE) || i==(AVR2/SAMPLE) || i==(AVR3/SAMPLE))
LBPUT(" %4d",(int)((float)s/(float)t*1000.0));
}
LBPUT(" pks/s");
LBEND();
}
}
}
}
// -- cHookManager -------------------------------------------------------------
class cHookManager : public cAction {
int cardNum;
cSimpleList<cLogHook> hooks;
//
cPidFilter *AddFilter(int Pid, int Section, int Mask, int Mode, int IdleTime, bool Crc);
void ClearHooks(void);
void DelHook(cLogHook *hook);
protected:
virtual void Process(cPidFilter *filter, unsigned char *data, int len);
public:
cHookManager(int CardNum);
virtual ~cHookManager();
void AddHook(cLogHook *hook);
bool TriggerHook(int id);
void Down(void);
};
cHookManager::cHookManager(int CardNum)
:cAction("hookmanager",CardNum)
{
cardNum=CardNum;
Priority(10);
}
cHookManager::~cHookManager()
{
Down();
}
void cHookManager::Down(void)
{
Lock();
while(cLogHook *hook=hooks.First()) DelHook(hook);
DelAllFilter();
Unlock();
}
bool cHookManager::TriggerHook(int id)
{
Lock();
for(cLogHook *hook=hooks.First(); hook; hook=hooks.Next(hook))
if(hook->id==id) {
hook->delay.Set(CHAIN_HOLD);
Unlock();
return true;
}
Unlock();
return false;
}
void cHookManager::AddHook(cLogHook *hook)
{
Lock();
PRINTF(L_CORE_HOOK,"%d: starting hook '%s' (%04x)",cardNum,hook->name,hook->id);
hook->delay.Set(CHAIN_HOLD);
hook->cardNum=cardNum;
hooks.Add(hook);
for(cPid *pid=hook->pids.First(); pid; pid=hook->pids.Next(pid)) {
cPidFilter *filter=AddFilter(pid->pid,pid->sct,pid->mask,pid->mode,CHAIN_HOLD/8,false);
if(filter) {
filter->userData=(void *)hook;
pid->filter=filter;
}
}
Unlock();
}
void cHookManager::DelHook(cLogHook *hook)
{
PRINTF(L_CORE_HOOK,"%d: stopping hook '%s' (%04x)",cardNum,hook->name,hook->id);
for(cPid *pid=hook->pids.First(); pid; pid=hook->pids.Next(pid)) {
cPidFilter *filter=pid->filter;
if(filter) {
DelFilter(filter);
pid->filter=0;
}
}
hooks.Del(hook);
}
cPidFilter *cHookManager::AddFilter(int Pid, int Section, int Mask, int Mode, int IdleTime, bool Crc)
{
cPidFilter *filter=NewFilter(IdleTime);
if(filter) {
filter->SetBuffSize(32768);
filter->Start(Pid,Section,Mask,Mode,Crc);
PRINTF(L_CORE_HOOK,"%d: added filter pid=0x%.4x sct=0x%.2x/0x%.2x/0x%.2x idle=%d crc=%d",cardNum,Pid,Section,Mask,Mode,IdleTime,Crc);
}
else PRINTF(L_GEN_ERROR,"no free slot or filter failed to open for hookmanager %d",cardNum);
return filter;
}
void cHookManager::Process(cPidFilter *filter, unsigned char *data, int len)
{
if(data && len>0) {
HEXDUMP(L_HEX_HOOK,data,len,"HOOK pid 0x%04x",filter->Pid());
if(SCT_LEN(data)==len) {
cLogHook *hook=(cLogHook *)(filter->userData);
if(hook) {
hook->Process(filter->Pid(),data);
if(hook->bailOut || hook->delay.TimedOut()) DelHook(hook);
}
}
else PRINTF(L_CORE_HOOK,"%d: incomplete section %d != %d",cardNum,len,SCT_LEN(data));
}
else {
cLogHook *hook=(cLogHook *)(filter->userData);
if(hook && (hook->bailOut || hook->delay.TimedOut())) DelHook(hook);
}
}
// -- cLogChain ----------------------------------------------------------------
class cLogChain : public cSimpleItem {
public:
int cardNum, caid, source, transponder;
bool softCSA, active, delayed;
cTimeMs delay;
cPids pids;
cSimpleList<cSystem> systems;
//
cLogChain(int CardNum, bool soft, int src, int tr);
void Process(int pid, const unsigned char *data);
bool Parse(const unsigned char *cat);
};
cLogChain::cLogChain(int CardNum, bool soft, int src, int tr)
{
cardNum=CardNum; softCSA=soft; source=src; transponder=tr;
active=delayed=false;
}
void cLogChain::Process(int pid, const unsigned char *data)
{
if(active) {
for(cSystem *sys=systems.First(); sys; sys=systems.Next(sys))
sys->ProcessEMM(pid,caid,data);
}
}
bool cLogChain::Parse(const unsigned char *cat)
{
if(cat[0]==0x09) {
caid=WORD(cat,2,0xFFFF);
LBSTARTF(L_CORE_AU);
LBPUT("%d: chain caid %04x",cardNum,caid);
cSystem *sys;
if(systems.Count()>0) {
LBPUT(" ++");
for(sys=systems.First(); sys; sys=systems.Next(sys))
sys->ParseCAT(&pids,cat,source,transponder);
}
else {
LBPUT(" ->");
if(!overrides.Ignore(source,transponder,caid)) {
int Pri=0;
while((sys=cSystems::FindBySysId(caid,!softCSA,Pri))) {
Pri=sys->Pri();
if(sys->HasLogger()) {
sys->CardNum(cardNum);
sys->ParseCAT(&pids,cat,source,transponder);
systems.Add(sys);
LBPUT(" %s(%d)",sys->Name(),sys->Pri());
}
else
delete sys;
}
}
}
if(systems.Count()==0) LBPUT(" none available");
for(cPid *pid=pids.First(); pid; pid=pids.Next(pid))
LBPUT(" [%04x-%02x/%02x/%02x]",pid->pid,pid->sct,pid->mask,pid->mode);
LBEND();
if(systems.Count()>0 && pids.Count()>0)
return true;
}
return false;
}
// -- cLogger ------------------------------------------------------------------
class cLogger : public cAction {
private:
int cardNum;
bool softCSA, up;
cSimpleList<cLogChain> chains;
cSimpleList<cEcmInfo> active;
//
cPidFilter *catfilt;
int catVers;
int source, transponder;
//
enum ePreMode { pmNone, pmStart, pmWait, pmActive, pmStop };
ePreMode prescan;
cTimeMs pretime;
//
cPidFilter *AddFilter(int Pid, int Section, int Mask, int Mode, int IdleTime, bool Crc);
void SetChains(void);
void ClearChains(void);
void StartChain(cLogChain *chain);
void StopChain(cLogChain *chain, bool force);
void ProcessCat(unsigned char *data, int len);
protected:
virtual void Process(cPidFilter *filter, unsigned char *data, int len);
public:
cLogger(int CardNum, bool soft);
virtual ~cLogger();
void EcmStatus(const cEcmInfo *ecm, bool on);
void Up(void);
void Down(void);
void PreScan(int src, int tr);
};
cLogger::cLogger(int CardNum, bool soft)
:cAction("logger",CardNum)
{
cardNum=CardNum; softCSA=soft;
catfilt=0; up=false; prescan=pmNone;
Priority(10);
}
cLogger::~cLogger()
{
Down();
}
void cLogger::Up(void)
{
Lock();
if(!up) {
PRINTF(L_CORE_AUEXTRA,"%d: UP",cardNum);
catVers=-1;
catfilt=AddFilter(1,0x01,0xFF,0,0,true);
up=true;
}
Unlock();
}
void cLogger::Down(void)
{
Lock();
if(up) {
PRINTF(L_CORE_AUEXTRA,"%d: DOWN",cardNum);
ClearChains();
DelAllFilter();
catfilt=0; up=false; prescan=pmNone;
}
Unlock();
}
void cLogger::PreScan(int src, int tr)
{
Lock();
source=src; transponder=tr;
prescan=pmStart; Up();
Unlock();
}
void cLogger::EcmStatus(const cEcmInfo *ecm, bool on)
{
Lock();
PRINTF(L_CORE_AUEXTRA,"%d: ecm prgid=%d caid=%04x prov=%.4x %s",cardNum,ecm->prgId,ecm->caId,ecm->provId,on ? "active":"inactive");
source=ecm->source; transponder=ecm->transponder;
cEcmInfo *e;
if(on) {
e=new cEcmInfo(ecm);
active.Add(e);
if(!up) Up();
}
else {
for(e=active.First(); e; e=active.Next(e))
if(e->Compare(ecm)) {
active.Del(e);
break;
}
}
if(prescan>=pmWait) prescan=pmStop;
SetChains();
prescan=pmNone;
Unlock();
}
void cLogger::SetChains(void)
{
for(cLogChain *chain=chains.First(); chain; chain=chains.Next(chain)) {
bool act=false;
if(ScSetup.AutoUpdate>1 || prescan==pmActive) act=true;
else if(ScSetup.AutoUpdate==1) {
for(cEcmInfo *e=active.First(); e; e=active.Next(e))
if((e->emmCaId && chain->caid==e->emmCaId) || chain->caid==e->caId) {
act=true; break;
}
}
if(act) StartChain(chain);
else StopChain(chain,prescan==pmStop);
}
}
void cLogger::ClearChains(void)
{
for(cLogChain *chain=chains.First(); chain; chain=chains.Next(chain))
StopChain(chain,true);
chains.Clear();
}
void cLogger::StartChain(cLogChain *chain)
{
if(chain->delayed)
PRINTF(L_CORE_AUEXTRA,"%d: restarting delayed chain %04x",cardNum,chain->caid);
chain->delayed=false;
if(!chain->active) {
PRINTF(L_CORE_AU,"%d: starting chain %04x",cardNum,chain->caid);
chain->active=true;
for(cPid *pid=chain->pids.First(); pid; pid=chain->pids.Next(pid)) {
cPidFilter *filter=AddFilter(pid->pid,pid->sct,pid->mask,pid->mode,CHAIN_HOLD/8,false);
if(filter) {
filter->userData=(void *)chain;
pid->filter=filter;
}
}
}
}
void cLogger::StopChain(cLogChain *chain, bool force)
{
if(chain->active) {
if(force || (chain->delayed && chain->delay.TimedOut())) {
PRINTF(L_CORE_AU,"%d: stopping chain %04x",cardNum,chain->caid);
chain->active=false;
for(cPid *pid=chain->pids.First(); pid; pid=chain->pids.Next(pid)) {
cPidFilter *filter=pid->filter;
if(filter) {
DelFilter(filter);
pid->filter=0;
}
}
}
else if(!chain->delayed) {
PRINTF(L_CORE_AUEXTRA,"%d: delaying chain %04x",cardNum,chain->caid);
chain->delayed=true;
chain->delay.Set(CHAIN_HOLD);
}
}
}
cPidFilter *cLogger::AddFilter(int Pid, int Section, int Mask, int Mode, int IdleTime, bool Crc)
{
cPidFilter *filter=NewFilter(IdleTime);
if(filter) {
if(Pid>1) filter->SetBuffSize(KILOBYTE(64));
filter->Start(Pid,Section,Mask,Mode,Crc);
PRINTF(L_CORE_AUEXTRA,"%d: added filter pid=0x%.4x sct=0x%.2x/0x%.2x/0x%.2x idle=%d crc=%d",cardNum,Pid,Section,Mask,Mode,IdleTime,Crc);
}
else PRINTF(L_GEN_ERROR,"no free slot or filter failed to open for logger %d",cardNum);
return filter;
}
void cLogger::ProcessCat(unsigned char *data, int len)
{
for(int i=0; i<len; i+=data[i+1]+2) {
if(data[i]==0x09) {
int caid=WORD(data,i+2,0xFFFF);
cLogChain *chain;
for(chain=chains.First(); chain; chain=chains.Next(chain))
if(chain->caid==caid) break;
if(chain)
chain->Parse(&data[i]);
else {
chain=new cLogChain(cardNum,softCSA,source,transponder);
if(chain->Parse(&data[i]))
chains.Add(chain);
else
delete chain;
}
}
}
}
void cLogger::Process(cPidFilter *filter, unsigned char *data, int len)
{
if(data && len>0) {
if(filter==catfilt) {
int vers=(data[5]&0x3E)>>1;
if(data[0]==0x01 && vers!=catVers) {
PRINTF(L_CORE_AUEXTRA,"%d: got CAT version %02x",cardNum,vers);
catVers=vers;
HEXDUMP(L_HEX_CAT,data,len,"CAT vers %02x",catVers);
ClearChains();
ProcessCat(&data[8],len-4-8);
unsigned char buff[2048];
if((len=overrides.GetCat(source,transponder,buff,sizeof(buff)))>0) {
HEXDUMP(L_HEX_CAT,buff,len,"override CAT");
ProcessCat(buff,len);
}
SetChains();
if(prescan==pmStart) { prescan=pmWait; pretime.Set(2000); }
}
if(prescan==pmWait && pretime.TimedOut()) { prescan=pmActive; SetChains(); }
}
else {
HEXDUMP(L_HEX_EMM,data,len,"EMM pid 0x%04x",filter->Pid());
if(logstats) logstats->Count();
if(SCT_LEN(data)==len) {
cLogChain *chain=(cLogChain *)(filter->userData);
if(chain) {
chain->Process(filter->Pid(),data);
if(chain->delayed) StopChain(chain,false);
}
}
else PRINTF(L_CORE_AU,"%d: incomplete section %d != %d",cardNum,len,SCT_LEN(data));
}
}
else {
cLogChain *chain=(cLogChain *)(filter->userData);
if(chain && chain->delayed) StopChain(chain,false);
}
}
// -- cEcmData -----------------------------------------------------------------
#define CACHE_VERS 1
class cEcmData : public cEcmInfo {
public:
cEcmData(void):cEcmInfo() {}
cEcmData(cEcmInfo *e):cEcmInfo(e) {}
virtual cString ToString(bool hide);
bool Parse(const char *buf);
};
bool cEcmData::Parse(const char *buf)
{
char Name[64];
int nu=0, num, vers=0;
Name[0]=0;
if(sscanf(buf,"V%d:%d:%x:%x:%63[^:]:%x/%x:%x:%x/%x:%d:%d/%d%n",
&vers,&grPrgId,&source,&transponder,Name,&caId,&emmCaId,&provId,
&ecm_pid,&ecm_table,&rewriterId,&nu,&dataIdx,&num)>=13
&& vers==CACHE_VERS) {
SetName(Name);
SetRewriter();
prgId=grPrgId%SIDGRP_SHIFT;
const char *line=buf+num;
if(nu>0 && *line++==':') {
unsigned char *dat=AUTOMEM(nu);
if(GetHex(line,dat,nu,true)==nu && dat[0]==0x09 && dat[1]==nu-2)
AddCaDescr(dat,nu);
}
return true;
}
return false;
}
cString cEcmData::ToString(bool hide)
{
char *str;
if(caDescr) {
str=AUTOARRAY(char,caDescrLen*2+16);
int q=sprintf(str,"%d/%d:",caDescrLen,dataIdx);
HexStr(str+q,caDescr,caDescrLen);
}
else {
str=AUTOARRAY(char,10);
sprintf(str,"0/%d:",dataIdx);
}
return cString::sprintf("V%d:%d:%x:%x:%s:%x/%x:%x:%x/%x:%d:%s",
CACHE_VERS,grPrgId,source,transponder,name,
caId,emmCaId,provId,ecm_pid,ecm_table,rewriterId,
str);
}
// -- cEcmCache ----------------------------------------------------------------
cEcmCache ecmcache;
cEcmCache::cEcmCache(void)
:cStructListPlain<cEcmData>("ecm cache",ECMCACHE_FILE,SL_READWRITE|SL_MISSINGOK)
{}
void cEcmCache::New(cEcmInfo *e)
{
if(ScSetup.EcmCache>0) return;
ListLock(true);
cEcmData *dat;
if(!(dat=Exists(e))) {
dat=new cEcmData(e);
Add(dat);
Modified();
PRINTF(L_CORE_ECM,"cache add prgId=%d source=%x transponder=%x ecm=%x/%x",e->grPrgId,e->source,e->transponder,e->ecm_pid,e->ecm_table);
}
else {
if(strcasecmp(e->name,dat->name)) {
dat->SetName(e->name);
Modified();
}
if(dat->AddCaDescr(e))
Modified();
}
ListUnlock();
e->SetCached();
}
cEcmData *cEcmCache::Exists(cEcmInfo *e)
{
cEcmData *dat;
for(dat=First(); dat; dat=Next(dat))
if(dat->Compare(e)) break;
return dat;
}
int cEcmCache::GetCached(cSimpleList<cEcmInfo> *list, int sid, int Source, int Transponder)
{
int n=0;
list->Clear();
if(ScSetup.EcmCache>1) return 0;
ListLock(false);
for(cEcmData *dat=First(); dat; dat=Next(dat)) {
if(dat->grPrgId==sid && dat->source==Source && dat->transponder==Transponder) {
cEcmInfo *e=new cEcmInfo(dat);
if(e) {
PRINTF(L_CORE_ECM,"from cache: system %s (%04x) id %04x with ecm %x/%x",e->name,e->caId,e->provId,e->ecm_pid,e->ecm_table);
e->SetCached();
list->Add(e);
n++;
}
}
}
ListUnlock();
return n;
}
void cEcmCache::Delete(cEcmInfo *e)
{
if(ScSetup.EcmCache>0) return;
ListLock(false);
cEcmData *dat=Exists(e);
ListUnlock();
if(dat) {
DelItem(dat);
PRINTF(L_CORE_ECM,"invalidated cached prgId=%d source=%x transponder=%x ecm=%x/%x",dat->grPrgId,dat->source,dat->transponder,dat->ecm_pid,dat->ecm_table);
}
}
void cEcmCache::Flush(void)
{
ListLock(true);
Clear();
Modified();
PRINTF(L_CORE_ECM,"cache flushed");
ListUnlock();
}
bool cEcmCache::ParseLinePlain(const char *line)
{
cEcmData *dat=new cEcmData;
if(dat && dat->Parse(line) && !Exists(dat)) Add(dat);
else delete dat;
return true;
}
// -- cEcmPri ------------------------------------------------------------------
class cEcmPri : public cSimpleItem {
public:
cEcmInfo *ecm;
int pri, sysIdent;
};
// -- cEcmHandler --------------------------------------------------------------
class cEcmHandler : public cSimpleItem, public cAction {
private:
int cardNum, cwIndex;
cCam *cam;
char *id;
cTimeMs idleTime;
//
cMutex dataMutex;
cPrg prg;
//
cSystem *sys;
cPidFilter *filter;
int filterCwIndex, filterSource, filterTransponder, filterSid;
cCaDescr filterCaDescr;
unsigned char lastCw[16];
bool sync, noKey, trigger, ecmUpd;
int triggerMode;
int mode, count;
cTimeMs lastsync, startecm, resendTime;
unsigned int cryptPeriod;
unsigned char parity;
cMsgCache failed;
//
cSimpleList<cEcmInfo> ecmList;
cSimpleList<cEcmPri> ecmPriList;
cEcmInfo *ecm;
cEcmPri *ecmPri;
//
int dolog;
//
void DeleteSys(void);
void NoSync(bool clearParity);
cEcmInfo *NewEcm(void);
cEcmInfo *JumpEcm(void);
void StopEcm(void);
bool UpdateEcm(void);
void EcmOk(void);
void EcmFail(void);
void ParseCAInfo(int sys);
void AddEcmPri(cEcmInfo *n);
protected:
virtual void Process(cPidFilter *filter, unsigned char *data, int len);
public:
cEcmHandler(cCam *Cam, int CardNum, int cwindex);
virtual ~cEcmHandler();
void Stop(void);
void SetPrg(cPrg *Prg);
void ShiftCwIndex(int cwindex);
char *CurrentKeyStr(void) const;
bool IsRemoveable(void);
bool IsIdle(void);
int Sid(void) const { return prg.sid; }
int CwIndex(void) const { return cwIndex; }
const char *Id(void) const { return id; }
};
cEcmHandler::cEcmHandler(cCam *Cam, int CardNum, int cwindex)
:cAction("ecmhandler",CardNum)
,failed(32,0)
{
cam=Cam;
cardNum=CardNum;
cwIndex=cwindex;
sys=0; filter=0; ecm=0; ecmPri=0; mode=-1;
trigger=ecmUpd=false; triggerMode=-1;
filterSource=filterTransponder=0; filterCwIndex=-1; filterSid=-1;
id=bprintf("%d.%d",cardNum,cwindex);
}
cEcmHandler::~cEcmHandler()
{
Lock();
StopEcm();
DelAllFilter(); // delete filters before sys for multi-threading reasons
DeleteSys();
Unlock();
free(id);
}
bool cEcmHandler::IsIdle(void)
{
dataMutex.Lock();
int n=prg.pids.Count();
dataMutex.Unlock();
return n==0;
}
bool cEcmHandler::IsRemoveable(void)
{
return IsIdle() && idleTime.Elapsed()>MAX_ECM_IDLE;
}
void cEcmHandler::Stop(void)
{
dataMutex.Lock();
if(!IsIdle() || prg.sid!=-1) {
PRINTF(L_CORE_ECM,"%s: stop",id);
prg.sid=-1;
idleTime.Set();
prg.pids.Clear();
prg.caDescr.Clear();
trigger=true;
}
dataMutex.Unlock();
if(filter) filter->Wakeup();
}
void cEcmHandler::ShiftCwIndex(int cwindex)
{
if(cwIndex!=cwindex) {
PRINTF(L_CORE_PIDS,"%s: shifting cwIndex from %d to %d",id,cwIndex,cwindex);
free(id);
id=bprintf("%d.%d",cardNum,cwindex);
dataMutex.Lock();
trigger=true;
cwIndex=cwindex;
for(cPrgPid *pid=prg.pids.First(); pid; pid=prg.pids.Next(pid))
cam->SetCWIndex(pid->pid,cwIndex);
dataMutex.Unlock();
if(filter) filter->Wakeup();
}
}
void cEcmHandler::SetPrg(cPrg *Prg)
{
dataMutex.Lock();
bool wasIdle=IsIdle();
if(Prg->sid!=prg.sid) {
PRINTF(L_CORE_ECM,"%s: setting new SID %d",id,Prg->sid);
prg.sid=Prg->sid;
prg.source=Prg->source;
prg.transponder=Prg->transponder;
idleTime.Set();
prg.pids.Clear();
trigger=true;
}
if(Prg->HasPidCaDescr())
PRINTF(L_GEN_DEBUG,"internal: pid specific caDescr not supported at this point (sid=%d)",Prg->sid);
LBSTART(L_CORE_PIDS);
LBPUT("%s: pids on entry",id);
for(cPrgPid *pid=prg.pids.First(); pid; pid=prg.pids.Next(pid))
LBPUT(" %s=%04x",TYPENAME(pid->type),pid->pid);
LBEND();
for(cPrgPid *pid=prg.pids.First(); pid;) {
cPrgPid *npid;
for(npid=Prg->pids.First(); npid; npid=Prg->pids.Next(npid)) {
if(pid->pid==npid->pid) {
npid->Proc(true);
break;
}
}
if(!npid) {
npid=prg.pids.Next(pid);
prg.pids.Del(pid);
pid=npid;
}
else pid=prg.pids.Next(pid);
}
LBSTART(L_CORE_PIDS);
LBPUT("%s: pids after delete",id);
for(cPrgPid *pid=prg.pids.First(); pid; pid=prg.pids.Next(pid))
LBPUT(" %s=%04x",TYPENAME(pid->type),pid->pid);
LBEND();
for(cPrgPid *npid=Prg->pids.First(); npid; npid=Prg->pids.Next(npid)) {
if(!npid->Proc()) {
cPrgPid *pid=new cPrgPid(npid->type,npid->pid);
prg.pids.Add(pid);
cam->SetCWIndex(pid->pid,cwIndex);
}
}
LBSTART(L_CORE_PIDS);
LBPUT("%s: pids after add",id);
for(cPrgPid *pid=prg.pids.First(); pid; pid=prg.pids.Next(pid))
LBPUT(" %s=%04x",TYPENAME(pid->type),pid->pid);
LBEND();
if(!IsIdle()) {
if(!(prg.caDescr==Prg->caDescr)) prg.caDescr.Set(&Prg->caDescr);
trigger=true;
triggerMode=0;
if(wasIdle) PRINTF(L_CORE_ECM,"%s: is no longer idle",id);
}
else {
if(!wasIdle) idleTime.Set();
PRINTF(L_CORE_ECM,"%s: is idle%s",id,wasIdle?"":" now");
}
if(!filter) {
filter=NewFilter(IDLE_SLEEP);
if(!filter) PRINTF(L_GEN_ERROR,"failed to open ECM filter in handler %s",id);
}
dataMutex.Unlock();
if(filter) filter->Wakeup();
}
void cEcmHandler::Process(cPidFilter *filter, unsigned char *data, int len)
{
dataMutex.Lock();
if(trigger) {
PRINTF(L_CORE_ECM,"%s: triggered SID %d/%d idx %d/%d mode %d/%d %s",
id,filterSid,prg.sid,filterCwIndex,cwIndex,mode,triggerMode,(mode==3 && sync)?"sync":"-");
trigger=false;
if(filterSid!=prg.sid) {
filterSid=prg.sid;
filterSource=prg.source;
filterTransponder=prg.transponder;
filterCwIndex=cwIndex;
noKey=true; mode=0;
}
else {
if(filterCwIndex!=cwIndex) {
filterCwIndex=cwIndex;
if(mode==3 && sync)
cam->WriteCW(filterCwIndex,lastCw,true);
}
if(mode<triggerMode) mode=triggerMode;
}
if(!(prg.caDescr==filterCaDescr)) {
filterCaDescr.Set(&prg.caDescr);
ecmUpd=true;
//XXX
PRINTF(L_CORE_ECM,"%s: new caDescr: %s",id,*filterCaDescr.ToString());
}
triggerMode=-1;
}
dataMutex.Unlock();
switch(mode) {
case -1:
filter->SetIdleTime(IDLE_SLEEP);
break;
case 0:
StopEcm();
if(filterSid<0 || IsIdle()) { mode=-1; break; }
dolog=LOG_COUNT;
NewEcm();
filter->SetIdleTime(IDLE_GETCA);
startecm.Set();
mode=1;
break;
case 1:
if(!ecm && !JumpEcm()) {
if(startecm.Elapsed()>IDLE_GETCA_SLOW) {
if(IsIdle()) { mode=0; break; }
PRINTF(L_CORE_ECM,"%s: no encryption system found",id);
filter->SetIdleTime(IDLE_GETCA_SLOW/4);
startecm.Set();
}
break;
}
mode=4;
// fall through
case 4:
case 5:
NoSync(mode==4);
failed.Clear();
filter->SetIdleTime(IDLE_NO_SYNC/2);
lastsync.Set();
cryptPeriod=20*1000;
mode=2;
// fall through
case 2:
if(sys->NeedsData()) {
if(!UpdateEcm()) {
if(lastsync.Elapsed()<ECM_DATA_TIME) break;
PRINTF(L_CORE_ECM,"%s: no ecm extra data update (waited %d ms)",id,(int)lastsync.Elapsed());
}
if(lastsync.Elapsed()>IDLE_NO_SYNC/4 && dolog)
PRINTF(L_CORE_ECM,"%s: ecm extra data update took %d ms",id,(int)lastsync.Elapsed());