Changed default hash algorithm preferences
[gnupg.git] / scd / ccid-driver.c
blob8428d85369d100b7290f54e280f5be99c66b6753
1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2 * Copyright (C) 2003, 2004, 2005, 2006, 2007
3 * 2008, 2009 Free Software Foundation, Inc.
4 * Written by Werner Koch.
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 * ALTERNATIVELY, this file may be distributed under the terms of the
22 * following license, in which case the provisions of this license are
23 * required INSTEAD OF the GNU General Public License. If you wish to
24 * allow use of your version of this file only under the terms of the
25 * GNU General Public License, and not to allow others to use your
26 * version of this file under the terms of the following license,
27 * indicate your decision by deleting this paragraph and the license
28 * below.
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
32 * are met:
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, and the entire permission notice in its entirety,
35 * including the disclaimer of warranties.
36 * 2. Redistributions in binary form must reproduce the above copyright
37 * notice, this list of conditions and the following disclaimer in the
38 * documentation and/or other materials provided with the distribution.
39 * 3. The name of the author may not be used to endorse or promote
40 * products derived from this software without specific prior
41 * written permission.
43 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
44 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
45 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
46 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
47 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
48 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
49 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53 * OF THE POSSIBILITY OF SUCH DAMAGE.
55 * $Date$
59 /* CCID (ChipCardInterfaceDevices) is a specification for accessing
60 smartcard via a reader connected to the USB.
62 This is a limited driver allowing to use some CCID drivers directly
63 without any other specila drivers. This is a fallback driver to be
64 used when nothing else works or the system should be kept minimal
65 for security reasons. It makes use of the libusb library to gain
66 portable access to USB.
68 This driver has been tested with the SCM SCR335 and SPR532
69 smartcard readers and requires that a reader implements APDU or
70 TPDU level exchange and does fully automatic initialization.
73 #ifdef HAVE_CONFIG_H
74 # include <config.h>
75 #endif
77 #if defined(HAVE_LIBUSB) || defined(TEST)
79 #include <errno.h>
80 #include <stdio.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <assert.h>
84 #include <sys/types.h>
85 #include <sys/stat.h>
86 #include <fcntl.h>
88 #include <usb.h>
90 #include "ccid-driver.h"
92 #define DRVNAME "ccid-driver: "
95 /* Depending on how this source is used we either define our error
96 output to go to stderr or to the jnlib based logging functions. We
97 use the latter when GNUPG_MAJOR_VERSION is defines or when both,
98 GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
100 #if defined(GNUPG_MAJOR_VERSION) \
101 || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
103 #if defined(GNUPG_SCD_MAIN_HEADER)
104 # include GNUPG_SCD_MAIN_HEADER
105 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
106 # include "options.h"
107 # include "util.h"
108 # include "memory.h"
109 # include "cardglue.h"
110 # else /* This is the modularized GnuPG 1.9 or later. */
111 # include "scdaemon.h"
112 #endif
115 # define DEBUGOUT(t) do { if (debug_level) \
116 log_debug (DRVNAME t); } while (0)
117 # define DEBUGOUT_1(t,a) do { if (debug_level) \
118 log_debug (DRVNAME t,(a)); } while (0)
119 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
120 log_debug (DRVNAME t,(a),(b)); } while (0)
121 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
122 log_debug (DRVNAME t,(a),(b),(c));} while (0)
123 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
124 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
125 # define DEBUGOUT_CONT(t) do { if (debug_level) \
126 log_printf (t); } while (0)
127 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
128 log_printf (t,(a)); } while (0)
129 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
130 log_printf (t,(a),(b)); } while (0)
131 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
132 log_printf (t,(a),(b),(c)); } while (0)
133 # define DEBUGOUT_LF() do { if (debug_level) \
134 log_printf ("\n"); } while (0)
136 #else /* Other usage of this source - don't use gnupg specifics. */
138 # define DEBUGOUT(t) do { if (debug_level) \
139 fprintf (stderr, DRVNAME t); } while (0)
140 # define DEBUGOUT_1(t,a) do { if (debug_level) \
141 fprintf (stderr, DRVNAME t, (a)); } while (0)
142 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
143 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
144 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
145 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
146 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
147 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
148 # define DEBUGOUT_CONT(t) do { if (debug_level) \
149 fprintf (stderr, t); } while (0)
150 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
151 fprintf (stderr, t, (a)); } while (0)
152 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
153 fprintf (stderr, t, (a), (b)); } while (0)
154 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
155 fprintf (stderr, t, (a), (b), (c)); } while (0)
156 # define DEBUGOUT_LF() do { if (debug_level) \
157 putc ('\n', stderr); } while (0)
159 #endif /* This source not used by scdaemon. */
162 #ifndef EAGAIN
163 #define EAGAIN EWOULDBLOCK
164 #endif
168 enum {
169 RDR_to_PC_NotifySlotChange= 0x50,
170 RDR_to_PC_HardwareError = 0x51,
172 PC_to_RDR_SetParameters = 0x61,
173 PC_to_RDR_IccPowerOn = 0x62,
174 PC_to_RDR_IccPowerOff = 0x63,
175 PC_to_RDR_GetSlotStatus = 0x65,
176 PC_to_RDR_Secure = 0x69,
177 PC_to_RDR_T0APDU = 0x6a,
178 PC_to_RDR_Escape = 0x6b,
179 PC_to_RDR_GetParameters = 0x6c,
180 PC_to_RDR_ResetParameters = 0x6d,
181 PC_to_RDR_IccClock = 0x6e,
182 PC_to_RDR_XfrBlock = 0x6f,
183 PC_to_RDR_Mechanical = 0x71,
184 PC_to_RDR_Abort = 0x72,
185 PC_to_RDR_SetDataRate = 0x73,
187 RDR_to_PC_DataBlock = 0x80,
188 RDR_to_PC_SlotStatus = 0x81,
189 RDR_to_PC_Parameters = 0x82,
190 RDR_to_PC_Escape = 0x83,
191 RDR_to_PC_DataRate = 0x84
195 /* Two macro to detect whether a CCID command has failed and to get
196 the error code. These macros assume that we can access the
197 mandatory first 10 bytes of a CCID message in BUF. */
198 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
199 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
202 /* We need to know the vendor to do some hacks. */
203 enum {
204 VENDOR_CHERRY = 0x046a,
205 VENDOR_SCM = 0x04e6,
206 VENDOR_OMNIKEY= 0x076b,
207 VENDOR_GEMPC = 0x08e6,
208 VENDOR_KAAN = 0x0d46
211 /* A list and a table with special transport descriptions. */
212 enum {
213 TRANSPORT_USB = 0, /* Standard USB transport. */
214 TRANSPORT_CM4040 = 1 /* As used by the Cardman 4040. */
217 static struct
219 char *name; /* Device name. */
220 int type;
222 } transports[] = {
223 { "/dev/cmx0", TRANSPORT_CM4040 },
224 { "/dev/cmx1", TRANSPORT_CM4040 },
225 { NULL },
229 /* Store information on the driver's state. A pointer to such a
230 structure is used as handle for most functions. */
231 struct ccid_driver_s
233 usb_dev_handle *idev;
234 char *rid;
235 int dev_fd; /* -1 for USB transport or file descriptor of the
236 transport device. */
237 unsigned short id_vendor;
238 unsigned short id_product;
239 unsigned short bcd_device;
240 int ifc_no;
241 int ep_bulk_out;
242 int ep_bulk_in;
243 int ep_intr;
244 int seqno;
245 unsigned char t1_ns;
246 unsigned char t1_nr;
247 int nonnull_nad;
248 int auto_ifsd;
249 int max_ifsd;
250 int ifsd;
251 int ifsc;
252 int powered_off;
253 int has_pinpad;
254 int apdu_level; /* Reader supports short APDU level exchange.
255 With a value of 2 short and extended level is
256 supported.*/
260 static int initialized_usb; /* Tracks whether USB has been initialized. */
261 static int debug_level; /* Flag to control the debug output.
262 0 = No debugging
263 1 = USB I/O info
264 2 = Level 1 + T=1 protocol tracing
265 3 = Level 2 + USB/I/O tracing of SlotStatus.
269 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
270 int use_crc);
271 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
272 int no_debug);
273 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
274 size_t *nread, int expected_type, int seqno, int timeout,
275 int no_debug);
276 static int abort_cmd (ccid_driver_t handle, int seqno);
278 /* Convert a little endian stored 4 byte value into an unsigned
279 integer. */
280 static unsigned int
281 convert_le_u32 (const unsigned char *buf)
283 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
287 /* Convert a little endian stored 2 byte value into an unsigned
288 integer. */
289 static unsigned int
290 convert_le_u16 (const unsigned char *buf)
292 return buf[0] | (buf[1] << 8);
295 static void
296 set_msg_len (unsigned char *msg, unsigned int length)
298 msg[1] = length;
299 msg[2] = length >> 8;
300 msg[3] = length >> 16;
301 msg[4] = length >> 24;
305 /* Pint an error message for a failed CCID command including a textual
306 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
307 static void
308 print_command_failed (const unsigned char *msg)
310 const char *t;
311 char buffer[100];
312 int ec;
314 if (!debug_level)
315 return;
317 ec = CCID_ERROR_CODE (msg);
318 switch (ec)
320 case 0x00: t = "Command not supported"; break;
322 case 0xE0: t = "Slot busy"; break;
323 case 0xEF: t = "PIN cancelled"; break;
324 case 0xF0: t = "PIN timeout"; break;
326 case 0xF2: t = "Automatic sequence ongoing"; break;
327 case 0xF3: t = "Deactivated Protocol"; break;
328 case 0xF4: t = "Procedure byte conflict"; break;
329 case 0xF5: t = "ICC class not supported"; break;
330 case 0xF6: t = "ICC protocol not supported"; break;
331 case 0xF7: t = "Bad checksum in ATR"; break;
332 case 0xF8: t = "Bad TS in ATR"; break;
334 case 0xFB: t = "An all inclusive hardware error occurred"; break;
335 case 0xFC: t = "Overrun error while talking to the ICC"; break;
336 case 0xFD: t = "Parity error while talking to the ICC"; break;
337 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
338 case 0xFF: t = "Host aborted the current activity"; break;
340 default:
341 if (ec > 0 && ec < 128)
342 sprintf (buffer, "Parameter error at offset %d", ec);
343 else
344 sprintf (buffer, "Error code %02X", ec);
345 t = buffer;
346 break;
348 DEBUGOUT_1 ("CCID command failed: %s\n", t);
352 static void
353 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
355 int any = 0;
357 for (; off < datalen; off++)
359 if (!any || !(off % 16))
361 if (any)
362 DEBUGOUT_LF ();
363 DEBUGOUT_1 (" [%04d] ", off);
365 DEBUGOUT_CONT_1 (" %02X", data[off]);
366 any = 1;
368 if (any && (off % 16))
369 DEBUGOUT_LF ();
373 static void
374 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
376 DEBUGOUT_1 ("%s:\n", name);
377 if (msglen < 7)
378 return;
379 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
380 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
381 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
385 static void
386 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
388 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
389 if (msglen < 10)
390 return;
391 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
392 msg[7] == 0? "auto":
393 msg[7] == 1? "5.0 V":
394 msg[7] == 2? "3.0 V":
395 msg[7] == 3? "1.8 V":"");
396 print_pr_data (msg, msglen, 8);
400 static void
401 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
403 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
404 print_pr_data (msg, msglen, 7);
408 static void
409 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
411 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
412 print_pr_data (msg, msglen, 7);
416 static void
417 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
419 unsigned int val;
421 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
422 if (msglen < 10)
423 return;
424 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
425 val = convert_le_u16 (msg+8);
426 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
427 val == 1? " (continued)":
428 val == 2? " (continues+ends)":
429 val == 3? " (continues+continued)":
430 val == 16? " (DataBlock-expected)":"");
431 print_pr_data (msg, msglen, 10);
435 static void
436 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
438 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
439 print_pr_data (msg, msglen, 7);
443 static void
444 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
446 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
447 print_pr_data (msg, msglen, 7);
451 static void
452 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
454 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
455 if (msglen < 10)
456 return;
457 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
458 print_pr_data (msg, msglen, 8);
462 static void
463 print_p2r_escape (const unsigned char *msg, size_t msglen)
465 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
466 print_pr_data (msg, msglen, 7);
470 static void
471 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
473 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
474 if (msglen < 10)
475 return;
476 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
477 print_pr_data (msg, msglen, 8);
481 static void
482 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
484 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
485 if (msglen < 10)
486 return;
487 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
488 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
489 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
490 print_pr_data (msg, msglen, 10);
494 static void
495 print_p2r_secure (const unsigned char *msg, size_t msglen)
497 unsigned int val;
499 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
500 if (msglen < 10)
501 return;
502 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
503 val = convert_le_u16 (msg+8);
504 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
505 val == 1? " (continued)":
506 val == 2? " (continues+ends)":
507 val == 3? " (continues+continued)":
508 val == 16? " (DataBlock-expected)":"");
509 print_pr_data (msg, msglen, 10);
513 static void
514 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
516 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
517 if (msglen < 10)
518 return;
519 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
520 print_pr_data (msg, msglen, 8);
524 static void
525 print_p2r_abort (const unsigned char *msg, size_t msglen)
527 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
528 print_pr_data (msg, msglen, 7);
532 static void
533 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
535 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
536 if (msglen < 10)
537 return;
538 print_pr_data (msg, msglen, 7);
542 static void
543 print_p2r_unknown (const unsigned char *msg, size_t msglen)
545 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
546 if (msglen < 10)
547 return;
548 print_pr_data (msg, msglen, 0);
552 static void
553 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
555 DEBUGOUT_1 ("%s:\n", name);
556 if (msglen < 9)
557 return;
558 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
559 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
560 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
561 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
562 if (msg[8])
563 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
567 static void
568 print_r2p_datablock (const unsigned char *msg, size_t msglen)
570 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
571 if (msglen < 10)
572 return;
573 if (msg[9])
574 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
575 msg[9] == 1? " (continued)":
576 msg[9] == 2? " (continues+ends)":
577 msg[9] == 3? " (continues+continued)":
578 msg[9] == 16? " (XferBlock-expected)":"");
579 print_pr_data (msg, msglen, 10);
583 static void
584 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
586 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
587 if (msglen < 10)
588 return;
589 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
590 msg[9] == 0? " (running)":
591 msg[9] == 1? " (stopped-L)":
592 msg[9] == 2? " (stopped-H)":
593 msg[9] == 3? " (stopped)":"");
594 print_pr_data (msg, msglen, 10);
598 static void
599 print_r2p_parameters (const unsigned char *msg, size_t msglen)
601 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
602 if (msglen < 10)
603 return;
605 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
606 if (msglen == 17 && msg[9] == 1)
608 /* Protocol T=1. */
609 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
610 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
611 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
612 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
613 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
614 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
615 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
617 else
618 print_pr_data (msg, msglen, 10);
622 static void
623 print_r2p_escape (const unsigned char *msg, size_t msglen)
625 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
626 if (msglen < 10)
627 return;
628 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
629 print_pr_data (msg, msglen, 10);
633 static void
634 print_r2p_datarate (const unsigned char *msg, size_t msglen)
636 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
637 if (msglen < 10)
638 return;
639 if (msglen >= 18)
641 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
642 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
643 print_pr_data (msg, msglen, 18);
645 else
646 print_pr_data (msg, msglen, 10);
650 static void
651 print_r2p_unknown (const unsigned char *msg, size_t msglen)
653 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
654 if (msglen < 10)
655 return;
656 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
657 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
658 print_pr_data (msg, msglen, 10);
662 /* Given a handle used for special transport prepare it for use. In
663 particular setup all information in way that resembles what
664 parse_cccid_descriptor does. */
665 static void
666 prepare_special_transport (ccid_driver_t handle)
668 assert (!handle->id_vendor);
670 handle->nonnull_nad = 0;
671 handle->auto_ifsd = 0;
672 handle->max_ifsd = 32;
673 handle->ifsd = 0;
674 handle->has_pinpad = 0;
675 handle->apdu_level = 0;
676 switch (handle->id_product)
678 case TRANSPORT_CM4040:
679 DEBUGOUT ("setting up transport for CardMan 4040\n");
680 handle->apdu_level = 1;
681 break;
683 default: assert (!"transport not defined");
687 /* Parse a CCID descriptor, optionally print all available features
688 and test whether this reader is usable by this driver. Returns 0
689 if it is usable.
691 Note, that this code is based on the one in lsusb.c of the
692 usb-utils package, I wrote on 2003-09-01. -wk. */
693 static int
694 parse_ccid_descriptor (ccid_driver_t handle,
695 const unsigned char *buf, size_t buflen)
697 unsigned int i;
698 unsigned int us;
699 int have_t1 = 0, have_tpdu=0, have_auto_conf = 0;
702 handle->nonnull_nad = 0;
703 handle->auto_ifsd = 0;
704 handle->max_ifsd = 32;
705 handle->ifsd = 0;
706 handle->has_pinpad = 0;
707 handle->apdu_level = 0;
708 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
709 handle->id_vendor, handle->id_product, handle->bcd_device);
710 if (buflen < 54 || buf[0] < 54)
712 DEBUGOUT ("CCID device descriptor is too short\n");
713 return -1;
716 DEBUGOUT ("ChipCard Interface Descriptor:\n");
717 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
718 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
719 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
720 if (buf[3] != 1 || buf[2] != 0)
721 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
722 DEBUGOUT_LF ();
724 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
725 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
726 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
727 : buf[5] == 3? "1.8V":"?"));
729 us = convert_le_u32 (buf+6);
730 DEBUGOUT_1 (" dwProtocols %5u ", us);
731 if ((us & 1))
732 DEBUGOUT_CONT (" T=0");
733 if ((us & 2))
735 DEBUGOUT_CONT (" T=1");
736 have_t1 = 1;
738 if ((us & ~3))
739 DEBUGOUT_CONT (" (Invalid values detected)");
740 DEBUGOUT_LF ();
742 us = convert_le_u32(buf+10);
743 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
744 us = convert_le_u32(buf+14);
745 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
746 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
747 us = convert_le_u32(buf+19);
748 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
749 us = convert_le_u32(buf+23);
750 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
751 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
753 us = convert_le_u32(buf+28);
754 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
755 handle->max_ifsd = us;
757 us = convert_le_u32(buf+32);
758 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
759 if ((us&1))
760 DEBUGOUT_CONT ( " 2-wire");
761 if ((us&2))
762 DEBUGOUT_CONT ( " 3-wire");
763 if ((us&4))
764 DEBUGOUT_CONT ( " I2C");
765 DEBUGOUT_LF ();
767 us = convert_le_u32(buf+36);
768 DEBUGOUT_1 (" dwMechanical %08X ", us);
769 if ((us & 1))
770 DEBUGOUT_CONT (" accept");
771 if ((us & 2))
772 DEBUGOUT_CONT (" eject");
773 if ((us & 4))
774 DEBUGOUT_CONT (" capture");
775 if ((us & 8))
776 DEBUGOUT_CONT (" lock");
777 DEBUGOUT_LF ();
779 us = convert_le_u32(buf+40);
780 DEBUGOUT_1 (" dwFeatures %08X\n", us);
781 if ((us & 0x0002))
783 DEBUGOUT (" Auto configuration based on ATR\n");
784 have_auto_conf = 1;
786 if ((us & 0x0004))
787 DEBUGOUT (" Auto activation on insert\n");
788 if ((us & 0x0008))
789 DEBUGOUT (" Auto voltage selection\n");
790 if ((us & 0x0010))
791 DEBUGOUT (" Auto clock change\n");
792 if ((us & 0x0020))
793 DEBUGOUT (" Auto baud rate change\n");
794 if ((us & 0x0040))
795 DEBUGOUT (" Auto parameter negotation made by CCID\n");
796 else if ((us & 0x0080))
797 DEBUGOUT (" Auto PPS made by CCID\n");
798 else if ((us & (0x0040 | 0x0080)))
799 DEBUGOUT (" WARNING: conflicting negotation features\n");
801 if ((us & 0x0100))
802 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
803 if ((us & 0x0200))
805 DEBUGOUT (" NAD value other than 0x00 accepted\n");
806 handle->nonnull_nad = 1;
808 if ((us & 0x0400))
810 DEBUGOUT (" Auto IFSD exchange\n");
811 handle->auto_ifsd = 1;
814 if ((us & 0x00010000))
816 DEBUGOUT (" TPDU level exchange\n");
817 have_tpdu = 1;
819 else if ((us & 0x00020000))
821 DEBUGOUT (" Short APDU level exchange\n");
822 handle->apdu_level = 1;
824 else if ((us & 0x00040000))
826 DEBUGOUT (" Short and extended APDU level exchange\n");
827 handle->apdu_level = 2;
829 else if ((us & 0x00070000))
830 DEBUGOUT (" WARNING: conflicting exchange levels\n");
832 us = convert_le_u32(buf+44);
833 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
835 DEBUGOUT ( " bClassGetResponse ");
836 if (buf[48] == 0xff)
837 DEBUGOUT_CONT ("echo\n");
838 else
839 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
841 DEBUGOUT ( " bClassEnvelope ");
842 if (buf[49] == 0xff)
843 DEBUGOUT_CONT ("echo\n");
844 else
845 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
847 DEBUGOUT ( " wlcdLayout ");
848 if (!buf[50] && !buf[51])
849 DEBUGOUT_CONT ("none\n");
850 else
851 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
853 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
854 if ((buf[52] & 1))
856 DEBUGOUT_CONT ( " verification");
857 handle->has_pinpad |= 1;
859 if ((buf[52] & 2))
861 DEBUGOUT_CONT ( " modification");
862 handle->has_pinpad |= 2;
864 DEBUGOUT_LF ();
866 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
868 if (buf[0] > 54) {
869 DEBUGOUT (" junk ");
870 for (i=54; i < buf[0]-54; i++)
871 DEBUGOUT_CONT_1 (" %02X", buf[i]);
872 DEBUGOUT_LF ();
875 if (!have_t1 || !(have_tpdu || handle->apdu_level) || !have_auto_conf)
877 DEBUGOUT ("this drivers requires that the reader supports T=1, "
878 "TPDU or APDU level exchange and auto configuration - "
879 "this is not available\n");
880 return -1;
884 /* SCM drivers get stuck in their internal USB stack if they try to
885 send a frame of n*wMaxPacketSize back to us. Given that
886 wMaxPacketSize is 64 for these readers we set the IFSD to a value
887 lower than that:
888 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
889 Product Ids:
890 0xe001 - SCR 331
891 0x5111 - SCR 331-DI
892 0x5115 - SCR 335
893 0xe003 - SPR 532
895 if (handle->id_vendor == VENDOR_SCM
896 && handle->max_ifsd > 48
897 && ( (handle->id_product == 0xe001 && handle->bcd_device < 0x0516)
898 ||(handle->id_product == 0x5111 && handle->bcd_device < 0x0620)
899 ||(handle->id_product == 0x5115 && handle->bcd_device < 0x0514)
900 ||(handle->id_product == 0xe003 && handle->bcd_device < 0x0504)
903 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
904 handle->max_ifsd = 48;
908 return 0;
912 static char *
913 get_escaped_usb_string (usb_dev_handle *idev, int idx,
914 const char *prefix, const char *suffix)
916 int rc;
917 unsigned char buf[280];
918 unsigned char *s;
919 unsigned int langid;
920 size_t i, n, len;
921 char *result;
923 if (!idx)
924 return NULL;
926 /* Fixme: The next line is for the current Valgrid without support
927 for USB IOCTLs. */
928 memset (buf, 0, sizeof buf);
930 /* First get the list of supported languages and use the first one.
931 If we do don't find it we try to use English. Note that this is
932 all in a 2 bute Unicode encoding using little endian. */
933 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
934 (USB_DT_STRING << 8), 0,
935 (char*)buf, sizeof buf, 1000 /* ms timeout */);
936 if (rc < 4)
937 langid = 0x0409; /* English. */
938 else
939 langid = (buf[3] << 8) | buf[2];
941 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
942 (USB_DT_STRING << 8) + idx, langid,
943 (char*)buf, sizeof buf, 1000 /* ms timeout */);
944 if (rc < 2 || buf[1] != USB_DT_STRING)
945 return NULL; /* Error or not a string. */
946 len = buf[0];
947 if (len > rc)
948 return NULL; /* Larger than our buffer. */
950 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
952 if (s[1])
953 n++; /* High byte set. */
954 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
955 n += 3 ;
956 else
957 n++;
960 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
961 if (!result)
962 return NULL;
964 strcpy (result, prefix);
965 n = strlen (prefix);
966 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
968 if (s[1])
969 result[n++] = '\xff'; /* High byte set. */
970 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
972 sprintf (result+n, "%%%02X", *s);
973 n += 3;
975 else
976 result[n++] = *s;
978 strcpy (result+n, suffix);
980 return result;
983 /* This function creates an reader id to be used to find the same
984 physical reader after a reset. It returns an allocated and possibly
985 percent escaped string or NULL if not enough memory is available. */
986 static char *
987 make_reader_id (usb_dev_handle *idev,
988 unsigned int vendor, unsigned int product,
989 unsigned char serialno_index)
991 char *rid;
992 char prefix[20];
994 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
995 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
996 if (!rid)
998 rid = malloc (strlen (prefix) + 3 + 1);
999 if (!rid)
1000 return NULL;
1001 strcpy (rid, prefix);
1002 strcat (rid, "X:0");
1004 return rid;
1008 /* Helper to find the endpoint from an interface descriptor. */
1009 static int
1010 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
1012 int no;
1013 int want_bulk_in = 0;
1015 if (mode == 1)
1016 want_bulk_in = 0x80;
1017 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1019 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1020 if (ep->bDescriptorType != USB_DT_ENDPOINT)
1022 else if (mode == 2
1023 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1024 == USB_ENDPOINT_TYPE_INTERRUPT)
1025 && (ep->bEndpointAddress & 0x80))
1026 return (ep->bEndpointAddress & 0x0f);
1027 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1028 == USB_ENDPOINT_TYPE_BULK)
1029 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1030 return (ep->bEndpointAddress & 0x0f);
1032 /* Should never happen. */
1033 return mode == 2? 0x83 : mode == 1? 0x82 :1;
1037 /* Helper for scan_or_find_devices. This function returns true if a
1038 requested device has been found or the caller should stop scanning
1039 for other reasons. */
1040 static int
1041 scan_or_find_usb_device (int scan_mode,
1042 int *readerno, int *count, char **rid_list,
1043 const char *readerid,
1044 struct usb_device *dev,
1045 char **r_rid,
1046 struct usb_device **r_dev,
1047 usb_dev_handle **r_idev,
1048 unsigned char **ifcdesc_extra,
1049 size_t *ifcdesc_extra_len,
1050 int *interface_number,
1051 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1053 int cfg_no;
1054 int ifc_no;
1055 int set_no;
1056 struct usb_config_descriptor *config;
1057 struct usb_interface *interface;
1058 struct usb_interface_descriptor *ifcdesc;
1059 char *rid;
1060 usb_dev_handle *idev;
1062 *r_idev = NULL;
1064 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
1066 config = dev->config + cfg_no;
1067 if(!config)
1068 continue;
1070 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1072 interface = config->interface + ifc_no;
1073 if (!interface)
1074 continue;
1076 for (set_no=0; set_no < interface->num_altsetting; set_no++)
1078 ifcdesc = (interface->altsetting + set_no);
1079 /* The second condition is for older SCM SPR 532 who did
1080 not know about the assigned CCID class. Instead of
1081 trying to interpret the strings we simply check the
1082 product ID. */
1083 if (ifcdesc && ifcdesc->extra
1084 && ((ifcdesc->bInterfaceClass == 11
1085 && ifcdesc->bInterfaceSubClass == 0
1086 && ifcdesc->bInterfaceProtocol == 0)
1087 || (ifcdesc->bInterfaceClass == 255
1088 && dev->descriptor.idVendor == VENDOR_SCM
1089 && dev->descriptor.idProduct == 0xe003)))
1091 idev = usb_open (dev);
1092 if (!idev)
1094 DEBUGOUT_1 ("usb_open failed: %s\n",
1095 strerror (errno));
1096 continue; /* with next setting. */
1099 rid = make_reader_id (idev,
1100 dev->descriptor.idVendor,
1101 dev->descriptor.idProduct,
1102 dev->descriptor.iSerialNumber);
1103 if (rid)
1105 if (scan_mode)
1107 char *p;
1109 /* We are collecting infos about all
1110 available CCID readers. Store them and
1111 continue. */
1112 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
1113 *count, rid );
1114 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1115 + strlen (rid) + 1);
1116 if (p)
1118 *p = 0;
1119 if (*rid_list)
1121 strcat (p, *rid_list);
1122 free (*rid_list);
1124 strcat (p, rid);
1125 strcat (p, "\n");
1126 *rid_list = p;
1128 else /* Out of memory. */
1129 free (rid);
1131 rid = NULL;
1132 ++*count;
1134 else if (!*readerno
1135 || (*readerno < 0
1136 && readerid
1137 && !strcmp (readerid, rid)))
1139 /* We found the requested reader. */
1140 if (ifcdesc_extra && ifcdesc_extra_len)
1142 *ifcdesc_extra = malloc (ifcdesc
1143 ->extralen);
1144 if (!*ifcdesc_extra)
1146 usb_close (idev);
1147 free (rid);
1148 return 1; /* Out of core. */
1150 memcpy (*ifcdesc_extra, ifcdesc->extra,
1151 ifcdesc->extralen);
1152 *ifcdesc_extra_len = ifcdesc->extralen;
1155 if (interface_number)
1156 *interface_number = (ifcdesc->bInterfaceNumber);
1158 if (ep_bulk_out)
1159 *ep_bulk_out = find_endpoint (ifcdesc, 0);
1160 if (ep_bulk_in)
1161 *ep_bulk_in = find_endpoint (ifcdesc, 1);
1162 if (ep_intr)
1163 *ep_intr = find_endpoint (ifcdesc, 2);
1165 if (r_dev)
1166 *r_dev = dev;
1167 if (r_rid)
1169 *r_rid = rid;
1170 rid = NULL;
1172 else
1173 free (rid);
1175 *r_idev = idev;
1176 return 1; /* Found requested device. */
1178 else
1180 /* This is not yet the reader we want.
1181 fixme: We should avoid the extra usb_open
1182 in this case. */
1183 if (*readerno >= 0)
1184 --*readerno;
1186 free (rid);
1189 usb_close (idev);
1190 idev = NULL;
1191 return 0;
1197 return 0;
1200 /* Combination function to either scan all CCID devices or to find and
1201 open one specific device.
1203 The function returns 0 if a reader has been found or when a scan
1204 returned without error.
1206 With READERNO = -1 and READERID is NULL, scan mode is used and
1207 R_RID should be the address where to store the list of reader_ids
1208 we found. If on return this list is empty, no CCID device has been
1209 found; otherwise it points to an allocated linked list of reader
1210 IDs. Note that in this mode the function always returns NULL.
1212 With READERNO >= 0 or READERID is not NULL find mode is used. This
1213 uses the same algorithm as the scan mode but stops and returns at
1214 the entry number READERNO and return the handle for the the opened
1215 USB device. If R_RID is not NULL it will receive the reader ID of
1216 that device. If R_DEV is not NULL it will the device pointer of
1217 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
1218 malloced copy of the interfaces "extra: data filed;
1219 IFCDESC_EXTRA_LEN receive the length of this field. If there is
1220 no reader with number READERNO or that reader is not usable by our
1221 implementation NULL will be returned. The caller must close a
1222 returned USB device handle and free (if not passed as NULL) the
1223 returned reader ID info as well as the IFCDESC_EXTRA. On error
1224 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1225 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
1226 the READERID was found.
1228 If R_FD is not -1 on return the device is not using USB for
1229 transport but the device associated with that file descriptor. In
1230 this case INTERFACE will receive the transport type and the other
1231 USB specific return values are not used; the return value is
1232 (void*)(1).
1234 Note that the first entry of the returned reader ID list in scan mode
1235 corresponds with a READERNO of 0 in find mode.
1237 static int
1238 scan_or_find_devices (int readerno, const char *readerid,
1239 char **r_rid,
1240 struct usb_device **r_dev,
1241 unsigned char **ifcdesc_extra,
1242 size_t *ifcdesc_extra_len,
1243 int *interface_number,
1244 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1245 usb_dev_handle **r_idev,
1246 int *r_fd)
1248 char *rid_list = NULL;
1249 int count = 0;
1250 struct usb_bus *busses, *bus;
1251 struct usb_device *dev = NULL;
1252 usb_dev_handle *idev = NULL;
1253 int scan_mode = (readerno == -1 && !readerid);
1254 int i;
1256 /* Set return values to a default. */
1257 if (r_rid)
1258 *r_rid = NULL;
1259 if (r_dev)
1260 *r_dev = NULL;
1261 if (ifcdesc_extra)
1262 *ifcdesc_extra = NULL;
1263 if (ifcdesc_extra_len)
1264 *ifcdesc_extra_len = 0;
1265 if (interface_number)
1266 *interface_number = 0;
1267 if (r_idev)
1268 *r_idev = NULL;
1269 if (r_fd)
1270 *r_fd = -1;
1272 /* See whether we want scan or find mode. */
1273 if (scan_mode)
1275 assert (r_rid);
1278 usb_find_busses();
1279 usb_find_devices();
1281 #ifdef HAVE_USB_GET_BUSSES
1282 busses = usb_get_busses();
1283 #else
1284 busses = usb_busses;
1285 #endif
1287 for (bus = busses; bus; bus = bus->next)
1289 for (dev = bus->devices; dev; dev = dev->next)
1291 if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
1292 readerid,
1293 dev,
1294 r_rid,
1295 r_dev,
1296 &idev,
1297 ifcdesc_extra,
1298 ifcdesc_extra_len,
1299 interface_number,
1300 ep_bulk_out, ep_bulk_in, ep_intr))
1302 /* Found requested device or out of core. */
1303 if (!idev)
1305 free (rid_list);
1306 return -1; /* error */
1308 *r_idev = idev;
1309 return 0;
1314 /* Now check whether there are any devices with special transport types. */
1315 for (i=0; transports[i].name; i++)
1317 int fd;
1318 char *rid, *p;
1320 fd = open (transports[i].name, O_RDWR);
1321 if (fd == -1 && scan_mode && errno == EBUSY)
1323 /* Ignore this error in scan mode because it indicates that
1324 the device exists but is already open (most likely by us)
1325 and thus in general suitable as a reader. */
1327 else if (fd == -1)
1329 DEBUGOUT_2 ("failed to open `%s': %s\n",
1330 transports[i].name, strerror (errno));
1331 continue;
1334 rid = malloc (strlen (transports[i].name) + 30 + 10);
1335 if (!rid)
1337 if (fd != -1)
1338 close (fd);
1339 free (rid_list);
1340 return -1; /* Error. */
1342 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1343 if (scan_mode)
1345 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1346 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1347 if (!p)
1349 if (fd != -1)
1350 close (fd);
1351 free (rid_list);
1352 free (rid);
1353 return -1; /* Error. */
1355 *p = 0;
1356 if (rid_list)
1358 strcat (p, rid_list);
1359 free (rid_list);
1361 strcat (p, rid);
1362 strcat (p, "\n");
1363 rid_list = p;
1364 ++count;
1366 else if (!readerno ||
1367 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1369 /* Found requested device. */
1370 if (interface_number)
1371 *interface_number = transports[i].type;
1372 if (r_rid)
1373 *r_rid = rid;
1374 else
1375 free (rid);
1376 if (r_fd)
1377 *r_fd = fd;
1378 return 0; /* Okay, found device */
1380 else /* This is not yet the reader we want. */
1382 if (readerno >= 0)
1383 --readerno;
1385 free (rid);
1386 if (fd != -1)
1387 close (fd);
1390 if (scan_mode)
1392 *r_rid = rid_list;
1393 return 0;
1395 else
1396 return -1;
1400 /* Set the level of debugging to LEVEL and return the old level. -1
1401 just returns the old level. A level of 0 disables debugging, 1
1402 enables debugging, 2 enables additional tracing of the T=1
1403 protocol, 3 additionally enables debuggng for GetSlotStatus, other
1404 values are not yet defined.
1406 Note that libusb may provide its own debugging feature which is
1407 enabled by setting the envvar USB_DEBUG. */
1409 ccid_set_debug_level (int level)
1411 int old = debug_level;
1412 if (level != -1)
1413 debug_level = level;
1414 return old;
1418 char *
1419 ccid_get_reader_list (void)
1421 char *reader_list;
1423 if (!initialized_usb)
1425 usb_init ();
1426 initialized_usb = 1;
1429 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1430 NULL, NULL, NULL, NULL, NULL))
1431 return NULL; /* Error. */
1432 return reader_list;
1436 /* Open the reader with the internal number READERNO and return a
1437 pointer to be used as handle in HANDLE. Returns 0 on success. */
1438 int
1439 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
1441 int rc = 0;
1442 struct usb_device *dev = NULL;
1443 usb_dev_handle *idev = NULL;
1444 int dev_fd = -1;
1445 char *rid = NULL;
1446 unsigned char *ifcdesc_extra = NULL;
1447 size_t ifcdesc_extra_len;
1448 int readerno;
1449 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1451 *handle = NULL;
1453 if (!initialized_usb)
1455 usb_init ();
1456 initialized_usb = 1;
1459 /* See whether we want to use the reader ID string or a reader
1460 number. A readerno of -1 indicates that the reader ID string is
1461 to be used. */
1462 if (readerid && strchr (readerid, ':'))
1463 readerno = -1; /* We want to use the readerid. */
1464 else if (readerid)
1466 readerno = atoi (readerid);
1467 if (readerno < 0)
1469 DEBUGOUT ("no CCID readers found\n");
1470 rc = CCID_DRIVER_ERR_NO_READER;
1471 goto leave;
1474 else
1475 readerno = 0; /* Default. */
1477 if (scan_or_find_devices (readerno, readerid, &rid, &dev,
1478 &ifcdesc_extra, &ifcdesc_extra_len,
1479 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1480 &idev, &dev_fd) )
1482 if (readerno == -1)
1483 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1484 else
1485 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1486 rc = CCID_DRIVER_ERR_NO_READER;
1487 goto leave;
1490 /* Okay, this is a CCID reader. */
1491 *handle = calloc (1, sizeof **handle);
1492 if (!*handle)
1494 DEBUGOUT ("out of memory\n");
1495 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1496 goto leave;
1498 (*handle)->rid = rid;
1499 if (idev) /* Regular USB transport. */
1501 (*handle)->idev = idev;
1502 (*handle)->dev_fd = -1;
1503 (*handle)->id_vendor = dev->descriptor.idVendor;
1504 (*handle)->id_product = dev->descriptor.idProduct;
1505 (*handle)->bcd_device = dev->descriptor.bcdDevice;
1506 (*handle)->ifc_no = ifc_no;
1507 (*handle)->ep_bulk_out = ep_bulk_out;
1508 (*handle)->ep_bulk_in = ep_bulk_in;
1509 (*handle)->ep_intr = ep_intr;
1511 else if (dev_fd != -1) /* Device transport. */
1513 (*handle)->idev = NULL;
1514 (*handle)->dev_fd = dev_fd;
1515 (*handle)->id_vendor = 0; /* Magic vendor for special transport. */
1516 (*handle)->id_product = ifc_no; /* Transport type */
1517 prepare_special_transport (*handle);
1519 else
1521 assert (!"no transport"); /* Bug. */
1524 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1526 if (idev)
1528 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1530 DEBUGOUT ("device not supported\n");
1531 rc = CCID_DRIVER_ERR_NO_READER;
1532 goto leave;
1535 rc = usb_claim_interface (idev, ifc_no);
1536 if (rc)
1538 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1539 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1540 goto leave;
1544 leave:
1545 free (ifcdesc_extra);
1546 if (rc)
1548 free (rid);
1549 if (idev)
1550 usb_close (idev);
1551 if (dev_fd != -1)
1552 close (dev_fd);
1553 free (*handle);
1554 *handle = NULL;
1557 return rc;
1561 static void
1562 do_close_reader (ccid_driver_t handle)
1564 int rc;
1565 unsigned char msg[100];
1566 size_t msglen;
1567 unsigned char seqno;
1569 if (!handle->powered_off)
1571 msg[0] = PC_to_RDR_IccPowerOff;
1572 msg[5] = 0; /* slot */
1573 msg[6] = seqno = handle->seqno++;
1574 msg[7] = 0; /* RFU */
1575 msg[8] = 0; /* RFU */
1576 msg[9] = 0; /* RFU */
1577 set_msg_len (msg, 0);
1578 msglen = 10;
1580 rc = bulk_out (handle, msg, msglen, 0);
1581 if (!rc)
1582 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1583 seqno, 2000, 0);
1584 handle->powered_off = 1;
1586 if (handle->idev)
1588 usb_release_interface (handle->idev, handle->ifc_no);
1589 usb_close (handle->idev);
1590 handle->idev = NULL;
1592 if (handle->dev_fd != -1)
1594 close (handle->dev_fd);
1595 handle->dev_fd = -1;
1600 /* Reset a reader on HANDLE. This is useful in case a reader has been
1601 plugged of and inserted at a different port. By resetting the
1602 handle, the same reader will be get used. Note, that on error the
1603 handle won't get released.
1605 This does not return an ATR, so ccid_get_atr should be called right
1606 after this one.
1608 int
1609 ccid_shutdown_reader (ccid_driver_t handle)
1611 int rc = 0;
1612 struct usb_device *dev = NULL;
1613 usb_dev_handle *idev = NULL;
1614 unsigned char *ifcdesc_extra = NULL;
1615 size_t ifcdesc_extra_len;
1616 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1618 if (!handle || !handle->rid)
1619 return CCID_DRIVER_ERR_INV_VALUE;
1621 do_close_reader (handle);
1623 if (scan_or_find_devices (-1, handle->rid, NULL, &dev,
1624 &ifcdesc_extra, &ifcdesc_extra_len,
1625 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1626 &idev, NULL) || !idev)
1628 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1629 return CCID_DRIVER_ERR_NO_READER;
1632 if (idev)
1634 handle->idev = idev;
1635 handle->ifc_no = ifc_no;
1636 handle->ep_bulk_out = ep_bulk_out;
1637 handle->ep_bulk_in = ep_bulk_in;
1638 handle->ep_intr = ep_intr;
1640 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1642 DEBUGOUT ("device not supported\n");
1643 rc = CCID_DRIVER_ERR_NO_READER;
1644 goto leave;
1647 rc = usb_claim_interface (idev, ifc_no);
1648 if (rc)
1650 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1651 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1652 goto leave;
1656 leave:
1657 free (ifcdesc_extra);
1658 if (rc)
1660 if (handle->idev)
1661 usb_close (handle->idev);
1662 handle->idev = NULL;
1663 if (handle->dev_fd != -1)
1664 close (handle->dev_fd);
1665 handle->dev_fd = -1;
1668 return rc;
1673 /* Close the reader HANDLE. */
1674 int
1675 ccid_close_reader (ccid_driver_t handle)
1677 if (!handle || (!handle->idev && handle->dev_fd == -1))
1678 return 0;
1680 do_close_reader (handle);
1681 free (handle->rid);
1682 free (handle);
1683 return 0;
1687 /* Return False if a card is present and powered. */
1689 ccid_check_card_presence (ccid_driver_t handle)
1691 (void)handle; /* Not yet implemented. */
1692 return -1;
1696 /* Write NBYTES of BUF to file descriptor FD. */
1697 static int
1698 writen (int fd, const void *buf, size_t nbytes)
1700 size_t nleft = nbytes;
1701 int nwritten;
1703 while (nleft > 0)
1705 nwritten = write (fd, buf, nleft);
1706 if (nwritten < 0)
1708 if (errno == EINTR)
1709 nwritten = 0;
1710 else
1711 return -1;
1713 nleft -= nwritten;
1714 buf = (const char*)buf + nwritten;
1717 return 0;
1721 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1722 Returns 0 on success. */
1723 static int
1724 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1725 int no_debug)
1727 int rc;
1729 if (debug_level && (!no_debug || debug_level >= 3))
1731 switch (msglen? msg[0]:0)
1733 case PC_to_RDR_IccPowerOn:
1734 print_p2r_iccpoweron (msg, msglen);
1735 break;
1736 case PC_to_RDR_IccPowerOff:
1737 print_p2r_iccpoweroff (msg, msglen);
1738 break;
1739 case PC_to_RDR_GetSlotStatus:
1740 print_p2r_getslotstatus (msg, msglen);
1741 break;
1742 case PC_to_RDR_XfrBlock:
1743 print_p2r_xfrblock (msg, msglen);
1744 break;
1745 case PC_to_RDR_GetParameters:
1746 print_p2r_getparameters (msg, msglen);
1747 break;
1748 case PC_to_RDR_ResetParameters:
1749 print_p2r_resetparameters (msg, msglen);
1750 break;
1751 case PC_to_RDR_SetParameters:
1752 print_p2r_setparameters (msg, msglen);
1753 break;
1754 case PC_to_RDR_Escape:
1755 print_p2r_escape (msg, msglen);
1756 break;
1757 case PC_to_RDR_IccClock:
1758 print_p2r_iccclock (msg, msglen);
1759 break;
1760 case PC_to_RDR_T0APDU:
1761 print_p2r_to0apdu (msg, msglen);
1762 break;
1763 case PC_to_RDR_Secure:
1764 print_p2r_secure (msg, msglen);
1765 break;
1766 case PC_to_RDR_Mechanical:
1767 print_p2r_mechanical (msg, msglen);
1768 break;
1769 case PC_to_RDR_Abort:
1770 print_p2r_abort (msg, msglen);
1771 break;
1772 case PC_to_RDR_SetDataRate:
1773 print_p2r_setdatarate (msg, msglen);
1774 break;
1775 default:
1776 print_p2r_unknown (msg, msglen);
1777 break;
1781 if (handle->idev)
1783 rc = usb_bulk_write (handle->idev,
1784 handle->ep_bulk_out,
1785 (char*)msg, msglen,
1786 5000 /* ms timeout */);
1787 if (rc == msglen)
1788 return 0;
1789 if (rc == -1)
1790 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1791 else
1792 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1794 else
1796 rc = writen (handle->dev_fd, msg, msglen);
1797 if (!rc)
1798 return 0;
1799 DEBUGOUT_2 ("writen to %d failed: %s\n",
1800 handle->dev_fd, strerror (errno));
1803 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1807 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1808 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1809 is the sequence number used to send the request and EXPECTED_TYPE
1810 the type of message we expect. Does checks on the ccid
1811 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1812 avoid debug messages in case of no error; this can be overriden
1813 with a glibal debug level of at least 3. Returns 0 on success. */
1814 static int
1815 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1816 size_t *nread, int expected_type, int seqno, int timeout,
1817 int no_debug)
1819 int rc;
1820 size_t msglen;
1821 int eagain_retries = 0;
1823 /* Fixme: The next line for the current Valgrind without support
1824 for USB IOCTLs. */
1825 memset (buffer, 0, length);
1826 retry:
1827 if (handle->idev)
1829 rc = usb_bulk_read (handle->idev,
1830 handle->ep_bulk_in,
1831 (char*)buffer, length,
1832 timeout);
1833 if (rc < 0)
1835 rc = errno;
1836 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (rc));
1837 if (rc == EAGAIN && eagain_retries++ < 3)
1839 #ifndef TEST
1840 gnupg_sleep (1);
1841 #endif
1842 goto retry;
1844 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1846 *nread = msglen = rc;
1848 else
1850 rc = read (handle->dev_fd, buffer, length);
1851 if (rc < 0)
1853 rc = errno;
1854 DEBUGOUT_2 ("read from %d failed: %s\n",
1855 handle->dev_fd, strerror (rc));
1856 if (rc == EAGAIN && eagain_retries++ < 5)
1858 #ifndef TEST
1859 gnupg_sleep (1);
1860 #endif
1861 goto retry;
1863 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1865 *nread = msglen = rc;
1867 eagain_retries = 0;
1869 if (msglen < 10)
1871 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1872 abort_cmd (handle, seqno);
1873 return CCID_DRIVER_ERR_INV_VALUE;
1875 if (buffer[5] != 0)
1877 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1878 return CCID_DRIVER_ERR_INV_VALUE;
1880 if (buffer[6] != seqno)
1882 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1883 seqno, buffer[6]);
1884 /* Retry until we are synced again. */
1885 goto retry;
1888 /* We need to handle the time extension request before we check that
1889 we got the expected message type. This is in particular required
1890 for the Cherry keyboard which sends a time extension request for
1891 each key hit. */
1892 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1894 /* Card present and active, time extension requested. */
1895 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1896 buffer[7], buffer[8]);
1897 goto retry;
1900 if (buffer[0] != expected_type)
1902 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1903 abort_cmd (handle, seqno);
1904 return CCID_DRIVER_ERR_INV_VALUE;
1907 if (debug_level && (!no_debug || debug_level >= 3))
1909 switch (buffer[0])
1911 case RDR_to_PC_DataBlock:
1912 print_r2p_datablock (buffer, msglen);
1913 break;
1914 case RDR_to_PC_SlotStatus:
1915 print_r2p_slotstatus (buffer, msglen);
1916 break;
1917 case RDR_to_PC_Parameters:
1918 print_r2p_parameters (buffer, msglen);
1919 break;
1920 case RDR_to_PC_Escape:
1921 print_r2p_escape (buffer, msglen);
1922 break;
1923 case RDR_to_PC_DataRate:
1924 print_r2p_datarate (buffer, msglen);
1925 break;
1926 default:
1927 print_r2p_unknown (buffer, msglen);
1928 break;
1931 if (CCID_COMMAND_FAILED (buffer))
1932 print_command_failed (buffer);
1934 /* Check whether a card is at all available. Note: If you add new
1935 error codes here, check whether they need to be ignored in
1936 send_escape_cmd. */
1937 switch ((buffer[7] & 0x03))
1939 case 0: /* no error */ break;
1940 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
1941 case 2: return CCID_DRIVER_ERR_NO_CARD;
1942 case 3: /* RFU */ break;
1944 return 0;
1949 /* Send an abort sequence and wait until everything settled. */
1950 static int
1951 abort_cmd (ccid_driver_t handle, int seqno)
1953 int rc;
1954 char dummybuf[8];
1955 unsigned char msg[100];
1956 size_t msglen;
1958 if (!handle->idev)
1960 /* I don't know how to send an abort to non-USB devices. */
1961 rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
1964 seqno &= 0xff;
1965 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
1966 /* Send the abort command to the control pipe. Note that we don't
1967 need to keep track of sent abort commands because there should
1968 never be another thread using the same slot concurrently. */
1969 rc = usb_control_msg (handle->idev,
1970 0x21,/* bmRequestType: host-to-device,
1971 class specific, to interface. */
1972 1, /* ABORT */
1973 (seqno << 8 | 0 /* slot */),
1974 handle->ifc_no,
1975 dummybuf, 0,
1976 1000 /* ms timeout */);
1977 if (rc < 0)
1979 DEBUGOUT_1 ("usb_control_msg error: %s\n", strerror (errno));
1980 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1983 /* Now send the abort command to the bulk out pipe using the same
1984 SEQNO and SLOT. Do this in a loop to so that all seqno are
1985 tried. */
1986 seqno--; /* Adjust for next increment. */
1989 seqno++;
1990 msg[0] = PC_to_RDR_Abort;
1991 msg[5] = 0; /* slot */
1992 msg[6] = seqno;
1993 msg[7] = 0; /* RFU */
1994 msg[8] = 0; /* RFU */
1995 msg[9] = 0; /* RFU */
1996 msglen = 10;
1997 set_msg_len (msg, 0);
1999 rc = usb_bulk_write (handle->idev,
2000 handle->ep_bulk_out,
2001 (char*)msg, msglen,
2002 5000 /* ms timeout */);
2003 if (rc == msglen)
2004 rc = 0;
2005 else if (rc == -1)
2006 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2007 strerror (errno));
2008 else
2009 DEBUGOUT_1 ("usb_bulk_write failed in abort_cmd: %d\n", rc);
2011 if (rc)
2012 return rc;
2014 rc = usb_bulk_read (handle->idev,
2015 handle->ep_bulk_in,
2016 (char*)msg, sizeof msg,
2017 5000 /*ms timeout*/);
2018 if (rc < 0)
2020 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2021 strerror (errno));
2022 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2024 msglen = rc;
2026 if (msglen < 10)
2028 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2029 (unsigned int)msglen);
2030 return CCID_DRIVER_ERR_INV_VALUE;
2032 if (msg[5] != 0)
2034 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2035 return CCID_DRIVER_ERR_INV_VALUE;
2038 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2039 msg[7], msg[8], msg[9]);
2040 if (CCID_COMMAND_FAILED (msg))
2041 print_command_failed (msg);
2043 while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2045 handle->seqno = ((seqno + 1) & 0xff);
2046 DEBUGOUT ("sending abort sequence succeeded\n");
2048 return 0;
2052 /* Note that this function won't return the error codes NO_CARD or
2053 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2054 operation will get returned in RESULT and its length in RESULTLEN.
2055 If the response is larger than RESULTMAX, an error is returned and
2056 the required buffer length returned in RESULTLEN. */
2057 static int
2058 send_escape_cmd (ccid_driver_t handle,
2059 const unsigned char *data, size_t datalen,
2060 unsigned char *result, size_t resultmax, size_t *resultlen)
2062 int rc;
2063 unsigned char msg[100];
2064 size_t msglen;
2065 unsigned char seqno;
2067 if (resultlen)
2068 *resultlen = 0;
2070 if (datalen > sizeof msg - 10)
2071 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2073 msg[0] = PC_to_RDR_Escape;
2074 msg[5] = 0; /* slot */
2075 msg[6] = seqno = handle->seqno++;
2076 msg[7] = 0; /* RFU */
2077 msg[8] = 0; /* RFU */
2078 msg[9] = 0; /* RFU */
2079 memcpy (msg+10, data, datalen);
2080 msglen = 10 + datalen;
2081 set_msg_len (msg, datalen);
2083 rc = bulk_out (handle, msg, msglen, 0);
2084 if (rc)
2085 return rc;
2086 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2087 seqno, 5000, 0);
2088 if (result)
2089 switch (rc)
2091 /* We need to ignore certain errorcode here. */
2092 case 0:
2093 case CCID_DRIVER_ERR_CARD_INACTIVE:
2094 case CCID_DRIVER_ERR_NO_CARD:
2096 if (msglen > resultmax)
2097 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2098 else
2100 memcpy (result, msg, msglen);
2101 *resultlen = msglen;
2103 rc = 0;
2105 break;
2106 default:
2107 break;
2110 return rc;
2115 ccid_transceive_escape (ccid_driver_t handle,
2116 const unsigned char *data, size_t datalen,
2117 unsigned char *resp, size_t maxresplen, size_t *nresp)
2119 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2124 /* experimental */
2126 ccid_poll (ccid_driver_t handle)
2128 int rc;
2129 unsigned char msg[10];
2130 size_t msglen;
2131 int i, j;
2133 if (handle->idev)
2135 rc = usb_bulk_read (handle->idev,
2136 handle->ep_intr,
2137 (char*)msg, sizeof msg,
2138 0 /* ms timeout */ );
2139 if (rc < 0 && errno == ETIMEDOUT)
2140 return 0;
2142 else
2143 return 0;
2145 if (rc < 0)
2147 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
2148 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2151 msglen = rc;
2152 rc = 0;
2154 if (msglen < 1)
2156 DEBUGOUT ("intr-in msg too short\n");
2157 return CCID_DRIVER_ERR_INV_VALUE;
2160 if (msg[0] == RDR_to_PC_NotifySlotChange)
2162 DEBUGOUT ("notify slot change:");
2163 for (i=1; i < msglen; i++)
2164 for (j=0; j < 4; j++)
2165 DEBUGOUT_CONT_3 (" %d:%c%c",
2166 (i-1)*4+j,
2167 (msg[i] & (1<<(j*2)))? 'p':'-',
2168 (msg[i] & (2<<(j*2)))? '*':' ');
2169 DEBUGOUT_LF ();
2171 else if (msg[0] == RDR_to_PC_HardwareError)
2173 DEBUGOUT ("hardware error occured\n");
2175 else
2177 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2180 return 0;
2184 /* Note that this function won't return the error codes NO_CARD or
2185 CARD_INACTIVE */
2186 int
2187 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2189 int rc;
2190 unsigned char msg[100];
2191 size_t msglen;
2192 unsigned char seqno;
2193 int retries = 0;
2195 retry:
2196 msg[0] = PC_to_RDR_GetSlotStatus;
2197 msg[5] = 0; /* slot */
2198 msg[6] = seqno = handle->seqno++;
2199 msg[7] = 0; /* RFU */
2200 msg[8] = 0; /* RFU */
2201 msg[9] = 0; /* RFU */
2202 set_msg_len (msg, 0);
2204 rc = bulk_out (handle, msg, 10, 1);
2205 if (rc)
2206 return rc;
2207 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2208 get cluttered up by a ticker function checking for the slot
2209 status and debugging enabled. */
2210 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2211 seqno, retries? 1000 : 200, 1);
2212 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2214 if (!retries)
2216 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2217 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2218 usb_clear_halt (handle->idev, handle->ep_bulk_out);
2220 else
2221 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2222 retries++;
2223 goto retry;
2225 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2226 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2227 return rc;
2228 *statusbits = (msg[7] & 3);
2230 return 0;
2234 /* Return the ATR of the card. This is not a cached value and thus an
2235 actual reset is done. */
2236 int
2237 ccid_get_atr (ccid_driver_t handle,
2238 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2240 int rc;
2241 int statusbits;
2242 unsigned char msg[100];
2243 unsigned char *tpdu;
2244 size_t msglen, tpdulen;
2245 unsigned char seqno;
2246 int use_crc = 0;
2247 unsigned int edc;
2248 int tried_iso = 0;
2249 int got_param;
2251 /* First check whether a card is available. */
2252 rc = ccid_slot_status (handle, &statusbits);
2253 if (rc)
2254 return rc;
2255 if (statusbits == 2)
2256 return CCID_DRIVER_ERR_NO_CARD;
2258 /* For an inactive and also for an active card, issue the PowerOn
2259 command to get the ATR. */
2260 again:
2261 msg[0] = PC_to_RDR_IccPowerOn;
2262 msg[5] = 0; /* slot */
2263 msg[6] = seqno = handle->seqno++;
2264 msg[7] = 0; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2265 msg[8] = 0; /* RFU */
2266 msg[9] = 0; /* RFU */
2267 set_msg_len (msg, 0);
2268 msglen = 10;
2270 rc = bulk_out (handle, msg, msglen, 0);
2271 if (rc)
2272 return rc;
2273 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2274 seqno, 5000, 0);
2275 if (rc)
2276 return rc;
2277 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2278 && ((handle->id_vendor == VENDOR_CHERRY
2279 && handle->id_product == 0x0005)
2280 || (handle->id_vendor == VENDOR_GEMPC
2281 && handle->id_product == 0x4433)
2284 tried_iso = 1;
2285 /* Try switching to ISO mode. */
2286 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2287 NULL, 0, NULL))
2288 goto again;
2290 else if (CCID_COMMAND_FAILED (msg))
2291 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2294 handle->powered_off = 0;
2296 if (atr)
2298 size_t n = msglen - 10;
2300 if (n > maxatrlen)
2301 n = maxatrlen;
2302 memcpy (atr, msg+10, n);
2303 *atrlen = n;
2306 got_param = 0;
2307 msg[0] = PC_to_RDR_GetParameters;
2308 msg[5] = 0; /* slot */
2309 msg[6] = seqno = handle->seqno++;
2310 msg[7] = 0; /* RFU */
2311 msg[8] = 0; /* RFU */
2312 msg[9] = 0; /* RFU */
2313 set_msg_len (msg, 0);
2314 msglen = 10;
2315 rc = bulk_out (handle, msg, msglen, 0);
2316 if (!rc)
2317 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2318 seqno, 2000, 0);
2319 if (rc)
2320 DEBUGOUT ("GetParameters failed\n");
2321 else if (msglen == 17 && msg[9] == 1)
2322 got_param = 1;
2324 /* Setup parameters to select T=1. */
2325 msg[0] = PC_to_RDR_SetParameters;
2326 msg[5] = 0; /* slot */
2327 msg[6] = seqno = handle->seqno++;
2328 msg[7] = 1; /* Select T=1. */
2329 msg[8] = 0; /* RFU */
2330 msg[9] = 0; /* RFU */
2332 if (!got_param)
2334 /* FIXME: Get those values from the ATR. */
2335 msg[10]= 0x01; /* Fi/Di */
2336 msg[11]= 0x10; /* LRC, direct convention. */
2337 msg[12]= 0; /* Extra guardtime. */
2338 msg[13]= 0x41; /* BWI/CWI */
2339 msg[14]= 0; /* No clock stoppping. */
2340 msg[15]= 254; /* IFSC */
2341 msg[16]= 0; /* Does not support non default NAD values. */
2343 set_msg_len (msg, 7);
2344 msglen = 10 + 7;
2346 rc = bulk_out (handle, msg, msglen, 0);
2347 if (rc)
2348 return rc;
2349 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2350 seqno, 5000, 0);
2351 if (rc)
2352 DEBUGOUT ("SetParameters failed (ignored)\n");
2354 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2355 handle->ifsc = msg[15];
2356 else
2357 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2359 handle->t1_ns = 0;
2360 handle->t1_nr = 0;
2362 /* Send an S-Block with our maximum IFSD to the CCID. */
2363 if (!handle->apdu_level && !handle->auto_ifsd)
2365 tpdu = msg+10;
2366 /* NAD: DAD=1, SAD=0 */
2367 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2368 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2369 tpdu[2] = 1;
2370 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2371 tpdulen = 4;
2372 edc = compute_edc (tpdu, tpdulen, use_crc);
2373 if (use_crc)
2374 tpdu[tpdulen++] = (edc >> 8);
2375 tpdu[tpdulen++] = edc;
2377 msg[0] = PC_to_RDR_XfrBlock;
2378 msg[5] = 0; /* slot */
2379 msg[6] = seqno = handle->seqno++;
2380 msg[7] = 0;
2381 msg[8] = 0; /* RFU */
2382 msg[9] = 0; /* RFU */
2383 set_msg_len (msg, tpdulen);
2384 msglen = 10 + tpdulen;
2386 if (debug_level > 1)
2387 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2388 ((msg[11] & 0xc0) == 0x80)? 'R' :
2389 (msg[11] & 0x80)? 'S' : 'I',
2390 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2391 : !!(msg[11] & 0x40)),
2392 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2394 rc = bulk_out (handle, msg, msglen, 0);
2395 if (rc)
2396 return rc;
2399 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2400 RDR_to_PC_DataBlock, seqno, 5000, 0);
2401 if (rc)
2402 return rc;
2404 tpdu = msg + 10;
2405 tpdulen = msglen - 10;
2407 if (tpdulen < 4)
2408 return CCID_DRIVER_ERR_ABORTED;
2410 if (debug_level > 1)
2411 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2412 ((msg[11] & 0xc0) == 0x80)? 'R' :
2413 (msg[11] & 0x80)? 'S' : 'I',
2414 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2415 : !!(msg[11] & 0x40)),
2416 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2417 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2419 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2421 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2422 return -1;
2424 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2427 return 0;
2433 static unsigned int
2434 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2436 if (use_crc)
2438 return 0x42; /* Not yet implemented. */
2440 else
2442 unsigned char crc = 0;
2444 for (; datalen; datalen--)
2445 crc ^= *data++;
2446 return crc;
2451 /* Return true if APDU is an extended length one. */
2452 static int
2453 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2455 if (apdulen < 7 || apdu[4])
2456 return 0; /* Too short or no Z byte. */
2457 return 1;
2461 /* Helper for ccid_transceive used for APDU level exchanges. */
2462 static int
2463 ccid_transceive_apdu_level (ccid_driver_t handle,
2464 const unsigned char *apdu_buf, size_t apdu_buflen,
2465 unsigned char *resp, size_t maxresplen,
2466 size_t *nresp)
2468 int rc;
2469 unsigned char send_buffer[10+261+300], recv_buffer[10+261+300];
2470 const unsigned char *apdu;
2471 size_t apdulen;
2472 unsigned char *msg;
2473 size_t msglen;
2474 unsigned char seqno;
2475 int bwi = 4;
2477 msg = send_buffer;
2479 apdu = apdu_buf;
2480 apdulen = apdu_buflen;
2481 assert (apdulen);
2483 /* The maximum length for a short APDU T=1 block is 261. For an
2484 extended APDU T=1 block the maximum length 65544; however
2485 extended APDU exchange level is not yet supported. */
2486 if (apdulen > 261)
2487 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2489 msg[0] = PC_to_RDR_XfrBlock;
2490 msg[5] = 0; /* slot */
2491 msg[6] = seqno = handle->seqno++;
2492 msg[7] = bwi; /* bBWI */
2493 msg[8] = 0; /* RFU */
2494 msg[9] = 0; /* RFU */
2495 memcpy (msg+10, apdu, apdulen);
2496 set_msg_len (msg, apdulen);
2497 msglen = 10 + apdulen;
2499 rc = bulk_out (handle, msg, msglen, 0);
2500 if (rc)
2501 return rc;
2503 msg = recv_buffer;
2504 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2505 RDR_to_PC_DataBlock, seqno, 5000, 0);
2506 if (rc)
2507 return rc;
2509 apdu = msg + 10;
2510 apdulen = msglen - 10;
2512 if (resp)
2514 if (apdulen > maxresplen)
2516 DEBUGOUT_2 ("provided buffer too short for received data "
2517 "(%u/%u)\n",
2518 (unsigned int)apdulen, (unsigned int)maxresplen);
2519 return CCID_DRIVER_ERR_INV_VALUE;
2522 memcpy (resp, apdu, apdulen);
2523 *nresp = apdulen;
2526 return 0;
2532 Protocol T=1 overview
2534 Block Structure:
2535 Prologue Field:
2536 1 byte Node Address (NAD)
2537 1 byte Protocol Control Byte (PCB)
2538 1 byte Length (LEN)
2539 Information Field:
2540 0-254 byte APDU or Control Information (INF)
2541 Epilogue Field:
2542 1 byte Error Detection Code (EDC)
2544 NAD:
2545 bit 7 unused
2546 bit 4..6 Destination Node Address (DAD)
2547 bit 3 unused
2548 bit 2..0 Source Node Address (SAD)
2550 If node adresses are not used, SAD and DAD should be set to 0 on
2551 the first block sent to the card. If they are used they should
2552 have different values (0 for one is okay); that first block sets up
2553 the addresses of the nodes.
2555 PCB:
2556 Information Block (I-Block):
2557 bit 7 0
2558 bit 6 Sequence number (yep, that is modulo 2)
2559 bit 5 Chaining flag
2560 bit 4..0 reserved
2561 Received-Ready Block (R-Block):
2562 bit 7 1
2563 bit 6 0
2564 bit 5 0
2565 bit 4 Sequence number
2566 bit 3..0 0 = no error
2567 1 = EDC or parity error
2568 2 = other error
2569 other values are reserved
2570 Supervisory Block (S-Block):
2571 bit 7 1
2572 bit 6 1
2573 bit 5 clear=request,set=response
2574 bit 4..0 0 = resyncronisation request
2575 1 = information field size request
2576 2 = abort request
2577 3 = extension of BWT request
2578 4 = VPP error
2579 other values are reserved
2584 ccid_transceive (ccid_driver_t handle,
2585 const unsigned char *apdu_buf, size_t apdu_buflen,
2586 unsigned char *resp, size_t maxresplen, size_t *nresp)
2588 int rc;
2589 /* The size of the buffer used to be 10+259. For the via_escape
2590 hack we need one extra byte, thus 11+259. */
2591 unsigned char send_buffer[11+259], recv_buffer[11+259];
2592 const unsigned char *apdu;
2593 size_t apdulen;
2594 unsigned char *msg, *tpdu, *p;
2595 size_t msglen, tpdulen, last_tpdulen, n;
2596 unsigned char seqno;
2597 unsigned int edc;
2598 int use_crc = 0;
2599 int hdrlen, pcboff;
2600 size_t dummy_nresp;
2601 int via_escape = 0;
2602 int next_chunk = 1;
2603 int sending = 1;
2604 int retries = 0;
2605 int resyncing = 0;
2606 int nad_byte;
2608 if (!nresp)
2609 nresp = &dummy_nresp;
2610 *nresp = 0;
2612 /* Smarter readers allow to send APDUs directly; divert here. */
2613 if (handle->apdu_level)
2615 /* We employ a hack for Omnikey readers which are able to send
2616 TPDUs using an escape sequence. There is no documentation
2617 but the Windows driver does it this way. Tested using a
2618 CM6121. This method works also for the Cherry XX44
2619 keyboards; however there are problems with the
2620 ccid_tranceive_secure which leads to a loss of sync on the
2621 CCID level. If Cherry wants to make their keyboard work
2622 again, they should hand over some docs. */
2623 if ((handle->id_vendor == VENDOR_OMNIKEY
2624 || (!handle->idev && handle->id_product == TRANSPORT_CM4040))
2625 && handle->apdu_level < 2
2626 && is_exlen_apdu (apdu_buf, apdu_buflen))
2627 via_escape = 1;
2628 else
2629 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
2630 resp, maxresplen, nresp);
2633 /* The other readers we support require sending TPDUs. */
2635 tpdulen = 0; /* Avoid compiler warning about no initialization. */
2636 msg = send_buffer;
2637 hdrlen = via_escape? 11 : 10;
2639 /* NAD: DAD=1, SAD=0 */
2640 nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
2641 if (via_escape)
2642 nad_byte = 0;
2644 last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */
2645 for (;;)
2647 if (next_chunk)
2649 next_chunk = 0;
2651 apdu = apdu_buf;
2652 apdulen = apdu_buflen;
2653 assert (apdulen);
2655 /* Construct an I-Block. */
2656 tpdu = msg + hdrlen;
2657 tpdu[0] = nad_byte;
2658 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
2659 if (apdulen > handle->ifsc )
2661 apdulen = handle->ifsc;
2662 apdu_buf += handle->ifsc;
2663 apdu_buflen -= handle->ifsc;
2664 tpdu[1] |= (1 << 5); /* Set more bit. */
2666 tpdu[2] = apdulen;
2667 memcpy (tpdu+3, apdu, apdulen);
2668 tpdulen = 3 + apdulen;
2669 edc = compute_edc (tpdu, tpdulen, use_crc);
2670 if (use_crc)
2671 tpdu[tpdulen++] = (edc >> 8);
2672 tpdu[tpdulen++] = edc;
2675 if (via_escape)
2677 msg[0] = PC_to_RDR_Escape;
2678 msg[5] = 0; /* slot */
2679 msg[6] = seqno = handle->seqno++;
2680 msg[7] = 0; /* RFU */
2681 msg[8] = 0; /* RFU */
2682 msg[9] = 0; /* RFU */
2683 msg[10] = 0x1a; /* Omnikey command to send a TPDU. */
2684 set_msg_len (msg, 1 + tpdulen);
2686 else
2688 msg[0] = PC_to_RDR_XfrBlock;
2689 msg[5] = 0; /* slot */
2690 msg[6] = seqno = handle->seqno++;
2691 msg[7] = 4; /* bBWI */
2692 msg[8] = 0; /* RFU */
2693 msg[9] = 0; /* RFU */
2694 set_msg_len (msg, tpdulen);
2696 msglen = hdrlen + tpdulen;
2697 if (!resyncing)
2698 last_tpdulen = tpdulen;
2699 pcboff = hdrlen+1;
2701 if (debug_level > 1)
2702 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2703 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
2704 (msg[pcboff] & 0x80)? 'S' : 'I',
2705 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
2706 : !!(msg[pcboff] & 0x40)),
2707 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
2708 " [more]":""));
2710 rc = bulk_out (handle, msg, msglen, 0);
2711 if (rc)
2712 return rc;
2714 msg = recv_buffer;
2715 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2716 via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock,
2717 seqno, 5000, 0);
2718 if (rc)
2719 return rc;
2721 tpdu = msg + hdrlen;
2722 tpdulen = msglen - hdrlen;
2723 resyncing = 0;
2725 if (tpdulen < 4)
2727 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2728 return CCID_DRIVER_ERR_ABORTED;
2731 if (debug_level > 1)
2732 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2733 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
2734 (msg[pcboff] & 0x80)? 'S' : 'I',
2735 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
2736 : !!(msg[pcboff] & 0x40)),
2737 ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
2738 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
2739 " [more]":""));
2741 if (!(tpdu[1] & 0x80))
2742 { /* This is an I-block. */
2743 retries = 0;
2744 if (sending)
2745 { /* last block sent was successful. */
2746 handle->t1_ns ^= 1;
2747 sending = 0;
2750 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2751 { /* Reponse does not match our sequence number. */
2752 msg = send_buffer;
2753 tpdu = msg + hdrlen;
2754 tpdu[0] = nad_byte;
2755 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
2756 tpdu[2] = 0;
2757 tpdulen = 3;
2758 edc = compute_edc (tpdu, tpdulen, use_crc);
2759 if (use_crc)
2760 tpdu[tpdulen++] = (edc >> 8);
2761 tpdu[tpdulen++] = edc;
2763 continue;
2766 handle->t1_nr ^= 1;
2768 p = tpdu + 3; /* Skip the prologue field. */
2769 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2770 /* fixme: verify the checksum. */
2771 if (resp)
2773 if (n > maxresplen)
2775 DEBUGOUT_2 ("provided buffer too short for received data "
2776 "(%u/%u)\n",
2777 (unsigned int)n, (unsigned int)maxresplen);
2778 return CCID_DRIVER_ERR_INV_VALUE;
2781 memcpy (resp, p, n);
2782 resp += n;
2783 *nresp += n;
2784 maxresplen -= n;
2787 if (!(tpdu[1] & 0x20))
2788 return 0; /* No chaining requested - ready. */
2790 msg = send_buffer;
2791 tpdu = msg + hdrlen;
2792 tpdu[0] = nad_byte;
2793 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
2794 tpdu[2] = 0;
2795 tpdulen = 3;
2796 edc = compute_edc (tpdu, tpdulen, use_crc);
2797 if (use_crc)
2798 tpdu[tpdulen++] = (edc >> 8);
2799 tpdu[tpdulen++] = edc;
2801 else if ((tpdu[1] & 0xc0) == 0x80)
2802 { /* This is a R-block. */
2803 if ( (tpdu[1] & 0x0f))
2805 retries++;
2806 if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
2808 /* Error probably due to switching to TPDU. Send a
2809 resync request. We use the recv_buffer so that
2810 we don't corrupt the send_buffer. */
2811 msg = recv_buffer;
2812 tpdu = msg + hdrlen;
2813 tpdu[0] = nad_byte;
2814 tpdu[1] = 0xc0; /* S-block resync request. */
2815 tpdu[2] = 0;
2816 tpdulen = 3;
2817 edc = compute_edc (tpdu, tpdulen, use_crc);
2818 if (use_crc)
2819 tpdu[tpdulen++] = (edc >> 8);
2820 tpdu[tpdulen++] = edc;
2821 resyncing = 1;
2822 DEBUGOUT ("T=1: requesting resync\n");
2824 else if (retries > 3)
2826 DEBUGOUT ("T=1: 3 failed retries\n");
2827 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2829 else
2831 /* Error: repeat last block */
2832 msg = send_buffer;
2833 tpdulen = last_tpdulen;
2836 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
2837 { /* Response does not match our sequence number. */
2838 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2839 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2841 else if (sending)
2842 { /* Send next chunk. */
2843 retries = 0;
2844 msg = send_buffer;
2845 next_chunk = 1;
2846 handle->t1_ns ^= 1;
2848 else
2850 DEBUGOUT ("unexpected ACK R-block received\n");
2851 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2854 else
2855 { /* This is a S-block. */
2856 retries = 0;
2857 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
2858 (tpdu[1] & 0x20)? "response": "request",
2859 (tpdu[1] & 0x1f));
2860 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
2862 /* Information field size request. */
2863 unsigned char ifsc = tpdu[3];
2865 if (ifsc < 16 || ifsc > 254)
2866 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2868 msg = send_buffer;
2869 tpdu = msg + hdrlen;
2870 tpdu[0] = nad_byte;
2871 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
2872 tpdu[2] = 1;
2873 tpdu[3] = ifsc;
2874 tpdulen = 4;
2875 edc = compute_edc (tpdu, tpdulen, use_crc);
2876 if (use_crc)
2877 tpdu[tpdulen++] = (edc >> 8);
2878 tpdu[tpdulen++] = edc;
2879 DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
2881 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
2883 /* Wait time extension request. */
2884 unsigned char bwi = tpdu[3];
2885 msg = send_buffer;
2886 tpdu = msg + hdrlen;
2887 tpdu[0] = nad_byte;
2888 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
2889 tpdu[2] = 1;
2890 tpdu[3] = bwi;
2891 tpdulen = 4;
2892 edc = compute_edc (tpdu, tpdulen, use_crc);
2893 if (use_crc)
2894 tpdu[tpdulen++] = (edc >> 8);
2895 tpdu[tpdulen++] = edc;
2896 DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
2898 else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
2900 DEBUGOUT ("T=1: resync ack from reader\n");
2901 /* Repeat previous block. */
2902 msg = send_buffer;
2903 tpdulen = last_tpdulen;
2905 else
2906 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2908 } /* end T=1 protocol loop. */
2910 return 0;
2914 /* Send the CCID Secure command to the reader. APDU_BUF should
2915 contain the APDU template. PIN_MODE defines how the pin gets
2916 formatted:
2918 1 := The PIN is ASCII encoded and of variable length. The
2919 length of the PIN entered will be put into Lc by the reader.
2920 The APDU should me made up of 4 bytes without Lc.
2922 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
2923 may be used t enable reasonable defaults. PIN_PADLEN should be 0.
2925 When called with RESP and NRESP set to NULL, the function will
2926 merely check whether the reader supports the secure command for the
2927 given APDU and PIN_MODE. */
2929 ccid_transceive_secure (ccid_driver_t handle,
2930 const unsigned char *apdu_buf, size_t apdu_buflen,
2931 int pin_mode, int pinlen_min, int pinlen_max,
2932 int pin_padlen,
2933 unsigned char *resp, size_t maxresplen, size_t *nresp)
2935 int rc;
2936 unsigned char send_buffer[10+259], recv_buffer[10+259];
2937 unsigned char *msg, *tpdu, *p;
2938 size_t msglen, tpdulen, n;
2939 unsigned char seqno;
2940 size_t dummy_nresp;
2941 int testmode;
2942 int cherry_mode = 0;
2944 testmode = !resp && !nresp;
2946 if (!nresp)
2947 nresp = &dummy_nresp;
2948 *nresp = 0;
2950 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
2952 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
2953 return CCID_DRIVER_ERR_NOT_SUPPORTED; /* Not yet by our code. */
2954 else
2955 return CCID_DRIVER_ERR_NO_KEYPAD;
2957 if (pin_mode != 1)
2958 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2960 if (pin_padlen != 0)
2961 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2963 if (!pinlen_min)
2964 pinlen_min = 1;
2965 if (!pinlen_max)
2966 pinlen_max = 25;
2968 /* Note that the 25 is the maximum value the SPR532 allows. */
2969 if (pinlen_min < 1 || pinlen_min > 25
2970 || pinlen_max < 1 || pinlen_max > 25
2971 || pinlen_min > pinlen_max)
2972 return CCID_DRIVER_ERR_INV_VALUE;
2974 /* We have only tested a few readers so better don't risk anything
2975 and do not allow the use with other readers. */
2976 switch (handle->id_vendor)
2978 case VENDOR_SCM: /* Tested with SPR 532. */
2979 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
2980 break;
2981 case VENDOR_CHERRY:
2982 /* The CHERRY XX44 keyboard echos an asterisk for each entered
2983 character on the keyboard channel. We use a special variant
2984 of PC_to_RDR_Secure which directs these characters to the
2985 smart card's bulk-in channel. We also need to append a zero
2986 Lc byte to the APDU. It seems that it will be replaced with
2987 the actual length instead of being appended before the APDU
2988 is send to the card. */
2989 cherry_mode = 1;
2990 break;
2991 default:
2992 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2995 if (testmode)
2996 return 0; /* Success */
2998 msg = send_buffer;
2999 if (handle->id_vendor == VENDOR_SCM)
3001 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
3002 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
3003 NULL, 0, NULL);
3004 if (rc)
3005 return rc;
3008 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3009 msg[5] = 0; /* slot */
3010 msg[6] = seqno = handle->seqno++;
3011 msg[7] = 0; /* bBWI */
3012 msg[8] = 0; /* RFU */
3013 msg[9] = 0; /* RFU */
3014 msg[10] = 0; /* Perform PIN verification. */
3015 msg[11] = 0; /* Timeout in seconds. */
3016 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3017 if (handle->id_vendor == VENDOR_SCM)
3019 /* For the SPR532 the next 2 bytes need to be zero. We do this
3020 for all SCM products. Kudos to Martin Paljak for this
3021 hint. */
3022 msg[13] = msg[14] = 0;
3024 else
3026 msg[13] = 0x00; /* bmPINBlockString:
3027 0 bits of pin length to insert.
3028 0 bytes of PIN block size. */
3029 msg[14] = 0x00; /* bmPINLengthFormat:
3030 Units are bytes, position is 0. */
3033 /* The following is a little endian word. */
3034 msg[15] = pinlen_max; /* wPINMaxExtraDigit-Maximum. */
3035 msg[16] = pinlen_min; /* wPINMaxExtraDigit-Minimum. */
3037 msg[17] = 0x02; /* bEntryValidationCondition:
3038 Validation key pressed */
3039 if (pinlen_min && pinlen_max && pinlen_min == pinlen_max)
3040 msg[17] |= 0x01; /* Max size reached. */
3041 msg[18] = 0xff; /* bNumberMessage: Default. */
3042 msg[19] = 0x04; /* wLangId-High. */
3043 msg[20] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
3044 msg[21] = 0; /* bMsgIndex. */
3045 /* bTeoProlog follows: */
3046 msg[22] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3047 msg[23] = ((handle->t1_ns & 1) << 6); /* I-block */
3048 msg[24] = 0; /* The apdulen will be filled in by the reader. */
3049 /* APDU follows: */
3050 msg[25] = apdu_buf[0]; /* CLA */
3051 msg[26] = apdu_buf[1]; /* INS */
3052 msg[27] = apdu_buf[2]; /* P1 */
3053 msg[28] = apdu_buf[3]; /* P2 */
3054 msglen = 29;
3055 if (cherry_mode)
3056 msg[msglen++] = 0;
3057 /* An EDC is not required. */
3058 set_msg_len (msg, msglen - 10);
3060 rc = bulk_out (handle, msg, msglen, 0);
3061 if (rc)
3062 return rc;
3064 msg = recv_buffer;
3065 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3066 RDR_to_PC_DataBlock, seqno, 30000, 0);
3067 if (rc)
3068 return rc;
3070 tpdu = msg + 10;
3071 tpdulen = msglen - 10;
3073 if (handle->apdu_level)
3075 if (resp)
3077 if (tpdulen > maxresplen)
3079 DEBUGOUT_2 ("provided buffer too short for received data "
3080 "(%u/%u)\n",
3081 (unsigned int)tpdulen, (unsigned int)maxresplen);
3082 return CCID_DRIVER_ERR_INV_VALUE;
3085 memcpy (resp, tpdu, tpdulen);
3086 *nresp = tpdulen;
3088 return 0;
3091 if (tpdulen < 4)
3093 usb_clear_halt (handle->idev, handle->ep_bulk_in);
3094 return CCID_DRIVER_ERR_ABORTED;
3096 if (debug_level > 1)
3097 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3098 ((msg[11] & 0xc0) == 0x80)? 'R' :
3099 (msg[11] & 0x80)? 'S' : 'I',
3100 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3101 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3102 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3104 if (!(tpdu[1] & 0x80))
3105 { /* This is an I-block. */
3106 /* Last block sent was successful. */
3107 handle->t1_ns ^= 1;
3109 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3110 { /* Reponse does not match our sequence number. */
3111 DEBUGOUT ("I-block with wrong seqno received\n");
3112 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3115 handle->t1_nr ^= 1;
3117 p = tpdu + 3; /* Skip the prologue field. */
3118 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3119 /* fixme: verify the checksum. */
3120 if (resp)
3122 if (n > maxresplen)
3124 DEBUGOUT_2 ("provided buffer too short for received data "
3125 "(%u/%u)\n",
3126 (unsigned int)n, (unsigned int)maxresplen);
3127 return CCID_DRIVER_ERR_INV_VALUE;
3130 memcpy (resp, p, n);
3131 resp += n;
3132 *nresp += n;
3133 maxresplen -= n;
3136 if (!(tpdu[1] & 0x20))
3137 return 0; /* No chaining requested - ready. */
3139 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3140 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3142 else if ((tpdu[1] & 0xc0) == 0x80)
3143 { /* This is a R-block. */
3144 if ( (tpdu[1] & 0x0f))
3145 { /* Error: repeat last block */
3146 DEBUGOUT ("No retries supported for Secure operation\n");
3147 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3149 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3150 { /* Reponse does not match our sequence number. */
3151 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3152 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3154 else
3155 { /* Send next chunk. */
3156 DEBUGOUT ("chaining not supported on Secure operation\n");
3157 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3160 else
3161 { /* This is a S-block. */
3162 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3163 (tpdu[1] & 0x20)? "response": "request",
3164 (tpdu[1] & 0x1f));
3165 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3168 return 0;
3174 #ifdef TEST
3177 static void
3178 print_error (int err)
3180 const char *p;
3181 char buf[50];
3183 switch (err)
3185 case 0: p = "success";
3186 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3187 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3188 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3189 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3190 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3191 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3192 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3193 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3194 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3195 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3196 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3197 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3198 default: sprintf (buf, "0x%05x", err); p = buf; break;
3200 fprintf (stderr, "operation failed: %s\n", p);
3204 static void
3205 print_data (const unsigned char *data, size_t length)
3207 if (length >= 2)
3209 fprintf (stderr, "operation status: %02X%02X\n",
3210 data[length-2], data[length-1]);
3211 length -= 2;
3213 if (length)
3215 fputs (" returned data:", stderr);
3216 for (; length; length--, data++)
3217 fprintf (stderr, " %02X", *data);
3218 putc ('\n', stderr);
3222 static void
3223 print_result (int rc, const unsigned char *data, size_t length)
3225 if (rc)
3226 print_error (rc);
3227 else if (data)
3228 print_data (data, length);
3232 main (int argc, char **argv)
3234 int rc;
3235 ccid_driver_t ccid;
3236 int slotstat;
3237 unsigned char result[512];
3238 size_t resultlen;
3239 int no_pinpad = 0;
3240 int verify_123456 = 0;
3241 int did_verify = 0;
3242 int no_poll = 0;
3244 if (argc)
3246 argc--;
3247 argv++;
3250 while (argc)
3252 if ( !strcmp (*argv, "--list"))
3254 char *p;
3255 p = ccid_get_reader_list ();
3256 if (!p)
3257 return 1;
3258 fputs (p, stderr);
3259 free (p);
3260 return 0;
3262 else if ( !strcmp (*argv, "--debug"))
3264 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3265 argc--; argv++;
3267 else if ( !strcmp (*argv, "--no-poll"))
3269 no_poll = 1;
3270 argc--; argv++;
3272 else if ( !strcmp (*argv, "--no-pinpad"))
3274 no_pinpad = 1;
3275 argc--; argv++;
3277 else if ( !strcmp (*argv, "--verify-123456"))
3279 verify_123456 = 1;
3280 argc--; argv++;
3282 else
3283 break;
3286 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
3287 if (rc)
3288 return 1;
3290 if (!no_poll)
3291 ccid_poll (ccid);
3292 fputs ("getting ATR ...\n", stderr);
3293 rc = ccid_get_atr (ccid, NULL, 0, NULL);
3294 if (rc)
3296 print_error (rc);
3297 return 1;
3300 if (!no_poll)
3301 ccid_poll (ccid);
3302 fputs ("getting slot status ...\n", stderr);
3303 rc = ccid_slot_status (ccid, &slotstat);
3304 if (rc)
3306 print_error (rc);
3307 return 1;
3310 if (!no_poll)
3311 ccid_poll (ccid);
3313 fputs ("selecting application OpenPGP ....\n", stderr);
3315 static unsigned char apdu[] = {
3316 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3317 rc = ccid_transceive (ccid,
3318 apdu, sizeof apdu,
3319 result, sizeof result, &resultlen);
3320 print_result (rc, result, resultlen);
3324 if (!no_poll)
3325 ccid_poll (ccid);
3327 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3329 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3330 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3331 result, sizeof result, &resultlen);
3332 print_result (rc, result, resultlen);
3335 if (!no_pinpad)
3339 if (!no_pinpad)
3341 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3344 if (ccid_transceive_secure (ccid,
3345 apdu, sizeof apdu,
3346 1, 0, 0, 0,
3347 NULL, 0, NULL))
3348 fputs ("can't verify using a PIN-Pad reader\n", stderr);
3349 else
3351 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3353 rc = ccid_transceive_secure (ccid,
3354 apdu, sizeof apdu,
3355 1, 0, 0, 0,
3356 result, sizeof result, &resultlen);
3357 print_result (rc, result, resultlen);
3358 did_verify = 1;
3362 if (verify_123456 && !did_verify)
3364 fputs ("verifying that CHV1 is 123456....\n", stderr);
3366 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3367 6, '1','2','3','4','5','6'};
3368 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3369 result, sizeof result, &resultlen);
3370 print_result (rc, result, resultlen);
3374 if (!rc)
3376 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
3378 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
3379 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3380 result, sizeof result, &resultlen);
3381 print_result (rc, result, resultlen);
3385 ccid_close_reader (ccid);
3387 return 0;
3391 * Local Variables:
3392 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
3393 * End:
3395 #endif /*TEST*/
3396 #endif /*HAVE_LIBUSB*/