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