1/*
2    commands.c: Commands sent to the card
3    Copyright (C) 2003-2004   Ludovic Rousseau
4
5    This library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9
10    This library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15	You should have received a copy of the GNU Lesser General Public License
16	along with this library; if not, write to the Free Software Foundation,
17	Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18*/
19
20/*
21 * $Id: commands.c 4235 2009-05-29 11:42:46Z rousseau $
22 */
23
24#include <string.h>
25#include <stdlib.h>
26#include <errno.h>
27#include <pcsclite.h>
28#include <ifdhandler.h>
29#include <reader.h>
30
31#include "misc.h"
32#include "commands.h"
33#include "openct/proto-t1.h"
34#include "ccid.h"
35#include "defs.h"
36#include "ccid_ifdhandler.h"
37#include "config.h"
38#include "debug.h"
39#include "ccid_usb.h"
40
41/* All the pinpad readers I used are more or less bogus
42 * I use code to change the user command and make the firmware happy */
43#define BOGUS_PINPAD_FIRMWARE
44
45/* The firmware of SCM readers reports dwMaxCCIDMessageLength = 263
46 * instead of 270 so this prevents from sending a full length APDU
47 * of 260 bytes since the driver check this value */
48#define BOGUS_SCM_FIRMWARE_FOR_dwMaxCCIDMessageLength
49
50#define max( a, b )   ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
51#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
52#define IFD_ERROR_INSUFFICIENT_BUFFER 700
53
54/* internal functions */
55static RESPONSECODE CmdXfrBlockAPDU_extended(unsigned int reader_index,
56	unsigned int tx_length, unsigned char tx_buffer[], unsigned int *rx_length,
57	unsigned char rx_buffer[]);
58
59static RESPONSECODE CmdXfrBlockTPDU_T0(unsigned int reader_index,
60	unsigned int tx_length, unsigned char tx_buffer[], unsigned int *rx_length,
61	unsigned char rx_buffer[]);
62
63static RESPONSECODE CmdXfrBlockCHAR_T0(unsigned int reader_index, unsigned int
64	tx_length, unsigned char tx_buffer[], unsigned int *rx_length, unsigned
65	char rx_buffer[]);
66
67static RESPONSECODE CmdXfrBlockTPDU_T1(unsigned int reader_index,
68	unsigned int tx_length, unsigned char tx_buffer[], unsigned int *rx_length,
69	unsigned char rx_buffer[]);
70
71static void i2dw(int value, unsigned char *buffer);
72
73
74/*****************************************************************************
75 *
76 *					CmdPowerOn
77 *
78 ****************************************************************************/
79RESPONSECODE CmdPowerOn(unsigned int reader_index, unsigned int * nlength,
80	unsigned char buffer[], int voltage)
81{
82	unsigned char cmd[10];
83	status_t res;
84	int length, count = 1;
85	unsigned int atr_len;
86	RESPONSECODE return_value = IFD_SUCCESS;
87	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
88
89#ifndef TWIN_SERIAL
90	if (ICCD_A == ccid_descriptor->bInterfaceProtocol)
91	{
92		int r;
93		unsigned char pcbuffer[SIZE_GET_SLOT_STATUS];
94
95		/* first power off to reset the ICC state machine */
96		r = CmdPowerOff(reader_index);
97		if (r != IFD_SUCCESS)
98			return r;
99
100		/* wait for ready */
101		r = CmdGetSlotStatus(reader_index, pcbuffer);
102		if (r != IFD_SUCCESS)
103			return r;
104
105		/* Power On */
106		r = ControlUSB(reader_index, 0xA1, 0x62, 0, buffer, *nlength);
107
108		/* we got an error? */
109		if (r < 0)
110		{
111			DEBUG_INFO2("ICC Power On failed: %s", strerror(errno));
112			return IFD_COMMUNICATION_ERROR;
113		}
114
115		*nlength = r;
116
117		return IFD_SUCCESS;
118	}
119
120	if (ICCD_B == ccid_descriptor->bInterfaceProtocol)
121	{
122		int r;
123		unsigned char tmp[MAX_ATR_SIZE+1];
124
125		/* first power off to reset the ICC state machine */
126		r = CmdPowerOff(reader_index);
127		if (r != IFD_SUCCESS)
128			return r;
129
130		/* Power On */
131		r = ControlUSB(reader_index, 0x21, 0x62, 1, NULL, 0);
132
133		/* we got an error? */
134		if (r < 0)
135		{
136			DEBUG_INFO2("ICC Power On failed: %s", strerror(errno));
137			return IFD_COMMUNICATION_ERROR;
138		}
139
140		/* Data Block */
141		r = ControlUSB(reader_index, 0xA1, 0x6F, 0, tmp, sizeof(tmp));
142
143		/* we got an error? */
144		if (r < 0)
145		{
146			DEBUG_INFO2("ICC Data Block failed: %s", strerror(errno));
147			return IFD_COMMUNICATION_ERROR;
148		}
149
150		if (tmp[0] != 0x00)
151		{
152			DEBUG_CRITICAL2("bResponseType: 0x%02X", tmp[0]);
153
154			/* Status Information? */
155			if (0x40 == tmp[0])
156				ccid_error(tmp[2], __FILE__, __LINE__, __FUNCTION__);
157			return IFD_COMMUNICATION_ERROR;
158		}
159
160		DEBUG_INFO_XXD("Data Block: ", tmp, r);
161		if (*nlength > r-1)
162			*nlength = r-1;
163		memcpy(buffer, tmp+1, *nlength);
164
165		return IFD_SUCCESS;
166	}
167#endif
168
169	/* store length of buffer[] */
170	length = *nlength;
171
172	if (ccid_descriptor->dwFeatures & CCID_CLASS_AUTO_VOLTAGE)
173		voltage = 0;	/* automatic voltage selection */
174	else
175	{
176		int bVoltageSupport = ccid_descriptor->bVoltageSupport;
177
178		if ((1 == voltage) && !(bVoltageSupport & 1))
179		{
180			DEBUG_INFO("5V requested but not support by reader");
181			voltage = 2;	/* 3V */
182		}
183
184		if ((2 == voltage) && !(bVoltageSupport & 2))
185		{
186			DEBUG_INFO("3V requested but not support by reader");
187			voltage = 3;	/* 1.8V */
188		}
189
190		if ((3 == voltage) && !(bVoltageSupport & 4))
191		{
192			DEBUG_INFO("1.8V requested but not support by reader");
193			voltage = 0;	/* auto */
194		}
195	}
196
197again:
198	cmd[0] = 0x62; /* IccPowerOn */
199	cmd[1] = cmd[2] = cmd[3] = cmd[4] = 0;	/* dwLength */
200	cmd[5] = ccid_descriptor->bCurrentSlotIndex;	/* slot number */
201	cmd[6] = (*ccid_descriptor->pbSeq)++;
202	cmd[7] = voltage;
203	cmd[8] = cmd[9] = 0; /* RFU */
204
205	res = WritePort(reader_index, sizeof(cmd), cmd);
206	if (res != STATUS_SUCCESS)
207		return IFD_COMMUNICATION_ERROR;
208
209	/* reset available buffer size */
210	/* needed if we go back after a switch to ISO mode */
211	*nlength = length;
212
213	res = ReadPort(reader_index, nlength, buffer);
214	if (res != STATUS_SUCCESS)
215		return IFD_COMMUNICATION_ERROR;
216
217	if (*nlength < STATUS_OFFSET+1)
218	{
219		DEBUG_CRITICAL2("Not enough data received: %d bytes", *nlength);
220		return IFD_COMMUNICATION_ERROR;
221	}
222
223	if (buffer[STATUS_OFFSET] & CCID_COMMAND_FAILED)
224	{
225		ccid_error(buffer[ERROR_OFFSET], __FILE__, __LINE__, __FUNCTION__);    /* bError */
226
227		if (0xBB == buffer[ERROR_OFFSET] &&	/* Protocol error in EMV mode */
228			((GEMPC433 == ccid_descriptor->readerID)
229			|| (CHERRYXX33 == ccid_descriptor->readerID)))
230		{
231			unsigned char cmd_tmp[] = {0x1F, 0x01};
232			unsigned char res_tmp[1];
233			unsigned int res_length = sizeof(res_tmp);
234
235			if ((return_value = CmdEscape(reader_index, cmd_tmp,
236				sizeof(cmd_tmp), res_tmp, &res_length)) != IFD_SUCCESS)
237				return return_value;
238
239			/* avoid looping if we can't switch mode */
240			if (count--)
241				goto again;
242			else
243				DEBUG_CRITICAL("Can't set reader in ISO mode");
244		}
245
246		/* continue with 3 volts and 5 volts */
247		if (voltage > 1)
248		{
249			const char *voltage_code[] = { "auto", "5V", "3V", "1.8V" };
250
251			DEBUG_INFO3("Power up with %s failed. Try with %s.",
252				voltage_code[voltage], voltage_code[voltage-1]);
253			voltage--;
254			goto again;
255		}
256
257		return IFD_COMMUNICATION_ERROR;
258	}
259
260	/* extract the ATR */
261	atr_len = dw2i(buffer, 1);	/* ATR length */
262	if (atr_len > *nlength)
263		atr_len = *nlength;
264	else
265		*nlength = atr_len;
266
267	memmove(buffer, buffer+10, atr_len);
268
269	return return_value;
270} /* CmdPowerOn */
271
272
273/*****************************************************************************
274 *
275 *					SecurePINVerify
276 *
277 ****************************************************************************/
278RESPONSECODE SecurePINVerify(unsigned int reader_index,
279	unsigned char TxBuffer[], unsigned int TxLength,
280	unsigned char RxBuffer[], unsigned int *RxLength)
281{
282	unsigned char cmd[11+14+CMD_BUF_SIZE];
283	unsigned int a, b;
284	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
285	int old_read_timeout;
286	RESPONSECODE ret;
287
288	cmd[0] = 0x69;	/* Secure */
289	cmd[5] = ccid_descriptor->bCurrentSlotIndex;	/* slot number */
290	cmd[6] = (*ccid_descriptor->pbSeq)++;
291	cmd[7] = 0;		/* bBWI */
292	cmd[8] = 0;		/* wLevelParameter */
293	cmd[9] = 0;
294	cmd[10] = 0;	/* bPINOperation: PIN Verification */
295
296	/* 19 is the size of the PCSCv2 PIN verify structure
297	 * The equivalent CCID structure is only 14-bytes long */
298	if (TxLength > 19+CMD_BUF_SIZE) /* command too large? */
299	{
300		DEBUG_INFO3("Command too long: %d > %d", TxLength, 19+CMD_BUF_SIZE);
301		return IFD_NOT_SUPPORTED;
302	}
303
304	if (TxLength < 19+4 /* 4 = APDU size */)	/* command too short? */
305	{
306		DEBUG_INFO3("Command too short: %d < %d", TxLength, 19+4);
307		return IFD_NOT_SUPPORTED;
308	}
309
310	if (dw2i(TxBuffer, 15) + 19 != TxLength) /* ulDataLength field coherency */
311	{
312		DEBUG_INFO3("Wrong lengths: %d %d", dw2i(TxBuffer, 15) + 19, TxLength);
313		return IFD_NOT_SUPPORTED;
314	}
315
316	/* make sure bEntryValidationCondition is valid
317	 * The Cherry XX44 reader crashes with a wrong value */
318	if ((0x00 == TxBuffer[7]) || (TxBuffer[7] > 0x07))
319	{
320		DEBUG_INFO2("Correct bEntryValidationCondition (was 0x%02X)",
321			TxBuffer[7]);
322		TxBuffer[7] = 0x02;
323	}
324
325#ifdef BOGUS_PINPAD_FIRMWARE
326	/* bug circumvention for the GemPC Pinpad */
327	if (GEMPCPINPAD == ccid_descriptor->readerID)
328	{
329		/* the firmware reject the cases: 00h No string and FFh default
330		 * CCID message. The only value supported is 01h (display 1 message) */
331		if (0x01 != TxBuffer[8])
332		{
333			DEBUG_INFO2("Correct bNumberMessage for GemPC Pinpad (was %d)",
334				TxBuffer[8]);
335			TxBuffer[8] = 0x01;
336		}
337
338		/* The reader does not support, and actively reject, "max size reached"
339		 * and "timeout occured" validation conditions */
340		if (0x02 != TxBuffer[7])
341		{
342			DEBUG_INFO2("Correct bEntryValidationCondition for GemPC Pinpad (was %d)",
343				TxBuffer[7]);
344			TxBuffer[7] = 0x02;	/* validation key pressed */
345		}
346
347	}
348
349	if (DELLSCRK == ccid_descriptor->readerID)
350	{
351		/* the firmware rejects the cases: 01h-FEh and FFh default
352		 * CCID message. The only value supported is 00h (no message) */
353		if (0x00 != TxBuffer[8])
354		{
355			DEBUG_INFO2("Correct bNumberMessage for Dell keyboard (was %d)",
356				TxBuffer[8]);
357			TxBuffer[8] = 0x00;
358		}
359	}
360#endif
361
362	/* T=1 Protocol Management for a TPDU reader */
363	if ((SCARD_PROTOCOL_T1 == ccid_descriptor->cardProtocol)
364		&& (CCID_CLASS_TPDU == (ccid_descriptor->dwFeatures & CCID_CLASS_EXCHANGE_MASK)))
365	{
366		ct_buf_t sbuf;
367		unsigned char sdata[T1_BUFFER_SIZE];
368
369		/* Initialize send buffer with the APDU */
370		ct_buf_set(&sbuf,
371			(void *)(TxBuffer + offsetof(PIN_VERIFY_STRUCTURE, abData)),
372			TxLength - offsetof(PIN_VERIFY_STRUCTURE, abData));
373
374		/* Create T=1 block */
375		ret = t1_build(&((get_ccid_slot(reader_index))->t1),
376			sdata, 0, T1_I_BLOCK, &sbuf, NULL);
377
378		/* Increment the sequence numbers  */
379		get_ccid_slot(reader_index)->t1.ns ^= 1;
380		get_ccid_slot(reader_index)->t1.nr ^= 1;
381
382		/* Copy the generated T=1 block prologue into the teoprologue
383		 * of the CCID command */
384		memcpy(TxBuffer + offsetof(PIN_VERIFY_STRUCTURE, bTeoPrologue),
385			sdata, 3);
386	}
387
388	/* Build a CCID block from a PC/SC V2.02.05 Part 10 block */
389	for (a = 11, b = 0; b < TxLength; b++)
390	{
391		if (1 == b) /* bTimeOut2 field */
392			/* Ignore the second timeout as there's nothing we can do with
393			 * it currently */
394			continue;
395
396		if ((b >= 15) && (b <= 18)) /* ulDataLength field (4 bytes) */
397			/* the ulDataLength field is not present in the CCID frame
398			 * so do not copy */
399			continue;
400
401		/* copy the CCID block 'verbatim' */
402		cmd[a] = TxBuffer[b];
403		a++;
404	}
405
406	/* SPR532 and Case 1 APDU */
407	if ((SPR532 == ccid_descriptor->readerID)
408		/* bmPINBlockString = 0 => PIN length not inserted in APDU */
409		&& (0 == TxBuffer[3])
410		/* case 1 APDU */
411		&& (4 == TxBuffer[15]))
412	{
413		RESPONSECODE return_value;
414		unsigned char cmd_tmp[] = { 0x80, 0x02, 0x00 };
415		unsigned char res_tmp[1];
416		unsigned int res_length = sizeof(res_tmp);
417
418		/* the SPR532 will append the PIN code without any padding */
419		return_value = CmdEscape(reader_index, cmd_tmp, sizeof(cmd_tmp),
420			res_tmp, &res_length);
421		if (return_value != IFD_SUCCESS)
422			return return_value;
423
424		/* we need to set bSeq again to avoid a "Duplicate frame detected"
425		 * error since the bSeq of CmdEscape is now greater than bSeq set at
426		 * the beginning of this function */
427		cmd[6] = (*ccid_descriptor->pbSeq)++;
428	}
429
430	i2dw(a - 10, cmd + 1);  /* CCID message length */
431
432	old_read_timeout = ccid_descriptor -> readTimeout;
433	ccid_descriptor -> readTimeout = max(30, TxBuffer[0]+10);	/* at least 30 seconds */
434
435	if (WritePort(reader_index, a, cmd) != STATUS_SUCCESS)
436	{
437		ret = IFD_COMMUNICATION_ERROR;
438		goto end;
439	}
440
441	ret = CCID_Receive(reader_index, RxLength, RxBuffer, NULL);
442
443	/* T=1 Protocol Management for a TPDU reader */
444	if ((IFD_SUCCESS == ret)
445		&& (SCARD_PROTOCOL_T1 == ccid_descriptor->cardProtocol)
446		&& (CCID_CLASS_TPDU == (ccid_descriptor->dwFeatures & CCID_CLASS_EXCHANGE_MASK)))
447	{
448		/* timeout and cancel cases are faked by CCID_Receive() */
449		if (2 == *RxLength)
450		{
451			/* Decrement the sequence numbers since no TPDU was sent */
452			get_ccid_slot(reader_index)->t1.ns ^= 1;
453			get_ccid_slot(reader_index)->t1.nr ^= 1;
454		}
455		else
456		{
457			/* get only the T=1 data */
458			/* FIXME: manage T=1 error blocks */
459			memmove(RxBuffer, RxBuffer+3, *RxLength -4);
460			*RxLength -= 4;	/* remove NAD, PCB, LEN and CRC */
461		}
462	}
463
464end:
465	ccid_descriptor -> readTimeout = old_read_timeout;
466	return ret;
467} /* SecurePINVerify */
468
469
470/*****************************************************************************
471 *
472 *					SecurePINModify
473 *
474 ****************************************************************************/
475RESPONSECODE SecurePINModify(unsigned int reader_index,
476	unsigned char TxBuffer[], unsigned int TxLength,
477	unsigned char RxBuffer[], unsigned int *RxLength)
478{
479	unsigned char cmd[11+19+CMD_BUF_SIZE];
480	unsigned int a, b;
481	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
482	int old_read_timeout;
483	RESPONSECODE ret;
484#ifdef BOGUS_PINPAD_FIRMWARE
485	int bNumberMessages = 0; /* for GemPC Pinpad */
486#endif
487
488	cmd[0] = 0x69;	/* Secure */
489	cmd[5] = ccid_descriptor->bCurrentSlotIndex;	/* slot number */
490	cmd[6] = (*ccid_descriptor->pbSeq)++;
491	cmd[7] = 0;		/* bBWI */
492	cmd[8] = 0;		/* wLevelParameter */
493	cmd[9] = 0;
494	cmd[10] = 1;	/* bPINOperation: PIN Modification */
495
496	/* 24 is the size of the PCSC PIN modify structure
497	 * The equivalent CCID structure is only 18 or 19-bytes long */
498	if (TxLength > 24+CMD_BUF_SIZE) /* command too large? */
499	{
500		DEBUG_INFO3("Command too long: %d > %d", TxLength, 24+CMD_BUF_SIZE);
501		return IFD_NOT_SUPPORTED;
502	}
503
504	if (TxLength < 24+4 /* 4 = APDU size */) /* command too short? */
505	{
506		DEBUG_INFO3("Command too short: %d < %d", TxLength, 24+4);
507		return IFD_NOT_SUPPORTED;
508	}
509
510	if (dw2i(TxBuffer, 20) + 24 != TxLength) /* ulDataLength field coherency */
511	{
512		DEBUG_INFO3("Wrong lengths: %d %d", dw2i(TxBuffer, 20) + 24, TxLength);
513		return IFD_NOT_SUPPORTED;
514	}
515
516	/* Make sure in the beginning if bNumberMessage is valid or not.
517	 * 0xFF is the default value. */
518	if ((TxBuffer[11] > 3) && (TxBuffer[11] != 0xFF))
519	{
520		DEBUG_INFO2("Wrong bNumberMessage: %d", TxBuffer[11]);
521		return IFD_NOT_SUPPORTED;
522	}
523
524	/* Make sure bEntryValidationCondition is valid
525	 * The Cherry XX44 reader crashes with a wrong value */
526	if ((0x00 == TxBuffer[10]) || (TxBuffer[10] > 0x07))
527	{
528		DEBUG_INFO2("Correct bEntryValidationCondition (was 0x%02X)",
529			TxBuffer[10]);
530		TxBuffer[10] = 0x02;
531	}
532
533#ifdef BOGUS_PINPAD_FIRMWARE
534	/* some firmwares are buggy so we try to "correct" the frame */
535	/*
536	 * SPR 532 and Cherry ST 2000C has no display but requires _all_
537	 * bMsgIndex fields with bNumberMessage set to 0.
538	 */
539	if ((SPR532 == ccid_descriptor->readerID)
540		|| (CHERRYST2000 == ccid_descriptor->readerID))
541	{
542		TxBuffer[11] = 0x03; /* set bNumberMessages to 3 so that
543								all bMsgIndex123 are filled */
544		TxBuffer[14] = TxBuffer[15] = TxBuffer[16] = 0;	/* bMsgIndex123 */
545	}
546
547	/* the bug is a bit different than for the Cherry ST 2000C
548	 * with bNumberMessages < 3 the command seems to be accepted
549	 * and the card sends 6B 80 */
550	if (CHERRYXX44 == ccid_descriptor->readerID)
551	{
552		TxBuffer[11] = 0x03; /* set bNumberMessages to 3 so that
553								all bMsgIndex123 are filled */
554	}
555
556	/* bug circumvention for the GemPC Pinpad */
557	if (GEMPCPINPAD == ccid_descriptor->readerID)
558	{
559		/* The reader does not support, and actively reject, "max size reached"
560		 * and "timeout occured" validation conditions */
561		if (0x02 != TxBuffer[10])
562		{
563			DEBUG_INFO2("Correct bEntryValidationCondition for GemPC Pinpad (was %d)",
564				TxBuffer[10]);
565			TxBuffer[10] = 0x02;	/* validation key pressed */
566		}
567
568		/* the reader does not support any other value than 3 for the number
569		 * of messages */
570		bNumberMessages = TxBuffer[11];
571		if (0x03 != TxBuffer[11])
572		{
573			DEBUG_INFO2("Correct bNumberMessages for GemPC Pinpad (was %d)",
574				TxBuffer[11]);
575			TxBuffer[11] = 0x03; /* 3 messages */
576		}
577	}
578#endif
579
580	/* T=1 Protocol Management for a TPDU reader */
581	if ((SCARD_PROTOCOL_T1 == ccid_descriptor->cardProtocol)
582		&& (CCID_CLASS_TPDU == (ccid_descriptor->dwFeatures & CCID_CLASS_EXCHANGE_MASK)))
583	{
584		ct_buf_t sbuf;
585		unsigned char sdata[T1_BUFFER_SIZE];
586
587		/* Initialize send buffer with the APDU */
588		ct_buf_set(&sbuf,
589			(void *)(TxBuffer + offsetof(PIN_MODIFY_STRUCTURE, abData)),
590			TxLength - offsetof(PIN_MODIFY_STRUCTURE, abData));
591
592		/* Create T=1 block */
593		ret = t1_build(&((get_ccid_slot(reader_index))->t1),
594			sdata, 0, T1_I_BLOCK, &sbuf, NULL);
595
596		/* Increment the sequence numbers  */
597		get_ccid_slot(reader_index)->t1.ns ^= 1;
598		get_ccid_slot(reader_index)->t1.nr ^= 1;
599
600		/* Copy the generated T=1 block prologue into the teoprologue
601		 * of the CCID command */
602		memcpy(TxBuffer + offsetof(PIN_MODIFY_STRUCTURE, bTeoPrologue),
603			sdata, 3);
604	}
605
606	/* Build a CCID block from a PC/SC V2.02.05 Part 10 block */
607
608	/* Do adjustments as needed - CCID spec is not exact with some
609	 * details in the format of the structure, per-reader adaptions
610	 * might be needed.
611	 */
612	for (a = 11, b = 0; b < TxLength; b++)
613	{
614		if (1 == b) /* bTimeOut2 */
615			/* Ignore the second timeout as there's nothing we can do with it
616			 * currently */
617			continue;
618
619		if (15 == b) /* bMsgIndex2 */
620		{
621			/* in CCID the bMsgIndex2 is present only if bNumberMessage != 0 */
622			if (0 == TxBuffer[11])
623				continue;
624		}
625
626		if (16 == b) /* bMsgIndex3 */
627		{
628			/* in CCID the bMsgIndex3 is present only if bNumberMessage == 3 */
629			if (TxBuffer[11] < 3)
630				continue;
631		}
632
633		if ((b >= 20) && (b <= 23)) /* ulDataLength field (4 bytes) */
634			/* the ulDataLength field is not present in the CCID frame
635			 * so do not copy */
636			continue;
637
638		/* copy to the CCID block 'verbatim' */
639		cmd[a] = TxBuffer[b];
640		a++;
641 	}
642
643#ifdef BOGUS_PINPAD_FIRMWARE
644	if ((SPR532 == ccid_descriptor->readerID)
645		|| (CHERRYST2000 == ccid_descriptor->readerID))
646	{
647		cmd[21] = 0x00; /* set bNumberMessages to 0 */
648	}
649
650	if (GEMPCPINPAD == ccid_descriptor->readerID)
651		cmd[21] = bNumberMessages;	/* restore the real value */
652#endif
653
654	/* We know the size of the CCID message now */
655	i2dw(a - 10, cmd + 1);	/* command length (includes bPINOperation) */
656
657	old_read_timeout = ccid_descriptor -> readTimeout;
658	ccid_descriptor -> readTimeout = max(30, TxBuffer[0]+10);	/* at least 30 seconds */
659
660	if (WritePort(reader_index, a, cmd) != STATUS_SUCCESS)
661	{
662 		ret = IFD_COMMUNICATION_ERROR;
663		goto end;
664	}
665
666 	ret = CCID_Receive(reader_index, RxLength, RxBuffer, NULL);
667
668	/* T=1 Protocol Management for a TPDU reader */
669	if ((IFD_SUCCESS == ret)
670		&& (SCARD_PROTOCOL_T1 == ccid_descriptor->cardProtocol)
671		&& (CCID_CLASS_TPDU == (ccid_descriptor->dwFeatures & CCID_CLASS_EXCHANGE_MASK)))
672	{
673		/* timeout and cancel cases are faked by CCID_Receive() */
674		if (2 == *RxLength)
675		{
676			/* Decrement the sequence numbers since no TPDU was sent */
677			get_ccid_slot(reader_index)->t1.ns ^= 1;
678			get_ccid_slot(reader_index)->t1.nr ^= 1;
679		}
680		else
681		{
682			/* get only the T=1 data */
683			/* FIXME: manage T=1 error blocks */
684			memmove(RxBuffer, RxBuffer+3, *RxLength -4);
685			*RxLength -= 4;	/* remove NAD, PCB, LEN and CRC */
686		}
687	}
688
689end:
690	ccid_descriptor -> readTimeout = old_read_timeout;
691	return ret;
692} /* SecurePINModify */
693
694
695/*****************************************************************************
696 *
697 *					Escape
698 *
699 ****************************************************************************/
700RESPONSECODE CmdEscape(unsigned int reader_index,
701	const unsigned char TxBuffer[], unsigned int TxLength,
702	unsigned char RxBuffer[], unsigned int *RxLength)
703{
704	unsigned char *cmd_in, *cmd_out;
705	status_t res;
706	unsigned int length_in, length_out;
707	RESPONSECODE return_value = IFD_SUCCESS;
708	int old_read_timeout;
709	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
710
711	old_read_timeout = ccid_descriptor -> readTimeout;
712	ccid_descriptor -> readTimeout = 30;	/* 30 seconds */
713
714again:
715	/* allocate buffers */
716	length_in = 10 + TxLength;
717	if (NULL == (cmd_in = malloc(length_in)))
718	{
719		return_value = IFD_COMMUNICATION_ERROR;
720		goto end;
721	}
722
723	length_out = 10 + *RxLength;
724	if (NULL == (cmd_out = malloc(length_out)))
725	{
726		free(cmd_in);
727		return_value = IFD_COMMUNICATION_ERROR;
728		goto end;
729	}
730
731	cmd_in[0] = 0x6B; /* PC_to_RDR_Escape */
732	i2dw(length_in - 10, cmd_in+1);	/* dwLength */
733	cmd_in[5] = ccid_descriptor->bCurrentSlotIndex;	/* slot number */
734	cmd_in[6] = (*ccid_descriptor->pbSeq)++;
735	cmd_in[7] = cmd_in[8] = cmd_in[9] = 0; /* RFU */
736
737	/* copy the command */
738	memcpy(&cmd_in[10], TxBuffer, TxLength);
739
740	res = WritePort(reader_index, length_in, cmd_in);
741	free(cmd_in);
742	if (res != STATUS_SUCCESS)
743	{
744		free(cmd_out);
745		return_value = IFD_COMMUNICATION_ERROR;
746		goto end;
747	}
748
749	res = ReadPort(reader_index, &length_out, cmd_out);
750
751	/* replay the command if NAK
752	 * This (generally) happens only for the first command sent to the reader
753	 * with the serial protocol so it is not really needed for all the other
754	 * ReadPort() calls */
755	if (STATUS_COMM_NAK == res)
756	{
757		free(cmd_out);
758		goto again;
759	}
760
761	if (res != STATUS_SUCCESS)
762	{
763		free(cmd_out);
764		return_value = IFD_COMMUNICATION_ERROR;
765		goto end;
766	}
767
768	if (length_out < STATUS_OFFSET+1)
769	{
770		DEBUG_CRITICAL2("Not enough data received: %d bytes", length_out);
771		return_value = IFD_COMMUNICATION_ERROR;
772		goto end;
773	}
774
775	if (cmd_out[STATUS_OFFSET] & CCID_COMMAND_FAILED)
776	{
777		ccid_error(cmd_out[ERROR_OFFSET], __FILE__, __LINE__, __FUNCTION__);    /* bError */
778		return_value = IFD_COMMUNICATION_ERROR;
779	}
780
781	/* copy the response */
782	length_out = dw2i(cmd_out, 1);
783	if (length_out > *RxLength)
784		length_out = *RxLength;
785	*RxLength = length_out;
786	memcpy(RxBuffer, &cmd_out[10], length_out);
787
788	free(cmd_out);
789
790end:
791	ccid_descriptor -> readTimeout = old_read_timeout;
792	return return_value;
793} /* Escape */
794
795
796/*****************************************************************************
797 *
798 *					CmdPowerOff
799 *
800 ****************************************************************************/
801RESPONSECODE CmdPowerOff(unsigned int reader_index)
802{
803	unsigned char cmd[10];
804	status_t res;
805	unsigned int length;
806	RESPONSECODE return_value = IFD_SUCCESS;
807	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
808
809#ifndef TWIN_SERIAL
810	if (ICCD_A == ccid_descriptor->bInterfaceProtocol)
811	{
812		int r;
813
814		/* PowerOff */
815		r = ControlUSB(reader_index, 0x21, 0x63, 0, NULL, 0);
816
817		/* we got an error? */
818		if (r < 0)
819		{
820			DEBUG_INFO2("ICC Power Off failed: %s", strerror(errno));
821			return IFD_COMMUNICATION_ERROR;
822		}
823
824		return IFD_SUCCESS;
825	}
826
827	if (ICCD_B == ccid_descriptor->bInterfaceProtocol)
828	{
829		int r;
830		unsigned char buffer[3];
831
832		/* PowerOff */
833		r = ControlUSB(reader_index, 0x21, 0x63, 0, NULL, 0);
834
835		/* we got an error? */
836		if (r < 0)
837		{
838			DEBUG_INFO2("ICC Power Off failed: %s", strerror(errno));
839			return IFD_COMMUNICATION_ERROR;
840		}
841
842		/* SlotStatus */
843		r = ControlUSB(reader_index, 0xA1, 0x81, 0, buffer, sizeof(buffer));
844
845		/* we got an error? */
846		if (r < 0)
847		{
848			DEBUG_INFO2("ICC SlotStatus failed: %s", strerror(errno));
849			return IFD_COMMUNICATION_ERROR;
850		}
851
852		return IFD_SUCCESS;
853	}
854#endif
855
856	cmd[0] = 0x63; /* IccPowerOff */
857	cmd[1] = cmd[2] = cmd[3] = cmd[4] = 0;	/* dwLength */
858	cmd[5] = ccid_descriptor->bCurrentSlotIndex;	/* slot number */
859	cmd[6] = (*ccid_descriptor->pbSeq)++;
860	cmd[7] = cmd[8] = cmd[9] = 0; /* RFU */
861
862	res = WritePort(reader_index, sizeof(cmd), cmd);
863	if (res != STATUS_SUCCESS)
864		return IFD_COMMUNICATION_ERROR;
865
866	length = sizeof(cmd);
867	res = ReadPort(reader_index, &length, cmd);
868	if (res != STATUS_SUCCESS)
869		return IFD_COMMUNICATION_ERROR;
870
871	if (length < STATUS_OFFSET+1)
872	{
873		DEBUG_CRITICAL2("Not enough data received: %d bytes", length);
874		return IFD_COMMUNICATION_ERROR;
875	}
876
877	if (cmd[STATUS_OFFSET] & CCID_COMMAND_FAILED)
878	{
879		ccid_error(cmd[ERROR_OFFSET], __FILE__, __LINE__, __FUNCTION__);    /* bError */
880		return_value = IFD_COMMUNICATION_ERROR;
881	}
882
883	return return_value;
884} /* CmdPowerOff */
885
886
887/*****************************************************************************
888 *
889 *					CmdGetSlotStatus
890 *
891 ****************************************************************************/
892RESPONSECODE CmdGetSlotStatus(unsigned int reader_index, unsigned char buffer[])
893{
894	unsigned char cmd[10];
895	status_t res;
896	unsigned int length;
897	RESPONSECODE return_value = IFD_SUCCESS;
898	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
899
900#ifndef TWIN_SERIAL
901	if (ICCD_A == ccid_descriptor->bInterfaceProtocol)
902	{
903		int r;
904		unsigned char status[1];
905
906again_status:
907		/* SlotStatus */
908		r = ControlUSB(reader_index, 0xA1, 0xA0, 0, status, sizeof(status));
909
910		/* we got an error? */
911		if (r < 0)
912		{
913			DEBUG_INFO2("ICC Slot Status failed: %s", strerror(errno));
914			if (ENODEV == errno)
915				return IFD_NO_SUCH_DEVICE;
916			return IFD_COMMUNICATION_ERROR;
917		}
918
919		/* busy */
920		if (status[0] & 0x40)
921		{
922			DEBUG_INFO2("Busy: 0x%02X", status[0]);
923			(void)usleep(1000 * 10);
924			goto again_status;
925		}
926
927		/* simulate a CCID bStatus */
928		/* present and active by default */
929		buffer[7] = CCID_ICC_PRESENT_ACTIVE;
930
931		/* mute */
932		if (0x80 == status[0])
933			buffer[7] = CCID_ICC_ABSENT;
934
935		/* store the status for CmdXfrBlockCHAR_T0() */
936		buffer[0] = status[0];
937
938		return IFD_SUCCESS;
939	}
940
941	if (ICCD_B == ccid_descriptor->bInterfaceProtocol)
942	{
943		int r;
944		unsigned char buffer_tmp[3];
945
946		/* SlotStatus */
947		r = ControlUSB(reader_index, 0xA1, 0x81, 0, buffer_tmp,
948			sizeof(buffer_tmp));
949
950		/* we got an error? */
951		if (r < 0)
952		{
953			DEBUG_INFO2("ICC Slot Status failed: %s", strerror(errno));
954			if (ENODEV == errno)
955				return IFD_NO_SUCH_DEVICE;
956			return IFD_COMMUNICATION_ERROR;
957		}
958
959		/* simulate a CCID bStatus */
960		switch (buffer_tmp[1] & 0x03)
961		{
962			case 0:
963				buffer[7] = CCID_ICC_PRESENT_ACTIVE;
964				break;
965			case 1:
966				buffer[7] = CCID_ICC_PRESENT_INACTIVE;
967				break;
968			case 2:
969			case 3:
970				buffer[7] = CCID_ICC_ABSENT;
971		}
972		return IFD_SUCCESS;
973	}
974#endif
975
976	cmd[0] = 0x65; /* GetSlotStatus */
977	cmd[1] = cmd[2] = cmd[3] = cmd[4] = 0;	/* dwLength */
978	cmd[5] = ccid_descriptor->bCurrentSlotIndex;	/* slot number */
979	cmd[6] = (*ccid_descriptor->pbSeq)++;
980	cmd[7] = cmd[8] = cmd[9] = 0; /* RFU */
981
982	res = WritePort(reader_index, sizeof(cmd), cmd);
983	if (res != STATUS_SUCCESS)
984	{
985		if (STATUS_NO_SUCH_DEVICE == res)
986			return IFD_NO_SUCH_DEVICE;
987		return IFD_COMMUNICATION_ERROR;
988	}
989
990	length = SIZE_GET_SLOT_STATUS;
991	res = ReadPort(reader_index, &length, buffer);
992	if (res != STATUS_SUCCESS)
993		return IFD_COMMUNICATION_ERROR;
994
995	if (length < STATUS_OFFSET+1)
996	{
997		DEBUG_CRITICAL2("Not enough data received: %d bytes", length);
998		return IFD_COMMUNICATION_ERROR;
999	}
1000
1001	if (buffer[STATUS_OFFSET] & CCID_COMMAND_FAILED)
1002	{
1003#ifdef O2MICRO_OZ776_PATCH
1004		/* the O2MICRO OZ 776 reader sends card absent or mute errors
1005		 * when no card is inserted */
1006		if (! (((OZ776 == ccid_descriptor->readerID)
1007			|| (OZ776_7772 == ccid_descriptor->readerID))
1008			&& (buffer[ERROR_OFFSET] == 0xFE)))
1009#endif
1010		ccid_error(buffer[ERROR_OFFSET], __FILE__, __LINE__, __FUNCTION__);    /* bError */
1011
1012		/* card absent or mute is not an communication error */
1013		if (buffer[ERROR_OFFSET] != 0xFE)
1014			return_value = IFD_COMMUNICATION_ERROR;
1015	}
1016
1017	return return_value;
1018} /* CmdGetSlotStatus */
1019
1020
1021/*****************************************************************************
1022 *
1023 *					CmdXfrBlock
1024 *
1025 ****************************************************************************/
1026RESPONSECODE CmdXfrBlock(unsigned int reader_index, unsigned int tx_length,
1027	unsigned char tx_buffer[], unsigned int *rx_length,
1028	unsigned char rx_buffer[], int protocol)
1029{
1030	RESPONSECODE return_value = IFD_SUCCESS;
1031	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
1032
1033	/* APDU or TPDU? */
1034	switch (ccid_descriptor->dwFeatures & CCID_CLASS_EXCHANGE_MASK)
1035	{
1036		case CCID_CLASS_TPDU:
1037			if (protocol == T_0)
1038				return_value = CmdXfrBlockTPDU_T0(reader_index,
1039					tx_length, tx_buffer, rx_length, rx_buffer);
1040			else
1041				if (protocol == T_1)
1042					return_value = CmdXfrBlockTPDU_T1(reader_index, tx_length,
1043						tx_buffer, rx_length, rx_buffer);
1044				else
1045					return_value = IFD_PROTOCOL_NOT_SUPPORTED;
1046			break;
1047
1048		case CCID_CLASS_SHORT_APDU:
1049			return_value = CmdXfrBlockTPDU_T0(reader_index,
1050				tx_length, tx_buffer, rx_length, rx_buffer);
1051			break;
1052
1053		case CCID_CLASS_EXTENDED_APDU:
1054			return_value = CmdXfrBlockAPDU_extended(reader_index,
1055				tx_length, tx_buffer, rx_length, rx_buffer);
1056			break;
1057
1058		case CCID_CLASS_CHARACTER:
1059			if (protocol == T_0)
1060				return_value = CmdXfrBlockCHAR_T0(reader_index, tx_length,
1061					tx_buffer, rx_length, rx_buffer);
1062			else
1063				if (protocol == T_1)
1064					return_value = CmdXfrBlockTPDU_T1(reader_index, tx_length,
1065						tx_buffer, rx_length, rx_buffer);
1066 				else
1067					return_value = IFD_PROTOCOL_NOT_SUPPORTED;
1068			break;
1069
1070		default:
1071			return_value = IFD_COMMUNICATION_ERROR;
1072	}
1073
1074	return return_value;
1075} /* CmdXfrBlock */
1076
1077
1078/*****************************************************************************
1079 *
1080 *					CCID_Transmit
1081 *
1082 ****************************************************************************/
1083RESPONSECODE CCID_Transmit(unsigned int reader_index, unsigned int tx_length,
1084	const unsigned char tx_buffer[], unsigned short rx_length, unsigned char bBWI)
1085{
1086	unsigned char cmd[10+CMD_BUF_SIZE];	/* CCID + APDU buffer */
1087	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
1088	status_t ret;
1089
1090#ifndef TWIN_SERIAL
1091	if (ICCD_A == ccid_descriptor->bInterfaceProtocol)
1092	{
1093		int r;
1094
1095		/* Xfr Block */
1096		r = ControlUSB(reader_index, 0x21, 0x65, 0, tx_buffer, tx_length);
1097
1098		/* we got an error? */
1099		if (r < 0)
1100		{
1101			DEBUG_INFO2("ICC Xfr Block failed: %s", strerror(errno));
1102			return IFD_COMMUNICATION_ERROR;
1103		}
1104
1105		return IFD_SUCCESS;
1106	}
1107
1108	if (ICCD_B == ccid_descriptor->bInterfaceProtocol)
1109	{
1110		int r;
1111
1112		/* nul block so we are chaining */
1113		if (NULL == tx_buffer)
1114			rx_length = 0x10;	/* bLevelParameter */
1115
1116		/* Xfr Block */
1117		DEBUG_COMM2("chain parameter: %d", rx_length);
1118		r = ControlUSB(reader_index, 0x21, 0x65, rx_length << 8, tx_buffer,
1119			tx_length);
1120
1121		/* we got an error? */
1122		if (r < 0)
1123		{
1124			DEBUG_INFO2("ICC Xfr Block failed: %s", strerror(errno));
1125			return IFD_COMMUNICATION_ERROR;
1126		}
1127
1128		return IFD_SUCCESS;
1129	}
1130#endif
1131
1132	cmd[0] = 0x6F; /* XfrBlock */
1133	i2dw(tx_length, cmd+1);	/* APDU length */
1134	cmd[5] = ccid_descriptor->bCurrentSlotIndex;	/* slot number */
1135	cmd[6] = (*ccid_descriptor->pbSeq)++;
1136	cmd[7] = bBWI;	/* extend block waiting timeout */
1137	cmd[8] = rx_length & 0xFF;	/* Expected length, in character mode only */
1138	cmd[9] = (rx_length >> 8) & 0xFF;
1139
1140	/* check that the command is not too large */
1141	if (tx_length > CMD_BUF_SIZE)
1142	{
1143		DEBUG_CRITICAL2("TX Length too big: %d", tx_length);
1144		return IFD_NOT_SUPPORTED;
1145	}
1146
1147	memcpy(cmd+10, tx_buffer, tx_length);
1148
1149	ret = WritePort(reader_index, 10+tx_length, cmd);
1150	if (STATUS_NO_SUCH_DEVICE == ret)
1151		return IFD_NO_SUCH_DEVICE;
1152	if (ret != STATUS_SUCCESS)
1153		return IFD_COMMUNICATION_ERROR;
1154
1155	return IFD_SUCCESS;
1156} /* CCID_Transmit */
1157
1158
1159/*****************************************************************************
1160 *
1161 *					CCID_Receive
1162 *
1163 ****************************************************************************/
1164RESPONSECODE CCID_Receive(unsigned int reader_index, unsigned int *rx_length,
1165	unsigned char rx_buffer[], unsigned char *chain_parameter)
1166{
1167	unsigned char cmd[10+CMD_BUF_SIZE];	/* CCID + APDU buffer */
1168	unsigned int length;
1169	RESPONSECODE return_value = IFD_SUCCESS;
1170	status_t ret;
1171
1172#ifndef TWIN_SERIAL
1173	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
1174
1175	if (ICCD_A == ccid_descriptor->bInterfaceProtocol)
1176	{
1177		int r;
1178
1179		/* Data Block */
1180		r = ControlUSB(reader_index, 0xA1, 0x6F, 0, rx_buffer, *rx_length);
1181
1182		/* we got an error? */
1183		if (r < 0)
1184		{
1185			DEBUG_INFO2("ICC Data Block failed: %s", strerror(errno));
1186			return IFD_COMMUNICATION_ERROR;
1187		}
1188
1189		return IFD_SUCCESS;
1190	}
1191
1192	if (ICCD_B == ccid_descriptor->bInterfaceProtocol)
1193	{
1194		int r;
1195		unsigned char rx_tmp[4];
1196		unsigned char *old_rx_buffer = NULL;
1197		int old_rx_length = 0;
1198
1199		/* read a nul block. buffer need to be at least 4-bytes */
1200		if (NULL == rx_buffer)
1201		{
1202			rx_buffer = rx_tmp;
1203			*rx_length = sizeof(rx_tmp);
1204		}
1205
1206		/* the buffer must be 4 bytes minimum for ICCD-B */
1207		if (*rx_length < 4)
1208		{
1209			old_rx_buffer = rx_buffer;
1210			old_rx_length = *rx_length;
1211			rx_buffer = rx_tmp;
1212			*rx_length = sizeof(rx_tmp);
1213		}
1214
1215time_request_ICCD_B:
1216		/* Data Block */
1217		r = ControlUSB(reader_index, 0xA1, 0x6F, 0, rx_buffer, *rx_length);
1218
1219		/* we got an error? */
1220		if (r < 0)
1221		{
1222			DEBUG_INFO2("ICC Data Block failed: %s", strerror(errno));
1223			return IFD_COMMUNICATION_ERROR;
1224		}
1225
1226		/* copy from the 4 bytes buffer if used */
1227		if (old_rx_buffer)
1228		{
1229			memcpy(old_rx_buffer, rx_buffer, min(r, old_rx_length));
1230			rx_buffer = old_rx_buffer;
1231		}
1232
1233		/* bResponseType */
1234		switch (rx_buffer[0])
1235		{
1236			case 0x00:
1237				/* the abData field contains the information created by the
1238				 * preceding request */
1239				break;
1240
1241			case 0x40:
1242				/* Status Information */
1243				ccid_error(rx_buffer[2], __FILE__, __LINE__, __FUNCTION__);
1244				return IFD_COMMUNICATION_ERROR;
1245
1246			case 0x80:
1247				/* Polling */
1248			{
1249				int delay;
1250
1251				delay = (rx_buffer[2] << 8) + rx_buffer[1];
1252				DEBUG_COMM2("Pooling delay: %d", delay);
1253
1254				if (0 == delay)
1255					/* host select the delay */
1256					delay = 1;
1257				(void)usleep(delay * 1000 * 10);
1258				goto time_request_ICCD_B;
1259			}
1260
1261			case 0x01:
1262			case 0x02:
1263			case 0x03:
1264			case 0x10:
1265				/* Extended case
1266				 * Only valid for Data Block frames */
1267				if (chain_parameter)
1268					*chain_parameter = rx_buffer[0];
1269				break;
1270
1271			default:
1272				DEBUG_CRITICAL2("Unknown bResponseType: 0x%02X", rx_buffer[0]);
1273				return IFD_COMMUNICATION_ERROR;
1274		}
1275
1276		memmove(rx_buffer, rx_buffer+1, r-1);
1277		*rx_length = r-1;
1278
1279		return IFD_SUCCESS;
1280	}
1281#endif
1282
1283time_request:
1284	length = sizeof(cmd);
1285	ret = ReadPort(reader_index, &length, cmd);
1286	if (ret != STATUS_SUCCESS)
1287	{
1288		if (STATUS_NO_SUCH_DEVICE == ret)
1289			return IFD_NO_SUCH_DEVICE;
1290		return IFD_COMMUNICATION_ERROR;
1291	}
1292
1293	if (length < STATUS_OFFSET+1)
1294	{
1295		DEBUG_CRITICAL2("Not enough data received: %d bytes", length);
1296		return IFD_COMMUNICATION_ERROR;
1297	}
1298
1299	if (cmd[STATUS_OFFSET] & CCID_COMMAND_FAILED)
1300	{
1301		ccid_error(cmd[ERROR_OFFSET], __FILE__, __LINE__, __FUNCTION__);    /* bError */
1302		switch (cmd[ERROR_OFFSET])
1303		{
1304			case 0xEF:	/* cancel */
1305				if (*rx_length < 2)
1306					return IFD_COMMUNICATION_ERROR;
1307				rx_buffer[0]= 0x64;
1308				rx_buffer[1]= 0x01;
1309				*rx_length = 2;
1310				return IFD_SUCCESS;
1311
1312			case 0xF0:	/* timeout */
1313				if (*rx_length < 2)
1314					return IFD_COMMUNICATION_ERROR;
1315				rx_buffer[0]= 0x64;
1316				rx_buffer[1]= 0x00;
1317				*rx_length = 2;
1318				return IFD_SUCCESS;
1319
1320			case 0xFD:	/* Parity error during exchange */
1321				return IFD_PARITY_ERROR;
1322
1323			default:
1324				return IFD_COMMUNICATION_ERROR;
1325		}
1326	}
1327
1328	if (cmd[STATUS_OFFSET] & CCID_TIME_EXTENSION)
1329	{
1330		DEBUG_COMM2("Time extension requested: 0x%02X", cmd[ERROR_OFFSET]);
1331		goto time_request;
1332	}
1333
1334	/* we have read less (or more) data than the CCID frame says to contain */
1335	if (length-10 != dw2i(cmd, 1))
1336	{
1337		DEBUG_CRITICAL3("Can't read all data (%d out of %d expected)",
1338			length-10, dw2i(cmd, 1));
1339		return_value = IFD_COMMUNICATION_ERROR;
1340	}
1341
1342	length = dw2i(cmd, 1);
1343	if (length <= *rx_length)
1344		*rx_length = length;
1345	else
1346	{
1347		DEBUG_CRITICAL2("overrun by %d bytes", length - *rx_length);
1348		length = *rx_length;
1349		return_value = IFD_ERROR_INSUFFICIENT_BUFFER;
1350	}
1351
1352	/* Kobil firmware bug. No support for chaining */
1353	if (length && (NULL == rx_buffer))
1354	{
1355		DEBUG_CRITICAL2("Nul block expected but got %d bytes", length);
1356		return_value = IFD_COMMUNICATION_ERROR;
1357	}
1358	else
1359		memcpy(rx_buffer, cmd+10, length);
1360
1361	/* Extended case?
1362	 * Only valid for RDR_to_PC_DataBlock frames */
1363	if (chain_parameter)
1364		*chain_parameter = cmd[CHAIN_PARAMETER_OFFSET];
1365
1366	return return_value;
1367} /* CCID_Receive */
1368
1369
1370/*****************************************************************************
1371 *
1372 *					CmdXfrBlockAPDU_extended
1373 *
1374 ****************************************************************************/
1375static RESPONSECODE CmdXfrBlockAPDU_extended(unsigned int reader_index,
1376	unsigned int tx_length, unsigned char tx_buffer[], unsigned int *rx_length,
1377	unsigned char rx_buffer[])
1378{
1379	RESPONSECODE return_value;
1380	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
1381	unsigned char chain_parameter;
1382	unsigned int local_tx_length, sent_length;
1383	unsigned int local_rx_length, received_length;
1384	int buffer_overflow = 0;
1385
1386	if (ICCD_B == ccid_descriptor->bInterfaceProtocol)
1387	{
1388		/* length is on 16-bits only
1389		 * if a size > 0x1000 is used then usb_control_msg() fails with
1390		 * "Invalid argument" */
1391		if (*rx_length > 0x1000)
1392			*rx_length = 0x1000;
1393	}
1394
1395	DEBUG_COMM2("T=0 (extended): %d bytes", tx_length);
1396
1397	/* send the APDU */
1398	sent_length = 0;
1399
1400	/* we suppose one command is enough */
1401	chain_parameter = 0x00;
1402
1403	local_tx_length = tx_length - sent_length;
1404	if (local_tx_length > CMD_BUF_SIZE)
1405	{
1406		local_tx_length = CMD_BUF_SIZE;
1407		/* the command APDU begins with this command, and continue in the next
1408		 * PC_to_RDR_XfrBlock */
1409		chain_parameter = 0x01;
1410	}
1411	if (local_tx_length > ccid_descriptor->dwMaxCCIDMessageLength-10)
1412	{
1413		local_tx_length = ccid_descriptor->dwMaxCCIDMessageLength-10;
1414		chain_parameter = 0x01;
1415	}
1416
1417send_next_block:
1418	return_value = CCID_Transmit(reader_index, local_tx_length, tx_buffer,
1419		chain_parameter, 0);
1420	if (return_value != IFD_SUCCESS)
1421		return return_value;
1422
1423	sent_length += local_tx_length;
1424	tx_buffer += local_tx_length;
1425
1426	/* we just sent the last block (0x02) or only one block was needded (0x00) */
1427	if ((0x02 == chain_parameter) || (0x00 == chain_parameter))
1428		goto receive_block;
1429
1430	/* read a nul block */
1431	return_value = CCID_Receive(reader_index, &local_rx_length, NULL, NULL);
1432	if (return_value != IFD_SUCCESS)
1433		return return_value;
1434
1435	/* size of the next block */
1436	if (tx_length - sent_length > local_tx_length)
1437	{
1438		/* the abData field continues a command APDU and
1439		 * another block is to follow */
1440		chain_parameter = 0x03;
1441	}
1442	else
1443	{
1444		/* this abData field continues a command APDU and ends
1445		 * the APDU command */
1446		chain_parameter = 0x02;
1447
1448		/* last (smaller) block */
1449		local_tx_length = tx_length - sent_length;
1450	}
1451
1452	goto send_next_block;
1453
1454receive_block:
1455	/* receive the APDU */
1456	received_length = 0;
1457
1458receive_next_block:
1459	local_rx_length = *rx_length - received_length;
1460	return_value = CCID_Receive(reader_index, &local_rx_length, rx_buffer,
1461		&chain_parameter);
1462	if (IFD_ERROR_INSUFFICIENT_BUFFER == return_value)
1463	{
1464		buffer_overflow = 1;
1465
1466		/* we continue to read all the response APDU */
1467		return_value = IFD_SUCCESS;
1468	}
1469
1470	if (return_value != IFD_SUCCESS)
1471		return return_value;
1472
1473	/* advance in the reiceiving buffer */
1474	rx_buffer += local_rx_length;
1475	received_length += local_rx_length;
1476
1477	switch (chain_parameter)
1478	{
1479		/* the response APDU begins and ends in this command */
1480		case 0x00:
1481		/* this abData field continues the response APDU and ends the response
1482		 * APDU */
1483		case 0x02:
1484			break;
1485
1486		/* the response APDU begins with this command and is to continue */
1487		case 0x01:
1488		/* this abData field continues the response APDU and another block is
1489		 * to follow */
1490		case 0x03:
1491		/* empty abData field, continuation of the command APDU is expected in
1492		 * next PC_to_RDR_XfrBlock command */
1493		case 0x10:
1494			/* send a nul block */
1495			/* set wLevelParameter to 0010h: empty abData field,
1496			 * continuation of response APDU is
1497			 * expected in the next RDR_to_PC_DataBlock. */
1498			return_value = CCID_Transmit(reader_index, 0, NULL, 0x10, 0);
1499			if (return_value != IFD_SUCCESS)
1500				return return_value;
1501
1502			goto receive_next_block;
1503	}
1504
1505	*rx_length = received_length;
1506
1507	/* generate an overflow detected by pcscd */
1508	if (buffer_overflow)
1509		(*rx_length)++;
1510
1511	return IFD_SUCCESS;
1512} /* CmdXfrBlockAPDU_extended */
1513
1514
1515/*****************************************************************************
1516 *
1517 *					CmdXfrBlockTPDU_T0
1518 *
1519 ****************************************************************************/
1520static RESPONSECODE CmdXfrBlockTPDU_T0(unsigned int reader_index,
1521	unsigned int tx_length, unsigned char tx_buffer[], unsigned int *rx_length,
1522	unsigned char rx_buffer[])
1523{
1524	RESPONSECODE return_value = IFD_SUCCESS;
1525	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
1526
1527	DEBUG_COMM2("T=0: %d bytes", tx_length);
1528
1529	/* command length too big for CCID reader? */
1530	if (tx_length > ccid_descriptor->dwMaxCCIDMessageLength-10)
1531	{
1532#ifdef BOGUS_SCM_FIRMWARE_FOR_dwMaxCCIDMessageLength
1533		if (263 == ccid_descriptor->dwMaxCCIDMessageLength)
1534		{
1535			DEBUG_INFO3("Command too long (%d bytes) for max: %d bytes."
1536				" SCM reader with bogus firmware?",
1537				tx_length, ccid_descriptor->dwMaxCCIDMessageLength-10);
1538		}
1539		else
1540#endif
1541		{
1542			DEBUG_CRITICAL3("Command too long (%d bytes) for max: %d bytes",
1543				tx_length, ccid_descriptor->dwMaxCCIDMessageLength-10);
1544			return IFD_COMMUNICATION_ERROR;
1545		}
1546	}
1547
1548	/* command length too big for CCID driver? */
1549	if (tx_length > CMD_BUF_SIZE)
1550	{
1551		DEBUG_CRITICAL3("Command too long (%d bytes) for max: %d bytes",
1552				tx_length, CMD_BUF_SIZE);
1553		return IFD_COMMUNICATION_ERROR;
1554	}
1555
1556	return_value = CCID_Transmit(reader_index, tx_length, tx_buffer, 0, 0);
1557	if (return_value != IFD_SUCCESS)
1558		return return_value;
1559
1560	return CCID_Receive(reader_index, rx_length, rx_buffer, NULL);
1561} /* CmdXfrBlockTPDU_T0 */
1562
1563
1564/*****************************************************************************
1565 *
1566 *					T0CmdParsing
1567 *
1568 ****************************************************************************/
1569static RESPONSECODE T0CmdParsing(unsigned char *cmd, unsigned int cmd_len,
1570	/*@out@*/ unsigned int *exp_len)
1571{
1572	*exp_len = 0;
1573
1574	/* Ref: 7816-4 Annex A */
1575	switch (cmd_len)
1576	{
1577		case 4:	/* Case 1 */
1578			*exp_len = 2; /* SW1 and SW2 only */
1579			break;
1580
1581		case 5: /* Case 2 */
1582			if (cmd[4] != 0)
1583				*exp_len = cmd[4] + 2;
1584			else
1585				*exp_len = 256 + 2;
1586			break;
1587
1588		default: /* Case 3 */
1589			if (cmd_len > 5 && cmd_len == (unsigned int)(cmd[4] + 5))
1590				*exp_len = 2; /* SW1 and SW2 only */
1591			else
1592				return IFD_COMMUNICATION_ERROR;	/* situation not supported */
1593			break;
1594	}
1595
1596	return IFD_SUCCESS;
1597} /* T0CmdParsing */
1598
1599
1600/*****************************************************************************
1601 *
1602 *					T0ProcACK
1603 *
1604 ****************************************************************************/
1605static RESPONSECODE T0ProcACK(unsigned int reader_index,
1606	unsigned char **snd_buf, unsigned int *snd_len,
1607	unsigned char **rcv_buf, unsigned int *rcv_len,
1608	unsigned char **in_buf, unsigned int *in_len,
1609	unsigned int proc_len, int is_rcv)
1610{
1611	RESPONSECODE return_value;
1612	unsigned int remain_len;
1613	unsigned char tmp_buf[512];
1614	unsigned int ret_len;
1615
1616	DEBUG_COMM2("Enter, is_rcv = %d", is_rcv);
1617
1618	if (is_rcv == 1)
1619	{	/* Receiving mode */
1620		if (*in_len > 0)
1621		{	/* There are still available data in our buffer */
1622			if (*in_len >= proc_len)
1623			{
1624				/* We only need to get the data from our buffer */
1625				memcpy(*rcv_buf, *in_buf, proc_len);
1626				*rcv_buf += proc_len;
1627				*in_buf += proc_len;
1628				*rcv_len += proc_len;
1629				*in_len -= proc_len;
1630
1631				return IFD_SUCCESS;
1632			}
1633			else
1634			{
1635				/* Move all data in the input buffer to the reply buffer */
1636				remain_len = proc_len - *in_len;
1637				memcpy(*rcv_buf, *in_buf, *in_len);
1638				*rcv_buf += *in_len;
1639				*in_buf += *in_len;
1640				*rcv_len += *in_len;
1641				*in_len = 0;
1642			}
1643		}
1644		else
1645			/* There is no data in our tmp_buf,
1646			 * we have to read all data we needed */
1647			remain_len = proc_len;
1648
1649		/* Read the expected data from the smartcard */
1650		if (*in_len != 0)
1651		{
1652			DEBUG_CRITICAL("*in_len != 0");
1653			return IFD_COMMUNICATION_ERROR;
1654		}
1655
1656		memset(tmp_buf, 0, sizeof(tmp_buf));
1657
1658#ifdef O2MICRO_OZ776_PATCH
1659		if((0 != remain_len) && (0 == (remain_len + 10) % 64))
1660        {
1661			/* special hack to avoid a command of size modulo 64
1662			 * we send two commands instead */
1663            ret_len = 1;
1664            return_value = CCID_Transmit(reader_index, 0, *snd_buf, ret_len, 0);
1665            if (return_value != IFD_SUCCESS)
1666                return return_value;
1667            return_value = CCID_Receive(reader_index, &ret_len, tmp_buf, NULL);
1668            if (return_value != IFD_SUCCESS)
1669                return return_value;
1670
1671            ret_len = remain_len - 1;
1672            return_value = CCID_Transmit(reader_index, 0, *snd_buf, ret_len, 0);
1673            if (return_value != IFD_SUCCESS)
1674                return return_value;
1675            return_value = CCID_Receive(reader_index, &ret_len, &tmp_buf[1],
1676				NULL);
1677            if (return_value != IFD_SUCCESS)
1678                return return_value;
1679
1680            ret_len += 1;
1681        }
1682        else
1683#endif
1684		{
1685			ret_len = remain_len;
1686			return_value = CCID_Transmit(reader_index, 0, *snd_buf, ret_len, 0);
1687			if (return_value != IFD_SUCCESS)
1688				return return_value;
1689
1690			return_value = CCID_Receive(reader_index, &ret_len, tmp_buf, NULL);
1691			if (return_value != IFD_SUCCESS)
1692				return return_value;
1693		}
1694		memcpy(*rcv_buf, tmp_buf, remain_len);
1695		*rcv_buf += remain_len, *rcv_len += remain_len;
1696
1697		/* If ret_len != remain_len, our logic is erroneous */
1698		if (ret_len != remain_len)
1699		{
1700			DEBUG_CRITICAL("ret_len != remain_len");
1701			return IFD_COMMUNICATION_ERROR;
1702		}
1703	}
1704	else
1705	{	/* Sending mode */
1706
1707		return_value = CCID_Transmit(reader_index, proc_len, *snd_buf, 1, 0);
1708		if (return_value != IFD_SUCCESS)
1709			return return_value;
1710
1711		*snd_len -= proc_len;
1712		*snd_buf += proc_len;
1713	}
1714
1715	DEBUG_COMM("Exit");
1716
1717	return IFD_SUCCESS;
1718} /* T0ProcACK */
1719
1720
1721/*****************************************************************************
1722 *
1723 *					T0ProcSW1
1724 *
1725 ****************************************************************************/
1726static RESPONSECODE T0ProcSW1(unsigned int reader_index,
1727	unsigned char *rcv_buf, unsigned int *rcv_len,
1728	unsigned char *in_buf, unsigned int in_len)
1729{
1730	RESPONSECODE return_value = IFD_SUCCESS;
1731	UCHAR tmp_buf[512];
1732	unsigned char *rcv_buf_tmp = rcv_buf;
1733	const unsigned int rcv_len_tmp = *rcv_len;
1734	unsigned char sw1, sw2;
1735
1736	/* store the SW1 */
1737	sw1 = *rcv_buf = *in_buf;
1738	rcv_buf++;
1739	in_buf++;
1740	in_len--;
1741	(*rcv_len)++;
1742
1743	/* store the SW2 */
1744	if (0 == in_len)
1745	{
1746		return_value = CCID_Transmit(reader_index, 0, rcv_buf, 1, 0);
1747		if (return_value != IFD_SUCCESS)
1748			return return_value;
1749
1750		in_len = 1;
1751
1752		return_value = CCID_Receive(reader_index, &in_len, tmp_buf, NULL);
1753		if (return_value != IFD_SUCCESS)
1754			return return_value;
1755
1756		in_buf = tmp_buf;
1757	}
1758	sw2 = *rcv_buf = *in_buf;
1759	rcv_buf++;
1760	in_buf++;
1761	in_len--;
1762	(*rcv_len)++;
1763
1764	if (return_value != IFD_SUCCESS)
1765	{
1766		rcv_buf_tmp[0] = rcv_buf_tmp[1] = 0;
1767		*rcv_len = rcv_len_tmp;
1768	}
1769
1770	DEBUG_COMM3("Exit: SW=%02X %02X", sw1, sw2);
1771
1772	return return_value;
1773} /* T0ProcSW1 */
1774
1775
1776/*****************************************************************************
1777 *
1778 *					CmdXfrBlockCHAR_T0
1779 *
1780 ****************************************************************************/
1781static RESPONSECODE CmdXfrBlockCHAR_T0(unsigned int reader_index,
1782	unsigned int snd_len, unsigned char snd_buf[], unsigned int *rcv_len,
1783	unsigned char rcv_buf[])
1784{
1785	int is_rcv;
1786	unsigned char cmd[5];
1787	unsigned char tmp_buf[512];
1788	unsigned int exp_len, in_len;
1789	unsigned char ins, *in_buf;
1790	RESPONSECODE return_value = IFD_SUCCESS;
1791	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
1792
1793	DEBUG_COMM2("T=0: %d bytes", snd_len);
1794
1795	if (ICCD_A == ccid_descriptor->bInterfaceProtocol)
1796	{
1797		unsigned char pcbuffer[SIZE_GET_SLOT_STATUS];
1798
1799		/* Command to send to the smart card (must be 5 bytes) */
1800		memset(cmd, 0, sizeof(cmd));
1801		if (snd_len == 4)
1802		{
1803			memcpy(cmd, snd_buf, 4);
1804			snd_buf += 4;
1805			snd_len -= 4;
1806		}
1807		else
1808		{
1809			memcpy(cmd, snd_buf, 5);
1810			snd_buf += 5;
1811			snd_len -= 5;
1812		}
1813
1814		/* at most 5 bytes */
1815		return_value = CCID_Transmit(reader_index, 5, cmd, 0, 0);
1816		if (return_value != IFD_SUCCESS)
1817			return return_value;
1818
1819		/* wait for ready */
1820		return_value = CmdGetSlotStatus(reader_index, pcbuffer);
1821		if (return_value != IFD_SUCCESS)
1822			return return_value;
1823
1824		if ((0x20 != pcbuffer[0]) && (snd_len > 0))
1825		{
1826			/* continue sending the APDU */
1827			return_value = CCID_Transmit(reader_index, snd_len, snd_buf, 0, 0);
1828			if (return_value != IFD_SUCCESS)
1829				return return_value;
1830		}
1831		else
1832		{
1833			if ((0x20 == pcbuffer[0]) && (*rcv_len > 2))
1834				/* we will just read SW1-SW2 */
1835				*rcv_len = 2;
1836
1837			return_value = CCID_Receive(reader_index, rcv_len, rcv_buf, NULL);
1838			if (return_value != IFD_SUCCESS)
1839				DEBUG_CRITICAL("CCID_Receive failed");
1840
1841			return return_value;
1842		}
1843
1844		/* wait for ready */
1845		return_value = CmdGetSlotStatus(reader_index, pcbuffer);
1846		if (return_value != IFD_SUCCESS)
1847			return return_value;
1848
1849		if ((0x20 == pcbuffer[0]) && (*rcv_len > 2))
1850			/* we will just read SW1-SW2 */
1851			*rcv_len = 2;
1852
1853		/* read SW1-SW2 */
1854		return_value = CCID_Receive(reader_index, rcv_len, rcv_buf, NULL);
1855		if (return_value != IFD_SUCCESS)
1856			DEBUG_CRITICAL("CCID_Receive failed");
1857
1858		return return_value;
1859	}
1860
1861	in_buf = tmp_buf;
1862	in_len = 0;
1863	*rcv_len = 0;
1864
1865	return_value = T0CmdParsing(snd_buf, snd_len, &exp_len);
1866	if (return_value != IFD_SUCCESS)
1867	{
1868		DEBUG_CRITICAL("T0CmdParsing failed");
1869		return IFD_COMMUNICATION_ERROR;
1870	}
1871
1872	if (snd_len == 5 || snd_len == 4)
1873		is_rcv = 1;
1874	else
1875		is_rcv = 0;
1876
1877	/* Command to send to the smart card (must be 5 bytes, from 7816 p.15) */
1878	memset(cmd, 0, sizeof(cmd));
1879	if (snd_len == 4)
1880	{
1881		memcpy(cmd, snd_buf, 4);
1882		snd_buf += 4;
1883		snd_len -= 4;
1884	}
1885	else
1886	{
1887		memcpy(cmd, snd_buf, 5);
1888		snd_buf += 5;
1889		snd_len -= 5;
1890	}
1891
1892	/* Make sure this is a valid command by checking the INS field */
1893	ins = cmd[1];
1894	if ((ins & 0xF0) == 0x60 ||	/* 7816-3 8.3.2 */
1895		(ins & 0xF0) == 0x90)
1896	{
1897		DEBUG_CRITICAL2("fatal: INS (0x%02X) = 0x6X or 0x9X", ins);
1898		return IFD_COMMUNICATION_ERROR;
1899	}
1900
1901	return_value = CCID_Transmit(reader_index, 5, cmd, 1, 0);
1902	if (return_value != IFD_SUCCESS)
1903		return return_value;
1904
1905	while (1)
1906	{
1907		if (in_len == 0)
1908		{
1909			in_len = 1;
1910			return_value = CCID_Receive(reader_index, &in_len, tmp_buf, NULL);
1911			if (return_value != IFD_SUCCESS)
1912			{
1913				DEBUG_CRITICAL("CCID_Receive failed");
1914				return return_value;
1915			}
1916			in_buf = tmp_buf;
1917		}
1918		if (in_len == 0)
1919		{
1920			/* Suppose we should be able to get data.
1921			 * If not, error. Set the time-out error */
1922			DEBUG_CRITICAL("error: in_len = 0");
1923			return IFD_RESPONSE_TIMEOUT;
1924		}
1925
1926		/* Start to process the procedure bytes */
1927		if (*in_buf == 0x60)
1928		{
1929			in_len = 0;
1930			return_value = CCID_Transmit(reader_index, 0, cmd, 1, 0);
1931
1932			if (return_value != IFD_SUCCESS)
1933				return return_value;
1934
1935			continue;
1936		}
1937		else if (*in_buf == ins || *in_buf == (ins ^ 0x01))
1938		{
1939			/* ACK => To transfer all remaining data bytes */
1940			in_buf++, in_len--;
1941			if (is_rcv)
1942				return_value = T0ProcACK(reader_index, &snd_buf, &snd_len,
1943					&rcv_buf, rcv_len, &in_buf, &in_len, exp_len - *rcv_len, 1);
1944			else
1945				return_value = T0ProcACK(reader_index, &snd_buf, &snd_len,
1946					&rcv_buf, rcv_len, &in_buf, &in_len, snd_len, 0);
1947
1948			if (*rcv_len == exp_len)
1949				return return_value;
1950
1951			continue;
1952		}
1953		else if (*in_buf == (ins ^ 0xFF) || *in_buf == (ins ^ 0xFE))
1954		{
1955			/* ACK => To transfer 1 remaining bytes */
1956			in_buf++, in_len--;
1957			return_value = T0ProcACK(reader_index, &snd_buf, &snd_len,
1958				&rcv_buf, rcv_len, &in_buf, &in_len, 1, is_rcv);
1959
1960			if (return_value != IFD_SUCCESS)
1961				return return_value;
1962
1963			continue;
1964		}
1965		else if ((*in_buf & 0xF0) == 0x60 || (*in_buf & 0xF0) == 0x90)
1966			/* SW1 */
1967			return T0ProcSW1(reader_index, rcv_buf, rcv_len, in_buf, in_len);
1968
1969		/* Error, unrecognized situation found */
1970		DEBUG_CRITICAL2("Unrecognized Procedure byte (0x%02X) found!", *in_buf);
1971		return return_value;
1972	}
1973
1974	return return_value;
1975} /* CmdXfrBlockCHAR_T0 */
1976
1977
1978/*****************************************************************************
1979 *
1980 *					CmdXfrBlockTPDU_T1
1981 *
1982 ****************************************************************************/
1983static RESPONSECODE CmdXfrBlockTPDU_T1(unsigned int reader_index,
1984	unsigned int tx_length, unsigned char tx_buffer[], unsigned int *rx_length,
1985	unsigned char rx_buffer[])
1986{
1987	RESPONSECODE return_value = IFD_SUCCESS;
1988	int ret;
1989
1990	DEBUG_COMM3("T=1: %d and %d bytes", tx_length, *rx_length);
1991
1992	ret = t1_transceive(&((get_ccid_slot(reader_index)) -> t1), 0,
1993		tx_buffer, tx_length, rx_buffer, *rx_length);
1994
1995	if (ret < 0)
1996		return_value = IFD_COMMUNICATION_ERROR;
1997	else
1998		*rx_length = ret;
1999
2000	return return_value;
2001} /* CmdXfrBlockTPDU_T1 */
2002
2003
2004/*****************************************************************************
2005 *
2006 *					SetParameters
2007 *
2008 ****************************************************************************/
2009RESPONSECODE SetParameters(unsigned int reader_index, char protocol,
2010	unsigned int length, unsigned char buffer[])
2011{
2012	unsigned char cmd[10+CMD_BUF_SIZE];	/* CCID + APDU buffer */
2013	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
2014
2015	DEBUG_COMM2("length: %d bytes", length);
2016
2017	cmd[0] = 0x61; /* SetParameters */
2018	i2dw(length, cmd+1);	/* APDU length */
2019	cmd[5] = ccid_descriptor->bCurrentSlotIndex;	/* slot number */
2020	cmd[6] = (*ccid_descriptor->pbSeq)++;
2021	cmd[7] = protocol;	/* bProtocolNum */
2022	cmd[8] = cmd[9] = 0; /* RFU */
2023
2024	/* check that the command is not too large */
2025	if (length > CMD_BUF_SIZE)
2026		return IFD_NOT_SUPPORTED;
2027
2028	memcpy(cmd+10, buffer, length);
2029
2030	if (WritePort(reader_index, 10+length, cmd) != STATUS_SUCCESS)
2031		return IFD_COMMUNICATION_ERROR;
2032
2033	length = sizeof(cmd);
2034	if (ReadPort(reader_index, &length, cmd) != STATUS_SUCCESS)
2035		return IFD_COMMUNICATION_ERROR;
2036
2037	if (length < STATUS_OFFSET+1)
2038	{
2039		DEBUG_CRITICAL2("Not enough data received: %d bytes", length);
2040		return IFD_COMMUNICATION_ERROR;
2041	}
2042
2043	if (cmd[STATUS_OFFSET] & CCID_COMMAND_FAILED)
2044	{
2045		ccid_error(cmd[ERROR_OFFSET], __FILE__, __LINE__, __FUNCTION__);    /* bError */
2046		if (0x00 == cmd[ERROR_OFFSET])	/* command not supported */
2047			return IFD_NOT_SUPPORTED;
2048		else
2049			if ((cmd[ERROR_OFFSET] >= 1) && (cmd[ERROR_OFFSET] <= 127))
2050				/* a parameter is not changeable */
2051				return IFD_SUCCESS;
2052			else
2053				return IFD_COMMUNICATION_ERROR;
2054	}
2055
2056	return IFD_SUCCESS;
2057} /* SetParameters */
2058
2059
2060/*****************************************************************************
2061 *
2062 *					isCharLevel
2063 *
2064 ****************************************************************************/
2065int isCharLevel(int reader_index)
2066{
2067	return CCID_CLASS_CHARACTER == (get_ccid_descriptor(reader_index)->dwFeatures & CCID_CLASS_EXCHANGE_MASK);
2068} /* isCharLevel */
2069
2070
2071/*****************************************************************************
2072 *
2073 *					i2dw
2074 *
2075 ****************************************************************************/
2076static void i2dw(int value, unsigned char buffer[])
2077{
2078	buffer[0] = value & 0xFF;
2079	buffer[1] = (value >> 8) & 0xFF;
2080	buffer[2] = (value >> 16) & 0xFF;
2081	buffer[3] = (value >> 24) & 0xFF;
2082} /* i2dw */
2083
2084