1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 /**
18 * This is a very basic implementation of fingerprint to allow testing on the emulator. It
19 * is *not* meant to be the final implementation on real devices. For example, it does *not*
20 * implement all of the required features, such as secure template storage and recognition
21 * inside a Trusted Execution Environment (TEE). However, this file is a reasonable starting
22 * point as developers add fingerprint support to their platform. See inline comments and
23 * recommendations for details.
24 *
25 * Please see the Android Compatibility Definition Document (CDD) for a full list of requirements
26 * and suggestions.
27 */
28 #define LOG_TAG "FingerprintHal"
29
30 #include <errno.h>
31 #include <endian.h>
32 #include <inttypes.h>
33 #include <malloc.h>
34 #include <string.h>
35 #include <log/log.h>
36 #include <hardware/hardware.h>
37 #include <hardware/fingerprint.h>
38 #include "qemud.h"
39
40 #include <poll.h>
41
42 #define FINGERPRINT_LISTEN_SERVICE_NAME "fingerprintlisten"
43 #define FINGERPRINT_FILENAME "emufp.bin"
44 #define AUTHENTICATOR_ID_FILENAME "emuauthid.bin"
45 #define MAX_COMM_CHARS 128
46 #define MAX_COMM_ERRORS 8
47 // Typical devices will allow up to 5 fingerprints per user to maintain performance of
48 // t < 500ms for recognition. This is the total number of fingerprints we'll store.
49 #define MAX_NUM_FINGERS 20
50 #define MAX_FID_VALUE 0x7FFFFFFF // Arbitrary limit
51
52 /**
53 * Most devices will have an internal state machine resembling this. There are 3 basic states, as
54 * shown below. When device is not authenticating or enrolling, it is expected to be in
55 * the idle state.
56 *
57 * Note that this is completely independent of device wake state. If the hardware device was in
58 * the "scan" state when the device drops into power collapse, it should resume scanning when power
59 * is restored. This is to facilitate rapid touch-to-unlock from keyguard.
60 */
61 typedef enum worker_state_t {
62 STATE_IDLE = 0,
63 STATE_ENROLL,
64 STATE_SCAN,
65 STATE_EXIT
66 } worker_state_t;
67
68 typedef struct worker_thread_t {
69 pthread_t thread;
70 worker_state_t state;
71 int samples_remaining;
72 uint64_t secureid[MAX_NUM_FINGERS];
73 uint64_t fingerid[MAX_NUM_FINGERS];
74 char fp_filename[PATH_MAX];
75 char authid_filename[PATH_MAX];
76 } worker_thread_t;
77
78 typedef struct qemu_fingerprint_device_t {
79 fingerprint_device_t device; // "inheritance"
80 worker_thread_t listener;
81 uint64_t op_id;
82 uint64_t challenge;
83 uint64_t user_id;
84 uint64_t group_id;
85 uint64_t secure_user_id;
86 uint64_t authenticator_id;
87 int qchanfd;
88 pthread_mutex_t lock;
89 } qemu_fingerprint_device_t;
90
91 /******************************************************************************/
92
93 static FILE* openForWrite(const char* filename);
94
saveFingerprint(worker_thread_t * listener,int idx)95 static void saveFingerprint(worker_thread_t* listener, int idx) {
96 ALOGD("----------------> %s -----------------> idx %d", __FUNCTION__, idx);
97
98 // Save fingerprints to file
99 FILE* fp = openForWrite(listener->fp_filename);
100 if (fp == NULL) {
101 ALOGE("Could not open fingerprints storage at %s; "
102 "fingerprints won't be saved",
103 listener->fp_filename);
104 perror("Failed to open file");
105 return;
106 }
107
108 ALOGD("Write fingerprint[%d] (0x%" PRIx64 ",0x%" PRIx64 ")", idx,
109 listener->secureid[idx], listener->fingerid[idx]);
110
111 if (fseek(fp, (idx) * sizeof(uint64_t), SEEK_SET) < 0) {
112 ALOGE("Failed while seeking for fingerprint[%d] in emulator storage",
113 idx);
114 fclose(fp);
115 return;
116 }
117 int ns = fwrite(&listener->secureid[idx], sizeof(uint64_t), 1, fp);
118
119 if (fseek(fp, (MAX_NUM_FINGERS + idx) * sizeof(uint64_t), SEEK_SET) < 0) {
120 ALOGE("Failed while seeking for fingerprint[%d] in emulator storage",
121 idx);
122 fclose(fp);
123 return;
124 }
125 int nf = fwrite(&listener->fingerid[idx], sizeof(uint64_t), 1, fp);
126 if (ns != 1 || ns !=1)
127 ALOGW("Corrupt emulator fingerprints storage; could not save "
128 "fingerprints");
129
130 fclose(fp);
131
132 return;
133 }
134
openForWrite(const char * filename)135 static FILE* openForWrite(const char* filename) {
136
137 if (!filename) return NULL;
138
139 FILE* fp = fopen(filename, "r+"); // write but don't truncate
140 if (fp == NULL) {
141 fp = fopen(filename, "w");
142 if (fp) {
143 uint64_t zero = 0;
144 int i = 0;
145 for (i = 0; i < 2*MAX_NUM_FINGERS; ++i) {
146 fwrite(&zero, sizeof(uint64_t), 1, fp);
147 }
148
149 //the last one is for authenticator id
150 fwrite(&zero, sizeof(uint64_t), 1, fp);
151 }
152 }
153 return fp;
154 }
155
saveAuthenticatorId(const char * filename,uint64_t authenid)156 static void saveAuthenticatorId(const char* filename, uint64_t authenid) {
157 ALOGD("----------------> %s ----------------->", __FUNCTION__);
158 FILE* fp = openForWrite(filename);
159 if (!fp) {
160 ALOGE("Failed to open emulator storage file to save authenticator id");
161 return;
162 }
163
164 rewind(fp);
165
166 int na = fwrite(&authenid, sizeof(authenid), 1, fp);
167 if (na != 1) {
168 ALOGE("Failed while writing authenticator id in emulator storage");
169 }
170
171 ALOGD("Save authenticator id (0x%" PRIx64 ")", authenid);
172
173 fclose(fp);
174 }
175
loadAuthenticatorId(const char * authid_filename,uint64_t * pauthenid)176 static void loadAuthenticatorId(const char* authid_filename, uint64_t* pauthenid) {
177 ALOGD("----------------> %s ----------------->", __FUNCTION__);
178 FILE* fp = fopen(authid_filename, "r");
179 if (fp == NULL) {
180 ALOGE("Could not load authenticator id from storage at %s; "
181 "it has not yet been created.",
182 authid_filename);
183 perror("Failed to open/create file");
184 return;
185 }
186
187 rewind(fp);
188
189 int na = fread(pauthenid, sizeof(*pauthenid), 1, fp);
190 if (na != 1)
191 ALOGW("Corrupt emulator authenticator id storage (read %d)", na);
192
193 ALOGD("Read authenticator id (0x%" PRIx64 ")", *pauthenid);
194
195 fclose(fp);
196
197 return;
198 }
199
loadFingerprints(worker_thread_t * listener)200 static void loadFingerprints(worker_thread_t* listener) {
201 ALOGD("----------------> %s ----------------->", __FUNCTION__);
202 FILE* fp = fopen(listener->fp_filename, "r");
203 if (fp == NULL) {
204 ALOGE("Could not load fingerprints from storage at %s; "
205 "it has not yet been created.",
206 listener->fp_filename);
207 perror("Failed to open/create file");
208 return;
209 }
210
211 int ns = fread(listener->secureid, MAX_NUM_FINGERS * sizeof(uint64_t), 1,
212 fp);
213 int nf = fread(listener->fingerid, MAX_NUM_FINGERS * sizeof(uint64_t), 1,
214 fp);
215 if (ns != 1 || nf != 1)
216 ALOGW("Corrupt emulator fingerprints storage (read %d+%db)", ns, nf);
217
218 int i = 0;
219 for (i = 0; i < MAX_NUM_FINGERS; i++)
220 ALOGD("Read fingerprint %d (0x%" PRIx64 ",0x%" PRIx64 ")", i,
221 listener->secureid[i], listener->fingerid[i]);
222
223 fclose(fp);
224
225 return;
226 }
227
228 /******************************************************************************/
229
get_64bit_rand()230 static uint64_t get_64bit_rand() {
231 // This should use a cryptographically-secure random number generator like arc4random().
232 // It should be generated inside of the TEE where possible. Here we just use something
233 // very simple.
234 ALOGD("----------------> %s ----------------->", __FUNCTION__);
235 uint64_t r = (((uint64_t)rand()) << 32) | ((uint64_t)rand());
236 return r != 0 ? r : 1;
237 }
238
fingerprint_get_auth_id(struct fingerprint_device * device)239 static uint64_t fingerprint_get_auth_id(struct fingerprint_device* device) {
240 // This should return the authentication_id generated when the fingerprint template database
241 // was created. Though this isn't expected to be secret, it is reasonable to expect it to be
242 // cryptographically generated to avoid replay attacks.
243 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
244 ALOGD("----------------> %s ----------------->", __FUNCTION__);
245 uint64_t authenticator_id = 0;
246 pthread_mutex_lock(&qdev->lock);
247 authenticator_id = qdev->authenticator_id;
248 pthread_mutex_unlock(&qdev->lock);
249
250 ALOGD("----------------> %s auth id %" PRIx64 "----------------->", __FUNCTION__, authenticator_id);
251 return authenticator_id;
252 }
253
fingerprint_set_active_group(struct fingerprint_device * device,uint32_t gid,const char * path)254 static int fingerprint_set_active_group(struct fingerprint_device *device, uint32_t gid,
255 const char *path) {
256 ALOGD("----------------> %s -----------------> path %s", __FUNCTION__, path);
257 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
258 pthread_mutex_lock(&qdev->lock);
259 qdev->group_id = gid;
260 snprintf(qdev->listener.fp_filename, sizeof(qdev->listener.fp_filename),
261 "%s/%s", path, FINGERPRINT_FILENAME);
262 snprintf(qdev->listener.authid_filename, sizeof(qdev->listener.authid_filename),
263 "%s/%s", path, AUTHENTICATOR_ID_FILENAME);
264 uint64_t authenticator_id = 0;
265 loadFingerprints(&qdev->listener);
266 loadAuthenticatorId(qdev->listener.authid_filename, &authenticator_id);
267 if (authenticator_id == 0) {
268 // firs time, create an authenticator id
269 authenticator_id = get_64bit_rand();
270 // save it to disk
271 saveAuthenticatorId(qdev->listener.authid_filename, authenticator_id);
272 }
273
274 qdev->authenticator_id = authenticator_id;
275 pthread_mutex_unlock(&qdev->lock);
276
277 return 0;
278 }
279
280 /**
281 * If fingerprints are enrolled, then this function is expected to put the sensor into a
282 * "scanning" state where it's actively scanning and recognizing fingerprint features.
283 * Actual authentication must happen in TEE and should be monitored in a separate thread
284 * since this function is expected to return immediately.
285 */
fingerprint_authenticate(struct fingerprint_device * device,uint64_t operation_id,__unused uint32_t gid)286 static int fingerprint_authenticate(struct fingerprint_device *device,
287 uint64_t operation_id, __unused uint32_t gid)
288 {
289 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
290
291 pthread_mutex_lock(&qdev->lock);
292 qdev->op_id = operation_id;
293 qdev->listener.state = STATE_SCAN;
294 pthread_mutex_unlock(&qdev->lock);
295
296 return 0;
297 }
298
299 /**
300 * This is expected to put the sensor into an "enroll" state where it's actively scanning and
301 * working towards a finished fingerprint database entry. Authentication must happen in
302 * a separate thread since this function is expected to return immediately.
303 *
304 * Note: This method should always generate a new random authenticator_id.
305 *
306 * Note: As with fingerprint_authenticate(), this would run in TEE on a real device.
307 */
fingerprint_enroll(struct fingerprint_device * device,const hw_auth_token_t * hat,uint32_t __unused gid,uint32_t __unused timeout_sec)308 static int fingerprint_enroll(struct fingerprint_device *device,
309 const hw_auth_token_t *hat,
310 uint32_t __unused gid,
311 uint32_t __unused timeout_sec) {
312 fingerprint_msg_t msg = {0, {0}};
313 msg.type = FINGERPRINT_ERROR;
314 msg.data.error = FINGERPRINT_ERROR_UNABLE_TO_PROCESS;
315 ALOGD("fingerprint_enroll");
316 qemu_fingerprint_device_t* dev = (qemu_fingerprint_device_t*)device;
317 if (!hat) {
318 ALOGW("%s: null auth token", __func__);
319 dev->device.notify(&msg);
320 return 0;
321 }
322 if (hat->challenge == dev->challenge) {
323 // The secure_user_id retrieved from the auth token should be stored
324 // with the enrolled fingerprint template and returned in the auth result
325 // for a successful authentication with that finger.
326 dev->secure_user_id = hat->user_id;
327 } else {
328 ALOGW("%s: invalid auth token", __func__);
329 }
330
331 if (hat->version != HW_AUTH_TOKEN_VERSION) {
332 dev->device.notify(&msg);
333 return 0;
334 }
335 if (hat->challenge != dev->challenge && !(hat->authenticator_type & HW_AUTH_FINGERPRINT)) {
336 dev->device.notify(&msg);
337 return 0;
338 }
339
340 dev->user_id = hat->user_id;
341
342 pthread_mutex_lock(&dev->lock);
343 dev->listener.state = STATE_ENROLL;
344 dev->listener.samples_remaining = 2;
345 pthread_mutex_unlock(&dev->lock);
346
347 // fingerprint id, authenticator id, and secure_user_id
348 // will be stored by worked thread
349
350 return 0;
351
352 }
353
354 /**
355 * The pre-enrollment step is simply to get an authentication token that can be wrapped and
356 * verified at a later step. The primary purpose is to return a token that protects against
357 * spoofing and replay attacks. It is passed to password authentication where it is wrapped and
358 * propagated to the enroll step.
359 */
fingerprint_pre_enroll(struct fingerprint_device * device)360 static uint64_t fingerprint_pre_enroll(struct fingerprint_device *device) {
361 ALOGD("----------------> %s ----------------->", __FUNCTION__);
362 uint64_t challenge = 0;
363 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
364
365 // The challenge will typically be a cryptographically-secure key
366 // coming from the TEE so it can be verified at a later step. For now we just generate a
367 // random value.
368 challenge = get_64bit_rand();
369
370 pthread_mutex_lock(&qdev->lock);
371 qdev->challenge = challenge;
372 pthread_mutex_unlock(&qdev->lock);
373
374 return challenge;
375 }
376
fingerprint_post_enroll(struct fingerprint_device * device)377 static int fingerprint_post_enroll(struct fingerprint_device* device) {
378 ALOGD("----------------> %s ----------------->", __FUNCTION__);
379 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
380
381 pthread_mutex_lock(&qdev->lock);
382 qdev->challenge = 0;
383 pthread_mutex_unlock(&qdev->lock);
384
385 return 0;
386 }
387
388 /**
389 * Cancel is called by the framework to cancel an outstanding event. This should *not* be called
390 * by the driver since it will cause the framework to stop listening for fingerprints.
391 */
fingerprint_cancel(struct fingerprint_device * device)392 static int fingerprint_cancel(struct fingerprint_device *device) {
393 ALOGD("----------------> %s ----------------->", __FUNCTION__);
394 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
395
396 pthread_mutex_lock(&qdev->lock);
397 qdev->listener.state = STATE_IDLE;
398 pthread_mutex_unlock(&qdev->lock);
399
400 fingerprint_msg_t msg = {0, {0}};
401 msg.type = FINGERPRINT_ERROR;
402 msg.data.error = FINGERPRINT_ERROR_CANCELED;
403 qdev->device.notify(&msg);
404
405 return 0;
406 }
407
fingerprint_enumerate(struct fingerprint_device * device)408 static int fingerprint_enumerate(struct fingerprint_device *device) {
409 ALOGD("----------------> %s ----------------->", __FUNCTION__);
410 if (device == NULL) {
411 ALOGE("Cannot enumerate saved fingerprints with uninitialized params");
412 return -1;
413 }
414
415 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
416 int template_count = 0;
417 for (int i = 0; i < MAX_NUM_FINGERS; i++) {
418 if (qdev->listener.secureid[i] != 0 ||
419 qdev->listener.fingerid[i] != 0) {
420 ALOGD("ENUM: Fingerprint [%d] = 0x%" PRIx64 ",%" PRIx64, i,
421 qdev->listener.secureid[i], qdev->listener.fingerid[i]);
422 template_count++;
423 }
424 }
425 fingerprint_msg_t message = {0, {0}};
426 message.type = FINGERPRINT_TEMPLATE_ENUMERATING;
427 message.data.enumerated.finger.gid = qdev->group_id;
428
429 if(template_count == 0) {
430 message.data.enumerated.remaining_templates = 0;
431 message.data.enumerated.finger.fid = 0;
432 qdev->device.notify(&message);
433 }
434 else {
435 for (int i = 0; i < MAX_NUM_FINGERS; i++) {
436 if (qdev->listener.secureid[i] != 0 ||
437 qdev->listener.fingerid[i] != 0) {
438 template_count--;
439 message.data.enumerated.remaining_templates = template_count;
440 message.data.enumerated.finger.fid = qdev->listener.fingerid[i];
441 qdev->device.notify(&message);
442 }
443 }
444 }
445
446 return 0;
447 }
448
fingerprint_remove(struct fingerprint_device * device,uint32_t __unused gid,uint32_t fid)449 static int fingerprint_remove(struct fingerprint_device *device,
450 uint32_t __unused gid, uint32_t fid) {
451 int idx = 0;
452 fingerprint_msg_t msg = {0, {0}};
453 ALOGD("----------------> %s -----------------> fid %d", __FUNCTION__, fid);
454 if (device == NULL) {
455 ALOGE("Can't remove fingerprint (gid=%d, fid=%d); "
456 "device not initialized properly",
457 gid, fid);
458 return -ENODEV;
459 }
460
461 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
462
463 if (fid == 0) {
464 // Delete all fingerprints
465 // I'll do this one at a time, so I am not
466 // holding the mutext during the notification
467 bool listIsEmpty;
468 do {
469 pthread_mutex_lock(&qdev->lock);
470 listIsEmpty = true; // Haven't seen a valid entry yet
471 for (idx = 0; idx < MAX_NUM_FINGERS; idx++) {
472 uint32_t theFid = qdev->listener.fingerid[idx];
473 if (theFid != 0) {
474 // Delete this entry
475 qdev->listener.secureid[idx] = 0;
476 qdev->listener.fingerid[idx] = 0;
477 saveFingerprint(&qdev->listener, idx);
478
479 // Send a notification that we deleted this one
480 pthread_mutex_unlock(&qdev->lock);
481 msg.type = FINGERPRINT_TEMPLATE_REMOVED;
482 msg.data.removed.finger.fid = theFid;
483 msg.data.removed.finger.gid = qdev->group_id;
484 device->notify(&msg);
485
486 // Because we released the mutex, the list
487 // may have changed. Restart the 'for' loop
488 // after reacquiring the mutex.
489 listIsEmpty = false;
490 break;
491 }
492 } // end for (idx < MAX_NUM_FINGERS)
493 } while (!listIsEmpty);
494 qdev->listener.state = STATE_IDLE;
495 pthread_mutex_unlock(&qdev->lock);
496 msg.type = FINGERPRINT_TEMPLATE_REMOVED;
497 msg.data.removed.finger.fid = 0;
498 msg.data.removed.finger.gid = qdev->group_id;
499 device->notify(&msg);
500 } else {
501 // Delete one fingerprint
502 // Look for this finger ID in our table.
503 pthread_mutex_lock(&qdev->lock);
504 for (idx = 0; idx < MAX_NUM_FINGERS; idx++) {
505 if (qdev->listener.fingerid[idx] == fid &&
506 qdev->listener.secureid[idx] != 0) {
507 // Found it!
508 break;
509 }
510 }
511 if (idx >= MAX_NUM_FINGERS) {
512 qdev->listener.state = STATE_IDLE;
513 pthread_mutex_unlock(&qdev->lock);
514 ALOGE("Fingerprint ID %d not found", fid);
515 //msg.type = FINGERPRINT_ERROR;
516 //msg.data.error = FINGERPRINT_ERROR_UNABLE_TO_REMOVE;
517 //device->notify(&msg);
518 msg.type = FINGERPRINT_TEMPLATE_REMOVED;
519 msg.data.removed.finger.fid = 0;
520 msg.data.removed.finger.gid = qdev->group_id;
521 msg.data.removed.remaining_templates = 0;
522 device->notify(&msg);
523 return 0;
524 }
525
526 qdev->listener.secureid[idx] = 0;
527 qdev->listener.fingerid[idx] = 0;
528 saveFingerprint(&qdev->listener, idx);
529
530 qdev->listener.state = STATE_IDLE;
531 pthread_mutex_unlock(&qdev->lock);
532
533 msg.type = FINGERPRINT_TEMPLATE_REMOVED;
534 msg.data.removed.finger.fid = fid;
535 device->notify(&msg);
536 }
537
538 return 0;
539 }
540
set_notify_callback(struct fingerprint_device * device,fingerprint_notify_t notify)541 static int set_notify_callback(struct fingerprint_device *device,
542 fingerprint_notify_t notify) {
543 ALOGD("----------------> %s ----------------->", __FUNCTION__);
544 if (device == NULL || notify == NULL) {
545 ALOGE("Failed to set notify callback @ %p for fingerprint device %p",
546 device, notify);
547 return -1;
548 }
549
550 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
551 pthread_mutex_lock(&qdev->lock);
552 qdev->listener.state = STATE_IDLE;
553 device->notify = notify;
554 pthread_mutex_unlock(&qdev->lock);
555 ALOGD("fingerprint callback notification set");
556
557 return 0;
558 }
559
is_valid_fid(qemu_fingerprint_device_t * qdev,uint64_t fid)560 static bool is_valid_fid(qemu_fingerprint_device_t* qdev, uint64_t fid) {
561 int idx = 0;
562 if (0 == fid) { return false; }
563 for (idx = 0; idx < MAX_NUM_FINGERS; idx++) {
564 if (qdev->listener.fingerid[idx] == fid) {
565 return true;
566 }
567 }
568 return false;
569 }
570
send_scan_notice(qemu_fingerprint_device_t * qdev,int fid)571 static void send_scan_notice(qemu_fingerprint_device_t* qdev, int fid) {
572 ALOGD("----------------> %s ----------------->", __FUNCTION__);
573
574 // acquired message
575 fingerprint_msg_t acqu_msg = {0, {0}};
576 acqu_msg.type = FINGERPRINT_ACQUIRED;
577 acqu_msg.data.acquired.acquired_info = FINGERPRINT_ACQUIRED_GOOD;
578
579 // authenticated message
580 fingerprint_msg_t auth_msg = {0, {0}};
581 auth_msg.type = FINGERPRINT_AUTHENTICATED;
582 auth_msg.data.authenticated.finger.fid = is_valid_fid(qdev, fid) ? fid : 0;
583 auth_msg.data.authenticated.finger.gid = 0; // unused
584 auth_msg.data.authenticated.hat.version = HW_AUTH_TOKEN_VERSION;
585 auth_msg.data.authenticated.hat.authenticator_type =
586 htobe32(HW_AUTH_FINGERPRINT);
587 auth_msg.data.authenticated.hat.challenge = qdev->op_id;
588 auth_msg.data.authenticated.hat.authenticator_id = qdev->authenticator_id;
589 auth_msg.data.authenticated.hat.user_id = qdev->secure_user_id;
590 struct timespec ts;
591 clock_gettime(CLOCK_MONOTONIC, &ts);
592 auth_msg.data.authenticated.hat.timestamp =
593 htobe64((uint64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
594
595 // pthread_mutex_lock(&qdev->lock);
596 qdev->device.notify(&acqu_msg);
597 qdev->device.notify(&auth_msg);
598 // pthread_mutex_unlock(&qdev->lock);
599
600 return;
601 }
602
send_enroll_notice(qemu_fingerprint_device_t * qdev,int fid)603 static void send_enroll_notice(qemu_fingerprint_device_t* qdev, int fid) {
604 ALOGD("----------------> %s -----------------> fid %d", __FUNCTION__, fid);
605
606 if (fid == 0) {
607 ALOGD("Fingerprint ID is zero (invalid)");
608 return;
609 }
610 if (qdev->secure_user_id == 0) {
611 ALOGD("Secure user ID is zero (invalid)");
612 return;
613 }
614
615 // Find an available entry in the table
616 pthread_mutex_lock(&qdev->lock);
617 int idx = 0;
618 for (idx = 0; idx < MAX_NUM_FINGERS; idx++) {
619 if (qdev->listener.secureid[idx] == 0 ||
620 qdev->listener.fingerid[idx] == 0) {
621 // This entry is available
622 break;
623 }
624 }
625 if (idx >= MAX_NUM_FINGERS) {
626 qdev->listener.state = STATE_IDLE;
627 pthread_mutex_unlock(&qdev->lock);
628 ALOGD("Fingerprint ID table is full");
629 return;
630 }
631 qdev->listener.samples_remaining--;
632 int samples_remaining = qdev->listener.samples_remaining;
633 if (samples_remaining <= 0) {
634 qdev->listener.secureid[idx] = qdev->secure_user_id;
635 qdev->listener.fingerid[idx] = fid;
636 saveFingerprint(&qdev->listener, idx);
637 qdev->listener.state = STATE_IDLE;
638 }
639 pthread_mutex_unlock(&qdev->lock);
640 // LOCKED notification?
641 fingerprint_msg_t msg = {0, {0}};
642 msg.type = FINGERPRINT_TEMPLATE_ENROLLING;
643 msg.data.enroll.finger.fid = fid;
644 msg.data.enroll.samples_remaining = samples_remaining > 0 ? samples_remaining : 0;
645 qdev->device.notify(&msg);
646 return;
647 }
648
getListenerState(qemu_fingerprint_device_t * dev)649 static worker_state_t getListenerState(qemu_fingerprint_device_t* dev) {
650 ALOGV("----------------> %s ----------------->", __FUNCTION__);
651 worker_state_t state = STATE_IDLE;
652
653 pthread_mutex_lock(&dev->lock);
654 state = dev->listener.state;
655 pthread_mutex_unlock(&dev->lock);
656
657 return state;
658 }
659
660 /**
661 * This a very simple event loop for the fingerprint sensor. For a given state (enroll, scan),
662 * this would receive events from the sensor and forward them to fingerprintd using the
663 * notify() method.
664 *
665 * In this simple example, we open a qemu channel (a pipe) where the developer can inject events to
666 * exercise the API and test application code.
667 *
668 * The scanner should remain in the scanning state until either an error occurs or the operation
669 * completes.
670 *
671 * Recoverable errors such as EINTR should be handled locally; they should not
672 * be propagated unless there's something the user can do about it (e.g. "clean sensor"). Such
673 * messages should go through the onAcquired() interface.
674 *
675 * If an unrecoverable error occurs, an acquired message (e.g. ACQUIRED_PARTIAL) should be sent,
676 * followed by an error message (e.g. FINGERPRINT_ERROR_UNABLE_TO_PROCESS).
677 *
678 * Note that this event loop would typically run in TEE since it must interact with the sensor
679 * hardware and handle raw fingerprint data and encrypted templates. It is expected that
680 * this code monitors the TEE for resulting events, such as enrollment and authentication status.
681 * Here we just have a very simple event loop that monitors a qemu channel for pseudo events.
682 */
listenerFunction(void * data)683 static void* listenerFunction(void* data) {
684 ALOGD("----------------> %s ----------------->", __FUNCTION__);
685 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)data;
686
687 int fd = qemud_channel_open(FINGERPRINT_LISTEN_SERVICE_NAME);
688 pthread_mutex_lock(&qdev->lock);
689 qdev->qchanfd = fd;
690 if (qdev->qchanfd < 0) {
691 ALOGE("listener cannot open fingerprint listener service exit");
692 pthread_mutex_unlock(&qdev->lock);
693 return NULL;
694 }
695 qdev->listener.state = STATE_IDLE;
696 pthread_mutex_unlock(&qdev->lock);
697
698 const char* cmd = "listen";
699 if (qemud_channel_send(qdev->qchanfd, cmd, strlen(cmd)) < 0) {
700 ALOGE("cannot write fingerprint 'listen' to host");
701 goto done_quiet;
702 }
703
704 int comm_errors = 0;
705 struct pollfd pfd = {
706 .fd = qdev->qchanfd,
707 .events = POLLIN,
708 };
709 while (1) {
710 int size = 0;
711 int fid = 0;
712 char buffer[MAX_COMM_CHARS] = {0};
713 bool disconnected = false;
714 while (1) {
715 if (getListenerState(qdev) == STATE_EXIT) {
716 ALOGD("Received request to exit listener thread");
717 goto done;
718 }
719
720 // Reset revents before poll() (just to be safe)
721 pfd.revents = 0;
722
723 // Poll qemud channel for 5 seconds
724 // TODO: Eliminate the timeout so that polling can be interrupted
725 // instantly. One possible solution is to follow the example of
726 // android::Looper ($AOSP/system/core/include/utils/Looper.h and
727 // $AOSP/system/core/libutils/Looper.cpp), which makes use of an
728 // additional file descriptor ("wake event fd").
729 int nfds = poll(&pfd, 1, 5000);
730 if (nfds < 0) {
731 ALOGE("Could not poll qemud channel: %s", strerror(errno));
732 goto done;
733 }
734
735 if (!nfds) {
736 // poll() timed out - try again
737 continue;
738 }
739
740 // assert(nfds == 1)
741 if (pfd.revents & POLLIN) {
742 // Input data being available doesn't rule out a disconnection
743 disconnected = pfd.revents & (POLLERR | POLLHUP);
744 break; // Exit inner while loop
745 } else {
746 // Some event(s) other than "input data available" occurred,
747 // i.e. POLLERR or POLLHUP, indicating a disconnection
748 ALOGW("Lost connection to qemud channel");
749 goto done;
750 }
751 }
752
753 // Shouldn't block since we were just notified of a POLLIN event
754 if ((size = qemud_channel_recv(qdev->qchanfd, buffer,
755 sizeof(buffer) - 1)) > 0) {
756 buffer[size] = '\0';
757 if (sscanf(buffer, "on:%d", &fid) == 1) {
758 if (fid > 0 && fid <= MAX_FID_VALUE) {
759 switch (qdev->listener.state) {
760 case STATE_ENROLL:
761 send_enroll_notice(qdev, fid);
762 break;
763 case STATE_SCAN:
764 send_scan_notice(qdev, fid);
765 break;
766 default:
767 ALOGE("fingerprint event listener at unexpected "
768 "state 0%x",
769 qdev->listener.state);
770 }
771 } else {
772 ALOGE("fingerprintid %d not in valid range [%d, %d] and "
773 "will be "
774 "ignored",
775 fid, 1, MAX_FID_VALUE);
776 continue;
777 }
778 } else if (strncmp("off", buffer, 3) == 0) {
779 // TODO: Nothing to do here ? Looks valid
780 ALOGD("fingerprint ID %d off", fid);
781 } else {
782 ALOGE("Invalid command '%s' to fingerprint listener", buffer);
783 }
784
785 if (disconnected) {
786 ALOGW("Connection to qemud channel has been lost");
787 break;
788 }
789 } else {
790 ALOGE("fingerprint listener receive failure");
791 if (comm_errors > MAX_COMM_ERRORS)
792 break;
793 }
794 }
795
796 done:
797 ALOGD("Listener exit with %d receive errors", comm_errors);
798 done_quiet:
799 close(qdev->qchanfd);
800 return NULL;
801 }
802
fingerprint_close(hw_device_t * device)803 static int fingerprint_close(hw_device_t* device) {
804 ALOGD("----------------> %s ----------------->", __FUNCTION__);
805 if (device == NULL) {
806 ALOGE("fingerprint hw device is NULL");
807 return -1;
808 }
809
810 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)device;
811 pthread_mutex_lock(&qdev->lock);
812 // Ask listener thread to exit
813 qdev->listener.state = STATE_EXIT;
814 pthread_mutex_unlock(&qdev->lock);
815
816 pthread_join(qdev->listener.thread, NULL);
817 pthread_mutex_destroy(&qdev->lock);
818 free(qdev);
819
820 return 0;
821 }
822
fingerprint_open(const hw_module_t * module,const char __unused * id,hw_device_t ** device)823 static int fingerprint_open(const hw_module_t* module, const char __unused *id,
824 hw_device_t** device)
825 {
826
827 ALOGD("----------------> %s ----------------->", __FUNCTION__);
828 if (device == NULL) {
829 ALOGE("NULL device on open");
830 return -EINVAL;
831 }
832
833 qemu_fingerprint_device_t* qdev = (qemu_fingerprint_device_t*)calloc(
834 1, sizeof(qemu_fingerprint_device_t));
835 if (qdev == NULL) {
836 ALOGE("Insufficient memory for virtual fingerprint device");
837 return -ENOMEM;
838 }
839
840
841 qdev->device.common.tag = HARDWARE_DEVICE_TAG;
842 qdev->device.common.version = HARDWARE_MODULE_API_VERSION(2, 1);
843 qdev->device.common.module = (struct hw_module_t*)module;
844 qdev->device.common.close = fingerprint_close;
845
846 qdev->device.pre_enroll = fingerprint_pre_enroll;
847 qdev->device.enroll = fingerprint_enroll;
848 qdev->device.post_enroll = fingerprint_post_enroll;
849 qdev->device.get_authenticator_id = fingerprint_get_auth_id;
850 qdev->device.set_active_group = fingerprint_set_active_group;
851 qdev->device.authenticate = fingerprint_authenticate;
852 qdev->device.cancel = fingerprint_cancel;
853 qdev->device.enumerate = fingerprint_enumerate;
854 qdev->device.remove = fingerprint_remove;
855 qdev->device.set_notify = set_notify_callback;
856 qdev->device.notify = NULL;
857
858 // init and create listener thread
859 pthread_mutex_init(&qdev->lock, NULL);
860 if (pthread_create(&qdev->listener.thread, NULL, listenerFunction, qdev) !=
861 0)
862 return -1;
863
864 // "Inheritance" / casting
865 *device = &qdev->device.common;
866
867 return 0;
868 }
869
870 static struct hw_module_methods_t fingerprint_module_methods = {
871 .open = fingerprint_open,
872 };
873
874 fingerprint_module_t HAL_MODULE_INFO_SYM = {
875 .common = {
876 .tag = HARDWARE_MODULE_TAG,
877 .module_api_version = FINGERPRINT_MODULE_API_VERSION_2_1,
878 .hal_api_version = HARDWARE_HAL_API_VERSION,
879 .id = FINGERPRINT_HARDWARE_MODULE_ID,
880 .name = "Emulator Fingerprint HAL",
881 .author = "The Android Open Source Project",
882 .methods = &fingerprint_module_methods,
883 },
884 };
885