1 /*
2 	ccid_usb.c: USB access routines using the libusb library
3 	Copyright (C) 2003-2010	Ludovic Rousseau
4 	Copyright (C) 2009-2019	Advanced Card Systems Ltd.
5 
6 	This library is free software; you can redistribute it and/or
7 	modify it under the terms of the GNU Lesser General Public
8 	License as published by the Free Software Foundation; either
9 	version 2.1 of the License, or (at your option) any later version.
10 
11 	This library is distributed in the hope that it will be useful,
12 	but WITHOUT ANY WARRANTY; without even the implied warranty of
13 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 	Lesser General Public License for more details.
15 
16 	You should have received a copy of the GNU Lesser General Public License
17 	along with this library; if not, write to the Free Software Foundation,
18 	Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20 
21 #define __CCID_USB__
22 
23 #include <stdio.h>
24 #include <string.h>
25 #include <unistd.h>
26 # ifdef S_SPLINT_S
27 # include <sys/types.h>
28 # endif
29 #include <libusb.h>
30 #include <stdlib.h>
31 #include <pthread.h>
32 #include <sys/time.h>
33 #include <ifdhandler.h>
34 
35 #include <config.h>
36 #include "misc.h"
37 #include "ccid.h"
38 #include "debug.h"
39 #include "defs.h"
40 #include "utils.h"
41 #include "parser.h"
42 #include "ccid_ifdhandler.h"
43 
44 
45 /* write timeout
46  * we don't have to wait a long time since the card was doing nothing */
47 #define USB_WRITE_TIMEOUT (5 * 1000)	/* 5 seconds timeout */
48 
49 /*
50  * Proprietary USB Class (0xFF) are (or are not) accepted
51  * A proprietary class is used for devices released before the final CCID
52  * specifications were ready.
53  * We should not have problems with non CCID devices because the
54  * Manufacturer and Product ID are also used to identify the device */
55 #define ALLOW_PROPRIETARY_CLASS
56 
57 #define BUS_DEVICE_STRSIZE 32
58 
59 /* Using the default libusb context */
60 /* does not work for libusb <= 1.0.8 */
61 /* #define ctx NULL */
62 libusb_context *ctx = NULL;
63 
64 #define CCID_INTERRUPT_SIZE 8
65 
66 struct usbDevice_MultiSlot_Extension
67 {
68 	int reader_index;
69 
70 	/* The multi-threaded polling part */
71 	int terminated;
72 	int status;
73 	unsigned char buffer[CCID_INTERRUPT_SIZE];
74 	pthread_t thread_proc;
75 	pthread_mutex_t mutex;
76 	pthread_cond_t condition;
77 	struct libusb_transfer *transfer;
78 };
79 
80 typedef struct
81 {
82 	libusb_device_handle *dev_handle;
83 	uint8_t bus_number;
84 	uint8_t device_address;
85 	int interface;
86 
87 	/*
88 	 * Endpoints
89 	 */
90 	int bulk_in;
91 	int bulk_out;
92 	int interrupt;
93 
94 	/* Number of slots using the same device */
95 	int real_nb_opened_slots;
96 	int *nb_opened_slots;
97 
98 	/*
99 	 * CCID infos common to USB and serial
100 	 */
101 	_ccid_descriptor ccid;
102 
103 	/* libusb transfer for the polling (or NULL) */
104 	struct libusb_transfer *polling_transfer;
105 
106 	/* pointer to the multislot extension (if any) */
107 	struct usbDevice_MultiSlot_Extension *multislot_extension;
108 
109 #ifdef __APPLE__
110 	// Thread handle for card detection
111 	pthread_t hThread;
112 	int threadCreated;
113 
114 	// Flag to terminate thread
115 	int terminated;
116 	int *pTerminated;
117 
118 	// Pointer to libusb transfer
119 	struct libusb_transfer **pTransfer;
120 
121 	// Lock for libusb transfer
122 	pthread_mutex_t transferLock;
123 	pthread_mutex_t *pTransferLock;
124 #endif
125 
126 	// Max packet size of bulk out endpoint
127 	int bulkOutMaxPacketSize;
128 
129 	// For a workaround for ACR122U
130 	int last_write_size;
131 } _usbDevice;
132 
133 /* The _usbDevice structure must be defined before including ccid_usb.h */
134 #include "ccid_usb.h"
135 
136 /* Specific hooks for multislot readers */
137 static int Multi_InterruptRead(int reader_index, int timeout /* in ms */);
138 static void Multi_InterruptStop(int reader_index);
139 static struct usbDevice_MultiSlot_Extension *Multi_CreateFirstSlot(int reader_index);
140 static struct usbDevice_MultiSlot_Extension *Multi_CreateNextSlot(int physical_reader_index);
141 static void Multi_PollingTerminate(struct usbDevice_MultiSlot_Extension *msExt);
142 
143 static int get_end_points(struct libusb_config_descriptor *desc,
144 	_usbDevice *usbdevice, int num);
145 int ccid_check_firmware(struct libusb_device_descriptor *desc);
146 static unsigned int *get_data_rates(unsigned int reader_index,
147 	struct libusb_config_descriptor *desc, int num);
148 
149 #ifdef __APPLE__
150 static void *CardDetectionThread(void *pParam);
151 #endif
152 
153 /* ne need to initialize to 0 since it is static */
154 static _usbDevice usbDevice[CCID_DRIVER_MAX_READERS];
155 
156 #define PCSCLITE_MANUKEY_NAME "ifdVendorID"
157 #define PCSCLITE_PRODKEY_NAME "ifdProductID"
158 #define PCSCLITE_NAMEKEY_NAME "ifdFriendlyName"
159 
160 struct _bogus_firmware
161 {
162 	int vendor;		/* idVendor */
163 	int product;	/* idProduct */
164 	int firmware;	/* bcdDevice: previous firmwares have bugs */
165 };
166 
167 static struct _bogus_firmware Bogus_firmwares[] = {
168 	{ 0x04e6, 0xe001, 0x0516 },	/* SCR 331 */
169 	{ 0x04e6, 0x5111, 0x0620 },	/* SCR 331-DI */
170 	{ 0x04e6, 0xe003, 0x0510 },	/* SPR 532 */
171 	{ 0x0D46, 0x3001, 0x0037 },	/* KAAN Base */
172 	{ 0x0D46, 0x3002, 0x0037 },	/* KAAN Advanced */
173 	{ 0x09C3, 0x0008, 0x0203 },	/* ActivCard V2 */
174 	{ 0x0DC3, 0x1004, 0x0502 },	/* ASE IIIe USBv2 */
175 	{ 0x0DC3, 0x1102, 0x0607 },	/* ASE IIIe KB USB */
176 	{ 0x058F, 0x9520, 0x0102 },	/* Alcor AU9520-G */
177 	{ 0x08C3, 0x0402, 0x5000 },	/* Precise Biometrics Precise 200 MC */
178 	{ 0x08C3, 0x0401, 0x5000 },	/* Precise Biometrics Precise 250 MC */
179 	{ 0x0B0C, 0x0050, 0x0101 },	/* Todos Argos Mini II */
180 	{ 0x0DC3, 0x0900, 0x0200 }, /* Athena IDProtect Key v2 */
181 	{ 0x03F0, 0x0036, 0x0124 }, /* HP USB CCID Smartcard Keyboard */
182 	{ 0x062D, 0x0001, 0x0102 }, /* THRC Smart Card Reader */
183 	{ 0x04E6, 0x5291, 0x0112 }, /* SCM SCL010 Contactless Reader */
184 
185 	/* the firmware version is not correct since I do not have received a
186 	 * working reader yet */
187 #ifndef O2MICRO_OZ776_PATCH
188 	{ 0x0b97, 0x7762, 0x0111 },	/* Oz776S */
189 #endif
190 };
191 
192 /* data rates supported by the secondary slots on the GemCore Pos Pro & SIM Pro */
193 unsigned int SerialCustomDataRates[] = { GEMPLUS_CUSTOM_DATA_RATES, 0 };
194 
195 /*****************************************************************************
196  *
197  *					close_libusb_if_needed
198  *
199  ****************************************************************************/
close_libusb_if_needed(void)200 static void close_libusb_if_needed(void)
201 {
202 	int i, to_exit = TRUE;
203 
204 	if (NULL == ctx)
205 		return;
206 
207 	/* if at least 1 reader is still in use we do not exit libusb */
208 	for (i=0; i<CCID_DRIVER_MAX_READERS; i++)
209 	{
210 		if (usbDevice[i].dev_handle != NULL)
211 			to_exit = FALSE;
212 	}
213 
214 	if (to_exit)
215 	{
216 		DEBUG_INFO1("libusb_exit");
217 		libusb_exit(ctx);
218 		ctx = NULL;
219 	}
220 } /* close_libusb_if_needed */
221 
222 /*****************************************************************************
223  *
224  *					OpenUSB
225  *
226  ****************************************************************************/
OpenUSB(unsigned int reader_index,int Channel)227 status_t OpenUSB(unsigned int reader_index, /*@unused@*/ int Channel)
228 {
229 	(void)Channel;
230 
231 	return OpenUSBByName(reader_index, NULL);
232 } /* OpenUSB */
233 
234 
235 /*****************************************************************************
236  *
237  *					OpenUSBByName
238  *
239  ****************************************************************************/
OpenUSBByName(unsigned int reader_index,char * device)240 status_t OpenUSBByName(unsigned int reader_index, /*@null@*/ char *device)
241 {
242 	unsigned int alias;
243 	struct libusb_device_handle *dev_handle;
244 	char infofile[FILENAME_MAX];
245 #ifndef __APPLE__
246 	unsigned int device_vendor, device_product;
247 	unsigned int device_bus = 0;
248 	unsigned int device_addr = 0;
249 #else
250 	/* 100 ms delay */
251 	struct timespec sleep_time = { 0, 100 * 1000 * 1000 };
252 	int count_libusb = 10;
253 #endif
254 	int interface_number = -1;
255 	int i;
256 	static int previous_reader_index = -1;
257 	libusb_device **devs, *dev;
258 	ssize_t cnt;
259 	list_t plist, *values, *ifdVendorID, *ifdProductID, *ifdFriendlyName;
260 	int rv;
261 	int claim_failed = FALSE;
262 	int return_value = STATUS_SUCCESS;
263 
264 	DEBUG_COMM3("Reader index: %X, Device: %s", reader_index, device);
265 
266 #ifndef __APPLE__
267 	/* device name specified */
268 	if (device)
269 	{
270 		char *dirname;
271 
272 		/* format: usb:%04x/%04x, vendor, product */
273 		if (strncmp("usb:", device, 4) != 0)
274 		{
275 			DEBUG_CRITICAL2("device name does not start with \"usb:\": %s",
276 				device);
277 			return STATUS_UNSUCCESSFUL;
278 		}
279 
280 		if (sscanf(device, "usb:%x/%x", &device_vendor, &device_product) != 2)
281 		{
282 			DEBUG_CRITICAL2("device name can't be parsed: %s", device);
283 			return STATUS_UNSUCCESSFUL;
284 		}
285 
286 		/* format usb:%04x/%04x:libudev:%d:%s
287 		 * with %d set to
288 		 * 01 (or whatever the interface number is)
289 		 * and %s set to
290 		 * /dev/bus/usb/008/004
291 		 */
292 		if ((dirname = strstr(device, "libudev:")) != NULL)
293 		{
294 			/* convert the interface number, bus and device ids */
295 			if (sscanf(dirname + 8, "%d:/dev/bus/usb/%d/%d", &interface_number, &device_bus, &device_addr) == 3) {
296 				DEBUG_COMM2("interface_number: %d", interface_number);
297 				DEBUG_COMM3("usb bus/device: %d/%d", device_bus, device_addr);
298 			}
299 		}
300 		else
301 		{
302 			/* format usb:%04x/%04x:libusb-1.0:%d:%d:%d */
303 			if ((dirname = strstr(device, "libusb-1.0:")) != NULL)
304 			{
305 				/* convert the interface number, bus and device ids */
306 				if (sscanf(dirname + 11, "%d:%d:%d",
307 					&device_bus, &device_addr, &interface_number) == 3)
308 				{
309 					DEBUG_COMM2("interface_number: %d", interface_number);
310 					DEBUG_COMM3("usb bus/device: %d/%d", device_bus,
311 						device_addr);
312 				}
313 			}
314 		}
315 	}
316 #endif
317 
318 	/* is the reader_index already used? */
319 	if (usbDevice[reader_index].dev_handle != NULL)
320 	{
321 		DEBUG_CRITICAL2("USB driver with index %X already in use",
322 			reader_index);
323 		return STATUS_UNSUCCESSFUL;
324 	}
325 
326 	/* Info.plist full patch filename */
327 	(void)snprintf(infofile, sizeof(infofile), "%s/%s/Contents/Info.plist",
328 		PCSCLITE_HP_DROPDIR, BUNDLE);
329 	DEBUG_INFO2("Using: %s", infofile);
330 
331 	rv = bundleParse(infofile, &plist);
332 	if (rv)
333 		return STATUS_UNSUCCESSFUL;
334 
335 #define GET_KEY(key, values) \
336 	rv = LTPBundleFindValueWithKey(&plist, key, &values); \
337 	if (rv) \
338 	{ \
339 		DEBUG_CRITICAL2("Value/Key not defined for " key " in %s", infofile); \
340 		return_value = STATUS_UNSUCCESSFUL; \
341 		goto end1; \
342 	} \
343 	else \
344 		DEBUG_INFO2(key ": %s", (char *)list_get_at(values, 0));
345 
346 	/* general driver info */
347 	GET_KEY("ifdManufacturerString", values)
348 	GET_KEY("ifdProductString", values)
349 	GET_KEY("Copyright", values)
350 
351 	if (NULL == ctx)
352 	{
353 		rv = libusb_init(&ctx);
354 		if (rv != 0)
355 		{
356 			DEBUG_CRITICAL2("libusb_init failed: %s", libusb_error_name(rv));
357 			return_value = STATUS_UNSUCCESSFUL;
358 			goto end1;
359 		}
360 	}
361 
362 #define GET_KEYS(key, values) \
363 	rv = LTPBundleFindValueWithKey(&plist, key, values); \
364 	if (rv) \
365 	{ \
366 		DEBUG_CRITICAL2("Value/Key not defined for " key " in %s", infofile); \
367 		return_value = STATUS_UNSUCCESSFUL; \
368 		goto end1; \
369 	}
370 
371 	GET_KEYS("ifdVendorID", &ifdVendorID)
372 	GET_KEYS("ifdProductID", &ifdProductID);
373 	GET_KEYS("ifdFriendlyName", &ifdFriendlyName)
374 
375 	/* The 3 lists do not have the same size */
376 	if ((list_size(ifdVendorID) != list_size(ifdProductID))
377 		|| (list_size(ifdVendorID) != list_size(ifdFriendlyName)))
378 	{
379 		DEBUG_CRITICAL2("Error parsing %s", infofile);
380 		return_value = STATUS_UNSUCCESSFUL;
381 		goto end1;
382 	}
383 
384 #ifdef __APPLE__
385 again_libusb:
386 #endif
387 	cnt = libusb_get_device_list(ctx, &devs);
388 	if (cnt < 0)
389 	{
390 		DEBUG_CRITICAL("libusb_get_device_list() failed\n");
391 		return_value = STATUS_UNSUCCESSFUL;
392 		goto end1;
393 	}
394 
395 	/* for any supported reader */
396 	for (alias=0; alias<list_size(ifdVendorID); alias++)
397 	{
398 		unsigned int vendorID, productID;
399 		char *friendlyName;
400 
401 		vendorID = strtoul(list_get_at(ifdVendorID, alias), NULL, 0);
402 		productID = strtoul(list_get_at(ifdProductID, alias), NULL, 0);
403 		friendlyName = list_get_at(ifdFriendlyName, alias);
404 
405 #ifndef __APPLE__
406 		/* the device was specified but is not the one we are trying to find */
407 		if (device
408 			&& (vendorID != device_vendor || productID != device_product))
409 			continue;
410 #else
411 		/* Leopard puts the friendlyname in the device argument */
412 		if (device && strcmp(device, friendlyName))
413 			continue;
414 #endif
415 
416 		/* for every device */
417 		i = 0;
418 		while ((dev = devs[i++]) != NULL)
419 		{
420 			struct libusb_device_descriptor desc;
421 			struct libusb_config_descriptor *config_desc;
422 			uint8_t bus_number = libusb_get_bus_number(dev);
423 			uint8_t device_address = libusb_get_device_address(dev);
424 
425 #ifndef __APPLE__
426 			if ((device_bus || device_addr)
427 				&& ((bus_number != device_bus)
428 				|| (device_address != device_addr))) {
429 				/* not USB the device we are looking for */
430 				continue;
431 			}
432 #endif
433 			DEBUG_COMM3("Try device: %d/%d", bus_number, device_address);
434 
435 			int r = libusb_get_device_descriptor(dev, &desc);
436 			if (r < 0)
437 			{
438 				DEBUG_INFO3("failed to get device descriptor for %d/%d",
439 					bus_number, device_address);
440 				continue;
441 			}
442 
443 			DEBUG_COMM3("vid/pid : %04X/%04X", desc.idVendor, desc.idProduct);
444 
445 			if (desc.idVendor == vendorID && desc.idProduct == productID)
446 			{
447 				int already_used;
448 				const struct libusb_interface *usb_interface = NULL;
449 				int interface;
450 				int num = 0;
451 				const unsigned char *device_descriptor;
452 				int readerID = (vendorID << 16) + productID;
453 				int numSlots = 0;
454 
455 #ifdef USE_COMPOSITE_AS_MULTISLOT
456 				/* use the first CCID interface on first call */
457 				static int static_interface = -1;
458 				int max_interface_number = 2;
459 
460 				/* simulate a composite device as when libudev is used */
461 				if ((GEMALTOPROXDU == readerID)
462 					|| (GEMALTOPROXSU == readerID)
463 					|| (HID_OMNIKEY_5422 == readerID)
464 					|| (FEITIANR502DUAL == readerID)
465 					|| (ACS_ACR1281_DUAL_READER_QPBOC == readerID)
466 					|| (ACS_ACR1281_DUAL_READER_BSI == readerID)
467 					|| (ACS_ACR1281_1S_PICC_READER == readerID)
468 					|| (ACS_ACR1251_1S_CL_READER == readerID)
469 					|| (ACS_ACR1251U_C == readerID)
470 					|| (ACS_ACR1251K_DUAL_READER == readerID)
471 					|| (ACS_ACR1252_1S_CL_READER == readerID)
472 					|| (ACS_ACR1252IMP_1S_CL_READER == readerID))
473 				{
474 						/*
475 						 * We can't talk to the two CCID interfaces
476 						 * at the same time (the reader enters a
477 						 * dead lock). So we simulate a multi slot
478 						 * reader. By default multi slot readers
479 						 * can't use the slots at the same time. See
480 						 * TAG_IFD_SLOT_THREAD_SAFE
481 						 *
482 						 * One side effect is that the two readers
483 						 * are seen by pcscd as one reader so the
484 						 * interface name is the same for the two.
485 						 *
486 	* So we have:
487 	* 0: Gemalto Prox-DU [Prox-DU Contact_09A00795] (09A00795) 00 00
488 	* 1: Gemalto Prox-DU [Prox-DU Contact_09A00795] (09A00795) 00 01
489 	* instead of
490 	* 0: Gemalto Prox-DU [Prox-DU Contact_09A00795] (09A00795) 00 00
491 	* 1: Gemalto Prox-DU [Prox-DU Contactless_09A00795] (09A00795) 01 00
492 						 */
493 
494 					/* for the Gemalto Prox-DU/SU the interfaces are:
495 					 * 0: Prox-DU HID (not used)
496 					 * 1: Prox-DU Contactless (CCID)
497 					 * 2: Prox-DU Contact (CCID)
498 					 *
499 					 * For the Feitian R502 the interfaces are:
500 					 * 0: R502 Contactless Reader (CCID)
501 					 * 1: R502 Contact Reader (CCID)
502 					 * 2: R502 SAM1 Reader (CCID)
503 					 *
504 					 * For the HID Omnikey 5422 the interfaces are:
505 					 * 0: OMNIKEY 5422CL Smartcard Reader
506 					 * 1: OMNIKEY 5422 Smartcard Reader
507 					 */
508 					interface_number = static_interface;
509 
510 					if ((HID_OMNIKEY_5422 == readerID)
511 						|| (ACS_ACR1281_DUAL_READER_QPBOC == readerID)
512 						|| (ACS_ACR1281_DUAL_READER_BSI == readerID)
513 						|| (ACS_ACR1281_1S_PICC_READER == readerID)
514 						|| (ACS_ACR1251_1S_CL_READER == readerID)
515 						|| (ACS_ACR1251U_C == readerID)
516 						|| (ACS_ACR1251K_DUAL_READER == readerID)
517 						|| (ACS_ACR1252_1S_CL_READER == readerID)
518 						|| (ACS_ACR1252IMP_1S_CL_READER == readerID))
519 						/* only 2 interfaces for this device */
520 						max_interface_number = 1;
521 				}
522 #endif
523 				/* is it already opened? */
524 				already_used = FALSE;
525 
526 				DEBUG_COMM3("Checking device: %d/%d",
527 					bus_number, device_address);
528 				for (r=0; r<CCID_DRIVER_MAX_READERS; r++)
529 				{
530 					if (usbDevice[r].dev_handle)
531 					{
532 						/* same bus, same address */
533 						if (usbDevice[r].bus_number == bus_number
534 							&& usbDevice[r].device_address == device_address)
535 							already_used = TRUE;
536 					}
537 				}
538 
539 				/* this reader is already managed by us */
540 				if (already_used)
541 				{
542 					if ((previous_reader_index != -1)
543 						&& usbDevice[previous_reader_index].dev_handle
544 						&& (usbDevice[previous_reader_index].bus_number == bus_number)
545 						&& (usbDevice[previous_reader_index].device_address == device_address)
546 						&& usbDevice[previous_reader_index].ccid.bCurrentSlotIndex < usbDevice[previous_reader_index].ccid.bMaxSlotIndex)
547 					{
548 						/* we reuse the same device
549 						 * and the reader is multi-slot */
550 						usbDevice[reader_index] = usbDevice[previous_reader_index];
551 						/* The other slots of GemCore SIM Pro firmware
552 						 * 1.0 do not have the same data rates.
553 						 * Firmware 2.0 do not have this limitation */
554 						if ((GEMCOREPOSPRO == readerID)
555 							|| ((GEMCORESIMPRO == readerID)
556 							&& (usbDevice[reader_index].ccid.IFD_bcdDevice < 0x0200)))
557 						{
558 							/* Allocate a memory buffer that will be
559 							 * released in CloseUSB() */
560 							void *ptr = malloc(sizeof SerialCustomDataRates);
561 							if (ptr)
562 							{
563 								memcpy(ptr, SerialCustomDataRates,
564 									sizeof SerialCustomDataRates);
565 							}
566 
567 							usbDevice[reader_index].ccid.arrayOfSupportedDataRates = ptr;
568 							usbDevice[reader_index].ccid.dwMaxDataRate = 125000;
569 						}
570 
571 						*usbDevice[reader_index].nb_opened_slots += 1;
572 						usbDevice[reader_index].ccid.bCurrentSlotIndex++;
573 						usbDevice[reader_index].ccid.dwSlotStatus =
574 							IFD_ICC_PRESENT;
575 						DEBUG_INFO2("Opening slot: %d",
576 							usbDevice[reader_index].ccid.bCurrentSlotIndex);
577 
578 						// Simulate ACR85 as multi-slot reader
579 						if (usbDevice[reader_index].ccid.readerID == ACS_ACR85_PINPAD_READER_ICC)
580 						{
581 							libusb_device *picc_dev = NULL;
582 							int picc_index = 0;
583 							struct libusb_device_descriptor picc_desc;
584 							uint8_t picc_bus_number = 0;
585 
586 							// Reset number of opened slots
587 							*usbDevice[reader_index].nb_opened_slots = 1;
588 
589 							// Find PICC
590 							dev = NULL;
591 							while ((picc_dev = devs[picc_index++]) != NULL)
592 							{
593 								picc_bus_number = libusb_get_bus_number(picc_dev);
594 
595 								r = libusb_get_device_descriptor(picc_dev, &picc_desc);
596 								if (r < 0)
597 								{
598 									continue;
599 								}
600 
601 								if ((picc_bus_number == bus_number) &&
602 									((picc_desc.idVendor << 16) + picc_desc.idProduct == ACS_ACR85_PINPAD_READER_PICC))
603 								{
604 									dev = picc_dev;
605 									break;
606 								}
607 							}
608 
609 							if (dev == NULL)
610 							{
611 								DEBUG_CRITICAL("ACR85 PICC not found.");
612 								return_value = STATUS_UNSUCCESSFUL;
613 								goto end2;
614 							}
615 						}
616 						else
617 						{
618 #ifndef __APPLE__
619 							/* This is a multislot reader
620 							 * Init the multislot stuff for this next slot */
621 							usbDevice[reader_index].multislot_extension = Multi_CreateNextSlot(previous_reader_index);
622 #endif
623 							goto end;
624 						}
625 					}
626 					else
627 					{
628 						/* if an interface number is given by HAL we
629 						 * continue with this device. */
630 						if (-1 == interface_number)
631 						{
632 							DEBUG_INFO3("USB device %d/%d already in use."
633 								" Checking next one.",
634 								bus_number, device_address);
635 							continue;
636 						}
637 					}
638 				}
639 
640 				DEBUG_COMM3("Trying to open USB bus/device: %d/%d",
641 					bus_number, device_address);
642 
643 				r = libusb_open(dev, &dev_handle);
644 				if (r < 0)
645 				{
646 					DEBUG_CRITICAL4("Can't libusb_open(%d/%d): %s",
647 						bus_number, device_address, libusb_error_name(r));
648 
649 					continue;
650 				}
651 
652 again:
653 				r = libusb_get_active_config_descriptor(dev, &config_desc);
654 				if (r < 0)
655 				{
656 #ifdef __APPLE__
657 					/* Some early Gemalto Ezio CB+ readers have
658 					 * bDeviceClass, bDeviceSubClass and bDeviceProtocol set
659 					 * to 0xFF (proprietary) instead of 0x00.
660 					 *
661 					 * So on Mac OS X the reader configuration is not done
662 					 * by the OS/kernel and we do it ourself.
663 					 */
664 					r = libusb_set_configuration(dev_handle, 1);
665 					if (r < 0)
666 					{
667 						(void)libusb_close(dev_handle);
668 						DEBUG_CRITICAL4("Can't set configuration on %d/%d: %s",
669 								bus_number, device_address,
670 								libusb_error_name(r));
671 						continue;
672 					}
673 
674 					/* recall */
675 					r = libusb_get_active_config_descriptor(dev, &config_desc);
676 					if (r < 0)
677 					{
678 #endif
679 						(void)libusb_close(dev_handle);
680 						DEBUG_CRITICAL4("Can't get config descriptor on %d/%d: %s",
681 							bus_number, device_address, libusb_error_name(r));
682 						continue;
683 					}
684 #ifdef __APPLE__
685 				}
686 #endif
687 
688 
689 				usb_interface = get_ccid_usb_interface(config_desc, &num);
690 				if (usb_interface == NULL)
691 				{
692 					libusb_free_config_descriptor(config_desc);
693 					(void)libusb_close(dev_handle);
694 					if (0 == num)
695 						DEBUG_CRITICAL3("Can't find a CCID interface on %d/%d",
696 							bus_number, device_address);
697 					interface_number = -1;
698 					continue;
699 				}
700 
701 				device_descriptor = get_ccid_device_descriptor(usb_interface);
702 				if (NULL == device_descriptor)
703 				{
704 					// These readers do not have altsetting
705 					if ((readerID != ACS_ACR38U) &&
706 						(readerID != ACS_ACR38U_SAM) &&
707 						(readerID != IRIS_SCR21U) &&
708 						(readerID != ACS_AET65_1SAM_ICC_READER) &&
709 						(readerID != ACS_CRYPTOMATE) &&
710 						(readerID != ACS_ACR88U) &&
711 						(readerID != ACS_ACR128U) &&
712 						(readerID != ACS_ACR1281_1S_DUAL_READER) &&
713 						(readerID != ACS_ACR1281_2S_CL_READER))
714 					{
715 						libusb_free_config_descriptor(config_desc);
716 						(void)libusb_close(dev_handle);
717 						DEBUG_CRITICAL3("Unable to find the device descriptor for %d/%d",
718 							bus_number, device_address);
719 						return_value = STATUS_UNSUCCESSFUL;
720 						goto end2;
721 					}
722 				}
723 
724 				interface = usb_interface->altsetting->bInterfaceNumber;
725 				if (interface_number >= 0 && interface != interface_number)
726 				{
727 					libusb_free_config_descriptor(config_desc);
728 					/* an interface was specified and it is not the
729 					 * current one */
730 					DEBUG_INFO3("Found interface %d but expecting %d",
731 						interface, interface_number);
732 					DEBUG_INFO3("Wrong interface for USB device %d/%d."
733 						" Checking next one.", bus_number, device_address);
734 
735 					/* check for another CCID interface on the same device */
736 					num++;
737 
738 					goto again;
739 				}
740 
741 				r = libusb_claim_interface(dev_handle, interface);
742 				if (r < 0)
743 				{
744 					libusb_free_config_descriptor(config_desc);
745 					(void)libusb_close(dev_handle);
746 					DEBUG_CRITICAL4("Can't claim interface %d/%d: %s",
747 						bus_number, device_address, libusb_error_name(r));
748 					claim_failed = TRUE;
749 					interface_number = -1;
750 					continue;
751 				}
752 
753 				DEBUG_INFO4("Found Vendor/Product: %04X/%04X (%s)",
754 					desc.idVendor, desc.idProduct, friendlyName);
755 				DEBUG_INFO3("Using USB bus/device: %d/%d",
756 					bus_number, device_address);
757 
758 				/* check for firmware bugs */
759 				if (ccid_check_firmware(&desc))
760 				{
761 					libusb_free_config_descriptor(config_desc);
762 					(void)libusb_close(dev_handle);
763 					return_value = STATUS_UNSUCCESSFUL;
764 					goto end2;
765 				}
766 
767 #ifdef USE_COMPOSITE_AS_MULTISLOT
768 				if ((GEMALTOPROXDU == readerID)
769 					|| (GEMALTOPROXSU == readerID)
770 					|| (HID_OMNIKEY_5422 == readerID)
771 					|| (FEITIANR502DUAL == readerID)
772 					|| (ACS_ACR1281_DUAL_READER_QPBOC == readerID)
773 					|| (ACS_ACR1281_DUAL_READER_BSI == readerID)
774 					|| (ACS_ACR1281_1S_PICC_READER == readerID)
775 					|| (ACS_ACR1251_1S_CL_READER == readerID)
776 					|| (ACS_ACR1251U_C == readerID)
777 					|| (ACS_ACR1251K_DUAL_READER == readerID)
778 					|| (ACS_ACR1252_1S_CL_READER == readerID)
779 					|| (ACS_ACR1252IMP_1S_CL_READER == readerID))
780 				{
781 					/* use the next interface for the next "slot" */
782 					static_interface = interface + 1;
783 
784 					/* reset for a next reader */
785 					/* max interface number for all 3 readers is 2 */
786 					if (static_interface > max_interface_number)
787 						static_interface = -1;
788 				}
789 #endif
790 
791 				/* Get Endpoints values*/
792 				(void)get_end_points(config_desc, &usbDevice[reader_index], num);
793 
794 				/* store device information */
795 				usbDevice[reader_index].dev_handle = dev_handle;
796 				usbDevice[reader_index].bus_number = bus_number;
797 				usbDevice[reader_index].device_address = device_address;
798 				usbDevice[reader_index].interface = interface;
799 				usbDevice[reader_index].real_nb_opened_slots = 1;
800 				usbDevice[reader_index].nb_opened_slots = &usbDevice[reader_index].real_nb_opened_slots;
801 				usbDevice[reader_index].polling_transfer = NULL;
802 
803 				/* CCID common informations */
804 				usbDevice[reader_index].ccid.real_bSeq = 0;
805 				usbDevice[reader_index].ccid.pbSeq = &usbDevice[reader_index].ccid.real_bSeq;
806 				usbDevice[reader_index].ccid.readerID =
807 					(desc.idVendor << 16) + desc.idProduct;
808 
809 				// These readers do not have altsetting
810 				if ((readerID == ACS_ACR38U) || (readerID == ACS_CRYPTOMATE))
811 				{
812 					usbDevice[reader_index].ccid.dwFeatures = 0x00010030;
813 					usbDevice[reader_index].ccid.wLcdLayout = 0;
814 					usbDevice[reader_index].ccid.bPINSupport = 0;
815 					usbDevice[reader_index].ccid.dwMaxCCIDMessageLength = 271;
816 					usbDevice[reader_index].ccid.dwMaxIFSD = 248;
817 					usbDevice[reader_index].ccid.dwDefaultClock = 4000;
818 					usbDevice[reader_index].ccid.dwMaxDataRate = 229390;
819 					usbDevice[reader_index].ccid.bMaxSlotIndex = 0;
820 					usbDevice[reader_index].ccid.bCurrentSlotIndex = 0;
821 					usbDevice[reader_index].ccid.readTimeout = DEFAULT_COM_READ_TIMEOUT;
822 					usbDevice[reader_index].ccid.arrayOfSupportedDataRates = NULL;
823 					usbDevice[reader_index].ccid.bInterfaceProtocol = PROTOCOL_ACR38;
824 					usbDevice[reader_index].ccid.bNumEndpoints = 3;
825 					usbDevice[reader_index].ccid.dwSlotStatus = IFD_ICC_PRESENT;
826 					usbDevice[reader_index].ccid.bVoltageSupport = 0x07;
827 				}
828 				else if ((readerID == ACS_ACR38U_SAM) || (readerID == IRIS_SCR21U) ||
829 					(readerID == ACS_AET65_1SAM_ICC_READER))
830 				{
831 					usbDevice[reader_index].ccid.dwFeatures = 0x00010030;
832 					usbDevice[reader_index].ccid.wLcdLayout = 0;
833 					usbDevice[reader_index].ccid.bPINSupport = 0;
834 					usbDevice[reader_index].ccid.dwMaxCCIDMessageLength = 271;
835 					usbDevice[reader_index].ccid.dwMaxIFSD = 248;
836 					usbDevice[reader_index].ccid.dwDefaultClock = 4000;
837 					usbDevice[reader_index].ccid.dwMaxDataRate = 229390;
838 					usbDevice[reader_index].ccid.bMaxSlotIndex = 1;
839 					usbDevice[reader_index].ccid.bCurrentSlotIndex = 0;
840 					usbDevice[reader_index].ccid.readTimeout = DEFAULT_COM_READ_TIMEOUT;
841 					usbDevice[reader_index].ccid.arrayOfSupportedDataRates = NULL;
842 					usbDevice[reader_index].ccid.bInterfaceProtocol = PROTOCOL_ACR38;
843 					usbDevice[reader_index].ccid.bNumEndpoints = 3;
844 					usbDevice[reader_index].ccid.dwSlotStatus = IFD_ICC_PRESENT;
845 					usbDevice[reader_index].ccid.bVoltageSupport = 0x07;
846 				}
847 				else if (readerID == ACS_ACR88U)
848 				{
849 					usbDevice[reader_index].ccid.dwFeatures = 0x000204BA;
850 					usbDevice[reader_index].ccid.wLcdLayout = 0x0815;
851 					usbDevice[reader_index].ccid.bPINSupport = 0x03;
852 					usbDevice[reader_index].ccid.dwMaxCCIDMessageLength = 271;
853 					usbDevice[reader_index].ccid.dwMaxIFSD = 248;
854 					usbDevice[reader_index].ccid.dwDefaultClock = 3600;
855 					usbDevice[reader_index].ccid.dwMaxDataRate = 116129;
856 					usbDevice[reader_index].ccid.bMaxSlotIndex = 4;
857 					usbDevice[reader_index].ccid.bCurrentSlotIndex = 0;
858 					usbDevice[reader_index].ccid.readTimeout = DEFAULT_COM_READ_TIMEOUT;
859 					usbDevice[reader_index].ccid.arrayOfSupportedDataRates = NULL;
860 					usbDevice[reader_index].ccid.bInterfaceProtocol = 0;
861 					usbDevice[reader_index].ccid.bNumEndpoints = 3;
862 					usbDevice[reader_index].ccid.dwSlotStatus = IFD_ICC_PRESENT;
863 					usbDevice[reader_index].ccid.bVoltageSupport = 0x03;
864 				}
865 				else if (readerID == ACS_ACR128U)
866 				{
867 					usbDevice[reader_index].ccid.dwFeatures = 0x000204BA;
868 					usbDevice[reader_index].ccid.wLcdLayout = 0;
869 					usbDevice[reader_index].ccid.bPINSupport = 0;
870 					usbDevice[reader_index].ccid.dwMaxCCIDMessageLength = 271;
871 					usbDevice[reader_index].ccid.dwMaxIFSD = 248;
872 					usbDevice[reader_index].ccid.dwDefaultClock = 3600;
873 					usbDevice[reader_index].ccid.dwMaxDataRate = 116129;
874 					usbDevice[reader_index].ccid.bMaxSlotIndex = 2;
875 					usbDevice[reader_index].ccid.bCurrentSlotIndex = 0;
876 					usbDevice[reader_index].ccid.readTimeout = DEFAULT_COM_READ_TIMEOUT;
877 					usbDevice[reader_index].ccid.arrayOfSupportedDataRates = NULL;
878 					usbDevice[reader_index].ccid.bInterfaceProtocol = 0;
879 					usbDevice[reader_index].ccid.bNumEndpoints = 3;
880 					usbDevice[reader_index].ccid.dwSlotStatus = IFD_ICC_PRESENT;
881 					usbDevice[reader_index].ccid.bVoltageSupport = 0x03;
882 				}
883 				else if ((readerID == ACS_ACR1251_1S_DUAL_READER) ||
884 					(readerID == ACS_ACR1261_1S_DUAL_READER) ||
885 					(readerID == ACS_ACR1281_1S_DUAL_READER) ||
886 					(readerID == ACS_ACR1281_2S_CL_READER))
887 				{
888 					usbDevice[reader_index].ccid.dwFeatures = 0x000204BA;
889 					usbDevice[reader_index].ccid.wLcdLayout = 0;
890 					usbDevice[reader_index].ccid.bPINSupport = 0;
891 					usbDevice[reader_index].ccid.dwMaxCCIDMessageLength = 271;
892 					usbDevice[reader_index].ccid.dwMaxIFSD = 248;
893 					usbDevice[reader_index].ccid.dwDefaultClock = 4000;
894 					usbDevice[reader_index].ccid.dwMaxDataRate = 344100;
895 					usbDevice[reader_index].ccid.bMaxSlotIndex = 2;
896 					usbDevice[reader_index].ccid.bCurrentSlotIndex = 0;
897 					usbDevice[reader_index].ccid.readTimeout = DEFAULT_COM_READ_TIMEOUT;
898 					usbDevice[reader_index].ccid.arrayOfSupportedDataRates = NULL;
899 					usbDevice[reader_index].ccid.bInterfaceProtocol = 0;
900 					usbDevice[reader_index].ccid.bNumEndpoints = 3;
901 					usbDevice[reader_index].ccid.dwSlotStatus = IFD_ICC_PRESENT;
902 					usbDevice[reader_index].ccid.bVoltageSupport = 0x03;
903 				}
904 				else
905 				{
906 					usbDevice[reader_index].ccid.dwFeatures = dw2i(device_descriptor, 40);
907 					usbDevice[reader_index].ccid.wLcdLayout =
908 						(device_descriptor[51] << 8) + device_descriptor[50];
909 					usbDevice[reader_index].ccid.bPINSupport = device_descriptor[52];
910 					usbDevice[reader_index].ccid.dwMaxCCIDMessageLength = dw2i(device_descriptor, 44);
911 					usbDevice[reader_index].ccid.dwMaxIFSD = dw2i(device_descriptor, 28);
912 					usbDevice[reader_index].ccid.dwDefaultClock = dw2i(device_descriptor, 10);
913 					usbDevice[reader_index].ccid.dwMaxDataRate = dw2i(device_descriptor, 23);
914 
915 					// Fix ACR1222 incorrect max slot index
916 					if ((readerID == ACS_ACR1222_1SAM_PICC_READER) ||
917 						(readerID == ACS_ACR1222_DUAL_READER))
918 						usbDevice[reader_index].ccid.bMaxSlotIndex = 1;
919 					else if (readerID == ACS_ACR1222_1SAM_DUAL_READER)
920 						usbDevice[reader_index].ccid.bMaxSlotIndex = 2;
921 					// Fix ACR32 incorrect max slot index
922 					else if (readerID == ACS_ACR32_ICC_READER)
923 						usbDevice[reader_index].ccid.bMaxSlotIndex = 0;
924 					else
925 						usbDevice[reader_index].ccid.bMaxSlotIndex = device_descriptor[4];
926 
927 					usbDevice[reader_index].ccid.bCurrentSlotIndex = 0;
928 					usbDevice[reader_index].ccid.readTimeout = DEFAULT_COM_READ_TIMEOUT;
929 					if (device_descriptor[27])
930 						usbDevice[reader_index].ccid.arrayOfSupportedDataRates = get_data_rates(reader_index, config_desc, num);
931 					else
932 					{
933 						usbDevice[reader_index].ccid.arrayOfSupportedDataRates = NULL;
934 						DEBUG_INFO1("bNumDataRatesSupported is 0");
935 					}
936 					usbDevice[reader_index].ccid.bInterfaceProtocol = usb_interface->altsetting->bInterfaceProtocol;
937 					usbDevice[reader_index].ccid.bNumEndpoints = usb_interface->altsetting->bNumEndpoints;
938 					usbDevice[reader_index].ccid.dwSlotStatus = IFD_ICC_PRESENT;
939 					usbDevice[reader_index].ccid.bVoltageSupport = device_descriptor[5];
940 				}
941 
942 				usbDevice[reader_index].ccid.sIFD_serial_number = NULL;
943 				usbDevice[reader_index].ccid.gemalto_firmware_features = NULL;
944 				if (desc.iSerialNumber)
945 				{
946 					unsigned char serial[128];
947 					int ret;
948 
949 					ret = libusb_get_string_descriptor_ascii(dev_handle,
950 							desc.iSerialNumber, serial,
951 							sizeof(serial));
952 					if (ret > 0)
953 						usbDevice[reader_index].ccid.sIFD_serial_number
954 							= strdup((char *)serial);
955 				}
956 
957 				usbDevice[reader_index].ccid.sIFD_iManufacturer = NULL;
958 				if (desc.iManufacturer)
959 				{
960 					unsigned char iManufacturer[128];
961 					int ret;
962 
963 					ret = libusb_get_string_descriptor_ascii(dev_handle,
964 							desc.iManufacturer, iManufacturer,
965 							sizeof(iManufacturer));
966 					if (ret > 0)
967 						usbDevice[reader_index].ccid.sIFD_iManufacturer
968 							= strdup((char *)iManufacturer);
969 				}
970 
971 				usbDevice[reader_index].ccid.IFD_bcdDevice = desc.bcdDevice;
972 #ifndef __APPLE__
973 				/* If this is a multislot reader, init the multislot stuff */
974 				if (usbDevice[reader_index].ccid.bMaxSlotIndex)
975 					usbDevice[reader_index].multislot_extension = Multi_CreateFirstSlot(reader_index);
976 				else
977 #endif
978 					usbDevice[reader_index].multislot_extension = NULL;
979 
980 				libusb_free_config_descriptor(config_desc);
981 
982 				// Get number of slots
983 				numSlots = usbDevice[reader_index].ccid.bMaxSlotIndex + 1;
984 
985 				// Allocate array of bStatus
986 				usbDevice[reader_index].ccid.bStatus = (unsigned char *) calloc(numSlots, sizeof(unsigned char));
987 				if (usbDevice[reader_index].ccid.bStatus == NULL)
988 				{
989 					(void)libusb_close(dev_handle);
990 					DEBUG_CRITICAL("Not enough memory");
991 					return_value = STATUS_UNSUCCESSFUL;
992 					goto end2;
993 				}
994 
995 				// Initialize array of bStatus
996 				memset(usbDevice[reader_index].ccid.bStatus, 0xFF, numSlots * sizeof(unsigned char));
997 
998 				// Initialize firmware fix enabled
999 				usbDevice[reader_index].ccid.firmwareFixEnabled = FALSE;
1000 
1001 				// Simulate ACR85 as multi-slot reader
1002 				if (readerID == ACS_ACR85_PINPAD_READER_ICC)
1003 					usbDevice[reader_index].ccid.bMaxSlotIndex = 1;
1004 
1005 				// Simulate ACR85 as multi-slot reader
1006 				if (readerID != ACS_ACR85_PINPAD_READER_PICC)
1007 				{
1008 					// Initialize PICC enabled
1009 					usbDevice[reader_index].ccid.piccEnabled = TRUE;
1010 					usbDevice[reader_index].ccid.pPiccEnabled = &usbDevice[reader_index].ccid.piccEnabled;
1011 
1012 					// Initialize PICC reader index
1013 					usbDevice[reader_index].ccid.piccReaderIndex = -1;
1014 					usbDevice[reader_index].ccid.pPiccReaderIndex = &usbDevice[reader_index].ccid.piccReaderIndex;
1015 				}
1016 
1017 				// Initialize card voltage (ACR38U, ACR38U-SAM and SCR21U)
1018 				usbDevice[reader_index].ccid.cardVoltage = 0;
1019 
1020 				// Initialize card type (ACR38U, ACR38U-SAM and SCR21U)
1021 				usbDevice[reader_index].ccid.cardType = 0;
1022 
1023 				// Initialize isSamSlot
1024 				usbDevice[reader_index].ccid.isSamSlot = FALSE;
1025 
1026 				// The 2nd interface (composite device) is a SAM slot
1027 				if ((readerID == ACS_ACR1281_1S_PICC_READER) ||
1028 					(readerID == ACS_ACR1251_1S_CL_READER) ||
1029 					(readerID == ACS_ACR1251U_C) ||
1030 					(readerID == ACS_ACR1252_1S_CL_READER) ||
1031 					(readerID == ACS_ACR1252IMP_1S_CL_READER))
1032 				{
1033 					if (interface == 1)
1034 						usbDevice[reader_index].ccid.isSamSlot = TRUE;
1035 				}
1036 #ifdef __APPLE__
1037 				// Initialize terminated flag to false
1038 				usbDevice[reader_index].terminated = FALSE;
1039 				usbDevice[reader_index].pTerminated = &usbDevice[reader_index].terminated;
1040 				usbDevice[reader_index].pTransfer = &usbDevice[reader_index].polling_transfer;
1041 				usbDevice[reader_index].pTransferLock = &usbDevice[reader_index].transferLock;
1042 				usbDevice[reader_index].threadCreated = FALSE;
1043 				usbDevice[reader_index].ccid.pbStatusLock = &usbDevice[reader_index].ccid.bStatusLock;
1044 				usbDevice[reader_index].ccid.lastSlotOpened = FALSE;
1045 				usbDevice[reader_index].ccid.pLastSlotOpened = &usbDevice[reader_index].ccid.lastSlotOpened;
1046 
1047 				// Create transfer lock
1048 				r = pthread_mutex_init(usbDevice[reader_index].pTransferLock, NULL);
1049 				if (r != 0)
1050 				{
1051 					(void)libusb_close(dev_handle);
1052 					DEBUG_CRITICAL2("pthread_mutex_init failed with error %d", r);
1053 					return_value = STATUS_UNSUCCESSFUL;
1054 					goto end2;
1055 				}
1056 
1057 				// Create bStatus lock
1058 				r = pthread_mutex_init(usbDevice[reader_index].ccid.pbStatusLock, NULL);
1059 				if (r != 0)
1060 				{
1061 					pthread_mutex_destroy(usbDevice[reader_index].pTransferLock);
1062 					free(usbDevice[reader_index].ccid.bStatus);
1063 
1064 					(void)libusb_close(dev_handle);
1065 					DEBUG_CRITICAL2("pthread_mutex_init failed with error %d", r);
1066 					return_value = STATUS_UNSUCCESSFUL;
1067 					goto end2;
1068 				}
1069 
1070 				/* Disable card detection thread for APG8201-B2. */
1071 				if (usbDevice[reader_index].ccid.readerID == ACS_APG8201_B2)
1072 				{
1073 					goto end;
1074 				}
1075 
1076 				// Create thread for card detection
1077 				r = pthread_create(&usbDevice[reader_index].hThread, NULL, CardDetectionThread, (void *) (intptr_t) reader_index);
1078 				if (r != 0)
1079 				{
1080 					pthread_mutex_destroy(usbDevice[reader_index].pTransferLock);
1081 					pthread_mutex_destroy(usbDevice[reader_index].ccid.pbStatusLock);
1082 					free(usbDevice[reader_index].ccid.bStatus);
1083 
1084 					(void)libusb_close(dev_handle);
1085 					DEBUG_CRITICAL2("pthread_create failed with error %d", r);
1086 					return_value = STATUS_UNSUCCESSFUL;
1087 					goto end2;
1088 				}
1089 
1090 				usbDevice[reader_index].threadCreated = TRUE;
1091 #endif
1092 				goto end;
1093 			}
1094 		}
1095 	}
1096 end:
1097 	if (usbDevice[reader_index].dev_handle == NULL)
1098 	{
1099 		/* free the libusb allocated list & devices */
1100 		libusb_free_device_list(devs, 1);
1101 
1102 #ifdef __APPLE__
1103 		/* give some time to libusb to detect the new USB devices on Mac OS X */
1104 		if (count_libusb > 0)
1105 		{
1106 			count_libusb--;
1107 			DEBUG_INFO2("Wait after libusb: %d", count_libusb);
1108 			nanosleep(&sleep_time, NULL);
1109 
1110 			goto again_libusb;
1111 		}
1112 #endif
1113 
1114 		/* free bundle list */
1115 		bundleRelease(&plist);
1116 
1117 		/* failed */
1118 		close_libusb_if_needed();
1119 
1120 		if (claim_failed)
1121 			return STATUS_COMM_ERROR;
1122 		DEBUG_INFO1("Device not found?");
1123 		return STATUS_NO_SUCH_DEVICE;
1124 	}
1125 
1126 	/* memorise the current reader_index so we can detect
1127 	 * a new OpenUSBByName on a multi slot reader */
1128 	previous_reader_index = reader_index;
1129 
1130 end2:
1131 	/* free the libusb allocated list & devices */
1132 	libusb_free_device_list(devs, 1);
1133 
1134 end1:
1135 	/* free bundle list */
1136 	bundleRelease(&plist);
1137 
1138 	if (return_value != STATUS_SUCCESS)
1139 		close_libusb_if_needed();
1140 
1141 	return return_value;
1142 } /* OpenUSBByName */
1143 
1144 
1145 /*****************************************************************************
1146  *
1147  *					WriteUSB
1148  *
1149  ****************************************************************************/
WriteUSB(unsigned int reader_index,unsigned int length,unsigned char * buffer)1150 status_t WriteUSB(unsigned int reader_index, unsigned int length,
1151 	unsigned char *buffer)
1152 {
1153 	int rv;
1154 	int actual_length;
1155 	char debug_header[] = "-> 121234 ";
1156 	int pos;
1157 	int len;
1158 	int delayed = FALSE;
1159 
1160 	(void)snprintf(debug_header, sizeof(debug_header), "-> %06X ",
1161 		(int)reader_index);
1162 
1163 	// Fix APG8201 and ACR85 ICC cannot receive command properly
1164 	// Add delay for APG8201 and ACR85 ICC
1165 	if ((usbDevice[reader_index].ccid.readerID == ACS_APG8201) ||
1166 		(usbDevice[reader_index].ccid.readerID == ACS_ACR85_PINPAD_READER_ICC))
1167 	{
1168 		delayed = TRUE;
1169 	}
1170 
1171 	// Workaround for ACR122U reader
1172 	usbDevice[reader_index].last_write_size = length;
1173 
1174 	// Send command by dividing number of packets
1175 	pos = 0;
1176 	while (length > 0)
1177 	{
1178 		if (length > usbDevice[reader_index].bulkOutMaxPacketSize)
1179 			len = usbDevice[reader_index].bulkOutMaxPacketSize;
1180 		else
1181 			len = length;
1182 
1183 		DEBUG_XXD(debug_header, buffer + pos, len);
1184 
1185 		rv = libusb_bulk_transfer(usbDevice[reader_index].dev_handle,
1186 			usbDevice[reader_index].bulk_out, buffer + pos, len,
1187 			&actual_length, USB_WRITE_TIMEOUT);
1188 
1189 		if (rv < 0)
1190 		{
1191 			DEBUG_CRITICAL5("write failed (%d/%d): %d %s",
1192 				usbDevice[reader_index].bus_number,
1193 				usbDevice[reader_index].device_address, rv, libusb_error_name(rv));
1194 
1195 			if (LIBUSB_ERROR_NO_DEVICE == rv)
1196 				return STATUS_NO_SUCH_DEVICE;
1197 
1198 			return STATUS_UNSUCCESSFUL;
1199 		}
1200 
1201 		if (delayed)
1202 		{
1203 			// Delay 10 ms
1204 			if (length > usbDevice[reader_index].bulkOutMaxPacketSize)
1205 				usleep(10 * 1000);
1206 		}
1207 
1208 		pos += len;
1209 		length -= len;
1210 	}
1211 
1212 	return STATUS_SUCCESS;
1213 } /* WriteUSB */
1214 
1215 
1216 /*****************************************************************************
1217  *
1218  *					ReadUSB
1219  *
1220  ****************************************************************************/
ReadUSB(unsigned int reader_index,unsigned int * length,unsigned char * buffer)1221 status_t ReadUSB(unsigned int reader_index, unsigned int * length,
1222 	unsigned char *buffer)
1223 {
1224 	int rv;
1225 	int actual_length;
1226 	char debug_header[] = "<- 121234 ";
1227 	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
1228 	int duplicate_frame = 0;
1229 
1230 	(void)snprintf(debug_header, sizeof(debug_header), "<- %06X ",
1231 		(int)reader_index);
1232 
1233 	if (ccid_descriptor->bInterfaceProtocol == PROTOCOL_ACR38)
1234 	{
1235 		unsigned char epBuffer[64];
1236 		int responseReceived = FALSE;
1237 		int headerReceived = FALSE;
1238 		unsigned int bufferLen = *length;
1239 		unsigned int readLen = 0;
1240 		unsigned int dataLen = 0;
1241 
1242 		while (!responseReceived)
1243 		{
1244 			// Read data from BULK IN endpoint
1245 			rv = libusb_bulk_transfer(usbDevice[reader_index].dev_handle,
1246 				usbDevice[reader_index].bulk_in, epBuffer, sizeof(epBuffer),
1247 				&actual_length, usbDevice[reader_index].ccid.readTimeout);
1248 
1249 			if (rv < 0)
1250 			{
1251 				*length = 0;
1252 				DEBUG_CRITICAL5("read failed (%d/%d): %d %s",
1253 					usbDevice[reader_index].bus_number,
1254 					usbDevice[reader_index].device_address, rv, libusb_error_name(rv));
1255 
1256 				if (LIBUSB_ERROR_NO_DEVICE == rv)
1257 					return STATUS_NO_SUCH_DEVICE;
1258 
1259 				return STATUS_UNSUCCESSFUL;
1260 			}
1261 
1262 			DEBUG_XXD(debug_header, epBuffer, actual_length);
1263 
1264 			// Copy data to buffer
1265 			if (readLen + actual_length <= bufferLen)
1266 				memcpy(buffer + readLen, epBuffer, actual_length);
1267 			readLen += actual_length;
1268 
1269 			if (!headerReceived)
1270 			{
1271 				if ((readLen >= 4) &&
1272 					(buffer[0] == 0x01))	// Header
1273 				{
1274 					// Header is received
1275 					headerReceived = TRUE;
1276 
1277 					// Get data length
1278 					dataLen = ((buffer[2] << 8) | buffer[3]) + 4;
1279 				}
1280 			}
1281 
1282 			if (headerReceived)
1283 			{
1284 				if (readLen >= dataLen)
1285 				{
1286 					// Response is received
1287 					*length = readLen;
1288 					responseReceived = TRUE;
1289 				}
1290 			}
1291 		}
1292 
1293 		// Insufficient buffer
1294 		if (readLen > bufferLen)
1295 		{
1296 			DEBUG_CRITICAL("Insufficient buffer");
1297 			return STATUS_UNSUCCESSFUL;
1298 		}
1299 
1300 		return STATUS_SUCCESS;
1301 	}
1302 
1303 read_again:
1304 	rv = libusb_bulk_transfer(usbDevice[reader_index].dev_handle,
1305 		usbDevice[reader_index].bulk_in, buffer, *length,
1306 		&actual_length, usbDevice[reader_index].ccid.readTimeout);
1307 
1308 	if (rv < 0)
1309 	{
1310 		*length = 0;
1311 		DEBUG_CRITICAL5("read failed (%d/%d): %d %s",
1312 			usbDevice[reader_index].bus_number,
1313 			usbDevice[reader_index].device_address, rv, libusb_error_name(rv));
1314 
1315 		if (LIBUSB_ERROR_NO_DEVICE == rv)
1316 			return STATUS_NO_SUCH_DEVICE;
1317 
1318 		return STATUS_UNSUCCESSFUL;
1319 	}
1320 
1321 	*length = actual_length;
1322 
1323 	DEBUG_XXD(debug_header, buffer, *length);
1324 
1325 #define BSEQ_OFFSET 6
1326 	if ((*length >= BSEQ_OFFSET)
1327 		&& (buffer[BSEQ_OFFSET] < *ccid_descriptor->pbSeq -1))
1328 	{
1329 		// Workaround for ACR122U reader
1330 		if ((ccid_descriptor->readerID == ACS_ACR122U) &&
1331 			(usbDevice[reader_index].last_write_size > 64) &&
1332 			(buffer[BSEQ_OFFSET] == *ccid_descriptor->pbSeq -2))
1333 			return STATUS_SUCCESS;
1334 
1335 		duplicate_frame++;
1336 		if (duplicate_frame > 10)
1337 		{
1338 			DEBUG_CRITICAL("Too many duplicate frame detected");
1339 			return STATUS_UNSUCCESSFUL;
1340 		}
1341 		DEBUG_INFO1("Duplicate frame detected");
1342 		goto read_again;
1343 	}
1344 
1345 	return STATUS_SUCCESS;
1346 } /* ReadUSB */
1347 
1348 
1349 /*****************************************************************************
1350  *
1351  *					CloseUSB
1352  *
1353  ****************************************************************************/
CloseUSB(unsigned int reader_index)1354 status_t CloseUSB(unsigned int reader_index)
1355 {
1356 	/* device not opened */
1357 	if (usbDevice[reader_index].dev_handle == NULL)
1358 		return STATUS_UNSUCCESSFUL;
1359 
1360 	DEBUG_COMM3("Closing USB device: %d/%d",
1361 		usbDevice[reader_index].bus_number,
1362 		usbDevice[reader_index].device_address);
1363 
1364 	/* one slot closed */
1365 	(*usbDevice[reader_index].nb_opened_slots)--;
1366 
1367 	/* release the allocated ressources for the last slot only */
1368 	if (0 == *usbDevice[reader_index].nb_opened_slots)
1369 	{
1370 		struct usbDevice_MultiSlot_Extension *msExt;
1371 
1372 		DEBUG_COMM("Last slot closed. Release resources");
1373 
1374 #ifdef __APPLE__
1375 		if (usbDevice[reader_index].threadCreated)
1376 		{
1377 			DEBUG_INFO3("Terminating thread: %d/%d",
1378 				usbDevice[reader_index].bus_number,
1379 				usbDevice[reader_index].device_address);
1380 
1381 			// Terminate thread
1382 			*usbDevice[reader_index].pTerminated = TRUE;
1383 
1384 			// Lock transfer
1385 			pthread_mutex_lock(usbDevice[reader_index].pTransferLock);
1386 
1387 			// Cancel transfer
1388 			if (*usbDevice[reader_index].pTransfer != NULL)
1389 			{
1390 				libusb_cancel_transfer(*usbDevice[reader_index].pTransfer);
1391 				*usbDevice[reader_index].pTransfer = NULL;
1392 			}
1393 
1394 			// Unlock transfer
1395 			pthread_mutex_unlock(usbDevice[reader_index].pTransferLock);
1396 
1397 			// Wait thread
1398 			pthread_join(usbDevice[reader_index].hThread, NULL);
1399 			usbDevice[reader_index].threadCreated = FALSE;
1400 		}
1401 
1402 		// Free bStatus lock
1403 		pthread_mutex_destroy(usbDevice[reader_index].ccid.pbStatusLock);
1404 
1405 		// Free transfer lock
1406 		pthread_mutex_destroy(usbDevice[reader_index].pTransferLock);
1407 #endif
1408 		// Free array of bStatus
1409 		free(usbDevice[reader_index].ccid.bStatus);
1410 
1411 		msExt = usbDevice[reader_index].multislot_extension;
1412 		/* If this is a multislot reader, close using the multislot stuff */
1413 		if (msExt)
1414 		{
1415 			/* terminate the interrupt waiter thread */
1416 			Multi_PollingTerminate(msExt);
1417 
1418 			/* wait for the thread to actually terminate */
1419 			pthread_join(msExt->thread_proc, NULL);
1420 
1421 			/* release the shared objects */
1422 			pthread_cond_destroy(&msExt->condition);
1423 			pthread_mutex_destroy(&msExt->mutex);
1424 
1425 			/* Deallocate the extension itself */
1426 			free(msExt);
1427 
1428 			/* Stop the slot */
1429 			usbDevice[reader_index].multislot_extension = NULL;
1430 		}
1431 
1432 		if (usbDevice[reader_index].ccid.gemalto_firmware_features)
1433 			free(usbDevice[reader_index].ccid.gemalto_firmware_features);
1434 
1435 		if (usbDevice[reader_index].ccid.sIFD_serial_number)
1436 			free(usbDevice[reader_index].ccid.sIFD_serial_number);
1437 
1438 		if (usbDevice[reader_index].ccid.sIFD_iManufacturer)
1439 			free(usbDevice[reader_index].ccid.sIFD_iManufacturer);
1440 
1441 		if (usbDevice[reader_index].ccid.arrayOfSupportedDataRates)
1442 			free(usbDevice[reader_index].ccid.arrayOfSupportedDataRates);
1443 
1444 		(void)libusb_release_interface(usbDevice[reader_index].dev_handle,
1445 			usbDevice[reader_index].interface);
1446 		(void)libusb_close(usbDevice[reader_index].dev_handle);
1447 	}
1448 
1449 	/* mark the resource unused */
1450 	usbDevice[reader_index].dev_handle = NULL;
1451 	usbDevice[reader_index].interface = 0;
1452 	usbDevice[reader_index].ccid.bStatus = NULL;	// Array of bStatus
1453 	close_libusb_if_needed();
1454 
1455 	return STATUS_SUCCESS;
1456 } /* CloseUSB */
1457 
1458 
1459 /*****************************************************************************
1460  *
1461  *					get_ccid_descriptor
1462  *
1463  ****************************************************************************/
get_ccid_descriptor(unsigned int reader_index)1464 _ccid_descriptor *get_ccid_descriptor(unsigned int reader_index)
1465 {
1466 	return &usbDevice[reader_index].ccid;
1467 } /* get_ccid_descriptor */
1468 
1469 
1470 /*****************************************************************************
1471  *
1472  *					get_ccid_device_descriptor
1473  *
1474  ****************************************************************************/
get_ccid_device_descriptor(const struct libusb_interface * usb_interface)1475 const unsigned char *get_ccid_device_descriptor(const struct libusb_interface *usb_interface)
1476 {
1477 #ifdef O2MICRO_OZ776_PATCH
1478 	uint8_t last_endpoint;
1479 #endif
1480 
1481 	if (54 == usb_interface->altsetting->extra_length)
1482 		return usb_interface->altsetting->extra;
1483 
1484 	if (0 != usb_interface->altsetting->extra_length)
1485 	{
1486 		/* If extra_length is zero, the descriptor might be at
1487 		 * the end, but if it's not zero, we have a
1488 		 * problem. */
1489 		DEBUG_CRITICAL2("Extra field has a wrong length: %d",
1490 			usb_interface->altsetting->extra_length);
1491 		return NULL;
1492 	}
1493 
1494 #ifdef O2MICRO_OZ776_PATCH
1495 	/* Some devices, such as the Oz776, Reiner SCT and bludrive II
1496 	 * report the device descriptor at the end of the endpoint
1497 	 * descriptors; to support those, look for it at the end as well.
1498 	 */
1499 	last_endpoint = usb_interface->altsetting->bNumEndpoints-1;
1500 	if (usb_interface->altsetting->endpoint
1501 		&& usb_interface->altsetting->endpoint[last_endpoint].extra_length == 54)
1502 		return usb_interface->altsetting->endpoint[last_endpoint].extra;
1503 #else
1504 	DEBUG_CRITICAL2("Extra field has a wrong length: %d",
1505 		usb_interface->altsetting->extra_length);
1506 #endif
1507 
1508 	return NULL;
1509 } /* get_ccid_device_descriptor */
1510 
1511 
1512 /*****************************************************************************
1513  *
1514  *					get_end_points
1515  *
1516  ****************************************************************************/
get_end_points(struct libusb_config_descriptor * desc,_usbDevice * usbdevice,int num)1517 static int get_end_points(struct libusb_config_descriptor *desc,
1518 	_usbDevice *usbdevice, int num)
1519 {
1520 	int i;
1521 	int bEndpointAddress;
1522 	const struct libusb_interface *usb_interface;
1523 
1524 	usb_interface = get_ccid_usb_interface(desc, &num);
1525 
1526 	/*
1527 	 * 3 Endpoints maximum: Interrupt In, Bulk In, Bulk Out
1528 	 */
1529 	for (i=0; i<usb_interface->altsetting->bNumEndpoints; i++)
1530 	{
1531 		/* interrupt end point (if available) */
1532 		if (usb_interface->altsetting->endpoint[i].bmAttributes
1533 			== LIBUSB_TRANSFER_TYPE_INTERRUPT)
1534 		{
1535 			usbdevice->interrupt =
1536 				usb_interface->altsetting->endpoint[i].bEndpointAddress;
1537 			continue;
1538 		}
1539 
1540 		if (usb_interface->altsetting->endpoint[i].bmAttributes
1541 			!= LIBUSB_TRANSFER_TYPE_BULK)
1542 			continue;
1543 
1544 		bEndpointAddress =
1545 			usb_interface->altsetting->endpoint[i].bEndpointAddress;
1546 
1547 		if ((bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
1548 			== LIBUSB_ENDPOINT_IN)
1549 			usbdevice->bulk_in = bEndpointAddress;
1550 
1551 		if ((bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
1552 			== LIBUSB_ENDPOINT_OUT)
1553 		{
1554 			usbdevice->bulk_out = bEndpointAddress;
1555 			usbdevice->bulkOutMaxPacketSize = usb_interface->altsetting->endpoint[i].wMaxPacketSize;
1556 		}
1557 	}
1558 
1559 	return 0;
1560 } /* get_end_points */
1561 
1562 
1563 /*****************************************************************************
1564  *
1565  *					get_ccid_usb_interface
1566  *
1567  ****************************************************************************/
get_ccid_usb_interface(struct libusb_config_descriptor * desc,int * num)1568 /*@null@*/ EXTERNAL const struct libusb_interface * get_ccid_usb_interface(
1569 	struct libusb_config_descriptor *desc, int *num)
1570 {
1571 	const struct libusb_interface *usb_interface = NULL;
1572 	int i;
1573 
1574 	/* if multiple interfaces use the first one with CCID class type */
1575 	for (i = *num; i < desc->bNumInterfaces; i++)
1576 	{
1577 		/* CCID Class? */
1578 		if (desc->interface[i].altsetting->bInterfaceClass == 0xb
1579 #ifdef ALLOW_PROPRIETARY_CLASS
1580 			|| (desc->interface[i].altsetting->bInterfaceClass == 0xff
1581 			&& 54 == desc->interface[i].altsetting->extra_length)
1582 
1583 			// bInterfaceClass is 0x00 in ACR83U, ACR88U and ACR128U
1584 			|| desc->interface[i].altsetting->bInterfaceClass == 0x00
1585 #endif
1586 			)
1587 		{
1588 			usb_interface = &desc->interface[i];
1589 			/* store the interface number for further reference */
1590 			*num = i;
1591 			break;
1592 		}
1593 	}
1594 
1595 	return usb_interface;
1596 } /* get_ccid_usb_interface */
1597 
1598 
1599 /*****************************************************************************
1600  *
1601  *					ccid_check_firmware
1602  *
1603  ****************************************************************************/
ccid_check_firmware(struct libusb_device_descriptor * desc)1604 int ccid_check_firmware(struct libusb_device_descriptor *desc)
1605 {
1606 	unsigned int i;
1607 
1608 	for (i=0; i<COUNT_OF(Bogus_firmwares); i++)
1609 	{
1610 		if (desc->idVendor != Bogus_firmwares[i].vendor)
1611 			continue;
1612 
1613 		if (desc->idProduct != Bogus_firmwares[i].product)
1614 			continue;
1615 
1616 		/* firmware too old and buggy */
1617 		if (desc->bcdDevice < Bogus_firmwares[i].firmware)
1618 		{
1619 			if (DriverOptions & DRIVER_OPTION_USE_BOGUS_FIRMWARE)
1620 			{
1621 				DEBUG_INFO3("Firmware (%X.%02X) is bogus! but you choosed to use it",
1622 					desc->bcdDevice >> 8, desc->bcdDevice & 0xFF);
1623 				return FALSE;
1624 			}
1625 			else
1626 			{
1627 				DEBUG_CRITICAL3("Firmware (%X.%02X) is bogus! Upgrade the reader firmware or get a new reader.",
1628 					desc->bcdDevice >> 8, desc->bcdDevice & 0xFF);
1629 				return TRUE;
1630 			}
1631 		}
1632 	}
1633 
1634 	/* by default the firmware is not bogus */
1635 	return FALSE;
1636 } /* ccid_check_firmware */
1637 
1638 
1639 /*****************************************************************************
1640  *
1641  *					get_data_rates
1642  *
1643  ****************************************************************************/
get_data_rates(unsigned int reader_index,struct libusb_config_descriptor * desc,int num)1644 static unsigned int *get_data_rates(unsigned int reader_index,
1645 	struct libusb_config_descriptor *desc, int num)
1646 {
1647 	int n, i, len;
1648 	unsigned char buffer[256*sizeof(int)];	/* maximum is 256 records */
1649 	unsigned int *uint_array;
1650 
1651 	/* See CCID 3.7.3 page 25 */
1652 	n = ControlUSB(reader_index,
1653 		0xA1, /* request type */
1654 		0x03, /* GET_DATA_RATES */
1655 		0x00, /* value */
1656 		buffer, sizeof(buffer));
1657 
1658 	/* we got an error? */
1659 	if (n <= 0)
1660 	{
1661 		DEBUG_INFO2("IFD does not support GET_DATA_RATES request: %d", n);
1662 		return NULL;
1663 	}
1664 
1665 	/* we got a strange value */
1666 	if (n % 4)
1667 	{
1668 		DEBUG_INFO2("Wrong GET DATA RATES size: %d", n);
1669 		return NULL;
1670 	}
1671 
1672 	/* allocate the buffer (including the end marker) */
1673 	n /= sizeof(int);
1674 
1675 	/* we do not get the expected number of data rates */
1676 	len = get_ccid_device_descriptor(get_ccid_usb_interface(desc, &num))[27]; /* bNumDataRatesSupported */
1677 	if ((n != len) && len)
1678 	{
1679 		DEBUG_INFO3("Got %d data rates but was expecting %d", n, len);
1680 
1681 		/* we got more data than expected */
1682 		if (n > len)
1683 			n = len;
1684 	}
1685 
1686 	uint_array = calloc(n+1, sizeof(uint_array[0]));
1687 	if (NULL == uint_array)
1688 	{
1689 		DEBUG_CRITICAL("Memory allocation failed");
1690 		return NULL;
1691 	}
1692 
1693 	/* convert in correct endianess */
1694 	for (i=0; i<n; i++)
1695 	{
1696 		uint_array[i] = dw2i(buffer, i*4);
1697 		DEBUG_INFO2("declared: %d bps", uint_array[i]);
1698 	}
1699 
1700 	/* end of array marker */
1701 	uint_array[i] = 0;
1702 
1703 	return uint_array;
1704 } /* get_data_rates */
1705 
1706 
1707 /*****************************************************************************
1708  *
1709  *					ControlUSB
1710  *
1711  ****************************************************************************/
ControlUSB(int reader_index,int requesttype,int request,int value,unsigned char * bytes,unsigned int size)1712 int ControlUSB(int reader_index, int requesttype, int request, int value,
1713 	unsigned char *bytes, unsigned int size)
1714 {
1715 	int ret;
1716 
1717 	DEBUG_COMM2("request: 0x%02X", request);
1718 
1719 	if (0 == (requesttype & 0x80))
1720 		DEBUG_XXD("send: ", bytes, size);
1721 
1722 	ret = libusb_control_transfer(usbDevice[reader_index].dev_handle,
1723 		requesttype, request, value, usbDevice[reader_index].interface,
1724 		bytes, size, usbDevice[reader_index].ccid.readTimeout);
1725 
1726 	if (ret < 0)
1727 	{
1728 		DEBUG_CRITICAL5("control failed (%d/%d): %d %s",
1729 			usbDevice[reader_index].bus_number,
1730 			usbDevice[reader_index].device_address, ret, libusb_error_name(ret));
1731 
1732 		return ret;
1733 	}
1734 
1735 	if (requesttype & 0x80)
1736 		DEBUG_XXD("receive: ", bytes, ret);
1737 
1738 	return ret;
1739 } /* ControlUSB */
1740 
1741 /*****************************************************************************
1742  *
1743  *					Transfer is complete
1744  *
1745  ****************************************************************************/
bulk_transfer_cb(struct libusb_transfer * transfer)1746 static void bulk_transfer_cb(struct libusb_transfer *transfer)
1747 {
1748 	int *completed = transfer->user_data;
1749 	*completed = 1;
1750 	/* caller interprets results and frees transfer */
1751 }
1752 
1753 /*****************************************************************************
1754  *
1755  *					InterruptRead
1756  *
1757  ****************************************************************************/
InterruptRead(int reader_index,int timeout)1758 int InterruptRead(int reader_index, int timeout /* in ms */)
1759 {
1760 	int ret, actual_length;
1761 	int return_value = IFD_SUCCESS;
1762 	unsigned char buffer[8];
1763 	struct libusb_transfer *transfer;
1764 	int completed = 0;
1765 
1766 	/* Multislot reader: redirect to Multi_InterrupRead */
1767 	if (usbDevice[reader_index].multislot_extension != NULL)
1768 		return Multi_InterruptRead(reader_index, timeout);
1769 
1770 	DEBUG_PERIODIC3("before (%d), timeout: %d ms", reader_index, timeout);
1771 
1772 	transfer = libusb_alloc_transfer(0);
1773 	if (NULL == transfer)
1774 		return LIBUSB_ERROR_NO_MEM;
1775 
1776 	libusb_fill_bulk_transfer(transfer,
1777 		usbDevice[reader_index].dev_handle,
1778 		usbDevice[reader_index].interrupt, buffer, sizeof(buffer),
1779 		bulk_transfer_cb, &completed, timeout);
1780 	transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT;
1781 
1782 	ret = libusb_submit_transfer(transfer);
1783 	if (ret < 0) {
1784 		libusb_free_transfer(transfer);
1785 		DEBUG_CRITICAL2("libusb_submit_transfer failed: %s",
1786 			libusb_error_name(ret));
1787 		return IFD_COMMUNICATION_ERROR;
1788 	}
1789 
1790 	usbDevice[reader_index].polling_transfer = transfer;
1791 
1792 	while (!completed)
1793 	{
1794 		ret = libusb_handle_events_completed(ctx, &completed);
1795 		if (ret < 0)
1796 		{
1797 			if (ret == LIBUSB_ERROR_INTERRUPTED)
1798 				continue;
1799 			libusb_cancel_transfer(transfer);
1800 			while (!completed)
1801 				if (libusb_handle_events_completed(ctx, &completed) < 0)
1802 					break;
1803 			libusb_free_transfer(transfer);
1804 			DEBUG_CRITICAL2("libusb_handle_events failed: %s",
1805 				libusb_error_name(ret));
1806 			return IFD_COMMUNICATION_ERROR;
1807 		}
1808 	}
1809 
1810 	actual_length = transfer->actual_length;
1811 	ret = transfer->status;
1812 
1813 	usbDevice[reader_index].polling_transfer = NULL;
1814 	libusb_free_transfer(transfer);
1815 
1816 	DEBUG_PERIODIC3("after (%d) (%d)", reader_index, ret);
1817 
1818 	switch (ret)
1819 	{
1820 		case LIBUSB_TRANSFER_COMPLETED:
1821 			DEBUG_XXD("NotifySlotChange: ", buffer, actual_length);
1822 
1823 			// If RDR_to_PC_NotifySlotChange is received
1824 			if ((actual_length > 0) && (buffer[0] == 0x50))
1825 			{
1826 				int bufferIndex = 0;
1827 				int bitIndex = 0;
1828 				int i = 0;
1829 
1830 				// For each slot
1831 				for (i = 0; i <= usbDevice[reader_index].ccid.bMaxSlotIndex; i++)
1832 				{
1833 					bufferIndex = i / 4;
1834 					bitIndex = 2 * (i % 4);
1835 
1836 					if (bufferIndex + 1 < actual_length)
1837 					{
1838 						if (buffer[bufferIndex + 1] & (1 << bitIndex))
1839 							usbDevice[reader_index].ccid.bStatus[i] = CCID_ICC_PRESENT_ACTIVE;
1840 						else
1841 							usbDevice[reader_index].ccid.bStatus[i] = CCID_ICC_ABSENT;
1842 
1843 						DEBUG_INFO5("%d/%d: Slot %d: 0x%02X",
1844 							usbDevice[reader_index].bus_number,
1845 							usbDevice[reader_index].device_address, i,
1846 							usbDevice[reader_index].ccid.bStatus[i]);
1847 					}
1848 				}
1849 			}
1850 			break;
1851 
1852 		case LIBUSB_TRANSFER_TIMED_OUT:
1853 			break;
1854 
1855 		default:
1856 			/* if libusb_interrupt_transfer() times out we get EILSEQ or EAGAIN */
1857 			DEBUG_COMM4("InterruptRead (%d/%d): %d",
1858 				usbDevice[reader_index].bus_number,
1859 				usbDevice[reader_index].device_address, ret);
1860 			return_value = IFD_COMMUNICATION_ERROR;
1861 	}
1862 
1863 	return return_value;
1864 } /* InterruptRead */
1865 
1866 
1867 /*****************************************************************************
1868  *
1869  *					Stop the async loop
1870  *
1871  ****************************************************************************/
InterruptStop(int reader_index)1872 void InterruptStop(int reader_index)
1873 {
1874 	struct libusb_transfer *transfer;
1875 
1876 	/* Multislot reader: redirect to Multi_InterrupStop */
1877 	if (usbDevice[reader_index].multislot_extension != NULL)
1878 	{
1879 		Multi_InterruptStop(reader_index);
1880 		return;
1881 	}
1882 
1883 	transfer = usbDevice[reader_index].polling_transfer;
1884 	usbDevice[reader_index].polling_transfer = NULL;
1885 	if (transfer)
1886 	{
1887 		int ret;
1888 
1889 		ret = libusb_cancel_transfer(transfer);
1890 		if (ret < 0)
1891 			DEBUG_CRITICAL2("libusb_cancel_transfer failed: %s",
1892 				libusb_error_name(ret));
1893 	}
1894 } /* InterruptStop */
1895 
1896 
1897 /*****************************************************************************
1898  *
1899  *					TriggerSlotChange
1900  *
1901  ****************************************************************************/
TriggerSlotChange(int reader_index)1902 void TriggerSlotChange(int reader_index)
1903 {
1904 	struct usbDevice_MultiSlot_Extension *msExt =
1905 		usbDevice[reader_index].multislot_extension;
1906 
1907 	if (msExt != NULL)
1908 	{
1909 		int interrupt_byte =
1910 			(usbDevice[reader_index].ccid.bCurrentSlotIndex / 4) + 1;
1911 		int interrupt_value =
1912 			0x02 << (2 * (usbDevice[reader_index].ccid.bCurrentSlotIndex % 4));
1913 
1914 		pthread_mutex_lock(&msExt->mutex);
1915 
1916 		msExt->status = LIBUSB_TRANSFER_COMPLETED;
1917 		memset(msExt->buffer, 0, sizeof(msExt->buffer));
1918 		msExt->buffer[interrupt_byte] = interrupt_value;
1919 
1920 		pthread_cond_broadcast(&msExt->condition);
1921 		pthread_mutex_unlock(&msExt->mutex);
1922 	}
1923 }
1924 
1925 
1926 /*****************************************************************************
1927  *
1928  *					Multi_PollingProc
1929  *
1930  ****************************************************************************/
Multi_PollingProc(void * p_ext)1931 static void *Multi_PollingProc(void *p_ext)
1932 {
1933 	struct usbDevice_MultiSlot_Extension *msExt = p_ext;
1934 	int rv, status, actual_length;
1935 	unsigned char buffer[CCID_INTERRUPT_SIZE];
1936 	struct libusb_transfer *transfer;
1937 	int completed;
1938 
1939 	DEBUG_COMM3("Multi_PollingProc (%d/%d): thread starting",
1940 		usbDevice[msExt->reader_index].bus_number,
1941 		usbDevice[msExt->reader_index].device_address);
1942 
1943 	rv = 0;
1944 	while (!msExt->terminated)
1945 	{
1946 		DEBUG_COMM3("Multi_PollingProc (%d/%d): waiting",
1947 			usbDevice[msExt->reader_index].bus_number,
1948 			usbDevice[msExt->reader_index].device_address);
1949 
1950 		transfer = libusb_alloc_transfer(0);
1951 		if (NULL == transfer)
1952 		{
1953 			rv = LIBUSB_ERROR_NO_MEM;
1954 			DEBUG_COMM2("libusb_alloc_transfer err %d", rv);
1955 			break;
1956 		}
1957 
1958 		libusb_fill_bulk_transfer(transfer,
1959 			usbDevice[msExt->reader_index].dev_handle,
1960 			usbDevice[msExt->reader_index].interrupt,
1961 			buffer, CCID_INTERRUPT_SIZE,
1962 			bulk_transfer_cb, &completed, 0); /* No timeout ! */
1963 
1964 		transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT;
1965 
1966 		rv = libusb_submit_transfer(transfer);
1967 		if (rv < 0)
1968 		{
1969 			libusb_free_transfer(transfer);
1970 			DEBUG_COMM2("libusb_submit_transfer err %d", rv);
1971 			break;
1972 		}
1973 
1974 		usbDevice[msExt->reader_index].polling_transfer = transfer;
1975 
1976 		completed = 0;
1977 		while (!completed && !msExt->terminated)
1978 		{
1979 			rv = libusb_handle_events_completed(ctx, &completed);
1980 			if (rv < 0)
1981 			{
1982 				DEBUG_COMM2("libusb_handle_events err %d", rv);
1983 
1984 				if (rv == LIBUSB_ERROR_INTERRUPTED)
1985 					continue;
1986 
1987 				libusb_cancel_transfer(transfer);
1988 
1989 				while (!completed && !msExt->terminated)
1990 				{
1991 					if (libusb_handle_events_completed(ctx, &completed) < 0)
1992 						break;
1993 				}
1994 
1995 				break;
1996 			}
1997 		}
1998 
1999 		usbDevice[msExt->reader_index].polling_transfer = NULL;
2000 
2001 		if (rv < 0)
2002 			libusb_free_transfer(transfer);
2003 		else
2004 		{
2005 			int b, slot;
2006 
2007 			actual_length = transfer->actual_length;
2008 			status = transfer->status;
2009 
2010 			libusb_free_transfer(transfer);
2011 
2012 			/* Break if the device was disconnected. */
2013 			if (status == LIBUSB_TRANSFER_NO_DEVICE)
2014 			{
2015 				DEBUG_COMM3("Multi_PollingProc (%d/%d): Device disconnected",
2016 					usbDevice[msExt->reader_index].bus_number,
2017 					usbDevice[msExt->reader_index].device_address);
2018 				break;
2019 			}
2020 
2021 			switch (status)
2022 			{
2023 				case LIBUSB_TRANSFER_COMPLETED:
2024 					DEBUG_COMM3("Multi_PollingProc (%d/%d): OK",
2025 						usbDevice[msExt->reader_index].bus_number,
2026 						usbDevice[msExt->reader_index].device_address);
2027 					DEBUG_XXD("NotifySlotChange: ", buffer, actual_length);
2028 
2029 					// If ACR38 card status message is received, then convert it
2030 					// to RDR_to_PC_NotifySlotChange.
2031 					if ((actual_length > 1) && (buffer[0] == 0x01))
2032 					{
2033 						buffer[0] = 0x50;
2034 						buffer[1] = (buffer[1] == 0xC0) ? 0x02 : 0x03;
2035 						actual_length = 2;
2036 					}
2037 
2038 					/* log the RDR_to_PC_NotifySlotChange data */
2039 					slot = 0;
2040 					for (b=0; b<actual_length-1; b++)
2041 					{
2042 						int s;
2043 
2044 						/* 4 slots per byte */
2045 						for (s=0; s<4; s++)
2046 						{
2047 							/* 2 bits per slot */
2048 							int slot_status = ((buffer[1+b] >> (s*2)) & 3);
2049 							const char *present, *change;
2050 
2051 							present = (slot_status & 1) ? "present" : "absent";
2052 							change = (slot_status & 2) ? "status changed" : "no change";
2053 
2054 							DEBUG_COMM3("slot %d status: %d",
2055 								s + b*4, slot_status);
2056 							DEBUG_COMM3("ICC %s, %s", present, change);
2057 						}
2058 						slot += 4;
2059 					}
2060 					break;
2061 
2062 				case LIBUSB_TRANSFER_TIMED_OUT:
2063 					DEBUG_COMM3("Multi_PollingProc (%d/%d): Timeout",
2064 						usbDevice[msExt->reader_index].bus_number,
2065 						usbDevice[msExt->reader_index].device_address);
2066 					break;
2067 
2068 				default:
2069 					/* if libusb_interrupt_transfer() times out
2070 					 * we get EILSEQ or EAGAIN */
2071 					DEBUG_COMM4("Multi_PollingProc (%d/%d): %d",
2072 						usbDevice[msExt->reader_index].bus_number,
2073 						usbDevice[msExt->reader_index].device_address,
2074 						status);
2075 			}
2076 
2077 			/* Tell other slots that there's a new interrupt buffer */
2078 			DEBUG_COMM3("Multi_PollingProc (%d/%d): Broadcast to slot(s)",
2079 				usbDevice[msExt->reader_index].bus_number,
2080 				usbDevice[msExt->reader_index].device_address);
2081 
2082 			/* Lock the mutex */
2083 			pthread_mutex_lock(&msExt->mutex);
2084 
2085 			/* Set the status and the interrupt buffer */
2086 			msExt->status = status;
2087 			memset(msExt->buffer, 0, sizeof msExt->buffer);
2088 			memcpy(msExt->buffer, buffer, actual_length);
2089 
2090 			/* Broadcast the condition and unlock */
2091 			pthread_cond_broadcast(&msExt->condition);
2092 			pthread_mutex_unlock(&msExt->mutex);
2093 		}
2094 	}
2095 
2096 	msExt->terminated = TRUE;
2097 
2098 	if (rv < 0)
2099 	{
2100 		DEBUG_CRITICAL4("Multi_PollingProc (%d/%d): error %d",
2101 			usbDevice[msExt->reader_index].bus_number,
2102 			usbDevice[msExt->reader_index].device_address, rv);
2103 	}
2104 
2105 	/* Wake up the slot threads so they will exit as well */
2106 
2107 	/* Lock the mutex */
2108 	pthread_mutex_lock(&msExt->mutex);
2109 
2110 	/* Set the status and fill-in the interrupt buffer */
2111 	msExt->status = 0;
2112 	memset(msExt->buffer, 0xFF, sizeof msExt->buffer);
2113 
2114 	/* Broadcast the condition */
2115 	pthread_cond_broadcast(&msExt->condition);
2116 
2117 	/* Unlock */
2118 	pthread_mutex_unlock(&msExt->mutex);
2119 
2120 	/* Now exit */
2121 	DEBUG_COMM3("Multi_PollingProc (%d/%d): Thread terminated",
2122 		usbDevice[msExt->reader_index].bus_number,
2123 		usbDevice[msExt->reader_index].device_address);
2124 
2125 	pthread_exit(NULL);
2126 	return NULL;
2127 } /* Multi_PollingProc */
2128 
2129 
2130 /*****************************************************************************
2131  *
2132  *					Multi_PollingTerminate
2133  *
2134  ****************************************************************************/
Multi_PollingTerminate(struct usbDevice_MultiSlot_Extension * msExt)2135 static void Multi_PollingTerminate(struct usbDevice_MultiSlot_Extension *msExt)
2136 {
2137 	struct libusb_transfer *transfer;
2138 
2139 	if (msExt && !msExt->terminated)
2140 	{
2141 		msExt->terminated = TRUE;
2142 
2143 		transfer = usbDevice[msExt->reader_index].polling_transfer;
2144 
2145 		if (transfer)
2146 		{
2147 			int ret;
2148 
2149 			ret = libusb_cancel_transfer(transfer);
2150 			if (ret < 0)
2151 				DEBUG_CRITICAL2("libusb_cancel_transfer failed: %d", ret);
2152 		}
2153 	}
2154 } /* Multi_PollingTerminate */
2155 
2156 
2157 /*****************************************************************************
2158  *
2159  *					Multi_InterruptRead
2160  *
2161  ****************************************************************************/
Multi_InterruptRead(int reader_index,int timeout)2162 static int Multi_InterruptRead(int reader_index, int timeout /* in ms */)
2163 {
2164 	struct usbDevice_MultiSlot_Extension *msExt;
2165 	unsigned char buffer[CCID_INTERRUPT_SIZE];
2166 	struct timespec cond_wait_until;
2167 	struct timeval local_time;
2168 	int rv, status, interrupt_byte, interrupt_mask;
2169 
2170 	msExt = usbDevice[reader_index].multislot_extension;
2171 
2172 	/* When stopped, return 0 so IFDHPolling will return IFD_NO_SUCH_DEVICE */
2173 	if ((msExt == NULL) || msExt->terminated)
2174 		return 0;
2175 
2176 	DEBUG_PERIODIC3("Multi_InterruptRead (%d), timeout: %d ms",
2177 		reader_index, timeout);
2178 
2179 	/* Select the relevant bit in the interrupt buffer */
2180 	interrupt_byte = (usbDevice[reader_index].ccid.bCurrentSlotIndex / 4) + 1;
2181 	interrupt_mask = 0x02 << (2 * (usbDevice[reader_index].ccid.bCurrentSlotIndex % 4));
2182 
2183 	/* Wait until the condition is signaled or a timeout occurs */
2184 	gettimeofday(&local_time, NULL);
2185 	cond_wait_until.tv_sec = local_time.tv_sec;
2186 	cond_wait_until.tv_nsec = local_time.tv_usec * 1000;
2187 
2188 	cond_wait_until.tv_sec += timeout / 1000;
2189 	cond_wait_until.tv_nsec += 1000000 * (timeout % 1000);
2190 
2191 again:
2192 	pthread_mutex_lock(&msExt->mutex);
2193 
2194 	rv = pthread_cond_timedwait(&msExt->condition, &msExt->mutex,
2195 		&cond_wait_until);
2196 
2197 	if (0 == rv)
2198 	{
2199 		/* Retrieve interrupt buffer and request result */
2200 		memcpy(buffer, msExt->buffer, sizeof buffer);
2201 		status = msExt->status;
2202 	}
2203 	else
2204 		if (rv == ETIMEDOUT)
2205 			status = LIBUSB_TRANSFER_TIMED_OUT;
2206 		else
2207 			status = -1;
2208 
2209 	/* Don't forget to unlock the mutex */
2210 	pthread_mutex_unlock(&msExt->mutex);
2211 
2212 	/* When stopped, return 0 so IFDHPolling will return IFD_NO_SUCH_DEVICE */
2213 	if (msExt->terminated)
2214 		return 0;
2215 
2216 	/* Not stopped */
2217 	if (status == LIBUSB_TRANSFER_COMPLETED)
2218 	{
2219 		if (0 == (buffer[interrupt_byte] & interrupt_mask))
2220 		{
2221 			DEBUG_PERIODIC2("Multi_InterruptRead (%d) -- skipped", reader_index);
2222 			goto again;
2223 		}
2224 		DEBUG_PERIODIC2("Multi_InterruptRead (%d), got an interrupt", reader_index);
2225 	}
2226 	else
2227 	{
2228 		DEBUG_PERIODIC3("Multi_InterruptRead (%d), status=%d", reader_index, status);
2229 	}
2230 
2231 	return status;
2232 } /* Multi_InterruptRead */
2233 
2234 
2235 /*****************************************************************************
2236  *
2237  *					Multi_InterruptStop
2238  *
2239  ****************************************************************************/
Multi_InterruptStop(int reader_index)2240 static void Multi_InterruptStop(int reader_index)
2241 {
2242 	struct usbDevice_MultiSlot_Extension *msExt;
2243 	int interrupt_byte, interrupt_mask;
2244 
2245 	msExt = usbDevice[reader_index].multislot_extension;
2246 
2247 	/* Already stopped ? */
2248 	if ((NULL == msExt) || msExt->terminated)
2249 		return;
2250 
2251 	DEBUG_PERIODIC2("Stop (%d)", reader_index);
2252 
2253 	interrupt_byte = (usbDevice[reader_index].ccid.bCurrentSlotIndex / 4) + 1;
2254 	interrupt_mask = 0x02 << (2 * (usbDevice[reader_index].ccid.bCurrentSlotIndex % 4));
2255 
2256 	pthread_mutex_lock(&msExt->mutex);
2257 
2258 	/* Broacast an interrupt to wake-up the slot's thread */
2259 	msExt->buffer[interrupt_byte] |= interrupt_mask;
2260 	pthread_cond_broadcast(&msExt->condition);
2261 
2262 	pthread_mutex_unlock(&msExt->mutex);
2263 } /* Multi_InterruptStop */
2264 
2265 
2266 /*****************************************************************************
2267  *
2268  *					Multi_CreateFirstSlot
2269  *
2270  ****************************************************************************/
Multi_CreateFirstSlot(int reader_index)2271 static struct usbDevice_MultiSlot_Extension *Multi_CreateFirstSlot(int reader_index)
2272 {
2273 	struct usbDevice_MultiSlot_Extension *msExt;
2274 
2275 	/* Allocate a new extension buffer */
2276 	msExt = malloc(sizeof(struct usbDevice_MultiSlot_Extension));
2277 	if (NULL == msExt)
2278 		return NULL;
2279 
2280 	/* Remember the index */
2281 	msExt->reader_index = reader_index;
2282 
2283 	msExt->terminated = FALSE;
2284 	msExt->status = 0;
2285 	msExt->transfer = NULL;
2286 
2287 	/* Create mutex and condition object for the interrupt polling */
2288 	pthread_mutex_init(&msExt->mutex, NULL);
2289 	pthread_cond_init(&msExt->condition, NULL);
2290 
2291 	/* create the thread in charge of the interrupt polling */
2292 	pthread_create(&msExt->thread_proc, NULL, Multi_PollingProc, msExt);
2293 
2294 	return msExt;
2295 } /* Multi_CreateFirstSlot */
2296 
2297 
2298 /*****************************************************************************
2299  *
2300  *					Multi_CreateNextSlot
2301  *
2302  ****************************************************************************/
Multi_CreateNextSlot(int physical_reader_index)2303 static struct usbDevice_MultiSlot_Extension *Multi_CreateNextSlot(int physical_reader_index)
2304 {
2305 	/* Take the extension buffer from the main slot */
2306 	return usbDevice[physical_reader_index].multislot_extension;
2307 } /* Multi_CreateNextSlot */
2308 
2309 
2310 #ifdef __APPLE__
2311 // Card detection thread
CardDetectionThread(void * pParam)2312 static void *CardDetectionThread(void *pParam)
2313 {
2314 	int reader_index = (int) pParam;
2315 	int rv = 0;
2316 	int status = 0;
2317 	int actual_length = 0;
2318 	unsigned char buffer[CCID_INTERRUPT_SIZE];
2319 	struct libusb_transfer *transfer = NULL;
2320 	int completed = 0;
2321 
2322 	DEBUG_COMM3("%d/%d: Enter",
2323 		usbDevice[reader_index].bus_number,
2324 		usbDevice[reader_index].device_address);
2325 
2326 	while (!usbDevice[reader_index].terminated)
2327 	{
2328 		DEBUG_COMM3("%d/%d: Waiting...",
2329 			usbDevice[reader_index].bus_number,
2330 			usbDevice[reader_index].device_address);
2331 
2332 		transfer = libusb_alloc_transfer(0);
2333 		if (NULL == transfer)
2334 		{
2335 			rv = LIBUSB_ERROR_NO_MEM;
2336 			DEBUG_COMM2("libusb_alloc_transfer err %d", rv);
2337 			break;
2338 		}
2339 
2340 		libusb_fill_bulk_transfer(transfer,
2341 			usbDevice[reader_index].dev_handle,
2342 			usbDevice[reader_index].interrupt,
2343 			buffer, CCID_INTERRUPT_SIZE,
2344 			bulk_transfer_cb, &completed, 0);	// Infinite timeout
2345 
2346 		transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT;
2347 
2348 		rv = libusb_submit_transfer(transfer);
2349 		if (rv < 0)
2350 		{
2351 			libusb_free_transfer(transfer);
2352 			DEBUG_COMM2("libusb_submit_transfer err %d", rv);
2353 			break;
2354 		}
2355 
2356 		// Lock transfer
2357 		pthread_mutex_lock(usbDevice[reader_index].pTransferLock);
2358 
2359 		*usbDevice[reader_index].pTransfer = transfer;
2360 
2361 		// Unlock transfer
2362 		pthread_mutex_unlock(usbDevice[reader_index].pTransferLock);
2363 
2364 		completed = 0;
2365 		while (!completed && !usbDevice[reader_index].terminated)
2366 		{
2367 			rv = libusb_handle_events_completed(ctx, &completed);
2368 			if (rv < 0)
2369 			{
2370 				DEBUG_COMM2("libusb_handle_events err %d", rv);
2371 
2372 				if (rv == LIBUSB_ERROR_INTERRUPTED)
2373 					continue;
2374 
2375 				libusb_cancel_transfer(transfer);
2376 
2377 				while (!completed && !usbDevice[reader_index].terminated)
2378 				{
2379 					if (libusb_handle_events_completed(ctx, &completed) < 0)
2380 						break;
2381 				}
2382 
2383 				break;
2384 			}
2385 		}
2386 
2387 		// Lock transfer
2388 		pthread_mutex_lock(usbDevice[reader_index].pTransferLock);
2389 
2390 		*usbDevice[reader_index].pTransfer = NULL;
2391 
2392 		// Unlock transfer
2393 		pthread_mutex_unlock(usbDevice[reader_index].pTransferLock);
2394 
2395 		if (rv < 0)
2396 			libusb_free_transfer(transfer);
2397 		else
2398 		{
2399 			actual_length = transfer->actual_length;
2400 			status = transfer->status;
2401 
2402 			libusb_free_transfer(transfer);
2403 
2404 			/* Break if the device was disconnected. */
2405 			if (status == LIBUSB_TRANSFER_NO_DEVICE)
2406 			{
2407 				DEBUG_COMM3("%d/%d: Device disconnected",
2408 					usbDevice[reader_index].bus_number,
2409 					usbDevice[reader_index].device_address);
2410 				break;
2411 			}
2412 
2413 			switch (status)
2414 			{
2415 				case LIBUSB_TRANSFER_COMPLETED:
2416 					DEBUG_COMM3("%d/%d: OK",
2417 						usbDevice[reader_index].bus_number,
2418 						usbDevice[reader_index].device_address);
2419 					DEBUG_XXD("NotifySlotChange: ", buffer, actual_length);
2420 
2421 					// If RDR_to_PC_NotifySlotChange is received
2422 					if ((actual_length > 0) && (buffer[0] == 0x50))
2423 					{
2424 						int bufferIndex = 0;
2425 						int bitIndex = 0;
2426 						int i = 0;
2427 
2428 						// Lock bStatus
2429 						pthread_mutex_lock(usbDevice[reader_index].ccid.pbStatusLock);
2430 
2431 						// For each slot
2432 						for (i = 0; i <= usbDevice[reader_index].ccid.bMaxSlotIndex; i++)
2433 						{
2434 							bufferIndex = i / 4;
2435 							bitIndex = 2 * (i % 4);
2436 
2437 							if (bufferIndex + 1 < actual_length)
2438 							{
2439 								if (buffer[bufferIndex + 1] & (1 << bitIndex))
2440 									usbDevice[reader_index].ccid.bStatus[i] = CCID_ICC_PRESENT_ACTIVE;
2441 								else
2442 									usbDevice[reader_index].ccid.bStatus[i] = CCID_ICC_ABSENT;
2443 
2444 								DEBUG_INFO5("%d/%d: Slot %d: 0x%02X",
2445 									usbDevice[reader_index].bus_number,
2446 									usbDevice[reader_index].device_address, i,
2447 									usbDevice[reader_index].ccid.bStatus[i]);
2448 							}
2449 						}
2450 
2451 						// Unlock bStatus
2452 						pthread_mutex_unlock(usbDevice[reader_index].ccid.pbStatusLock);
2453 					}
2454 					break;
2455 
2456 				case LIBUSB_TRANSFER_TIMED_OUT:
2457 					DEBUG_COMM3("%d/%d: Timeout",
2458 						usbDevice[reader_index].bus_number,
2459 						usbDevice[reader_index].device_address);
2460 					break;
2461 
2462 				default:
2463 					DEBUG_COMM4("%d/%d: Status: %d",
2464 						usbDevice[reader_index].bus_number,
2465 						usbDevice[reader_index].device_address,
2466 						status);
2467 			}
2468 		}
2469 	}
2470 
2471 	usbDevice[reader_index].terminated = TRUE;
2472 
2473 	if (rv < 0)
2474 	{
2475 		DEBUG_CRITICAL4("%d/%d: Error: %d",
2476 			usbDevice[reader_index].bus_number,
2477 			usbDevice[reader_index].device_address, rv);
2478 	}
2479 
2480 	DEBUG_COMM3("%d/%d: Exit",
2481 		usbDevice[reader_index].bus_number,
2482 		usbDevice[reader_index].device_address);
2483 
2484 	pthread_exit(NULL);
2485 	return NULL;
2486 }
2487 #endif
2488