aboutsummaryrefslogtreecommitdiffstats
path: root/firmware/libcommon/source/cciddriver.c
blob: 8cf28ca30977f7c96ef2971585fff6578fcd71ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
/* ----------------------------------------------------------------------------
 *         ATMEL Microcontroller Software Support 
 * ----------------------------------------------------------------------------
 * Copyright (c) 2008, Atmel Corporation
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer below.
 *
 * Atmel's name may not be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ----------------------------------------------------------------------------
 */

//------------------------------------------------------------------------------
/// \unit
///
/// !Purpose
/// 
/// CCID driver
/// 
/// !Usage
/// 
/// Explanation on the usage of the code made available through the header file.
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//       Headers
//------------------------------------------------------------------------------

#include "board.h"
#include "simtrace.h"

#ifdef HAVE_CCID

#include <USBDDriver.h>
#include <USBRequests.h>
#include <USBDescriptors.h>
//#include <usb/device/dfu/dfu.h>
#include <cciddriverdescriptors.h>

// FIXME: Remove DFU related stuff 
/* no DFU bootloader is being used */
#define DFU_NUM_IF      0
#define DFU_IF_DESCRIPTORS_STRUCT
#define DFU_IF_DESCRIPTORS

#define DFU_NUM_STRINGS 0
#define DFU_STRING_DESCRIPTORS

//------------------------------------------------------------------------------
//         Local definition
//------------------------------------------------------------------------------

/// Constants: IDs: Device product ID.
//#define CCIDDriverDescriptors_PRODUCTID       0x6129
#define CCIDDriverDescriptors_PRODUCTID       SIMTRACE_PRODUCT_ID
/// Constants: IDs: Device vendor ID.
#define CCIDDriverDescriptors_VENDORID        ATMEL_VENDOR_ID
//#define CCIDDriverDescriptors_VENDORID        0x03EB
/// Constants: IDs: Device release number.
#define CCIDDriverDescriptors_RELEASE         0x0100

//------------------------------------------------------------------------------
//         Types
//------------------------------------------------------------------------------

/// Driver structure for an CCID device
typedef struct {

    /// CCID message
    S_ccid_bulk_in_header  sCcidMessage;
    /// CCID command
    S_ccid_bulk_out_header sCcidCommand;
    /// Interrupt message answer
    unsigned char          BufferINT[4];
    /// Buffer data of message
    unsigned char          ProtocolDataStructure[10];
    /// Protocol used
    unsigned char          bProtocol;
    /// SlotStatus
    /// Bit 0 = Slot 0 current state
    /// Bit 1 = Slot 0 changed status
    /// Bit 2 = Slot 1 current state
    /// Bit 3 = Slot 1 changed status
    /// Bit 4 = Slot 2 current state
    /// Bit 5 = Slot 2 changed status
    unsigned char          SlotStatus;

} CCIDDriver;

//------------------------------------------------------------------------------
//         Local variables
//------------------------------------------------------------------------------

/// Static instance of the CCID device driver.
static CCIDDriver ccidDriver;
static CCIDDriverConfigurationDescriptors *configurationDescriptorsFS;

//------------------------------------------------------------------------------
//      Internal functions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
/// Initializes the CCID device driver.
//------------------------------------------------------------------------------
void CCIDDriver_Initialize( void )
{
    configurationDescriptorsFS = (CCIDDriverConfigurationDescriptors *) configurationDescriptorsArr[CFG_NUM_CCID-1];
}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Return the Slot Status to the host
/// Answer to:
///   PC_to_RDR_IccPowerOff
///   PC_to_RDR_GetSlotStatus
///   PC_to_RDR_IccClock
///   PC_to_RDR_T0APDU
///   PC_to_RDR_Mechanical
///   PC_to_RDR_Abort and Class specific ABORT request
//------------------------------------------------------------------------------
static void RDRtoPCSlotStatus( void )
{
    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_SLOTSTATUS;
    ccidDriver.sCcidMessage.wLength   = 0;

    if (ccidDriver.SlotStatus == ICC_INSERTED_EVENT) {
        ccidDriver.sCcidMessage.bStatus = 0;    /* ICC present and active card */
    } else if (ccidDriver.SlotStatus == ICC_NOT_PRESENT) {
        ccidDriver.sCcidMessage.bStatus = 2;    /* No ICC present*/
    } else{
        TRACE_ERROR("Strange bStatus");
        ccidDriver.sCcidMessage.bStatus = 0;
    }
    ccidDriver.sCcidMessage.bError    = 0;
    // 00h Clock running
    // 01h Clock stopped in state L
    // 02h Clock stopped in state H
    // 03h Clock stopped in an unknown state
    // All other values are Reserved for Future Use.
    ccidDriver.sCcidMessage.bSpecific = 0;
}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Answer to PC_to_RDR_IccPowerOn
//------------------------------------------------------------------------------
static void RDRtoPCDatablock_ATR( void )
{
    unsigned char i;
    unsigned char Atr[ATR_SIZE_MAX];
    unsigned char length;
    uint32_t status; 

    TRACE_DEBUG(".");

    status = ISO7816_Datablock_ATR( Atr, &length );
    ISO7816_Decode_ATR( Atr );

    if (status == 0) {
        TRACE_DEBUG("Timeout occured while reading ATR");
// FIXME: react properly to timeout..
//        return;
    }

// FIXME: More tests? Is bProtocol = Atr[3] ?
    if( length > 5 ) {
        ccidDriver.ProtocolDataStructure[1] = Atr[3]&0x0F; // TD(1)
        ccidDriver.bProtocol = Atr[3]&0x0F;           // TD(1)
        TRACE_INFO("Protocol data structure: 0x%x\n\r",
                        ccidDriver.ProtocolDataStructure[1]);
    }

    // S_ccid_protocol_t0
    // bmFindexDindex
    ccidDriver.ProtocolDataStructure[0] = Atr[2];     // TA(1)

    // bmTCCKST0
    // For T=0 ,B0 – 0b, B7-2 – 000000b
    // B1 – Convention used (b1=0 for direct, b1=1 for inverse)

    // bGuardTimeT0
    // Extra Guardtime between two characters. Add 0 to 254 etu to the normal 
    // guardtime of 12etu. FFh is the same as 00h.
    ccidDriver.ProtocolDataStructure[2] = Atr[4];     // TC(1)
    // AT91C_BASE_US0->US_TTGR = 0;  // TC1

    // bWaitingIntegerT0
    // WI for T=0 used to define WWT
    ccidDriver.ProtocolDataStructure[3] = Atr[7];     // TC(2)

    // bClockStop
    // ICC Clock Stop Support
    // 00 = Stopping the Clock is not allowed
    // 01 = Stop with Clock signal Low
    // 02 = Stop with Clock signal High
    // 03 = Stop with Clock either High or Low
    ccidDriver.ProtocolDataStructure[4] = 0x00;       // 0 to 3

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_DATABLOCK;
    ccidDriver.sCcidMessage.wLength      = length;  // Size of ATR
    ccidDriver.sCcidMessage.bSizeToSend += length;  // Size of ATR
    // bChainParameter: 00 the response APDU begins and ends in this command
    ccidDriver.sCcidMessage.bSpecific    = 0;

    for( i=0; i<length; i++ ) {

        ccidDriver.sCcidMessage.abData[i]  = Atr[i];
    }

    // Set the slot to an active status
    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError = 0;
}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// In other cases, the response message has the following format: 
/// The response data will contain the optional data returned by the ICC, 
/// followed by the 2 byte-size status words SW1-SW2.
///
/// Answer to:
///   PC_to_RDR_XfrBlock
///   PC_to_RDR_Secure
//------------------------------------------------------------------------------
static void RDRtoPCDatablock( void )
{
    //TRACE_DEBUG(".");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_DATABLOCK;
    ccidDriver.sCcidMessage.bSizeToSend += ccidDriver.sCcidMessage.wLength;
    // bChainParameter: 00 the response APDU begins and ends in this command
    ccidDriver.sCcidMessage.bSpecific = 0;

    // Set the slot to an active status
    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError = 0;
}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Answer to:
///   PC_to_RDR_GetParameters
///   PC_to_RDR_ResetParameters
///   PC_to_RDR_SetParameters
//------------------------------------------------------------------------------
static void RDRtoPCParameters( void )
{
    unsigned int i;

    TRACE_DEBUG(".");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_PARAMETERS;

    //ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError  = 0;

    if( ccidDriver.ProtocolDataStructure[1] == PROTOCOL_TO ) {

        // T=0
        ccidDriver.sCcidMessage.wLength   = sizeof(S_ccid_protocol_t0);
        ccidDriver.sCcidMessage.bSpecific = PROTOCOL_TO;
    }
    else {

        // T=1
        ccidDriver.sCcidMessage.wLength   = sizeof(S_ccid_protocol_t1);
        ccidDriver.sCcidMessage.bSpecific = PROTOCOL_T1;
    }

    ccidDriver.sCcidMessage.bSizeToSend += ccidDriver.sCcidMessage.wLength;

    for( i=0; i<ccidDriver.sCcidMessage.wLength; i++ ) {
        ccidDriver.sCcidMessage.abData[i] = ccidDriver.ProtocolDataStructure[i];
    }

}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Answer to:
///   PC_to_RDR_Escape
//------------------------------------------------------------------------------
static void RDRtoPCEscape( unsigned char length, unsigned char *data_send_from_CCID )
{
    unsigned int i;

    TRACE_DEBUG(".");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_ESCAPE;

    ccidDriver.sCcidMessage.wLength   = length;

    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError  = 0;

    ccidDriver.sCcidMessage.bSpecific = 0;  // bRFU

    for( i=0; i<length; i++ ) {
        ccidDriver.sCcidMessage.abData[i] = data_send_from_CCID[i];
    }
}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Answer to: 
///   PC_to_RDR_SetDataRateAndClockFrequency
//------------------------------------------------------------------------------
static void RDRtoPCDataRateAndClockFrequency( unsigned int dwClockFrequency, 
                                       unsigned int dwDataRate )
{
    TRACE_DEBUG(".");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_DATARATEANDCLOCKFREQUENCY;

    ccidDriver.sCcidMessage.wLength   = 8;

    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError  = 0;

    ccidDriver.sCcidMessage.bSpecific = 0;  // bRFU

    ccidDriver.sCcidMessage.abData[0] = dwClockFrequency;
    
    ccidDriver.sCcidMessage.abData[4] = dwDataRate;
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// Power On Command - Cold Reset & Warm Reset 
/// Return the ATR to the host
//------------------------------------------------------------------------------
static void PCtoRDRIccPowerOn( void )
{
    TRACE_DEBUG(".");
    if( CCID_FEATURES_AUTO_VOLT == (configurationDescriptorsFS->ccid.dwFeatures & CCID_FEATURES_AUTO_VOLT) ) {

        //bPowerSelect = ccidDriver.sCcidCommand.bSpecific_0;
        ccidDriver.sCcidCommand.bSpecific_0 = VOLTS_AUTO;
    }

    ISO7816_warm_reset();
//    ISO7816_cold_reset();

    // for emulation only //JCB 
    if ( ccidDriver.sCcidCommand.bSpecific_0 != VOLTS_5_0 ) {

        TRACE_ERROR("POWER_NOT_SUPPORTED\n\r");
    }

    else {

        RDRtoPCDatablock_ATR();

    }
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// Power Off Command - Set the ICC in an inactive state
/// Return the slot status to the host
//------------------------------------------------------------------------------
static void PCtoRDRIccPowerOff( void )
{
    unsigned char bStatus;

    TRACE_DEBUG(".");

    ISO7816_IccPowerOff();

    //JCB stub
    bStatus = ICC_BS_PRESENT_NOTACTIVATED;

    // Set the slot to an inactive status
    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError = 0;

    // if error, see Table 6.1-2 errors

    // Return the slot status to the host
    RDRtoPCSlotStatus();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// Get slot status
//------------------------------------------------------------------------------
static void PCtoRDRGetSlotStatus( void )
{
    TRACE_DEBUG(".");

    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError = 0;

    // Return the slot status to the host
    RDRtoPCSlotStatus();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// If the command header is valid, an APDU command is received and can be read
/// by the application
//------------------------------------------------------------------------------
static void PCtoRDRXfrBlock( void )
{
    uint16_t msglen = 0;
    uint32_t ret;

    TRACE_DEBUG("PCtoRDRXfrBlock\n");

    // Check the block length
    if ( ccidDriver.sCcidCommand.wLength > (configurationDescriptorsFS->ccid.dwMaxCCIDMessageLength-10) ) {
        TRACE_DEBUG("Err block/msg len");
        ccidDriver.sCcidMessage.bStatus = 1;
        ccidDriver.sCcidMessage.bError  = 0;
    }
    // check bBWI
    else if ( 0 != ccidDriver.sCcidCommand.bSpecific_0 ) {

         TRACE_ERROR("Bad bBWI\n\r");
    }
    else {

        // APDU or TPDU
        switch(configurationDescriptorsFS->ccid.dwFeatures 
              & (CCID_FEATURES_EXC_TPDU|CCID_FEATURES_EXC_SAPDU|CCID_FEATURES_EXC_APDU)) {

            case CCID_FEATURES_EXC_TPDU:
                if (ccidDriver.ProtocolDataStructure[1] == PROTOCOL_TO) {
                    TRACE_DEBUG("APDU cmd: %x %x %x ..", ccidDriver.sCcidCommand.APDU[0], ccidDriver.sCcidCommand.APDU[1],ccidDriver.sCcidCommand.APDU[2] );

                    // Send commande APDU
                    ret = ISO7816_XfrBlockTPDU_T0( ccidDriver.sCcidCommand.APDU ,
                                            ccidDriver.sCcidMessage.abData,
                                            ccidDriver.sCcidCommand.wLength,
                                            &msglen );
                    if (ret != 0) {
                        TRACE_ERROR("APDU could not be sent: (US_CSR = 0x%x)", ret);
                        return;
                    }
                }
                else {
                    if (ccidDriver.ProtocolDataStructure[1] == PROTOCOL_T1) {
                        TRACE_DEBUG("Not supported T=1\n\r");
                    }
                    else {
                        TRACE_DEBUG("Not supported 0x%x\n\r", ccidDriver.ProtocolDataStructure[1]);
                    }
                }
                break;

            case CCID_FEATURES_EXC_APDU:
                TRACE_DEBUG("Not supported CCID_FEATURES_EXC_APDU\n\r");
                break;

            default:
                break;
        }

    }

    ccidDriver.sCcidMessage.wLength = msglen;
    TRACE_DEBUG("USB: 0x%X, 0x%X, 0x%X, 0x%X, 0x%X\n\r", ccidDriver.sCcidMessage.abData[0], 
                                                                    ccidDriver.sCcidMessage.abData[1], 
                                                                    ccidDriver.sCcidMessage.abData[2], 
                                                                    ccidDriver.sCcidMessage.abData[3],
                                                                    ccidDriver.sCcidMessage.abData[4] );
     RDRtoPCDatablock();

}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// return parameters by the command: RDR_to_PC_Parameters
//------------------------------------------------------------------------------
static void PCtoRDRGetParameters( void )
{
    TRACE_DEBUG(".");

    // We support only one slot

    // bmIccStatus
    if( ISO7816_StatusReset() ) {
        // 0: An ICC is present and active (power is on and stable, RST is inactive
        ccidDriver.sCcidMessage.bStatus = 0;
    }
    else {
        // 1: An ICC is present and inactive (not activated or shut down by hardware error)
        ccidDriver.sCcidMessage.bStatus = 1;
    }

    RDRtoPCParameters();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command resets the slot parameters to their default values
//------------------------------------------------------------------------------
static void PCtoRDRResetParameters( void )
{
    TRACE_DEBUG(".");

    ccidDriver.SlotStatus = ICC_NOT_PRESENT;
    ccidDriver.sCcidMessage.bStatus = ccidDriver.SlotStatus;

    RDRtoPCParameters();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command is used to change the parameters for a given slot.
//------------------------------------------------------------------------------
static void PCtoRDRSetParameters( void )
{
    TRACE_DEBUG(".");

    ccidDriver.SlotStatus = ccidDriver.sCcidCommand.bSlot;
    ccidDriver.sCcidMessage.bStatus = ccidDriver.SlotStatus;
    // Not all feature supported

    RDRtoPCParameters();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command allows the CCID manufacturer to define and access extended 
/// features. 
/// Information sent via this command is processed by the CCID control logic.
//------------------------------------------------------------------------------
static void PCtoRDREscape( void )
{
    TRACE_DEBUG(".");

    // If needed by the user
    ISO7816_Escape();

    // stub, return all value send
    RDRtoPCEscape( ccidDriver.sCcidCommand.wLength, ccidDriver.sCcidCommand.APDU);    
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command stops or restarts the clock.
//------------------------------------------------------------------------------
static void PCtoRDRICCClock( void )
{
    TRACE_DEBUG(".");

    if( 0 == ccidDriver.sCcidCommand.bSpecific_0 ) {
        // restarts the clock
        ISO7816_RestartClock();
    }
    else {
        // stop clock in the state shown in the bClockStop field
        ISO7816_StopClock();
    }

    RDRtoPCSlotStatus( );    
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command changes the parameters used to perform the transportation of 
/// APDU messages by the T=0 protocol. 
//------------------------------------------------------------------------------
static void PCtoRDRtoAPDU( void )
{
    unsigned char bmChanges;
    unsigned char bClassGetResponse;
    unsigned char bClassEnvelope;

    TRACE_INFO(".");

    if( configurationDescriptorsFS->ccid.dwFeatures == (CCID_FEATURES_EXC_SAPDU|CCID_FEATURES_EXC_APDU) ) {

        bmChanges = ccidDriver.sCcidCommand.bSpecific_0;
        bClassGetResponse = ccidDriver.sCcidCommand.bSpecific_1;
        bClassEnvelope = ccidDriver.sCcidCommand.bSpecific_2;

        ISO7816_toAPDU();
    }

    RDRtoPCSlotStatus();    
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This is a command message to allow entering the PIN for verification or
/// modification.
//------------------------------------------------------------------------------
static void PCtoRDRSecure( void )
{
    TRACE_DEBUG(".");

    TRACE_DEBUG("For user\n\r");
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command is used to manage motorized type CCID functionality. 
/// The Lock Card function is used to hold the ICC. 
/// This prevents an ICC from being easily removed from the CCID. 
/// The Unlock Card function is used to remove the hold initiated by the Lock 
/// Card function
//------------------------------------------------------------------------------
static void PCtoRDRMechanical( void )
{
    TRACE_DEBUG(".");
    TRACE_DEBUG("Not implemented\n\r");

    RDRtoPCSlotStatus();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command is used with the Control pipe Abort request to tell the CCID 
/// to stop any current transfer at the specified slot and return to a state 
/// where the slot is ready to accept a new command pipe Bulk-OUT message.
//------------------------------------------------------------------------------
static void PCtoRDRAbort( void )
{
    TRACE_DEBUG(".");

    RDRtoPCSlotStatus();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command is used to manually set the data rate and clock frequency of 
/// a specific slot.
//------------------------------------------------------------------------------
static void PCtoRDRSetDataRateAndClockFrequency( void )
{
    unsigned int dwClockFrequency;
    unsigned int dwDataRate;

    TRACE_DEBUG(".");

    dwClockFrequency = ccidDriver.sCcidCommand.APDU[0]
                     + (ccidDriver.sCcidCommand.APDU[1]<<8)
                     + (ccidDriver.sCcidCommand.APDU[2]<<16)
                     + (ccidDriver.sCcidCommand.APDU[3]<<24);

    dwDataRate = ccidDriver.sCcidCommand.APDU[4]
               + (ccidDriver.sCcidCommand.APDU[5]<<8)
               + (ccidDriver.sCcidCommand.APDU[6]<<16)
               + (ccidDriver.sCcidCommand.APDU[7]<<24);

    ISO7816_SetDataRateandClockFrequency( dwClockFrequency, dwDataRate );

    RDRtoPCDataRateAndClockFrequency( dwClockFrequency, dwDataRate );

}

//------------------------------------------------------------------------------
/// Report the CMD_NOT_SUPPORTED error to the host
//------------------------------------------------------------------------------
static void vCCIDCommandNotSupported( void )
{
    // Command not supported
    // vCCIDReportError(CMD_NOT_SUPPORTED);

    TRACE_DEBUG("CMD_NOT_SUPPORTED\n\r");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_SLOTSTATUS;
    ccidDriver.sCcidMessage.wLength      = 0;
    ccidDriver.sCcidMessage.bSpecific    = 0;

    ccidDriver.sCcidMessage.bStatus |= ICC_CS_FAILED;

    // Send the response to the host
    //vCCIDSendResponse();
}

//------------------------------------------------------------------------------
/// Sent CCID response on USB
//------------------------------------------------------------------------------
static void vCCIDSendResponse( void )
{
    unsigned char bStatus;
    TRACE_DEBUG(".");

    do {
        bStatus = CCID_Write((void*)&ccidDriver.sCcidMessage,
                              ccidDriver.sCcidMessage.bSizeToSend, 0, 0 );
    } while (bStatus != USBD_STATUS_SUCCESS);

    TRACE_DEBUG("bStatus: 0x%x\n\r", bStatus);
}


//------------------------------------------------------------------------------
///  Description: CCID Command dispatcher
//------------------------------------------------------------------------------
static void CCIDCommandDispatcher( void *pArg, uint8_t status, uint32_t transferred, uint32_t remaining )
{
    unsigned char MessageToSend = 0;

    if (status != USBD_STATUS_SUCCESS) {
        TRACE_ERROR("USB error: %d", status);
        return;
    }
    TRACE_DEBUG("Command: 0x%X 0x%x 0x%X 0x%X 0x%X 0x%X 0x%X\n\r\n\r",
                   (unsigned int)ccidDriver.sCcidCommand.bMessageType,
                   (unsigned int)ccidDriver.sCcidCommand.wLength,
                   (unsigned int)ccidDriver.sCcidCommand.bSlot,
                   (unsigned int)ccidDriver.sCcidCommand.bSeq,
                   (unsigned int)ccidDriver.sCcidCommand.bSpecific_0,
                   (unsigned int)ccidDriver.sCcidCommand.bSpecific_1,
                   (unsigned int)ccidDriver.sCcidCommand.bSpecific_2);

    // Check the slot number
    if ( ccidDriver.sCcidCommand.bSlot > 0 ) {

        TRACE_ERROR("BAD_SLOT_NUMBER\n\r");
    }

    TRACE_INFO("typ=0x%X\n\r", ccidDriver.sCcidCommand.bMessageType);

    ccidDriver.sCcidMessage.bStatus = 0;

    ccidDriver.sCcidMessage.bSeq  = ccidDriver.sCcidCommand.bSeq;
    ccidDriver.sCcidMessage.bSlot = ccidDriver.sCcidCommand.bSlot;

    ccidDriver.sCcidMessage.bSizeToSend = sizeof(S_ccid_bulk_in_header)-(ABDATA_SIZE+1);


    // Command dispatcher
    switch ( ccidDriver.sCcidCommand.bMessageType ) {

        case PC_TO_RDR_ICCPOWERON:
            PCtoRDRIccPowerOn();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_ICCPOWEROFF:
            PCtoRDRIccPowerOff();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_GETSLOTSTATUS:
            PCtoRDRGetSlotStatus();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_XFRBLOCK:
            PCtoRDRXfrBlock();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_GETPARAMETERS:
            PCtoRDRGetParameters();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_RESETPARAMETERS:
            PCtoRDRResetParameters();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_SETPARAMETERS:
            PCtoRDRSetParameters();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_ESCAPE:
            PCtoRDREscape();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_ICCCLOCK:
            PCtoRDRICCClock();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_T0APDU:
            // Only CCIDs reporting a short or extended APDU level in the dwFeatures 
            // field of the CCID class descriptor may take this command into account.
            if( (CCID_FEATURES_EXC_SAPDU == (CCID_FEATURES_EXC_SAPDU&configurationDescriptorsFS->ccid.dwFeatures))
            || (CCID_FEATURES_EXC_APDU  == (CCID_FEATURES_EXC_APDU &configurationDescriptorsFS->ccid.dwFeatures)) ) {

                // command supported
                PCtoRDRtoAPDU();
            }
            else {
                // command not supported
                TRACE_INFO("Not supported: PC_TO_RDR_T0APDU\n\r");
                vCCIDCommandNotSupported();
            }
            MessageToSend = 1;
            break;

        case PC_TO_RDR_SECURE:
            PCtoRDRSecure();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_MECHANICAL:
            PCtoRDRMechanical();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_ABORT:
            PCtoRDRAbort();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY:
            PCtoRDRSetDataRateAndClockFrequency();
            MessageToSend = 1;
            break;

        default:
            TRACE_DEBUG("default: Not supported: 0x%X\n\r", ccidDriver.sCcidCommand.bMessageType);
            vCCIDCommandNotSupported();
            MessageToSend = 1;
            break;

    }

    if( MessageToSend == 1 ) {
        vCCIDSendResponse();
    }
}


//------------------------------------------------------------------------------
/// SETUP request handler for a CCID device
/// \param pRequest Pointer to a USBGenericRequest instance
//------------------------------------------------------------------------------
static void CCID_RequestHandler(const USBGenericRequest *pRequest)
{
    TRACE_DEBUG("CCID_RHl\n\r");

    // Check if this is a class request
    if (USBGenericRequest_GetType(pRequest) == USBGenericRequest_CLASS) {

        // Check if the request is supported
        switch (USBGenericRequest_GetRequest(pRequest)) {

            case CCIDGenericRequest_ABORT:
                TRACE_DEBUG("CCIDGenericRequest_ABORT\n\r");
                break;

            case CCIDGenericRequest_GET_CLOCK_FREQUENCIES:
                TRACE_DEBUG("Not supported: CCIDGenericRequest_GET_CLOCK_FREQUENCIES\n\r");
                // A CCID with bNumClockSupported equal to 00h does not have 
                // to support this request
                break;

            case CCIDGenericRequest_GET_DATA_RATES:
                TRACE_DEBUG("Not supported: CCIDGenericRequest_GET_DATA_RATES\n\r");
                // A CCID with bNumDataRatesSupported equal to 00h does not have 
                // to support this request.
                break;

            default:
                TRACE_WARNING( "CCIDDriver_RequestHandler: Unsupported request (%d)\n\r",
                                                    USBGenericRequest_GetRequest(pRequest));
                USBD_Stall(0);
        }
    }

    else if (USBGenericRequest_GetType(pRequest) == USBGenericRequest_STANDARD) {

        // Forward request to the standard handler
        USBDDriver_RequestHandler(USBD_GetDriver(), pRequest);
    }
    else {

        // Unsupported request type
        TRACE_WARNING( "CCIDDriver_RequestHandler: Unsupported request type (%d)\n\r",
                                                    USBGenericRequest_GetType(pRequest));
        USBD_Stall(0);
    }
}


//------------------------------------------------------------------------------
//      Exported functions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
/// Optional callback re-implementation
//------------------------------------------------------------------------------
#if !defined(NOAUTOCALLBACK)
// not static function
void USBDCallbacks_RequestReceived(const USBGenericRequest *request)
{
    CCID_RequestHandler(request);
}
#endif


//------------------------------------------------------------------------------
/// Handles SmartCart request
//------------------------------------------------------------------------------
void CCID_SmartCardRequest( void )
{
    unsigned char bStatus;
    TRACE_DEBUG("CCID_req\n");

    do {

        bStatus = CCID_Read( (void*)&ccidDriver.sCcidCommand,
                             sizeof(S_ccid_bulk_out_header),
                             (TransferCallback)&CCIDCommandDispatcher,
                             (void*)0 );
    }
    while (0);
}


//------------------------------------------------------------------------------
/// Reads data from the Data OUT endpoint
/// \param pBuffer   Buffer to store the received data
/// \param dLength   data buffer length
/// \param fCallback Optional callback function
/// \param pArgument Optional parameter for the callback function
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char CCID_Read(void *pBuffer,
                        unsigned int dLength,
                        TransferCallback fCallback,
                        void *pArgument)
{
    return USBD_Read(CCID_EPT_DATA_OUT, pBuffer, dLength, fCallback, pArgument);
}

//------------------------------------------------------------------------------
/// Sends data through the Data IN endpoint
/// \param pBuffer   Buffer holding the data to transmit
/// \param dLength   Length of data buffer
/// \param fCallback Optional callback function
/// \param pArgument Optional parameter for the callback function
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char CCID_Write(void *pBuffer,
                         unsigned int dLength,
                         TransferCallback fCallback,
                         void *pArgument)
{
    return USBD_Write(CCID_EPT_DATA_IN, pBuffer, dLength, fCallback, pArgument);
}

//------------------------------------------------------------------------------
/// Sends data through the interrupt endpoint, ICC insertion event
/// RDR_to_PC_NotifySlotChange
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char CCID_Insertion( void )
{
    TRACE_DEBUG(".");

    // Build the Interrupt-IN message
    ccidDriver.BufferINT[0] = RDR_TO_PC_NOTIFYSLOTCHANGE;
    ccidDriver.BufferINT[1] = ICC_INSERTED_EVENT;
    ccidDriver.SlotStatus   = ICC_INSERTED_EVENT;

    // Notify the host that a ICC is inserted
    return USBD_Write( CCID_EPT_NOTIFICATION, ccidDriver.BufferINT, 2, 0, 0 );
}

//------------------------------------------------------------------------------
/// Sends data through the interrupt endpoint, ICC removal event
/// RDR_to_PC_NotifySlotChange
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char CCID_Removal( void )
{
    TRACE_DEBUG(".");

    // Build the Interrupt-IN message
    ccidDriver.BufferINT[0] = RDR_TO_PC_NOTIFYSLOTCHANGE;
    ccidDriver.BufferINT[1] = ICC_NOT_PRESENT;
    ccidDriver.SlotStatus   = ICC_NOT_PRESENT;

    // Notify the host that a ICC is inserted
    return USBD_Write( CCID_EPT_NOTIFICATION, ccidDriver.BufferINT, 2, 0, 0 );
}

//------------------------------------------------------------------------------
/// Interrupt-IN Messages
/// This message is sent when any bit in the bHardwareErrorCode field is set. 
/// If this message is sent when there is no “outstanding” command, the bSeq 
/// field will be undefined.
/// \param bSlot ICC slot number
/// \param bSeq  Sequence number of the bulk OUT command when the hardware error
/// occured
/// \param bHardwareErrorCode Hardware error code
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char RDRtoPCHardwareError( unsigned char bSlot, 
                                    unsigned char bSeq, 
                                    unsigned char bHardwareErrorCode )
{
    TRACE_DEBUG(".");

    // Build the Interrupt-IN message
    ccidDriver.BufferINT[0] = RDR_TO_PC_HARDWAREERROR;
    ccidDriver.BufferINT[1] = bSlot;
    ccidDriver.BufferINT[2] = bSeq;
    ccidDriver.BufferINT[3] = bHardwareErrorCode;

    // Notify the host that a ICC is inserted
    return USBD_Write( CCID_EPT_NOTIFICATION, ccidDriver.BufferINT, 4, 0, 0 );
}

#endif /* HAVE_CCID */