-
Notifications
You must be signed in to change notification settings - Fork 7
/
ci.c
3107 lines (2836 loc) · 94.3 KB
/
ci.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
/*
* ci.c: Common Interface
*
* See the main source file 'vdr.c' for copyright information and
* how to reach the author.
*
* $Id: ci.c 5.1 2021/06/09 09:41:18 kls Exp $
*/
#include "ci.h"
#include <ctype.h>
#include <linux/dvb/ca.h>
#include <malloc.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#include "device.h"
#include "mtd.h"
#include "pat.h"
#include "receiver.h"
#include "remux.h"
#include "libsi/si.h"
#include "skins.h"
#include "tools.h"
// Set these to 'true' for debug output:
static bool DumpTPDUDataTransfer = false;
static bool DebugProtocol = false;
static bool DumpPolls = false;
static bool DumpDateTime = false;
#define dbgprotocol(a...) if (DebugProtocol) fprintf(stderr, a)
// --- Helper functions ------------------------------------------------------
#define SIZE_INDICATOR 0x80
static const uint8_t *GetLength(const uint8_t *Data, int &Length)
///< Gets the length field from the beginning of Data.
///< Returns a pointer to the first byte after the length and
///< stores the length value in Length.
{
Length = *Data++;
if ((Length & SIZE_INDICATOR) != 0) {
int l = Length & ~SIZE_INDICATOR;
Length = 0;
for (int i = 0; i < l; i++)
Length = (Length << 8) | *Data++;
}
return Data;
}
static uint8_t *SetLength(uint8_t *Data, int Length)
///< Sets the length field at the beginning of Data.
///< Returns a pointer to the first byte after the length.
{
uint8_t *p = Data;
if (Length < 128)
*p++ = Length;
else {
int n = sizeof(Length);
for (int i = n - 1; i >= 0; i--) {
int b = (Length >> (8 * i)) & 0xFF;
if (p != Data || b)
*++p = b;
}
*Data = (p - Data) | SIZE_INDICATOR;
p++;
}
return p;
}
static char *CopyString(int Length, const uint8_t *Data)
///< Copies the string at Data.
///< Returns a pointer to a newly allocated string.
{
char *s = MALLOC(char, Length + 1);
char *p = s;
while (Length > 0) {
int c = *Data;
if (isprint(c)) // some CAMs send funny characters in their strings, let's just skip them
*p++ = c;
else if (c == 0x8A) // the character 0x8A is used as newline, so let's put a real '\n' in there
*p++ = '\n';
Length--;
Data++;
}
*p = 0;
return s;
}
static char *GetString(int &Length, const uint8_t **Data)
///< Gets the string at Data.
///< Returns a pointer to a newly allocated string, or NULL in case of error.
///< Upon return Length and Data represent the remaining data after the string has been skipped.
{
if (Length > 0 && Data && *Data) {
int l = 0;
const uint8_t *d = GetLength(*Data, l);
char *s = CopyString(l, d);
Length -= d - *Data + l;
*Data = d + l;
return s;
}
return NULL;
}
// --- cCaPidReceiver --------------------------------------------------------
// A receiver that is used to make the device receive the ECM pids, as well as the
// CAT and the EMM pids.
class cCaPidReceiver : public cReceiver {
private:
int catVersion;
cVector<int> emmPids;
uchar buffer[1024]; // CAT table length: 10 bit -> max. 1021 + 3 bytes
uchar *bufp;
#define CAT_MAXPACKETS 6 // 6 * 184 = 1104 bytes for CAT table
uchar mtdCatBuffer[CAT_MAXPACKETS][TS_SIZE]; // TODO: handle multi table CATs!
int mtdNumCatPackets;
int length;
cMutex mutex;
bool handlingPid;
void AddEmmPid(int Pid);
void DelEmmPids(void);
public:
cCaPidReceiver(void);
virtual ~cCaPidReceiver() { Detach(); }
virtual void Receive(const uchar *Data, int Length);
bool HasCaPids(void) const { return NumPids() - emmPids.Size() - 1 > 0; }
void Reset(void) { DelEmmPids(); catVersion = -1; }
bool HandlingPid(void);
///< The cCaPidReceiver adds/deletes PIDs to/from the base class cReceiver,
///< which in turn does the same on the cDevice it is attached to. The cDevice
///< then sets the PIDs on the assigned cCamSlot, which can cause a deadlock on the
///< cCamSlot's mutex if a cReceiver is detached from the device at the same time.
///< Since these PIDs, however, are none that have to be decrypted,
///< it is not necessary to set them in the CAM. Therefore this function is
///< used in cCamSlot::SetPid() to detect this situation, and thus avoid the
///< deadlock.
};
cCaPidReceiver::cCaPidReceiver(void)
{
catVersion = -1;
bufp = NULL;
mtdNumCatPackets = 0;
length = 0;
handlingPid = false;
cMutexLock MutexLock(&mutex);
handlingPid = true;
AddPid(CATPID);
handlingPid = false;
}
void cCaPidReceiver::AddEmmPid(int Pid)
{
for (int i = 0; i < emmPids.Size(); i++) {
if (emmPids[i] == Pid)
return;
}
emmPids.Append(Pid);
cMutexLock MutexLock(&mutex);
handlingPid = true;
AddPid(Pid);
handlingPid = false;
}
void cCaPidReceiver::DelEmmPids(void)
{
cMutexLock MutexLock(&mutex);
handlingPid = true;
for (int i = 0; i < emmPids.Size(); i++)
DelPid(emmPids[i]);
emmPids.Clear();
handlingPid = false;
}
void cCaPidReceiver::Receive(const uchar *Data, int Length)
{
if (TsPid(Data) == CATPID) {
cMtdCamSlot *MtdCamSlot = dynamic_cast<cMtdCamSlot *>(Device()->CamSlot());
const uchar *p = NULL;
if (TsPayloadStart(Data)) {
if (Data[5] == SI::TableIdCAT) {
if (bufp) { // incomplete multi-packet CAT
catVersion = -1;
bufp = NULL;
}
length = (int(Data[6] & 0x0F) << 8) | Data[7]; // section length (12 bit field)
if (length > 5) {
int v = (Data[10] & 0x3E) >> 1; // version number
if (v != catVersion) {
if (Data[11] == 0 && Data[12] == 0) { // section number, last section number
length += 3; // with TableIdCAT -> Data[5]
if (length > TS_SIZE - 5) {
int n = TS_SIZE - 5;
memcpy(buffer, Data + 5, n);
bufp = buffer + n;
length -= n;
}
else {
p = Data + 5; // no need to copy the data
}
if (MtdCamSlot) {
mtdNumCatPackets = 0;
memcpy(mtdCatBuffer[mtdNumCatPackets++], Data, TS_SIZE);
}
}
else
dsyslog("multi table CAT section - unhandled!");
catVersion = v;
}
else if (MtdCamSlot) {
for (int i = 0; i < mtdNumCatPackets; i++)
MtdCamSlot->PutCat(mtdCatBuffer[i], TS_SIZE);
}
}
}
}
else if (bufp && length > 0) {
int n = min(length, TS_SIZE - 4);
if (bufp + n - buffer <= int(sizeof(buffer))) {
memcpy(bufp, Data + 4, n);
bufp += n;
length -= n;
if (length <= 0) {
p = buffer;
length = bufp - buffer;
}
if (MtdCamSlot)
memcpy(mtdCatBuffer[mtdNumCatPackets++], Data, TS_SIZE);
}
else {
esyslog("ERROR: buffer overflow in cCaPidReceiver::Receive()");
bufp = NULL;
length = 0;
}
}
if (p) {
if (!SI::CRC32::crc32((const char *)p, length, 0xFFFFFFFF)) { // <TableIdCAT,....,crc32>
DelEmmPids();
for (int i = 8; i < length - 4; i++) { // -4 = checksum
if (p[i] == 0x09) {
int CaId = int(p[i + 2] << 8) | p[i + 3];
int EmmPid = Peek13(p + i + 4);
AddEmmPid(EmmPid);
if (MtdCamSlot)
MtdMapPid(const_cast<uchar *>(p + i + 4), MtdCamSlot->MtdMapper());
switch (CaId >> 8) {
case 0x01: for (int j = i + 7; j < i + p[i + 1] + 2; j += 4) {
EmmPid = Peek13(p + j);
AddEmmPid(EmmPid);
if (MtdCamSlot)
MtdMapPid(const_cast<uchar *>(p + j), MtdCamSlot->MtdMapper());
}
break;
}
i += p[i + 1] + 2 - 1; // -1 to compensate for the loop increment
}
}
if (MtdCamSlot) {
// update crc32
uint32_t crc = SI::CRC32::crc32((const char *)p, length - 4, 0xFFFFFFFF); // <TableIdCAT....>[crc32]
uchar *c = const_cast<uchar *>(p + length - 4);
*c++ = crc >> 24;
*c++ = crc >> 16;
*c++ = crc >> 8;
*c++ = crc;
// modify CAT packets
const uchar *t = p;
for (int i = 0, j = 5; i < mtdNumCatPackets; i++, j = 4) {
int n = min(length, TS_SIZE - j);
memcpy(mtdCatBuffer[i] + j, t, n);
t += n;
length -= n;
MtdCamSlot->PutCat(mtdCatBuffer[i], TS_SIZE);
}
}
}
else {
esyslog("ERROR: wrong checksum in CAT");
catVersion = -1;
}
p = NULL;
bufp = NULL;
length = 0;
}
}
}
bool cCaPidReceiver::HandlingPid(void)
{
cMutexLock MutexLock(&mutex);
return handlingPid;
}
// --- cCaActivationReceiver -------------------------------------------------
// A receiver that is used to make the device stay on a given channel and
// keep the CAM slot assigned.
#define UNSCRAMBLE_TIME 5 // seconds of receiving purely unscrambled data before considering the smart card "activated"
#define TS_PACKET_FACTOR 1024 // only process every TS_PACKET_FACTORth packet to keep the load down
class cCaActivationReceiver : public cReceiver {
private:
cCamSlot *camSlot;
time_t lastScrambledTime;
int numTsPackets;
protected:
virtual void Receive(const uchar *Data, int Length);
public:
cCaActivationReceiver(const cChannel *Channel, cCamSlot *CamSlot);
virtual ~cCaActivationReceiver();
};
cCaActivationReceiver::cCaActivationReceiver(const cChannel *Channel, cCamSlot *CamSlot)
:cReceiver(Channel, MINPRIORITY + 1)
{
camSlot = CamSlot;
lastScrambledTime = time(NULL);
numTsPackets = 0;
}
cCaActivationReceiver::~cCaActivationReceiver()
{
Detach();
}
void cCaActivationReceiver::Receive(const uchar *Data, int Length)
{
if (numTsPackets++ % TS_PACKET_FACTOR == 0) {
time_t Now = time(NULL);
if (TsIsScrambled(Data))
lastScrambledTime = Now;
else if (Now - lastScrambledTime > UNSCRAMBLE_TIME) {
dsyslog("CAM %d: activated!", camSlot->MasterSlotNumber());
Skins.QueueMessage(mtInfo, tr("CAM activated!"));
cDevice *d = Device();
Detach();
if (d) {
if (cCamSlot *s = d->CamSlot())
s->CancelActivation(); // this will delete *this* object, so no more code referencing *this* after this call!
}
}
}
}
// --- cCamResponse ----------------------------------------------------------
// CAM Response Actions:
#define CRA_NONE 0
#define CRA_DISCARD -1
#define CRA_CONFIRM -2
#define CRA_SELECT -3
class cCamResponse : public cListObject {
private:
int camNumber;
char *text;
int action;
public:
cCamResponse(void);
~cCamResponse();
bool Parse(const char *s);
int Matches(int CamNumber, const char *Text) const;
};
cCamResponse::cCamResponse(void)
{
camNumber = -1;
text = NULL;
action = CRA_NONE;
}
cCamResponse::~cCamResponse()
{
free(text);
}
bool cCamResponse::Parse(const char *s)
{
// Number:
s = skipspace(s);
if (*s == '*') {
camNumber = 0; // all CAMs
s++;
}
else {
char *e;
camNumber = strtol(s, &e, 10);
if (e == s || camNumber <= 0)
return false;
s = e;
}
// Text:
s = skipspace(s);
char *t = const_cast<char *>(s); // might have to modify it
char *q = NULL; // holds a copy in case of backslashes
bool InQuotes = false;
while (*t) {
if (*t == '"') {
if (t == s) { // opening quotes
InQuotes = true;
s++;
}
else if (InQuotes) // closing quotes
break;
}
else if (*t == '\\') {
if (!q) { // need to make a copy in order to strip backslashes
q = strdup(s);
t = q + (t - s);
s = q;
}
memmove(t, t + 1, strlen(t));
}
else if (*t == ' ') {
if (!InQuotes)
break;
}
t++;
}
free(text); // just for safety
text = NULL;
if (t != s) {
text = strndup(s, t - s);
s = t + 1;
}
free(q);
if (!text)
return false;
// Action:
s = skipspace(s);
if (strcasecmp(s, "DISCARD") == 0) action = CRA_DISCARD;
else if (strcasecmp(s, "CONFIRM") == 0) action = CRA_CONFIRM;
else if (strcasecmp(s, "SELECT") == 0) action = CRA_SELECT;
else if (isnumber(s)) action = atoi(s);
else
return false;
return true;
}
int cCamResponse::Matches(int CamNumber, const char *Text) const
{
if (!camNumber || camNumber == CamNumber) {
if (strcmp(text, Text) == 0)
return action;
}
return CRA_NONE;
}
// --- cCamResponses --------------------------------------------------------
class cCamResponses : public cConfig<cCamResponse> {
public:
int GetMatch(int CamNumber, const char *Text) const;
};
int cCamResponses::GetMatch(int CamNumber, const char *Text) const
{
for (const cCamResponse *cr = First(); cr; cr = Next(cr)) {
int Action = cr->Matches(CamNumber, Text);
if (Action != CRA_NONE) {
dsyslog("CAM %d: auto response %4d to '%s'\n", CamNumber, Action, Text);
return Action;
}
}
return CRA_NONE;
}
cCamResponses CamResponses;
bool CamResponsesLoad(const char *FileName, bool AllowComments, bool MustExist)
{
return CamResponses.Load(FileName, AllowComments, MustExist);
}
// --- cTPDU -----------------------------------------------------------------
#define MAX_TPDU_SIZE 4096
#define MAX_TPDU_DATA (MAX_TPDU_SIZE - 4)
#define DATA_INDICATOR 0x80
#define T_SB 0x80
#define T_RCV 0x81
#define T_CREATE_TC 0x82
#define T_CTC_REPLY 0x83
#define T_DELETE_TC 0x84
#define T_DTC_REPLY 0x85
#define T_REQUEST_TC 0x86
#define T_NEW_TC 0x87
#define T_TC_ERROR 0x88
#define T_DATA_LAST 0xA0
#define T_DATA_MORE 0xA1
class cTPDU {
private:
int size;
uint8_t buffer[MAX_TPDU_SIZE];
const uint8_t *GetData(const uint8_t *Data, int &Length);
public:
cTPDU(void) { size = 0; }
cTPDU(uint8_t Slot, uint8_t Tcid, uint8_t Tag, int Length = 0, const uint8_t *Data = NULL);
uint8_t Slot(void) { return buffer[0]; }
uint8_t Tcid(void) { return buffer[1]; }
uint8_t Tag(void) { return buffer[2]; }
const uint8_t *Data(int &Length) { return GetData(buffer + 3, Length); }
uint8_t Status(void);
uint8_t *Buffer(void) { return buffer; }
int Size(void) { return size; }
void SetSize(int Size) { size = Size; }
int MaxSize(void) { return sizeof(buffer); }
void Dump(int SlotNumber, bool Outgoing);
};
cTPDU::cTPDU(uint8_t Slot, uint8_t Tcid, uint8_t Tag, int Length, const uint8_t *Data)
{
size = 0;
buffer[0] = Slot;
buffer[1] = Tcid;
buffer[2] = Tag;
switch (Tag) {
case T_RCV:
case T_CREATE_TC:
case T_CTC_REPLY:
case T_DELETE_TC:
case T_DTC_REPLY:
case T_REQUEST_TC:
buffer[3] = 1; // length
buffer[4] = Tcid;
size = 5;
break;
case T_NEW_TC:
case T_TC_ERROR:
if (Length == 1) {
buffer[3] = 2; // length
buffer[4] = Tcid;
buffer[5] = Data[0];
size = 6;
}
else
esyslog("ERROR: invalid data length for TPDU tag 0x%02X: %d (%d/%d)", Tag, Length, Slot, Tcid);
break;
case T_DATA_LAST:
case T_DATA_MORE:
if (Length <= MAX_TPDU_DATA) {
uint8_t *p = buffer + 3;
p = SetLength(p, Length + 1);
*p++ = Tcid;
if (Length)
memcpy(p, Data, Length);
size = Length + (p - buffer);
}
else
esyslog("ERROR: invalid data length for TPDU tag 0x%02X: %d (%d/%d)", Tag, Length, Slot, Tcid);
break;
default:
esyslog("ERROR: unknown TPDU tag: 0x%02X (%d/%d)", Tag, Slot, Tcid);
}
}
void cTPDU::Dump(int SlotNumber, bool Outgoing)
{
if (DumpTPDUDataTransfer && (DumpPolls || Tag() != T_SB)) {
#define MAX_DUMP 256
fprintf(stderr, " %d: %s ", SlotNumber, Outgoing ? "-->" : "<--");
for (int i = 0; i < size && i < MAX_DUMP; i++)
fprintf(stderr, "%02X ", buffer[i]);
fprintf(stderr, "%s\n", size >= MAX_DUMP ? "..." : "");
if (!Outgoing) {
fprintf(stderr, " ");
for (int i = 0; i < size && i < MAX_DUMP; i++)
fprintf(stderr, "%2c ", isprint(buffer[i]) ? buffer[i] : '.');
fprintf(stderr, "%s\n", size >= MAX_DUMP ? "..." : "");
}
}
}
const uint8_t *cTPDU::GetData(const uint8_t *Data, int &Length)
{
if (size) {
Data = GetLength(Data, Length);
if (Length) {
Length--; // the first byte is always the tcid
return Data + 1;
}
}
return NULL;
}
uint8_t cTPDU::Status(void)
{
if (size >= 4 && buffer[size - 4] == T_SB && buffer[size - 3] == 2)
return buffer[size - 1];
return 0;
}
// --- cCiTransportConnection ------------------------------------------------
#define MAX_SESSIONS_PER_TC 16
class cCiTransportConnection {
private:
enum eState { stIDLE, stCREATION, stACTIVE, stDELETION };
cMutex mutex;
cCamSlot *camSlot;
uint8_t tcid;
eState state;
bool createConnectionRequested;
bool deleteConnectionRequested;
bool hasUserIO;
cTimeMs alive;
cTimeMs timer;
cCiSession *sessions[MAX_SESSIONS_PER_TC + 1]; // session numbering starts with 1
cCiSession *tsPostProcessor;
void SendTPDU(uint8_t Tag, int Length = 0, const uint8_t *Data = NULL);
void SendTag(uint8_t Tag, uint16_t SessionId, uint32_t ResourceId = 0, int Status = -1);
void Poll(void);
uint32_t ResourceIdToInt(const uint8_t *Data);
cCiSession *GetSessionBySessionId(uint16_t SessionId);
void OpenSession(int Length, const uint8_t *Data);
void CloseSession(uint16_t SessionId);
void HandleSessions(cTPDU *TPDU);
public:
cCiTransportConnection(cCamSlot *CamSlot, uint8_t Tcid);
virtual ~cCiTransportConnection();
void SetTsPostProcessor(cCiSession *CiSession);
bool TsPostProcess(uint8_t *TsPacket);
cCamSlot *CamSlot(void) { return camSlot; }
uint8_t Tcid(void) const { return tcid; }
void CreateConnection(void) { createConnectionRequested = true; }
void DeleteConnection(void) { deleteConnectionRequested = true; }
const char *GetCamName(void);
bool Ready(void);
bool HasUserIO(void) { return hasUserIO; }
void SendData(int Length, const uint8_t *Data);
bool Process(cTPDU *TPDU = NULL);
cCiSession *GetSessionByResourceId(uint32_t ResourceId);
};
// --- cCiSession ------------------------------------------------------------
// Session Tags:
#define ST_SESSION_NUMBER 0x90
#define ST_OPEN_SESSION_REQUEST 0x91
#define ST_OPEN_SESSION_RESPONSE 0x92
#define ST_CREATE_SESSION 0x93
#define ST_CREATE_SESSION_RESPONSE 0x94
#define ST_CLOSE_SESSION_REQUEST 0x95
#define ST_CLOSE_SESSION_RESPONSE 0x96
// Session Status:
#define SS_OK 0x00
#define SS_NOT_ALLOCATED 0xF0
// Resource Identifiers:
#define RI_RESOURCE_MANAGER 0x00010041
#define RI_APPLICATION_INFORMATION 0x00020041
#define RI_CONDITIONAL_ACCESS_SUPPORT 0x00030041
#define RI_HOST_CONTROL 0x00200041
#define RI_DATE_TIME 0x00240041
#define RI_MMI 0x00400041
// Application Object Tags:
#define AOT_NONE 0x000000
#define AOT_PROFILE_ENQ 0x9F8010
#define AOT_PROFILE 0x9F8011
#define AOT_PROFILE_CHANGE 0x9F8012
#define AOT_APPLICATION_INFO_ENQ 0x9F8020
#define AOT_APPLICATION_INFO 0x9F8021
#define AOT_ENTER_MENU 0x9F8022
#define AOT_CA_INFO_ENQ 0x9F8030
#define AOT_CA_INFO 0x9F8031
#define AOT_CA_PMT 0x9F8032
#define AOT_CA_PMT_REPLY 0x9F8033
#define AOT_TUNE 0x9F8400
#define AOT_REPLACE 0x9F8401
#define AOT_CLEAR_REPLACE 0x9F8402
#define AOT_ASK_RELEASE 0x9F8403
#define AOT_DATE_TIME_ENQ 0x9F8440
#define AOT_DATE_TIME 0x9F8441
#define AOT_CLOSE_MMI 0x9F8800
#define AOT_DISPLAY_CONTROL 0x9F8801
#define AOT_DISPLAY_REPLY 0x9F8802
#define AOT_TEXT_LAST 0x9F8803
#define AOT_TEXT_MORE 0x9F8804
#define AOT_KEYPAD_CONTROL 0x9F8805
#define AOT_KEYPRESS 0x9F8806
#define AOT_ENQ 0x9F8807
#define AOT_ANSW 0x9F8808
#define AOT_MENU_LAST 0x9F8809
#define AOT_MENU_MORE 0x9F880A
#define AOT_MENU_ANSW 0x9F880B
#define AOT_LIST_LAST 0x9F880C
#define AOT_LIST_MORE 0x9F880D
#define AOT_SUBTITLE_SEGMENT_LAST 0x9F880E
#define AOT_SUBTITLE_SEGMENT_MORE 0x9F880F
#define AOT_DISPLAY_MESSAGE 0x9F8810
#define AOT_SCENE_END_MARK 0x9F8811
#define AOT_SCENE_DONE 0x9F8812
#define AOT_SCENE_CONTROL 0x9F8813
#define AOT_SUBTITLE_DOWNLOAD_LAST 0x9F8814
#define AOT_SUBTITLE_DOWNLOAD_MORE 0x9F8815
#define AOT_FLUSH_DOWNLOAD 0x9F8816
#define AOT_DOWNLOAD_REPLY 0x9F8817
#define AOT_COMMS_CMD 0x9F8C00
#define AOT_CONNECTION_DESCRIPTOR 0x9F8C01
#define AOT_COMMS_REPLY 0x9F8C02
#define AOT_COMMS_SEND_LAST 0x9F8C03
#define AOT_COMMS_SEND_MORE 0x9F8C04
#define AOT_COMMS_RCV_LAST 0x9F8C05
#define AOT_COMMS_RCV_MORE 0x9F8C06
#define RESOURCE_CLASS_MASK 0xFFFF0000
cCiSession::cCiSession(uint16_t SessionId, uint32_t ResourceId, cCiTransportConnection *Tc)
{
sessionId = SessionId;
resourceId = ResourceId;
tc = Tc;
}
cCiSession::~cCiSession()
{
}
void cCiSession::SetResourceId(uint32_t Id)
{
resourceId = Id;
}
void cCiSession::SetTsPostProcessor(void)
{
tc->SetTsPostProcessor(this);
}
int cCiSession::GetTag(int &Length, const uint8_t **Data)
///< Gets the tag at Data.
///< Returns the actual tag, or AOT_NONE in case of error.
///< Upon return Length and Data represent the remaining data after the tag has been skipped.
{
if (Length >= 3 && Data && *Data) {
int t = 0;
for (int i = 0; i < 3; i++)
t = (t << 8) | *(*Data)++;
Length -= 3;
return t;
}
return AOT_NONE;
}
const uint8_t *cCiSession::GetData(const uint8_t *Data, int &Length)
{
Data = GetLength(Data, Length);
return Length ? Data : NULL;
}
void cCiSession::SendData(int Tag, int Length, const uint8_t *Data)
{
uint8_t buffer[MAX_TPDU_SIZE];
uint8_t *p = buffer;
*p++ = ST_SESSION_NUMBER;
*p++ = 0x02;
*p++ = (sessionId >> 8) & 0xFF;
*p++ = sessionId & 0xFF;
*p++ = (Tag >> 16) & 0xFF;
*p++ = (Tag >> 8) & 0xFF;
*p++ = Tag & 0xFF;
p = SetLength(p, Length);
if (p - buffer + Length < int(sizeof(buffer))) {
if (Data)
memcpy(p, Data, Length);
p += Length;
tc->SendData(p - buffer, buffer);
}
else
esyslog("ERROR: CAM %d: data length (%d) exceeds buffer size", CamSlot()->SlotNumber(), Length);
}
cCamSlot *cCiSession::CamSlot(void)
{
return Tc()->CamSlot();
}
void cCiSession::Process(int Length, const uint8_t *Data)
{
}
// --- cCiResourceManager ----------------------------------------------------
class cCiResourceManager : public cCiSession {
private:
int state;
public:
cCiResourceManager(uint16_t SessionId, cCiTransportConnection *Tc);
virtual void Process(int Length = 0, const uint8_t *Data = NULL);
};
cCiResourceManager::cCiResourceManager(uint16_t SessionId, cCiTransportConnection *Tc)
:cCiSession(SessionId, RI_RESOURCE_MANAGER, Tc)
{
dbgprotocol("Slot %d: new Resource Manager (session id %d)\n", CamSlot()->SlotNumber(), SessionId);
state = 0;
}
void cCiResourceManager::Process(int Length, const uint8_t *Data)
{
if (Data) {
int Tag = GetTag(Length, &Data);
switch (Tag) {
case AOT_PROFILE_ENQ: {
dbgprotocol("Slot %d: <== Profile Enquiry (%d)\n", CamSlot()->SlotNumber(), SessionId());
dbgprotocol("Slot %d: ==> Profile (%d)\n", CamSlot()->SlotNumber(), SessionId());
SendData(AOT_PROFILE, CiResourceHandlers.NumIds() * sizeof(uint32_t), (uint8_t*)CiResourceHandlers.Ids());
state = 3;
}
break;
case AOT_PROFILE: {
dbgprotocol("Slot %d: <== Profile (%d)\n", CamSlot()->SlotNumber(), SessionId());
if (state == 1) {
int l = 0;
const uint8_t *d = GetData(Data, l);
if (l > 0 && d)
esyslog("ERROR: CAM %d: resource manager: unexpected data", CamSlot()->SlotNumber());
dbgprotocol("Slot %d: ==> Profile Change (%d)\n", CamSlot()->SlotNumber(), SessionId());
SendData(AOT_PROFILE_CHANGE);
state = 2;
}
else {
esyslog("ERROR: CAM %d: resource manager: unexpected tag %06X in state %d", CamSlot()->SlotNumber(), Tag, state);
}
}
break;
default: esyslog("ERROR: CAM %d: resource manager: unknown tag %06X", CamSlot()->SlotNumber(), Tag);
}
}
else if (state == 0) {
dbgprotocol("Slot %d: ==> Profile Enq (%d)\n", CamSlot()->SlotNumber(), SessionId());
SendData(AOT_PROFILE_ENQ);
state = 1;
}
}
// --- cCiApplicationInformation ---------------------------------------------
cCiApplicationInformation::cCiApplicationInformation(uint16_t SessionId, cCiTransportConnection *Tc)
:cCiSession(SessionId, RI_APPLICATION_INFORMATION, Tc)
{
dbgprotocol("Slot %d: new Application Information (session id %d)\n", CamSlot()->SlotNumber(), SessionId);
state = 0;
menuString = NULL;
}
cCiApplicationInformation::~cCiApplicationInformation()
{
free(menuString);
}
void cCiApplicationInformation::Process(int Length, const uint8_t *Data)
{
if (Data) {
int Tag = GetTag(Length, &Data);
switch (Tag) {
case AOT_APPLICATION_INFO: {
dbgprotocol("Slot %d: <== Application Info (%d)\n", CamSlot()->SlotNumber(), SessionId());
int l = 0;
const uint8_t *d = GetData(Data, l);
if ((l -= 1) < 0) break;
applicationType = *d++;
if ((l -= 2) < 0) break;
applicationManufacturer = ntohs(get_unaligned((uint16_t *)d));
d += 2;
if ((l -= 2) < 0) break;
manufacturerCode = ntohs(get_unaligned((uint16_t *)d));
d += 2;
free(menuString);
menuString = GetString(l, &d);
isyslog("CAM %d: %s, %02X, %04X, %04X", CamSlot()->SlotNumber(), menuString, applicationType, applicationManufacturer, manufacturerCode);
state = 2;
}
break;
default: esyslog("ERROR: CAM %d: application information: unknown tag %06X", CamSlot()->SlotNumber(), Tag);
}
}
else if (state == 0) {
dbgprotocol("Slot %d: ==> Application Info Enq (%d)\n", CamSlot()->SlotNumber(), SessionId());
SendData(AOT_APPLICATION_INFO_ENQ);
state = 1;
}
}
bool cCiApplicationInformation::EnterMenu(void)
{
if (state == 2) {
dbgprotocol("Slot %d: ==> Enter Menu (%d)\n", CamSlot()->SlotNumber(), SessionId());
SendData(AOT_ENTER_MENU);
return true;
}
return false;
}
// --- cCiCaPmt --------------------------------------------------------------
#define MAXCASYSTEMIDS 64
// Ca Pmt List Management:
#define CPLM_MORE 0x00
#define CPLM_FIRST 0x01
#define CPLM_LAST 0x02
#define CPLM_ONLY 0x03
#define CPLM_ADD 0x04
#define CPLM_UPDATE 0x05
// Ca Pmt Cmd Ids:
#define CPCI_OK_DESCRAMBLING 0x01
#define CPCI_OK_MMI 0x02
#define CPCI_QUERY 0x03
#define CPCI_NOT_SELECTED 0x04
class cCiCaPmt {
friend class cCiConditionalAccessSupport;
private:
uint8_t cmdId;
int esInfoLengthPos;
cDynamicBuffer caDescriptors;
cDynamicBuffer capmt;
int source;
int transponder;
int programNumber;
int caSystemIds[MAXCASYSTEMIDS + 1]; // list is zero terminated!
void AddCaDescriptors(int Length, const uint8_t *Data);
public:
cCiCaPmt(uint8_t CmdId, int Source, int Transponder, int ProgramNumber, const int *CaSystemIds);
uint8_t CmdId(void) { return cmdId; }
void SetListManagement(uint8_t ListManagement);
uint8_t ListManagement(void) { return capmt.Get(0); }
void AddPid(int Pid, uint8_t StreamType);
void MtdMapPids(cMtdMapper *MtdMapper);
};
cCiCaPmt::cCiCaPmt(uint8_t CmdId, int Source, int Transponder, int ProgramNumber, const int *CaSystemIds)
{
cmdId = CmdId;
source = Source;
transponder = Transponder;
programNumber = ProgramNumber;
int i = 0;
if (CaSystemIds) {
for (; CaSystemIds[i]; i++)
caSystemIds[i] = CaSystemIds[i];
}
caSystemIds[i] = 0;
GetCaDescriptors(source, transponder, programNumber, caSystemIds, caDescriptors, 0);
capmt.Append(CPLM_ONLY);
capmt.Append((ProgramNumber >> 8) & 0xFF);
capmt.Append( ProgramNumber & 0xFF);
capmt.Append(0x01); // version_number, current_next_indicator - apparently vn doesn't matter, but cni must be 1
esInfoLengthPos = capmt.Length();
capmt.Append(0x00); // program_info_length H (at program level)
capmt.Append(0x00); // program_info_length L
AddCaDescriptors(caDescriptors.Length(), caDescriptors.Data());
}
void cCiCaPmt::SetListManagement(uint8_t ListManagement)
{
capmt.Set(0, ListManagement);
}
void cCiCaPmt::AddPid(int Pid, uint8_t StreamType)
{
if (Pid) {
GetCaDescriptors(source, transponder, programNumber, caSystemIds, caDescriptors, Pid);
capmt.Append(StreamType);
capmt.Append((Pid >> 8) & 0xFF);
capmt.Append( Pid & 0xFF);
esInfoLengthPos = capmt.Length();
capmt.Append(0x00); // ES_info_length H (at ES level)
capmt.Append(0x00); // ES_info_length L
AddCaDescriptors(caDescriptors.Length(), caDescriptors.Data());
}
}
void cCiCaPmt::AddCaDescriptors(int Length, const uint8_t *Data)
{
if (esInfoLengthPos) {