1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
|
/**
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.fingerprint;
import android.content.ContentResolver;
import android.content.Context;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.MessageQueue;
import android.os.RemoteException;
import android.util.ArrayMap;
import android.util.Slog;
import com.android.server.SystemService;
import android.hardware.fingerprint.FingerprintUtils;
import android.hardware.fingerprint.Fingerprint;
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.IFingerprintService;
import android.hardware.fingerprint.IFingerprintServiceReceiver;
import static android.Manifest.permission.MANAGE_FINGERPRINT;
import static android.Manifest.permission.USE_FINGERPRINT;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A service to manage multiple clients that want to access the fingerprint HAL API.
* The service is responsible for maintaining a list of clients and dispatching all
* fingerprint -related events.
*
* @hide
*/
public class FingerprintService extends SystemService {
private static final String TAG = "FingerprintService";
private static final boolean DEBUG = true;
private ClientMonitor mAuthClient = null;
private ClientMonitor mEnrollClient = null;
private ClientMonitor mRemoveClient = null;
private static final int MSG_NOTIFY = 10;
private static final int ENROLLMENT_TIMEOUT_MS = 60 * 1000; // 1 minute
// Message types. Used internally to dispatch messages to the correct callback.
// Must agree with the list in fingerprint.h
private static final int FINGERPRINT_ERROR = -1;
private static final int FINGERPRINT_ACQUIRED = 1;
private static final int FINGERPRINT_TEMPLATE_ENROLLING = 3;
private static final int FINGERPRINT_TEMPLATE_REMOVED = 4;
private static final int FINGERPRINT_AUTHENTICATED = 5;
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_NOTIFY:
FpHalMsg m = (FpHalMsg) msg.obj;
handleNotify(m.type, m.arg1, m.arg2, m.arg3);
break;
default:
Slog.w(TAG, "Unknown message:" + msg.what);
}
}
};
private Context mContext;
private int mHalDeviceId;
private int mFailedAttempts;
private final Runnable mLockoutReset = new Runnable() {
@Override
public void run() {
resetFailedAttempts();
}
};
private static final int STATE_IDLE = 0;
private static final int STATE_AUTHENTICATING = 1;
private static final int STATE_ENROLLING = 2;
private static final int STATE_REMOVING = 3;
private static final long MS_PER_SEC = 1000;
private static final long FAIL_LOCKOUT_TIMEOUT_MS = 30*1000;
private static final int MAX_FAILED_ATTEMPTS = 5;
public FingerprintService(Context context) {
super(context);
mContext = context;
nativeInit(Looper.getMainLooper().getQueue(), this);
}
// TODO: Move these into separate process
// JNI methods to communicate from FingerprintService to HAL
static native int nativeEnroll(byte [] token, int groupId, int timeout);
static native long nativePreEnroll();
static native int nativeStopEnrollment();
static native int nativeAuthenticate(long sessionId, int groupId);
static native int nativeStopAuthentication();
static native int nativeRemove(int fingerId, int groupId);
static native int nativeOpenHal();
static native int nativeCloseHal();
static native void nativeInit(MessageQueue queue, FingerprintService service);
static final class FpHalMsg {
int type; // Type of the message. One of the constants in fingerprint.h
int arg1; // optional arguments
int arg2;
int arg3;
FpHalMsg(int type, int arg1, int arg2, int arg3) {
this.type = type;
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
}
/**
* Called from JNI to communicate messages from fingerprint HAL.
*/
void notify(int type, int arg1, int arg2, int arg3) {
mHandler.obtainMessage(MSG_NOTIFY, new FpHalMsg(type, arg1, arg2, arg3)).sendToTarget();
}
void handleNotify(int type, int arg1, int arg2, int arg3) {
Slog.v(TAG, "handleNotify(type=" + type + ", arg1=" + arg1 + ", arg2=" + arg2 + ")"
+ ", mAuthClients = " + mAuthClient + ", mEnrollClient = " + mEnrollClient);
if (mEnrollClient != null) {
final IBinder token = mEnrollClient.token;
if (doNotify(mEnrollClient, type, arg1, arg2, arg3)) {
stopEnrollment(token);
}
}
if (mAuthClient != null) {
final IBinder token = mAuthClient.token;
if (doNotify(mAuthClient, type, arg1, arg2, arg3)) {
stopAuthentication(token);
}
}
if (mRemoveClient != null) {
if (doNotify(mRemoveClient, type, arg1, arg2, arg3)) {
removeClient(mRemoveClient);
}
}
}
// Returns true if the operation is done, i.e. authentication completed
boolean doNotify(ClientMonitor clientMonitor, int type, int arg1, int arg2, int arg3) {
ContentResolver contentResolver = mContext.getContentResolver();
boolean operationCompleted = false;
switch (type) {
case FINGERPRINT_ERROR:
{
final int error = arg1;
clientMonitor.sendError(error);
removeClient(clientMonitor);
operationCompleted = true; // any error means the operation is done
}
break;
case FINGERPRINT_ACQUIRED:
clientMonitor.sendAcquired(arg1 /* acquireInfo */);
break;
case FINGERPRINT_AUTHENTICATED:
{
final int fpId = arg1;
final int groupId = arg2;
clientMonitor.sendAuthenticated(fpId, groupId);
if (fpId == 0) {
if (clientMonitor == mAuthClient) {
operationCompleted = handleFailedAttempt(clientMonitor);
}
} else {
mLockoutReset.run(); // a valid fingerprint resets lockout
}
}
break;
case FINGERPRINT_TEMPLATE_ENROLLING:
{
final int fpId = arg1;
final int groupId = arg2;
final int remaining = arg3;
clientMonitor.sendEnrollResult(fpId, groupId, remaining);
if (remaining == 0) {
addTemplateForUser(clientMonitor, contentResolver, fpId);
operationCompleted = true; // enroll completed
}
}
break;
case FINGERPRINT_TEMPLATE_REMOVED:
{
final int fingerId = arg1;
final int groupId = arg2;
removeTemplateForUser(clientMonitor, contentResolver, fingerId);
if (fingerId == 0) {
operationCompleted = true; // remove completed
} else {
clientMonitor.sendRemoved(fingerId, groupId);
}
}
break;
}
return operationCompleted;
}
private void removeClient(ClientMonitor clientMonitor) {
if (clientMonitor == null) return;
clientMonitor.destroy();
if (clientMonitor == mAuthClient) {
mAuthClient = null;
} else if (clientMonitor == mEnrollClient) {
mEnrollClient = null;
} else if (clientMonitor == mRemoveClient) {
mRemoveClient = null;
}
}
private boolean inLockoutMode() {
return mFailedAttempts > MAX_FAILED_ATTEMPTS;
}
private void resetFailedAttempts() {
if (DEBUG) Slog.v(TAG, "Reset fingerprint lockout");
mFailedAttempts = 0;
}
private boolean handleFailedAttempt(ClientMonitor clientMonitor) {
mFailedAttempts++;
if (mFailedAttempts > MAX_FAILED_ATTEMPTS) {
// Failing multiple times will continue to push out the lockout time.
mHandler.removeCallbacks(mLockoutReset);
mHandler.postDelayed(mLockoutReset, FAIL_LOCKOUT_TIMEOUT_MS);
if (clientMonitor != null
&& !clientMonitor.sendError(FingerprintManager.FINGERPRINT_ERROR_LOCKOUT)) {
Slog.w(TAG, "Cannot send lockout message to client");
}
return true;
}
return false;
}
private void removeTemplateForUser(ClientMonitor clientMonitor, ContentResolver contentResolver,
final int fingerId) {
FingerprintUtils.removeFingerprintIdForUser(fingerId, contentResolver,
clientMonitor.userId);
}
private void addTemplateForUser(ClientMonitor clientMonitor, ContentResolver contentResolver,
final int fingerId) {
FingerprintUtils.addFingerprintIdForUser(contentResolver, fingerId,
clientMonitor.userId);
}
void startEnrollment(IBinder token, byte[] cryptoToken, int groupId,
IFingerprintServiceReceiver receiver, int flags) {
stopPendingOperations();
mEnrollClient = new ClientMonitor(token, receiver, groupId);
final int timeout = (int) (ENROLLMENT_TIMEOUT_MS / MS_PER_SEC);
final int result = nativeEnroll(cryptoToken, groupId, timeout);
if (result != 0) {
Slog.w(TAG, "startEnroll failed, result=" + result);
}
}
public long startPreEnroll(IBinder token) {
return nativePreEnroll();
}
private void stopPendingOperations() {
if (mEnrollClient != null) {
stopEnrollment(mEnrollClient.token);
}
if (mAuthClient != null) {
stopAuthentication(mAuthClient.token);
}
// mRemoveClient is allowed to continue
}
void stopEnrollment(IBinder token) {
final ClientMonitor client = mEnrollClient;
if (client == null || client.token != token) return;
int result = nativeStopEnrollment();
client.sendError(FingerprintManager.FINGERPRINT_ERROR_CANCELED);
removeClient(mEnrollClient);
if (result != 0) {
Slog.w(TAG, "startEnrollCancel failed, result=" + result);
}
}
void startAuthentication(IBinder token, long opId, int groupId,
IFingerprintServiceReceiver receiver, int flags) {
stopPendingOperations();
mAuthClient = new ClientMonitor(token, receiver, groupId);
if (inLockoutMode()) {
Slog.v(TAG, "In lockout mode; disallowing authentication");
if (!mAuthClient.sendError(FingerprintManager.FINGERPRINT_ERROR_LOCKOUT)) {
Slog.w(TAG, "Cannot send timeout message to client");
}
mAuthClient = null;
return;
}
final int timeout = (int) (ENROLLMENT_TIMEOUT_MS / MS_PER_SEC);
final int result = nativeAuthenticate(opId, groupId);
if (result != 0) {
Slog.w(TAG, "startAuthentication failed, result=" + result);
}
}
void stopAuthentication(IBinder token) {
final ClientMonitor client = mAuthClient;
if (client == null || client.token != token) return;
int result = nativeStopAuthentication();
client.sendError(FingerprintManager.FINGERPRINT_ERROR_CANCELED);
removeClient(mAuthClient);
if (result != 0) {
Slog.w(TAG, "stopAuthentication failed, result=" + result);
}
}
void startRemove(IBinder token, int fingerId, int userId,
IFingerprintServiceReceiver receiver) {
mRemoveClient = new ClientMonitor(token, receiver, userId);
// The fingerprint template ids will be removed when we get confirmation from the HAL
final int result = nativeRemove(fingerId, userId);
if (result != 0) {
Slog.w(TAG, "startRemove with id = " + fingerId + " failed with result=" + result);
}
}
public List<Fingerprint> getEnrolledFingerprints(int groupId) {
ContentResolver resolver = mContext.getContentResolver();
int[] ids = FingerprintUtils.getFingerprintIdsForUser(resolver, groupId);
List<Fingerprint> result = new ArrayList<Fingerprint>();
for (int i = 0; i < ids.length; i++) {
// TODO: persist names in Settings
CharSequence name = "Finger" + ids[i];
final int group = 0; // TODO
final int fingerId = ids[i];
final long deviceId = 0; // TODO
Fingerprint item = new Fingerprint(name, 0, ids[i], 0);
result.add(item);
}
return result;
}
public boolean hasEnrolledFingerprints(int groupId) {
ContentResolver resolver = mContext.getContentResolver();
return FingerprintUtils.getFingerprintIdsForUser(resolver, groupId).length > 0;
}
void checkPermission(String permission) {
getContext().enforceCallingOrSelfPermission(permission,
"Must have " + permission + " permission.");
}
private class ClientMonitor implements IBinder.DeathRecipient {
IBinder token;
WeakReference<IFingerprintServiceReceiver> receiver;
int userId;
public ClientMonitor(IBinder token, IFingerprintServiceReceiver receiver, int userId) {
this.token = token;
this.receiver = new WeakReference<IFingerprintServiceReceiver>(receiver);
this.userId = userId;
try {
token.linkToDeath(this, 0);
} catch (RemoteException e) {
Slog.w(TAG, "caught remote exception in linkToDeath: ", e);
}
}
public void destroy() {
if (token != null) {
token.unlinkToDeath(this, 0);
token = null;
}
receiver = null;
}
public void binderDied() {
token = null;
removeClient(this);
}
protected void finalize() throws Throwable {
try {
if (token != null) {
if (DEBUG) Slog.w(TAG, "removing leaked reference: " + token);
removeClient(this);
}
} finally {
super.finalize();
}
}
private boolean sendRemoved(int fingerId, int groupId) {
IFingerprintServiceReceiver rx = receiver.get();
if (rx != null) {
try {
rx.onRemoved(mHalDeviceId, fingerId, groupId);
return true;
} catch (RemoteException e) {
if (DEBUG) Slog.v(TAG, "Failed to invoke sendRemoved:", e);
}
}
removeClient(this);
return false;
}
private boolean sendEnrollResult(int fpId, int groupId, int remaining) {
IFingerprintServiceReceiver rx = receiver.get();
if (rx != null) {
try {
rx.onEnrollResult(mHalDeviceId, fpId, groupId, remaining);
return true;
} catch (RemoteException e) {
if (DEBUG) Slog.v(TAG, "Failed to invoke sendEnrollResult:", e);
}
}
removeClient(this);
return false;
}
private boolean sendAuthenticated(int fpId, int groupId) {
IFingerprintServiceReceiver rx = receiver.get();
if (rx != null) {
try {
rx.onAuthenticated(mHalDeviceId, fpId, groupId);
return true;
} catch (RemoteException e) {
if (DEBUG) Slog.v(TAG, "Failed to invoke sendProcessed:", e);
}
}
removeClient(this);
return false;
}
private boolean sendAcquired(int acquiredInfo) {
IFingerprintServiceReceiver rx = receiver.get();
if (rx != null) {
try {
rx.onAcquired(mHalDeviceId, acquiredInfo);
return true;
} catch (RemoteException e) {
if (DEBUG) Slog.v(TAG, "Failed to invoke sendAcquired:", e);
}
}
removeClient(this);
return false;
}
private boolean sendError(int error) {
IFingerprintServiceReceiver rx = receiver.get();
if (rx != null) {
try {
rx.onError(mHalDeviceId, error);
return true;
} catch (RemoteException e) {
if (DEBUG) Slog.v(TAG, "Failed to invoke sendError:", e);
}
}
removeClient(this);
return false;
}
}
private final class FingerprintServiceWrapper extends IFingerprintService.Stub {
@Override
public long preEnroll(IBinder token) {
checkPermission(MANAGE_FINGERPRINT);
return startPreEnroll(token);
}
@Override
// Binder call
public void enroll(final IBinder token, final byte[] cryptoToken, final int groupId,
final IFingerprintServiceReceiver receiver, final int flags) {
checkPermission(MANAGE_FINGERPRINT);
final byte [] cryptoClone = Arrays.copyOf(cryptoToken, cryptoToken.length);
mHandler.post(new Runnable() {
@Override
public void run() {
startEnrollment(token, cryptoClone, groupId, receiver, flags);
}
});
}
@Override
// Binder call
public void cancelEnrollment(final IBinder token) {
checkPermission(MANAGE_FINGERPRINT);
mHandler.post(new Runnable() {
@Override
public void run() {
stopEnrollment(token);
}
});
}
@Override
// Binder call
public void authenticate(final IBinder token, final long opId, final int groupId,
final IFingerprintServiceReceiver receiver, final int flags) {
checkPermission(USE_FINGERPRINT);
mHandler.post(new Runnable() {
@Override
public void run() {
startAuthentication(token, opId, groupId, receiver, flags);
}
});
}
@Override
// Binder call
public void cancelAuthentication(final IBinder token) {
checkPermission(USE_FINGERPRINT);
mHandler.post(new Runnable() {
@Override
public void run() {
stopAuthentication(token);
}
});
}
@Override
// Binder call
public void remove(final IBinder token, final int fingerId, final int groupId,
final IFingerprintServiceReceiver receiver) {
checkPermission(MANAGE_FINGERPRINT); // TODO: Maybe have another permission
mHandler.post(new Runnable() {
@Override
public void run() {
startRemove(token, fingerId, groupId, receiver);
}
});
}
@Override
// Binder call
public boolean isHardwareDetected(long deviceId) {
checkPermission(USE_FINGERPRINT);
return mHalDeviceId != 0; // TODO
}
@Override
// Binder call
public void rename(final int fingerId, final int groupId, final String name) {
checkPermission(MANAGE_FINGERPRINT);
mHandler.post(new Runnable() {
@Override
public void run() {
Slog.w(TAG, "rename id=" + fingerId + ",gid=" + groupId + ",name=" + name);
}
});
}
@Override
// Binder call
public List<Fingerprint> getEnrolledFingerprints(int groupId) {
checkPermission(USE_FINGERPRINT);
return FingerprintService.this.getEnrolledFingerprints(groupId);
}
@Override
// Binder call
public boolean hasEnrolledFingerprints(int groupId) {
checkPermission(USE_FINGERPRINT);
return FingerprintService.this.hasEnrolledFingerprints(groupId);
}
}
@Override
public void onStart() {
publishBinderService(Context.FINGERPRINT_SERVICE, new FingerprintServiceWrapper());
mHalDeviceId = nativeOpenHal();
if (DEBUG) Slog.v(TAG, "Fingerprint HAL id: " + mHalDeviceId);
}
}
|