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