1/*
2	ccid_usb.c: USB access routines using the libusb library
3	Copyright (C) 2003-2010	Ludovic Rousseau
4
5	This library is free software; you can redistribute it and/or
6	modify it under the terms of the GNU Lesser General Public
7	License as published by the Free Software Foundation; either
8	version 2.1 of the License, or (at your option) any later version.
9
10	This library is distributed in the hope that it will be useful,
11	but WITHOUT ANY WARRANTY; without even the implied warranty of
12	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13	Lesser General Public License for more details.
14
15	You should have received a copy of the GNU Lesser General Public License
16	along with this library; if not, write to the Free Software Foundation,
17	Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18*/
19
20/*
21 * $Id: ccid_usb.c 6793 2013-11-25 13:09:41Z rousseau $
22 */
23
24#define __CCID_USB__
25
26#include <stdio.h>
27#include <string.h>
28#include <errno.h>
29# ifdef S_SPLINT_S
30# include <sys/types.h>
31# endif
32#include <libusb.h>
33#include <stdlib.h>
34#include <pthread.h>
35#include <sys/time.h>
36#include <ifdhandler.h>
37
38#include "config.h"
39#include "misc.h"
40#include "ccid.h"
41#include "debug.h"
42#include "defs.h"
43#include "utils.h"
44#include "parser.h"
45#include "ccid_ifdhandler.h"
46
47
48/* write timeout
49 * we don't have to wait a long time since the card was doing nothing */
50#define USB_WRITE_TIMEOUT (5 * 1000)	/* 5 seconds timeout */
51
52/*
53 * Proprietary USB Class (0xFF) are (or are not) accepted
54 * A proprietary class is used for devices released before the final CCID
55 * specifications were ready.
56 * We should not have problems with non CCID devices because the
57 * Manufacturer and Product ID are also used to identify the device */
58#define ALLOW_PROPRIETARY_CLASS
59
60#define BUS_DEVICE_STRSIZE 32
61
62/* Using the default libusb context */
63/* does not work for libusb <= 1.0.8 */
64/* #define ctx NULL */
65libusb_context *ctx = NULL;
66
67#define CCID_INTERRUPT_SIZE 8
68
69struct usbDevice_MultiSlot_Extension
70{
71	int reader_index;
72
73	/* The multi-threaded polling part */
74	int terminated;
75	int status;
76	unsigned char buffer[CCID_INTERRUPT_SIZE];
77	pthread_t thread_proc;
78	pthread_mutex_t mutex;
79	pthread_cond_t condition;
80	struct libusb_transfer *transfer;
81};
82
83typedef struct
84{
85	libusb_device_handle *dev_handle;
86	uint8_t bus_number;
87	uint8_t device_address;
88	int interface;
89
90	/*
91	 * Endpoints
92	 */
93	int bulk_in;
94	int bulk_out;
95	int interrupt;
96
97	/* Number of slots using the same device */
98	int real_nb_opened_slots;
99	int *nb_opened_slots;
100
101	/*
102	 * CCID infos common to USB and serial
103	 */
104	_ccid_descriptor ccid;
105
106	/* libusb transfer for the polling (or NULL) */
107	struct libusb_transfer *polling_transfer;
108
109	/* pointer to the multislot extension (if any) */
110	struct usbDevice_MultiSlot_Extension *multislot_extension;
111
112} _usbDevice;
113
114/* The _usbDevice structure must be defined before including ccid_usb.h */
115#include "ccid_usb.h"
116
117/* Specific hooks for multislot readers */
118static int Multi_InterruptRead(int reader_index, int timeout /* in ms */);
119static void Multi_InterruptStop(int reader_index);
120static struct usbDevice_MultiSlot_Extension *Multi_CreateFirstSlot(int reader_index);
121static struct usbDevice_MultiSlot_Extension *Multi_CreateNextSlot(int physical_reader_index);
122static void Multi_PollingTerminate(struct usbDevice_MultiSlot_Extension *msExt);
123
124static int get_end_points(struct libusb_config_descriptor *desc,
125	_usbDevice *usbdevice, int num);
126int ccid_check_firmware(struct libusb_device_descriptor *desc);
127static unsigned int *get_data_rates(unsigned int reader_index,
128	struct libusb_config_descriptor *desc, int num);
129
130/* ne need to initialize to 0 since it is static */
131static _usbDevice usbDevice[CCID_DRIVER_MAX_READERS];
132
133#define PCSCLITE_MANUKEY_NAME "ifdVendorID"
134#define PCSCLITE_PRODKEY_NAME "ifdProductID"
135#define PCSCLITE_NAMEKEY_NAME "ifdFriendlyName"
136
137struct _bogus_firmware
138{
139	int vendor;		/* idVendor */
140	int product;	/* idProduct */
141	int firmware;	/* bcdDevice: previous firmwares have bugs */
142};
143
144static struct _bogus_firmware Bogus_firmwares[] = {
145	{ 0x04e6, 0xe001, 0x0516 },	/* SCR 331 */
146	{ 0x04e6, 0x5111, 0x0620 },	/* SCR 331-DI */
147	{ 0x04e6, 0xe003, 0x0510 },	/* SPR 532 */
148	{ 0x0D46, 0x3001, 0x0037 },	/* KAAN Base */
149	{ 0x0D46, 0x3002, 0x0037 },	/* KAAN Advanced */
150	{ 0x09C3, 0x0008, 0x0203 },	/* ActivCard V2 */
151	{ 0x0DC3, 0x1004, 0x0502 },	/* ASE IIIe USBv2 */
152	{ 0x0DC3, 0x1102, 0x0607 },	/* ASE IIIe KB USB */
153	{ 0x058F, 0x9520, 0x0102 },	/* Alcor AU9520-G */
154	{ 0x072F, 0x2200, 0x0206 }, /* ACS ACR122U-WB-R */
155	{ 0x08C3, 0x0402, 0x5000 },	/* Precise Biometrics Precise 200 MC */
156	{ 0x08C3, 0x0401, 0x5000 },	/* Precise Biometrics Precise 250 MC */
157	{ 0x0B0C, 0x0050, 0x0101 },	/* Todos Argos Mini II */
158	{ 0x0DC3, 0x0900, 0x0200 }, /* Athena IDProtect Key v2 */
159	{ 0x03F0, 0x0036, 0x0124 }, /* HP USB CCID Smartcard Keyboard */
160	{ 0x062D, 0x0001, 0x0102 }, /* THRC Smart Card Reader */
161	{ 0x04E6, 0x5291, 0x0112 }, /* SCM SCL010 Contactless Reader */
162
163	/* the firmware version is not correct since I do not have received a
164	 * working reader yet */
165#ifndef O2MICRO_OZ776_PATCH
166	{ 0x0b97, 0x7762, 0x0111 },	/* Oz776S */
167#endif
168};
169
170/* data rates supported by the secondary slots on the GemCore Pos Pro & SIM Pro */
171unsigned int SerialCustomDataRates[] = { GEMPLUS_CUSTOM_DATA_RATES, 0 };
172
173/*****************************************************************************
174 *
175 *					close_libusb_if_needed
176 *
177 ****************************************************************************/
178static void close_libusb_if_needed(void)
179{
180	int i, to_exit = TRUE;
181
182	/* if at least 1 reader is still in use we do not exit libusb */
183	for (i=0; i<CCID_DRIVER_MAX_READERS; i++)
184	{
185		if (usbDevice[i].dev_handle != NULL)
186			to_exit = FALSE;
187	}
188
189	if (to_exit)
190	{
191		DEBUG_INFO("libusb_exit");
192		libusb_exit(ctx);
193		ctx = NULL;
194	}
195} /* close_libusb_if_needed */
196
197/*****************************************************************************
198 *
199 *					OpenUSB
200 *
201 ****************************************************************************/
202status_t OpenUSB(unsigned int reader_index, /*@unused@*/ int Channel)
203{
204	(void)Channel;
205
206	return OpenUSBByName(reader_index, NULL);
207} /* OpenUSB */
208
209
210/*****************************************************************************
211 *
212 *					OpenUSBByName
213 *
214 ****************************************************************************/
215status_t OpenUSBByName(unsigned int reader_index, /*@null@*/ char *device)
216{
217	unsigned int alias;
218	struct libusb_device_handle *dev_handle;
219	char infofile[FILENAME_MAX];
220#ifndef __APPLE__
221	unsigned int device_vendor, device_product;
222#endif
223	int interface_number = -1;
224	int i;
225	static int previous_reader_index = -1;
226	libusb_device **devs, *dev;
227	ssize_t cnt;
228	list_t plist, *values, *ifdVendorID, *ifdProductID, *ifdFriendlyName;
229	int rv;
230	int claim_failed = FALSE;
231	int return_value = STATUS_SUCCESS;
232
233	DEBUG_COMM3("Reader index: %X, Device: %s", reader_index, device);
234
235#ifndef __APPLE__
236	/* device name specified */
237	if (device)
238	{
239		char *dirname;
240
241		/* format: usb:%04x/%04x, vendor, product */
242		if (strncmp("usb:", device, 4) != 0)
243		{
244			DEBUG_CRITICAL2("device name does not start with \"usb:\": %s",
245				device);
246			return STATUS_UNSUCCESSFUL;
247		}
248
249		if (sscanf(device, "usb:%x/%x", &device_vendor, &device_product) != 2)
250		{
251			DEBUG_CRITICAL2("device name can't be parsed: %s", device);
252			return STATUS_UNSUCCESSFUL;
253		}
254
255		/* format usb:%04x/%04x:libudev:%d:%s
256		 * with %d set to
257		 * 01 (or whatever the interface number is)
258		 * and %s set to
259		 * /dev/bus/usb/008/004
260		 */
261		if ((dirname = strstr(device, "libudev:")) != NULL)
262		{
263			/* convert the interface number */
264			interface_number = atoi(dirname + 8 /* "libudev:" */);
265			DEBUG_COMM2("interface_number: %d", interface_number);
266		}
267	}
268#endif
269
270	/* is the reader_index already used? */
271	if (usbDevice[reader_index].dev_handle != NULL)
272	{
273		DEBUG_CRITICAL2("USB driver with index %X already in use",
274			reader_index);
275		return STATUS_UNSUCCESSFUL;
276	}
277
278	/* Info.plist full patch filename */
279	(void)snprintf(infofile, sizeof(infofile), "%s/%s/Contents/Info.plist",
280		PCSCLITE_HP_DROPDIR, BUNDLE);
281	DEBUG_INFO2("Using: %s", infofile);
282
283	rv = bundleParse(infofile, &plist);
284	if (rv)
285		return STATUS_UNSUCCESSFUL;
286
287#define GET_KEY(key, values) \
288	rv = LTPBundleFindValueWithKey(&plist, key, &values); \
289	if (rv) \
290	{ \
291		DEBUG_CRITICAL2("Value/Key not defined for " key " in %s", infofile); \
292		return_value = STATUS_UNSUCCESSFUL; \
293		goto end1; \
294	} \
295	else \
296		DEBUG_INFO2(key ": %s", (char *)list_get_at(values, 0));
297
298	/* general driver info */
299	GET_KEY("ifdManufacturerString", values)
300	GET_KEY("ifdProductString", values)
301	GET_KEY("Copyright", values)
302
303	if (NULL == ctx)
304	{
305		rv = libusb_init(&ctx);
306		if (rv != 0)
307		{
308			DEBUG_CRITICAL2("libusb_init failed: %d", rv);
309			return_value = STATUS_UNSUCCESSFUL;
310			goto end1;
311		}
312	}
313
314	cnt = libusb_get_device_list(ctx, &devs);
315	if (cnt < 0)
316	{
317		DEBUG_CRITICAL("libusb_get_device_list() failed\n");
318		return_value = STATUS_UNSUCCESSFUL;
319		goto end1;
320	}
321
322#define GET_KEYS(key, values) \
323	rv = LTPBundleFindValueWithKey(&plist, key, values); \
324	if (rv) \
325	{ \
326		DEBUG_CRITICAL2("Value/Key not defined for " key " in %s", infofile); \
327		return_value = STATUS_UNSUCCESSFUL; \
328		goto end2; \
329	}
330
331	GET_KEYS("ifdVendorID", &ifdVendorID)
332	GET_KEYS("ifdProductID", &ifdProductID);
333	GET_KEYS("ifdFriendlyName", &ifdFriendlyName)
334
335	/* The 3 lists do not have the same size */
336	if ((list_size(ifdVendorID) != list_size(ifdProductID))
337		|| (list_size(ifdVendorID) != list_size(ifdFriendlyName)))
338	{
339		DEBUG_CRITICAL2("Error parsing %s", infofile);
340		return_value = STATUS_UNSUCCESSFUL;
341		goto end1;
342	}
343
344	/* for any supported reader */
345	for (alias=0; alias<list_size(ifdVendorID); alias++)
346	{
347		unsigned int vendorID, productID;
348		char *friendlyName;
349
350		vendorID = strtoul(list_get_at(ifdVendorID, alias), NULL, 0);
351		productID = strtoul(list_get_at(ifdProductID, alias), NULL, 0);
352		friendlyName = list_get_at(ifdFriendlyName, alias);
353
354#ifndef __APPLE__
355		/* the device was specified but is not the one we are trying to find */
356		if (device
357			&& (vendorID != device_vendor || productID != device_product))
358			continue;
359#else
360		/* Leopard puts the friendlyname in the device argument */
361		if (device && strcmp(device, friendlyName))
362			continue;
363#endif
364
365		/* for every device */
366		i = 0;
367		while ((dev = devs[i++]) != NULL)
368		{
369			struct libusb_device_descriptor desc;
370			struct libusb_config_descriptor *config_desc;
371			uint8_t bus_number = libusb_get_bus_number(dev);
372			uint8_t device_address = libusb_get_device_address(dev);
373
374			int r = libusb_get_device_descriptor(dev, &desc);
375			if (r < 0)
376			{
377				DEBUG_INFO3("failed to get device descriptor for %d/%d",
378					bus_number, device_address);
379				continue;
380			}
381
382			if (desc.idVendor == vendorID && desc.idProduct == productID)
383			{
384				int already_used;
385				const struct libusb_interface *usb_interface = NULL;
386				int interface;
387				int num = 0;
388				const unsigned char *device_descriptor;
389				int readerID = (vendorID << 16) + productID;
390
391#ifdef USE_COMPOSITE_AS_MULTISLOT
392				static int static_interface = 1;
393
394				/* simulate a composite device as when libudev is used */
395				if ((GEMALTOPROXDU == readerID)
396					|| (GEMALTOPROXSU == readerID))
397				{
398						/*
399						 * We can't talk to the two CCID interfaces
400						 * at the same time (the reader enters a
401						 * dead lock). So we simulate a multi slot
402						 * reader. By default multi slot readers
403						 * can't use the slots at the same time. See
404						 * TAG_IFD_SLOT_THREAD_SAFE
405						 *
406						 * One side effect is that the two readers
407						 * are seen by pcscd as one reader so the
408						 * interface name is the same for the two.
409						 *
410	* So we have:
411	* 0: Gemalto Prox-DU [Prox-DU Contact_09A00795] (09A00795) 00 00
412	* 1: Gemalto Prox-DU [Prox-DU Contact_09A00795] (09A00795) 00 01
413	* instead of
414	* 0: Gemalto Prox-DU [Prox-DU Contact_09A00795] (09A00795) 00 00
415	* 1: Gemalto Prox-DU [Prox-DU Contactless_09A00795] (09A00795) 01 00
416						 */
417
418					/* the CCID interfaces are 1 and 2 */
419					interface_number = static_interface;
420				}
421#endif
422				/* is it already opened? */
423				already_used = FALSE;
424
425				DEBUG_COMM3("Checking device: %d/%d",
426					bus_number, device_address);
427				for (r=0; r<CCID_DRIVER_MAX_READERS; r++)
428				{
429					if (usbDevice[r].dev_handle)
430					{
431						/* same bus, same address */
432						if (usbDevice[r].bus_number == bus_number
433							&& usbDevice[r].device_address == device_address)
434							already_used = TRUE;
435					}
436				}
437
438				/* this reader is already managed by us */
439				if (already_used)
440				{
441					if ((previous_reader_index != -1)
442						&& usbDevice[previous_reader_index].dev_handle
443						&& (usbDevice[previous_reader_index].bus_number == bus_number)
444						&& (usbDevice[previous_reader_index].device_address == device_address)
445						&& usbDevice[previous_reader_index].ccid.bCurrentSlotIndex < usbDevice[previous_reader_index].ccid.bMaxSlotIndex)
446					{
447						/* we reuse the same device
448						 * and the reader is multi-slot */
449						usbDevice[reader_index] = usbDevice[previous_reader_index];
450						/* The other slots of GemCore SIM Pro firmware
451						 * 1.0 do not have the same data rates.
452						 * Firmware 2.0 do not have this limitation */
453						if ((GEMCOREPOSPRO == readerID)
454							|| ((GEMCORESIMPRO == readerID)
455							&& (usbDevice[reader_index].ccid.IFD_bcdDevice < 0x0200)))
456						{
457							usbDevice[reader_index].ccid.arrayOfSupportedDataRates = SerialCustomDataRates;
458							usbDevice[reader_index].ccid.dwMaxDataRate = 125000;
459						}
460
461						*usbDevice[reader_index].nb_opened_slots += 1;
462						usbDevice[reader_index].ccid.bCurrentSlotIndex++;
463						usbDevice[reader_index].ccid.dwSlotStatus =
464							IFD_ICC_PRESENT;
465						DEBUG_INFO2("Opening slot: %d",
466							usbDevice[reader_index].ccid.bCurrentSlotIndex);
467
468						/* This is a multislot reader
469						 * Init the multislot stuff for this next slot */
470						usbDevice[reader_index].multislot_extension = Multi_CreateNextSlot(previous_reader_index);
471						goto end;
472					}
473					else
474					{
475						/* if an interface number is given by HAL we
476						 * continue with this device. */
477						if (-1 == interface_number)
478						{
479							DEBUG_INFO3("USB device %d/%d already in use."
480								" Checking next one.",
481								bus_number, device_address);
482							continue;
483						}
484					}
485				}
486
487				DEBUG_COMM3("Trying to open USB bus/device: %d/%d",
488					bus_number, device_address);
489
490				r = libusb_open(dev, &dev_handle);
491				if (r < 0)
492				{
493					DEBUG_CRITICAL4("Can't libusb_open(%d/%d): %d",
494						bus_number, device_address, r);
495
496					continue;
497				}
498
499again:
500				r = libusb_get_active_config_descriptor(dev, &config_desc);
501				if (r < 0)
502				{
503#ifdef __APPLE__
504					/* Some early Gemalto Ezio CB+ readers have
505					 * bDeviceClass, bDeviceSubClass and bDeviceProtocol set
506					 * to 0xFF (proprietary) instead of 0x00.
507					 *
508					 * So on Mac OS X the reader configuration is not done
509					 * by the OS/kernel and we do it ourself.
510					 */
511					if ((0xFF == desc.bDeviceClass)
512						&& (0xFF == desc.bDeviceSubClass)
513						&& (0xFF == desc.bDeviceProtocol))
514					{
515						r = libusb_set_configuration(dev_handle, 1);
516						if (r < 0)
517						{
518							(void)libusb_close(dev_handle);
519							DEBUG_CRITICAL4("Can't set configuration on %d/%d: %d",
520									bus_number, device_address, r);
521							continue;
522						}
523					}
524
525					/* recall */
526					r = libusb_get_active_config_descriptor(dev, &config_desc);
527					if (r < 0)
528					{
529#endif
530						(void)libusb_close(dev_handle);
531						DEBUG_CRITICAL4("Can't get config descriptor on %d/%d: %d",
532							bus_number, device_address, r);
533						continue;
534					}
535#ifdef __APPLE__
536				}
537#endif
538
539
540				usb_interface = get_ccid_usb_interface(config_desc, &num);
541				if (usb_interface == NULL)
542				{
543					(void)libusb_close(dev_handle);
544					if (0 == num)
545						DEBUG_CRITICAL3("Can't find a CCID interface on %d/%d",
546							bus_number, device_address);
547					interface_number = -1;
548					continue;
549				}
550
551				device_descriptor = get_ccid_device_descriptor(usb_interface);
552				if (NULL == device_descriptor)
553				{
554					(void)libusb_close(dev_handle);
555					DEBUG_CRITICAL3("Unable to find the device descriptor for %d/%d",
556						bus_number, device_address);
557					return_value = STATUS_UNSUCCESSFUL;
558					goto end2;
559				}
560
561				interface = usb_interface->altsetting->bInterfaceNumber;
562				if (interface_number >= 0 && interface != interface_number)
563				{
564					/* an interface was specified and it is not the
565					 * current one */
566					DEBUG_INFO3("Found interface %d but expecting %d",
567						interface_number, interface);
568					DEBUG_INFO3("Wrong interface for USB device %d/%d."
569						" Checking next one.", bus_number, device_address);
570
571					/* check for another CCID interface on the same device */
572					num++;
573
574					goto again;
575				}
576
577				r = libusb_claim_interface(dev_handle, interface);
578				if (r < 0)
579				{
580					(void)libusb_close(dev_handle);
581					DEBUG_CRITICAL4("Can't claim interface %d/%d: %d",
582						bus_number, device_address, r);
583					claim_failed = TRUE;
584					interface_number = -1;
585					continue;
586				}
587
588				DEBUG_INFO4("Found Vendor/Product: %04X/%04X (%s)",
589					desc.idVendor, desc.idProduct, friendlyName);
590				DEBUG_INFO3("Using USB bus/device: %d/%d",
591					bus_number, device_address);
592
593				/* check for firmware bugs */
594				if (ccid_check_firmware(&desc))
595				{
596					(void)libusb_close(dev_handle);
597					return_value = STATUS_UNSUCCESSFUL;
598					goto end2;
599				}
600
601#ifdef USE_COMPOSITE_AS_MULTISLOT
602				/* use the next interface for the next "slot" */
603				static_interface++;
604
605				/* reset for a next reader */
606				if (static_interface > 2)
607					static_interface = 1;
608#endif
609
610				/* Get Endpoints values*/
611				(void)get_end_points(config_desc, &usbDevice[reader_index], num);
612
613				/* store device information */
614				usbDevice[reader_index].dev_handle = dev_handle;
615				usbDevice[reader_index].bus_number = bus_number;
616				usbDevice[reader_index].device_address = device_address;
617				usbDevice[reader_index].interface = interface;
618				usbDevice[reader_index].real_nb_opened_slots = 1;
619				usbDevice[reader_index].nb_opened_slots = &usbDevice[reader_index].real_nb_opened_slots;
620				usbDevice[reader_index].polling_transfer = NULL;
621
622				/* CCID common informations */
623				usbDevice[reader_index].ccid.real_bSeq = 0;
624				usbDevice[reader_index].ccid.pbSeq = &usbDevice[reader_index].ccid.real_bSeq;
625				usbDevice[reader_index].ccid.readerID =
626					(desc.idVendor << 16) + desc.idProduct;
627				usbDevice[reader_index].ccid.dwFeatures = dw2i(device_descriptor, 40);
628				usbDevice[reader_index].ccid.wLcdLayout =
629					(device_descriptor[51] << 8) + device_descriptor[50];
630				usbDevice[reader_index].ccid.bPINSupport = device_descriptor[52];
631				usbDevice[reader_index].ccid.dwMaxCCIDMessageLength = dw2i(device_descriptor, 44);
632				usbDevice[reader_index].ccid.dwMaxIFSD = dw2i(device_descriptor, 28);
633				usbDevice[reader_index].ccid.dwDefaultClock = dw2i(device_descriptor, 10);
634				usbDevice[reader_index].ccid.dwMaxDataRate = dw2i(device_descriptor, 23);
635				usbDevice[reader_index].ccid.bMaxSlotIndex = device_descriptor[4];
636				usbDevice[reader_index].ccid.bCurrentSlotIndex = 0;
637				usbDevice[reader_index].ccid.readTimeout = DEFAULT_COM_READ_TIMEOUT;
638				usbDevice[reader_index].ccid.arrayOfSupportedDataRates = get_data_rates(reader_index, config_desc, num);
639				usbDevice[reader_index].ccid.bInterfaceProtocol = usb_interface->altsetting->bInterfaceProtocol;
640				usbDevice[reader_index].ccid.bNumEndpoints = usb_interface->altsetting->bNumEndpoints;
641				usbDevice[reader_index].ccid.dwSlotStatus = IFD_ICC_PRESENT;
642				usbDevice[reader_index].ccid.bVoltageSupport = device_descriptor[5];
643				usbDevice[reader_index].ccid.sIFD_serial_number = NULL;
644				usbDevice[reader_index].ccid.gemalto_firmware_features = NULL;
645				usbDevice[reader_index].ccid.zlp = FALSE;
646				if (desc.iSerialNumber)
647				{
648					unsigned char serial[128];
649					int ret;
650
651					ret = libusb_get_string_descriptor_ascii(dev_handle,
652							desc.iSerialNumber, serial,
653							sizeof(serial));
654					if (ret > 0)
655						usbDevice[reader_index].ccid.sIFD_serial_number
656							= strdup((char *)serial);
657				}
658
659				usbDevice[reader_index].ccid.sIFD_iManufacturer = NULL;
660				if (desc.iManufacturer)
661				{
662					unsigned char iManufacturer[128];
663					int ret;
664
665					ret = libusb_get_string_descriptor_ascii(dev_handle,
666							desc.iManufacturer, iManufacturer,
667							sizeof(iManufacturer));
668					if (ret > 0)
669						usbDevice[reader_index].ccid.sIFD_iManufacturer
670							= strdup((char *)iManufacturer);
671				}
672
673				usbDevice[reader_index].ccid.IFD_bcdDevice = desc.bcdDevice;
674
675				/* If this is a multislot reader, init the multislot stuff */
676				if (usbDevice[reader_index].ccid.bMaxSlotIndex)
677					usbDevice[reader_index].multislot_extension = Multi_CreateFirstSlot(reader_index);
678				else
679					usbDevice[reader_index].multislot_extension = NULL;
680
681				goto end;
682			}
683		}
684	}
685end:
686	if (usbDevice[reader_index].dev_handle == NULL)
687	{
688		close_libusb_if_needed();
689		if (claim_failed)
690			return STATUS_COMM_ERROR;
691		return STATUS_NO_SUCH_DEVICE;
692	}
693
694	/* memorise the current reader_index so we can detect
695	 * a new OpenUSBByName on a multi slot reader */
696	previous_reader_index = reader_index;
697
698end2:
699	/* free the libusb allocated list & devices */
700	libusb_free_device_list(devs, 1);
701
702end1:
703	/* free bundle list */
704	bundleRelease(&plist);
705
706	return return_value;
707} /* OpenUSBByName */
708
709
710/*****************************************************************************
711 *
712 *					WriteUSB
713 *
714 ****************************************************************************/
715status_t WriteUSB(unsigned int reader_index, unsigned int length,
716	unsigned char *buffer)
717{
718	int rv;
719	int actual_length;
720	char debug_header[] = "-> 121234 ";
721
722	(void)snprintf(debug_header, sizeof(debug_header), "-> %06X ",
723		(int)reader_index);
724
725	if (usbDevice[reader_index].ccid.zlp)
726	{ /* Zero Length Packet */
727		int dummy_length;
728
729		/* try to read a ZLP so transfer length = 0
730		 * timeout of 1 ms */
731		(void)libusb_bulk_transfer(usbDevice[reader_index].dev_handle,
732			usbDevice[reader_index].bulk_in, NULL, 0, &dummy_length, 1);
733	}
734
735	DEBUG_XXD(debug_header, buffer, length);
736
737	rv = libusb_bulk_transfer(usbDevice[reader_index].dev_handle,
738		usbDevice[reader_index].bulk_out, buffer, length,
739		&actual_length, USB_WRITE_TIMEOUT);
740
741	if (rv < 0)
742	{
743		DEBUG_CRITICAL5("write failed (%d/%d): %d %s",
744			usbDevice[reader_index].bus_number,
745			usbDevice[reader_index].device_address, rv, strerror(errno));
746
747		if ((ENODEV == errno) || (LIBUSB_ERROR_NO_DEVICE == rv))
748			return STATUS_NO_SUCH_DEVICE;
749
750		return STATUS_UNSUCCESSFUL;
751	}
752
753	return STATUS_SUCCESS;
754} /* WriteUSB */
755
756
757/*****************************************************************************
758 *
759 *					ReadUSB
760 *
761 ****************************************************************************/
762status_t ReadUSB(unsigned int reader_index, unsigned int * length,
763	unsigned char *buffer)
764{
765	int rv;
766	int actual_length;
767	char debug_header[] = "<- 121234 ";
768	_ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index);
769	int duplicate_frame = 0;
770
771read_again:
772	(void)snprintf(debug_header, sizeof(debug_header), "<- %06X ",
773		(int)reader_index);
774
775	rv = libusb_bulk_transfer(usbDevice[reader_index].dev_handle,
776		usbDevice[reader_index].bulk_in, buffer, *length,
777		&actual_length, usbDevice[reader_index].ccid.readTimeout);
778
779	if (rv < 0)
780	{
781		*length = 0;
782		DEBUG_CRITICAL5("read failed (%d/%d): %d %s",
783			usbDevice[reader_index].bus_number,
784			usbDevice[reader_index].device_address, rv, strerror(errno));
785
786		if ((ENODEV == errno) || (LIBUSB_ERROR_NO_DEVICE == rv))
787			return STATUS_NO_SUCH_DEVICE;
788
789		return STATUS_UNSUCCESSFUL;
790	}
791
792	*length = actual_length;
793
794	DEBUG_XXD(debug_header, buffer, *length);
795
796#define BSEQ_OFFSET 6
797	if ((*length >= BSEQ_OFFSET)
798		&& (buffer[BSEQ_OFFSET] < *ccid_descriptor->pbSeq -1))
799	{
800		duplicate_frame++;
801		if (duplicate_frame > 10)
802		{
803			DEBUG_CRITICAL("Too many duplicate frame detected");
804			return STATUS_UNSUCCESSFUL;
805		}
806		DEBUG_INFO("Duplicate frame detected");
807		goto read_again;
808	}
809
810	return STATUS_SUCCESS;
811} /* ReadUSB */
812
813
814/*****************************************************************************
815 *
816 *					CloseUSB
817 *
818 ****************************************************************************/
819status_t CloseUSB(unsigned int reader_index)
820{
821	/* device not opened */
822	if (usbDevice[reader_index].dev_handle == NULL)
823		return STATUS_UNSUCCESSFUL;
824
825	DEBUG_COMM3("Closing USB device: %d/%d",
826		usbDevice[reader_index].bus_number,
827		usbDevice[reader_index].device_address);
828
829	/* one slot closed */
830	(*usbDevice[reader_index].nb_opened_slots)--;
831
832	/* release the allocated ressources for the last slot only */
833	if (0 == *usbDevice[reader_index].nb_opened_slots)
834	{
835		struct usbDevice_MultiSlot_Extension *msExt;
836
837		DEBUG_COMM("Last slot closed. Release resources");
838
839		msExt = usbDevice[reader_index].multislot_extension;
840		/* If this is a multislot reader, close using the multislot stuff */
841		if (msExt)
842		{
843			/* terminate the interrupt waiter thread */
844			Multi_PollingTerminate(msExt);
845
846			/* wait for the thread to actually terminate */
847			pthread_join(msExt->thread_proc, NULL);
848
849			/* release the shared objects */
850			pthread_cond_destroy(&msExt->condition);
851			pthread_mutex_destroy(&msExt->mutex);
852
853			/* Deallocate the extension itself */
854			free(msExt);
855
856			/* Stop the slot */
857			usbDevice[reader_index].multislot_extension = NULL;
858		}
859
860		if (usbDevice[reader_index].ccid.gemalto_firmware_features)
861			free(usbDevice[reader_index].ccid.gemalto_firmware_features);
862
863		if (usbDevice[reader_index].ccid.sIFD_serial_number)
864			free(usbDevice[reader_index].ccid.sIFD_serial_number);
865
866		if (usbDevice[reader_index].ccid.sIFD_iManufacturer)
867			free(usbDevice[reader_index].ccid.sIFD_iManufacturer);
868
869		/* reset so that bSeq starts at 0 again */
870		if (DriverOptions & DRIVER_OPTION_RESET_ON_CLOSE)
871			(void)libusb_reset_device(usbDevice[reader_index].dev_handle);
872
873		if (usbDevice[reader_index].ccid.arrayOfSupportedDataRates)
874			free(usbDevice[reader_index].ccid.arrayOfSupportedDataRates);
875
876		(void)libusb_release_interface(usbDevice[reader_index].dev_handle,
877			usbDevice[reader_index].interface);
878		(void)libusb_close(usbDevice[reader_index].dev_handle);
879	}
880
881	/* mark the resource unused */
882	usbDevice[reader_index].dev_handle = NULL;
883	usbDevice[reader_index].interface = 0;
884
885	close_libusb_if_needed();
886
887	return STATUS_SUCCESS;
888} /* CloseUSB */
889
890
891/*****************************************************************************
892 *
893 *					get_ccid_descriptor
894 *
895 ****************************************************************************/
896_ccid_descriptor *get_ccid_descriptor(unsigned int reader_index)
897{
898	return &usbDevice[reader_index].ccid;
899} /* get_ccid_descriptor */
900
901
902/*****************************************************************************
903 *
904 *					get_ccid_device_descriptor
905 *
906 ****************************************************************************/
907const unsigned char *get_ccid_device_descriptor(const struct libusb_interface *usb_interface)
908{
909#ifdef O2MICRO_OZ776_PATCH
910	uint8_t last_endpoint;
911#endif
912
913	if (54 == usb_interface->altsetting->extra_length)
914		return usb_interface->altsetting->extra;
915
916	if (0 != usb_interface->altsetting->extra_length)
917	{
918		/* If extra_length is zero, the descriptor might be at
919		 * the end, but if it's not zero, we have a
920		 * problem. */
921		DEBUG_CRITICAL2("Extra field has a wrong length: %d",
922			usb_interface->altsetting->extra_length);
923		return NULL;
924	}
925
926#ifdef O2MICRO_OZ776_PATCH
927	/* Some devices, such as the Oz776, Reiner SCT and bludrive II
928	 * report the device descriptor at the end of the endpoint
929	 * descriptors; to support those, look for it at the end as well.
930	 */
931	last_endpoint = usb_interface->altsetting->bNumEndpoints-1;
932	if (usb_interface->altsetting->endpoint
933		&& usb_interface->altsetting->endpoint[last_endpoint].extra_length == 54)
934		return usb_interface->altsetting->endpoint[last_endpoint].extra;
935#else
936	DEBUG_CRITICAL2("Extra field has a wrong length: %d",
937		usb_interface->altsetting->extra_length);
938#endif
939
940	return NULL;
941} /* get_ccid_device_descriptor */
942
943
944/*****************************************************************************
945 *
946 *					get_end_points
947 *
948 ****************************************************************************/
949static int get_end_points(struct libusb_config_descriptor *desc,
950	_usbDevice *usbdevice, int num)
951{
952	int i;
953	int bEndpointAddress;
954	const struct libusb_interface *usb_interface;
955
956	usb_interface = get_ccid_usb_interface(desc, &num);
957
958	/*
959	 * 3 Endpoints maximum: Interrupt In, Bulk In, Bulk Out
960	 */
961	for (i=0; i<usb_interface->altsetting->bNumEndpoints; i++)
962	{
963		/* interrupt end point (if available) */
964		if (usb_interface->altsetting->endpoint[i].bmAttributes
965			== LIBUSB_TRANSFER_TYPE_INTERRUPT)
966		{
967			usbdevice->interrupt =
968				usb_interface->altsetting->endpoint[i].bEndpointAddress;
969			continue;
970		}
971
972		if (usb_interface->altsetting->endpoint[i].bmAttributes
973			!= LIBUSB_TRANSFER_TYPE_BULK)
974			continue;
975
976		bEndpointAddress =
977			usb_interface->altsetting->endpoint[i].bEndpointAddress;
978
979		if ((bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
980			== LIBUSB_ENDPOINT_IN)
981			usbdevice->bulk_in = bEndpointAddress;
982
983		if ((bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
984			== LIBUSB_ENDPOINT_OUT)
985			usbdevice->bulk_out = bEndpointAddress;
986	}
987
988	return 0;
989} /* get_end_points */
990
991
992/*****************************************************************************
993 *
994 *					get_ccid_usb_interface
995 *
996 ****************************************************************************/
997/*@null@*/ EXTERNAL const struct libusb_interface * get_ccid_usb_interface(
998	struct libusb_config_descriptor *desc, int *num)
999{
1000	const struct libusb_interface *usb_interface = NULL;
1001	int i;
1002
1003	/* if multiple interfaces use the first one with CCID class type */
1004	for (i = *num; i < desc->bNumInterfaces; i++)
1005	{
1006		/* CCID Class? */
1007		if (desc->interface[i].altsetting->bInterfaceClass == 0xb
1008#ifdef ALLOW_PROPRIETARY_CLASS
1009			|| desc->interface[i].altsetting->bInterfaceClass == 0xff
1010#endif
1011			)
1012		{
1013			usb_interface = &desc->interface[i];
1014			/* store the interface number for further reference */
1015			*num = i;
1016			break;
1017		}
1018	}
1019
1020	return usb_interface;
1021} /* get_ccid_usb_interface */
1022
1023
1024/*****************************************************************************
1025 *
1026 *					ccid_check_firmware
1027 *
1028 ****************************************************************************/
1029int ccid_check_firmware(struct libusb_device_descriptor *desc)
1030{
1031	unsigned int i;
1032
1033	for (i=0; i<COUNT_OF(Bogus_firmwares); i++)
1034	{
1035		if (desc->idVendor != Bogus_firmwares[i].vendor)
1036			continue;
1037
1038		if (desc->idProduct != Bogus_firmwares[i].product)
1039			continue;
1040
1041		/* firmware too old and buggy */
1042		if (desc->bcdDevice < Bogus_firmwares[i].firmware)
1043		{
1044			if (DriverOptions & DRIVER_OPTION_USE_BOGUS_FIRMWARE)
1045			{
1046				DEBUG_INFO3("Firmware (%X.%02X) is bogus! but you choosed to use it",
1047					desc->bcdDevice >> 8, desc->bcdDevice & 0xFF);
1048				return FALSE;
1049			}
1050			else
1051			{
1052				DEBUG_CRITICAL3("Firmware (%X.%02X) is bogus! Upgrade the reader firmware or get a new reader.",
1053					desc->bcdDevice >> 8, desc->bcdDevice & 0xFF);
1054				return TRUE;
1055			}
1056		}
1057	}
1058
1059	/* by default the firmware is not bogus */
1060	return FALSE;
1061} /* ccid_check_firmware */
1062
1063
1064/*****************************************************************************
1065 *
1066 *					get_data_rates
1067 *
1068 ****************************************************************************/
1069static unsigned int *get_data_rates(unsigned int reader_index,
1070	struct libusb_config_descriptor *desc, int num)
1071{
1072	int n, i, len;
1073	unsigned char buffer[256*sizeof(int)];	/* maximum is 256 records */
1074	unsigned int *uint_array;
1075
1076	/* See CCID 3.7.3 page 25 */
1077	n = ControlUSB(reader_index,
1078		0xA1, /* request type */
1079		0x03, /* GET_DATA_RATES */
1080		0x00, /* value */
1081		buffer, sizeof(buffer));
1082
1083	/* we got an error? */
1084	if (n <= 0)
1085	{
1086		DEBUG_INFO2("IFD does not support GET_DATA_RATES request: %d", n);
1087		return NULL;
1088	}
1089
1090	/* we got a strange value */
1091	if (n % 4)
1092	{
1093		DEBUG_INFO2("Wrong GET DATA RATES size: %d", n);
1094		return NULL;
1095	}
1096
1097	/* allocate the buffer (including the end marker) */
1098	n /= sizeof(int);
1099
1100	/* we do not get the expected number of data rates */
1101	len = get_ccid_device_descriptor(get_ccid_usb_interface(desc, &num))[27]; /* bNumDataRatesSupported */
1102	if ((n != len) && len)
1103	{
1104		DEBUG_INFO3("Got %d data rates but was expecting %d", n, len);
1105
1106		/* we got more data than expected */
1107		if (n > len)
1108			n = len;
1109	}
1110
1111	uint_array = calloc(n+1, sizeof(uint_array[0]));
1112	if (NULL == uint_array)
1113	{
1114		DEBUG_CRITICAL("Memory allocation failed");
1115		return NULL;
1116	}
1117
1118	/* convert in correct endianess */
1119	for (i=0; i<n; i++)
1120	{
1121		uint_array[i] = dw2i(buffer, i*4);
1122		DEBUG_INFO2("declared: %d bps", uint_array[i]);
1123	}
1124
1125	/* end of array marker */
1126	uint_array[i] = 0;
1127
1128	return uint_array;
1129} /* get_data_rates */
1130
1131
1132/*****************************************************************************
1133 *
1134 *					ControlUSB
1135 *
1136 ****************************************************************************/
1137int ControlUSB(int reader_index, int requesttype, int request, int value,
1138	unsigned char *bytes, unsigned int size)
1139{
1140	int ret;
1141
1142	DEBUG_COMM2("request: 0x%02X", request);
1143
1144	if (0 == (requesttype & 0x80))
1145		DEBUG_XXD("send: ", bytes, size);
1146
1147	ret = libusb_control_transfer(usbDevice[reader_index].dev_handle,
1148		requesttype, request, value, usbDevice[reader_index].interface,
1149		bytes, size, usbDevice[reader_index].ccid.readTimeout);
1150
1151	if (ret < 0)
1152	{
1153		DEBUG_CRITICAL5("control failed (%d/%d): %d %s",
1154			usbDevice[reader_index].bus_number,
1155			usbDevice[reader_index].device_address, ret, strerror(errno));
1156
1157		return ret;
1158	}
1159
1160	if (requesttype & 0x80)
1161		DEBUG_XXD("receive: ", bytes, ret);
1162
1163	return ret;
1164} /* ControlUSB */
1165
1166/*****************************************************************************
1167 *
1168 *					Transfer is complete
1169 *
1170 ****************************************************************************/
1171static void bulk_transfer_cb(struct libusb_transfer *transfer)
1172{
1173	int *completed = transfer->user_data;
1174	*completed = 1;
1175	/* caller interprets results and frees transfer */
1176}
1177
1178/*****************************************************************************
1179 *
1180 *					InterruptRead
1181 *
1182 ****************************************************************************/
1183int InterruptRead(int reader_index, int timeout /* in ms */)
1184{
1185	int ret, actual_length;
1186	int return_value = IFD_SUCCESS;
1187	unsigned char buffer[8];
1188	struct libusb_transfer *transfer;
1189	int completed = 0;
1190
1191	/* Multislot reader: redirect to Multi_InterrupRead */
1192	if (usbDevice[reader_index].multislot_extension != NULL)
1193		return Multi_InterruptRead(reader_index, timeout);
1194
1195	DEBUG_PERIODIC2("before (%d)", reader_index);
1196
1197	transfer = libusb_alloc_transfer(0);
1198	if (NULL == transfer)
1199		return LIBUSB_ERROR_NO_MEM;
1200
1201	libusb_fill_bulk_transfer(transfer,
1202		usbDevice[reader_index].dev_handle,
1203		usbDevice[reader_index].interrupt, buffer, sizeof(buffer),
1204		bulk_transfer_cb, &completed, timeout);
1205	transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT;
1206
1207	ret = libusb_submit_transfer(transfer);
1208	if (ret < 0) {
1209		libusb_free_transfer(transfer);
1210		return ret;
1211	}
1212
1213	usbDevice[reader_index].polling_transfer = transfer;
1214
1215	while (!completed)
1216	{
1217		ret = libusb_handle_events(ctx);
1218		if (ret < 0)
1219		{
1220			if (ret == LIBUSB_ERROR_INTERRUPTED)
1221				continue;
1222			libusb_cancel_transfer(transfer);
1223			while (!completed)
1224				if (libusb_handle_events(ctx) < 0)
1225					break;
1226			libusb_free_transfer(transfer);
1227			return ret;
1228		}
1229	}
1230
1231	actual_length = transfer->actual_length;
1232	ret = transfer->status;
1233
1234	usbDevice[reader_index].polling_transfer = NULL;
1235	libusb_free_transfer(transfer);
1236
1237	DEBUG_PERIODIC3("after (%d) (%d)", reader_index, ret);
1238
1239	switch (ret)
1240	{
1241		case LIBUSB_TRANSFER_COMPLETED:
1242			DEBUG_XXD("NotifySlotChange: ", buffer, actual_length);
1243			break;
1244
1245		case LIBUSB_TRANSFER_TIMED_OUT:
1246			break;
1247
1248		default:
1249			/* if libusb_interrupt_transfer() times out we get EILSEQ or EAGAIN */
1250			DEBUG_COMM4("InterruptRead (%d/%d): %s",
1251				usbDevice[reader_index].bus_number,
1252				usbDevice[reader_index].device_address, strerror(errno));
1253			return_value = IFD_COMMUNICATION_ERROR;
1254	}
1255
1256	return return_value;
1257} /* InterruptRead */
1258
1259
1260/*****************************************************************************
1261 *
1262 *					Stop the async loop
1263 *
1264 ****************************************************************************/
1265void InterruptStop(int reader_index)
1266{
1267	struct libusb_transfer *transfer;
1268
1269	/* Multislot reader: redirect to Multi_InterrupStop */
1270	if (usbDevice[reader_index].multislot_extension != NULL)
1271	{
1272		Multi_InterruptStop(reader_index);
1273		return;
1274	}
1275
1276	transfer = usbDevice[reader_index].polling_transfer;
1277	usbDevice[reader_index].polling_transfer = NULL;
1278	if (transfer)
1279	{
1280		int ret;
1281
1282		ret = libusb_cancel_transfer(transfer);
1283		if (ret < 0)
1284			DEBUG_CRITICAL2("libusb_cancel_transfer failed: %d", ret);
1285	}
1286} /* InterruptStop */
1287
1288
1289/*****************************************************************************
1290 *
1291 *					Multi_PollingProc
1292 *
1293 ****************************************************************************/
1294static void *Multi_PollingProc(void *p_ext)
1295{
1296	struct usbDevice_MultiSlot_Extension *msExt = p_ext;
1297	int rv, status, actual_length;
1298	unsigned char buffer[CCID_INTERRUPT_SIZE];
1299	struct libusb_transfer *transfer;
1300	int completed;
1301
1302	DEBUG_COMM3("Multi_PollingProc (%d/%d): thread starting",
1303		usbDevice[msExt->reader_index].bus_number,
1304		usbDevice[msExt->reader_index].device_address);
1305
1306	rv = 0;
1307	while (!msExt->terminated)
1308	{
1309		DEBUG_COMM3("Multi_PollingProc (%d/%d): waiting",
1310			usbDevice[msExt->reader_index].bus_number,
1311			usbDevice[msExt->reader_index].device_address);
1312
1313		transfer = libusb_alloc_transfer(0);
1314		if (NULL == transfer)
1315		{
1316			rv = LIBUSB_ERROR_NO_MEM;
1317			DEBUG_COMM2("libusb_alloc_transfer err %d", rv);
1318			break;
1319		}
1320
1321		libusb_fill_bulk_transfer(transfer,
1322			usbDevice[msExt->reader_index].dev_handle,
1323			usbDevice[msExt->reader_index].interrupt,
1324			buffer, CCID_INTERRUPT_SIZE,
1325			bulk_transfer_cb, &completed, 0); /* No timeout ! */
1326
1327		transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT;
1328
1329		rv = libusb_submit_transfer(transfer);
1330		if (rv)
1331		{
1332			DEBUG_COMM2("libusb_submit_transfer err %d", rv);
1333			break;
1334		}
1335
1336		usbDevice[msExt->reader_index].polling_transfer = transfer;
1337
1338		completed = 0;
1339		while (!completed && !msExt->terminated)
1340		{
1341			rv = libusb_handle_events(ctx);
1342			if (rv < 0)
1343			{
1344				DEBUG_COMM2("libusb_handle_events err %d", rv);
1345
1346				if (rv == LIBUSB_ERROR_INTERRUPTED)
1347					continue;
1348
1349				libusb_cancel_transfer(transfer);
1350
1351				while (!completed && !msExt->terminated)
1352				{
1353					if (libusb_handle_events(ctx) < 0)
1354						break;
1355				}
1356
1357				break;
1358			}
1359		}
1360
1361		usbDevice[msExt->reader_index].polling_transfer = NULL;
1362
1363		if (rv < 0)
1364			libusb_free_transfer(transfer);
1365		else
1366		{
1367			int b, slot;
1368
1369			actual_length = transfer->actual_length;
1370			status = transfer->status;
1371
1372			libusb_free_transfer(transfer);
1373
1374			switch (status)
1375			{
1376				case LIBUSB_TRANSFER_COMPLETED:
1377					DEBUG_COMM3("Multi_PollingProc (%d/%d): OK",
1378						usbDevice[msExt->reader_index].bus_number,
1379						usbDevice[msExt->reader_index].device_address);
1380					DEBUG_XXD("NotifySlotChange: ", buffer, actual_length);
1381
1382					/* log the RDR_to_PC_NotifySlotChange data */
1383					slot = 0;
1384					for (b=0; b<actual_length-1; b++)
1385					{
1386						int s;
1387
1388						/* 4 slots per byte */
1389						for (s=0; s<4; s++)
1390						{
1391							/* 2 bits per slot */
1392							int slot_status = ((buffer[1+b] >> (s*2)) & 3);
1393							const char *present, *change;
1394
1395							present = (slot_status & 1) ? "present" : "absent";
1396							change = (slot_status & 2) ? "status changed" : "no change";
1397
1398							DEBUG_COMM3("slot %d status: %d",
1399								s + b*4, slot_status);
1400							DEBUG_COMM3("ICC %s, %s", present, change);
1401						}
1402						slot += 4;
1403					}
1404					break;
1405
1406				case LIBUSB_TRANSFER_TIMED_OUT:
1407					DEBUG_COMM3("Multi_PollingProc (%d/%d): Timeout",
1408						usbDevice[msExt->reader_index].bus_number,
1409						usbDevice[msExt->reader_index].device_address);
1410					break;
1411
1412				default:
1413					/* if libusb_interrupt_transfer() times out
1414					 * we get EILSEQ or EAGAIN */
1415					DEBUG_COMM4("Multi_PollingProc (%d/%d): %d",
1416						usbDevice[msExt->reader_index].bus_number,
1417						usbDevice[msExt->reader_index].device_address,
1418						status);
1419			}
1420
1421			/* Tell other slots that there's a new interrupt buffer */
1422			DEBUG_COMM3("Multi_PollingProc (%d/%d): Broadcast to slot(s)",
1423				usbDevice[msExt->reader_index].bus_number,
1424				usbDevice[msExt->reader_index].device_address);
1425
1426			/* Lock the mutex */
1427			pthread_mutex_lock(&msExt->mutex);
1428
1429			/* Set the status and the interrupt buffer */
1430			msExt->status = status;
1431			memset(msExt->buffer, 0, sizeof msExt->buffer);
1432			memcpy(msExt->buffer, buffer, actual_length);
1433
1434			/* Broadcast the condition and unlock */
1435			pthread_cond_broadcast(&msExt->condition);
1436			pthread_mutex_unlock(&msExt->mutex);
1437		}
1438	}
1439
1440	msExt->terminated = TRUE;
1441
1442	if (rv < 0)
1443	{
1444		DEBUG_CRITICAL4("Multi_PollingProc (%d/%d): error %d",
1445			usbDevice[msExt->reader_index].bus_number,
1446			usbDevice[msExt->reader_index].device_address, rv);
1447	}
1448
1449	/* Wake up the slot threads so they will exit as well */
1450
1451	/* Lock the mutex */
1452	pthread_mutex_lock(&msExt->mutex);
1453
1454	/* Set the status and fill-in the interrupt buffer */
1455	msExt->status = 0;
1456	memset(msExt->buffer, 0xFF, sizeof msExt->buffer);
1457
1458	/* Broadcast the condition */
1459	pthread_cond_broadcast(&msExt->condition);
1460
1461	/* Unlock */
1462	pthread_mutex_unlock(&msExt->mutex);
1463
1464	/* Now exit */
1465	DEBUG_COMM3("Multi_PollingProc (%d/%d): Thread terminated",
1466		usbDevice[msExt->reader_index].bus_number,
1467		usbDevice[msExt->reader_index].device_address);
1468
1469	pthread_exit(NULL);
1470	return NULL;
1471} /* Multi_PollingProc */
1472
1473
1474/*****************************************************************************
1475 *
1476 *					Multi_PollingTerminate
1477 *
1478 ****************************************************************************/
1479static void Multi_PollingTerminate(struct usbDevice_MultiSlot_Extension *msExt)
1480{
1481	struct libusb_transfer *transfer;
1482
1483	if (msExt && !msExt->terminated)
1484	{
1485		msExt->terminated = TRUE;
1486
1487		transfer = usbDevice[msExt->reader_index].polling_transfer;
1488
1489		if (transfer)
1490		{
1491			int ret;
1492
1493			ret = libusb_cancel_transfer(transfer);
1494			if (ret < 0)
1495				DEBUG_CRITICAL2("libusb_cancel_transfer failed: %d", ret);
1496		}
1497	}
1498} /* Multi_PollingTerminate */
1499
1500
1501/*****************************************************************************
1502 *
1503 *					Multi_InterruptRead
1504 *
1505 ****************************************************************************/
1506static int Multi_InterruptRead(int reader_index, int timeout /* in ms */)
1507{
1508	struct usbDevice_MultiSlot_Extension *msExt;
1509	unsigned char buffer[CCID_INTERRUPT_SIZE];
1510	struct timespec cond_wait_until;
1511	struct timeval local_time;
1512	int rv, status, interrupt_byte, interrupt_mask;
1513
1514	msExt = usbDevice[reader_index].multislot_extension;
1515
1516	/* When stopped, return 0 so IFDHPolling will return IFD_NO_SUCH_DEVICE */
1517	if ((msExt == NULL) || msExt->terminated)
1518		return 0;
1519
1520	DEBUG_PERIODIC3("Multi_InterruptRead (%d), timeout: %d ms",
1521		reader_index, timeout);
1522
1523	/* Select the relevant bit in the interrupt buffer */
1524	interrupt_byte = (usbDevice[reader_index].ccid.bCurrentSlotIndex / 4) + 1;
1525	interrupt_mask = 0x02 << (2 * (usbDevice[reader_index].ccid.bCurrentSlotIndex % 4));
1526
1527	/* Wait until the condition is signaled or a timeout occurs */
1528	pthread_mutex_lock(&msExt->mutex);
1529	gettimeofday(&local_time, NULL);
1530	cond_wait_until.tv_sec = local_time.tv_sec;
1531	cond_wait_until.tv_nsec = local_time.tv_usec * 1000;
1532
1533	cond_wait_until.tv_sec += timeout / 1000;
1534	cond_wait_until.tv_nsec += 1000000 * (timeout % 1000);
1535
1536again:
1537	rv = pthread_cond_timedwait(&msExt->condition, &msExt->mutex,
1538		&cond_wait_until);
1539
1540	if (0 == rv)
1541	{
1542		/* Retrieve interrupt buffer and request result */
1543		memcpy(buffer, msExt->buffer, sizeof buffer);
1544		status = msExt->status;
1545	}
1546	else
1547		if (rv == ETIMEDOUT)
1548			status = LIBUSB_TRANSFER_TIMED_OUT;
1549		else
1550			status = -1;
1551
1552	/* Don't forget to unlock the mutex */
1553	pthread_mutex_unlock(&msExt->mutex);
1554
1555	/* When stopped, return 0 so IFDHPolling will return IFD_NO_SUCH_DEVICE */
1556	if (msExt->terminated)
1557		return 0;
1558
1559	/* Not stopped */
1560	if (status == LIBUSB_TRANSFER_COMPLETED)
1561	{
1562		if (0 == (buffer[interrupt_byte] & interrupt_mask))
1563		{
1564			DEBUG_PERIODIC2("Multi_InterruptRead (%d) -- skipped", reader_index);
1565			goto again;
1566		}
1567		DEBUG_PERIODIC2("Multi_InterruptRead (%d), got an interrupt", reader_index);
1568	}
1569	else
1570	{
1571		DEBUG_PERIODIC3("Multi_InterruptRead (%d), status=%d", reader_index, status);
1572	}
1573
1574	return status;
1575} /* Multi_InterruptRead */
1576
1577
1578/*****************************************************************************
1579 *
1580 *					Multi_InterruptStop
1581 *
1582 ****************************************************************************/
1583static void Multi_InterruptStop(int reader_index)
1584{
1585	struct usbDevice_MultiSlot_Extension *msExt;
1586	int interrupt_byte, interrupt_mask;
1587
1588	msExt = usbDevice[reader_index].multislot_extension;
1589
1590	/* Already stopped ? */
1591	if ((NULL == msExt) || msExt->terminated)
1592		return;
1593
1594	DEBUG_PERIODIC2("Stop (%d)", reader_index);
1595
1596	interrupt_byte = (usbDevice[reader_index].ccid.bCurrentSlotIndex / 4) + 1;
1597	interrupt_mask = 0x02 << (2 * (usbDevice[reader_index].ccid.bCurrentSlotIndex % 4));
1598
1599	pthread_mutex_lock(&msExt->mutex);
1600
1601	/* Broacast an interrupt to wake-up the slot's thread */
1602	msExt->buffer[interrupt_byte] |= interrupt_mask;
1603	pthread_cond_broadcast(&msExt->condition);
1604
1605	pthread_mutex_unlock(&msExt->mutex);
1606} /* Multi_InterruptStop */
1607
1608
1609/*****************************************************************************
1610 *
1611 *					Multi_CreateFirstSlot
1612 *
1613 ****************************************************************************/
1614static struct usbDevice_MultiSlot_Extension *Multi_CreateFirstSlot(int reader_index)
1615{
1616	struct usbDevice_MultiSlot_Extension *msExt;
1617
1618	/* Allocate a new extension buffer */
1619	msExt = malloc(sizeof(struct usbDevice_MultiSlot_Extension));
1620	if (NULL == msExt)
1621		return NULL;
1622
1623	/* Remember the index */
1624	msExt->reader_index = reader_index;
1625
1626	msExt->terminated = FALSE;
1627	msExt->status = 0;
1628	msExt->transfer = NULL;
1629
1630	/* Create mutex and condition object for the interrupt polling */
1631	pthread_mutex_init(&msExt->mutex, NULL);
1632	pthread_cond_init(&msExt->condition, NULL);
1633
1634	/* create the thread in charge of the interrupt polling */
1635	pthread_create(&msExt->thread_proc, NULL, Multi_PollingProc, msExt);
1636
1637	return msExt;
1638} /* Multi_CreateFirstSlot */
1639
1640
1641/*****************************************************************************
1642 *
1643 *					Multi_CreateNextSlot
1644 *
1645 ****************************************************************************/
1646static struct usbDevice_MultiSlot_Extension *Multi_CreateNextSlot(int physical_reader_index)
1647{
1648	/* Take the extension buffer from the main slot */
1649	return usbDevice[physical_reader_index].multislot_extension;
1650} /* Multi_CreateNextSlot */
1651
1652