Review fixes
[pub/USBasp.git] / Demos / Device / LowLevel / CCID / CCID.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2018.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2018 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11 Copyright 2018 Filipe Rodrigues (filipepazrodrigues [at] gmail [dot] com)
12
13 Permission to use, copy, modify, distribute, and sell this
14 software and its documentation for any purpose is hereby granted
15 without fee, provided that the above copyright notice appear in
16 all copies and that both that the copyright notice and this
17 permission notice and warranty disclaimer appear in supporting
18 documentation, and that the name of the author not be used in
19 advertising or publicity pertaining to distribution of the
20 software without specific, written prior permission.
21
22 The author disclaims all warranties with regard to this
23 software, including all implied warranties of merchantability
24 and fitness. In no event shall the author be liable for any
25 special, indirect or consequential damages or any damages
26 whatsoever resulting from loss of use, data or profits, whether
27 in an action of contract, negligence or other tortious action,
28 arising out of or in connection with the use or performance of
29 this software.
30 */
31
32 /** \file
33 *
34 * Main source file for the CCID demo. This file contains the main tasks of the demo and
35 * is responsible for the initial application hardware configuration.
36 *
37 * \warning
38 * LUFA is not a secure USB stack, and has not undergone, not is it expected to pass, any
39 * form of security audit. The CCID class here is presented as-is and is intended for
40 * research purposes only, and *should not* be used in a security critical application
41 * under any circumstances.
42 *
43 * \warning
44 * This code is not production ready and should not by any means be considered safe.
45 * If you plan to integrate it into your application, you should seriously consider strong
46 * encryption algorithms or a secure microprocessor. Since Atmel AVR microprocessors do not
47 * have any security requirement (therefore they don't offer any known protection against
48 * side channel attacks or fault injection) a secure microprocessor is the best option.
49 */
50
51 #include "CCID.h"
52
53 static bool Aborted;
54 static uint8_t AbortedSeq;
55
56
57 /** Main program entry point. This routine configures the hardware required by the application, then
58 * enters a loop to run the application tasks in sequence.
59 */
60 int main(void)
61 {
62 SetupHardware();
63
64 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
65 GlobalInterruptEnable();
66
67 for (;;)
68 {
69 USB_USBTask();
70 CCID_Task();
71 }
72 }
73
74 /** Configures the board hardware and chip peripherals for the demo's functionality. */
75 void SetupHardware(void)
76 {
77 #if (ARCH == ARCH_AVR8)
78 /* Disable watchdog if enabled by bootloader/fuses */
79 MCUSR &= ~(1 << WDRF);
80 wdt_disable();
81
82 /* Disable clock division */
83 clock_prescale_set(clock_div_1);
84 #elif (ARCH == ARCH_XMEGA)
85 /* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
86 XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
87 XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);
88
89 /* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
90 XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
91 XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);
92
93 PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
94 #endif
95
96 /* Hardware Initialization */
97 LEDs_Init();
98 USB_Init();
99 }
100
101 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
102 void EVENT_USB_Device_Connect(void)
103 {
104 /* Indicate USB enumerating */
105 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
106 }
107
108 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
109 * the status LEDs.
110 */
111 void EVENT_USB_Device_Disconnect(void)
112 {
113 /* Indicate USB not ready */
114 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
115 }
116
117 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
118 * of the USB device after enumeration - the device endpoints are configured.
119 */
120 void EVENT_USB_Device_ConfigurationChanged(void)
121 {
122 bool ConfigSuccess = true;
123
124 /* Setup CCID Data Endpoints */
125 ConfigSuccess &= Endpoint_ConfigureEndpoint(CCID_IN_EPADDR, EP_TYPE_BULK, CCID_EPSIZE, 1);
126 ConfigSuccess &= Endpoint_ConfigureEndpoint(CCID_OUT_EPADDR, EP_TYPE_BULK, CCID_EPSIZE, 1);
127
128 /* Indicate endpoint configuration success or failure */
129 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
130 }
131
132 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
133 * the device from the USB host before passing along unhandled control requests to the library for processing
134 * internally.
135 */
136 void EVENT_USB_Device_ControlRequest(void)
137 {
138 switch (USB_ControlRequest.bRequest)
139 {
140 case CCID_ABORT:
141 {
142 // Initiates the abort process
143 // The host should send 2 messages in the following order:
144 // - CCID_ABORT control request
145 // - CCID_PC_t_PCo_RDR_Abort command
146 //
147 // If the device is still processing a message, it should fail it until receiving a CCIRPC_to_RDR_Abort
148 // command.
149 //
150 // When the device receives the CCIRPC_to_RDR_Abort message, it replies with RDR_to_PC_SlotStatus
151 // and the abort process ends
152
153 // The wValue field contains the slot number (bSlot) in the low byte and the sequence number (bSeq) in
154 // the high byte
155 uint8_t Slot = USB_ControlRequest.wValue & 0xFF;
156 uint8_t Seq = USB_ControlRequest.wValue >> 8;
157
158 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE) && Slot == 0)
159 {
160 Endpoint_ClearSETUP();
161
162 Aborted = true;
163 AbortedSeq = Seq;
164
165 Endpoint_ClearOUT();
166 }
167
168 break;
169 }
170 case CCID_GET_CLOCK_FREQUENCIES:
171 {
172 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
173 {
174 Endpoint_ClearSETUP();
175 Endpoint_Write_8(0); // Not supported
176 Endpoint_ClearOUT();
177 }
178
179 break;
180 }
181 case CCID_GET_DATA_RATES:
182 {
183 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
184 {
185 Endpoint_ClearSETUP();
186 Endpoint_Write_8(0); // Not supported
187 Endpoint_ClearOUT();
188 }
189
190 break;
191 }
192 }
193 }
194
195 /** Event handler for the CCID_PC_to_RDR_IccPowerOn message. This message is sent to the device
196 * whenever an application at the host wants to send a power off signal to a slot.
197 * THe slot must reply back with a recognizable ATR (answer to reset)
198 */
199 uint8_t CCID_IccPowerOn(uint8_t slot,
200 uint8_t* atr,
201 uint8_t* atrLength,
202 uint8_t* error)
203 {
204 if (slot == 0)
205 {
206 Iso7816_CreateSimpleAtr(atr, atrLength);
207
208 *error = CCID_ERROR_NO_ERROR;
209 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_PRESENTANDACTIVE;
210 }
211 else
212 {
213 *error = CCID_ERROR_SLOT_NOT_FOUND;
214 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
215 }
216 }
217
218 /** Event handler for the CCID_PC_to_RDR_IccPowerOff message. This message is sent to the device
219 * whenever an application at the host wants to send a power off signal to a slot.
220 */
221 uint8_t CCID_IccPowerOff(uint8_t slot,
222 uint8_t* error)
223 {
224 if (slot == 0)
225 {
226 *error = CCID_ERROR_NO_ERROR;
227 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_NOICCPRESENT;
228 }
229 else
230 {
231 *error = CCID_ERROR_SLOT_NOT_FOUND;
232 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
233 }
234 }
235
236 /** Event handler for the CCID_PC_to_RDR_GetSlotStatus. THis message is sent to
237 * the device whenever an application at the host wants to the get the current
238 * slot status.
239 */
240 uint8_t CCID_GetSlotStatus(uint8_t slot,
241 uint8_t* error)
242 {
243 if (slot == 0)
244 {
245 *error = CCID_ERROR_NO_ERROR;
246 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_PRESENTANDACTIVE;
247 }
248 else
249 {
250 *error = CCID_ERROR_SLOT_NOT_FOUND;
251 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
252 }
253 }
254
255 /** Event handler for the CCID_PC_to_RDR_ABort message. This message is sent to the device
256 * whenever an application wants to abort the current operation. A previous CCID_ABORT
257 * control message has to be sent before this one in order to start the abort operation.
258 */
259 uint8_t CCID_Abort(uint8_t slot,
260 uint8_t seq,
261 uint8_t* error)
262 {
263 if (Aborted && slot == 0 && AbortedSeq == seq)
264 {
265 Aborted = false;
266 AbortedSeq = -1;
267 *error = CCID_ERROR_NO_ERROR;
268 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_PRESENTANDACTIVE;
269 }
270 else if (!Aborted)
271 {
272 *error = CCID_ERROR_CMD_NOT_ABORTED;
273 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_PRESENTANDACTIVE;
274 }
275 else if (slot != 0)
276 {
277 *error = CCID_ERROR_SLOT_NOT_FOUND;
278 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
279 }
280
281 *error = CCID_ERROR_NOT_SUPPORTED;
282 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
283 }
284
285 /** Gets and status and verifies whether an error occurred. */
286 bool CCID_CheckStatusNoError(int status)
287 {
288 return (status & 0xC0) == 0x0;
289 }
290
291 /** Function to manage CCID request parsing and responses back to the host. */
292 void CCID_Task(void)
293 {
294 Endpoint_SelectEndpoint(CCID_OUT_EPADDR);
295
296 uint8_t BlockBuffer[0x20];
297 Aborted = false;
298 AbortedSeq = -1;
299
300 if (Endpoint_IsOUTReceived())
301 {
302 USB_CCID_BulkMessage_Header_t CCIDHeader;
303 CCIDHeader.MessageType = Endpoint_Read_8();
304 CCIDHeader.Length = Endpoint_Read_32_LE();
305 CCIDHeader.Slot = Endpoint_Read_8();
306 CCIDHeader.Seq = Endpoint_Read_8();
307
308 uint8_t Status;
309 uint8_t Error = CCID_ERROR_NO_ERROR;
310
311 switch (CCIDHeader.MessageType)
312 {
313 case CCID_PC_to_RDR_IccPowerOn:
314 {
315 uint8_t AtrLength;
316 USB_CCID_RDR_to_PC_DataBlock_t* ResponseATR = (USB_CCID_RDR_to_PC_DataBlock_t*)&BlockBuffer;
317
318 ResponseATR->CCIDHeader.MessageType = CCID_RDR_to_PC_DataBlock;
319 ResponseATR->CCIDHeader.Slot = CCIDHeader.Slot;
320 ResponseATR->CCIDHeader.Seq = CCIDHeader.Seq;
321 ResponseATR->ChainParam = 0;
322
323 Status = CCID_IccPowerOn(ResponseATR->CCIDHeader.Slot, (uint8_t* )ResponseATR->Data, &AtrLength, &Error);
324
325 if (CCID_CheckStatusNoError(Status) && !Aborted)
326 {
327 ResponseATR->CCIDHeader.Length = AtrLength;
328 }
329 else if (Aborted)
330 {
331 Status = CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_PRESENTANDACTIVE;
332 Error = CCID_ERROR_CMD_ABORTED;
333 AtrLength = 0;
334 }
335 else
336 {
337 AtrLength = 0;
338 }
339
340 ResponseATR->Status = Status;
341 ResponseATR->Error = Error;
342
343 Endpoint_ClearOUT();
344
345 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
346 Endpoint_Write_Stream_LE(ResponseATR, sizeof(USB_CCID_RDR_to_PC_DataBlock_t) + AtrLength, NULL);
347 Endpoint_ClearIN();
348 break;
349 }
350
351 case CCID_PC_to_RDR_IccPowerOff:
352 {
353 USB_CCID_RDR_to_PC_SlotStatus_t* ResponsePowerOff = (USB_CCID_RDR_to_PC_SlotStatus_t*)&BlockBuffer;
354 ResponsePowerOff->CCIDHeader.MessageType = CCID_RDR_to_PC_SlotStatus;
355 ResponsePowerOff->CCIDHeader.Length = 0;
356 ResponsePowerOff->CCIDHeader.Slot = CCIDHeader.Slot;
357 ResponsePowerOff->CCIDHeader.Seq = CCIDHeader.Seq;
358
359 ResponsePowerOff->ClockStatus = 0;
360
361 Status = CCID_IccPowerOff(CCIDHeader.Slot, &Error);
362
363 ResponsePowerOff->Status = Status;
364 ResponsePowerOff->Error = Error;
365
366 Endpoint_ClearOUT();
367
368 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
369 Endpoint_Write_Stream_LE(ResponsePowerOff, sizeof(USB_CCID_RDR_to_PC_SlotStatus_t), NULL);
370 Endpoint_ClearIN();
371 break;
372 }
373
374 case CCID_PC_to_RDR_GetSlotStatus:
375 {
376 USB_CCID_RDR_to_PC_SlotStatus_t* ResponseSlotStatus = (USB_CCID_RDR_to_PC_SlotStatus_t*)&BlockBuffer;
377 ResponseSlotStatus->CCIDHeader.MessageType = CCID_RDR_to_PC_SlotStatus;
378 ResponseSlotStatus->CCIDHeader.Length = 0;
379 ResponseSlotStatus->CCIDHeader.Slot = CCIDHeader.Slot;
380 ResponseSlotStatus->CCIDHeader.Seq = CCIDHeader.Seq;
381
382 ResponseSlotStatus->ClockStatus = 0;
383
384 Status = CCID_GetSlotStatus(CCIDHeader.Slot, &Error);
385
386 ResponseSlotStatus->Status = Status;
387 ResponseSlotStatus->Error = Error;
388
389 Endpoint_ClearOUT();
390
391 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
392 Endpoint_Write_Stream_LE(ResponseSlotStatus, sizeof(USB_CCID_RDR_to_PC_SlotStatus_t), NULL);
393 Endpoint_ClearIN();
394 break;
395 }
396
397 case CCID_PC_to_RDR_Abort:
398 {
399 USB_CCID_RDR_to_PC_SlotStatus_t* ResponseAbort = (USB_CCID_RDR_to_PC_SlotStatus_t*)&BlockBuffer;
400 ResponseAbort->CCIDHeader.MessageType = CCID_RDR_to_PC_SlotStatus;
401 ResponseAbort->CCIDHeader.Length = 0;
402 ResponseAbort->CCIDHeader.Slot = CCIDHeader.Slot;
403 ResponseAbort->CCIDHeader.Seq = CCIDHeader.Seq;
404
405 ResponseAbort->ClockStatus = 0;
406
407 Status = CCID_Abort(CCIDHeader.Slot, CCIDHeader.Seq, &Error);
408
409 ResponseAbort->Status = Status;
410 ResponseAbort->Error = Error;
411
412 Endpoint_ClearOUT();
413
414 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
415 Endpoint_Write_Stream_LE(ResponseAbort, sizeof(USB_CCID_RDR_to_PC_SlotStatus_t), NULL);
416 Endpoint_ClearIN();
417 break;
418 }
419 default:
420 {
421 memset(BlockBuffer, 0x00, sizeof(BlockBuffer));
422
423 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
424 Endpoint_Write_Stream_LE(BlockBuffer, sizeof(BlockBuffer), NULL);
425 Endpoint_ClearIN();
426 }
427 }
428 }
429 }