-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsmartcard.c
2095 lines (1916 loc) · 64.1 KB
/
smartcard.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 <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/poll.h>
#include <unistd.h>
#include <termios.h>
#include <linux/serial.h>
#include <ctype.h>
#include <vdr/tools.h>
#include <vdr/thread.h>
#include "smartcard.h"
#include "global.h"
#include "misc.h"
#include "log-core.h"
#define ISO_FREQ 3571200 // Hz
#define ISO_BAUD 9600
//#define CARD_EMU // include smartcard emulation code
//#define NO_PTS_PROTO // disable PTS protocol (baudrate changes)
// -- cSmartCardSlot -----------------------------------------------------------
class cSmartCardSlot : private cThread, public cStructItem {
private:
cSmartCard *card;
int usecount, cardid;
bool firstRun, needsReset, dead;
cMutex mutex;
cCondVar cond;
//
void SetCard(cSmartCard *c, int cid=0);
bool CardReset(void);
protected:
virtual bool DeviceOpen(const char *cfg)=0;
virtual void DeviceClose(void) {}
virtual bool DeviceSetMode(int mode, int baud)=0;
virtual int DeviceRead(unsigned char *mem, int len, int timeout, int initialTimeout=0)=0;
virtual int DeviceWrite(const unsigned char *mem, int len, int delay=0)=0;
virtual void DeviceToggleReset(void)=0;
virtual bool DevicePTS(void)=0;
virtual bool DeviceIsInserted(void)=0;
virtual int DeviceCurrentMode(void) { return currMode; }
//
virtual void Action(void);
//
int Procedure(unsigned char ins, int restLen);
int Read(unsigned char *data, int len, int to=0);
int Write(const unsigned char *data, int len);
bool Test(bool res);
void Invert(unsigned char *data, int n);
virtual bool Reset(void);
bool ParseAtr(void);
//
int slotnum, clock;
const struct CardConfig *cfg;
unsigned char sb[SB_LEN];
struct Atr atr;
bool localecho, singlereset;
//
char devName[256];
int currMode;
public:
cSmartCardSlot(void);
virtual ~cSmartCardSlot();
bool Setup(int num, const char *cfg);
void SetCardConfig(const struct CardConfig *Cfg) { cfg=Cfg; }
void TriggerReset(void) { needsReset=true; }
bool HaveCard(int id);
cSmartCard *LockCard(int id);
void ReleaseCard(cSmartCard *sc);
void GetCardIdStr(char *str, int len);
bool GetCardInfoStr(char *str, int len);
int SlotNum(void) { return slotnum; }
//
virtual bool IsoRead(const unsigned char *cmd, unsigned char *data);
virtual bool IsoWrite(const unsigned char *cmd, const unsigned char *data);
virtual int RawRead(unsigned char *data, int len, int to=0);
virtual int RawWrite(const unsigned char *data, int len);
};
static const char *serModes[] = { 0,"8e2","8o2","8n2" };
cSmartCardSlot::cSmartCardSlot(void)
{
card=0; cfg=0; usecount=0; slotnum=-1; currMode=SM_NONE; clock=ISO_FREQ;
firstRun=true; needsReset=false; dead=false;
localecho=true; singlereset=false;
}
cSmartCardSlot::~cSmartCardSlot()
{
Cancel(3);
SetCard(0);
DeviceClose();
}
bool cSmartCardSlot::Setup(int num, const char *cfg)
{
slotnum=num;
SetDescription("CardSlot %d watcher",slotnum);
if(DeviceOpen(cfg)) {
firstRun=true;
Start();
return true;
}
return false;
}
bool cSmartCardSlot::HaveCard(int id)
{
cMutexLock lock(&mutex);
while(Running() && firstRun) cond.Wait(mutex);
return card && cardid==id;
}
cSmartCard *cSmartCardSlot::LockCard(int id)
{
mutex.Lock();
while(Running() && firstRun) cond.Wait(mutex);
if(card && cardid==id) {
usecount++;
mutex.Unlock();
card->Lock();
if(DeviceIsInserted() && card->CardUp() && !needsReset) return card;
// if failed, unlock the card and decrement UseCount
card->Unlock();
mutex.Lock();
usecount--;
cond.Broadcast();
}
mutex.Unlock();
return 0;
}
void cSmartCardSlot::ReleaseCard(cSmartCard *sc)
{
if(card==sc) {
card->Unlock();
mutex.Lock();
usecount--;
cond.Broadcast();
mutex.Unlock();
}
}
void cSmartCardSlot::GetCardIdStr(char *str, int len)
{
mutex.Lock();
if(card && !card->GetCardIdStr(str,len)) {
for(cSmartCardLink *scl=smartcards.First(); scl; smartcards.Next(scl)) {
if(scl->Id()==cardid) {
strn0cpy(str,scl->Name(),len);
break;
}
}
}
mutex.Unlock();
}
bool cSmartCardSlot::GetCardInfoStr(char *str, int len)
{
mutex.Lock();
bool res=false;
if(card) res=card->GetCardInfoStr(str,len);
mutex.Unlock();
return res;
}
void cSmartCardSlot::SetCard(cSmartCard *c, int cid)
{
mutex.Lock();
while(usecount) cond.Wait(mutex);
delete card;
card=c; cardid=cid; needsReset=dead=false;
mutex.Unlock();
}
void cSmartCardSlot::Action(void)
{
while(Running()) {
if(card) {
card->Lock();
if(!DeviceIsInserted()) {
card->Unlock();
PRINTF(L_CORE_SC,"%d: card removed (usecount=%d)",slotnum,usecount);
SetCard(0);
}
else if(needsReset) {
PRINTF(L_CORE_SC,"%d: card reset requested",slotnum);
int mode=DeviceCurrentMode()&SM_MASK;
if(!DeviceSetMode(mode,ISO_BAUD)
|| !CardReset()
|| !card->Setup(this,mode,&atr,sb)) {
card->Unlock();
PRINTF(L_CORE_SC,"%d: card re-init failed",slotnum);
SetCard(0); dead=true;
}
}
if(card) card->Unlock();
}
else if(DeviceIsInserted()) {
if(!dead) {
PRINTF(L_CORE_SC,"%d: new card inserted",slotnum);
bool resetdone=false;
for(int mode=SM_NONE+1 ; mode<SM_MAX ; mode++) {
if(DeviceSetMode(mode,ISO_BAUD)) {
if((singlereset && resetdone) || (resetdone=CardReset())) {
for(cSmartCardLink *scl=smartcards.First(); scl; scl=smartcards.Next(scl)) {
if(!Running()) goto done;
PRINTF(L_CORE_SC,"%d: checking for %s card",slotnum,scl->Name());
cSmartCard *sc=scl->Create();
if(sc && sc->Setup(this,mode,&atr,sb)) {
SetCard(sc,scl->Id());
goto done; // ugly, any better solution?
}
delete sc;
}
PRINTF(L_CORE_SC,"%d: no card handler found",slotnum);
}
else PRINTF(L_CORE_SC,"%d: reset/atr error",slotnum);
}
else PRINTF(L_CORE_SC,"%d: failed to set serial mode %s",slotnum,serModes[mode]);
}
dead=true;
PRINTF(L_CORE_SC,"%d: can't initialise new card, ignoring port until card reinserted",slotnum);
}
}
else {
if(dead) PRINTF(L_CORE_SC,"%d: card removed, port reactivated",slotnum);
dead=false;
}
done:
if(firstRun) {
mutex.Lock();
cond.Broadcast();
firstRun=false;
mutex.Unlock();
}
cCondWait::SleepMs(300);
}
}
bool cSmartCardSlot::Reset(void)
{
PRINTF(L_CORE_SC,"%d: reseting card (sermode %s)",slotnum,serModes[DeviceCurrentMode()]);
DeviceToggleReset();
cCondWait::SleepMs(100);
DeviceToggleReset();
int r=DeviceRead(atr.atr,-MAX_ATR_LEN,800,2000);
atr.atrLen=r;
if(r>0) LDUMP(L_CORE_SC,atr.atr,r,"%d: <- ATR len=%d:",slotnum,r);
return r>=2;
}
bool cSmartCardSlot::CardReset(void)
{
if(!Reset() || !ParseAtr()) return false;
if((atr.F!=372 || atr.D!=1.0) && !DevicePTS()) {
// reset card again and continue without PTS
if(!Reset() || !ParseAtr()) return false;
}
return true;
}
void cSmartCardSlot::Invert(unsigned char *data, int n)
{
static const unsigned char swaptab[] = { 15,7,11,3,13,5,9,1,14,6,10,2,12,4,8,0 };
for(int i=n-1; i>=0; i--)
data[i]=(swaptab[data[i]&0x0f]<<4) | swaptab[data[i]>>4];
}
int cSmartCardSlot::Read(unsigned char *data, int len, int to)
{
int r=DeviceRead(data,len,cfg->serTO,to);
if(atr.convention==SM_INDIRECT && r>0) Invert(data,r);
return r;
}
int cSmartCardSlot::Write(const unsigned char *data, int len)
{
unsigned char *tmp=AUTOMEM(len);
if(atr.convention==SM_INDIRECT) {
memcpy(tmp,data,len);
Invert(tmp,len);
data=tmp;
}
int r=DeviceWrite(data,len,cfg->serDL);
if(r>0 && localecho) {
unsigned char *buff=AUTOMEM(r);
int rr=DeviceRead(buff,r,cfg->serTO);
if(rr<0) r=rr;
}
return r;
}
int cSmartCardSlot::Procedure(unsigned char ins, int restLen)
{
int r;
unsigned char buff;
LBSTARTF(L_CORE_SC);
LBPUT("%d: <- PROC: ",slotnum);
do {
do {
if(Read(&buff,1,cfg->workTO)<=0) return -1;
LBPUT("%02x ",buff);
} while(buff==0x60);
if((buff&0xF0)==0x60 || (buff&0xF0)==0x90) { // SW1/SW2
sb[0]=buff;
if(Read(&buff,1)<=0) return -1;
LBPUT("%02x",buff);
sb[1]=buff;
return 0;
}
else {
if((buff&0xFE)==(ins&0xFE)) r=restLen;
else if((~buff&0xFE)==(ins&0xFE)) r=1;
else {
LBPUT("cannot handle procedure %02x (ins=%02x)",buff,ins);
return -1;
}
if(r>restLen) {
LBPUT("data overrun r=%d restLen=%d",r,restLen);
return -1;
}
}
} while(r==0);
LBEND();
return r;
}
bool cSmartCardSlot::Test(bool res)
{
if(!res) {
TriggerReset();
PRINTF(L_CORE_SC,"%d: reset triggered",slotnum);
}
return res;
}
bool cSmartCardSlot::IsoRead(const unsigned char *cmd, unsigned char *data)
{
LDUMP(L_CORE_SC,cmd,CMD_LEN,"%d: -> INS:",slotnum);
if(Write(cmd,CMD_LEN)<0) return Test(false);
int tr=cmd[LEN_IDX] ? cmd[LEN_IDX] : 256;
int len=0;
while(1) {
int r=Procedure(cmd[INS_IDX],tr-len);
if(r<=0) return Test(r==0);
if(Read(data+len,r)<0) return Test(false);
LDUMP(L_CORE_SC,data+len,r,"%d: <- DATA:",slotnum);
len+=r;
}
}
bool cSmartCardSlot::IsoWrite(const unsigned char *cmd, const unsigned char *data)
{
LDUMP(L_CORE_SC,cmd,CMD_LEN,"%d: -> INS:",slotnum);
if(Write(cmd,CMD_LEN)<0) return Test(false);
int len=0;
while(1) {
int r=Procedure(cmd[INS_IDX],cmd[LEN_IDX]-len);
if(r<=0) return Test(r==0);
if(Write(data+len,r)<0) return Test(false);
LDUMP(L_CORE_SC,data+len,r,"%d: -> DATA:",slotnum);
len+=r;
}
}
int cSmartCardSlot::RawRead(unsigned char *data, int len, int to)
{
int r=Read(data,len,to);
if(r<0) Test(false);
return r;
}
int cSmartCardSlot::RawWrite(const unsigned char *data, int len)
{
int r=Write(data,len);
if(r<0) Test(false);
return r;
}
#define NEED(x) { if(len+(x)>atr.atrLen) { LBPUT("SHORT ATR"); return false; } }
bool cSmartCardSlot::ParseAtr(void)
{
// default values
atr.histLen=0; atr.T=0; atr.F=372; atr.fs=clock; atr.D=1.0; atr.N=0; atr.WI=10;
atr.BWI=4; atr.CWI=0; atr.Tspec=-1;
static const int Ftable[16] = {
372,372,558,744,1116,1488,1860,0,0,512,768,1024,1536,2048,0,0
};
static const int fstable[16] = {
3571200,5000000,6000000, 8000000,12000000,16000000,20000000,0,
0,5000000,7500000,10000000,15000000,20000000, 0,0
};
static const float Dtable[16] = {
0.0,1.0,2.0,4.0,8.0,16.0,0.0,0.0,
0.0,0.0,0.5,0.25,0.125,0.0625,0.03125,0.015625
};
const unsigned char *rawatr=atr.atr;
if(rawatr[0]==0x03) {
PRINTF(L_CORE_SC,"%d: indirect convention detected",slotnum);
Invert(atr.atr,atr.atrLen);
atr.convention=SM_INDIRECT;
}
else if(rawatr[0]==0x3B) {
PRINTF(L_CORE_SC,"%d: direct convention detected",slotnum);
atr.convention=SM_DIRECT;
}
else if(rawatr[0]==0x3F) {
PRINTF(L_CORE_SC,"%d: inverted indirect convention detected",slotnum);
atr.convention=SM_INDIRECT_INV;
}
else {
PRINTF(L_CORE_SC,"%d: byte mode not supported 0x%02x",slotnum,rawatr[0]);
return false;
}
// TS TO
atr.histLen=rawatr[1]&0x0F;
int Y=rawatr[1]&0xF0, i=1, len=2;
LBSTARTF(L_CORE_SC);
LBPUT("%d: atr decoding TS=%02x hist=%d Y%d=%02x ",slotnum,rawatr[0],atr.histLen,i,Y);
do {
if(Y&0x10) { // TAi
NEED(1);
LBPUT("TA%d=%02x ",i,rawatr[len]);
if(i==1) {
atr.TA1=rawatr[len];
int i=(rawatr[len]>>4)&0x0F;
atr.F=Ftable[i]; atr.fs=fstable[i];
atr.D=Dtable[rawatr[len]&0x0F];
LBPUT("F=%d fs=%.4f D=%f ",atr.F,atr.fs/1000000.0,atr.D);
}
else if(i==2) {
atr.Tspec=rawatr[len]&0x0F;
LBPUT("Tspec=%d ",atr.Tspec);
}
else if(i==3) {
LBPUT("IFSC=%d ",rawatr[len]);
}
len++;
}
if(Y&0x20) { // TBi
NEED(1);
LBPUT("TB%d=%02x ",i,rawatr[len]);
if(i==3) {
atr.BWI=(rawatr[len]>>4)&0x0F;
atr.CWI=rawatr[len]&0x0F;
LBPUT("BWI=%d CWI=%d ",atr.BWI,atr.CWI);
}
len++;
}
if(Y&0x40) { // TCi
NEED(1);
LBPUT("TC%d=%02x ",i,rawatr[len]);
if(i==1) {
atr.N=rawatr[len];
LBPUT("N=%d ",atr.N);
}
else if(i==2) {
atr.WI=rawatr[len];
LBPUT("WI=%d ",atr.WI);
}
else if(i==3) {
LBPUT("CHK=%s ",rawatr[len]&1 ? "CRC16":"LRC");
}
len++;
}
if(Y&0x80) { // TDi
NEED(1);
LBPUT("TD%d=%02x ",i,rawatr[len]);
if(i==1) {
atr.T=rawatr[len]&0x0F;
LBPUT("T=%d ",atr.T);
}
else {
LBPUT("Tn=%d ",rawatr[len]&0x0F);
}
Y=rawatr[len]&0xF0;
len++;
}
else Y=0;
i++;
LBPUT("Y%d=%02x ",i,Y);
} while(Y);
NEED(atr.histLen);
LBEND();
LBSTART(L_CORE_SC);
LBPUT("%d: historical:",slotnum);
for(int i=0; i<atr.histLen; i++) LBPUT(" %02x",rawatr[len+i]);
LBFLUSH();
LBPUT("%d: historical: '",slotnum);
for(int i=0; i<atr.histLen; i++) LBPUT("%c",isprint(rawatr[len+i]) ? rawatr[len+i] : '.');
LBEND();
memcpy(atr.hist,&rawatr[len],atr.histLen);
len+=atr.histLen;
// TCK
if(atr.T!=0 && len+1<=atr.atrLen) {
len++;
unsigned char cs=XorSum(rawatr+1,len-1);
// according to the ISO the initial TS byte isn't checksumed, but
// some cards do so. In this case the checksum is equal TS.
if(cs==0) PRINTF(L_CORE_SC,"%d: atr checksum ok",slotnum);
else if(cs==rawatr[0]) PRINTF(L_CORE_SC,"iso: %d: atr checksum is TS (not ISO compliant)",slotnum);
else {
PRINTF(L_CORE_SC,"%d: atr checksum FAILED (cs:%02x)",slotnum,cs);
return false;
}
}
else PRINTF(L_CORE_SC,"%d: atr checksum not given/not required",slotnum);
if(atr.atrLen>len) PRINTF(L_CORE_SC,"%d: long atr read=%d len=%d",slotnum,atr.atrLen,len);
atr.wwt=960*atr.WI*atr.F/(clock/1000);
atr.bwt=(int)(960*(float)(1<<atr.BWI)*372/(clock/1000));
PRINTF(L_CORE_SC,"%d: indicated wwt(T0)=%d ms, bwt(T1)=%d ms (at %.4f MHz)",slotnum,atr.wwt,atr.bwt,(float)clock/1000000);
return true;
}
#undef NEED
// -- cSmartCardSlots / cSmartCardSlotLink -------------------------------------
class cSmartCardSlotLink {
public:
cSmartCardSlotLink *next;
const char *name;
public:
cSmartCardSlotLink(const char *Name);
virtual ~cSmartCardSlotLink() {}
virtual cSmartCardSlot *Create(void)=0;
};
template<class LL> class cSmartCardSlotLinkReg : public cSmartCardSlotLink {
public:
cSmartCardSlotLinkReg(const char *Name):cSmartCardSlotLink(Name) {}
virtual cSmartCardSlot *Create(void) { return new LL; }
};
class cSmartCardSlots : public cStructListPlain<cSmartCardSlot> {
friend class cSmartCardSlotLink;
private:
static cSmartCardSlotLink *first;
//
static void Register(cSmartCardSlotLink *scl);
protected:
virtual bool ParseLinePlain(const char *line);
public:
cSmartCardSlots(void);
cSmartCardSlot *GetSlot(int num);
cSmartCardSlot *FirstSlot(void);
void Release(void);
};
cSmartCardSlotLink *cSmartCardSlots::first=0;
static cSmartCardSlots cardslots;
cSmartCardSlotLink::cSmartCardSlotLink(const char *Name)
{
name=Name;
cSmartCardSlots::Register(this);
}
cSmartCardSlots::cSmartCardSlots(void)
:cStructListPlain<cSmartCardSlot>("cardslot config","cardslot.conf",SL_MISSINGOK|SL_VERBOSE|SL_NOPURGE)
{}
void cSmartCardSlots::Register(cSmartCardSlotLink *scl)
{
PRINTF(L_CORE_DYN,"registering cardslot type %s",scl->name);
scl->next=first;
first=scl;
}
cSmartCardSlot *cSmartCardSlots::GetSlot(int num)
{
ListLock(false);
for(cSmartCardSlot *slot=First(); slot; slot=Next(slot))
if(slot->SlotNum()==num) return slot;
return 0;
}
cSmartCardSlot *cSmartCardSlots::FirstSlot(void)
{
ListLock(false);
return First();
}
void cSmartCardSlots::Release(void)
{
ListUnlock();
}
bool cSmartCardSlots::ParseLinePlain(const char *line)
{
char type[32];
int num;
if(sscanf(line,"%31[^:]:%n",type,&num)==1) {
for(cSmartCardSlotLink *scs=first; scs; scs=scs->next) {
if(!strcasecmp(type,scs->name)) {
cSmartCardSlot *slot=scs->Create();
if(slot) {
if(slot->Setup(Count(),&line[num])) {
Add(slot);
return true;
}
delete slot;
}
else PRINTF(L_GEN_ERROR,"failed to create cardslot");
return false;
}
}
PRINTF(L_GEN_ERROR,"unknown cardslot type '%s'",type);
}
return false;
}
// -- cSmartCardSlotSerial -----------------------------------------------------
class cSmartCardSlotSerial : public cSmartCardSlot {
private:
int statInv, invRST;
bool custombaud;
//
speed_t FindBaud(int baud);
protected:
int fd;
//
void Flush(void);
void SetDtrRts(void);
//
virtual bool DeviceOpen(const char *cfg);
virtual void DeviceClose(void);
virtual bool DeviceSetMode(int mode, int baud);
virtual int DeviceRead(unsigned char *mem, int len, int timeout, int initialTimeout=0);
virtual int DeviceWrite(const unsigned char *mem, int len, int delay=0);
virtual void DeviceToggleReset(void);
virtual bool DevicePTS(void);
virtual bool DeviceIsInserted(void);
public:
cSmartCardSlotSerial(void);
};
static cSmartCardSlotLinkReg<cSmartCardSlotSerial> __scs_serial("serial");
cSmartCardSlotSerial::cSmartCardSlotSerial(void)
{
fd=-1; statInv=0; invRST=false; custombaud=false;
}
bool cSmartCardSlotSerial::DeviceOpen(const char *cfg)
{
int invCD=0;
if(sscanf(cfg,"%255[^:]:%d:%d:%d",devName,&invCD,&invRST,&clock)>=3) {
if(clock<=0) clock=ISO_FREQ;
statInv=invCD ? TIOCM_CAR:0;
PRINTF(L_CORE_SERIAL,"%s: open serial port",devName);
fd=open(devName,O_RDWR|O_NONBLOCK|O_NOCTTY);
if(fd>=0) {
SetDtrRts();
PRINTF(L_CORE_SERIAL,"%s: init done",devName);
PRINTF(L_CORE_LOAD,"cardslot: added serial port %s as port %d (%s CD, %s RESET, CLOCK %d)",
devName,slotnum,invCD?"inverse":"normal",invRST?"inverse":"normal",clock);
return true;
}
else PRINTF(L_GEN_ERROR,"%s: open failed: %s",devName,strerror(errno));
}
else PRINTF(L_GEN_ERROR,"bad parameter for cardslot type 'serial'");
return false;
}
void cSmartCardSlotSerial::SetDtrRts(void)
{
PRINTF(L_CORE_SERIAL,"%s: set DTR/RTS",devName);
unsigned int modembits;
modembits=TIOCM_DTR; CHECK(ioctl(fd, TIOCMBIS, &modembits));
modembits=TIOCM_RTS; CHECK(ioctl(fd, invRST?TIOCMBIS:TIOCMBIC, &modembits));
}
void cSmartCardSlotSerial::DeviceClose(void)
{
if(fd>=0) {
PRINTF(L_CORE_SERIAL,"%s: shutting down",devName);
Flush();
unsigned int modembits=0;
CHECK(ioctl(fd,TIOCMSET,&modembits));
close(fd); fd=-1;
PRINTF(L_CORE_SERIAL,"%s: shutdown done",devName);
}
}
void cSmartCardSlotSerial::Flush(void)
{
if(fd>=0) CHECK(tcflush(fd,TCIOFLUSH));
}
speed_t cSmartCardSlotSerial::FindBaud(int baud)
{
static const struct BaudRates { int real; speed_t apival; } BaudRateTab[] = {
{ 9600, B9600 }, { 19200, B19200 }, { 38400, B38400 },
{ 57600, B57600 }, { 115200, B115200 }, { 230400, B230400 }
};
for(int i=0; i<(int)(sizeof(BaudRateTab)/sizeof(struct BaudRates)); i++) {
int b=BaudRateTab[i].real;
int d=((b-baud)*10000)/b;
if(abs(d)<=300) {
PRINTF(L_CORE_SERIAL,"%s: requested baudrate %d -> %d (%+.2f%%)",devName,baud,b,(float)d/100.0);
return BaudRateTab[i].apival;
}
}
PRINTF(L_CORE_SERIAL,"%s: requested baudrate %d -> custom",devName,baud);
return B0;
}
bool cSmartCardSlotSerial::DeviceSetMode(int mode, int baud)
{
if(fd>=0) {
speed_t bconst=FindBaud(baud);
bool custom=false;
if(bconst==B0) { custom=true; bconst=B38400; }
struct termios tio;
memset(&tio,0,sizeof(tio));
LBSTARTF(L_CORE_SERIAL);
LBPUT("%s: set serial options: %d,",devName,baud);
tio.c_cflag = (CS8 | CREAD | HUPCL | CLOCAL);
if(!(mode&SM_1SB)) tio.c_cflag |= CSTOPB;
tio.c_iflag = (INPCK | IGNBRK);
tio.c_cc[VMIN] = 1;
cfsetispeed(&tio,bconst);
cfsetospeed(&tio,bconst);
switch(mode&SM_MASK) {
case SM_8E2:
LBPUT("8e%d",(mode&SM_1SB)?1:2);
tio.c_cflag |= PARENB; break;
case SM_8N2:
LBPUT("8n%d",(mode&SM_1SB)?1:2);
break;
case SM_8O2:
LBPUT("8o%d",(mode&SM_1SB)?1:2);
tio.c_cflag |= (PARENB | PARODD); break;
default:
LBPUT("BAD MODE");
return false;
}
LBEND();
struct serial_struct s;
if(ioctl(fd,TIOCGSERIAL,&s)<0) {
if(custom || custombaud) {
PRINTF(L_GEN_ERROR,"%s: get serial failed: %s",devName,strerror(errno));
return false;
}
PRINTF(L_CORE_SERIAL,"%s: get serial failed: %s",devName,strerror(errno));
PRINTF(L_CORE_SERIAL,"%s: custombaud not used, try to continue...",devName);
}
else if(!custom && ((s.flags&ASYNC_SPD_MASK)==ASYNC_SPD_CUST || s.custom_divisor!=0)) {
s.custom_divisor=0;
s.flags &= ~ASYNC_SPD_MASK;
if(ioctl(fd,TIOCSSERIAL,&s)<0) {
PRINTF(L_GEN_ERROR,"%s: set serial failed: %s",devName,strerror(errno));
return false;
}
custombaud=false;
}
if(!tcsetattr(fd,TCSANOW,&tio)) {
if(custom) {
s.custom_divisor=(s.baud_base+(baud/2))/baud;
s.flags=(s.flags&~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
PRINTF(L_CORE_SERIAL,"%s: custom: baud_base=%d baud=%d devisor=%d -> effective baudrate %d (%+.2f%% off)",devName,s.baud_base,baud,s.custom_divisor,s.baud_base/s.custom_divisor,(float)(s.baud_base/s.custom_divisor-baud)/(float)baud);
if(ioctl(fd,TIOCSSERIAL,&s)<0) {
PRINTF(L_GEN_ERROR,"%s: set serial failed: %s",devName,strerror(errno));
return false;
}
custombaud=true;
}
currMode=mode; Flush();
return true;
}
else PRINTF(L_GEN_ERROR,"%s: tcsetattr failed: %s",devName,strerror(errno));
}
return false;
}
int cSmartCardSlotSerial::DeviceRead(unsigned char *mem, int len, int timeout, int initialTimeout)
{
PRINTF(L_CORE_SERIAL,"%s: read len=%d timeout=%d:%d",devName,len,timeout,initialTimeout);
bool incomplete=false;
if(len<0) { len=-len; incomplete=true; }
int to=initialTimeout>0 ? initialTimeout : timeout;
int n=0;
while(n<len) {
int r=read(fd,mem+n,len-n);
if(r<=0) {
if(r==0) PRINTF(L_CORE_SERIAL,"%s: read bogus eof",devName);
if(errno==EAGAIN) {
struct pollfd u;
u.fd=fd; u.events=POLLIN;
r=poll(&u,1,to);
if(r<0) {
PRINTF(L_GEN_ERROR,"%s: read poll failed: %s",devName,strerror(errno));
return -1;
}
else if(r==0) { // timeout
PRINTF(L_CORE_SERIAL,"%s: read timeout (%d ms)",devName,to);
if(n>0 && incomplete) break; // return bytes read so far
return -2;
}
continue;
}
else {
PRINTF(L_GEN_ERROR,"%s: read failed: %s",devName,strerror(errno));
return -1;
}
}
n+=r; to=timeout;
}
HEXDUMP(L_CORE_SERIAL,mem,n,"%s: read data",devName);
return n;
}
int cSmartCardSlotSerial::DeviceWrite(const unsigned char *mem, int len, int delay)
{
PRINTF(L_CORE_SERIAL,"%s: write len=%d delay=%d",devName,len,delay);
HEXDUMP(L_CORE_SERIAL,mem,len,"%s: write data",devName);
Flush();
int n=0;
while(n<len) {
struct pollfd u;
u.fd=fd; u.events=POLLOUT;
int r;
do {
r=poll(&u,1,500);
if(r<0) {
PRINTF(L_GEN_ERROR,"%s: write poll failed: %s",devName,strerror(errno));
return -1;
}
else if(r==0) { // timeout
PRINTF(L_CORE_SERIAL,"%s: write timeout",devName);
return -2;
}
} while(r<1);
r=write(fd,mem+n,delay>0?1:len-n);
if(r<0 && errno!=EAGAIN) {
PRINTF(L_GEN_ERROR,"%s: write failed: %s",devName,strerror(errno));
return -1;
}
if(r>0) n+=r;
if(delay>0) cCondWait::SleepMs(delay);
}
return n;
}
void cSmartCardSlotSerial::DeviceToggleReset(void)
{
int mask=0;
if(ioctl(fd,TIOCMGET,&mask)<0) { LOG_ERROR; return; }
if(mask&TIOCM_RTS) { mask&=~TIOCM_RTS; PRINTF(L_CORE_SERIAL,"%s: toggle RTS, now off",devName); }
else { mask|= TIOCM_RTS; PRINTF(L_CORE_SERIAL,"%s: toggle RTS, now on",devName); }
CHECK(ioctl(fd,TIOCMSET,&mask));
Flush();
}
bool cSmartCardSlotSerial::DevicePTS(void)
{
int baud=(int)((float)clock*atr.D/atr.F);
PRINTF(L_CORE_SC,"%d: PTS cycle: calculated baudrate %d",slotnum,baud);
if(atr.Tspec<0) {
PRINTF(L_CORE_SC,"%d: negotiable mode",slotnum);
#ifdef NO_PTS_PROTO
PRINTF(L_CORE_SC,"%d: PTS disabled at compile time!!!",slotnum);
return true;
#else
unsigned char req[4], conf[16];
req[0]=0xFF;
req[1]=0x10 | atr.T;
req[2]=atr.TA1;
req[3]=XorSum(req,3);
LDUMP(L_CORE_SC,req,4,"%d: PTS request:",slotnum);
if(DeviceWrite(req,4)!=4) {
PRINTF(L_CORE_SC,"%d: PTS request, write failed",slotnum);
return false;
}
if(DeviceRead(conf,4,100,100)!=4) {
PRINTF(L_CORE_SC,"%d: PTS request, echo readback failed",slotnum);
return false;
}
int n=DeviceRead(conf,-16,200,1000);
if(n>0) LDUMP(L_CORE_SC,conf,n,"%d: PTS confirm:",slotnum);
if(n<1 || conf[0]!=0xFF || XorSum(conf,n)!=0) {
PRINTF(L_CORE_SC,"%d: PTS confirm, bad format",slotnum);
return false;
}
if(n<4 || conf[1]!=req[1] || conf[2]!=req[2]) {
PRINTF(L_CORE_SC,"%d: PTS not confirmed",slotnum);
return false;
}
#endif // NO_PTS_PROTO
}
else
PRINTF(L_CORE_SC,"%d: specific mode Tspec=%d",slotnum,atr.Tspec);
int mode=DeviceCurrentMode();
if(atr.N==255) mode|=SM_1SB;
if(!DeviceSetMode(mode,baud)) {
PRINTF(L_CORE_SC,"%d: setting baudrate %d failed",slotnum,baud);
return false;
}
return true;
}
bool cSmartCardSlotSerial::DeviceIsInserted(void)
{
int status=0;
if(ioctl(fd,TIOCMGET,&status)<0) { LOG_ERROR; return false; }
PRINTF(L_CORE_SERIAL,"%s: CAR is %sactive (lines:%s%s%s%s%s%s%s%s%s)",
devName,(status&TIOCM_CAR)?"in":"",
(status&TIOCM_LE)?" LE":"", (status&TIOCM_DTR)?" DTR":"",
(status&TIOCM_RTS)?" RTS":"",(status&TIOCM_ST)?" ST":"",
(status&TIOCM_SR)?" SR":"", (status&TIOCM_CTS)?" CTS":"",
(status&TIOCM_CAR)?" CAR":"",(status&TIOCM_RNG)?" RNG":"",
(status&TIOCM_DSR)?" DSR":"" );
status^=statInv; // invert status for broken cardreaders
return !(status & TIOCM_CAR);
}
// -- cSmartCardSlotSRPlus -----------------------------------------------------
class cSmartCardSlotSRPlus : public cSmartCardSlotSerial {
private:
bool SRConfig(int F, float D, int fs, int N, int T, int inv);
protected:
virtual bool DeviceOpen(const char *cfg);
virtual bool DeviceSetMode(int mode, int baud);
virtual bool DevicePTS(void);
public:
cSmartCardSlotSRPlus(void);
};
static cSmartCardSlotLinkReg<cSmartCardSlotSRPlus> __scs_srplus("srplus");
cSmartCardSlotSRPlus::cSmartCardSlotSRPlus(void)
{
localecho=false;
}
bool cSmartCardSlotSRPlus::DeviceOpen(const char *cfg)
{
if(sscanf(cfg,"%255[^:]:%d",devName,&clock)>=1) {
if(clock<=0) clock=ISO_FREQ;
PRINTF(L_CORE_SERIAL,"%s: open serial port",devName);
fd=open(devName,O_RDWR|O_NONBLOCK|O_NOCTTY);
if(fd>=0) {
SetDtrRts();
PRINTF(L_CORE_SERIAL,"%s: init done",devName);
PRINTF(L_CORE_LOAD,"cardslot: added smartreader+ port %s as port %d (CLOCK %d)",
devName,slotnum,clock);
return true;
}
else PRINTF(L_GEN_ERROR,"%s: open failed: %s",devName,strerror(errno));
}
else PRINTF(L_GEN_ERROR,"bad parameter for cardslot type 'srplus'");
return false;
}
bool cSmartCardSlotSRPlus::DeviceSetMode(int mode, int baud)