-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvfs_client.c
More file actions
1895 lines (1729 loc) · 79.9 KB
/
Copy pathvfs_client.c
File metadata and controls
1895 lines (1729 loc) · 79.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* vfs5011_enroll_verify.c
*
* Step 5: full pipeline. Two modes:
*
* ./vfs5011_enroll_verify enroll
* Captures a swipe, extracts minutiae, saves as template.dat
*
* ./vfs5011_enroll_verify verify
* Captures a swipe, extracts minutiae, compares against
* template.dat, and prints:
* checkmark + "Success!" on match
* X + "Incorrect fingerprint" on no match
*
* Build (macOS) — compiles the capture/init code, the matcher
* wrapper, and every mindtct + bozorth3 source file together:
*
* clang vfs5011_enroll_verify.c vfs5011_matcher.c \
* nbis/mindtct/*.c nbis/bozorth3/*.c \
* -o vfs5011_enroll_verify \
* -I. -Inbis/include \
* -I/usr/local/include/libusb-1.0 -L/usr/local/lib -lusb-1.0 \
* -lm
*
* (A build.sh with this exact command is provided alongside this file.)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <libgen.h>
#include <limits.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <termios.h>
#include <stdarg.h>
#include <ctype.h>
#include <stdbool.h>
#include <libusb.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include "vfs5011_proto.h"
#include "vfs5011_matcher.h"
#define VFS5011_VID 0x138a
#define VFS5011_PID 0x0018
enum action_type { ACTION_SEND, ACTION_RECEIVE };
struct usb_action {
enum action_type type;
const char *name;
int endpoint;
int size;
unsigned char *data;
int correct_reply_size;
};
#define SEND(ENDPOINT, COMMAND) \
{ ACTION_SEND, #COMMAND, ENDPOINT, sizeof(COMMAND), COMMAND, 0 },
#define RECV(ENDPOINT, SIZE) \
{ ACTION_RECEIVE, "recv", ENDPOINT, SIZE, NULL, 0 },
#define RECV_CHECK(ENDPOINT, SIZE, EXPECTED) \
{ ACTION_RECEIVE, "recv_check", ENDPOINT, SIZE, EXPECTED, sizeof(EXPECTED) },
static struct usb_action vfs5011_initialization[] = {
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_01)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_19)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_00)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_01)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_02)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_01)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_1A)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_03)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_04)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
RECV(VFS5011_IN_ENDPOINT_DATA, 256)
RECV(VFS5011_IN_ENDPOINT_DATA, 64)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_1A)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_05)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_01)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_06)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
RECV(VFS5011_IN_ENDPOINT_DATA, 17216)
RECV(VFS5011_IN_ENDPOINT_DATA, 32)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_07)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
RECV(VFS5011_IN_ENDPOINT_DATA, 45056)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_08)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
RECV(VFS5011_IN_ENDPOINT_DATA, 16896)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_09)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
RECV(VFS5011_IN_ENDPOINT_DATA, 4928)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_10)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
RECV(VFS5011_IN_ENDPOINT_DATA, 5632)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_11)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
RECV(VFS5011_IN_ENDPOINT_DATA, 5632)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_12)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
RECV(VFS5011_IN_ENDPOINT_DATA, 3328)
RECV(VFS5011_IN_ENDPOINT_DATA, 64)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_13)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_1A)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_03)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_14)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
RECV(VFS5011_IN_ENDPOINT_DATA, 4800)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_1A)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_02)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_27)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_1A)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_15)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_16)
RECV(VFS5011_IN_ENDPOINT_CTRL, 2368)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
RECV(VFS5011_IN_ENDPOINT_DATA, 4800)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_17)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_init_18)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
};
static struct usb_action vfs5011_initiate_capture[] = {
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_04)
RECV(VFS5011_IN_ENDPOINT_DATA, 64)
RECV(VFS5011_IN_ENDPOINT_DATA, 84032)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_1A)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_prepare_00)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_cmd_1A)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_prepare_01)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_prepare_02)
RECV(VFS5011_IN_ENDPOINT_CTRL, 2368)
RECV(VFS5011_IN_ENDPOINT_CTRL, 64)
RECV(VFS5011_IN_ENDPOINT_DATA, 4800)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_prepare_03)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 64, VFS5011_NORMAL_CONTROL_REPLY)
SEND(VFS5011_OUT_ENDPOINT, vfs5011_prepare_04)
RECV_CHECK(VFS5011_IN_ENDPOINT_CTRL, 2368, VFS5011_NORMAL_CONTROL_REPLY)
};
/* Attempts a bulk transfer; on LIBUSB_ERROR_PIPE (stall left over from a
* previous run, or a transient firmware hiccup), clears the halt on that
* endpoint and retries exactly once before giving up. This is what lets
* the program recover on its own instead of needing a manual rerun. */
static int bulk_transfer_with_pipe_retry(libusb_device_handle *handle, int endpoint,
unsigned char *data, int size, int *transferred,
unsigned int timeout) {
int r = libusb_bulk_transfer(handle, endpoint, data, size, transferred, timeout);
if (r == LIBUSB_ERROR_PIPE) {
fprintf(stderr, " (stall on endpoint 0x%02x, clearing halt and retrying)\n", endpoint);
libusb_clear_halt(handle, endpoint);
r = libusb_bulk_transfer(handle, endpoint, data, size, transferred, timeout);
}
return r;
}
static int run_sequence(libusb_device_handle *handle, struct usb_action *seq, int count) {
unsigned char recv_buf[VFS5011_RECEIVE_BUF_SIZE];
int r, transferred, i;
for (i = 0; i < count; i++) {
struct usb_action *a = &seq[i];
if (a->type == ACTION_SEND) {
r = bulk_transfer_with_pipe_retry(handle, a->endpoint, a->data, a->size,
&transferred, VFS5011_DEFAULT_WAIT_TIMEOUT);
if (r != 0 || transferred != a->size) {
fprintf(stderr, "SEND failed at step %d (%s): %s\n", i + 1, a->name, libusb_error_name(r));
return -1;
}
} else {
r = bulk_transfer_with_pipe_retry(handle, a->endpoint, recv_buf, a->size,
&transferred, VFS5011_DEFAULT_WAIT_TIMEOUT);
if (r != 0) {
fprintf(stderr, "RECV failed at step %d: %s\n", i + 1, libusb_error_name(r));
return -1;
}
if (a->data != NULL) {
if (transferred != a->correct_reply_size ||
memcmp(recv_buf, a->data, a->correct_reply_size) != 0) {
fprintf(stderr, "RECV_CHECK mismatch at step %d\n", i + 1);
return -1;
}
}
}
}
return 0;
}
#define CAPTURE_LINES 256
#define MAX_LINES_TOTAL 2000
#define MAX_LINES_READ 100000
#define DEVIATION_THRESHOLD (15*15)
#define DIFFERENCE_THRESHOLD 600
#define STOP_CHECK_LINES 50
#define ASM_RESOLUTION 10
#define ASM_MEDIAN_FILTER_SIZE 25
#define ASM_MAX_SEARCH_OFFSET 30
static int get_deviation(unsigned char *buf, int size) {
int mean = 0, res = 0, i;
for (i = 0; i < size; i++) mean += buf[i];
mean /= size;
for (i = 0; i < size; i++) { int d = (int)buf[i] - mean; res += d * d; }
return res / size;
}
static int get_diff_norm(unsigned char *a, unsigned char *b, int size) {
int res = 0, i;
for (i = 0; i < size; i++) { int d = (int)a[i] - (int)b[i]; res += d * d; }
return res / size;
}
static unsigned char get_pixel(unsigned char *line, int x) { return line[8 + x]; }
static int get_deviation2(unsigned char *row1, unsigned char *row2) {
unsigned char *buf1 = row1 + 56;
unsigned char *buf2 = row2 + 168;
const int size = 64;
int mean = 0, res = 0, i;
for (i = 0; i < size; i++) mean += (int)buf1[i] + (int)buf2[i];
mean /= size;
for (i = 0; i < size; i++) { int d = (int)buf1[i] + (int)buf2[i] - mean; res += d * d; }
return res / size;
}
static int cmpint(const void *a, const void *b) { return (*(const int *)a) - (*(const int *)b); }
static void median_filter(int *data, int size, int filtersize) {
int *result = calloc(size, sizeof(int));
int *sortbuf = calloc(filtersize, sizeof(int));
for (int i = 0; i < size; i++) {
int i1 = i - (filtersize - 1) / 2, i2 = i + (filtersize - 1) / 2;
if (i1 < 0) i1 = 0;
if (i2 >= size) i2 = size - 1;
memmove(sortbuf, data + i1, (size_t)(i2 - i1 + 1) * sizeof(int));
qsort(sortbuf, i2 - i1 + 1, sizeof(int), cmpint);
result[i] = sortbuf[(i2 - i1 + 1) / 2];
}
memmove(data, result, (size_t)size * sizeof(int));
free(result); free(sortbuf);
}
static void interpolate_lines(unsigned char *line1, float y1, unsigned char *line2,
float y2, unsigned char *output, float yi, int size) {
if (!line1 || !line2) return;
for (int i = 0; i < size; i++) {
unsigned char p1 = get_pixel(line1, i), p2 = get_pixel(line2, i);
output[i] = (unsigned char)((float)p1 + (yi - y1) / (y2 - y1) * ((float)p2 - (float)p1));
}
}
static unsigned char *assemble_lines(unsigned char *lines, int lines_len, int max_height, int *out_height) {
int line_stride = VFS5011_LINE_SIZE, width = VFS5011_IMAGE_WIDTH;
int *offsets = calloc((size_t)(lines_len / 2), sizeof(int));
unsigned char *output = calloc((size_t)width * max_height, 1);
float y = 0.0f; int line_ind = 0;
for (int i = 0; i < lines_len - 1; i += 2) {
int bestmatch = i, bestdiff = 0;
int firstrow = i + 1;
int lastrow = (i + ASM_MAX_SEARCH_OFFSET < lines_len - 1) ? i + ASM_MAX_SEARCH_OFFSET : lines_len - 1;
for (int j = firstrow; j <= lastrow; j++) {
int diff = get_deviation2(lines + (size_t)i * line_stride, lines + (size_t)j * line_stride);
if (j == firstrow || diff < bestdiff) { bestdiff = diff; bestmatch = j; }
}
offsets[i / 2] = bestmatch - i;
}
int off_count = (lines_len / 2) - 1;
if (off_count > 0) median_filter(offsets, off_count, ASM_MEDIAN_FILTER_SIZE);
for (int i = 0; i < lines_len - 1; i++) {
int offset = offsets[i / 2];
unsigned char *row1 = lines + (size_t)i * line_stride;
unsigned char *row2 = lines + (size_t)(i + 1) * line_stride;
if (offset > 0) {
float ynext = y + (float)ASM_RESOLUTION / (float)offset;
while ((float)line_ind < ynext) {
if (line_ind > max_height - 1) goto out;
interpolate_lines(row1, y, row2, ynext, output + (size_t)line_ind * width, (float)line_ind, width);
line_ind++;
}
y = ynext;
}
}
out:
free(offsets);
*out_height = line_ind;
return output;
}
/* Runs the full pipeline: init -> initiate-capture -> swipe capture ->
* alignment. Returns a malloc'd VFS5011_IMAGE_WIDTH x *out_height
* grayscale buffer, or NULL on failure. Caller must libusb_init/open
* the device and pass a claimed handle. */
static unsigned char *capture_fingerprint_image(libusb_device_handle *handle, int *out_height) {
if (run_sequence(handle, vfs5011_initialization,
sizeof(vfs5011_initialization)/sizeof(vfs5011_initialization[0])) != 0) {
fprintf(stderr, "Init sequence failed\n");
return NULL;
}
if (run_sequence(handle, vfs5011_initiate_capture,
sizeof(vfs5011_initiate_capture)/sizeof(vfs5011_initiate_capture[0])) != 0) {
fprintf(stderr, "Initiate-capture sequence failed\n");
return NULL;
}
printf("Swipe your finger across the sensor now...\n");
unsigned char *recorded = malloc((size_t)MAX_LINES_TOTAL * VFS5011_LINE_SIZE);
int lines_recorded = 0, lines_captured = 0, empty_lines = 0;
unsigned char *lastline = NULL;
unsigned char *chunk_buf = malloc((size_t)CAPTURE_LINES * VFS5011_LINE_SIZE);
int finished = 0, r;
while (!finished) {
int transferred = 0;
r = libusb_bulk_transfer(handle, VFS5011_IN_ENDPOINT_DATA, chunk_buf,
CAPTURE_LINES * VFS5011_LINE_SIZE, &transferred, 0);
if (r != 0 && r != LIBUSB_ERROR_TIMEOUT) {
fprintf(stderr, "Capture read failed: %s\n", libusb_error_name(r));
break;
}
if (transferred <= 0) continue;
int lines_in_chunk = transferred / VFS5011_LINE_SIZE;
for (int i = 0; i < lines_in_chunk; i++) {
unsigned char *line = chunk_buf + i * VFS5011_LINE_SIZE;
if (get_deviation(line + 8, VFS5011_IMAGE_WIDTH) < DEVIATION_THRESHOLD) {
if (lines_captured == 0) continue;
empty_lines++;
} else empty_lines = 0;
if (empty_lines >= STOP_CHECK_LINES) { finished = 1; break; }
lines_captured++;
if (lines_captured > MAX_LINES_READ) { finished = 1; break; }
if (lastline == NULL || get_diff_norm(lastline + 8, line + 8, VFS5011_IMAGE_WIDTH) >= DIFFERENCE_THRESHOLD) {
if (lines_recorded >= MAX_LINES_TOTAL) { finished = 1; break; }
lastline = recorded + (size_t)lines_recorded * VFS5011_LINE_SIZE;
memcpy(lastline, line, VFS5011_LINE_SIZE);
lines_recorded++;
}
}
}
free(chunk_buf);
if (lines_recorded < 2) {
fprintf(stderr, "Not enough lines captured (%d) — try a slower, fuller swipe.\n", lines_recorded);
free(recorded);
return NULL;
}
int height = 0;
unsigned char *aligned = assemble_lines(recorded, lines_recorded, MAX_LINES_TOTAL, &height);
free(recorded);
if (height <= 0) {
fprintf(stderr, "Alignment produced no output rows.\n");
free(aligned);
return NULL;
}
*out_height = height;
return aligned;
}
static libusb_context *g_ctx = NULL;
static libusb_device_handle *g_handle = NULL;
static int open_device(void) {
if (libusb_init(&g_ctx) < 0) return -1;
libusb_set_option(g_ctx, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_NONE);
/* Right after a close_device() from a previous attempt, macOS
* sometimes hasn't finished settling the device back into a
* re-openable state yet — libusb_open_device_with_vid_pid can
* transiently return NULL even though the device is still
* physically present. Retry a few times with backoff before
* treating it as a genuine "device not found". */
for (int i = 0; i < 5; i++) {
g_handle = libusb_open_device_with_vid_pid(g_ctx, VFS5011_VID, VFS5011_PID);
if (g_handle) break;
usleep(300000); /* 300ms between open attempts */
}
if (!g_handle) { fprintf(stderr, "Device not found\n"); return -1; }
/* Tell libusb to forcibly detach whatever kernel driver has grabbed
* this interface (common on macOS for HID-ish USB devices) BEFORE we
* try to claim it. Without this, claim_interface loses the race
* against the OS almost every time, and we were papering over that
* with a full device reset on every single run — which was hurting
* capture quality (device never fully settled before the swipe). */
libusb_set_auto_detach_kernel_driver(g_handle, 1);
if (libusb_claim_interface(g_handle, 0) == 0) return 0;
/* Before resorting to a full device reset (which is known to hurt
* capture quality on the next swipe), try a few quick re-claims —
* a lot of "Claim failed" cases on macOS are IOKit holding the
* interface exclusively for a brief moment right after enumeration
* or after a previous close, and that clears on its own within a
* few hundred ms without needing a disruptive reset. */
for (int i = 0; i < 3; i++) {
usleep(150000);
if (libusb_claim_interface(g_handle, 0) == 0) return 0;
}
/* Still failed after quick retries — now fall back to reset. This
* should be the rare case, not the common one. */
fprintf(stderr, "Claim failed, resetting device and retrying...\n");
int reset_r = libusb_reset_device(g_handle);
if (reset_r != 0) {
fprintf(stderr, "Device reset failed: %s\n", libusb_error_name(reset_r));
}
usleep(500000);
if (libusb_claim_interface(g_handle, 0) != 0) {
fprintf(stderr, "Claim failed again after reset\n");
return -1;
}
return 0;
}
static void close_device(void) {
if (g_handle) {
/* Proactively clear any halt on the endpoints we use before
* releasing, so the *next* run doesn't inherit a stalled pipe
* from this session (this is what caused the PIPE error /
* cascading Claim failed seen after a previous run). */
libusb_clear_halt(g_handle, VFS5011_IN_ENDPOINT_CTRL);
libusb_clear_halt(g_handle, VFS5011_IN_ENDPOINT_DATA);
libusb_clear_halt(g_handle, VFS5011_OUT_ENDPOINT);
libusb_release_interface(g_handle, 0);
libusb_close(g_handle);
}
if (g_ctx) libusb_exit(g_ctx);
}
#define MATCH_THRESHOLD 20 /* testing lower vs. confirmed impostor ceiling of ~18 */
/* Built-in macOS system sound (no bundled asset -- keeps the repo
* asset-free for open sourcing). Same cue as vfs5011_daemon.c's
* background polling loop, so a rejected swipe sounds the same
* whether it happened via the lock screen or this interactive menu. */
#define FAILURE_SOUND_PATH "/System/Library/Sounds/Basso.aiff"
#define SUCCESS_SOUND_PATH "/System/Library/Sounds/Glass.aiff"
/* Best-effort, backgrounded so it never blocks -- a missing sound
* file or no afplay shouldn't affect matching, just skip the cue. */
static void play_failure_sound(void) {
int status = system("afplay " FAILURE_SOUND_PATH " > /dev/null 2>&1 &");
(void)status;
}
static void play_success_sound(void) {
int status = system("afplay " SUCCESS_SOUND_PATH " > /dev/null 2>&1 &");
(void)status;
}
#define ENROLL_SWIPES 5 /* how many good swipes make up one enrollment */
#define MAX_STORED_TEMPLATES 8 /* array bound for save/load */
#define MIN_MINUTIAE 20 /* below this, a capture is too weak to trust */
#define MAX_SWIPE_RETRIES 3 /* re-prompt this many times before giving up on one swipe */
#define MIN_SELF_CONSISTENCY 15 /* a new enroll swipe must score at least this well against
at least one already-saved swipe from this same session,
or it's treated as an outlier capture and re-prompted */
/* Captures one swipe and extracts its template, re-prompting the user
* up to MAX_SWIPE_RETRIES times if the capture comes back too weak
* (too few minutiae) to be worth keeping.
*
* IMPORTANT: this opens and closes the device fresh for EVERY attempt.
* Testing showed the sensor's internal state doesn't tolerate two
* initiate-capture sequences back-to-back on the same open handle —
* the second swipe stalls both endpoints and never recovers, even
* with clear_halt. A full close+reopen between swipes is what was
* actually working in the separate-process-per-swipe testing, so we
* do that here automatically instead of relying on one long-lived
* handle across multiple swipes. */
static int capture_quality_template(struct xyt_struct *out_tmpl) {
for (int attempt = 1; attempt <= MAX_SWIPE_RETRIES; attempt++) {
if (open_device() != 0) {
close_device();
fprintf(stderr, "Could not open device (attempt %d/%d)\n", attempt, MAX_SWIPE_RETRIES);
usleep(500000);
continue;
}
int height = 0;
unsigned char *image = capture_fingerprint_image(g_handle, &height);
if (!image) {
close_device();
fprintf(stderr, "Capture failed (attempt %d/%d)\n", attempt, MAX_SWIPE_RETRIES);
usleep(500000);
continue;
}
memset(out_tmpl, 0, sizeof(*out_tmpl));
int r = vfs5011_extract_template(image, VFS5011_IMAGE_WIDTH, height, out_tmpl);
free(image);
close_device();
if (r != 0) {
fprintf(stderr, "Minutiae extraction failed (attempt %d/%d)\n", attempt, MAX_SWIPE_RETRIES);
usleep(500000);
continue;
}
if (out_tmpl->nrows < MIN_MINUTIAE) {
fprintf(stderr, "Swipe too weak (%d minutiae, need %d) — swipe again, slower and fuller.\n",
out_tmpl->nrows, MIN_MINUTIAE);
usleep(500000);
continue;
}
return 0;
}
fprintf(stderr, "Gave up after %d weak/failed swipes.\n", MAX_SWIPE_RETRIES);
return -1;
}
/* ------------------------------------------------------------------ *
* VFS CLIENT — interactive menu shell
*
* Everything above this point is the untouched enroll/verify pipeline
* from vfs5011_enroll_verify.c. Below is the menu wrapper: it calls
* straight into capture_quality_template(), vfs5011_save_templates(),
* vfs5011_load_templates(), and vfs5011_match_score() — no duplicated
* capture logic, no reinvented constants.
* ------------------------------------------------------------------ */
#define VFSC_RULE "--------------------------------------------------------------------"
#define MOUNT_SCRIPT_NAME "vfs5011_volume_mount.sh"
#define UNMOUNT_SCRIPT_NAME "vfs5011_volume_unmount.sh"
#define AGENT_INSTALL_SCRIPT_NAME "vfs5011_agent_install.sh"
#define SETUP_VOLUME_SCRIPT_NAME "vfs5011_setup_volume.sh"
#define GRANT_ACCESSIBILITY_SCRIPT_NAME "vfs5011_grant_accessibility.sh"
#define AGENT_LABEL "com.hackintosh.vfs5011agent"
#define VOLUME_NAME "VFSStore"
#define DAEMON_INSTALL_PATH "/usr/local/libexec/vfs5011/vfs5011_daemon"
#define TCC_DB_PATH "/Library/Application Support/com.apple.TCC/TCC.db"
/* ------------------------------------------------------------------ *
* Color / style. isatty()-gated so piping vfs_client's output to a
* file or another program doesn't fill it with raw escape codes --
* colors are a terminal nicety, not something a log parser should
* ever have to deal with. g_color_enabled is decided once at startup
* and every VFSC_* macro below reads through it, so the rest of the
* file never needs its own isatty() checks. */
static int g_color_enabled = 1;
#define VFSC_RESET (g_color_enabled ? "\033[0m" : "")
#define VFSC_BOLD (g_color_enabled ? "\033[1m" : "")
#define VFSC_DIM (g_color_enabled ? "\033[2m" : "")
#define VFSC_RED (g_color_enabled ? "\033[31m" : "")
#define VFSC_GREEN (g_color_enabled ? "\033[32m" : "")
#define VFSC_YELLOW (g_color_enabled ? "\033[33m" : "")
#define VFSC_BLUE (g_color_enabled ? "\033[34m" : "")
#define VFSC_MAGENTA (g_color_enabled ? "\033[35m" : "")
#define VFSC_CYAN (g_color_enabled ? "\033[36m" : "")
#define VFSC_BCYAN (g_color_enabled ? "\033[1;36m" : "")
#define VFSC_BGREEN (g_color_enabled ? "\033[1;32m" : "")
#define VFSC_BRED (g_color_enabled ? "\033[1;31m" : "")
#define VFSC_BYELLOW (g_color_enabled ? "\033[1;33m" : "")
/* Small printf-style helpers so success/error/warning lines look the
* same everywhere instead of every call site hand-rolling its own
* color codes. Errors go to stderr (matching the rest of the file's
* existing convention), success/info/warn go to stdout. */
static void vfsc_ok(const char *fmt, ...) {
va_list ap;
printf("%s", VFSC_GREEN);
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
printf("%s", VFSC_RESET);
}
static void vfsc_err(const char *fmt, ...) {
va_list ap;
fprintf(stderr, "%s", VFSC_BRED);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "%s", VFSC_RESET);
}
static void vfsc_warn(const char *fmt, ...) {
va_list ap;
printf("%s", VFSC_YELLOW);
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
printf("%s", VFSC_RESET);
}
/* ASCII banner shown once at startup, above the interactive menu loop
* -- a stylized fingertip next to a "VFS CLIENT" wordmark. Kept to 70
* columns so it doesn't wrap in a standard 80-column terminal. The
* fingertip glyph is printed in one color, the wordmark in another,
* so it reads as a proper logo rather than a wall of one-color ASCII. */
/* Disable color when stdout isn't a real terminal (piped/redirected)
* or when the caller opts out via the NO_COLOR convention
* (https://no-color.org/) -- both are standard courtesies for a CLI
* tool that other scripts or logs might capture output from. */
static void init_color_support(void) {
if (!isatty(STDOUT_FILENO)) {
g_color_enabled = 0;
return;
}
const char *no_color = getenv("NO_COLOR");
if (no_color && no_color[0] != '\0') {
g_color_enabled = 0;
}
}
static void print_banner(void) {
printf("%s", VFSC_CYAN);
printf(" ,ad8888ba, %s__ ____________%s\n", VFSC_BCYAN, VFSC_CYAN);
printf(" ,8P' \"Y8\" `Y8, %s\\ \\ / / ____/ ___/%s\n", VFSC_BCYAN, VFSC_CYAN);
printf(" ,8' .-\"\"-. `8, %s\\ \\ / / /_ \\__ \\%s\n", VFSC_BCYAN, VFSC_CYAN);
printf(" 8) / () \\ (8 %s\\ \\/ / __/ ___/ /%s\n", VFSC_BCYAN, VFSC_CYAN);
printf(" 8 | ()() | 8 %s\\ / /____/____/%s\n", VFSC_BCYAN, VFSC_CYAN);
printf(" 8) \\ () / (8 %sCLIENT%s\n", VFSC_BCYAN, VFSC_CYAN);
printf(" `8, `-..-' ,8'\n");
printf(" `8a, ,a8' %sValidity VFS5011 Fingerprint Auth%s\n", VFSC_DIM, VFSC_CYAN);
printf(" `\"Y8888P\"'%s %sv%s%s\n", VFSC_RESET, VFSC_DIM, VFS5011_PROJECT_VERSION, VFSC_RESET);
}
/* Clears the terminal and homes the cursor, then redraws the banner --
* used when returning to the main menu after an action completes, so
* the screen doesn't accumulate every enroll/verify/settings output
* from the whole session. Gated on g_color_enabled (same isatty()
* check used for color) since clearing a piped/redirected output
* stream makes no sense and would just inject garbage escape codes
* into a log file. */
static void clear_screen_and_redraw_banner(void) {
if (!g_color_enabled) return;
printf("\033[2J\033[H");
fflush(stdout);
print_banner();
}
/* Multi-finger storage: each enrolled finger gets its own file of
* ENROLL_SWIPES templates, named "<label>.dat", inside a "fingers/"
* subdirectory on the encrypted volume. This replaces the old single
* template.dat (which only ever supported one finger — the multiple
* templates in that file were multiple swipes of that ONE finger, for
* robustness, not multiple distinct fingers). */
#define FINGERS_DIRNAME "fingers"
#define MAX_FINGER_LABEL 40
#define MAX_ENROLLED_FINGERS 10
#define PASSWORD_FILENAME "password.txt" /* must match vfs5011_store_password.sh / vfs5011_daemon.c */
/* Reads one line of input with terminal echo turned off (like a
* normal sudo password prompt), stripping the trailing newline.
* Restores the terminal's original echo setting before returning,
* including on Ctrl+D/EOF. Returns 0 on success, -1 on EOF/error. */
static int read_hidden_line(char *buf, size_t buf_size) {
struct termios old_term, new_term;
int have_term = (tcgetattr(STDIN_FILENO, &old_term) == 0);
if (have_term) {
new_term = old_term;
new_term.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &new_term);
}
int ok = (fgets(buf, buf_size, stdin) != NULL);
if (have_term) tcsetattr(STDIN_FILENO, TCSAFLUSH, &old_term);
printf("\n");
if (!ok) return -1;
size_t len = strlen(buf);
while (len > 0 && (buf[len-1] == '\n' || buf[len-1] == '\r')) buf[--len] = '\0';
return 0;
}
/* Prompts for and stores the password the daemon auto-types on a
* fingerprint match, directly onto the already-mounted VFSStore
* volume at mount_path — same file, same permissions (root:wheel,
* 600) as vfs5011_store_password.sh, just inline in the client so
* Deploy can offer this as part of the same flow instead of requiring
* a separate manual script run. Does NOT mount/unmount the volume
* itself — the caller is expected to already have it mounted, since
* both call sites (Deploy, Settings) need to check for an existing
* password.txt first anyway. Returns 0 if a password ends up stored
* (either just now, or already present when only_if_missing is set),
* -1 on cancel/mismatch/error. */
static int prompt_and_store_password(const char *mount_path, int only_if_missing) {
char password_path[PATH_MAX];
snprintf(password_path, sizeof(password_path), "%s/%s", mount_path, PASSWORD_FILENAME);
if (only_if_missing && access(password_path, F_OK) == 0) {
return 0; /* already set — nothing to do */
}
printf("No stored password found — this is what the daemon types on a successful\n");
printf("fingerprint match, so it needs to be your actual macOS login password.\n\n");
char password[256], confirm[256];
printf("Password: ");
fflush(stdout);
if (read_hidden_line(password, sizeof(password)) != 0) {
printf("Cancelled.\n\n");
return -1;
}
printf("Confirm: ");
fflush(stdout);
if (read_hidden_line(confirm, sizeof(confirm)) != 0) {
memset(password, 0, sizeof(password));
printf("Cancelled.\n\n");
return -1;
}
if (strcmp(password, confirm) != 0) {
memset(password, 0, sizeof(password));
memset(confirm, 0, sizeof(confirm));
vfsc_err("Passwords did not match — nothing was saved.\n\n");
return -1;
}
FILE *f = fopen(password_path, "w");
if (!f) {
memset(password, 0, sizeof(password));
memset(confirm, 0, sizeof(confirm));
vfsc_err("Could not write password file: %s\n\n", strerror(errno));
return -1;
}
fputs(password, f); /* no trailing newline — it would get typed too */
fclose(f);
chmod(password_path, 0600); /* chown to root:wheel happens for free — we're already root here */
memset(password, 0, sizeof(password));
memset(confirm, 0, sizeof(confirm));
printf("Password stored.\n\n");
return 0;
}
/* Directory this binary is running from, resolved once at startup, so
* the mount/unmount scripts can be found by absolute path regardless
* of the caller's current working directory. */
static char g_exec_dir[PATH_MAX];
static void init_exec_dir(const char *argv0) {
char resolved[PATH_MAX];
if (realpath(argv0, resolved) == NULL) {
/* Fall back to argv0 as-is if realpath fails (unusual, but
* don't crash the whole menu over a cosmetic path lookup). */
strncpy(resolved, argv0, sizeof(resolved) - 1);
resolved[sizeof(resolved) - 1] = '\0';
}
char *dir = dirname(resolved); /* may alias into `resolved` — copy immediately */
strncpy(g_exec_dir, dir, sizeof(g_exec_dir) - 1);
g_exec_dir[sizeof(g_exec_dir) - 1] = '\0';
}
/* Cached enrolled-finger list for the status line and for Enroll's
* duplicate-name / capacity checks. NOT re-checked on every menu
* redraw on purpose — the templates volume is unmounted at rest, and
* mounting it just to paint a status line would mean mounting
* constantly while someone sits at the menu, defeating the point of
* per-operation mounting. Enroll/Verify/Manage refresh this for free
* as a side effect since they already have the volume mounted anyway.
* -1 = not checked yet this session. */
static int g_finger_count = -1;
static char g_finger_labels[MAX_ENROLLED_FINGERS][MAX_FINGER_LABEL + 1];
/* Trims whitespace/newline off a raw line of input and rejects
* anything that would be unsafe or ambiguous as a filename. Path
* separators are mapped to underscores rather than rejected outright,
* so a fat-fingered "Right/Index" doesn't just fail with no
* explanation. Returns 0 on success, -1 if the result would be empty. */
static int sanitize_finger_label(const char *input, char *out, size_t out_size) {
while (*input == ' ' || *input == '\t') input++;
size_t len = strlen(input);
while (len > 0 && (input[len - 1] == ' ' || input[len - 1] == '\t' ||
input[len - 1] == '\n' || input[len - 1] == '\r')) {
len--;
}
if (len == 0) return -1;
if (len > out_size - 1) len = out_size - 1;
for (size_t i = 0; i < len; i++) {
char c = input[i];
if (c == '/' || c == '\\') c = '_';
out[i] = c;
}
out[len] = '\0';
return 0;
}
/* Lists every enrolled finger by scanning fingers_dir for "*.dat"
* files and stripping the extension to recover the label. A missing
* directory (nothing enrolled yet) is reported as zero fingers, not
* an error — callers shouldn't need to special-case first-run. */
static int list_enrolled_fingers(const char *fingers_dir,
char labels[][MAX_FINGER_LABEL + 1],
int max_count) {
DIR *d = opendir(fingers_dir);
if (!d) return 0;
struct dirent *entry;
int count = 0;
while (count < max_count && (entry = readdir(d)) != NULL) {
size_t len = strlen(entry->d_name);
if (len > 4 && strcmp(entry->d_name + len - 4, ".dat") == 0) {
size_t label_len = len - 4;
if (label_len > MAX_FINGER_LABEL) label_len = MAX_FINGER_LABEL;
memcpy(labels[count], entry->d_name, label_len);
labels[count][label_len] = '\0';
count++;
}
}
closedir(d);
return count;
}
/* Mounts the encrypted template volume via vfs5011_volume_mount.sh,
* capturing the mount point path it prints on success. The script's
* own diagnostic lines are captured but only surfaced if the mount
* actually fails — on the success path they're just noise ahead of
* every enroll/verify/deploy operation. Returns 0 and fills out_path
* on success. */
static int mount_template_volume(char *out_path, size_t out_path_size) {
char cmd[PATH_MAX * 2];
snprintf(cmd, sizeof(cmd), "\"%s/%s\"", g_exec_dir, MOUNT_SCRIPT_NAME);
FILE *fp = popen(cmd, "r");
if (!fp) {
vfsc_err("Failed to run volume mount script: %s\n", strerror(errno));
return -1;
}
char line[PATH_MAX];
char last_line[PATH_MAX] = {0};
char captured[2048] = {0};
while (fgets(line, sizeof(line), fp)) {
size_t len = strlen(line);
while (len > 0 && (line[len-1] == '\n' || line[len-1] == '\r')) line[--len] = '\0';
if (len > 0) {
strncpy(last_line, line, sizeof(last_line) - 1);
last_line[sizeof(last_line) - 1] = '\0';
strncat(captured, line, sizeof(captured) - strlen(captured) - 2);
strncat(captured, "\n", sizeof(captured) - strlen(captured) - 1);
}
}
int status = pclose(fp);
/* The script's last printed line is the mount path on success — a
* plain absolute path starting with '/'. Anything else (empty, an
* error message, non-zero exit) means mounting failed. */
if (status != 0 || last_line[0] != '/') {
vfsc_err("Volume mount failed (exit status %d):\n%s\n", status, captured);
return -1;
}
strncpy(out_path, last_line, out_path_size - 1);
out_path[out_path_size - 1] = '\0';
return 0;
}
static void unmount_template_volume(void) {
char cmd[PATH_MAX * 2];
snprintf(cmd, sizeof(cmd), "\"%s/%s\" > /dev/null 2>&1", g_exec_dir, UNMOUNT_SCRIPT_NAME);
int status = system(cmd);
if (status != 0) {
vfsc_err(
"Warning: volume unmount script exited with status %d — the volume may "
"still be mounted. Run vfs5011_volume_unmount.sh manually to check.\n",
status);
}
}
/* Mounts the volume just long enough to (re)list enrolled fingers into
* the g_finger_* cache, then unmounts. Used whenever the cache is
* stale (-1) and something needs an authoritative answer — e.g. Enroll
* checking for a name collision, or Manage Fingerprints. */
static int refresh_finger_cache(void) {
char mount_path[PATH_MAX];
if (mount_template_volume(mount_path, sizeof(mount_path)) != 0) {
return -1;
}
char fingers_dir[PATH_MAX];
snprintf(fingers_dir, sizeof(fingers_dir), "%s/%s", mount_path, FINGERS_DIRNAME);
g_finger_count = list_enrolled_fingers(fingers_dir, g_finger_labels, MAX_ENROLLED_FINGERS);
unmount_template_volume();
return g_finger_count;
}
/* Quick presence check: does a device with our VID/PID show up on the
* bus at all? Deliberately does NOT claim the interface — this is just
* for the status line, so it shouldn't fight with (or be blocked by)
* whatever a real enroll/verify call is doing. Safe to call whether or
* not we're root; enumerating the device list doesn't need a claim. */
static int probe_sensor_present(void) {
libusb_context *ctx = NULL;
if (libusb_init(&ctx) < 0) return 0;
libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_NONE);
libusb_device **list = NULL;
ssize_t count = libusb_get_device_list(ctx, &list);
int found = 0;
for (ssize_t i = 0; i < count; i++) {
struct libusb_device_descriptor desc;
if (libusb_get_device_descriptor(list[i], &desc) != 0) continue;
if (desc.idVendor == VFS5011_VID && desc.idProduct == VFS5011_PID) {
found = 1;
break;
}
}
if (list) libusb_free_device_list(list, 1);
libusb_exit(ctx);
return found;
}
/* Deploy state is tracked by asking launchd directly whether the
* agent is loaded AND actually running (not just registered) in the
* calling user's own GUI session -- gui/<uid>, never gui/0, since
* vfs_client re-execs itself under sudo at startup and getuid() at
* that point would report the invoking user, but geteuid() reports
* 0. Reads the true console user via $SUDO_USER (set by sudo), same
* as vfs5011_agent_install.sh does, so this check targets the same
* domain the installer bootstraps into. */
static int is_auth_service_deployed(void) {
const char *sudo_user = getenv("SUDO_USER");
char cmd[512];
if (sudo_user && strcmp(sudo_user, "root") != 0) {
snprintf(cmd, sizeof(cmd),
"uid=$(id -u \"%s\" 2>/dev/null); "
"[ -n \"$uid\" ] && launchctl print \"gui/$uid/" AGENT_LABEL "\" 2>/dev/null "
"| grep -q 'state = running'",
sudo_user);
} else {
snprintf(cmd, sizeof(cmd),
"launchctl print \"gui/%d/" AGENT_LABEL "\" 2>/dev/null | grep -q 'state = running'",
(int)getuid());
}
/* system() returns the child's exit status; grep -q exits 0 on a
* match, non-zero if not found or if the service isn't loaded at
* all -- either case correctly means "not deployed" here. */
return system(cmd) == 0;
}
/* Does the encrypted VFSStore volume exist at all yet (regardless of
* whether it's currently mounted)? A quick, non-mounting check --
* `diskutil info` on a volume name that doesn't exist exits non-zero,
* which is all this needs to know for the status line and for
* deciding whether Deploy/Settings should offer first-time setup. */
static int is_volume_configured(void) {
char cmd[128];
snprintf(cmd, sizeof(cmd), "diskutil info \"%s\" >/dev/null 2>&1", VOLUME_NAME);
return system(cmd) == 0;
}
/* Checks the system TCC database directly for an Allowed
* (auth_value=2) Accessibility grant tied to the daemon's installed
* path -- the same table vfs5011_grant_accessibility.sh writes to.
* Returns 0 if the daemon isn't installed yet, the TCC db is missing,
* or no matching row exists. */
static int is_accessibility_granted(void) {
if (access(TCC_DB_PATH, F_OK) != 0) return 0;
char cmd[512];
snprintf(cmd, sizeof(cmd),
"sqlite3 \"%s\" \"SELECT auth_value FROM access WHERE "
"service='kTCCServiceAccessibility' AND client='%s';\" 2>/dev/null",
TCC_DB_PATH, DAEMON_INSTALL_PATH);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
char line[16] = {0};
int got = fgets(line, sizeof(line), fp) != NULL;
pclose(fp);
if (!got) return 0;
return atoi(line) == 2;
}
static void print_menu(void) {
int sensor_present = probe_sensor_present();
int deployed = is_auth_service_deployed();
int volume_ready = is_volume_configured();
int accessibility_ready = is_accessibility_granted();
printf("%s%s%s\n", VFSC_CYAN, VFSC_RULE, VFSC_RESET);
printf("%s[1]%s Enroll a Finger\n", VFSC_BOLD, VFSC_RESET);
printf("%s[2]%s Verify Fingerprint Match [Score / %d]\n", VFSC_BOLD, VFSC_RESET, MATCH_THRESHOLD);
printf("%s[3]%s Deploy VFS Client for Authentication Services\n", VFSC_BOLD, VFSC_RESET);
printf("\n");
printf("%s[S]%s Settings\n", VFSC_BOLD, VFSC_RESET);
printf("%s[A]%s About\n", VFSC_BOLD, VFSC_RESET);
printf("%s[Q]%s Quit\n", VFSC_BOLD, VFSC_RESET);
printf("%s%s%s\n", VFSC_CYAN, VFSC_RULE, VFSC_RESET);
printf(" * Sensor Status : %s%s%s\n",