1 /*
2  * libusb example program to manipulate U.are.U 4000B fingerprint scanner.
3  * Copyright © 2007 Daniel Drake <dsd@gentoo.org>
4  * Copyright © 2016 Nathan Hjelm <hjelmn@mac.com>
5  * Copyright © 2020 Chris Dickens <christopher.a.dickens@gmail.com>
6  *
7  * Basic image capture program only, does not consider the powerup quirks or
8  * the fact that image encryption may be enabled. Not expected to work
9  * flawlessly all of the time.
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24  */
25 
26 #include <config.h>
27 
28 #include <errno.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 
34 #include "libusb.h"
35 
36 #if defined(_MSC_VER)
37 #define snprintf _snprintf
38 #endif
39 
40 #if defined(DPFP_THREADED)
41 #if defined(PLATFORM_POSIX)
42 #include <fcntl.h>
43 #include <pthread.h>
44 #include <semaphore.h>
45 #include <unistd.h>
46 
47 #define THREAD_RETURN_VALUE	NULL
48 typedef sem_t * semaphore_t;
49 typedef pthread_t thread_t;
50 
semaphore_create(void)51 static inline semaphore_t semaphore_create(void)
52 {
53 	sem_t *semaphore;
54 	char name[50];
55 
56 	sprintf(name, "/org.libusb.example.dpfp_threaded:%d", (int)getpid());
57 	semaphore = sem_open(name, O_CREAT | O_EXCL, 0, 0);
58 	if (semaphore == SEM_FAILED)
59 		return NULL;
60 	/* Remove semaphore so that it does not persist after process exits */
61 	(void)sem_unlink(name);
62 	return semaphore;
63 }
64 
semaphore_give(semaphore_t semaphore)65 static inline void semaphore_give(semaphore_t semaphore)
66 {
67 	(void)sem_post(semaphore);
68 }
69 
semaphore_take(semaphore_t semaphore)70 static inline void semaphore_take(semaphore_t semaphore)
71 {
72 	(void)sem_wait(semaphore);
73 }
74 
semaphore_destroy(semaphore_t semaphore)75 static inline void semaphore_destroy(semaphore_t semaphore)
76 {
77 	(void)sem_close(semaphore);
78 }
79 
thread_create(thread_t * thread,void * (* thread_entry)(void * arg),void * arg)80 static inline int thread_create(thread_t *thread,
81 	void *(*thread_entry)(void *arg), void *arg)
82 {
83 	return pthread_create(thread, NULL, thread_entry, arg) == 0 ? 0 : -1;
84 }
85 
thread_join(thread_t thread)86 static inline void thread_join(thread_t thread)
87 {
88 	(void)pthread_join(thread, NULL);
89 }
90 #elif defined(PLATFORM_WINDOWS)
91 #define THREAD_RETURN_VALUE	0
92 typedef HANDLE semaphore_t;
93 typedef HANDLE thread_t;
94 
95 #if defined(__CYGWIN__)
96 typedef DWORD thread_return_t;
97 #else
98 #include <process.h>
99 typedef unsigned thread_return_t;
100 #endif
101 
semaphore_create(void)102 static inline semaphore_t semaphore_create(void)
103 {
104 	return CreateSemaphore(NULL, 0, 1, NULL);
105 }
106 
semaphore_give(semaphore_t semaphore)107 static inline void semaphore_give(semaphore_t semaphore)
108 {
109 	(void)ReleaseSemaphore(semaphore, 1, NULL);
110 }
111 
semaphore_take(semaphore_t semaphore)112 static inline void semaphore_take(semaphore_t semaphore)
113 {
114 	(void)WaitForSingleObject(semaphore, INFINITE);
115 }
116 
semaphore_destroy(semaphore_t semaphore)117 static inline void semaphore_destroy(semaphore_t semaphore)
118 {
119 	(void)CloseHandle(semaphore);
120 }
121 
thread_create(thread_t * thread,thread_return_t (__stdcall * thread_entry)(void * arg),void * arg)122 static inline int thread_create(thread_t *thread,
123 	thread_return_t (__stdcall *thread_entry)(void *arg), void *arg)
124 {
125 #if defined(__CYGWIN__)
126 	*thread = CreateThread(NULL, 0, thread_entry, arg, 0, NULL);
127 #else
128 	*thread = (HANDLE)_beginthreadex(NULL, 0, thread_entry, arg, 0, NULL);
129 #endif
130 	return *thread != NULL ? 0 : -1;
131 }
132 
thread_join(thread_t thread)133 static inline void thread_join(thread_t thread)
134 {
135 	(void)WaitForSingleObject(thread, INFINITE);
136 	(void)CloseHandle(thread);
137 }
138 #endif
139 #endif
140 
141 #define EP_INTR			(1 | LIBUSB_ENDPOINT_IN)
142 #define EP_DATA			(2 | LIBUSB_ENDPOINT_IN)
143 #define CTRL_IN			(LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN)
144 #define CTRL_OUT		(LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT)
145 #define USB_RQ			0x04
146 #define INTR_LENGTH		64
147 
148 enum {
149 	MODE_INIT = 0x00,
150 	MODE_AWAIT_FINGER_ON = 0x10,
151 	MODE_AWAIT_FINGER_OFF = 0x12,
152 	MODE_CAPTURE = 0x20,
153 	MODE_SHUT_UP = 0x30,
154 	MODE_READY = 0x80,
155 };
156 
157 static int next_state(void);
158 
159 enum {
160 	STATE_AWAIT_MODE_CHANGE_AWAIT_FINGER_ON = 1,
161 	STATE_AWAIT_IRQ_FINGER_DETECTED,
162 	STATE_AWAIT_MODE_CHANGE_CAPTURE,
163 	STATE_AWAIT_IMAGE,
164 	STATE_AWAIT_MODE_CHANGE_AWAIT_FINGER_OFF,
165 	STATE_AWAIT_IRQ_FINGER_REMOVED,
166 };
167 
168 static int state = 0;
169 static libusb_device_handle *devh = NULL;
170 static unsigned char imgbuf[0x1b340];
171 static unsigned char irqbuf[INTR_LENGTH];
172 static struct libusb_transfer *img_transfer = NULL;
173 static struct libusb_transfer *irq_transfer = NULL;
174 static int img_idx = 0;
175 static volatile sig_atomic_t do_exit = 0;
176 
177 #if defined(DPFP_THREADED)
178 static semaphore_t exit_semaphore;
179 static thread_t poll_thread;
180 #endif
181 
request_exit(sig_atomic_t code)182 static void request_exit(sig_atomic_t code)
183 {
184 	do_exit = code;
185 #if defined(DPFP_THREADED)
186 	semaphore_give(exit_semaphore);
187 #endif
188 }
189 
190 #if defined(DPFP_THREADED)
191 #if defined(PLATFORM_POSIX)
poll_thread_main(void * arg)192 static void *poll_thread_main(void *arg)
193 #elif defined(PLATFORM_WINDOWS)
194 static thread_return_t __stdcall poll_thread_main(void *arg)
195 #endif
196 {
197 	(void)arg;
198 
199 	printf("poll thread running\n");
200 
201 	while (!do_exit) {
202 		struct timeval tv = { 1, 0 };
203 		int r;
204 
205 		r = libusb_handle_events_timeout(NULL, &tv);
206 		if (r < 0) {
207 			request_exit(2);
208 			break;
209 		}
210 	}
211 
212 	printf("poll thread shutting down\n");
213 	return THREAD_RETURN_VALUE;
214 }
215 #endif
216 
find_dpfp_device(void)217 static int find_dpfp_device(void)
218 {
219 	devh = libusb_open_device_with_vid_pid(NULL, 0x05ba, 0x000a);
220 	return devh ? 0 : -ENODEV;
221 }
222 
print_f0_data(void)223 static int print_f0_data(void)
224 {
225 	unsigned char data[0x10];
226 	size_t i;
227 	int r;
228 
229 	r = libusb_control_transfer(devh, CTRL_IN, USB_RQ, 0xf0, 0, data,
230 		sizeof(data), 0);
231 	if (r < 0) {
232 		fprintf(stderr, "F0 error %d\n", r);
233 		return r;
234 	}
235 	if (r < (int)sizeof(data)) {
236 		fprintf(stderr, "short read (%d)\n", r);
237 		return -1;
238 	}
239 
240 	printf("F0 data:");
241 	for (i = 0; i < sizeof(data); i++)
242 		printf(" %02x", data[i]);
243 	printf("\n");
244 	return 0;
245 }
246 
get_hwstat(unsigned char * status)247 static int get_hwstat(unsigned char *status)
248 {
249 	int r;
250 
251 	r = libusb_control_transfer(devh, CTRL_IN, USB_RQ, 0x07, 0, status, 1, 0);
252 	if (r < 0) {
253 		fprintf(stderr, "read hwstat error %d\n", r);
254 		return r;
255 	}
256 	if (r < 1) {
257 		fprintf(stderr, "short read (%d)\n", r);
258 		return -1;
259 	}
260 
261 	printf("hwstat reads %02x\n", *status);
262 	return 0;
263 }
264 
set_hwstat(unsigned char data)265 static int set_hwstat(unsigned char data)
266 {
267 	int r;
268 
269 	printf("set hwstat to %02x\n", data);
270 	r = libusb_control_transfer(devh, CTRL_OUT, USB_RQ, 0x07, 0, &data, 1, 0);
271 	if (r < 0) {
272 		fprintf(stderr, "set hwstat error %d\n", r);
273 		return r;
274 	}
275 	if (r < 1) {
276 		fprintf(stderr, "short write (%d)\n", r);
277 		return -1;
278 	}
279 
280 	return 0;
281 }
282 
set_mode(unsigned char data)283 static int set_mode(unsigned char data)
284 {
285 	int r;
286 
287 	printf("set mode %02x\n", data);
288 	r = libusb_control_transfer(devh, CTRL_OUT, USB_RQ, 0x4e, 0, &data, 1, 0);
289 	if (r < 0) {
290 		fprintf(stderr, "set mode error %d\n", r);
291 		return r;
292 	}
293 	if (r < 1) {
294 		fprintf(stderr, "short write (%d)\n", r);
295 		return -1;
296 	}
297 
298 	return 0;
299 }
300 
cb_mode_changed(struct libusb_transfer * transfer)301 static void LIBUSB_CALL cb_mode_changed(struct libusb_transfer *transfer)
302 {
303 	if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
304 		fprintf(stderr, "mode change transfer not completed!\n");
305 		request_exit(2);
306 	}
307 
308 	printf("async cb_mode_changed length=%d actual_length=%d\n",
309 		transfer->length, transfer->actual_length);
310 	if (next_state() < 0)
311 		request_exit(2);
312 }
313 
set_mode_async(unsigned char data)314 static int set_mode_async(unsigned char data)
315 {
316 	unsigned char *buf = malloc(LIBUSB_CONTROL_SETUP_SIZE + 1);
317 	struct libusb_transfer *transfer;
318 
319 	if (!buf)
320 		return -ENOMEM;
321 
322 	transfer = libusb_alloc_transfer(0);
323 	if (!transfer) {
324 		free(buf);
325 		return -ENOMEM;
326 	}
327 
328 	printf("async set mode %02x\n", data);
329 	libusb_fill_control_setup(buf, CTRL_OUT, USB_RQ, 0x4e, 0, 1);
330 	buf[LIBUSB_CONTROL_SETUP_SIZE] = data;
331 	libusb_fill_control_transfer(transfer, devh, buf, cb_mode_changed, NULL,
332 		1000);
333 
334 	transfer->flags = LIBUSB_TRANSFER_SHORT_NOT_OK
335 		| LIBUSB_TRANSFER_FREE_BUFFER | LIBUSB_TRANSFER_FREE_TRANSFER;
336 	return libusb_submit_transfer(transfer);
337 }
338 
do_sync_intr(unsigned char * data)339 static int do_sync_intr(unsigned char *data)
340 {
341 	int r;
342 	int transferred;
343 
344 	r = libusb_interrupt_transfer(devh, EP_INTR, data, INTR_LENGTH,
345 		&transferred, 1000);
346 	if (r < 0) {
347 		fprintf(stderr, "intr error %d\n", r);
348 		return r;
349 	}
350 	if (transferred < INTR_LENGTH) {
351 		fprintf(stderr, "short read (%d)\n", r);
352 		return -1;
353 	}
354 
355 	printf("recv interrupt %04x\n", *((uint16_t *)data));
356 	return 0;
357 }
358 
sync_intr(unsigned char type)359 static int sync_intr(unsigned char type)
360 {
361 	int r;
362 	unsigned char data[INTR_LENGTH];
363 
364 	while (1) {
365 		r = do_sync_intr(data);
366 		if (r < 0)
367 			return r;
368 		if (data[0] == type)
369 			return 0;
370 	}
371 }
372 
save_to_file(unsigned char * data)373 static int save_to_file(unsigned char *data)
374 {
375 	FILE *f;
376 	char filename[64];
377 
378 	snprintf(filename, sizeof(filename), "finger%d.pgm", img_idx++);
379 	f = fopen(filename, "w");
380 	if (!f)
381 		return -1;
382 
383 	fputs("P5 384 289 255 ", f);
384 	(void)fwrite(data + 64, 1, 384*289, f);
385 	fclose(f);
386 	printf("saved image to %s\n", filename);
387 	return 0;
388 }
389 
next_state(void)390 static int next_state(void)
391 {
392 	int r = 0;
393 
394 	printf("old state: %d\n", state);
395 	switch (state) {
396 	case STATE_AWAIT_IRQ_FINGER_REMOVED:
397 		state = STATE_AWAIT_MODE_CHANGE_AWAIT_FINGER_ON;
398 		r = set_mode_async(MODE_AWAIT_FINGER_ON);
399 		break;
400 	case STATE_AWAIT_MODE_CHANGE_AWAIT_FINGER_ON:
401 		state = STATE_AWAIT_IRQ_FINGER_DETECTED;
402 		break;
403 	case STATE_AWAIT_IRQ_FINGER_DETECTED:
404 		state = STATE_AWAIT_MODE_CHANGE_CAPTURE;
405 		r = set_mode_async(MODE_CAPTURE);
406 		break;
407 	case STATE_AWAIT_MODE_CHANGE_CAPTURE:
408 		state = STATE_AWAIT_IMAGE;
409 		break;
410 	case STATE_AWAIT_IMAGE:
411 		state = STATE_AWAIT_MODE_CHANGE_AWAIT_FINGER_OFF;
412 		r = set_mode_async(MODE_AWAIT_FINGER_OFF);
413 		break;
414 	case STATE_AWAIT_MODE_CHANGE_AWAIT_FINGER_OFF:
415 		state = STATE_AWAIT_IRQ_FINGER_REMOVED;
416 		break;
417 	default:
418 		printf("unrecognised state %d\n", state);
419 	}
420 	if (r < 0) {
421 		fprintf(stderr, "error detected changing state\n");
422 		return r;
423 	}
424 
425 	printf("new state: %d\n", state);
426 	return 0;
427 }
428 
cb_irq(struct libusb_transfer * transfer)429 static void LIBUSB_CALL cb_irq(struct libusb_transfer *transfer)
430 {
431 	unsigned char irqtype = transfer->buffer[0];
432 
433 	if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
434 		fprintf(stderr, "irq transfer status %d?\n", transfer->status);
435 		goto err_free_transfer;
436 	}
437 
438 	printf("IRQ callback %02x\n", irqtype);
439 	switch (state) {
440 	case STATE_AWAIT_IRQ_FINGER_DETECTED:
441 		if (irqtype == 0x01) {
442 			if (next_state() < 0)
443 				goto err_free_transfer;
444 		} else {
445 			printf("finger-on-sensor detected in wrong state!\n");
446 		}
447 		break;
448 	case STATE_AWAIT_IRQ_FINGER_REMOVED:
449 		if (irqtype == 0x02) {
450 			if (next_state() < 0)
451 				goto err_free_transfer;
452 		} else {
453 			printf("finger-on-sensor detected in wrong state!\n");
454 		}
455 		break;
456 	}
457 	if (libusb_submit_transfer(irq_transfer) < 0)
458 		goto err_free_transfer;
459 
460 	return;
461 
462 err_free_transfer:
463 	libusb_free_transfer(transfer);
464 	irq_transfer = NULL;
465 	request_exit(2);
466 }
467 
cb_img(struct libusb_transfer * transfer)468 static void LIBUSB_CALL cb_img(struct libusb_transfer *transfer)
469 {
470 	if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
471 		fprintf(stderr, "img transfer status %d?\n", transfer->status);
472 		goto err_free_transfer;
473 	}
474 
475 	printf("Image callback\n");
476 	save_to_file(imgbuf);
477 	if (next_state() < 0)
478 		goto err_free_transfer;
479 
480 	if (libusb_submit_transfer(img_transfer) < 0)
481 		goto err_free_transfer;
482 
483 	return;
484 
485 err_free_transfer:
486 	libusb_free_transfer(transfer);
487 	img_transfer = NULL;
488 	request_exit(2);
489 }
490 
init_capture(void)491 static int init_capture(void)
492 {
493 	int r;
494 
495 	r = libusb_submit_transfer(irq_transfer);
496 	if (r < 0)
497 		return r;
498 
499 	r = libusb_submit_transfer(img_transfer);
500 	if (r < 0) {
501 		libusb_cancel_transfer(irq_transfer);
502 		while (irq_transfer)
503 			if (libusb_handle_events(NULL) < 0)
504 				break;
505 		return r;
506 	}
507 
508 	/* start state machine */
509 	state = STATE_AWAIT_IRQ_FINGER_REMOVED;
510 	return next_state();
511 }
512 
do_init(void)513 static int do_init(void)
514 {
515 	unsigned char status;
516 	int r;
517 
518 	r = get_hwstat(&status);
519 	if (r < 0)
520 		return r;
521 
522 	if (!(status & 0x80)) {
523 		r = set_hwstat(status | 0x80);
524 		if (r < 0)
525 			return r;
526 		r = get_hwstat(&status);
527 		if (r < 0)
528 			return r;
529 	}
530 
531 	status &= ~0x80;
532 	r = set_hwstat(status);
533 	if (r < 0)
534 		return r;
535 
536 	r = get_hwstat(&status);
537 	if (r < 0)
538 		return r;
539 
540 	r = sync_intr(0x56);
541 	if (r < 0)
542 		return r;
543 
544 	return 0;
545 }
546 
alloc_transfers(void)547 static int alloc_transfers(void)
548 {
549 	img_transfer = libusb_alloc_transfer(0);
550 	if (!img_transfer)
551 		return -ENOMEM;
552 
553 	irq_transfer = libusb_alloc_transfer(0);
554 	if (!irq_transfer)
555 		return -ENOMEM;
556 
557 	libusb_fill_bulk_transfer(img_transfer, devh, EP_DATA, imgbuf,
558 		sizeof(imgbuf), cb_img, NULL, 0);
559 	libusb_fill_interrupt_transfer(irq_transfer, devh, EP_INTR, irqbuf,
560 		sizeof(irqbuf), cb_irq, NULL, 0);
561 
562 	return 0;
563 }
564 
sighandler(int signum)565 static void sighandler(int signum)
566 {
567 	(void)signum;
568 
569 	request_exit(1);
570 }
571 
setup_signals(void)572 static void setup_signals(void)
573 {
574 #if defined(PLATFORM_POSIX)
575 	struct sigaction sigact;
576 
577 	sigact.sa_handler = sighandler;
578 	sigemptyset(&sigact.sa_mask);
579 	sigact.sa_flags = 0;
580 	(void)sigaction(SIGINT, &sigact, NULL);
581 	(void)sigaction(SIGTERM, &sigact, NULL);
582 	(void)sigaction(SIGQUIT, &sigact, NULL);
583 #else
584 	(void)signal(SIGINT, sighandler);
585 	(void)signal(SIGTERM, sighandler);
586 #endif
587 }
588 
main(void)589 int main(void)
590 {
591 	int r;
592 
593 	r = libusb_init(NULL);
594 	if (r < 0) {
595 		fprintf(stderr, "failed to initialise libusb %d - %s\n", r, libusb_strerror(r));
596 		exit(1);
597 	}
598 
599 	r = find_dpfp_device();
600 	if (r < 0) {
601 		fprintf(stderr, "Could not find/open device\n");
602 		goto out;
603 	}
604 
605 	r = libusb_claim_interface(devh, 0);
606 	if (r < 0) {
607 		fprintf(stderr, "claim interface error %d - %s\n", r, libusb_strerror(r));
608 		goto out;
609 	}
610 	printf("claimed interface\n");
611 
612 	r = print_f0_data();
613 	if (r < 0)
614 		goto out_release;
615 
616 	r = do_init();
617 	if (r < 0)
618 		goto out_deinit;
619 
620 	/* async from here onwards */
621 	setup_signals();
622 
623 	r = alloc_transfers();
624 	if (r < 0)
625 		goto out_deinit;
626 
627 #if defined(DPFP_THREADED)
628 	exit_semaphore = semaphore_create();
629 	if (!exit_semaphore) {
630 		fprintf(stderr, "failed to initialise semaphore\n");
631 		goto out_deinit;
632 	}
633 
634 	r = thread_create(&poll_thread, poll_thread_main, NULL);
635 	if (r) {
636 		semaphore_destroy(exit_semaphore);
637 		goto out_deinit;
638 	}
639 
640 	r = init_capture();
641 	if (r < 0)
642 		request_exit(2);
643 
644 	while (!do_exit)
645 		semaphore_take(exit_semaphore);
646 #else
647 	r = init_capture();
648 	if (r < 0)
649 		goto out_deinit;
650 
651 	while (!do_exit) {
652 		r = libusb_handle_events(NULL);
653 		if (r < 0)
654 			request_exit(2);
655 	}
656 #endif
657 
658 	printf("shutting down...\n");
659 
660 #if defined(DPFP_THREADED)
661 	thread_join(poll_thread);
662 	semaphore_destroy(exit_semaphore);
663 #endif
664 
665 	if (img_transfer) {
666 		r = libusb_cancel_transfer(img_transfer);
667 		if (r < 0)
668 			fprintf(stderr, "failed to cancel transfer %d - %s\n", r, libusb_strerror(r));
669 	}
670 
671 	if (irq_transfer) {
672 		r = libusb_cancel_transfer(irq_transfer);
673 		if (r < 0)
674 			fprintf(stderr, "failed to cancel transfer %d - %s\n", r, libusb_strerror(r));
675 	}
676 
677 	while (img_transfer || irq_transfer) {
678 		if (libusb_handle_events(NULL) < 0)
679 			break;
680 	}
681 
682 	if (do_exit == 1)
683 		r = 0;
684 	else
685 		r = 1;
686 
687 out_deinit:
688 	if (img_transfer)
689 		libusb_free_transfer(img_transfer);
690 	if (irq_transfer)
691 		libusb_free_transfer(irq_transfer);
692 	set_mode(0);
693 	set_hwstat(0x80);
694 out_release:
695 	libusb_release_interface(devh, 0);
696 out:
697 	libusb_close(devh);
698 	libusb_exit(NULL);
699 	return r >= 0 ? r : -r;
700 }
701