1 /**
2  * PertoSmart card reader driver (for readers using ACS AC-1030 chipset).
3  *
4  * Copyright 2005, Carlos Henrique Bauer <carlos.bauer@smartcon.com.br>
5  */
6 
7 #include "internal.h"
8 #include <string.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11 
12 #include "atr.h"
13 #include "usb-descriptors.h"
14 
15 #ifndef NULL
16 #define NULL 0
17 #endif
18 
19 #ifndef USB_RECIP_ENDPOINT
20 #define USB_RECIP_ENDPOINT 0x02
21 #endif
22 
23 #ifndef USB_TYPE_VENDOR
24 #define USB_TYPE_VENDOR (0x02 << 5)
25 #endif
26 
27 #ifndef min
28 #define min(a, b) (((a) < (b)) ? (a) : (b))
29 #endif
30 
31 typedef enum PS_INSTRUCTIION {
32 	PS_GET_ACR_STAT = 0x01,
33 	PS_SELECT_CARD_TYPE = 0x02,
34 	PS_SET_PROTOCOL = 0x03,
35 	PS_SET_NOTIFICATION = 0x06,
36 	PS_SET_OPTION = 0x07,
37 	PS_RESET = 0x80,
38 	PS_EXCHANGE_APDU = 0xa0,
39 	PS_EXCHANGE_T1_FRAME = 0xa1,
40 	PS_POWER_OFF = 0x81
41 } ps_instruction_t;
42 
43 typedef enum PS_TRANSMISSION_STATE {
44 	IDLE = 0,
45 	WAITING_TO_SEND,
46 	WAITING_TO_RECEIVE,
47 	FINISHED,
48 	ERROR
49 } ps_transmission_state_t;
50 
51 typedef enum PS_CARD_TYPE {
52 	PS_DEFAULT_CARD_TYPE = 0x00,
53 	PS_T0_CARD_TYPE = 0x0c,
54 	PS_T1_CARD_TYPE = 0x0d,
55 	PS_2WIRE_CARD_TYPE = 0x06,
56 	PS_3WIRE_CARD_TYPE = 0x05,
57 	PS_I2C_CARD_TYPE = 0x02
58 } ps_card_type_t;
59 
60 typedef struct ps_stat {
61 	unsigned char internal[10];
62 	unsigned char max_c;
63 	unsigned char max_r;
64 	unsigned short c_type;
65 	unsigned char c_sel;
66 	unsigned char c_stat;
67 } ps_stat_t;
68 
69 typedef struct ps_device_data {
70 	/* current reader status */
71 	ps_stat_t stat;
72 	/* state of the serial or usb interface */
73 	ps_transmission_state_t if_state;
74 	/* current protocol (negotiated by the reader during card powering up). */
75 	int cur_icc_proto;
76 	long dev_timeout;
77 	/* for USB readers */
78 	ifd_usb_capture_t *capture;
79 	struct timeval begin;
80 	long if_timeout;
81 } ps_device_data_t;
82 
83 typedef struct ps_baud_rate {
84 	unsigned int bps;
85 	unsigned char code;
86 } ps_baudrate_t;
87 
88 static const ps_baudrate_t ps_baudrate_table[] = {
89 	{9600, 0x12},
90 	{14400, 0x03},
91 	{19200, 0x11},
92 	{28800, 0x02},
93 	{38400, 0x10},
94 	{57600, 0x01},
95 	{115200, 0x00}
96 };
97 
98 #define PS_MAX_SEND_LEN         65535
99 #define PS_HEADER_IDX           0
100 #define PS_INSTRUCTION_IDX      1
101 
102 #define PS_HEADER               0x01
103 
104 #define PS_COMMAND_LENGTH0_IDX  2
105 #define PS_COMMAND_LENGTH1_IDX  3
106 #define PS_COMMAND_LENGTH2_IDX  4
107 
108 #define PS_RESPONSE_LENGTH0_IDX 3
109 #define PS_RESPONSE_LENGTH1_IDX 4
110 #define PS_RESPONSE_LENGTH2_IDX 5
111 
112 #define PS_SW1_IDX              1
113 #define PS_SW2_IDX              2
114 
115 #define PS_USB_INTERFACE_INDEX            0x00
116 #define PS_USB_INTERRUPT_ENDPOINT_ADDRESS 0x81
117 #define PS_USB_INTERRUPT_URB_DATA_SIZE    0x08
118 
119 #define PS_STX                  0x02
120 #define PS_ETX                  0x03
121 
122 #define PS_SET_NOTIFICATION_TRANSMIT 1
123 #define PS_SET_NOTIFICATION_DONT_TRANSMIT 2
124 
125 #define PS_OPTION_9600_TO_96000 0
126 #define PS_OPTION_9600_ONLY     1
127 #define PS_OPTION_EMV_MODE_OFF  0
128 #define PS_OPTION_EMV_MODE_ON   (1 << 4)
129 
130 /* read timeout
131  * we must wait enough so that the card can finish its calculation */
132 static const long PS_TIMEOUT = 30000;
133 
134 /* reader names */
135 static const char PS_USB_READER_NAME[] = "PertoSmart (AC1030, USB)";
136 static const char PS_SERIAL_READER_NAME[] = "PertoSmart (AC1030, Serial)";
137 
138 typedef int complete_fn_t(const void *, size_t);
139 
ps_calculate_tx_len(int proto,size_t slen)140 static size_t ps_calculate_tx_len(int proto, size_t slen)
141 {
142 	/* be didactic */
143 	size_t tx_len = 1 /* STX */  +
144 	    2 * (1 /* header */  +
145 		 1 /* command */  +
146 		 1 /* len */  +
147 		 1 /* checksum */ ) +
148 	    1 /* ETX */ ;
149 
150 	/* room for more 2 len bytes */
151 	tx_len += 2 * (slen >= 0xff);
152 	tx_len += 2 * slen;
153 
154 	return tx_len;
155 }
156 
157 /*
158  * Look for ETX.
159  *
160  * Return 0 if the transmission is not complete or the number of the bytes
161  * in the packet which are part of the transmission, including the ETX.
162  */
ps_complete_transmission(const void * p,size_t size)163 static int ps_complete_transmission(const void *p, size_t size)
164 {
165 	size_t i;
166 
167 	for (i = 0; i < size; i++) {
168 		if (((unsigned char *)p)[i] == PS_ETX) {
169 			if (ct_config.debug >= 4)
170 				ct_debug("ps_complete_transmission: ETX found");
171 			return i + 1;
172 		}
173 	}
174 
175 	return 0;
176 }
177 
178 #ifdef not_yet
ps_if_get_baudrate_code(int baudrate)179 static unsigned char ps_if_get_baudrate_code(int baudrate)
180 {
181 
182 	int i;
183 
184 	for (i = 0;
185 	     i < (sizeof(ps_baudrate_table) / sizeof(ps_baudrate_table)[0]);
186 	     i++) {
187 		if (ps_baudrate_table[i].bps == baudrate) {
188 			return ps_baudrate_table[i].code;
189 		}
190 	}
191 
192 	return ps_baudrate_table[0].code;
193 }
194 #endif
195 
196 /*
197  * Send USB control message, and receive data via
198  * Interrupt URBs.
199  */
ps_if_transmission_start(ifd_device_t * dev,long timeout)200 static int ps_if_transmission_start(ifd_device_t * dev, long timeout)
201 {
202 	int rc;
203 	ps_device_data_t *device_data;
204 
205 	if (ct_config.debug >= 1)
206 		ct_debug("ps_if_transmission_start: called");
207 
208 	device_data = (ps_device_data_t *) dev->user_data;
209 
210 	if (device_data->if_state != IDLE && device_data->if_state != ERROR) {
211 		ct_error("ps_if_transmission_start: can't start "
212 			 "transmission: device not idle");
213 		return IFD_ERROR_LOCKED;
214 	}
215 
216 	device_data->if_timeout = (timeout < 0) ? dev->timeout : timeout;
217 
218 	if (dev->type == IFD_DEVICE_TYPE_USB) {
219 		rc = ifd_usb_begin_capture(dev,
220 					   IFD_USB_URB_TYPE_INTERRUPT,
221 					   PS_USB_INTERRUPT_ENDPOINT_ADDRESS,
222 					   PS_USB_INTERRUPT_URB_DATA_SIZE,
223 					   &(device_data->capture));
224 		if (rc != IFD_SUCCESS) {
225 			ct_error("ps_if_transmission_start: failed: %i", rc);
226 			device_data->capture = NULL;
227 			device_data->if_state = ERROR;
228 		}
229 	} else {
230 		rc = IFD_SUCCESS;
231 	}
232 
233 	device_data->if_state = (rc == IFD_SUCCESS) ? WAITING_TO_SEND : ERROR;
234 
235 	return rc;
236 }
237 
238 static int
ps_if_transmission_send(ifd_device_t * dev,const void * sbuf,size_t slen)239 ps_if_transmission_send(ifd_device_t * dev, const void *sbuf, size_t slen)
240 {
241 	int rc;
242 	ps_device_data_t *device_data;
243 
244 	device_data = (ps_device_data_t *) dev->user_data;
245 
246 	if (ct_config.debug >= 4)
247 		ct_debug("ps_if_transmission_send: sent %u bytes: %s",
248 			 slen, ct_hexdump(sbuf, slen));
249 	else
250 		if (ct_config.debug >= 1)
251 			ct_debug("ps_if_transmission_send: called");
252 
253 
254 
255 	if (device_data->if_state != WAITING_TO_SEND) {
256 		ct_error
257 		    ("ps_if_transmission_send: invalid transmission state %i.",
258 		     device_data->if_state);
259 		return IFD_ERROR_GENERIC;
260 	}
261 
262 	gettimeofday(&(device_data->begin), NULL);
263 
264 	if (dev->type == IFD_DEVICE_TYPE_USB) {
265 		rc = ifd_usb_control(dev,
266 				     IFD_USB_ENDPOINT_OUT |
267 				     IFD_USB_TYPE_VENDOR  |
268 				     IFD_USB_RECIP_DEVICE,
269 				     0, 0, 0, (void *)sbuf, slen,
270 				     device_data->if_timeout);
271 	} else {
272 		ifd_device_flush(dev);
273 		rc = ifd_device_send(dev, sbuf, slen);
274 	}
275 
276 	if (rc < 0) {
277 		ct_error("ps_if_transmission_send: failed: %i", rc);
278 	}
279 
280 	device_data->if_state = (rc < 0) ? ERROR : WAITING_TO_RECEIVE;
281 
282 	return rc;
283 }
284 
285 static int
ps_if_transmission_receive(ifd_device_t * dev,const void * rbuf,size_t rlen)286 ps_if_transmission_receive(ifd_device_t * dev, const void *rbuf, size_t rlen)
287 {
288 
289 	int rc = IFD_SUCCESS;
290 	ps_device_data_t *device_data;
291 	size_t received;
292 
293 	device_data = (ps_device_data_t *) dev->user_data;
294 	received = 0;
295 
296 	if (device_data->if_state != WAITING_TO_RECEIVE) {
297 		ct_error
298 		    ("ps_if_transmission_receive: invalid transmission state %i.",
299 		     device_data->if_state);
300 		return IFD_ERROR_GENERIC;
301 	}
302 
303 	if (rlen < PS_USB_INTERRUPT_URB_DATA_SIZE) {
304 		ct_error("ps_if_transmission_receive: buffer too small for "
305 			 "receiving interrupt urbs: %i", rlen);
306 		return IFD_ERROR_GENERIC;
307 	}
308 
309 	if (rlen % PS_USB_INTERRUPT_URB_DATA_SIZE) {
310 		rlen =
311 		    (rlen / PS_USB_INTERRUPT_URB_DATA_SIZE) * PS_USB_INTERRUPT_URB_DATA_SIZE;
312 	}
313 
314 	/* Capture URBs or read from the serial until we have a complete answer */
315 	for (;;) {
316 		unsigned char packet_buf[PS_USB_INTERRUPT_URB_DATA_SIZE];
317 		const int packet_buf_len = sizeof(packet_buf);
318 		long wait;
319 
320 		wait =
321 		    device_data->if_timeout -
322 		    ifd_time_elapsed(&(device_data->begin));
323 
324 		if (wait <= 0) {
325 			ct_error("ps_if_transmission_receive: timeout");
326 			rc = IFD_ERROR_TIMEOUT;
327 		} else {
328 			if (IFD_DEVICE_TYPE_USB == dev->type) {
329 				rc = ifd_usb_capture(dev, device_data->capture,
330 						     packet_buf, packet_buf_len,
331 						     wait);
332 			} else {
333 				ct_config.suppress_errors++;
334 				rc = ifd_device_recv(dev, packet_buf, 1, wait);
335 				ct_config.suppress_errors--;
336 			}
337 		}
338 
339 		if (rc > 0) {
340 
341 			int last_packet_len = 0;
342 
343 			last_packet_len =
344 			    ps_complete_transmission(packet_buf, rc);
345 
346 			if (last_packet_len) {
347 				rc = last_packet_len;
348 			}
349 
350 			memcpy((caddr_t) rbuf + received, packet_buf, rc);
351 
352 			received += rc;
353 
354 			if (last_packet_len) {
355 				device_data->if_state = FINISHED;
356 				break;
357 			}
358 
359 			if (received >= rlen) {
360 				break;
361 			}
362 
363 		} else if (rc < 0) {
364 			device_data->if_state = ERROR;
365 			break;
366 		}
367 	}
368 
369 	if (rc >= 0) {
370 		rc = received;
371 		if (ct_config.debug >= 4)
372 			ct_debug("ps_if_transmission_receive: received %u bytes:%s", rc,
373 			 	 ct_hexdump(rbuf, rc));
374 	} else {
375 		ct_error("ps_if_transmission_receive: failed: %i", rc);
376 	}
377 
378 	return rc;
379 }
380 
ps_if_transmission_flush_reader_output_buffer(ifd_device_t * dev)381 static int ps_if_transmission_flush_reader_output_buffer(ifd_device_t * dev)
382 {
383 	int rc = 0;
384 	ps_device_data_t *device_data;
385 	unsigned char packet_buf[256];
386 	const size_t packet_buf_len = sizeof(packet_buf);
387 	const long timeout = 20;
388 
389 	if (ct_config.debug >= 1)
390 		ct_debug("ps_if_transmission_flush_reader_output_buffer: called");
391 
392 	device_data = (ps_device_data_t *) dev->user_data;
393 
394 	do {
395 		memset(packet_buf, 0, packet_buf_len);
396 
397 		if (dev->type == IFD_DEVICE_TYPE_USB) {
398 			rc = ifd_usb_capture(dev, device_data->capture,
399 					     packet_buf, packet_buf_len,
400 					     timeout);
401 		} else {
402 			ct_config.suppress_errors++;
403 			rc = ifd_device_recv(dev, packet_buf, packet_buf_len,
404 					     timeout);
405 			ct_config.suppress_errors--;
406 		}
407 
408 		if (rc <= 0) {
409 			break;
410 		}
411 
412 	} while (!ps_complete_transmission(packet_buf, rc));
413 
414 	return IFD_SUCCESS;
415 }
416 
ps_if_transmission_end(ifd_device_t * dev)417 static int ps_if_transmission_end(ifd_device_t * dev)
418 {
419 	ps_device_data_t *device_data;
420 
421 	if (ct_config.debug >= 1)
422 		ct_debug("ps_if_transmission_end: called");
423 
424 	device_data = (ps_device_data_t *) dev->user_data;
425 
426 	switch (device_data->if_state) {
427 
428 	case WAITING_TO_RECEIVE:
429 	case WAITING_TO_SEND:
430 	case FINISHED:
431 	case ERROR:
432 		if (dev->type == IFD_DEVICE_TYPE_USB) {
433 			ifd_usb_end_capture(dev, device_data->capture);
434 			device_data->capture = NULL;
435 		}
436 		device_data->if_state = IDLE;
437 
438 		break;
439 
440 	default:
441 	case IDLE:
442 		break;
443 	}
444 
445 	return IFD_SUCCESS;
446 }
447 
PS_ASCII_TO_HEX(unsigned char a)448 static unsigned char PS_ASCII_TO_HEX(unsigned char a)
449 {
450 	return ((a) + (((a) >= 0x0a) ? 'A' - 0x0a : '0'));
451 }
452 
PS_HEX_TO_ASCII(unsigned char h)453 static unsigned char PS_HEX_TO_ASCII(unsigned char h)
454 {
455 	return h - ((h >= 'A') ?
456 		    (((h >= 'a') ? 'a' : 'A') - (unsigned char)0x0a) : '0');
457 }
458 
PS_VALID_HEX(unsigned char h)459 static unsigned char PS_VALID_HEX(unsigned char h)
460 {
461 	return (('0' <= (h) && (h) <= '9') ||
462 		('A' <= (h) && (h) <= 'F') || ('a' <= (h) && (h) <= 'f'));
463 }
464 
465 /*
466  * Encode a buffer to will be sent to the reader (to ASCII-HEX)
467  */
468 static int
ps_encode_ascii_hex(unsigned char * out,size_t out_len,const unsigned char * in,size_t in_len)469 ps_encode_ascii_hex(unsigned char *out, size_t out_len,
470 		    const unsigned char *in, size_t in_len)
471 {
472 	int i, k;
473 
474 	if (ct_config.debug >= 4)
475 		ct_debug("ps_encode_ascii_hex: called");
476 
477 	if (out_len < (2 * in_len)) {
478 		ct_error("ps_encode_ascii_hex: output buffer too small.");
479 		return -1;
480 	}
481 
482 	for (i = 0, k = 0; i < in_len; i++) {
483 		/* convert the most significant nibble */
484 		out[k++] = PS_ASCII_TO_HEX(in[i] >> 4);
485 		/* convert the less significant nibble */
486 		out[k++] = PS_ASCII_TO_HEX(in[i] & 0x0f);
487 	}
488 
489 	/* return the number of byte copied to output buffer */
490 	return k;
491 }
492 
493 /*
494  * Decode a buffer received from the reader (from ASCII-HEX)
495  */
496 static int
ps_decode_ascii_hex(unsigned char * out,size_t out_len,const unsigned char * in,size_t in_len)497 ps_decode_ascii_hex(unsigned char *out, size_t out_len,
498 		    const unsigned char *in, size_t in_len)
499 {
500 	size_t i, k;
501 
502 	if (ct_config.debug >= 4)
503 		ct_debug("ps_decode_ascii_hex: called");
504 
505 	if (in_len % 2) {
506 		ct_error
507 		    ("ps_decode_ascii_hex: input buffer len is not a power of 2.");
508 		return IFD_ERROR_GENERIC;
509 	}
510 
511 	if (out_len < (in_len > 1)) {
512 		ct_error("ps_decode_ascii_hex: output buffer too small.");
513 		return IFD_ERROR_BUFFER_TOO_SMALL;
514 	}
515 
516 	for (i = 0, k = 0; (i + 1) < in_len && k < out_len; k++) {
517 
518 		if (!(PS_VALID_HEX(in[i]))) {
519 			ct_error
520 			    ("ps_decode_ascii_hex: invalid ascii code hex value: %#x = %c.",
521 			     i, in[i]);
522 			return IFD_ERROR_GENERIC;
523 		}
524 
525 		if (!(PS_VALID_HEX(in[i + 1]))) {
526 			ct_error
527 			    ("ps_decode_ascii_hex: invalid ascii code hex value: %#x = %c.",
528 			     i + 1, in[i + 1]);
529 			return IFD_ERROR_GENERIC;
530 		}
531 
532 		out[k] = PS_HEX_TO_ASCII(in[i++]) << 4;
533 		out[k] |= PS_HEX_TO_ASCII(in[i++]);
534 	}
535 
536 	return k;
537 }
538 
ps_checksum(unsigned char iv,const unsigned char * buf,size_t len)539 static unsigned char ps_checksum(unsigned char iv,
540 			  const unsigned char *buf, size_t len)
541 {
542 	unsigned char checksum = iv;
543 	int mylen = len;
544 
545 	if (buf != NULL) {
546 		while (mylen) {
547 			checksum ^= buf[--mylen];
548 		}
549 	}
550 
551 	return checksum;
552 }
553 
554 /*
555  * Send command to IFD
556  */
557 static int
ps_send_to_ifd(ifd_reader_t * reader,ps_instruction_t instruction,const unsigned char * sbuf,size_t slen)558 ps_send_to_ifd(ifd_reader_t * reader, ps_instruction_t instruction,
559 	       const unsigned char *sbuf, size_t slen)
560 {
561 	int rc;
562 	unsigned char buffer[1024];
563 	unsigned char protocol_bytes[5]; /* 1 header byte      +
564 					    1 instruction byte +
565 					    3 size bytes         */
566 	unsigned char *buffer_start = buffer;
567 	unsigned char *p;
568 	unsigned char checksum;
569 	size_t buffer_len = sizeof(buffer);
570 	size_t size_tmp;
571 	ifd_device_t *dev;
572 	ps_device_data_t *device_data;
573 	size_t tx_len;
574 
575 	if (ct_config.debug >= 4)
576 		ct_debug("ps_send_to_ifd: sending %u bytes:%s", slen,
577 		 	 ct_hexdump(sbuf, slen));
578 	else if (ct_config.debug >= 1)
579 		ct_debug("ps_send_to_ifd: called");
580 
581 
582 	dev = reader->device;
583 	device_data = (ps_device_data_t *) dev->user_data;
584 
585 	if (slen > PS_MAX_SEND_LEN) {
586 		ct_error ("ps_apdu_send: transmission is larger "
587 				"than maximum allowed: %i", slen);
588 		return IFD_ERROR_GENERIC;
589 	}
590 
591 	tx_len = ps_calculate_tx_len(device_data->cur_icc_proto, slen);
592 
593 	if (tx_len > sizeof(buffer)) {
594 		ct_error
595 		    ("ps_send_to_ifd: failed: transmission is too large (%i bytes) "
596 		     "for drivers's transmission buffer (%i bytes)",
597 		     (int)tx_len, sizeof(buffer));
598 		return IFD_ERROR_NO_MEMORY;
599 	}
600 
601 	p = buffer;
602 
603 	/* add STX */
604 	*p++ = PS_STX;
605 
606 	/* add protocol bytes */
607 	protocol_bytes[PS_HEADER_IDX] = PS_HEADER;
608 	protocol_bytes[PS_INSTRUCTION_IDX] = instruction;
609 
610 	/* add data length */
611 	if (slen < 0xff) {
612 		/* normal command */
613 		protocol_bytes[PS_COMMAND_LENGTH0_IDX] = (unsigned char)slen;
614 		size_tmp = PS_COMMAND_LENGTH0_IDX + 1;
615 	} else {
616 		/* extended command */
617 		protocol_bytes[PS_COMMAND_LENGTH0_IDX] = 0xff;
618 		protocol_bytes[PS_COMMAND_LENGTH1_IDX] =
619 		    (unsigned char)(slen >> 8);
620 		protocol_bytes[PS_COMMAND_LENGTH2_IDX] =
621 		    (unsigned char)(slen & 0xff);
622 		size_tmp = PS_COMMAND_LENGTH2_IDX + 1;
623 	}
624 
625 	rc = ps_encode_ascii_hex(p,
626 				 buffer_len - (p - buffer_start),
627 				 protocol_bytes, size_tmp);
628 
629 	checksum = ps_checksum(0, protocol_bytes, size_tmp);
630 
631 	if (rc < 0)
632 		goto out;
633 
634 	p += rc;
635 
636 	/* add data */
637 	rc = ps_encode_ascii_hex(p, buffer_len - (p - buffer_start), sbuf,
638 				 slen);
639 
640 	if (rc < 0)
641 		goto out;
642 
643 	p += rc;
644 
645 	checksum = ps_checksum(checksum, sbuf, slen);
646 
647 	/* add checksum */
648 	rc = ps_encode_ascii_hex(p, buffer_len - (p - buffer_start),
649 				 &checksum, sizeof(checksum));
650 
651 	p += rc;
652 
653 	/* add ETX */
654 	*p++ = PS_ETX;
655 
656 	/* start the transmission */
657 	rc = ps_if_transmission_start(dev, dev->timeout);
658 
659 	if (rc != IFD_SUCCESS)
660 		goto out;
661 
662 	rc = ps_if_transmission_flush_reader_output_buffer(dev);
663 
664 	if (rc != IFD_SUCCESS)
665 		goto out;
666 
667 	/* send the data */
668 	rc = ps_if_transmission_send(dev, buffer_start, p - buffer_start);
669 
670       out:
671 
672 	if (buffer != buffer_start && buffer != NULL) {
673 		free(buffer_start);
674 	}
675 
676 	if (rc < 0) {
677 		ct_error("ps_send_to_ifd: failed: %i", rc);
678 		ps_if_transmission_end(dev);
679 	}
680 
681 	return rc;
682 }
683 
684 static int
ps_receive_from_ifd(ifd_reader_t * reader,unsigned char * rbuf,size_t rlen)685 ps_receive_from_ifd(ifd_reader_t * reader, unsigned char *rbuf, size_t rlen)
686 {
687 	int rc;
688 	unsigned char protocol_bytes[6]; /* 1 STX    byte  +
689 					    2 status bytes +
690 					    3 size bytes */
691 	unsigned char checksum;
692 	unsigned char expected_checksum;
693 	unsigned char sw1 = 0;
694 	unsigned char sw2 = 0;
695 	unsigned char buffer[536];
696 	unsigned char *p = buffer;
697 	const size_t buffer_len = sizeof(buffer);
698 	size_t tmp_length;
699 	size_t data_length;
700 	size_t remaining_data_length;
701 	size_t rbuf_offset;
702 	size_t encoded_data_slice_len;
703 	int rcvd_len;
704 	ifd_device_t *dev;
705 	ps_device_data_t *device_data;
706 
707 	if (ct_config.debug >= 1)
708 		ct_debug("ps_receive_from_ifd: called");
709 
710 	dev = reader->device;
711 	device_data = (ps_device_data_t *) dev->user_data;
712 	data_length = 0;
713 
714 	/**
715 	 * rbuf == NULL && rlen == 0 IS VALID,
716 	 * it means receive the reader status, but no data
717 	 */
718 	if(rbuf == NULL && rlen > 0) {
719 		ct_error("ps_receive_from_ifd: NULL == rbuf && rlen > 0");
720 		rc = IFD_ERROR_GENERIC;
721 		goto out;
722 	}
723 
724 	memset(rbuf, 0, rlen);
725 
726 	/* receive transmission */
727 	rc = ps_if_transmission_receive(dev, buffer, buffer_len);
728 
729 	if (rc < 0)
730 		goto out;
731 
732 	rcvd_len = rc;
733 
734 	p = buffer;
735 
736 	/* must start with a STX, send error? */
737 	if (*p != PS_STX) {
738 		ct_error("ps_receive_from_ifd: missing STX");
739 		rc = IFD_ERROR_COMM_ERROR;
740 		goto out;
741 	}
742 
743 	p++;
744 
745 	/* decode the "protocol bytes", i.e. header, SW1, SW1 and data length */
746 		/* 8 = 2 * (header + sw1 + sw2 + data_length) */
747 		/* make sure it's even size */
748 	rc = ps_decode_ascii_hex(protocol_bytes, sizeof(protocol_bytes), p,
749 			 min(8,(rcvd_len - (p - buffer)) & ~((size_t) 1)));
750 
751 	if (rc < 0)
752 		goto out;
753 
754 	/* calculate checksum of the decoded data */
755 	checksum = ps_checksum(0, protocol_bytes, rc);
756 
757 	/* header is present */
758 	if (protocol_bytes[PS_HEADER_IDX] != PS_HEADER) {
759 		/* receive error */
760 		rc = IFD_ERROR_COMM_ERROR;
761 		goto out;
762 	}
763 
764 	/* status word */
765 	sw1 = protocol_bytes[PS_SW1_IDX];
766 	sw2 = protocol_bytes[PS_SW2_IDX];
767 
768 	if (ct_config.debug >= 4)
769 		ct_debug("ps_receive_from_ifd: sw1 = %#02x, sw2 = %#02x", sw1, sw2);
770 
771 	if (sw1 != 0x90) {
772 		if (sw1 == 0x60 && sw2 == 0x02) {
773 			rc = IFD_ERROR_NO_CARD;
774 		} else {
775 			rc = IFD_ERROR_GENERIC;
776 		}
777 		goto out;
778 	}
779 
780 	/* skip already decoded data */
781 	p += 2 * rc;
782 
783 	if (ct_config.debug >= 4)
784 		ct_debug("ps_receive_from_ifd: "
785 			 "protocol_bytes[PS_RESPONSE_LENGTH0_IDX]: %i",
786 	     		 protocol_bytes[PS_RESPONSE_LENGTH0_IDX]);
787 
788 	/* decode the length of the received data */
789 	if (protocol_bytes[PS_RESPONSE_LENGTH0_IDX] == 0xff) {
790 		/* it's an extended response...
791 		   next two encoded bytes are the data length */
792 		if ((rcvd_len - (p - buffer)) < 4) {
793 			/* did't read enough bytes for size data */
794 			rc = IFD_ERROR_COMM_ERROR;
795 			goto out;
796 		}
797 
798 		rc = ps_decode_ascii_hex(&protocol_bytes
799 					 [PS_RESPONSE_LENGTH1_IDX],
800 					 sizeof(protocol_bytes) -
801 					 PS_RESPONSE_LENGTH1_IDX + 1, p, 4);
802 
803 		if (rc < 0 )
804 			goto out;
805 
806 		/* calculate checksum of the decoded data */
807 		checksum =
808 		    ps_checksum(checksum,
809 				&protocol_bytes[PS_RESPONSE_LENGTH1_IDX], rc);
810 
811 		if (ct_config.debug >= 4) {
812 			ct_debug("ps_receive_from_ifd: "
813 				 "protocol_bytes[PS_RESPONSE_LENGTH1_IDX]: %i",
814 		     		 protocol_bytes[PS_RESPONSE_LENGTH1_IDX]);
815 			ct_debug("ps_receive_from_ifd: "
816 				 "protocol_bytes[PS_RESPONSE_LENGTH2_IDX]: %i",
817 		     		 protocol_bytes[PS_RESPONSE_LENGTH2_IDX]);
818 		}
819 
820 		data_length = protocol_bytes[PS_RESPONSE_LENGTH1_IDX] << 8;
821 		data_length |= protocol_bytes[PS_RESPONSE_LENGTH2_IDX];
822 
823 		/* skip decoded data */
824 		p += 2 * rc;
825 
826 	} else {
827 		/* one byte for data length */
828 		data_length = protocol_bytes[PS_RESPONSE_LENGTH0_IDX];
829 	}
830 
831 	if (rlen < data_length) {
832 		ct_error("ps_receive_from_ifd: output buffer too small (%i), "
833 			 "%i bytes are needed", rlen, data_length);
834 		return IFD_ERROR_GENERIC;
835 	}
836 
837 	rbuf_offset = 0;
838 	remaining_data_length = data_length;
839 
840 	/* while has data to decode */
841 	while (1) {
842 		tmp_length = rcvd_len - (p - buffer);
843 
844 		/* if has data to send to the output */
845 		if (remaining_data_length > 0) {
846 			/* must be even number */
847 			encoded_data_slice_len =
848 			    min(remaining_data_length, tmp_length >> 1) << 1;
849 
850 			if (device_data->if_state == FINISHED) {
851 				if ((remaining_data_length << 1) !=
852 				    encoded_data_slice_len) {
853 					/* something got wrong */
854 					ct_error
855 					    ("ps_receive_from_ifd: data length is diferent "
856 					     "from data length reported by reader.");
857 					goto out;
858 				}
859 			}
860 
861 			/* decode slice */
862 			rc = ps_decode_ascii_hex(rbuf + rbuf_offset,
863 						 rlen - rbuf_offset, p,
864 						 encoded_data_slice_len);
865 
866 			if (rc < 0)
867 				goto out;
868 
869 			/* calculate checksum of the decode data */
870 			checksum =
871 			    ps_checksum(checksum, rbuf + rbuf_offset, rc);
872 
873 			p += 2 * rc;
874 			remaining_data_length -= rc;
875 			rbuf_offset = data_length - remaining_data_length;
876 		}
877 
878 		if (device_data->if_state == FINISHED)
879 			break;
880 
881 
882 		/* move buffer tail to beginning */
883 		tmp_length = rcvd_len - (p - buffer);
884 
885 		if (tmp_length > 0)
886 			memmove(buffer, p, tmp_length);
887 
888 		/* point p to end of data */
889 		p = buffer + tmp_length;
890 
891 		/* append the next slice */
892 		rc = ps_if_transmission_receive(dev, p, buffer_len);
893 
894 		if (rc < 0) {
895 			goto out;
896 		}
897 
898 		/* point p to the beginning of the buffer */
899 		p = buffer;
900 
901 		rcvd_len = tmp_length + rc;
902 	}
903 
904 	/* decode checksum */
905 	rc = ps_decode_ascii_hex(&expected_checksum,
906 				 sizeof(expected_checksum), p, 2);
907 
908 	if (checksum != expected_checksum) {
909 		ct_error("ps_receive_from_ifd: failed checksum.");
910 		rc = IFD_ERROR_COMM_ERROR;
911 		goto out;
912 	}
913 
914 	p += 2 * rc;
915 
916 	/* last byte is a ETX? */
917 	if (*p != PS_ETX) {
918 		ct_error("ps_receive_from_ifd: missing ETX.");
919 		rc = IFD_ERROR_COMM_ERROR;
920 		goto out;
921 	}
922 
923 	rc = data_length;
924 
925       out:
926 
927 	ps_if_transmission_end(dev);
928 
929 	if (rc < 0) {
930 		ct_error("ps_receive_from_ifd: failed: %i", rc);
931 	} else {
932 		if (ct_config.debug >= 4) {
933 			ct_debug("ps_receive_from_ifd: received: %i: %s", rc,
934 			 	 ct_hexdump(rbuf, rc));
935 		}
936 	}
937 
938 	return rc;
939 }
940 
941 static int
ps_transceive_instruction(ifd_reader_t * reader,ps_instruction_t instruction,const void * sbuf,size_t slen,void * rbuf,size_t rlen)942 ps_transceive_instruction(ifd_reader_t * reader,
943 			  ps_instruction_t instruction,
944 			  const void *sbuf,
945 			  size_t slen, void *rbuf, size_t rlen)
946 {
947 	int rc;
948 
949 	if (ct_config.debug >= 1)
950 		ct_debug("ps_transceive_instruction: called");
951 
952 	rc = ps_send_to_ifd(reader, instruction, sbuf, slen);
953 
954 	if (rc < 0) {
955 		ct_error("ps_transceive_instruction: failed: %i", rc);
956 	} else {
957 		rc = ps_receive_from_ifd(reader, rbuf, rlen);
958 	}
959 
960 	return rc;
961 }
962 
963 /*
964  * Power up the card slot
965  */
ps_activate(ifd_reader_t * reader)966 static int ps_activate(ifd_reader_t * reader)
967 {
968 
969 	if (ct_config.debug >= 1)
970 		ct_debug("ps_activate: called");
971 
972 	return IFD_SUCCESS;
973 }
974 
ps_deactivate(ifd_reader_t * reader)975 static int ps_deactivate(ifd_reader_t * reader)
976 {
977 	int rc;
978 
979 
980         if (ct_config.debug >= 1)
981 		ct_debug("ps_deactivate: called");
982 
983 	rc = ps_transceive_instruction(reader, PS_POWER_OFF, NULL, 0, NULL, 0);
984 
985 	if (rc < 0)
986 		ct_error("ps_deactivate: failed: %i", rc);
987 
988 	return rc;
989 }
990 
ps_get_stat(ifd_reader_t * reader,ps_stat_t * stat)991 static int ps_get_stat(ifd_reader_t * reader, ps_stat_t * stat)
992 {
993 	int rc;
994 	unsigned char buffer[16];
995 	unsigned char *p;
996 
997         if (ct_config.debug >= 1)
998 		ct_debug("ps_get_stat: called");
999 
1000 	rc = ps_transceive_instruction(reader, PS_GET_ACR_STAT,
1001 				       NULL, 0, buffer, sizeof(buffer));
1002 
1003 	if (rc < 0)
1004 		goto out;
1005 
1006 	if (sizeof(buffer) > rc) {
1007 		rc = IFD_ERROR_COMM_ERROR;
1008 		goto out;
1009 	}
1010 
1011 	for (p = buffer; p < (buffer + sizeof(stat->internal)); p++) {
1012 		stat->internal[p - buffer] = *p;
1013 	}
1014 
1015 	stat->max_c = *p++;
1016 	stat->max_r = *p++;
1017 	stat->c_type = *p++ << 8;
1018 	stat->c_type |= *p++;
1019 	stat->c_sel = *p++;
1020 	stat->c_stat = *p++;
1021 
1022       out:
1023 
1024 	if (rc < 0)
1025 		ct_error("ps_get_stat: failed: %i", rc);
1026 
1027 	return (0 <= rc) ? IFD_SUCCESS : rc;
1028 }
1029 
ps_card_status(ifd_reader_t * reader,int slot,int * status)1030 static int ps_card_status(ifd_reader_t * reader, int slot, int *status)
1031 {
1032 	int rc;
1033 	ifd_device_t *dev;
1034 	ps_device_data_t *device_data;
1035 	unsigned char c_stat;
1036 
1037         if (ct_config.debug >= 1)
1038 		ct_debug("ps_card_status: called");
1039 
1040 	if (slot != 0) {
1041 		ct_error("ps_card_status: bad slot index %u", slot);
1042 		return IFD_ERROR_INVALID_SLOT;
1043 	}
1044 
1045 	dev = reader->device;
1046 
1047 	device_data = (ps_device_data_t *) dev->user_data;
1048 
1049 	c_stat = device_data->stat.c_stat;
1050 
1051 	rc = ps_get_stat(reader, &(device_data->stat));
1052 
1053 	if (rc == IFD_SUCCESS) {
1054 		*status = (device_data->stat.c_stat) ? IFD_CARD_PRESENT : 0;
1055 
1056 		if (c_stat != device_data->stat.c_stat) {
1057 			*status |= IFD_CARD_STATUS_CHANGED;
1058 		}
1059 	} else {
1060 		ct_error("ps_card_status: failed: %i", rc);
1061 	}
1062 
1063 	return rc;
1064 }
1065 
1066 /*
1067  * Reset and reset the protocol
1068  */
1069 static int
ps_card_reset_select_protocol(ifd_reader_t * reader,int nslot,void * atr,size_t size,int new_icc_proto)1070 ps_card_reset_select_protocol(ifd_reader_t * reader, int nslot,
1071 			      void *atr, size_t size, int new_icc_proto)
1072 {
1073 	int rc;
1074 	int atr_len;
1075 	unsigned char sbuf[1];
1076 	ifd_device_t *dev;
1077 	ps_device_data_t *device_data;
1078 	ifd_slot_t *slot;
1079 	ifd_atr_info_t atr_info;
1080 
1081         if (ct_config.debug >= 1)
1082 		ct_debug("ps_card_reset_select_protocol: called");
1083 
1084 	if (nslot != 0) {
1085 		ct_error("ps_card_reset_select_protocol: bad slot index %u",
1086 			 nslot);
1087 		return IFD_ERROR_INVALID_SLOT;
1088 	}
1089 
1090 	dev = reader->device;
1091 	slot = &reader->slot[nslot];
1092 	device_data = (ps_device_data_t *) dev->user_data;
1093 
1094 	/* power of the card */
1095 	rc = ps_transceive_instruction(reader, PS_POWER_OFF, NULL, 0, NULL, 0);
1096 
1097 	if (rc != IFD_SUCCESS) {
1098 		ct_error
1099 		    ("ps_card_reset_select_protocol: failed (PS_POWER_OF): %i",
1100 		     rc);
1101 		return rc;
1102 	}
1103 
1104 	if (slot->proto == NULL || device_data->cur_icc_proto != new_icc_proto) {
1105 		switch (new_icc_proto) {
1106 
1107 		case IFD_PROTOCOL_DEFAULT:
1108 		        if (ct_config.debug >= 1)
1109 				ct_debug("ps_card_reset_select_protocol: "
1110 					 "using automatic protocol selecting");
1111 			sbuf[0] = PS_DEFAULT_CARD_TYPE;
1112 			break;
1113 
1114 		case IFD_PROTOCOL_T0:
1115 		        if (ct_config.debug >= 1)
1116 				ct_debug("ps_card_reset_select_protocol: "
1117 					 "selecting protocol T0");
1118 			sbuf[0] = PS_T0_CARD_TYPE;
1119 			break;
1120 
1121 		case IFD_PROTOCOL_T1:
1122 		        if (ct_config.debug >= 1)
1123 				ct_debug("ps_card_reset_select_protocol: "
1124 					 "selecting protocol T1");
1125 			sbuf[0] = PS_T1_CARD_TYPE;
1126 			break;
1127 
1128 		default:
1129 			ct_error("ps_card_reset_select_protocol: "
1130 				 "unknow protocol %i", new_icc_proto);
1131 			return IFD_ERROR_NOT_SUPPORTED;
1132 		}
1133 
1134 		rc = ps_transceive_instruction(reader, PS_SELECT_CARD_TYPE,
1135 					       sbuf, sizeof(sbuf), NULL, 0);
1136 
1137 		if (rc != IFD_SUCCESS) {
1138 			ct_error("ps_card_reset_select_protocol: "
1139 				 "error selecting card type %#02x", sbuf[0]);
1140 			return rc;
1141 		}
1142 	}
1143 
1144 	/* power up the card */
1145 	rc = ps_transceive_instruction(reader, PS_RESET, NULL, 0, atr, size);
1146 
1147 	if (rc < 0) {
1148 		ct_error("ps_card_reset_select_protocol: failed (PS_RESET): %i",
1149 			 rc);
1150 		return rc;
1151 	}
1152 
1153 	atr_len = rc;
1154 
1155 	/* the reader does PPS negotiation with the card
1156 	   parse the atr to check the protocol negotiated by the reader */
1157 
1158 	rc = ifd_atr_parse(&atr_info, atr, atr_len);
1159 
1160 	if (rc < 0) {
1161 		ct_error("ps_card_reset_select_protocol: %s: Bad ATR",
1162 			 reader->name);
1163 		return rc;
1164 	}
1165 
1166 	if (atr_info.TA[1] != -1) {
1167 		/* specific mode */
1168 	        if (ct_config.debug >= 1)
1169 			ct_debug("ps_card_reset_select_protocol: "
1170 				 "card in specific mode %#02x",
1171 		     		 atr_info.TA[1] & 0x0f);
1172 		new_icc_proto = atr_info.TA[1] & 0x0f;
1173 	} else {
1174 		if (new_icc_proto == IFD_PROTOCOL_DEFAULT) {
1175 			new_icc_proto = atr_info.default_protocol;
1176 		}
1177 	}
1178 
1179 	if (slot->proto == NULL || device_data->cur_icc_proto != new_icc_proto) {
1180 
1181 		if (slot->proto != NULL) {
1182 			ifd_protocol_free(slot->proto);
1183 		}
1184 
1185 		slot->proto =
1186 		    ifd_protocol_new(new_icc_proto, reader, slot->dad);
1187 
1188 		if (slot->proto == NULL) {
1189 			ct_error("ps_cart_reset_select_protocol: "
1190 				 "ifd_protocol_new");
1191 			return IFD_ERROR_GENERIC;
1192 		}
1193 
1194 		/* set protocol parameters */
1195 		switch (new_icc_proto) {
1196 
1197 		case IFD_PROTOCOL_T0:
1198 		        if (ct_config.debug >= 1)
1199 				ct_debug("ps_card_reset_select_protocol: "
1200 					 "using protocol T0");
1201 			ifd_protocol_set_parameter(slot->proto,
1202 						   IFD_PROTOCOL_BLOCK_ORIENTED,
1203 						   1);
1204 			break;
1205 
1206 		case IFD_PROTOCOL_T1:
1207 		        if (ct_config.debug >= 1)
1208 				ct_debug("ps_card_reset_select_protocol: "
1209 					 "using protocol T1");
1210 			ifd_protocol_set_parameter(slot->proto,
1211 						   IFD_PROTOCOL_BLOCK_ORIENTED,
1212 						   1);
1213 			ifd_protocol_set_parameter(slot->proto,
1214 						   IFD_PROTOCOL_T1_IFSC,
1215 						   (atr_info.TA[2] !=
1216 						    -1) ? atr_info.
1217 						   TA[2] : 0x20);
1218 			ifd_protocol_set_parameter(slot->proto,
1219 						   IFD_PROTOCOL_T1_IFSD, 254);
1220 			break;
1221 
1222 		default:
1223 			ct_error("ps_card_reset_select_protocol: "
1224 				 "protocol not supported %#02x",
1225 			     	 atr_info.default_protocol);
1226 			return IFD_ERROR_NOT_SUPPORTED;
1227 		}
1228 
1229 		/* save protocol info */
1230 		device_data->cur_icc_proto = new_icc_proto;
1231 	}
1232 
1233 	return atr_len;
1234 }
1235 
1236 static int
ps_card_reset(ifd_reader_t * reader,int slot,void * atr,size_t size)1237 ps_card_reset(ifd_reader_t * reader, int slot, void *atr, size_t size)
1238 {
1239 	ifd_device_t *dev;
1240 	ps_device_data_t *device_data;
1241 
1242 	if (ct_config.debug >= 1)
1243 		ct_debug("ps_card_reset: called");
1244 
1245 	dev = reader->device;
1246 	device_data = (ps_device_data_t *) dev->user_data;
1247 
1248 	return ps_card_reset_select_protocol(reader, slot,
1249 					     atr, size,
1250 					     device_data->cur_icc_proto);
1251 }
1252 
1253 /*
1254  * Select a protocol for communication with the ICC.
1255  *
1256  */
ps_set_protocol(ifd_reader_t * reader,int nslot,int proto)1257 static int ps_set_protocol(ifd_reader_t * reader, int nslot, int proto)
1258 {
1259 	int rc;
1260 	ifd_device_t *dev;
1261 	ps_device_data_t *device_data;
1262 	ifd_slot_t *slot;
1263 
1264         if (ct_config.debug >= 1)
1265 		ct_debug("ps_set_protocol: called");
1266 
1267 	dev = reader->device;
1268 	device_data = (ps_device_data_t *) dev->user_data;
1269 	slot = &reader->slot[nslot];
1270 
1271 	if (slot->proto == NULL || device_data->cur_icc_proto != proto) {
1272 
1273 		/* the reader negotiates the protocol during the card power up
1274 		   must power down and reset the card to change it */
1275 		rc = ps_card_reset_select_protocol(reader, nslot,
1276 						   slot->atr, sizeof(slot->atr),
1277 						   proto);
1278 
1279 		if (rc >= IFD_SUCCESS) {
1280 			slot->atr_len = rc;
1281 			rc = IFD_SUCCESS;
1282 		} else {
1283 			memset(slot->atr, 0, sizeof(slot->atr));
1284 			slot->atr_len = 0;
1285 		}
1286 
1287 	} else {
1288 		rc = IFD_SUCCESS;
1289 	}
1290 
1291 	return rc;
1292 }
1293 
1294 static int
ps_apdu_send(ifd_reader_t * reader,unsigned int dad,const unsigned char * sbuf,size_t slen)1295 ps_apdu_send(ifd_reader_t * reader, unsigned int dad,
1296 	     const unsigned char *sbuf, size_t slen)
1297 {
1298 	int rc;
1299 	int cse;
1300 	ifd_device_t *dev;
1301 	ps_device_data_t *device_data;
1302 	ps_instruction_t instruction;
1303 	unsigned char t0_buffer[260];
1304 
1305         if (ct_config.debug >= 3)
1306 		ct_debug("ps_apdu_send: sending %i: %s",
1307 		         slen, ct_hexdump(sbuf, slen));
1308 	else
1309 		if (ct_config.debug >= 1)
1310 			ct_debug("ps_apdu_send: called");
1311 
1312 
1313 	dev = reader->device;
1314 	device_data = (ps_device_data_t *) dev->user_data;
1315 
1316 	switch (device_data->cur_icc_proto) {
1317 
1318 	case IFD_PROTOCOL_T0:
1319 
1320 	        if (ct_config.debug >= 1)
1321 			ct_debug("ps_apdu_send: using EXCHANGE_APDU");
1322 
1323 		instruction = PS_EXCHANGE_APDU;
1324 
1325 		/* must have room for le=0 or lc=0 */
1326 		if (sizeof(t0_buffer) <= slen) {
1327 			ct_error("ps_apdu_send: apdu size not supported: "
1328 				 "%i bytes (max: %i)",
1329 			     	 slen, sizeof(t0_buffer) - 1);
1330 			return IFD_ERROR_NO_MEMORY;
1331 		}
1332 
1333 		cse = ifd_apdu_case(sbuf, slen);
1334 
1335 		switch (cse) {
1336 
1337 		case IFD_APDU_CASE_1:
1338 
1339 			if (ct_config.debug >= 1)
1340 				ct_debug("ps_apdu_send: T0 case 1");
1341 
1342 			/* lc = 0 at the end of sbuf
1343 			   must add le = 0 at end */
1344 
1345 			/* fall through */
1346 
1347 		case IFD_APDU_CASE_3S:
1348 
1349 			if (ct_config.debug >= 1 && IFD_APDU_CASE_3S == cse)
1350 				ct_debug("ps_apdu_send: T0 case 3S");
1351 
1352 			/* lc is in the expected placed
1353 			   must add le = 0  at end */
1354 
1355 			memcpy(t0_buffer, sbuf, slen);
1356 
1357 			t0_buffer[slen] = 0;
1358 
1359 			break;
1360 
1361 		case IFD_APDU_CASE_2S:
1362 
1363 			if (ct_config.debug >= 1)
1364 				ct_debug("ps_apdu_send: T0 case 2S");
1365 
1366 			/* le is at the end of sbuf
1367 			   must insert lc = 0 before le */
1368 
1369 			memcpy(t0_buffer, sbuf, slen);
1370 
1371 			t0_buffer[slen] = sbuf[slen - 1];
1372 			t0_buffer[slen - 1] = 0;
1373 
1374 			break;
1375 
1376 		case IFD_ERROR_GENERIC:
1377 			ct_error("ps_apdu_send: ifd_apdu_case failed");
1378 			return IFD_ERROR_GENERIC;
1379 
1380 		default:
1381 			ct_error("ps_apdu_send: apdu case not supported %i",
1382 				 cse);
1383 			return IFD_ERROR_NOT_SUPPORTED;
1384 		}
1385 
1386 		rc = ps_send_to_ifd(reader, instruction, t0_buffer, slen + 1);
1387 
1388 		break;
1389 
1390 	case IFD_PROTOCOL_T1:
1391 		if (ct_config.debug >= 1)
1392 			ct_debug("ps_apdu_send: using EXCHANGE_T1 FRAME");
1393 		instruction = PS_EXCHANGE_T1_FRAME;
1394 		rc = ps_send_to_ifd(reader, instruction, sbuf, slen);
1395 		break;
1396 
1397 	default:
1398 		if (ct_config.debug >= 1)
1399 			ct_debug("ps_apdu_send: unknow protocol");
1400 		return IFD_ERROR_GENERIC;
1401 	}
1402 
1403 	if (rc < 0)
1404 		ct_error("ps_apdu_send: error %i", rc);
1405 
1406 	return rc;
1407 }
1408 
1409 static int
ps_apdu_recv(ifd_reader_t * reader,unsigned int dad,unsigned char * buffer,size_t len,long timeout)1410 ps_apdu_recv(ifd_reader_t * reader, unsigned int dad, unsigned char *buffer,
1411 	     size_t len, long timeout)
1412 {
1413 	int rc;
1414 
1415 	if (ct_config.debug >= 1)
1416 		ct_debug("ps_apdu_recv: called");
1417 
1418 	rc = ps_receive_from_ifd(reader, buffer, len);
1419 
1420 	if (rc < 0) {
1421 		ct_error("ps_apdu_recv: failed");
1422 	} else {
1423 		if (ct_config.debug >= 3)
1424 			ct_debug("ps_apdu_recv: received %i bytes: %s", rc,
1425 				 ct_hexdump(buffer, rc));
1426 	}
1427 
1428 	return rc;
1429 }
1430 
1431 /*
1432  * Initialize the device
1433  */
ps_open(ifd_reader_t * reader,const char * device_name)1434 static int ps_open(ifd_reader_t * reader, const char *device_name)
1435 {
1436 	int rc;
1437 	ifd_device_t *dev;
1438 	ps_device_data_t *device_data;
1439 	ifd_device_params_t params;
1440 
1441 	unsigned char sbuf[2];
1442 
1443 	if (ct_config.debug >= 1)
1444 		ct_debug("ps_open: called: device name =%s", device_name);
1445 
1446 	dev = ifd_device_open(device_name);
1447 
1448 	if (dev == NULL) {
1449 		ct_error("ps_open: failed to open device: %", device_name);
1450 		return IFD_ERROR_GENERIC;
1451 	}
1452 
1453 	switch (dev->type) {
1454 
1455 	case IFD_DEVICE_TYPE_USB:
1456 
1457 		reader->name = PS_USB_READER_NAME;
1458 
1459 		params = dev->settings;
1460 		params.usb.interface = PS_USB_INTERFACE_INDEX;
1461 		params.usb.ep_intr = PS_USB_INTERRUPT_ENDPOINT_ADDRESS;
1462 
1463 		rc = ifd_device_set_parameters(dev, &params);
1464 
1465 		if (rc != IFD_SUCCESS) {
1466 			ct_error("ps_open: ifd_device_set_parameters "
1467 			"returned error %i", rc);
1468 			return rc;
1469 		}
1470 		break;
1471 
1472 	case IFD_DEVICE_TYPE_SERIAL:
1473 		reader->name = PS_SERIAL_READER_NAME;
1474 		break;
1475 
1476 	default:
1477 		ifd_device_close(dev);
1478 		ct_error("ps_open: unknow device type %i", dev->type);
1479 		return IFD_ERROR_GENERIC;
1480 	}
1481 
1482 	sleep(1);
1483 
1484 	ifd_device_flush(dev);
1485 
1486 	device_data = (ps_device_data_t *) calloc(1, sizeof(*device_data));
1487 
1488 	if (NULL == device_data) {
1489 		ifd_device_close(dev);
1490 		ct_error("ps_open: not enough memory");
1491 		return IFD_ERROR_NO_MEMORY;
1492 	}
1493 
1494 	memset(device_data, 0, sizeof(*device_data));
1495 
1496 	device_data->if_state = IDLE;
1497 	device_data->cur_icc_proto = IFD_PROTOCOL_DEFAULT;
1498 
1499 	reader->nslots = 1;
1500 	reader->device = dev;
1501 	reader->device->user_data = device_data;
1502 	reader->device->timeout = PS_TIMEOUT;
1503 
1504 	sbuf[0] = PS_SET_NOTIFICATION_DONT_TRANSMIT;
1505 
1506 	/* disable reader notifications */
1507 	ps_transceive_instruction(reader, PS_SET_NOTIFICATION, sbuf, 1, NULL,
1508 				  0);
1509 
1510 #ifdef not_yet
1511 
1512 	if (dev->type == IFD_DEVICE_TYPE_SERIAL) {
1513 		int rc;
1514 		ifd_device_params_t params;
1515 		unsigned char rbuf[2];
1516 
1517 		/* try to to use 115200 */
1518 
1519 		rc = ifd_device_get_parameters(dev, &params);
1520 
1521 		if (0 > rc) {
1522 			return rc;
1523 		}
1524 
1525 		sbuf[0] = 0;	/* delay */
1526 		sbuf[1] = ps_if_get_baudrate_code(115200);
1527 
1528 		rc = ps_transceive_instruction(reader, PS_SET_PROTOCOL,
1529 					       sbuf, 2, rbuf, sizeof(rbuf));
1530 
1531 		if (rc => 0) {
1532 			params.serial.speed = 115200;
1533 			rc = ifd_device_set_parameters(dev, &params);
1534 
1535 			if (rc < 0)
1536 				return rc;
1537 
1538 			if (ct_config.debug >= 1)
1539 				ct_debug("ps_open: baudrate changed to 115200");
1540 		}
1541 	}
1542 #endif
1543 
1544 	sbuf[0] = PS_OPTION_9600_TO_96000 | PS_OPTION_EMV_MODE_OFF;
1545 
1546 	rc = ps_transceive_instruction(reader, PS_SET_OPTION, sbuf, 1, NULL, 0);
1547 
1548 	if (rc != IFD_SUCCESS) {
1549 		ct_error("ps_open: error setting reader option");
1550 		return rc;
1551 	}
1552 
1553 	return IFD_SUCCESS;
1554 }
1555 
ps_close(ifd_reader_t * reader)1556 static int ps_close(ifd_reader_t * reader)
1557 {
1558 	ifd_device_t *dev;
1559 	ps_device_data_t *device_data;
1560 
1561 	if (ct_config.debug >= 1)
1562 		ct_debug("ps_open: called");
1563 
1564 	dev = reader->device;
1565 	device_data = (ps_device_data_t *) dev->user_data;
1566 
1567 	ps_deactivate(reader);
1568 
1569 	free(device_data);
1570 
1571 	ifd_device_close(dev);
1572 
1573 	return 0;
1574 }
1575 
1576 /*
1577  * Initialize this module
1578  */
ifd_pertosmart_ac1030_register(void)1579 void ifd_pertosmart_ac1030_register(void)
1580 {
1581 
1582 	static struct ifd_driver_ops perto_smart_driver;
1583 
1584 	perto_smart_driver.open = ps_open;
1585 	perto_smart_driver.close = ps_close;
1586 	perto_smart_driver.activate = ps_activate;
1587 	perto_smart_driver.deactivate = ps_deactivate;
1588 	perto_smart_driver.card_status = ps_card_status;
1589 	perto_smart_driver.card_reset = ps_card_reset;
1590 	perto_smart_driver.set_protocol = ps_set_protocol;
1591 	perto_smart_driver.send = ps_apdu_send;
1592 	perto_smart_driver.recv = ps_apdu_recv;
1593 
1594 	ifd_driver_register("pertosmart1030", &perto_smart_driver);
1595 }
1596