summaryrefslogtreecommitdiff
path: root/services/core/java/com/android/server/biometrics/sensors/BiometricSchedulerOperation.java
blob: 968146a166ed39aea66b54e45f5c454e1c801781 (plain)
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
/*
 * Copyright (C) 2021 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.biometrics.sensors;

import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.hardware.biometrics.BiometricConstants;
import android.os.Handler;
import android.os.IBinder;
import android.util.Slog;

import com.android.internal.annotations.VisibleForTesting;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Contains all the necessary information for a HAL operation.
 */
public class BiometricSchedulerOperation {
    protected static final String TAG = "BiometricSchedulerOperation";

    /**
     * The operation is added to the list of pending operations and waiting for its turn.
     */
    protected static final int STATE_WAITING_IN_QUEUE = 0;

    /**
     * The operation is added to the list of pending operations, but a subsequent operation
     * has been added. This state only applies to {@link Interruptable} operations. When this
     * operation reaches the head of the queue, it will send ERROR_CANCELED and finish.
     */
    protected static final int STATE_WAITING_IN_QUEUE_CANCELING = 1;

    /**
     * The operation has reached the front of the queue and has started.
     */
    protected static final int STATE_STARTED = 2;

    /**
     * The operation was started, but is now canceling. Operations should wait for the HAL to
     * acknowledge that the operation was canceled, at which point it finishes.
     */
    protected static final int STATE_STARTED_CANCELING = 3;

    /**
     * The operation has reached the head of the queue but is waiting for BiometricService
     * to acknowledge and start the operation.
     */
    protected static final int STATE_WAITING_FOR_COOKIE = 4;

    /**
     * The {@link ClientMonitorCallback} has been invoked and the client is finished.
     */
    protected static final int STATE_FINISHED = 5;

    @IntDef({STATE_WAITING_IN_QUEUE,
            STATE_WAITING_IN_QUEUE_CANCELING,
            STATE_STARTED,
            STATE_STARTED_CANCELING,
            STATE_WAITING_FOR_COOKIE,
            STATE_FINISHED})
    @Retention(RetentionPolicy.SOURCE)
    protected @interface OperationState {}

    private static final int CANCEL_WATCHDOG_DELAY_MS = 3000;

    @NonNull
    private final BaseClientMonitor mClientMonitor;
    @Nullable
    private final ClientMonitorCallback mClientCallback;
    @Nullable
    private ClientMonitorCallback mOnStartCallback;
    @OperationState
    private int mState;
    @VisibleForTesting
    @NonNull
    final Runnable mCancelWatchdog;

    BiometricSchedulerOperation(
            @NonNull BaseClientMonitor clientMonitor,
            @Nullable ClientMonitorCallback callback
    ) {
        this(clientMonitor, callback, STATE_WAITING_IN_QUEUE);
    }

    protected BiometricSchedulerOperation(
            @NonNull BaseClientMonitor clientMonitor,
            @Nullable ClientMonitorCallback callback,
            @OperationState int state
    ) {
        mClientMonitor = clientMonitor;
        mClientCallback = callback;
        mState = state;
        mCancelWatchdog = () -> {
            if (!isFinished()) {
                Slog.e(TAG, "[Watchdog Triggered]: " + this);
                getWrappedCallback(mOnStartCallback)
                        .onClientFinished(mClientMonitor, false /* success */);
            }
        };
    }

    /**
     * Zero if this operation is ready to start or has already started. A non-zero cookie
     * is returned if the operation has not started and is waiting on
     * {@link android.hardware.biometrics.IBiometricService#onReadyForAuthentication(int)}.
     *
     * @return cookie or 0 if ready/started
     */
    public int isReadyToStart(@NonNull ClientMonitorCallback callback) {
        if (mState == STATE_WAITING_FOR_COOKIE || mState == STATE_WAITING_IN_QUEUE) {
            final int cookie = mClientMonitor.getCookie();
            if (cookie != 0) {
                mState = STATE_WAITING_FOR_COOKIE;
                mClientMonitor.waitForCookie(getWrappedCallback(callback));
            }
            return cookie;
        }

        return 0;
    }

    /**
     * Start this operation without waiting for a cookie
     * (i.e. {@link #isReadyToStart(ClientMonitorCallback)}  returns zero}
     *
     * @param callback lifecycle callback
     * @return if this operation started
     */
    public boolean start(@NonNull ClientMonitorCallback callback) {
        checkInState("start",
                STATE_WAITING_IN_QUEUE,
                STATE_WAITING_FOR_COOKIE,
                STATE_WAITING_IN_QUEUE_CANCELING);

        if (mClientMonitor.getCookie() != 0) {
            throw new IllegalStateException("operation requires cookie");
        }

        return doStart(callback);
    }

    /**
     * Start this operation after receiving the given cookie.
     *
     * @param callback lifecycle callback
     * @param cookie   cookie indicting the operation should begin
     * @return if this operation started
     */
    public boolean startWithCookie(@NonNull ClientMonitorCallback callback, int cookie) {
        checkInState("start",
                STATE_WAITING_IN_QUEUE,
                STATE_WAITING_FOR_COOKIE,
                STATE_WAITING_IN_QUEUE_CANCELING);

        if (mClientMonitor.getCookie() != cookie) {
            Slog.e(TAG, "Mismatched cookie for operation: " + this + ", received: " + cookie);
            return false;
        }

        return doStart(callback);
    }

    private boolean doStart(@NonNull ClientMonitorCallback callback) {
        mOnStartCallback = callback;
        final ClientMonitorCallback cb = getWrappedCallback(callback);

        if (mState == STATE_WAITING_IN_QUEUE_CANCELING) {
            Slog.d(TAG, "Operation marked for cancellation, cancelling now: " + this);

            cb.onClientFinished(mClientMonitor, true /* success */);
            if (mClientMonitor instanceof ErrorConsumer) {
                final ErrorConsumer errorConsumer = (ErrorConsumer) mClientMonitor;
                errorConsumer.onError(BiometricConstants.BIOMETRIC_ERROR_CANCELED,
                        0 /* vendorCode */);
            } else {
                Slog.w(TAG, "monitor cancelled but does not implement ErrorConsumer");
            }

            return false;
        }

        if (isUnstartableHalOperation()) {
            Slog.v(TAG, "unable to start: " + this);
            ((HalClientMonitor<?>) mClientMonitor).unableToStart();
            cb.onClientFinished(mClientMonitor, false /* success */);
            return false;
        }

        mState = STATE_STARTED;
        mClientMonitor.start(cb);

        Slog.v(TAG, "started: " + this);
        return true;
    }

    /**
     * Abort a pending operation.
     *
     * This is similar to cancel but the operation must not have been started. It will
     * immediately abort the operation and notify the client that it has finished unsuccessfully.
     */
    public void abort() {
        checkInState("cannot abort a non-pending operation",
                STATE_WAITING_IN_QUEUE,
                STATE_WAITING_FOR_COOKIE,
                STATE_WAITING_IN_QUEUE_CANCELING);

        if (isHalOperation()) {
            ((HalClientMonitor<?>) mClientMonitor).unableToStart();
        }
        getWrappedCallback().onClientFinished(mClientMonitor, false /* success */);

        Slog.v(TAG, "Aborted: " + this);
    }

    /** Flags this operation as canceled, if possible, but does not cancel it until started. */
    public boolean markCanceling() {
        if (mState == STATE_WAITING_IN_QUEUE && isInterruptable()) {
            mState = STATE_WAITING_IN_QUEUE_CANCELING;
            return true;
        }
        return false;
    }

    /**
     * Cancel the operation now.
     *
     * @param handler handler to use for the cancellation watchdog
     * @param callback lifecycle callback (only used if this operation hasn't started, otherwise
     *                 the callback used from {@link #start(ClientMonitorCallback)} is used)
     */
    public void cancel(@NonNull Handler handler, @NonNull ClientMonitorCallback callback) {
        checkNotInState("cancel", STATE_FINISHED);

        final int currentState = mState;
        if (!isInterruptable()) {
            Slog.w(TAG, "Cannot cancel - operation not interruptable: " + this);
            return;
        }
        if (currentState == STATE_STARTED_CANCELING) {
            Slog.w(TAG, "Cannot cancel - already invoked for operation: " + this);
            return;
        }

        mState = STATE_STARTED_CANCELING;
        if (currentState == STATE_WAITING_IN_QUEUE
                || currentState == STATE_WAITING_IN_QUEUE_CANCELING
                || currentState == STATE_WAITING_FOR_COOKIE) {
            Slog.d(TAG, "[Cancelling] Current client (without start): " + mClientMonitor);
            ((Interruptable) mClientMonitor).cancelWithoutStarting(getWrappedCallback(callback));
        } else {
            Slog.d(TAG, "[Cancelling] Current client: " + mClientMonitor);
            ((Interruptable) mClientMonitor).cancel();
        }

        // forcibly finish this client if the HAL does not acknowledge within the timeout
        handler.postDelayed(mCancelWatchdog, CANCEL_WATCHDOG_DELAY_MS);
    }

    @NonNull
    private ClientMonitorCallback getWrappedCallback() {
        return getWrappedCallback(null);
    }

    @NonNull
    private ClientMonitorCallback getWrappedCallback(
            @Nullable ClientMonitorCallback callback) {
        final ClientMonitorCallback destroyCallback = new ClientMonitorCallback() {
            @Override
            public void onClientFinished(@NonNull BaseClientMonitor clientMonitor,
                    boolean success) {
                Slog.d(TAG, "[Finished / destroy]: " + clientMonitor);
                mClientMonitor.destroy();
                mState = STATE_FINISHED;
            }
        };
        return new ClientMonitorCompositeCallback(destroyCallback, callback, mClientCallback);
    }

    /** {@link BaseClientMonitor#getSensorId()}. */
    public int getSensorId() {
        return mClientMonitor.getSensorId();
    }

    /** {@link BaseClientMonitor#getProtoEnum()}. */
    public int getProtoEnum() {
        return mClientMonitor.getProtoEnum();
    }

    /** {@link BaseClientMonitor#getTargetUserId()}. */
    public int getTargetUserId() {
        return mClientMonitor.getTargetUserId();
    }

    /** If the given clientMonitor is the same as the one in the constructor. */
    public boolean isFor(@NonNull BaseClientMonitor clientMonitor) {
        return mClientMonitor == clientMonitor;
    }

    /** If this operation is {@link Interruptable}. */
    public boolean isInterruptable() {
        return mClientMonitor instanceof Interruptable;
    }

    private boolean isHalOperation() {
        return mClientMonitor instanceof HalClientMonitor<?>;
    }

    private boolean isUnstartableHalOperation() {
        if (isHalOperation()) {
            final HalClientMonitor<?> client = (HalClientMonitor<?>) mClientMonitor;
            if (client.getFreshDaemon() == null) {
                return true;
            }
        }
        return false;
    }

    /** If this operation is an enrollment. */
    public boolean isEnrollOperation() {
        return mClientMonitor instanceof EnrollClient;
    }

    /** If this operation is authentication. */
    public boolean isAuthenticateOperation() {
        return mClientMonitor instanceof AuthenticationClient;
    }

    /** If this operation is authentication or detection. */
    public boolean isAuthenticationOrDetectionOperation() {
        final boolean isAuthentication = mClientMonitor instanceof AuthenticationConsumer;
        final boolean isDetection = mClientMonitor instanceof DetectionConsumer;
        return isAuthentication || isDetection;
    }

    /** If this operation performs acquisition {@link AcquisitionClient}. */
    public boolean isAcquisitionOperation() {
        return mClientMonitor instanceof AcquisitionClient;
    }

    /**
     * If this operation matches the original requestId.
     *
     * By default, monitors are not associated with a request id to retain the original
     * behavior (i.e. if no requestId is explicitly set then assume it matches)
     *
     * @param requestId a unique id {@link BaseClientMonitor#setRequestId(long)}.
     */
    public boolean isMatchingRequestId(long requestId) {
        return !mClientMonitor.hasRequestId()
                || mClientMonitor.getRequestId() == requestId;
    }

    /** If the token matches */
    public boolean isMatchingToken(@Nullable IBinder token) {
        return mClientMonitor.getToken() == token;
    }

    /** If this operation has started. */
    public boolean isStarted() {
        return mState == STATE_STARTED;
    }

    /** If this operation is cancelling but has not yet completed. */
    public boolean isCanceling() {
        return mState == STATE_STARTED_CANCELING;
    }

    /** If this operation has finished and completed its lifecycle. */
    public boolean isFinished() {
        return mState == STATE_FINISHED;
    }

    /** If {@link #markCanceling()} was called but the operation hasn't been canceled. */
    public boolean isMarkedCanceling() {
        return mState == STATE_WAITING_IN_QUEUE_CANCELING;
    }

    /**
     * The monitor passed to the constructor.
     * @deprecated avoid using and move to encapsulate within the operation
     */
    @Deprecated
    public BaseClientMonitor getClientMonitor() {
        return mClientMonitor;
    }

    private void checkNotInState(String message, @OperationState int... states) {
        for (int state : states) {
            if (mState == state) {
                throw new IllegalStateException(message + ": illegal state= " + state);
            }
        }
    }

    private void checkInState(String message, @OperationState int... states) {
        for (int state : states) {
            if (mState == state) {
                return;
            }
        }
        throw new IllegalStateException(message + ": illegal state= " + mState);
    }

    @Override
    public String toString() {
        return mClientMonitor + ", State: " + mState;
    }
}