1 /*
2  * Copyright (C) 2008 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 package com.android.keyguard;
18 
19 import static android.app.StatusBarManager.SESSION_KEYGUARD;
20 import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
21 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
22 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
23 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
24 import static android.content.Intent.ACTION_USER_REMOVED;
25 import static android.content.Intent.ACTION_USER_STOPPED;
26 import static android.content.Intent.ACTION_USER_UNLOCKED;
27 import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FACE;
28 import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT;
29 import static android.hardware.biometrics.BiometricConstants.BIOMETRIC_LOCKOUT_NONE;
30 import static android.hardware.biometrics.BiometricConstants.BIOMETRIC_LOCKOUT_PERMANENT;
31 import static android.hardware.biometrics.BiometricConstants.BIOMETRIC_LOCKOUT_TIMED;
32 import static android.hardware.biometrics.BiometricConstants.LockoutMode;
33 import static android.hardware.biometrics.BiometricSourceType.FACE;
34 import static android.hardware.biometrics.BiometricSourceType.FINGERPRINT;
35 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
36 import static android.os.BatteryManager.CHARGING_POLICY_DEFAULT;
37 import static android.os.PowerManager.WAKE_REASON_UNKNOWN;
38 
39 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_BOOT;
40 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
41 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT;
42 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN;
43 import static com.android.keyguard.FaceAuthReasonKt.apiRequestReasonToUiEvent;
44 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_DISPLAY_OFF;
45 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_NON_STRONG_BIOMETRIC_ALLOWED_CHANGED;
46 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_STOPPED_DREAM_STARTED;
47 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_STOPPED_FACE_CANCEL_NOT_RECEIVED;
48 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_STOPPED_FINISHED_GOING_TO_SLEEP;
49 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_STOPPED_FP_LOCKED_OUT;
50 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_STOPPED_KEYGUARD_GOING_AWAY;
51 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_STOPPED_TRUST_ENABLED;
52 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_STOPPED_USER_INPUT_ON_BOUNCER;
53 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_TRIGGERED_ALL_AUTHENTICATORS_REGISTERED;
54 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_TRIGGERED_ALTERNATE_BIOMETRIC_BOUNCER_SHOWN;
55 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_TRIGGERED_DURING_CANCELLATION;
56 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_TRIGGERED_ENROLLMENTS_CHANGED;
57 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_TRIGGERED_FACE_LOCKOUT_RESET;
58 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_TRIGGERED_OCCLUDING_APP_REQUESTED;
59 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_TRIGGERED_ON_REACH_GESTURE_ON_AOD;
60 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_TRIGGERED_RETRY_AFTER_HW_UNAVAILABLE;
61 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_TRIGGERED_TRUST_DISABLED;
62 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_ASSISTANT_VISIBILITY_CHANGED;
63 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_BIOMETRIC_ENABLED_ON_KEYGUARD;
64 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_CAMERA_LAUNCHED;
65 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_FP_AUTHENTICATED;
66 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_GOING_TO_SLEEP;
67 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_KEYGUARD_OCCLUSION_CHANGED;
68 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_KEYGUARD_RESET;
69 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_KEYGUARD_VISIBILITY_CHANGED;
70 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_ON_FACE_AUTHENTICATED;
71 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_ON_KEYGUARD_INIT;
72 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_POSTURE_CHANGED;
73 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_PRIMARY_BOUNCER_SHOWN;
74 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_STARTED_WAKING_UP;
75 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_STRONG_AUTH_CHANGED;
76 import static com.android.keyguard.FaceAuthUiEvent.FACE_AUTH_UPDATED_USER_SWITCHING;
77 import static com.android.systemui.DejankUtils.whitelistIpcs;
78 import static com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_AWAKE;
79 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_OPENED;
80 import static com.android.systemui.statusbar.policy.DevicePostureController.DEVICE_POSTURE_UNKNOWN;
81 
82 import android.annotation.AnyThread;
83 import android.annotation.MainThread;
84 import android.annotation.SuppressLint;
85 import android.app.ActivityTaskManager.RootTaskInfo;
86 import android.app.AlarmManager;
87 import android.app.IActivityTaskManager;
88 import android.app.admin.DevicePolicyManager;
89 import android.app.trust.TrustManager;
90 import android.content.BroadcastReceiver;
91 import android.content.ComponentName;
92 import android.content.Context;
93 import android.content.Intent;
94 import android.content.IntentFilter;
95 import android.content.pm.PackageManager;
96 import android.content.pm.ResolveInfo;
97 import android.content.pm.UserInfo;
98 import android.database.ContentObserver;
99 import android.hardware.SensorPrivacyManager;
100 import android.hardware.biometrics.BiometricAuthenticator;
101 import android.hardware.biometrics.BiometricFingerprintConstants;
102 import android.hardware.biometrics.BiometricManager;
103 import android.hardware.biometrics.BiometricSourceType;
104 import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
105 import android.hardware.biometrics.SensorProperties;
106 import android.hardware.biometrics.SensorPropertiesInternal;
107 import android.hardware.face.FaceAuthenticateOptions;
108 import android.hardware.face.FaceManager;
109 import android.hardware.face.FaceSensorPropertiesInternal;
110 import android.hardware.face.IFaceAuthenticatorsRegisteredCallback;
111 import android.hardware.fingerprint.FingerprintAuthenticateOptions;
112 import android.hardware.fingerprint.FingerprintManager;
113 import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback;
114 import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
115 import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
116 import android.hardware.fingerprint.IFingerprintAuthenticatorsRegisteredCallback;
117 import android.hardware.usb.UsbManager;
118 import android.nfc.NfcAdapter;
119 import android.os.CancellationSignal;
120 import android.os.Handler;
121 import android.os.Looper;
122 import android.os.Message;
123 import android.os.PowerManager;
124 import android.os.RemoteException;
125 import android.os.Trace;
126 import android.os.UserHandle;
127 import android.os.UserManager;
128 import android.provider.Settings;
129 import android.service.dreams.IDreamManager;
130 import android.telephony.CarrierConfigManager;
131 import android.telephony.ServiceState;
132 import android.telephony.SubscriptionInfo;
133 import android.telephony.SubscriptionManager;
134 import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
135 import android.telephony.TelephonyCallback;
136 import android.telephony.TelephonyManager;
137 import android.text.TextUtils;
138 import android.util.SparseArray;
139 import android.util.SparseBooleanArray;
140 import android.view.Display;
141 
142 import androidx.annotation.NonNull;
143 import androidx.annotation.Nullable;
144 
145 import com.android.internal.annotations.VisibleForTesting;
146 import com.android.internal.jank.InteractionJankMonitor;
147 import com.android.internal.logging.InstanceId;
148 import com.android.internal.logging.UiEventLogger;
149 import com.android.internal.util.LatencyTracker;
150 import com.android.internal.widget.LockPatternUtils;
151 import com.android.keyguard.logging.KeyguardUpdateMonitorLogger;
152 import com.android.settingslib.Utils;
153 import com.android.settingslib.WirelessUtils;
154 import com.android.settingslib.fuelgauge.BatteryStatus;
155 import com.android.systemui.Dumpable;
156 import com.android.systemui.R;
157 import com.android.systemui.biometrics.AuthController;
158 import com.android.systemui.biometrics.FingerprintInteractiveToAuthProvider;
159 import com.android.systemui.broadcast.BroadcastDispatcher;
160 import com.android.systemui.dagger.SysUISingleton;
161 import com.android.systemui.dagger.qualifiers.Background;
162 import com.android.systemui.dagger.qualifiers.Main;
163 import com.android.systemui.dump.DumpManager;
164 import com.android.systemui.dump.DumpsysTableLogger;
165 import com.android.systemui.flags.FeatureFlags;
166 import com.android.systemui.flags.Flags;
167 import com.android.systemui.keyguard.WakefulnessLifecycle;
168 import com.android.systemui.keyguard.domain.interactor.FaceAuthenticationListener;
169 import com.android.systemui.keyguard.domain.interactor.KeyguardFaceAuthInteractor;
170 import com.android.systemui.keyguard.shared.constants.TrustAgentUiEvent;
171 import com.android.systemui.keyguard.shared.model.AcquiredFaceAuthenticationStatus;
172 import com.android.systemui.keyguard.shared.model.ErrorFaceAuthenticationStatus;
173 import com.android.systemui.keyguard.shared.model.FaceAuthenticationStatus;
174 import com.android.systemui.keyguard.shared.model.FaceDetectionStatus;
175 import com.android.systemui.keyguard.shared.model.FailedFaceAuthenticationStatus;
176 import com.android.systemui.keyguard.shared.model.HelpFaceAuthenticationStatus;
177 import com.android.systemui.keyguard.shared.model.SuccessFaceAuthenticationStatus;
178 import com.android.systemui.keyguard.shared.model.SysUiFaceAuthenticateOptions;
179 import com.android.systemui.log.SessionTracker;
180 import com.android.systemui.plugins.WeatherData;
181 import com.android.systemui.plugins.statusbar.StatusBarStateController;
182 import com.android.systemui.settings.DisplayTracker;
183 import com.android.systemui.settings.UserTracker;
184 import com.android.systemui.shared.system.TaskStackChangeListener;
185 import com.android.systemui.shared.system.TaskStackChangeListeners;
186 import com.android.systemui.statusbar.StatusBarState;
187 import com.android.systemui.statusbar.phone.KeyguardBypassController;
188 import com.android.systemui.statusbar.policy.DevicePostureController;
189 import com.android.systemui.statusbar.policy.DevicePostureController.DevicePostureInt;
190 import com.android.systemui.telephony.TelephonyListenerManager;
191 import com.android.systemui.util.Assert;
192 import com.android.systemui.util.settings.SecureSettings;
193 
194 import com.google.android.collect.Lists;
195 
196 import java.io.PrintWriter;
197 import java.lang.ref.WeakReference;
198 import java.util.ArrayList;
199 import java.util.Arrays;
200 import java.util.Collections;
201 import java.util.HashMap;
202 import java.util.HashSet;
203 import java.util.Iterator;
204 import java.util.List;
205 import java.util.Map;
206 import java.util.Map.Entry;
207 import java.util.Optional;
208 import java.util.Set;
209 import java.util.TimeZone;
210 import java.util.concurrent.CountDownLatch;
211 import java.util.concurrent.Executor;
212 import java.util.stream.Collectors;
213 
214 import javax.inject.Inject;
215 import javax.inject.Provider;
216 
217 /**
218  * Watches for updates that may be interesting to the keyguard, and provides
219  * the up to date information as well as a registration for callbacks that care
220  * to be updated.
221  */
222 @SysUISingleton
223 public class KeyguardUpdateMonitor implements TrustManager.TrustListener, Dumpable {
224 
225     private static final String TAG = "KeyguardUpdateMonitor";
226     private static final int BIOMETRIC_LOCKOUT_RESET_DELAY_MS = 600;
227 
228     // Callback messages
229     private static final int MSG_TIME_UPDATE = 301;
230     private static final int MSG_BATTERY_UPDATE = 302;
231     private static final int MSG_SIM_STATE_CHANGE = 304;
232     private static final int MSG_PHONE_STATE_CHANGED = 306;
233     private static final int MSG_DEVICE_PROVISIONED = 308;
234     private static final int MSG_DPM_STATE_CHANGED = 309;
235     private static final int MSG_USER_SWITCHING = 310;
236     private static final int MSG_KEYGUARD_RESET = 312;
237     private static final int MSG_USER_SWITCH_COMPLETE = 314;
238     private static final int MSG_REPORT_EMERGENCY_CALL_ACTION = 318;
239     private static final int MSG_STARTED_WAKING_UP = 319;
240     private static final int MSG_FINISHED_GOING_TO_SLEEP = 320;
241     private static final int MSG_STARTED_GOING_TO_SLEEP = 321;
242     private static final int MSG_KEYGUARD_BOUNCER_CHANGED = 322;
243     private static final int MSG_SIM_SUBSCRIPTION_INFO_CHANGED = 328;
244     private static final int MSG_AIRPLANE_MODE_CHANGED = 329;
245     private static final int MSG_SERVICE_STATE_CHANGE = 330;
246     private static final int MSG_SCREEN_TURNED_OFF = 332;
247     private static final int MSG_DREAMING_STATE_CHANGED = 333;
248     private static final int MSG_USER_UNLOCKED = 334;
249     private static final int MSG_ASSISTANT_STACK_CHANGED = 335;
250     private static final int MSG_BIOMETRIC_AUTHENTICATION_CONTINUE = 336;
251     private static final int MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED = 337;
252     private static final int MSG_TELEPHONY_CAPABLE = 338;
253     private static final int MSG_TIMEZONE_UPDATE = 339;
254     private static final int MSG_USER_STOPPED = 340;
255     private static final int MSG_USER_REMOVED = 341;
256     private static final int MSG_KEYGUARD_GOING_AWAY = 342;
257     private static final int MSG_TIME_FORMAT_UPDATE = 344;
258     private static final int MSG_REQUIRE_NFC_UNLOCK = 345;
259     private static final int MSG_KEYGUARD_DISMISS_ANIMATION_FINISHED = 346;
260     private static final int MSG_SERVICE_PROVIDERS_UPDATED = 347;
261     private static final int MSG_BIOMETRIC_ENROLLMENT_STATE_CHANGED = 348;
262 
263     /** Biometric authentication state: Not listening. */
264     private static final int BIOMETRIC_STATE_STOPPED = 0;
265 
266     /** Biometric authentication state: Listening. */
267     private static final int BIOMETRIC_STATE_RUNNING = 1;
268 
269     /**
270      * Biometric authentication: Cancelling and waiting for the relevant biometric service to
271      * send us the confirmation that cancellation has happened.
272      */
273     @VisibleForTesting
274     protected static final int BIOMETRIC_STATE_CANCELLING = 2;
275 
276     /**
277      * Biometric state: During cancelling we got another request to start listening, so when we
278      * receive the cancellation done signal, we should start listening again.
279      */
280     @VisibleForTesting
281     protected static final int BIOMETRIC_STATE_CANCELLING_RESTARTING = 3;
282 
283     /**
284      * Action indicating keyguard *can* start biometric authentiation.
285      */
286     private static final int BIOMETRIC_ACTION_START = 0;
287     /**
288      * Action indicating keyguard *can* stop biometric authentiation.
289      */
290     private static final int BIOMETRIC_ACTION_STOP = 1;
291     /**
292      * Action indicating keyguard *can* start or stop biometric authentiation.
293      */
294     private static final int BIOMETRIC_ACTION_UPDATE = 2;
295 
296     @VisibleForTesting
297     public static final int BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED = -1;
298     public static final int BIOMETRIC_HELP_FACE_NOT_RECOGNIZED = -2;
299     public static final int BIOMETRIC_HELP_FACE_NOT_AVAILABLE = -3;
300 
301     /**
302      * If no cancel signal has been received after this amount of time, set the biometric running
303      * state to stopped to allow Keyguard to retry authentication.
304      */
305     @VisibleForTesting
306     protected static final int DEFAULT_CANCEL_SIGNAL_TIMEOUT = 3000;
307 
308     private static final ComponentName FALLBACK_HOME_COMPONENT = new ComponentName(
309             "com.android.settings", "com.android.settings.FallbackHome");
310 
311     private static final List<Integer> ABSENT_SIM_STATE_LIST = Arrays.asList(
312             TelephonyManager.SIM_STATE_ABSENT,
313             TelephonyManager.SIM_STATE_UNKNOWN,
314             TelephonyManager.SIM_STATE_NOT_READY);
315 
316     private final Context mContext;
317     private final UserTracker mUserTracker;
318     private final KeyguardUpdateMonitorLogger mLogger;
319     private final boolean mIsSystemUser;
320     private final AuthController mAuthController;
321     private final UiEventLogger mUiEventLogger;
322     private final Set<Integer> mFaceAcquiredInfoIgnoreList;
323     private final Set<String> mAllowFingerprintOnOccludingActivitiesFromPackage;
324     private final PackageManager mPackageManager;
325     private int mStatusBarState;
326     private final StatusBarStateController.StateListener mStatusBarStateControllerListener =
327             new StatusBarStateController.StateListener() {
328         @Override
329         public void onStateChanged(int newState) {
330             mStatusBarState = newState;
331         }
332 
333         @Override
334         public void onExpandedChanged(boolean isExpanded) {
335             for (int i = 0; i < mCallbacks.size(); i++) {
336                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
337                 if (cb != null) {
338                     cb.onShadeExpandedChanged(isExpanded);
339                 }
340             }
341         }
342     };
343     private final DisplayTracker.Callback mDisplayCallback = new DisplayTracker.Callback() {
344         @Override
345         public void onDisplayChanged(int displayId) {
346             if (displayId != Display.DEFAULT_DISPLAY) {
347                 return;
348             }
349 
350             if (mWakefulness.getWakefulness() == WAKEFULNESS_AWAKE
351                     && mDisplayTracker.getDisplay(mDisplayTracker.getDefaultDisplayId()).getState()
352                     == Display.STATE_OFF) {
353                 mAllowedDisplayStateWhileAwakeForFaceAuth = false;
354                 updateFaceListeningState(
355                         BIOMETRIC_ACTION_STOP,
356                         FACE_AUTH_DISPLAY_OFF
357                 );
358             } else {
359                 mAllowedDisplayStateWhileAwakeForFaceAuth = true;
360             }
361         }
362     };
363     private final FaceWakeUpTriggersConfig mFaceWakeUpTriggersConfig;
364 
365     HashMap<Integer, SimData> mSimDatas = new HashMap<>();
366     HashMap<Integer, ServiceState> mServiceStates = new HashMap<>();
367 
368     private int mPhoneState;
369     private boolean mKeyguardShowing;
370     private boolean mKeyguardOccluded;
371     private boolean mCredentialAttempted;
372     private boolean mKeyguardGoingAway;
373     private boolean mGoingToSleep;
374     private boolean mPrimaryBouncerFullyShown;
375     private boolean mPrimaryBouncerIsOrWillBeShowing;
376     private boolean mAlternateBouncerShowing;
377     private boolean mAuthInterruptActive;
378     private boolean mNeedsSlowUnlockTransition;
379     private boolean mAssistantVisible;
380     private boolean mOccludingAppRequestingFp;
381     private boolean mOccludingAppRequestingFace;
382     private boolean mSecureCameraLaunched;
383     private boolean mAllowedDisplayStateWhileAwakeForFaceAuth = true;
384     @VisibleForTesting
385     protected boolean mTelephonyCapable;
386     private boolean mAllowFingerprintOnCurrentOccludingActivity;
387 
388     // Device provisioning state
389     private boolean mDeviceProvisioned;
390 
391     // Battery status
392     @VisibleForTesting
393     BatteryStatus mBatteryStatus;
394     @VisibleForTesting
395     boolean mIncompatibleCharger;
396 
397     private StrongAuthTracker mStrongAuthTracker;
398 
399     private final ArrayList<WeakReference<KeyguardUpdateMonitorCallback>>
400             mCallbacks = Lists.newArrayList();
401     private ContentObserver mDeviceProvisionedObserver;
402     private final ContentObserver mTimeFormatChangeObserver;
403 
404     private boolean mSwitchingUser;
405 
406     private boolean mDeviceInteractive;
407     private final SubscriptionManager mSubscriptionManager;
408     private final TelephonyListenerManager mTelephonyListenerManager;
409     private final TrustManager mTrustManager;
410     private final UserManager mUserManager;
411     private final DevicePolicyManager mDevicePolicyManager;
412     private final DevicePostureController mPostureController;
413     private final BroadcastDispatcher mBroadcastDispatcher;
414     private final SecureSettings mSecureSettings;
415     private final InteractionJankMonitor mInteractionJankMonitor;
416     private final LatencyTracker mLatencyTracker;
417     private final StatusBarStateController mStatusBarStateController;
418     private final Executor mBackgroundExecutor;
419     private final SensorPrivacyManager mSensorPrivacyManager;
420     private final ActiveUnlockConfig mActiveUnlockConfig;
421     private final IDreamManager mDreamManager;
422     private final TelephonyManager mTelephonyManager;
423     private final FeatureFlags mFeatureFlags;
424     @Nullable
425     private final FingerprintManager mFpm;
426     @Nullable
427     private final FaceManager mFaceManager;
428     @Nullable
429     private KeyguardFaceAuthInteractor mFaceAuthInteractor;
430     private final TaskStackChangeListeners mTaskStackChangeListeners;
431     private final IActivityTaskManager mActivityTaskManager;
432     private final WakefulnessLifecycle mWakefulness;
433     private final DisplayTracker mDisplayTracker;
434     private final LockPatternUtils mLockPatternUtils;
435     @VisibleForTesting
436     @DevicePostureInt
437     protected int mConfigFaceAuthSupportedPosture;
438 
439     private KeyguardBypassController mKeyguardBypassController;
440     private List<SubscriptionInfo> mSubscriptionInfo;
441     @VisibleForTesting
442     protected int mFingerprintRunningState = BIOMETRIC_STATE_STOPPED;
443     private int mFaceRunningState = BIOMETRIC_STATE_STOPPED;
444     private boolean mIsDreaming;
445     private boolean mLogoutEnabled;
446     private boolean mIsFaceEnrolled;
447     private int mActiveMobileDataSubscription = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
448     private int mPostureState = DEVICE_POSTURE_UNKNOWN;
449     private FingerprintInteractiveToAuthProvider mFingerprintInteractiveToAuthProvider;
450 
451     /**
452      * Short delay before restarting fingerprint authentication after a successful try. This should
453      * be slightly longer than the time between onFingerprintAuthenticated and
454      * setKeyguardGoingAway(true).
455      */
456     private static final int FINGERPRINT_CONTINUE_DELAY_MS = 500;
457 
458     // If the HAL dies or is unable to authenticate, keyguard should retry after a short delay
459     private int mHardwareFingerprintUnavailableRetryCount = 0;
460     private int mHardwareFaceUnavailableRetryCount = 0;
461     private static final int HAL_ERROR_RETRY_TIMEOUT = 500; // ms
462     private static final int HAL_ERROR_RETRY_MAX = 20;
463 
464     @VisibleForTesting
465     protected static final int HAL_POWER_PRESS_TIMEOUT = 50; // ms
466 
467     @VisibleForTesting
468     protected final Runnable mFpCancelNotReceived = this::onFingerprintCancelNotReceived;
469 
470     private final Runnable mFaceCancelNotReceived = this::onFaceCancelNotReceived;
471     private final Provider<SessionTracker> mSessionTrackerProvider;
472 
473     @VisibleForTesting
getHandler()474     protected Handler getHandler() {
475         return mHandler;
476     }
477 
478     private final Handler mHandler;
479 
480     private final IBiometricEnabledOnKeyguardCallback mBiometricEnabledCallback =
481             new IBiometricEnabledOnKeyguardCallback.Stub() {
482                 @Override
483                 public void onChanged(boolean enabled, int userId) {
484                     mHandler.post(() -> {
485                         mBiometricEnabledForUser.put(userId, enabled);
486                         updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
487                                 FACE_AUTH_UPDATED_BIOMETRIC_ENABLED_ON_KEYGUARD);
488                     });
489                 }
490             };
491 
492     @VisibleForTesting
493     public TelephonyCallback.ActiveDataSubscriptionIdListener mPhoneStateListener =
494             new TelephonyCallback.ActiveDataSubscriptionIdListener() {
495         @Override
496         public void onActiveDataSubscriptionIdChanged(int subId) {
497             mActiveMobileDataSubscription = subId;
498             mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED);
499         }
500     };
501 
502     private final OnSubscriptionsChangedListener mSubscriptionListener =
503             new OnSubscriptionsChangedListener() {
504                 @Override
505                 public void onSubscriptionsChanged() {
506                     mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED);
507                 }
508             };
509 
510     @VisibleForTesting
511     static class BiometricAuthenticated {
512         private final boolean mAuthenticated;
513         private final boolean mIsStrongBiometric;
514 
BiometricAuthenticated(boolean authenticated, boolean isStrongBiometric)515         BiometricAuthenticated(boolean authenticated, boolean isStrongBiometric) {
516             this.mAuthenticated = authenticated;
517             this.mIsStrongBiometric = isStrongBiometric;
518         }
519     }
520 
521     private final SparseBooleanArray mUserIsUnlocked = new SparseBooleanArray();
522     private final SparseBooleanArray mUserHasTrust = new SparseBooleanArray();
523     private final SparseBooleanArray mUserTrustIsManaged = new SparseBooleanArray();
524     private final SparseBooleanArray mUserTrustIsUsuallyManaged = new SparseBooleanArray();
525     private final SparseBooleanArray mBiometricEnabledForUser = new SparseBooleanArray();
526     private final Map<Integer, Intent> mSecondaryLockscreenRequirement = new HashMap<>();
527 
528     private final KeyguardFingerprintListenModel.Buffer mFingerprintListenBuffer =
529             new KeyguardFingerprintListenModel.Buffer();
530     private final KeyguardFaceListenModel.Buffer mFaceListenBuffer =
531             new KeyguardFaceListenModel.Buffer();
532     private final KeyguardActiveUnlockModel.Buffer mActiveUnlockTriggerBuffer =
533             new KeyguardActiveUnlockModel.Buffer();
534 
535     @VisibleForTesting
536     SparseArray<BiometricAuthenticated> mUserFingerprintAuthenticated = new SparseArray<>();
537     @VisibleForTesting
538     SparseArray<BiometricAuthenticated> mUserFaceAuthenticated = new SparseArray<>();
539 
540     private static int sCurrentUser;
541 
setCurrentUser(int currentUser)542     public synchronized static void setCurrentUser(int currentUser) {
543         sCurrentUser = currentUser;
544     }
545 
546     /**
547      * @deprecated This can potentially return unexpected values in a multi user scenario
548      * as this state is managed by another component. Consider using {@link UserTracker}.
549      */
550     @Deprecated
getCurrentUser()551     public synchronized static int getCurrentUser() {
552         return sCurrentUser;
553     }
554 
555     @Override
onTrustChanged(boolean enabled, boolean newlyUnlocked, int userId, int flags, List<String> trustGrantedMessages)556     public void onTrustChanged(boolean enabled, boolean newlyUnlocked, int userId, int flags,
557             List<String> trustGrantedMessages) {
558         Assert.isMainThread();
559         boolean wasTrusted = mUserHasTrust.get(userId, false);
560         mUserHasTrust.put(userId, enabled);
561         // If there was no change in trusted state or trust granted, make sure we are not
562         // authenticating.  TrustManager sends an onTrustChanged whenever a user unlocks keyguard,
563         // for this reason we need to make sure to not authenticate.
564         if (wasTrusted == enabled || enabled) {
565             updateBiometricListeningState(BIOMETRIC_ACTION_STOP,
566                     FACE_AUTH_STOPPED_TRUST_ENABLED);
567         } else {
568             updateBiometricListeningState(BIOMETRIC_ACTION_START,
569                     FACE_AUTH_TRIGGERED_TRUST_DISABLED);
570         }
571 
572         mLogger.logTrustChanged(wasTrusted, enabled, userId);
573         for (int i = 0; i < mCallbacks.size(); i++) {
574             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
575             if (cb != null) {
576                 cb.onTrustChanged(userId);
577             }
578         }
579 
580         if (enabled) {
581             String message = null;
582             if (KeyguardUpdateMonitor.getCurrentUser() == userId
583                     && trustGrantedMessages != null) {
584                 // Show the first non-empty string provided by a trust agent OR intentionally pass
585                 // an empty string through (to prevent the default trust agent string from showing)
586                 for (String msg : trustGrantedMessages) {
587                     message = msg;
588                     if (!TextUtils.isEmpty(message)) {
589                         break;
590                     }
591                 }
592             }
593 
594             mLogger.logTrustGrantedWithFlags(flags, newlyUnlocked, userId, message);
595             if (userId == getCurrentUser()) {
596                 if (newlyUnlocked) {
597                     // if this callback is ever removed, this should then be logged in
598                     // TrustRepository
599                     mUiEventLogger.log(
600                             TrustAgentUiEvent.TRUST_AGENT_NEWLY_UNLOCKED,
601                             getKeyguardSessionId()
602                     );
603                 }
604                 final TrustGrantFlags trustGrantFlags = new TrustGrantFlags(flags);
605                 for (int i = 0; i < mCallbacks.size(); i++) {
606                     KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
607                     if (cb != null) {
608                         cb.onTrustGrantedForCurrentUser(
609                                 shouldDismissKeyguardOnTrustGrantedWithCurrentUser(trustGrantFlags),
610                                 newlyUnlocked,
611                                 trustGrantFlags,
612                                 message
613                         );
614                     }
615                 }
616             }
617         }
618     }
619 
620     @Override
onIsActiveUnlockRunningChanged(boolean isRunning, int userId)621     public void onIsActiveUnlockRunningChanged(boolean isRunning, int userId) {
622     }
623 
624     /**
625      * Whether the trust granted call with its passed flags should dismiss keyguard.
626      * It's assumed that the trust was granted for the current user.
627      */
shouldDismissKeyguardOnTrustGrantedWithCurrentUser(TrustGrantFlags flags)628     private boolean shouldDismissKeyguardOnTrustGrantedWithCurrentUser(TrustGrantFlags flags) {
629         final boolean isBouncerShowing =
630                 mPrimaryBouncerIsOrWillBeShowing || mAlternateBouncerShowing;
631         return (flags.isInitiatedByUser() || flags.dismissKeyguardRequested())
632                 && (mDeviceInteractive || flags.temporaryAndRenewable())
633                 && (isBouncerShowing || flags.dismissKeyguardRequested());
634     }
635 
636     @Override
onTrustError(CharSequence message)637     public void onTrustError(CharSequence message) {
638         dispatchErrorMessage(message);
639     }
640 
641     @Override
onEnabledTrustAgentsChanged(int userId)642     public void onEnabledTrustAgentsChanged(int userId) {
643         Assert.isMainThread();
644 
645         for (int i = 0; i < mCallbacks.size(); i++) {
646             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
647             if (cb != null) {
648                 cb.onEnabledTrustAgentsChanged(userId);
649             }
650         }
651     }
652 
handleSimSubscriptionInfoChanged()653     private void handleSimSubscriptionInfoChanged() {
654         Assert.isMainThread();
655         mLogger.v("onSubscriptionInfoChanged()");
656         List<SubscriptionInfo> sil = mSubscriptionManager
657                 .getCompleteActiveSubscriptionInfoList();
658         if (sil != null) {
659             for (SubscriptionInfo subInfo : sil) {
660                 mLogger.logSubInfo(subInfo);
661             }
662         } else {
663             mLogger.v("onSubscriptionInfoChanged: list is null");
664         }
665         List<SubscriptionInfo> subscriptionInfos = getSubscriptionInfo(true /* forceReload */);
666 
667         // Hack level over 9000: Because the subscription id is not yet valid when we see the
668         // first update in handleSimStateChange, we need to force refresh all SIM states
669         // so the subscription id for them is consistent.
670         ArrayList<SubscriptionInfo> changedSubscriptions = new ArrayList<>();
671         Set<Integer> activeSubIds = new HashSet<>();
672         for (int i = 0; i < subscriptionInfos.size(); i++) {
673             SubscriptionInfo info = subscriptionInfos.get(i);
674             activeSubIds.add(info.getSubscriptionId());
675             boolean changed = refreshSimState(info.getSubscriptionId(), info.getSimSlotIndex());
676             if (changed) {
677                 changedSubscriptions.add(info);
678             }
679         }
680 
681         // It is possible for active subscriptions to become invalid (-1), and these will not be
682         // present in the subscriptionInfo list
683         Iterator<Map.Entry<Integer, SimData>> iter = mSimDatas.entrySet().iterator();
684         while (iter.hasNext()) {
685             Map.Entry<Integer, SimData> simData = iter.next();
686             if (!activeSubIds.contains(simData.getKey())) {
687                 mLogger.logInvalidSubId(simData.getKey());
688                 iter.remove();
689 
690                 SimData data = simData.getValue();
691                 for (int j = 0; j < mCallbacks.size(); j++) {
692                     KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get();
693                     if (cb != null) {
694                         cb.onSimStateChanged(data.subId, data.slotId, data.simState);
695                     }
696                 }
697             }
698         }
699 
700         for (int i = 0; i < changedSubscriptions.size(); i++) {
701             SimData data = mSimDatas.get(changedSubscriptions.get(i).getSubscriptionId());
702             for (int j = 0; j < mCallbacks.size(); j++) {
703                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get();
704                 if (cb != null) {
705                     cb.onSimStateChanged(data.subId, data.slotId, data.simState);
706                 }
707             }
708         }
709         callbacksRefreshCarrierInfo();
710     }
711 
handleAirplaneModeChanged()712     private void handleAirplaneModeChanged() {
713         callbacksRefreshCarrierInfo();
714     }
715 
callbacksRefreshCarrierInfo()716     private void callbacksRefreshCarrierInfo() {
717         Assert.isMainThread();
718         for (int i = 0; i < mCallbacks.size(); i++) {
719             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
720             if (cb != null) {
721                 cb.onRefreshCarrierInfo();
722             }
723         }
724     }
725 
726     /**
727      * @return List of SubscriptionInfo records, maybe empty but never null.
728      */
getSubscriptionInfo(boolean forceReload)729     public List<SubscriptionInfo> getSubscriptionInfo(boolean forceReload) {
730         List<SubscriptionInfo> sil = mSubscriptionInfo;
731         if (sil == null || forceReload) {
732             sil = mSubscriptionManager.getCompleteActiveSubscriptionInfoList();
733         }
734         if (sil == null) {
735             // getCompleteActiveSubscriptionInfoList was null callers expect an empty list.
736             mSubscriptionInfo = new ArrayList<>();
737         } else {
738             mSubscriptionInfo = sil;
739         }
740         return new ArrayList<>(mSubscriptionInfo);
741     }
742 
743     /**
744      * This method returns filtered list of SubscriptionInfo from {@link #getSubscriptionInfo}.
745      * above. Maybe empty but never null.
746      *
747      * In DSDS mode if both subscriptions are grouped and one is opportunistic, we filter out one
748      * of them based on carrier config. e.g. In this case we should only show one carrier name
749      * on the status bar and quick settings.
750      */
getFilteredSubscriptionInfo()751     public List<SubscriptionInfo> getFilteredSubscriptionInfo() {
752         List<SubscriptionInfo> subscriptions = getSubscriptionInfo(false);
753         if (subscriptions.size() == 2) {
754             SubscriptionInfo info1 = subscriptions.get(0);
755             SubscriptionInfo info2 = subscriptions.get(1);
756             if (info1.getGroupUuid() != null && info1.getGroupUuid().equals(info2.getGroupUuid())) {
757                 // If both subscriptions are primary, show both.
758                 if (!info1.isOpportunistic() && !info2.isOpportunistic()) return subscriptions;
759 
760                 // If carrier required, always show signal bar of primary subscription.
761                 // Otherwise, show whichever subscription is currently active for Internet.
762                 boolean alwaysShowPrimary = CarrierConfigManager.getDefaultConfig()
763                         .getBoolean(CarrierConfigManager
764                         .KEY_ALWAYS_SHOW_PRIMARY_SIGNAL_BAR_IN_OPPORTUNISTIC_NETWORK_BOOLEAN);
765                 if (alwaysShowPrimary) {
766                     subscriptions.remove(info1.isOpportunistic() ? info1 : info2);
767                 } else {
768                     subscriptions.remove(info1.getSubscriptionId() == mActiveMobileDataSubscription
769                             ? info2 : info1);
770                 }
771 
772             }
773         }
774 
775         return subscriptions;
776     }
777 
778     @Override
onTrustManagedChanged(boolean managed, int userId)779     public void onTrustManagedChanged(boolean managed, int userId) {
780         Assert.isMainThread();
781         mUserTrustIsManaged.put(userId, managed);
782         boolean trustUsuallyManaged = mTrustManager.isTrustUsuallyManaged(userId);
783         mLogger.logTrustUsuallyManagedUpdated(userId, mUserTrustIsUsuallyManaged.get(userId),
784                 trustUsuallyManaged, "onTrustManagedChanged");
785         mUserTrustIsUsuallyManaged.put(userId, trustUsuallyManaged);
786         for (int i = 0; i < mCallbacks.size(); i++) {
787             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
788             if (cb != null) {
789                 cb.onTrustManagedChanged(userId);
790             }
791         }
792     }
793 
794     /**
795      * Updates KeyguardUpdateMonitor's internal state to know if credential was attempted on
796      * bouncer. Note that this does not care if the credential was correct/incorrect. This is
797      * cleared when the user leaves the bouncer (unlocked, screen off, back to lockscreen, etc)
798      */
setCredentialAttempted()799     public void setCredentialAttempted() {
800         mCredentialAttempted = true;
801         // Do not update face listening state in case of false authentication attempts.
802         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
803     }
804 
805     /**
806      * Updates KeyguardUpdateMonitor's internal state to know if keyguard is going away.
807      */
setKeyguardGoingAway(boolean goingAway)808     public void setKeyguardGoingAway(boolean goingAway) {
809         mKeyguardGoingAway = goingAway;
810         if (mKeyguardGoingAway) {
811             updateFaceListeningState(BIOMETRIC_ACTION_STOP,
812                     FACE_AUTH_STOPPED_KEYGUARD_GOING_AWAY);
813             for (int i = 0; i < mCallbacks.size(); i++) {
814                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
815                 if (cb != null) {
816                     cb.onKeyguardGoingAway();
817                 }
818             }
819         }
820         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
821     }
822 
823     /**
824      * Whether keyguard is going away due to screen off or device entry.
825      */
isKeyguardGoingAway()826     public boolean isKeyguardGoingAway() {
827         return mKeyguardGoingAway;
828     }
829 
830     /**
831      * Updates KeyguardUpdateMonitor's internal state to know if keyguard is showing and if
832      * its occluded. The keyguard is considered visible if its showing and NOT occluded.
833      */
setKeyguardShowing(boolean showing, boolean occluded)834     public void setKeyguardShowing(boolean showing, boolean occluded) {
835         final boolean occlusionChanged = mKeyguardOccluded != occluded;
836         final boolean showingChanged = mKeyguardShowing != showing;
837         if (!occlusionChanged && !showingChanged) {
838             return;
839         }
840 
841         final boolean wasKeyguardVisible = isKeyguardVisible();
842         mKeyguardShowing = showing;
843         mKeyguardOccluded = occluded;
844         final boolean isKeyguardVisible = isKeyguardVisible();
845         mLogger.logKeyguardShowingChanged(showing, occluded, isKeyguardVisible);
846 
847         if (isKeyguardVisible != wasKeyguardVisible) {
848             if (isKeyguardVisible) {
849                 mSecureCameraLaunched = false;
850             }
851             for (int i = 0; i < mCallbacks.size(); i++) {
852                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
853                 if (cb != null) {
854                     cb.onKeyguardVisibilityChanged(isKeyguardVisible);
855                 }
856             }
857         }
858 
859         if (occlusionChanged) {
860             updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
861                     FACE_AUTH_UPDATED_KEYGUARD_OCCLUSION_CHANGED);
862         } else if (showingChanged) {
863             updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
864                     FACE_AUTH_UPDATED_KEYGUARD_VISIBILITY_CHANGED);
865         }
866     }
867 
868     /**
869      * Request to listen for face authentication when an app is occluding keyguard.
870      *
871      * @param request if true and mKeyguardOccluded, request face auth listening, else default
872      *                to normal behavior.
873      *                See {@link KeyguardUpdateMonitor#shouldListenForFace()}
874      */
requestFaceAuthOnOccludingApp(boolean request)875     public void requestFaceAuthOnOccludingApp(boolean request) {
876         mOccludingAppRequestingFace = request;
877         int action = mOccludingAppRequestingFace ? BIOMETRIC_ACTION_UPDATE : BIOMETRIC_ACTION_STOP;
878         updateFaceListeningState(action, FACE_AUTH_TRIGGERED_OCCLUDING_APP_REQUESTED);
879     }
880 
881     /**
882      * Request to listen for fingerprint when an app is occluding keyguard.
883      *
884      * @param request if true and mKeyguardOccluded, request fingerprint listening, else default
885      *                to normal behavior.
886      *                See {@link KeyguardUpdateMonitor#shouldListenForFingerprint(boolean)}
887      */
requestFingerprintAuthOnOccludingApp(boolean request)888     public void requestFingerprintAuthOnOccludingApp(boolean request) {
889         mOccludingAppRequestingFp = request;
890         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
891     }
892 
893     /**
894      * Invoked when the secure camera is launched.
895      */
onCameraLaunched()896     public void onCameraLaunched() {
897         mSecureCameraLaunched = true;
898         updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
899                 FACE_AUTH_UPDATED_CAMERA_LAUNCHED);
900     }
901 
902     /**
903      * Whether the secure camera is currently showing over the keyguard.
904      */
isSecureCameraLaunchedOverKeyguard()905     public boolean isSecureCameraLaunchedOverKeyguard() {
906         return mSecureCameraLaunched;
907     }
908 
909     /**
910      * @return a cached version of DreamManager.isDreaming()
911      */
isDreaming()912     public boolean isDreaming() {
913         return mIsDreaming;
914     }
915 
916     /**
917      * If the device is dreaming, awakens the device
918      */
awakenFromDream()919     public void awakenFromDream() {
920         if (mIsDreaming) {
921             try {
922                 mDreamManager.awaken();
923             } catch (RemoteException e) {
924                 mLogger.logException(e, "Unable to awaken from dream");
925             }
926         }
927     }
928 
onBiometricDetected(int userId, BiometricSourceType biometricSourceType, boolean isStrongBiometric)929     private void onBiometricDetected(int userId, BiometricSourceType biometricSourceType,
930             boolean isStrongBiometric) {
931         Assert.isMainThread();
932         Trace.beginSection("KeyGuardUpdateMonitor#onBiometricDetected");
933         for (int i = 0; i < mCallbacks.size(); i++) {
934             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
935             if (cb != null) {
936                 cb.onBiometricDetected(userId, biometricSourceType, isStrongBiometric);
937             }
938         }
939         Trace.endSection();
940     }
941 
942     @VisibleForTesting
onFingerprintAuthenticated(int userId, boolean isStrongBiometric)943     public void onFingerprintAuthenticated(int userId, boolean isStrongBiometric) {
944         Assert.isMainThread();
945         Trace.beginSection("KeyGuardUpdateMonitor#onFingerPrintAuthenticated");
946         mUserFingerprintAuthenticated.put(userId,
947                 new BiometricAuthenticated(true, isStrongBiometric));
948         // Update/refresh trust state only if user can skip bouncer
949         if (getUserCanSkipBouncer(userId)) {
950             mTrustManager.unlockedByBiometricForUser(userId, FINGERPRINT);
951         }
952         // Don't send cancel if authentication succeeds
953         mFingerprintCancelSignal = null;
954         mLogger.logFingerprintSuccess(userId, isStrongBiometric);
955         updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
956                 FACE_AUTH_UPDATED_FP_AUTHENTICATED);
957         for (int i = 0; i < mCallbacks.size(); i++) {
958             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
959             if (cb != null) {
960                 cb.onBiometricAuthenticated(userId, FINGERPRINT,
961                         isStrongBiometric);
962             }
963         }
964 
965         mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE),
966                 FINGERPRINT_CONTINUE_DELAY_MS);
967 
968         // Only authenticate fingerprint once when assistant is visible
969         mAssistantVisible = false;
970 
971         // Report unlock with strong or non-strong biometric
972         reportSuccessfulBiometricUnlock(isStrongBiometric, userId);
973 
974         Trace.endSection();
975     }
976 
reportSuccessfulBiometricUnlock(boolean isStrongBiometric, int userId)977     private void reportSuccessfulBiometricUnlock(boolean isStrongBiometric, int userId) {
978         mBackgroundExecutor.execute(
979                 () -> {
980                     mLogger.logReportSuccessfulBiometricUnlock(isStrongBiometric, userId);
981                     mLockPatternUtils.reportSuccessfulBiometricUnlock(isStrongBiometric, userId);
982                 });
983     }
984 
handleFingerprintAuthFailed()985     private void handleFingerprintAuthFailed() {
986         Assert.isMainThread();
987         if (mHandler.hasCallbacks(mFpCancelNotReceived)) {
988             mLogger.d("handleFingerprintAuthFailed()"
989                     + " triggered while waiting for cancellation, removing watchdog");
990             mHandler.removeCallbacks(mFpCancelNotReceived);
991         }
992         mLogger.d("handleFingerprintAuthFailed");
993         for (int i = 0; i < mCallbacks.size(); i++) {
994             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
995             if (cb != null) {
996                 cb.onBiometricAuthFailed(FINGERPRINT);
997             }
998         }
999         if (isUdfpsSupported()) {
1000             handleFingerprintHelp(BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED,
1001                     mContext.getString(
1002                             com.android.internal.R.string.fingerprint_udfps_error_not_match));
1003         } else {
1004             handleFingerprintHelp(BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED,
1005                     mContext.getString(
1006                             com.android.internal.R.string.fingerprint_error_not_match));
1007         }
1008     }
1009 
handleFingerprintAcquired( @iometricFingerprintConstants.FingerprintAcquired int acquireInfo)1010     private void handleFingerprintAcquired(
1011             @BiometricFingerprintConstants.FingerprintAcquired int acquireInfo) {
1012         Assert.isMainThread();
1013         for (int i = 0; i < mCallbacks.size(); i++) {
1014             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1015             if (cb != null) {
1016                 cb.onBiometricAcquired(FINGERPRINT, acquireInfo);
1017             }
1018         }
1019     }
1020 
handleBiometricDetected(int authUserId, BiometricSourceType biometricSourceType, boolean isStrongBiometric)1021     private void handleBiometricDetected(int authUserId, BiometricSourceType biometricSourceType,
1022             boolean isStrongBiometric) {
1023         Trace.beginSection("KeyGuardUpdateMonitor#handlerBiometricDetected");
1024         onBiometricDetected(authUserId, biometricSourceType, isStrongBiometric);
1025         if (biometricSourceType == FINGERPRINT) {
1026             mLogger.logFingerprintDetected(authUserId, isStrongBiometric);
1027         } else if (biometricSourceType == FACE) {
1028             mLogger.logFaceDetected(authUserId, isStrongBiometric);
1029             setFaceRunningState(BIOMETRIC_STATE_STOPPED);
1030         }
1031 
1032         Trace.endSection();
1033     }
1034 
handleFingerprintAuthenticated(int authUserId, boolean isStrongBiometric)1035     private void handleFingerprintAuthenticated(int authUserId, boolean isStrongBiometric) {
1036         Trace.beginSection("KeyGuardUpdateMonitor#handlerFingerPrintAuthenticated");
1037         if (mHandler.hasCallbacks(mFpCancelNotReceived)) {
1038             mLogger.d("handleFingerprintAuthenticated()"
1039                     + " triggered while waiting for cancellation, removing watchdog");
1040             mHandler.removeCallbacks(mFpCancelNotReceived);
1041         }
1042         try {
1043             final int userId = mUserTracker.getUserId();
1044             if (userId != authUserId) {
1045                 mLogger.logFingerprintAuthForWrongUser(authUserId);
1046                 return;
1047             }
1048             if (isFingerprintDisabled(userId)) {
1049                 mLogger.logFingerprintDisabledForUser(userId);
1050                 return;
1051             }
1052             onFingerprintAuthenticated(userId, isStrongBiometric);
1053         } finally {
1054             setFingerprintRunningState(BIOMETRIC_STATE_STOPPED);
1055         }
1056         Trace.endSection();
1057     }
1058 
handleFingerprintHelp(int msgId, String helpString)1059     private void handleFingerprintHelp(int msgId, String helpString) {
1060         Assert.isMainThread();
1061         for (int i = 0; i < mCallbacks.size(); i++) {
1062             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1063             if (cb != null) {
1064                 cb.onBiometricHelp(msgId, helpString, FINGERPRINT);
1065             }
1066         }
1067     }
1068 
1069     private final Runnable mRetryFingerprintAuthenticationAfterHwUnavailable = new Runnable() {
1070         @SuppressLint("MissingPermission")
1071         @Override
1072         public void run() {
1073             mLogger.logRetryAfterFpHwUnavailable(mHardwareFingerprintUnavailableRetryCount);
1074             if (!mFingerprintSensorProperties.isEmpty()) {
1075                 updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
1076             } else if (mHardwareFingerprintUnavailableRetryCount < HAL_ERROR_RETRY_MAX) {
1077                 mHardwareFingerprintUnavailableRetryCount++;
1078                 mHandler.postDelayed(mRetryFingerprintAuthenticationAfterHwUnavailable,
1079                         HAL_ERROR_RETRY_TIMEOUT);
1080             }
1081         }
1082     };
1083 
onFingerprintCancelNotReceived()1084     private void onFingerprintCancelNotReceived() {
1085         mLogger.e("Fp cancellation not received, transitioning to STOPPED");
1086         final boolean wasCancellingRestarting = mFingerprintRunningState
1087                 == BIOMETRIC_STATE_CANCELLING_RESTARTING;
1088         mFingerprintRunningState = BIOMETRIC_STATE_STOPPED;
1089         if (wasCancellingRestarting) {
1090             KeyguardUpdateMonitor.this.updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
1091         } else {
1092             KeyguardUpdateMonitor.this.updateFingerprintListeningState(BIOMETRIC_ACTION_STOP);
1093         }
1094     }
1095 
handleFingerprintError(int msgId, String errString)1096     private void handleFingerprintError(int msgId, String errString) {
1097         Assert.isMainThread();
1098         if (mHandler.hasCallbacks(mFpCancelNotReceived)) {
1099             mHandler.removeCallbacks(mFpCancelNotReceived);
1100         }
1101 
1102         // Error is always the end of authentication lifecycle.
1103         mFingerprintCancelSignal = null;
1104 
1105         if (msgId == FingerprintManager.FINGERPRINT_ERROR_CANCELED
1106                 && mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
1107             setFingerprintRunningState(BIOMETRIC_STATE_STOPPED);
1108             updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
1109         } else {
1110             setFingerprintRunningState(BIOMETRIC_STATE_STOPPED);
1111         }
1112 
1113         if (msgId == FingerprintManager.FINGERPRINT_ERROR_HW_UNAVAILABLE) {
1114             mLogger.logRetryAfterFpErrorWithDelay(msgId, errString, HAL_ERROR_RETRY_TIMEOUT);
1115             mHandler.postDelayed(mRetryFingerprintAuthenticationAfterHwUnavailable,
1116                     HAL_ERROR_RETRY_TIMEOUT);
1117         }
1118 
1119         if (msgId == FingerprintManager.BIOMETRIC_ERROR_POWER_PRESSED) {
1120             mLogger.logRetryAfterFpErrorWithDelay(msgId, errString, HAL_POWER_PRESS_TIMEOUT);
1121             mHandler.postDelayed(() -> {
1122                 mLogger.d("Retrying fingerprint listening after power pressed error.");
1123                 updateFingerprintListeningState(BIOMETRIC_ACTION_START);
1124             }, HAL_POWER_PRESS_TIMEOUT);
1125         }
1126 
1127         boolean lockedOutStateChanged = false;
1128         if (msgId == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT_PERMANENT) {
1129             lockedOutStateChanged = !mFingerprintLockedOutPermanent;
1130             mFingerprintLockedOutPermanent = true;
1131             mLogger.d("Fingerprint permanently locked out - requiring stronger auth");
1132             mLockPatternUtils.requireStrongAuth(
1133                     STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, getCurrentUser());
1134         }
1135 
1136         if (msgId == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT
1137                 || msgId == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT_PERMANENT) {
1138             lockedOutStateChanged |= !mFingerprintLockedOut;
1139             mFingerprintLockedOut = true;
1140             mLogger.d("Fingerprint temporarily locked out - requiring stronger auth");
1141             if (isUdfpsEnrolled()) {
1142                 updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
1143             }
1144             stopListeningForFace(FACE_AUTH_STOPPED_FP_LOCKED_OUT);
1145         }
1146 
1147         mLogger.logFingerprintError(msgId, errString);
1148         for (int i = 0; i < mCallbacks.size(); i++) {
1149             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1150             if (cb != null) {
1151                 cb.onBiometricError(msgId, errString, FINGERPRINT);
1152             }
1153         }
1154 
1155         if (lockedOutStateChanged) {
1156             notifyLockedOutStateChanged(FINGERPRINT);
1157         }
1158     }
1159 
handleFingerprintLockoutReset(@ockoutMode int mode)1160     private void handleFingerprintLockoutReset(@LockoutMode int mode) {
1161         mLogger.logFingerprintLockoutReset(mode);
1162         final boolean wasLockout = mFingerprintLockedOut;
1163         final boolean wasLockoutPermanent = mFingerprintLockedOutPermanent;
1164         mFingerprintLockedOut = (mode == BIOMETRIC_LOCKOUT_TIMED)
1165                 || mode == BIOMETRIC_LOCKOUT_PERMANENT;
1166         mFingerprintLockedOutPermanent = (mode == BIOMETRIC_LOCKOUT_PERMANENT);
1167         final boolean changed = (mFingerprintLockedOut != wasLockout)
1168                 || (mFingerprintLockedOutPermanent != wasLockoutPermanent);
1169 
1170         if (isUdfpsEnrolled()) {
1171             // TODO(b/194825098): update the reset signal(s)
1172             // A successful unlock will trigger a lockout reset, but there is no guarantee
1173             // that the events will arrive in a particular order. Add a delay here in case
1174             // an unlock is in progress. In this is a normal unlock the extra delay won't
1175             // be noticeable.
1176             mHandler.postDelayed(
1177                     () -> updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE),
1178                     getBiometricLockoutDelay());
1179         } else {
1180             boolean temporaryLockoutReset = wasLockout && !mFingerprintLockedOut;
1181             if (temporaryLockoutReset) {
1182                 mLogger.d("temporaryLockoutReset - stopListeningForFingerprint() to stop"
1183                         + " detectFingerprint");
1184                 stopListeningForFingerprint();
1185             }
1186             updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
1187         }
1188 
1189         if (changed) {
1190             notifyLockedOutStateChanged(FINGERPRINT);
1191         }
1192     }
1193 
setFingerprintRunningState(int fingerprintRunningState)1194     private void setFingerprintRunningState(int fingerprintRunningState) {
1195         boolean wasRunning = mFingerprintRunningState == BIOMETRIC_STATE_RUNNING;
1196         boolean isRunning = fingerprintRunningState == BIOMETRIC_STATE_RUNNING;
1197         mFingerprintRunningState = fingerprintRunningState;
1198         mLogger.logFingerprintRunningState(mFingerprintRunningState);
1199         // Clients of KeyguardUpdateMonitor don't care about the internal state about the
1200         // asynchronousness of the cancel cycle. So only notify them if the actually running state
1201         // has changed.
1202         if (wasRunning != isRunning) {
1203             notifyFingerprintRunningStateChanged();
1204         }
1205     }
1206 
notifyFingerprintRunningStateChanged()1207     private void notifyFingerprintRunningStateChanged() {
1208         Assert.isMainThread();
1209         for (int i = 0; i < mCallbacks.size(); i++) {
1210             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1211             if (cb != null) {
1212                 cb.onBiometricRunningStateChanged(isFingerprintDetectionRunning(),
1213                         FINGERPRINT);
1214             }
1215         }
1216     }
1217 
1218     @VisibleForTesting
onFaceAuthenticated(int userId, boolean isStrongBiometric)1219     public void onFaceAuthenticated(int userId, boolean isStrongBiometric) {
1220         Trace.beginSection("KeyGuardUpdateMonitor#onFaceAuthenticated");
1221         Assert.isMainThread();
1222         mUserFaceAuthenticated.put(userId,
1223                 new BiometricAuthenticated(true, isStrongBiometric));
1224         // Update/refresh trust state only if user can skip bouncer
1225         if (getUserCanSkipBouncer(userId)) {
1226             mTrustManager.unlockedByBiometricForUser(userId, FACE);
1227         }
1228         // Don't send cancel if authentication succeeds
1229         mFaceCancelSignal = null;
1230         updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
1231                 FACE_AUTH_UPDATED_ON_FACE_AUTHENTICATED);
1232         mLogger.d("onFaceAuthenticated");
1233         for (int i = 0; i < mCallbacks.size(); i++) {
1234             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1235             if (cb != null) {
1236                 cb.onBiometricAuthenticated(userId,
1237                         FACE,
1238                         isStrongBiometric);
1239             }
1240         }
1241 
1242         // Only authenticate face once when assistant is visible
1243         mAssistantVisible = false;
1244 
1245         // Report unlock with strong or non-strong biometric
1246         reportSuccessfulBiometricUnlock(isStrongBiometric, userId);
1247 
1248         Trace.endSection();
1249     }
1250 
1251     /**
1252      * @deprecated This is being migrated to use modern architecture, this method is visible purely
1253      * for bridging the gap while the migration is active.
1254      */
handleFaceAuthFailed()1255     private void handleFaceAuthFailed() {
1256         Assert.isMainThread();
1257         String reason =
1258                 mKeyguardBypassController.canBypass() ? "bypass"
1259                         : mAlternateBouncerShowing ? "alternateBouncer"
1260                                 : mPrimaryBouncerFullyShown ? "bouncer"
1261                                         : "udfpsFpDown";
1262         requestActiveUnlock(
1263                 ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL,
1264                 "faceFailure-" + reason);
1265 
1266         mLogger.d("onFaceAuthFailed");
1267         mFaceCancelSignal = null;
1268         setFaceRunningState(BIOMETRIC_STATE_STOPPED);
1269         for (int i = 0; i < mCallbacks.size(); i++) {
1270             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1271             if (cb != null) {
1272                 cb.onBiometricAuthFailed(FACE);
1273             }
1274         }
1275         handleFaceHelp(BIOMETRIC_HELP_FACE_NOT_RECOGNIZED,
1276                 mContext.getString(R.string.kg_face_not_recognized));
1277     }
1278 
1279     /**
1280      * @deprecated This is being migrated to use modern architecture, this method is visible purely
1281      * for bridging the gap while the migration is active.
1282      */
handleFaceAcquired(int acquireInfo)1283     private void handleFaceAcquired(int acquireInfo) {
1284         Assert.isMainThread();
1285         for (int i = 0; i < mCallbacks.size(); i++) {
1286             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1287             if (cb != null) {
1288                 cb.onBiometricAcquired(FACE, acquireInfo);
1289             }
1290         }
1291 
1292         if (mActiveUnlockConfig.shouldRequestActiveUnlockOnFaceAcquireInfo(
1293                 acquireInfo)) {
1294             requestActiveUnlock(
1295                     ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL,
1296                     "faceAcquireInfo-" + acquireInfo);
1297         }
1298     }
1299 
1300     /**
1301      * @deprecated This is being migrated to use modern architecture, this method is visible purely
1302      * for bridging the gap while the migration is active.
1303      */
handleFaceAuthenticated(int authUserId, boolean isStrongBiometric)1304     private void handleFaceAuthenticated(int authUserId, boolean isStrongBiometric) {
1305         Trace.beginSection("KeyGuardUpdateMonitor#handlerFaceAuthenticated");
1306         try {
1307             if (mGoingToSleep) {
1308                 mLogger.d("Aborted successful auth because device is going to sleep.");
1309                 return;
1310             }
1311             final int userId = mUserTracker.getUserId();
1312             if (userId != authUserId) {
1313                 mLogger.logFaceAuthForWrongUser(authUserId);
1314                 return;
1315             }
1316             if (!isFaceAuthInteractorEnabled() && isFaceDisabled(userId)) {
1317                 mLogger.logFaceAuthDisabledForUser(userId);
1318                 return;
1319             }
1320             mLogger.logFaceAuthSuccess(userId);
1321             onFaceAuthenticated(userId, isStrongBiometric);
1322         } finally {
1323             setFaceRunningState(BIOMETRIC_STATE_STOPPED);
1324         }
1325         Trace.endSection();
1326     }
1327 
1328     /**
1329      * @deprecated This is being migrated to use modern architecture, this method is visible purely
1330      * for bridging the gap while the migration is active.
1331      */
handleFaceHelp(int msgId, String helpString)1332     private void handleFaceHelp(int msgId, String helpString) {
1333         if (mFaceAcquiredInfoIgnoreList.contains(msgId)) {
1334             return;
1335         }
1336         Assert.isMainThread();
1337         for (int i = 0; i < mCallbacks.size(); i++) {
1338             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1339             if (cb != null) {
1340                 cb.onBiometricHelp(msgId, helpString, FACE);
1341             }
1342         }
1343     }
1344 
1345     /**
1346      * @deprecated This is being migrated to use modern architecture, this method is visible purely
1347      * for bridging the gap while the migration is active.
1348      */
handleFaceError(int msgId, final String originalErrMsg)1349     private void handleFaceError(int msgId, final String originalErrMsg) {
1350         Assert.isMainThread();
1351         String errString = originalErrMsg;
1352         mLogger.logFaceAuthError(msgId, originalErrMsg);
1353         if (mHandler.hasCallbacks(mFaceCancelNotReceived)) {
1354             mHandler.removeCallbacks(mFaceCancelNotReceived);
1355         }
1356 
1357         // Error is always the end of authentication lifecycle
1358         mFaceCancelSignal = null;
1359         boolean cameraPrivacyEnabled = mSensorPrivacyManager.isSensorPrivacyEnabled(
1360                 SensorPrivacyManager.TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager.Sensors.CAMERA);
1361 
1362         if (msgId == FaceManager.FACE_ERROR_CANCELED
1363                 && mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
1364             setFaceRunningState(BIOMETRIC_STATE_STOPPED);
1365             updateFaceListeningState(BIOMETRIC_ACTION_UPDATE,
1366                     FACE_AUTH_TRIGGERED_DURING_CANCELLATION);
1367         } else {
1368             setFaceRunningState(BIOMETRIC_STATE_STOPPED);
1369         }
1370 
1371         final boolean isHwUnavailable = msgId == FaceManager.FACE_ERROR_HW_UNAVAILABLE;
1372 
1373         if (isHwUnavailable
1374                 || msgId == FaceManager.FACE_ERROR_UNABLE_TO_PROCESS) {
1375             if (mHardwareFaceUnavailableRetryCount < HAL_ERROR_RETRY_MAX) {
1376                 mHardwareFaceUnavailableRetryCount++;
1377                 mHandler.removeCallbacks(mRetryFaceAuthentication);
1378                 mHandler.postDelayed(mRetryFaceAuthentication, HAL_ERROR_RETRY_TIMEOUT);
1379             }
1380         }
1381 
1382         boolean lockedOutStateChanged = false;
1383         if (msgId == FaceManager.FACE_ERROR_LOCKOUT_PERMANENT) {
1384             lockedOutStateChanged = !mFaceLockedOutPermanent;
1385             mFaceLockedOutPermanent = true;
1386             if (isFaceClass3()) {
1387                 updateFingerprintListeningState(BIOMETRIC_ACTION_STOP);
1388             }
1389         }
1390 
1391         if (isHwUnavailable && cameraPrivacyEnabled) {
1392             errString = mContext.getString(R.string.kg_face_sensor_privacy_enabled);
1393         }
1394 
1395         for (int i = 0; i < mCallbacks.size(); i++) {
1396             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1397             if (cb != null) {
1398                 cb.onBiometricError(msgId, errString,
1399                         FACE);
1400             }
1401         }
1402 
1403         if (lockedOutStateChanged) {
1404             notifyLockedOutStateChanged(FACE);
1405         }
1406 
1407         if (mActiveUnlockConfig.shouldRequestActiveUnlockOnFaceError(msgId)) {
1408             requestActiveUnlock(
1409                     ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL,
1410                     "faceError-" + msgId);
1411         }
1412     }
1413 
1414     private final Runnable mRetryFaceAuthentication = new Runnable() {
1415         @Override
1416         public void run() {
1417             mLogger.logRetryingAfterFaceHwUnavailable(mHardwareFaceUnavailableRetryCount);
1418             updateFaceListeningState(BIOMETRIC_ACTION_UPDATE,
1419                     FACE_AUTH_TRIGGERED_RETRY_AFTER_HW_UNAVAILABLE);
1420         }
1421     };
1422 
onFaceCancelNotReceived()1423     private void onFaceCancelNotReceived() {
1424         mLogger.e("Face cancellation not received, transitioning to STOPPED");
1425         mFaceRunningState = BIOMETRIC_STATE_STOPPED;
1426         KeyguardUpdateMonitor.this.updateFaceListeningState(BIOMETRIC_ACTION_STOP,
1427                 FACE_AUTH_STOPPED_FACE_CANCEL_NOT_RECEIVED);
1428     }
1429 
handleFaceLockoutReset(@ockoutMode int mode)1430     private void handleFaceLockoutReset(@LockoutMode int mode) {
1431         mLogger.logFaceLockoutReset(mode);
1432         final boolean wasLockoutPermanent = mFaceLockedOutPermanent;
1433         mFaceLockedOutPermanent = (mode == BIOMETRIC_LOCKOUT_PERMANENT);
1434         final boolean changed = (mFaceLockedOutPermanent != wasLockoutPermanent);
1435 
1436         mHandler.postDelayed(() -> updateFaceListeningState(BIOMETRIC_ACTION_UPDATE,
1437                 FACE_AUTH_TRIGGERED_FACE_LOCKOUT_RESET), getBiometricLockoutDelay());
1438 
1439         if (changed) {
1440             notifyLockedOutStateChanged(FACE);
1441         }
1442     }
1443 
setFaceRunningState(int faceRunningState)1444     private void setFaceRunningState(int faceRunningState) {
1445         boolean wasRunning = mFaceRunningState == BIOMETRIC_STATE_RUNNING;
1446         boolean isRunning = faceRunningState == BIOMETRIC_STATE_RUNNING;
1447         mFaceRunningState = faceRunningState;
1448         mLogger.logFaceRunningState(mFaceRunningState);
1449         // Clients of KeyguardUpdateMonitor don't care about the internal state or about the
1450         // asynchronousness of the cancel cycle. So only notify them if the actually running state
1451         // has changed.
1452         if (wasRunning != isRunning) {
1453             notifyFaceRunningStateChanged();
1454         }
1455     }
1456 
notifyFaceRunningStateChanged()1457     private void notifyFaceRunningStateChanged() {
1458         Assert.isMainThread();
1459         for (int i = 0; i < mCallbacks.size(); i++) {
1460             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1461             if (cb != null) {
1462                 cb.onBiometricRunningStateChanged(isFaceDetectionRunning(),
1463                         FACE);
1464             }
1465         }
1466     }
1467 
isFingerprintDetectionRunning()1468     public boolean isFingerprintDetectionRunning() {
1469         return mFingerprintRunningState == BIOMETRIC_STATE_RUNNING;
1470     }
1471 
1472     /**
1473      * @deprecated This is being migrated to use modern architecture.
1474      */
1475     @Deprecated
isFaceDetectionRunning()1476     public boolean isFaceDetectionRunning() {
1477         if (isFaceAuthInteractorEnabled()) {
1478             return getFaceAuthInteractor().isRunning();
1479         }
1480         return mFaceRunningState == BIOMETRIC_STATE_RUNNING;
1481     }
1482 
isFaceAuthInteractorEnabled()1483     private boolean isFaceAuthInteractorEnabled() {
1484         return mFaceAuthInteractor != null && mFaceAuthInteractor.isEnabled();
1485     }
1486 
getFaceAuthInteractor()1487     private @Nullable KeyguardFaceAuthInteractor getFaceAuthInteractor() {
1488         return mFaceAuthInteractor;
1489     }
1490 
1491     /**
1492      * Set the face auth interactor that should be used for initiating face authentication.
1493      */
setFaceAuthInteractor(@ullable KeyguardFaceAuthInteractor faceAuthInteractor)1494     public void setFaceAuthInteractor(@Nullable KeyguardFaceAuthInteractor faceAuthInteractor) {
1495         mFaceAuthInteractor = faceAuthInteractor;
1496         mFaceAuthInteractor.registerListener(mFaceAuthenticationListener);
1497     }
1498 
1499     private FaceAuthenticationListener mFaceAuthenticationListener =
1500             new FaceAuthenticationListener() {
1501                 @Override
1502                 public void onAuthenticationStatusChanged(
1503                         @NonNull FaceAuthenticationStatus status
1504                 ) {
1505                     if (status instanceof AcquiredFaceAuthenticationStatus) {
1506                         handleFaceAcquired(
1507                                 ((AcquiredFaceAuthenticationStatus) status).getAcquiredInfo());
1508                     } else if (status instanceof ErrorFaceAuthenticationStatus) {
1509                         ErrorFaceAuthenticationStatus error =
1510                                 (ErrorFaceAuthenticationStatus) status;
1511                         handleFaceError(error.getMsgId(), error.getMsg());
1512                     } else if (status instanceof FailedFaceAuthenticationStatus) {
1513                         handleFaceAuthFailed();
1514                     } else if (status instanceof HelpFaceAuthenticationStatus) {
1515                         HelpFaceAuthenticationStatus helpMsg =
1516                                 (HelpFaceAuthenticationStatus) status;
1517                         handleFaceHelp(helpMsg.getMsgId(), helpMsg.getMsg());
1518                     } else if (status instanceof SuccessFaceAuthenticationStatus) {
1519                         FaceManager.AuthenticationResult result =
1520                                 ((SuccessFaceAuthenticationStatus) status).getSuccessResult();
1521                         handleFaceAuthenticated(result.getUserId(), result.isStrongBiometric());
1522                     }
1523                 }
1524 
1525                 @Override
1526                 public void onDetectionStatusChanged(@NonNull FaceDetectionStatus status) {
1527                     handleBiometricDetected(status.getUserId(), FACE, status.isStrongBiometric());
1528                 }
1529             };
1530 
isTrustDisabled()1531     private boolean isTrustDisabled() {
1532         // Don't allow trust agent if device is secured with a SIM PIN. This is here
1533         // mainly because there's no other way to prompt the user to enter their SIM PIN
1534         // once they get past the keyguard screen.
1535         return isSimPinSecure(); // Disabled by SIM PIN
1536     }
1537 
isFingerprintDisabled(int userId)1538     private boolean isFingerprintDisabled(int userId) {
1539         return (mDevicePolicyManager.getKeyguardDisabledFeatures(null, userId)
1540                         & DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT) != 0
1541                 || isSimPinSecure();
1542     }
1543 
1544     /**
1545      * @deprecated This method is not needed anymore with the new face auth system.
1546      */
1547     @Deprecated
isFaceDisabled(int userId)1548     private boolean isFaceDisabled(int userId) {
1549         // TODO(b/140035044)
1550         return whitelistIpcs(() ->
1551                 (mDevicePolicyManager.getKeyguardDisabledFeatures(null, userId)
1552                         & DevicePolicyManager.KEYGUARD_DISABLE_FACE) != 0
1553                 || isSimPinSecure());
1554     }
1555 
1556     /**
1557      * @return whether the current user has been authenticated with face. This may be true
1558      * on the lockscreen if the user doesn't have bypass enabled.
1559      *
1560      * @deprecated This is being migrated to use modern architecture.
1561      */
1562     @Deprecated
getIsFaceAuthenticated()1563     public boolean getIsFaceAuthenticated() {
1564         boolean faceAuthenticated = false;
1565         BiometricAuthenticated bioFaceAuthenticated = mUserFaceAuthenticated.get(getCurrentUser());
1566         if (bioFaceAuthenticated != null) {
1567             faceAuthenticated = bioFaceAuthenticated.mAuthenticated;
1568         }
1569         return faceAuthenticated;
1570     }
1571 
getUserCanSkipBouncer(int userId)1572     public boolean getUserCanSkipBouncer(int userId) {
1573         return getUserHasTrust(userId) || getUserUnlockedWithBiometric(userId);
1574     }
1575 
getUserHasTrust(int userId)1576     public boolean getUserHasTrust(int userId) {
1577         return !isTrustDisabled() && mUserHasTrust.get(userId)
1578                 && isUnlockingWithTrustAgentAllowed();
1579     }
1580 
1581     /**
1582      * Returns whether the user is unlocked with biometrics.
1583      */
getUserUnlockedWithBiometric(int userId)1584     public boolean getUserUnlockedWithBiometric(int userId) {
1585         BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(userId);
1586         boolean fingerprintAllowed = fingerprint != null && fingerprint.mAuthenticated
1587                 && isUnlockingWithBiometricAllowed(fingerprint.mIsStrongBiometric);
1588         return fingerprintAllowed || getUserUnlockedWithFace(userId);
1589     }
1590 
1591 
1592     /**
1593      * Returns whether the user is unlocked with face.
1594      */
getUserUnlockedWithFace(int userId)1595     public boolean getUserUnlockedWithFace(int userId) {
1596         BiometricAuthenticated face = mUserFaceAuthenticated.get(userId);
1597         return face != null && face.mAuthenticated
1598                 && isUnlockingWithBiometricAllowed(face.mIsStrongBiometric);
1599     }
1600 
1601     /**
1602      * Returns whether the user is unlocked with a biometric that is currently bypassing
1603      * the lock screen.
1604      */
getUserUnlockedWithBiometricAndIsBypassing(int userId)1605     public boolean getUserUnlockedWithBiometricAndIsBypassing(int userId) {
1606         BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(userId);
1607         BiometricAuthenticated face = mUserFaceAuthenticated.get(userId);
1608         // fingerprint always bypasses
1609         boolean fingerprintAllowed = fingerprint != null && fingerprint.mAuthenticated
1610                 && isUnlockingWithBiometricAllowed(fingerprint.mIsStrongBiometric);
1611         boolean faceAllowed = face != null && face.mAuthenticated
1612                 && isUnlockingWithBiometricAllowed(face.mIsStrongBiometric);
1613         return fingerprintAllowed || faceAllowed && mKeyguardBypassController.canBypass();
1614     }
1615 
getUserTrustIsManaged(int userId)1616     public boolean getUserTrustIsManaged(int userId) {
1617         return mUserTrustIsManaged.get(userId) && !isTrustDisabled();
1618     }
1619 
updateSecondaryLockscreenRequirement(int userId)1620     private void updateSecondaryLockscreenRequirement(int userId) {
1621         Intent oldIntent = mSecondaryLockscreenRequirement.get(userId);
1622         boolean enabled = mDevicePolicyManager.isSecondaryLockscreenEnabled(UserHandle.of(userId));
1623         boolean changed = false;
1624 
1625         if (enabled && (oldIntent == null)) {
1626             ComponentName supervisorComponent =
1627                     mDevicePolicyManager.getProfileOwnerOrDeviceOwnerSupervisionComponent(
1628                             UserHandle.of(userId));
1629             if (supervisorComponent == null) {
1630                 mLogger.logMissingSupervisorAppError(userId);
1631             } else {
1632                 Intent intent =
1633                         new Intent(DevicePolicyManager.ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE)
1634                                 .setPackage(supervisorComponent.getPackageName());
1635                 ResolveInfo resolveInfo = mPackageManager.resolveService(intent, 0);
1636                 if (resolveInfo != null && resolveInfo.serviceInfo != null) {
1637                     Intent launchIntent =
1638                             new Intent().setComponent(resolveInfo.serviceInfo.getComponentName());
1639                     mSecondaryLockscreenRequirement.put(userId, launchIntent);
1640                     changed = true;
1641                 }
1642             }
1643         } else if (!enabled && (oldIntent != null)) {
1644             mSecondaryLockscreenRequirement.put(userId, null);
1645             changed = true;
1646         }
1647         if (changed) {
1648             for (int i = 0; i < mCallbacks.size(); i++) {
1649                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1650                 if (cb != null) {
1651                     cb.onSecondaryLockscreenRequirementChanged(userId);
1652                 }
1653             }
1654         }
1655     }
1656 
1657     /**
1658      * Returns an Intent by which to bind to a service that will provide additional security screen
1659      * content that must be shown prior to dismissing the keyguard for this user.
1660      */
getSecondaryLockscreenRequirement(int userId)1661     public Intent getSecondaryLockscreenRequirement(int userId) {
1662         return mSecondaryLockscreenRequirement.get(userId);
1663     }
1664 
1665     /**
1666      * Cached version of {@link TrustManager#isTrustUsuallyManaged(int)}.
1667      */
isTrustUsuallyManaged(int userId)1668     public boolean isTrustUsuallyManaged(int userId) {
1669         Assert.isMainThread();
1670         return mUserTrustIsUsuallyManaged.get(userId);
1671     }
1672 
isUnlockingWithTrustAgentAllowed()1673     private boolean isUnlockingWithTrustAgentAllowed() {
1674         return isUnlockingWithBiometricAllowed(true);
1675     }
1676 
isUnlockingWithBiometricAllowed(boolean isStrongBiometric)1677     public boolean isUnlockingWithBiometricAllowed(boolean isStrongBiometric) {
1678         // StrongAuthTracker#isUnlockingWithBiometricAllowed includes
1679         // STRONG_AUTH_REQUIRED_AFTER_LOCKOUT which is the same as mFingerprintLockedOutPermanent;
1680         // however the strong auth tracker does not include the temporary lockout
1681         // mFingerprintLockedOut.
1682         // Class 3 biometric lockout will lockout ALL biometrics
1683         return mStrongAuthTracker.isUnlockingWithBiometricAllowed(isStrongBiometric)
1684                 && (!isFingerprintClass3() || !isFingerprintLockedOut())
1685                 && (!isFaceClass3() || !mFaceLockedOutPermanent);
1686     }
1687 
1688     /**
1689      * Whether fingerprint is allowed ot be used for unlocking based on the strongAuthTracker
1690      * and temporary lockout state (tracked by FingerprintManager via error codes).
1691      */
isUnlockingWithFingerprintAllowed()1692     public boolean isUnlockingWithFingerprintAllowed() {
1693         return isUnlockingWithBiometricAllowed(FINGERPRINT);
1694     }
1695 
1696     /**
1697      * Whether the given biometric is allowed based on strongAuth & lockout states.
1698      */
isUnlockingWithBiometricAllowed( @onNull BiometricSourceType biometricSourceType)1699     public boolean isUnlockingWithBiometricAllowed(
1700             @NonNull BiometricSourceType biometricSourceType) {
1701         switch (biometricSourceType) {
1702             case FINGERPRINT:
1703                 return isUnlockingWithBiometricAllowed(isFingerprintClass3());
1704             case FACE:
1705                 return isUnlockingWithBiometricAllowed(isFaceClass3());
1706             default:
1707                 return false;
1708         }
1709     }
1710 
1711     /**
1712      * Whether the user locked down the device. This doesn't include device policy manager lockdown.
1713      */
isUserInLockdown(int userId)1714     public boolean isUserInLockdown(int userId) {
1715         return containsFlag(mStrongAuthTracker.getStrongAuthForUser(userId),
1716                 STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
1717     }
1718 
1719     /**
1720      * Returns true if primary authentication is required for the given user due to lockdown
1721      * or encryption after reboot.
1722      */
isEncryptedOrLockdown(int userId)1723     public boolean isEncryptedOrLockdown(int userId) {
1724         final int strongAuth = mStrongAuthTracker.getStrongAuthForUser(userId);
1725         final boolean isLockDown =
1726                 containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW)
1727                         || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
1728         final boolean isEncrypted = containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_BOOT);
1729 
1730         return isEncrypted || isLockDown;
1731     }
1732 
containsFlag(int haystack, int needle)1733     private boolean containsFlag(int haystack, int needle) {
1734         return (haystack & needle) != 0;
1735     }
1736 
needsSlowUnlockTransition()1737     public boolean needsSlowUnlockTransition() {
1738         return mNeedsSlowUnlockTransition;
1739     }
1740 
getStrongAuthTracker()1741     public StrongAuthTracker getStrongAuthTracker() {
1742         return mStrongAuthTracker;
1743     }
1744 
1745     @VisibleForTesting
notifyStrongAuthAllowedChanged(int userId)1746     void notifyStrongAuthAllowedChanged(int userId) {
1747         Assert.isMainThread();
1748         for (int i = 0; i < mCallbacks.size(); i++) {
1749             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1750             if (cb != null) {
1751                 cb.onStrongAuthStateChanged(userId);
1752             }
1753         }
1754         if (userId == getCurrentUser()) {
1755             FACE_AUTH_UPDATED_STRONG_AUTH_CHANGED.setExtraInfo(
1756                     mStrongAuthTracker.getStrongAuthForUser(getCurrentUser()));
1757 
1758             // Strong auth is only reset when primary auth is used to enter the device,
1759             // so we only check whether to stop biometric listening states here
1760             updateBiometricListeningState(
1761                     BIOMETRIC_ACTION_STOP, FACE_AUTH_UPDATED_STRONG_AUTH_CHANGED);
1762         }
1763     }
1764 
notifyLockedOutStateChanged(BiometricSourceType type)1765     private void notifyLockedOutStateChanged(BiometricSourceType type) {
1766         Assert.isMainThread();
1767         for (int i = 0; i < mCallbacks.size(); i++) {
1768             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1769             if (cb != null) {
1770                 cb.onLockedOutStateChanged(type);
1771             }
1772         }
1773     }
1774     @VisibleForTesting
notifyNonStrongBiometricAllowedChanged(int userId)1775     void notifyNonStrongBiometricAllowedChanged(int userId) {
1776         Assert.isMainThread();
1777         for (int i = 0; i < mCallbacks.size(); i++) {
1778             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1779             if (cb != null) {
1780                 cb.onNonStrongBiometricAllowedChanged(userId);
1781             }
1782         }
1783         if (userId == getCurrentUser()) {
1784             FACE_AUTH_NON_STRONG_BIOMETRIC_ALLOWED_CHANGED.setExtraInfo(
1785                     mStrongAuthTracker.isNonStrongBiometricAllowedAfterIdleTimeout(
1786                             getCurrentUser()) ? -1 : 1);
1787 
1788             // This is only reset when primary auth is used to enter the device, so we only check
1789             // whether to stop biometric listening states here
1790             updateBiometricListeningState(BIOMETRIC_ACTION_STOP,
1791                     FACE_AUTH_NON_STRONG_BIOMETRIC_ALLOWED_CHANGED);
1792         }
1793     }
1794 
dispatchErrorMessage(CharSequence message)1795     private void dispatchErrorMessage(CharSequence message) {
1796         Assert.isMainThread();
1797         for (int i = 0; i < mCallbacks.size(); i++) {
1798             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1799             if (cb != null) {
1800                 cb.onTrustAgentErrorMessage(message);
1801             }
1802         }
1803 
1804     }
1805 
1806     @VisibleForTesting
setAssistantVisible(boolean assistantVisible)1807     void setAssistantVisible(boolean assistantVisible) {
1808         mAssistantVisible = assistantVisible;
1809         mLogger.logAssistantVisible(mAssistantVisible);
1810         if (isFaceAuthInteractorEnabled()) {
1811             mFaceAuthInteractor.onAssistantTriggeredOnLockScreen();
1812         }
1813         updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
1814                 FACE_AUTH_UPDATED_ASSISTANT_VISIBILITY_CHANGED);
1815         if (mAssistantVisible) {
1816             requestActiveUnlock(
1817                     ActiveUnlockConfig.ActiveUnlockRequestOrigin.ASSISTANT,
1818                     "assistant",
1819                     /* dismissKeyguard */ true);
1820         }
1821     }
1822 
1823     @VisibleForTesting
1824     protected final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1825 
1826         @Override
1827         public void onReceive(Context context, Intent intent) {
1828             final String action = intent.getAction();
1829             mLogger.logBroadcastReceived(action);
1830 
1831             if (Intent.ACTION_TIME_TICK.equals(action)
1832                     || Intent.ACTION_TIME_CHANGED.equals(action)) {
1833                 mHandler.sendEmptyMessage(MSG_TIME_UPDATE);
1834             } else if (Intent.ACTION_TIMEZONE_CHANGED.equals(action)) {
1835                 final Message msg = mHandler.obtainMessage(
1836                         MSG_TIMEZONE_UPDATE, intent.getStringExtra(Intent.EXTRA_TIMEZONE));
1837                 mHandler.sendMessage(msg);
1838             } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
1839                 final Message msg = mHandler.obtainMessage(
1840                         MSG_BATTERY_UPDATE, new BatteryStatus(intent, mIncompatibleCharger));
1841                 mHandler.sendMessage(msg);
1842             } else if (UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED.equals(action)) {
1843                 mIncompatibleCharger = Utils.containsIncompatibleChargers(context, TAG);
1844                 BatteryStatus batteryStatus = BatteryStatus.create(context, mIncompatibleCharger);
1845                 if (batteryStatus != null) {
1846                     mHandler.sendMessage(
1847                             mHandler.obtainMessage(MSG_BATTERY_UPDATE, batteryStatus));
1848                 }
1849             } else if (Intent.ACTION_SIM_STATE_CHANGED.equals(action)) {
1850                 SimData args = SimData.fromIntent(intent);
1851                 // ACTION_SIM_STATE_CHANGED is rebroadcast after unlocking the device to
1852                 // keep compatibility with apps that aren't direct boot aware.
1853                 // SysUI should just ignore this broadcast because it was already received
1854                 // and processed previously.
1855                 if (intent.getBooleanExtra(Intent.EXTRA_REBROADCAST_ON_UNLOCK, false)) {
1856                     // Guarantee mTelephonyCapable state after SysUI crash and restart
1857                     if (args.simState == TelephonyManager.SIM_STATE_ABSENT) {
1858                         mHandler.obtainMessage(MSG_TELEPHONY_CAPABLE, true).sendToTarget();
1859                     }
1860                     return;
1861                 }
1862                 mLogger.logSimStateFromIntent(action,
1863                         intent.getStringExtra(Intent.EXTRA_SIM_STATE),
1864                         args.slotId,
1865                         args.subId);
1866                 mHandler.obtainMessage(MSG_SIM_STATE_CHANGE, args.subId, args.slotId, args.simState)
1867                         .sendToTarget();
1868             } else if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(action)) {
1869                 String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
1870                 mHandler.sendMessage(mHandler.obtainMessage(MSG_PHONE_STATE_CHANGED, state));
1871             } else if (TelephonyManager.ACTION_SERVICE_PROVIDERS_UPDATED.equals(action)) {
1872                 mHandler.obtainMessage(MSG_SERVICE_PROVIDERS_UPDATED, intent).sendToTarget();
1873             } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
1874                 mHandler.sendEmptyMessage(MSG_AIRPLANE_MODE_CHANGED);
1875             } else if (Intent.ACTION_SERVICE_STATE.equals(action)) {
1876                 ServiceState serviceState = ServiceState.newFromBundle(intent.getExtras());
1877                 int subId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX,
1878                         SubscriptionManager.INVALID_SUBSCRIPTION_ID);
1879                 mLogger.logServiceStateIntent(action, serviceState, subId);
1880                 mHandler.sendMessage(
1881                         mHandler.obtainMessage(MSG_SERVICE_STATE_CHANGE, subId, 0, serviceState));
1882             } else if (TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED.equals(action)) {
1883                 mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED);
1884             } else if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals(
1885                     action)) {
1886                 mHandler.sendEmptyMessage(MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1887             }
1888         }
1889     };
1890 
1891     @VisibleForTesting
1892     protected final BroadcastReceiver mBroadcastAllReceiver = new BroadcastReceiver() {
1893 
1894         @Override
1895         public void onReceive(Context context, Intent intent) {
1896             final String action = intent.getAction();
1897             if (AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED.equals(action)) {
1898                 mHandler.sendEmptyMessage(MSG_TIME_UPDATE);
1899             } else if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1900                     .equals(action)) {
1901                 mHandler.sendMessage(mHandler.obtainMessage(MSG_DPM_STATE_CHANGED,
1902                         getSendingUserId(), 0));
1903             } else if (ACTION_USER_UNLOCKED.equals(action)) {
1904                 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_UNLOCKED,
1905                         getSendingUserId(), 0));
1906             } else if (ACTION_USER_STOPPED.equals(action)) {
1907                 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_STOPPED,
1908                         intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1), 0));
1909             } else if (ACTION_USER_REMOVED.equals(action)) {
1910                 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_REMOVED,
1911                         intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1), 0));
1912             } else if (NfcAdapter.ACTION_REQUIRE_UNLOCK_FOR_NFC.equals(action)) {
1913                 mHandler.sendEmptyMessage(MSG_REQUIRE_NFC_UNLOCK);
1914             }
1915         }
1916     };
1917 
1918     private final FingerprintManager.LockoutResetCallback mFingerprintLockoutResetCallback
1919             = new FingerprintManager.LockoutResetCallback() {
1920         @Override
1921         public void onLockoutReset(int sensorId) {
1922             handleFingerprintLockoutReset(BIOMETRIC_LOCKOUT_NONE);
1923         }
1924     };
1925 
1926     private final FaceManager.LockoutResetCallback mFaceLockoutResetCallback
1927             = new FaceManager.LockoutResetCallback() {
1928         @Override
1929         public void onLockoutReset(int sensorId) {
1930             handleFaceLockoutReset(BIOMETRIC_LOCKOUT_NONE);
1931         }
1932     };
1933 
1934     /**
1935      * Propagates a pointer down event to keyguard.
1936      */
onUdfpsPointerDown(int sensorId)1937     public void onUdfpsPointerDown(int sensorId) {
1938         mFingerprintAuthenticationCallback.onUdfpsPointerDown(sensorId);
1939     }
1940 
1941     /**
1942      * Propagates a pointer up event to keyguard.
1943      */
onUdfpsPointerUp(int sensorId)1944     public void onUdfpsPointerUp(int sensorId) {
1945         mFingerprintAuthenticationCallback.onUdfpsPointerUp(sensorId);
1946     }
1947 
1948     @VisibleForTesting
1949     final FingerprintManager.AuthenticationCallback mFingerprintAuthenticationCallback
1950             = new AuthenticationCallback() {
1951 
1952                 @Override
1953                 public void onAuthenticationFailed() {
1954                     requestActiveUnlockDismissKeyguard(
1955                             ActiveUnlockConfig.ActiveUnlockRequestOrigin.BIOMETRIC_FAIL,
1956                             "fingerprintFailure");
1957                     handleFingerprintAuthFailed();
1958                 }
1959 
1960                 @Override
1961                 public void onAuthenticationSucceeded(AuthenticationResult result) {
1962                     Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationSucceeded");
1963                     handleFingerprintAuthenticated(result.getUserId(), result.isStrongBiometric());
1964                     Trace.endSection();
1965                 }
1966 
1967                 @Override
1968                 public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
1969                     Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationHelp");
1970                     handleFingerprintHelp(helpMsgId, helpString.toString());
1971                     Trace.endSection();
1972                 }
1973 
1974                 @Override
1975                 public void onAuthenticationError(int errMsgId, CharSequence errString) {
1976                     Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationError");
1977                     handleFingerprintError(errMsgId, errString.toString());
1978                     Trace.endSection();
1979                 }
1980 
1981                 @Override
1982                 public void onAuthenticationAcquired(int acquireInfo) {
1983                     Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationAcquired");
1984                     handleFingerprintAcquired(acquireInfo);
1985                     Trace.endSection();
1986                 }
1987 
1988                 /**
1989                  * Note, this is currently called from UdfpsController.
1990                  */
1991                 @Override
1992                 public void onUdfpsPointerDown(int sensorId) {
1993                     mLogger.logUdfpsPointerDown(sensorId);
1994                     requestFaceAuth(FaceAuthApiRequestReason.UDFPS_POINTER_DOWN);
1995                 }
1996 
1997                 /**
1998                  * Note, this is currently called from UdfpsController.
1999                  */
2000                 @Override
2001                 public void onUdfpsPointerUp(int sensorId) {
2002                     mLogger.logUdfpsPointerUp(sensorId);
2003                 }
2004             };
2005 
2006     private final FingerprintManager.FingerprintDetectionCallback mFingerprintDetectionCallback =
2007             (sensorId, userId, isStrongBiometric) -> {
2008                 // Trigger the fingerprint detected path so the bouncer can be shown
2009                 handleBiometricDetected(userId, FINGERPRINT, isStrongBiometric);
2010             };
2011 
2012     private final FaceManager.FaceDetectionCallback mFaceDetectionCallback
2013             = (sensorId, userId, isStrongBiometric) -> {
2014                 // Trigger the face detected path so the bouncer can be shown
2015                 handleBiometricDetected(userId, FACE, isStrongBiometric);
2016             };
2017 
2018     @VisibleForTesting
2019     final FaceManager.AuthenticationCallback mFaceAuthenticationCallback
2020             = new FaceManager.AuthenticationCallback() {
2021 
2022                 @Override
2023                 public void onAuthenticationFailed() {
2024                     handleFaceAuthFailed();
2025                 }
2026 
2027                 @Override
2028                 public void onAuthenticationSucceeded(FaceManager.AuthenticationResult result) {
2029                     handleFaceAuthenticated(result.getUserId(), result.isStrongBiometric());
2030                 }
2031 
2032                 @Override
2033                 public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
2034                     handleFaceHelp(helpMsgId, helpString.toString());
2035                 }
2036 
2037                 @Override
2038                 public void onAuthenticationError(int errMsgId, CharSequence errString) {
2039                     handleFaceError(errMsgId, errString.toString());
2040                 }
2041 
2042                 @Override
2043                 public void onAuthenticationAcquired(int acquireInfo) {
2044                     handleFaceAcquired(acquireInfo);
2045                 }
2046     };
2047 
2048     @VisibleForTesting
2049     final DevicePostureController.Callback mPostureCallback =
2050             new DevicePostureController.Callback() {
2051                 @Override
2052                 public void onPostureChanged(@DevicePostureInt int posture) {
2053                     boolean currentPostureAllowsFaceAuth = doesPostureAllowFaceAuth(mPostureState);
2054                     boolean newPostureAllowsFaceAuth = doesPostureAllowFaceAuth(posture);
2055                     mPostureState = posture;
2056                     if (currentPostureAllowsFaceAuth && !newPostureAllowsFaceAuth) {
2057                         mLogger.d("New posture does not allow face auth, stopping it");
2058                         updateFaceListeningState(BIOMETRIC_ACTION_STOP,
2059                                 FACE_AUTH_UPDATED_POSTURE_CHANGED);
2060                     }
2061                     if (mPostureState == DEVICE_POSTURE_OPENED) {
2062                         mLogger.d("Posture changed to open - attempting to request active unlock");
2063                         requestActiveUnlockFromWakeReason(PowerManager.WAKE_REASON_UNFOLD_DEVICE,
2064                                 false);
2065                     }
2066                 }
2067             };
2068 
2069     @VisibleForTesting
2070     CancellationSignal mFingerprintCancelSignal;
2071     @VisibleForTesting
2072     CancellationSignal mFaceCancelSignal;
2073     private List<FingerprintSensorPropertiesInternal> mFingerprintSensorProperties =
2074             Collections.emptyList();
2075     private List<FaceSensorPropertiesInternal> mFaceSensorProperties = Collections.emptyList();
2076     private boolean mFingerprintLockedOut;
2077     private boolean mFingerprintLockedOutPermanent;
2078     private boolean mFaceLockedOutPermanent;
2079     private final HashMap<Integer, Boolean> mIsUnlockWithFingerprintPossible = new HashMap<>();
2080 
2081     /**
2082      * When we receive a {@link android.content.Intent#ACTION_SIM_STATE_CHANGED} broadcast,
2083      * and then pass a result via our handler to {@link KeyguardUpdateMonitor#handleSimStateChange},
2084      * we need a single object to pass to the handler.  This class helps decode
2085      * the intent and provide a {@link SimData} result.
2086      *
2087      * Below is the Sim state mapping matrixs:
2088      * +---+-----------------------------------------------------+----------------------------+
2089      * |   |Telephony FWK broadcast with action                  |SystemUI mapping SIM state  |
2090      * |   |android.content.Intent#ACTION_SIM_STATE_CHANGED      |refer to android.telephony. |
2091      * |NO.+-------------------------+---------------------------+TelephonyManager#getSimState|
2092      * |   |EXTRA_SIM_STATE          |EXTRA_SIM_LOCKED_REASON    |                            |
2093      * |   |(Intent#XXX)             |(Intent#XXX)               |TelephonyManager#SimState   |
2094      * +===+=====================================================+============================+
2095      * |1  |SIM_STATE_UNKNOWN        |always null                |SIM_STATE_UNKNOWN           |
2096      * +---+-------------------------+---------------------------+----------------------------+
2097      * |2  |SIM_STATE_ABSENT         |always null                |SIM_STATE_ABSENT            |
2098      * +---+-------------------------+---------------------------+----------------------------+
2099      * |3  |SIM_STATE_CARD_IO_ERROR  |SIM_STATE_CARD_IO_ERROR    |SIM_STATE_CARD_IO_ERROR     |
2100      * +---+-------------------------+---------------------------+----------------------------+
2101      * |4  |SIM_STATE_CARD_RESTRICTED|SIM_STATE_CARD_RESTRICTED  |SIM_STATE_CARD_RESTRICTED   |
2102      * +---+-------------------------+---------------------------+----------------------------+
2103      * |5  |SIM_STATE_LOCKED         |SIM_LOCKED_ON_PIN          |SIM_STATE_PIN_REQUIRED      |
2104      * +---+-------------------------+---------------------------+----------------------------+
2105      * |6  |SIM_STATE_LOCKED         |SIM_LOCKED_ON_PUK          |SIM_STATE_PUK_REQUIRED      |
2106      * +---+-------------------------+---------------------------+----------------------------+
2107      * |7  |SIM_STATE_LOCKED         |SIM_LOCKED_NETWORK         |SIM_STATE_NETWORK_LOCKED    |
2108      * +---+-------------------------+---------------------------+----------------------------+
2109      * |8  |SIM_STATE_LOCKED         |SIM_ABSENT_ON_PERM_DISABLED|SIM_STATE_PERM_DISABLED     |
2110      * +---+-------------------------+---------------------------+----------------------------+
2111      * |9  |SIM_STATE_NOT_READY      |always null                |SIM_STATE_NOT_READY         |
2112      * +---+-------------------------+---------------------------+----------------------------+
2113      * |10 |SIM_STATE_IMSI           |always null                |SIM_STATE_READY             |
2114      * +---+-------------------------+---------------------------+----------------------------+
2115      * |11 |SIM_STATE_READY          |always null                |SIM_STATE_READY             |
2116      * +---+-------------------------+---------------------------+----------------------------+
2117      * |12 |SIM_STATE_LOADED         |always null                |SIM_STATE_READY             |
2118      * +---+-------------------------+---------------------------+----------------------------+
2119      *
2120      * Note that, it seems #10 imsi ready case(i.e. SIM_STATE_IMSI) is never triggered from
2121      * Android Pie(telephony FWK doesn't trigger this broadcast any more), but it is still
2122      * OK keep this mapping logic.
2123      */
2124     private static class SimData {
2125         public int simState;
2126         public int slotId;
2127         public int subId;
2128 
SimData(int state, int slot, int id)2129         SimData(int state, int slot, int id) {
2130             simState = state;
2131             slotId = slot;
2132             subId = id;
2133         }
2134 
fromIntent(Intent intent)2135         static SimData fromIntent(Intent intent) {
2136             if (!Intent.ACTION_SIM_STATE_CHANGED.equals(intent.getAction())) {
2137                 throw new IllegalArgumentException("only handles intent ACTION_SIM_STATE_CHANGED");
2138             }
2139             int state = TelephonyManager.SIM_STATE_UNKNOWN;
2140             String stateExtra = intent.getStringExtra(Intent.EXTRA_SIM_STATE);
2141             int slotId = intent.getIntExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0);
2142             int subId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX,
2143                     SubscriptionManager.INVALID_SUBSCRIPTION_ID);
2144             if (Intent.SIM_STATE_ABSENT.equals(stateExtra)) {
2145                 state = TelephonyManager.SIM_STATE_ABSENT;
2146             } else if (Intent.SIM_STATE_LOCKED.equals(stateExtra)) {
2147                 final String lockedReason = intent
2148                         .getStringExtra(Intent.EXTRA_SIM_LOCKED_REASON);
2149                 if (Intent.SIM_LOCKED_ON_PIN.equals(lockedReason)) {
2150                     state = TelephonyManager.SIM_STATE_PIN_REQUIRED;
2151                 } else if (Intent.SIM_LOCKED_ON_PUK.equals(lockedReason)) {
2152                     state = TelephonyManager.SIM_STATE_PUK_REQUIRED;
2153                 } else if (Intent.SIM_LOCKED_NETWORK.equals(lockedReason)) {
2154                     state = TelephonyManager.SIM_STATE_NETWORK_LOCKED;
2155                 } else if (Intent.SIM_ABSENT_ON_PERM_DISABLED.equals(lockedReason)) {
2156                     state = TelephonyManager.SIM_STATE_PERM_DISABLED;
2157                 }
2158             } else if (Intent.SIM_STATE_CARD_IO_ERROR.equals(stateExtra)) {
2159                 state = TelephonyManager.SIM_STATE_CARD_IO_ERROR;
2160             } else if (Intent.SIM_STATE_CARD_RESTRICTED.equals(stateExtra)) {
2161                 state = TelephonyManager.SIM_STATE_CARD_RESTRICTED;
2162             } else if (Intent.SIM_STATE_NOT_READY.equals(stateExtra)) {
2163                 state = TelephonyManager.SIM_STATE_NOT_READY;
2164             } else if (Intent.SIM_STATE_READY.equals(stateExtra)
2165                     || Intent.SIM_STATE_LOADED.equals(stateExtra)
2166                     || Intent.SIM_STATE_IMSI.equals(stateExtra)) {
2167                 // Mapping SIM_STATE_LOADED and SIM_STATE_IMSI to SIM_STATE_READY is required
2168                 // because telephony doesn't return to "READY" after
2169                 // these state transitions. See bug 7197471.
2170                 state = TelephonyManager.SIM_STATE_READY;
2171             }
2172             return new SimData(state, slotId, subId);
2173         }
2174 
2175         @Override
toString()2176         public String toString() {
2177             return "SimData{state=" + simState + ",slotId=" + slotId + ",subId=" + subId + "}";
2178         }
2179     }
2180 
2181     /**
2182      * Updates callbacks when strong auth requirements change.
2183      */
2184     public class StrongAuthTracker extends LockPatternUtils.StrongAuthTracker {
StrongAuthTracker(Context context)2185         public StrongAuthTracker(Context context) {
2186             super(context);
2187         }
2188 
isUnlockingWithBiometricAllowed(boolean isStrongBiometric)2189         public boolean isUnlockingWithBiometricAllowed(boolean isStrongBiometric) {
2190             int userId = getCurrentUser();
2191             return isBiometricAllowedForUser(isStrongBiometric, userId);
2192         }
2193 
hasUserAuthenticatedSinceBoot()2194         public boolean hasUserAuthenticatedSinceBoot() {
2195             int userId = getCurrentUser();
2196             return (getStrongAuthForUser(userId)
2197                     & STRONG_AUTH_REQUIRED_AFTER_BOOT) == 0;
2198         }
2199 
2200         @Override
onStrongAuthRequiredChanged(int userId)2201         public void onStrongAuthRequiredChanged(int userId) {
2202             notifyStrongAuthAllowedChanged(userId);
2203         }
2204 
2205         // TODO(b/247091681): Renaming the inappropriate onIsNonStrongBiometricAllowedChanged
2206         //  callback wording for Weak/Convenience idle timeout constraint that only allow
2207         //  Strong-Auth
2208         @Override
onIsNonStrongBiometricAllowedChanged(int userId)2209         public void onIsNonStrongBiometricAllowedChanged(int userId) {
2210             notifyNonStrongBiometricAllowedChanged(userId);
2211         }
2212     }
2213 
handleStartedWakingUp(@owerManager.WakeReason int pmWakeReason)2214     protected void handleStartedWakingUp(@PowerManager.WakeReason int pmWakeReason) {
2215         Trace.beginSection("KeyguardUpdateMonitor#handleStartedWakingUp");
2216         Assert.isMainThread();
2217 
2218         mAllowedDisplayStateWhileAwakeForFaceAuth = true;
2219         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
2220         if (mFaceWakeUpTriggersConfig.shouldTriggerFaceAuthOnWakeUpFrom(pmWakeReason)) {
2221             FACE_AUTH_UPDATED_STARTED_WAKING_UP.setExtraInfo(pmWakeReason);
2222             updateFaceListeningState(BIOMETRIC_ACTION_UPDATE,
2223                     FACE_AUTH_UPDATED_STARTED_WAKING_UP);
2224         } else {
2225             mLogger.logSkipUpdateFaceListeningOnWakeup(pmWakeReason);
2226         }
2227         requestActiveUnlockFromWakeReason(pmWakeReason, true);
2228 
2229         for (int i = 0; i < mCallbacks.size(); i++) {
2230             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2231             if (cb != null) {
2232                 cb.onStartedWakingUp();
2233             }
2234         }
2235         Trace.endSection();
2236     }
2237 
handleStartedGoingToSleep(int arg1)2238     protected void handleStartedGoingToSleep(int arg1) {
2239         Assert.isMainThread();
2240         clearBiometricRecognized();
2241         for (int i = 0; i < mCallbacks.size(); i++) {
2242             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2243             if (cb != null) {
2244                 cb.onStartedGoingToSleep(arg1);
2245             }
2246         }
2247         mGoingToSleep = true;
2248         // Resetting assistant visibility state as the device is going to sleep now.
2249         // TaskStackChangeListener gets triggered a little late when we transition to AoD,
2250         // which results in face auth running once on AoD.
2251         mAssistantVisible = false;
2252         mLogger.d("Started going to sleep, mGoingToSleep=true, mAssistantVisible=false");
2253         updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE, FACE_AUTH_UPDATED_GOING_TO_SLEEP);
2254     }
2255 
handleFinishedGoingToSleep(int arg1)2256     protected void handleFinishedGoingToSleep(int arg1) {
2257         Assert.isMainThread();
2258         mGoingToSleep = false;
2259         for (int i = 0; i < mCallbacks.size(); i++) {
2260             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2261             if (cb != null) {
2262                 cb.onFinishedGoingToSleep(arg1);
2263             }
2264         }
2265         updateFaceListeningState(BIOMETRIC_ACTION_STOP,
2266                 FACE_AUTH_STOPPED_FINISHED_GOING_TO_SLEEP);
2267         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
2268     }
2269 
handleScreenTurnedOff()2270     private void handleScreenTurnedOff() {
2271         Assert.isMainThread();
2272         mHardwareFingerprintUnavailableRetryCount = 0;
2273         mHardwareFaceUnavailableRetryCount = 0;
2274     }
2275 
handleDreamingStateChanged(int dreamStart)2276     private void handleDreamingStateChanged(int dreamStart) {
2277         Assert.isMainThread();
2278         mIsDreaming = dreamStart == 1;
2279         for (int i = 0; i < mCallbacks.size(); i++) {
2280             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2281             if (cb != null) {
2282                 cb.onDreamingStateChanged(mIsDreaming);
2283             }
2284         }
2285         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
2286         if (mIsDreaming) {
2287             updateFaceListeningState(BIOMETRIC_ACTION_STOP, FACE_AUTH_STOPPED_DREAM_STARTED);
2288         }
2289     }
2290 
handleUserUnlocked(int userId)2291     private void handleUserUnlocked(int userId) {
2292         Assert.isMainThread();
2293         mUserIsUnlocked.put(userId, true);
2294         mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition();
2295         for (int i = 0; i < mCallbacks.size(); i++) {
2296             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2297             if (cb != null) {
2298                 cb.onUserUnlocked();
2299             }
2300         }
2301     }
2302 
handleUserStopped(int userId)2303     private void handleUserStopped(int userId) {
2304         Assert.isMainThread();
2305         mUserIsUnlocked.put(userId, mUserManager.isUserUnlocked(userId));
2306     }
2307 
2308     @VisibleForTesting
handleUserRemoved(int userId)2309     void handleUserRemoved(int userId) {
2310         Assert.isMainThread();
2311         mUserIsUnlocked.delete(userId);
2312         mUserTrustIsUsuallyManaged.delete(userId);
2313     }
2314 
handleKeyguardGoingAway(boolean goingAway)2315     private void handleKeyguardGoingAway(boolean goingAway) {
2316         Assert.isMainThread();
2317         setKeyguardGoingAway(goingAway);
2318     }
2319 
2320     @VisibleForTesting
setStrongAuthTracker(@onNull StrongAuthTracker tracker)2321     protected void setStrongAuthTracker(@NonNull StrongAuthTracker tracker) {
2322         if (mStrongAuthTracker != null) {
2323             mLockPatternUtils.unregisterStrongAuthTracker(mStrongAuthTracker);
2324         }
2325 
2326         mStrongAuthTracker = tracker;
2327         mLockPatternUtils.registerStrongAuthTracker(mStrongAuthTracker);
2328     }
2329 
2330     @VisibleForTesting
resetBiometricListeningState()2331     void resetBiometricListeningState() {
2332         mFingerprintRunningState = BIOMETRIC_STATE_STOPPED;
2333         mFaceRunningState = BIOMETRIC_STATE_STOPPED;
2334     }
2335 
2336     @VisibleForTesting
2337     @Inject
KeyguardUpdateMonitor( Context context, UserTracker userTracker, @Main Looper mainLooper, BroadcastDispatcher broadcastDispatcher, SecureSettings secureSettings, DumpManager dumpManager, @Background Executor backgroundExecutor, @Main Executor mainExecutor, StatusBarStateController statusBarStateController, LockPatternUtils lockPatternUtils, AuthController authController, TelephonyListenerManager telephonyListenerManager, InteractionJankMonitor interactionJankMonitor, LatencyTracker latencyTracker, ActiveUnlockConfig activeUnlockConfiguration, KeyguardUpdateMonitorLogger logger, UiEventLogger uiEventLogger, Provider<SessionTracker> sessionTrackerProvider, TrustManager trustManager, SubscriptionManager subscriptionManager, UserManager userManager, IDreamManager dreamManager, DevicePolicyManager devicePolicyManager, SensorPrivacyManager sensorPrivacyManager, TelephonyManager telephonyManager, PackageManager packageManager, @Nullable FaceManager faceManager, @Nullable FingerprintManager fingerprintManager, @Nullable BiometricManager biometricManager, FaceWakeUpTriggersConfig faceWakeUpTriggersConfig, DevicePostureController devicePostureController, Optional<FingerprintInteractiveToAuthProvider> interactiveToAuthProvider, FeatureFlags featureFlags, TaskStackChangeListeners taskStackChangeListeners, IActivityTaskManager activityTaskManagerService, DisplayTracker displayTracker, WakefulnessLifecycle wakefulness)2338     protected KeyguardUpdateMonitor(
2339             Context context,
2340             UserTracker userTracker,
2341             @Main Looper mainLooper,
2342             BroadcastDispatcher broadcastDispatcher,
2343             SecureSettings secureSettings,
2344             DumpManager dumpManager,
2345             @Background Executor backgroundExecutor,
2346             @Main Executor mainExecutor,
2347             StatusBarStateController statusBarStateController,
2348             LockPatternUtils lockPatternUtils,
2349             AuthController authController,
2350             TelephonyListenerManager telephonyListenerManager,
2351             InteractionJankMonitor interactionJankMonitor,
2352             LatencyTracker latencyTracker,
2353             ActiveUnlockConfig activeUnlockConfiguration,
2354             KeyguardUpdateMonitorLogger logger,
2355             UiEventLogger uiEventLogger,
2356             // This has to be a provider because SessionTracker depends on KeyguardUpdateMonitor :(
2357             Provider<SessionTracker> sessionTrackerProvider,
2358             TrustManager trustManager,
2359             SubscriptionManager subscriptionManager,
2360             UserManager userManager,
2361             IDreamManager dreamManager,
2362             DevicePolicyManager devicePolicyManager,
2363             SensorPrivacyManager sensorPrivacyManager,
2364             TelephonyManager telephonyManager,
2365             PackageManager packageManager,
2366             @Nullable FaceManager faceManager,
2367             @Nullable FingerprintManager fingerprintManager,
2368             @Nullable BiometricManager biometricManager,
2369             FaceWakeUpTriggersConfig faceWakeUpTriggersConfig,
2370             DevicePostureController devicePostureController,
2371             Optional<FingerprintInteractiveToAuthProvider> interactiveToAuthProvider,
2372             FeatureFlags featureFlags,
2373             TaskStackChangeListeners taskStackChangeListeners,
2374             IActivityTaskManager activityTaskManagerService,
2375             DisplayTracker displayTracker,
2376             WakefulnessLifecycle wakefulness) {
2377         mContext = context;
2378         mSubscriptionManager = subscriptionManager;
2379         mUserTracker = userTracker;
2380         mTelephonyListenerManager = telephonyListenerManager;
2381         mDeviceProvisioned = isDeviceProvisionedInSettingsDb();
2382         mStrongAuthTracker = new StrongAuthTracker(context);
2383         mBackgroundExecutor = backgroundExecutor;
2384         mBroadcastDispatcher = broadcastDispatcher;
2385         mInteractionJankMonitor = interactionJankMonitor;
2386         mLatencyTracker = latencyTracker;
2387         mStatusBarStateController = statusBarStateController;
2388         mStatusBarStateController.addCallback(mStatusBarStateControllerListener);
2389         mStatusBarState = mStatusBarStateController.getState();
2390         mLockPatternUtils = lockPatternUtils;
2391         mAuthController = authController;
2392         mSecureSettings = secureSettings;
2393         dumpManager.registerDumpable(getClass().getName(), this);
2394         mSensorPrivacyManager = sensorPrivacyManager;
2395         mActiveUnlockConfig = activeUnlockConfiguration;
2396         mLogger = logger;
2397         mUiEventLogger = uiEventLogger;
2398         mSessionTrackerProvider = sessionTrackerProvider;
2399         mTrustManager = trustManager;
2400         mUserManager = userManager;
2401         mDreamManager = dreamManager;
2402         mTelephonyManager = telephonyManager;
2403         mDevicePolicyManager = devicePolicyManager;
2404         mPostureController = devicePostureController;
2405         mPackageManager = packageManager;
2406         mFpm = fingerprintManager;
2407         mFaceManager = faceManager;
2408         mFeatureFlags = featureFlags;
2409         mActiveUnlockConfig.setKeyguardUpdateMonitor(this);
2410         mFaceAcquiredInfoIgnoreList = Arrays.stream(
2411                 mContext.getResources().getIntArray(
2412                         R.array.config_face_acquire_device_entry_ignorelist))
2413                 .boxed()
2414                 .collect(Collectors.toSet());
2415         mConfigFaceAuthSupportedPosture = mContext.getResources().getInteger(
2416                 R.integer.config_face_auth_supported_posture);
2417         mFaceWakeUpTriggersConfig = faceWakeUpTriggersConfig;
2418         mAllowFingerprintOnOccludingActivitiesFromPackage = Arrays.stream(
2419                 mContext.getResources().getStringArray(
2420                         R.array.config_fingerprint_listen_on_occluding_activity_packages))
2421                 .collect(Collectors.toSet());
2422         mTaskStackChangeListeners = taskStackChangeListeners;
2423         mActivityTaskManager = activityTaskManagerService;
2424         mWakefulness = wakefulness;
2425         mDisplayTracker = displayTracker;
2426         if (mFeatureFlags.isEnabled(Flags.STOP_FACE_AUTH_ON_DISPLAY_OFF)) {
2427             mDisplayTracker.addDisplayChangeCallback(mDisplayCallback, mainExecutor);
2428         }
2429 
2430         mHandler = new Handler(mainLooper) {
2431             @Override
2432             public void handleMessage(Message msg) {
2433                 switch (msg.what) {
2434                     case MSG_TIME_UPDATE:
2435                         handleTimeUpdate();
2436                         break;
2437                     case MSG_TIMEZONE_UPDATE:
2438                         handleTimeZoneUpdate((String) msg.obj);
2439                         break;
2440                     case MSG_BATTERY_UPDATE:
2441                         handleBatteryUpdate((BatteryStatus) msg.obj);
2442                         break;
2443                     case MSG_SIM_STATE_CHANGE:
2444                         handleSimStateChange(msg.arg1, msg.arg2, (int) msg.obj);
2445                         break;
2446                     case MSG_PHONE_STATE_CHANGED:
2447                         handlePhoneStateChanged((String) msg.obj);
2448                         break;
2449                     case MSG_DEVICE_PROVISIONED:
2450                         handleDeviceProvisioned();
2451                         break;
2452                     case MSG_DPM_STATE_CHANGED:
2453                         handleDevicePolicyManagerStateChanged(msg.arg1);
2454                         break;
2455                     case MSG_USER_SWITCHING:
2456                         handleUserSwitching(msg.arg1, (CountDownLatch) msg.obj);
2457                         break;
2458                     case MSG_USER_SWITCH_COMPLETE:
2459                         handleUserSwitchComplete(msg.arg1);
2460                         break;
2461                     case MSG_KEYGUARD_RESET:
2462                         handleKeyguardReset();
2463                         break;
2464                     case MSG_KEYGUARD_BOUNCER_CHANGED:
2465                         handlePrimaryBouncerChanged(msg.arg1, msg.arg2);
2466                         break;
2467                     case MSG_REPORT_EMERGENCY_CALL_ACTION:
2468                         handleReportEmergencyCallAction();
2469                         break;
2470                     case MSG_STARTED_GOING_TO_SLEEP:
2471                         handleStartedGoingToSleep(msg.arg1);
2472                         break;
2473                     case MSG_FINISHED_GOING_TO_SLEEP:
2474                         handleFinishedGoingToSleep(msg.arg1);
2475                         break;
2476                     case MSG_STARTED_WAKING_UP:
2477                         Trace.beginSection("KeyguardUpdateMonitor#handler MSG_STARTED_WAKING_UP");
2478                         handleStartedWakingUp(msg.arg1);
2479                         Trace.endSection();
2480                         break;
2481                     case MSG_SIM_SUBSCRIPTION_INFO_CHANGED:
2482                         handleSimSubscriptionInfoChanged();
2483                         break;
2484                     case MSG_AIRPLANE_MODE_CHANGED:
2485                         handleAirplaneModeChanged();
2486                         break;
2487                     case MSG_SERVICE_STATE_CHANGE:
2488                         handleServiceStateChange(msg.arg1, (ServiceState) msg.obj);
2489                         break;
2490                     case MSG_SERVICE_PROVIDERS_UPDATED:
2491                         handleServiceProvidersUpdated((Intent) msg.obj);
2492                         break;
2493                     case MSG_SCREEN_TURNED_OFF:
2494                         Trace.beginSection("KeyguardUpdateMonitor#handler MSG_SCREEN_TURNED_OFF");
2495                         handleScreenTurnedOff();
2496                         Trace.endSection();
2497                         break;
2498                     case MSG_DREAMING_STATE_CHANGED:
2499                         handleDreamingStateChanged(msg.arg1);
2500                         break;
2501                     case MSG_USER_UNLOCKED:
2502                         handleUserUnlocked(msg.arg1);
2503                         break;
2504                     case MSG_USER_STOPPED:
2505                         handleUserStopped(msg.arg1);
2506                         break;
2507                     case MSG_USER_REMOVED:
2508                         handleUserRemoved(msg.arg1);
2509                         break;
2510                     case MSG_ASSISTANT_STACK_CHANGED:
2511                         setAssistantVisible((boolean) msg.obj);
2512                         break;
2513                     case MSG_BIOMETRIC_AUTHENTICATION_CONTINUE:
2514                         updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
2515                                 FACE_AUTH_UPDATED_FP_AUTHENTICATED);
2516                         break;
2517                     case MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED:
2518                         updateLogoutEnabled();
2519                         break;
2520                     case MSG_TELEPHONY_CAPABLE:
2521                         updateTelephonyCapable((boolean) msg.obj);
2522                         break;
2523                     case MSG_KEYGUARD_GOING_AWAY:
2524                         handleKeyguardGoingAway((boolean) msg.obj);
2525                         break;
2526                     case MSG_TIME_FORMAT_UPDATE:
2527                         handleTimeFormatUpdate((String) msg.obj);
2528                         break;
2529                     case MSG_REQUIRE_NFC_UNLOCK:
2530                         handleRequireUnlockForNfc();
2531                         break;
2532                     case MSG_KEYGUARD_DISMISS_ANIMATION_FINISHED:
2533                         handleKeyguardDismissAnimationFinished();
2534                         break;
2535                     case MSG_BIOMETRIC_ENROLLMENT_STATE_CHANGED:
2536                         notifyAboutEnrollmentChange(msg.arg1);
2537                         break;
2538                     default:
2539                         super.handleMessage(msg);
2540                         break;
2541                 }
2542             }
2543         };
2544 
2545         // Since device can't be un-provisioned, we only need to register a content observer
2546         // to update mDeviceProvisioned when we are...
2547         if (!mDeviceProvisioned) {
2548             watchForDeviceProvisioning();
2549         }
2550 
2551         // Take a guess at initial SIM state, battery status and PLMN until we get an update
2552         mBatteryStatus = new BatteryStatus(BATTERY_STATUS_UNKNOWN, /* level= */ 100, /* plugged= */
2553                 0, CHARGING_POLICY_DEFAULT, /* maxChargingWattage= */0, /* present= */true);
2554 
2555         // Watch for interesting updates
2556         final IntentFilter filter = new IntentFilter();
2557         filter.addAction(Intent.ACTION_TIME_TICK);
2558         filter.addAction(Intent.ACTION_TIME_CHANGED);
2559         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
2560         filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
2561         filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
2562         filter.addAction(Intent.ACTION_SIM_STATE_CHANGED);
2563         filter.addAction(Intent.ACTION_SERVICE_STATE);
2564         filter.addAction(TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
2565         filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
2566         filter.addAction(TelephonyManager.ACTION_SERVICE_PROVIDERS_UPDATED);
2567         filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2568         filter.addAction(UsbManager.ACTION_USB_PORT_COMPLIANCE_CHANGED);
2569         mBroadcastDispatcher.registerReceiverWithHandler(mBroadcastReceiver, filter, mHandler);
2570         // Since ACTION_SERVICE_STATE is being moved to a non-sticky broadcast, trigger the
2571         // listener now with the service state from the default sub.
2572         mBackgroundExecutor.execute(() -> {
2573             int subId = SubscriptionManager.getDefaultSubscriptionId();
2574             ServiceState serviceState = mTelephonyManager.getServiceStateForSubscriber(subId);
2575             mHandler.sendMessage(
2576                     mHandler.obtainMessage(MSG_SERVICE_STATE_CHANGE, subId, 0, serviceState));
2577         });
2578 
2579         final IntentFilter allUserFilter = new IntentFilter();
2580         allUserFilter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
2581         allUserFilter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2582         allUserFilter.addAction(ACTION_USER_UNLOCKED);
2583         allUserFilter.addAction(ACTION_USER_STOPPED);
2584         allUserFilter.addAction(ACTION_USER_REMOVED);
2585         allUserFilter.addAction(NfcAdapter.ACTION_REQUIRE_UNLOCK_FOR_NFC);
2586         mBroadcastDispatcher.registerReceiverWithHandler(mBroadcastAllReceiver, allUserFilter,
2587                 mHandler, UserHandle.ALL);
2588 
2589         mSubscriptionManager.addOnSubscriptionsChangedListener(mSubscriptionListener);
2590         mUserTracker.addCallback(mUserChangedCallback, mainExecutor);
2591 
2592         mTrustManager.registerTrustListener(this);
2593 
2594         setStrongAuthTracker(mStrongAuthTracker);
2595 
2596         if (mFpm != null) {
2597             mFpm.addAuthenticatorsRegisteredCallback(
2598                     new IFingerprintAuthenticatorsRegisteredCallback.Stub() {
2599                         @Override
2600                         public void onAllAuthenticatorsRegistered(
2601                                 List<FingerprintSensorPropertiesInternal> sensors)
2602                                 throws RemoteException {
2603                             mFingerprintSensorProperties = sensors;
2604                             updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
2605                             mLogger.d("FingerprintManager onAllAuthenticatorsRegistered");
2606                         }
2607                     });
2608             mFpm.addLockoutResetCallback(mFingerprintLockoutResetCallback);
2609         }
2610         if (mFaceManager != null) {
2611             mFaceManager.addAuthenticatorsRegisteredCallback(
2612                     new IFaceAuthenticatorsRegisteredCallback.Stub() {
2613                         @Override
2614                         public void onAllAuthenticatorsRegistered(
2615                                 List<FaceSensorPropertiesInternal> sensors) throws RemoteException {
2616                             mFaceSensorProperties = sensors;
2617                             mLogger.d("FaceManager onAllAuthenticatorsRegistered");
2618                         }
2619                     });
2620             mFaceManager.addLockoutResetCallback(mFaceLockoutResetCallback);
2621         }
2622 
2623         if (biometricManager != null) {
2624             biometricManager.registerEnabledOnKeyguardCallback(mBiometricEnabledCallback);
2625         }
2626 
2627         // in case authenticators aren't registered yet at this point:
2628         mAuthController.addCallback(new AuthController.Callback() {
2629             @Override
2630             public void onAllAuthenticatorsRegistered(
2631                     @BiometricAuthenticator.Modality int modality) {
2632                 mainExecutor.execute(() -> updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
2633                         FACE_AUTH_TRIGGERED_ALL_AUTHENTICATORS_REGISTERED));
2634             }
2635 
2636             @Override
2637             public void onEnrollmentsChanged(@BiometricAuthenticator.Modality int modality) {
2638                 mHandler.obtainMessage(MSG_BIOMETRIC_ENROLLMENT_STATE_CHANGED, modality, 0)
2639                         .sendToTarget();
2640                 mainExecutor.execute(() -> updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
2641                         FACE_AUTH_TRIGGERED_ENROLLMENTS_CHANGED));
2642             }
2643         });
2644         if (mConfigFaceAuthSupportedPosture != DEVICE_POSTURE_UNKNOWN) {
2645             mPostureController.addCallback(mPostureCallback);
2646         }
2647         updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE, FACE_AUTH_UPDATED_ON_KEYGUARD_INIT);
2648 
2649         mTaskStackChangeListeners.registerTaskStackListener(mTaskStackListener);
2650         mIsSystemUser = mUserManager.isSystemUser();
2651         int user = mUserTracker.getUserId();
2652         mUserIsUnlocked.put(user, mUserManager.isUserUnlocked(user));
2653         mLogoutEnabled = mDevicePolicyManager.isLogoutEnabled();
2654         updateSecondaryLockscreenRequirement(user);
2655         List<UserInfo> allUsers = mUserManager.getUsers();
2656         for (UserInfo userInfo : allUsers) {
2657             boolean trustUsuallyManaged = mTrustManager.isTrustUsuallyManaged(userInfo.id);
2658             mLogger.logTrustUsuallyManagedUpdated(userInfo.id,
2659                     mUserTrustIsUsuallyManaged.get(userInfo.id),
2660                     trustUsuallyManaged, "init from constructor");
2661             mUserTrustIsUsuallyManaged.put(userInfo.id,
2662                     trustUsuallyManaged);
2663         }
2664         updateAirplaneModeState();
2665 
2666         mTelephonyListenerManager.addActiveDataSubscriptionIdListener(mPhoneStateListener);
2667         initializeSimState();
2668 
2669         mTimeFormatChangeObserver = new ContentObserver(mHandler) {
2670             @Override
2671             public void onChange(boolean selfChange) {
2672                 mHandler.sendMessage(mHandler.obtainMessage(
2673                         MSG_TIME_FORMAT_UPDATE,
2674                         Settings.System.getString(
2675                                 mContext.getContentResolver(),
2676                                 Settings.System.TIME_12_24)));
2677             }
2678         };
2679 
2680         mContext.getContentResolver().registerContentObserver(
2681                 Settings.System.getUriFor(Settings.System.TIME_12_24),
2682                 false, mTimeFormatChangeObserver, UserHandle.USER_ALL);
2683 
2684         mFingerprintInteractiveToAuthProvider = interactiveToAuthProvider.orElse(null);
2685     }
2686 
initializeSimState()2687     private void initializeSimState() {
2688         // Set initial sim states values.
2689         for (int slot = 0; slot < mTelephonyManager.getActiveModemCount(); slot++) {
2690             int state = mTelephonyManager.getSimState(slot);
2691             int[] subIds = mSubscriptionManager.getSubscriptionIds(slot);
2692             if (subIds != null) {
2693                 for (int subId : subIds) {
2694                     mHandler.obtainMessage(MSG_SIM_STATE_CHANGE, subId, slot, state)
2695                             .sendToTarget();
2696                 }
2697             }
2698         }
2699     }
2700 
updateFaceEnrolled(int userId)2701     private void updateFaceEnrolled(int userId) {
2702         final Boolean isFaceEnrolled = isFaceSupported()
2703                 && mBiometricEnabledForUser.get(userId)
2704                 && mAuthController.isFaceAuthEnrolled(userId);
2705         if (mIsFaceEnrolled != isFaceEnrolled) {
2706             mLogger.logFaceEnrolledUpdated(mIsFaceEnrolled, isFaceEnrolled);
2707         }
2708         mIsFaceEnrolled = isFaceEnrolled;
2709     }
2710 
isFaceSupported()2711     private boolean isFaceSupported() {
2712         return mFaceManager != null && !mFaceSensorProperties.isEmpty();
2713     }
2714 
isFingerprintSupported()2715     private boolean isFingerprintSupported() {
2716         return mFpm != null && !mFingerprintSensorProperties.isEmpty();
2717     }
2718 
2719     /**
2720      * @return true if there's at least one udfps enrolled for the current user.
2721      */
isUdfpsEnrolled()2722     public boolean isUdfpsEnrolled() {
2723         return mAuthController.isUdfpsEnrolled(getCurrentUser());
2724     }
2725 
2726     /**
2727      * @return true if udfps HW is supported on this device. Can return true even if the user has
2728      * not enrolled udfps. This may be false if called before onAllAuthenticatorsRegistered.
2729      */
isUdfpsSupported()2730     public boolean isUdfpsSupported() {
2731         return mAuthController.isUdfpsSupported();
2732     }
2733 
2734     /**
2735      * @return true if there's at least one sfps enrollment for the current user.
2736      */
isSfpsEnrolled()2737     public boolean isSfpsEnrolled() {
2738         return mAuthController.isSfpsEnrolled(getCurrentUser());
2739     }
2740 
2741     /**
2742      * @return true if sfps HW is supported on this device. Can return true even if the user has
2743      * not enrolled sfps. This may be false if called before onAllAuthenticatorsRegistered.
2744      */
isSfpsSupported()2745     public boolean isSfpsSupported() {
2746         return mAuthController.isSfpsSupported();
2747     }
2748 
2749     /**
2750      * @return true if there's at least one face enrolled
2751      */
isFaceEnrolled()2752     public boolean isFaceEnrolled() {
2753         return mIsFaceEnrolled;
2754     }
2755 
2756     private final UserTracker.Callback mUserChangedCallback = new UserTracker.Callback() {
2757         @Override
2758         public void onUserChanging(int newUser, Context userContext, CountDownLatch latch) {
2759             mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCHING,
2760                     newUser, 0, latch));
2761         }
2762 
2763         @Override
2764         public void onUserChanged(int newUser, Context userContext) {
2765             mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCH_COMPLETE,
2766                     newUser, 0));
2767         }
2768     };
2769 
updateAirplaneModeState()2770     private void updateAirplaneModeState() {
2771         // ACTION_AIRPLANE_MODE_CHANGED do not broadcast if device set AirplaneMode ON and boot
2772         if (!WirelessUtils.isAirplaneModeOn(mContext)
2773                 || mHandler.hasMessages(MSG_AIRPLANE_MODE_CHANGED)) {
2774             return;
2775         }
2776         mHandler.sendEmptyMessage(MSG_AIRPLANE_MODE_CHANGED);
2777     }
2778 
updateBiometricListeningState(int action, @NonNull FaceAuthUiEvent faceAuthUiEvent)2779     private void updateBiometricListeningState(int action,
2780             @NonNull FaceAuthUiEvent faceAuthUiEvent) {
2781         updateFingerprintListeningState(action);
2782         updateFaceListeningState(action, faceAuthUiEvent);
2783     }
2784 
updateFingerprintListeningState(int action)2785     private void updateFingerprintListeningState(int action) {
2786         // If this message exists, we should not authenticate again until this message is
2787         // consumed by the handler
2788         if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) {
2789             mLogger.logHandlerHasAuthContinueMsgs(action);
2790             return;
2791         }
2792 
2793         // don't start running fingerprint until they're registered
2794         if (!mAuthController.areAllFingerprintAuthenticatorsRegistered()) {
2795             mLogger.d("All FP authenticators not registered, skipping FP listening state update");
2796             return;
2797         }
2798         final boolean shouldListenForFingerprint = shouldListenForFingerprint(isUdfpsSupported());
2799         final boolean runningOrRestarting = mFingerprintRunningState == BIOMETRIC_STATE_RUNNING
2800                 || mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING;
2801         if (runningOrRestarting && !shouldListenForFingerprint) {
2802             if (action == BIOMETRIC_ACTION_START) {
2803                 mLogger.v("Ignoring stopListeningForFingerprint()");
2804                 return;
2805             }
2806             stopListeningForFingerprint();
2807         } else if (!runningOrRestarting && shouldListenForFingerprint) {
2808             if (action == BIOMETRIC_ACTION_STOP) {
2809                 mLogger.v("Ignoring startListeningForFingerprint()");
2810                 return;
2811             }
2812             startListeningForFingerprint();
2813         }
2814     }
2815 
2816     /**
2817      * If a user is encrypted or not.
2818      * This is NOT related to the lock screen being visible or not.
2819      *
2820      * @param userId The user.
2821      * @return {@code true} when encrypted.
2822      * @see UserManager#isUserUnlocked()
2823      * @see Intent#ACTION_USER_UNLOCKED
2824      */
isUserUnlocked(int userId)2825     public boolean isUserUnlocked(int userId) {
2826         return mUserIsUnlocked.get(userId);
2827     }
2828 
2829     /**
2830      * Called whenever passive authentication is requested or aborted by a sensor.
2831      *
2832      * @param active If the interrupt started or ended.
2833      */
onAuthInterruptDetected(boolean active)2834     public void onAuthInterruptDetected(boolean active) {
2835         mLogger.logAuthInterruptDetected(active);
2836         if (mAuthInterruptActive == active) {
2837             return;
2838         }
2839         mAuthInterruptActive = active;
2840         updateFaceListeningState(BIOMETRIC_ACTION_UPDATE,
2841                 FACE_AUTH_TRIGGERED_ON_REACH_GESTURE_ON_AOD);
2842         requestActiveUnlock(ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE, "onReach");
2843     }
2844 
2845     /**
2846      * Requests face authentication if we're on a state where it's allowed.
2847      * This will re-trigger auth in case it fails.
2848      * @param reason One of the reasons {@link FaceAuthApiRequestReason} on why this API is being
2849      * invoked.
2850      * @return current face auth detection state, true if it is running.
2851      * @deprecated This is being migrated to use modern architecture.
2852      */
2853     @Deprecated
requestFaceAuth(@aceAuthApiRequestReason String reason)2854     public boolean requestFaceAuth(@FaceAuthApiRequestReason String reason) {
2855         mLogger.logFaceAuthRequested(reason);
2856         updateFaceListeningState(BIOMETRIC_ACTION_START, apiRequestReasonToUiEvent(reason));
2857         return isFaceDetectionRunning();
2858     }
2859 
2860     /**
2861      * In case face auth is running, cancel it.
2862      */
cancelFaceAuth()2863     public void cancelFaceAuth() {
2864         stopListeningForFace(FACE_AUTH_STOPPED_USER_INPUT_ON_BOUNCER);
2865     }
2866 
updateFaceListeningState(int action, @NonNull FaceAuthUiEvent faceAuthUiEvent)2867     private void updateFaceListeningState(int action, @NonNull FaceAuthUiEvent faceAuthUiEvent) {
2868         if (isFaceAuthInteractorEnabled()) return;
2869         // If this message exists, we should not authenticate again until this message is
2870         // consumed by the handler
2871         if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) {
2872             return;
2873         }
2874         mHandler.removeCallbacks(mRetryFaceAuthentication);
2875         boolean shouldListenForFace = shouldListenForFace();
2876         if (mFaceRunningState == BIOMETRIC_STATE_RUNNING && !shouldListenForFace) {
2877             if (action == BIOMETRIC_ACTION_START) {
2878                 mLogger.v("Ignoring stopListeningForFace()");
2879                 return;
2880             }
2881             stopListeningForFace(faceAuthUiEvent);
2882         } else if (mFaceRunningState != BIOMETRIC_STATE_RUNNING && shouldListenForFace) {
2883             if (action == BIOMETRIC_ACTION_STOP) {
2884                 mLogger.v("Ignoring startListeningForFace()");
2885                 return;
2886             }
2887             startListeningForFace(faceAuthUiEvent);
2888         }
2889     }
2890 
2891     @Nullable
getKeyguardSessionId()2892     private InstanceId getKeyguardSessionId() {
2893         return mSessionTrackerProvider.get().getSessionId(SESSION_KEYGUARD);
2894     }
2895 
2896     /**
2897      * Initiates active unlock to get the unlock token ready.
2898      */
initiateActiveUnlock(String reason)2899     private void initiateActiveUnlock(String reason) {
2900         // If this message exists, FP has already authenticated, so wait until that is handled
2901         if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) {
2902             return;
2903         }
2904 
2905         if (shouldTriggerActiveUnlock()) {
2906             mLogger.logActiveUnlockTriggered(reason);
2907             mTrustManager.reportUserMayRequestUnlock(KeyguardUpdateMonitor.getCurrentUser());
2908         }
2909     }
2910 
requestActiveUnlockFromWakeReason(@owerManager.WakeReason int wakeReason, boolean powerManagerWakeup)2911     private void requestActiveUnlockFromWakeReason(@PowerManager.WakeReason int wakeReason,
2912             boolean powerManagerWakeup) {
2913         if (!mFaceWakeUpTriggersConfig.shouldTriggerFaceAuthOnWakeUpFrom(wakeReason)) {
2914             mLogger.logActiveUnlockRequestSkippedForWakeReasonDueToFaceConfig(wakeReason);
2915             return;
2916         }
2917 
2918         final ActiveUnlockConfig.ActiveUnlockRequestOrigin requestOrigin =
2919                 mActiveUnlockConfig.isWakeupConsideredUnlockIntent(wakeReason)
2920                         ? ActiveUnlockConfig.ActiveUnlockRequestOrigin.UNLOCK_INTENT
2921                         : ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE;
2922         final String reason = "wakingUp - " + PowerManager.wakeReasonToString(wakeReason)
2923                 + " powerManagerWakeup=" + powerManagerWakeup;
2924         if (mActiveUnlockConfig.shouldWakeupForceDismissKeyguard(wakeReason)) {
2925             requestActiveUnlockDismissKeyguard(
2926                     requestOrigin,
2927                     reason
2928             );
2929         } else {
2930             requestActiveUnlock(
2931                     requestOrigin,
2932                     reason
2933             );
2934         }
2935     }
2936 
2937     /**
2938      * Attempts to trigger active unlock from trust agent.
2939      */
requestActiveUnlock( @onNull ActiveUnlockConfig.ActiveUnlockRequestOrigin requestOrigin, String reason, boolean dismissKeyguard )2940     private void requestActiveUnlock(
2941             @NonNull ActiveUnlockConfig.ActiveUnlockRequestOrigin requestOrigin,
2942             String reason,
2943             boolean dismissKeyguard
2944     ) {
2945         // If this message exists, FP has already authenticated, so wait until that is handled
2946         if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) {
2947             return;
2948         }
2949 
2950         final boolean allowRequest =
2951                 mActiveUnlockConfig.shouldAllowActiveUnlockFromOrigin(requestOrigin);
2952         if (requestOrigin == ActiveUnlockConfig.ActiveUnlockRequestOrigin.WAKE
2953                 && !allowRequest && mActiveUnlockConfig.isActiveUnlockEnabled()) {
2954             // instead of requesting the active unlock, initiate the unlock
2955             initiateActiveUnlock(reason);
2956             return;
2957         }
2958 
2959         if (allowRequest && shouldTriggerActiveUnlock()) {
2960             mLogger.logUserRequestedUnlock(requestOrigin, reason, dismissKeyguard);
2961             mTrustManager.reportUserRequestedUnlock(KeyguardUpdateMonitor.getCurrentUser(),
2962                     dismissKeyguard);
2963         }
2964     }
2965 
2966 
2967     /**
2968      * Attempts to trigger active unlock from trust agent.
2969      * Only dismisses the keyguard under certain conditions.
2970      */
requestActiveUnlock( @onNull ActiveUnlockConfig.ActiveUnlockRequestOrigin requestOrigin, String extraReason )2971     public void requestActiveUnlock(
2972             @NonNull ActiveUnlockConfig.ActiveUnlockRequestOrigin requestOrigin,
2973             String extraReason
2974     ) {
2975         final boolean canFaceBypass = isFaceEnrolled() && mKeyguardBypassController != null
2976                 && mKeyguardBypassController.canBypass();
2977         requestActiveUnlock(
2978                 requestOrigin,
2979                 extraReason, canFaceBypass
2980                         || mAlternateBouncerShowing
2981                         || mPrimaryBouncerFullyShown
2982                         || mAuthController.isUdfpsFingerDown());
2983     }
2984 
2985     /**
2986      * Attempts to trigger active unlock from trust agent with a request to dismiss the keyguard.
2987      */
requestActiveUnlockDismissKeyguard( @onNull ActiveUnlockConfig.ActiveUnlockRequestOrigin requestOrigin, String extraReason )2988     public void requestActiveUnlockDismissKeyguard(
2989             @NonNull ActiveUnlockConfig.ActiveUnlockRequestOrigin requestOrigin,
2990             String extraReason
2991     ) {
2992         requestActiveUnlock(
2993                 requestOrigin,
2994                 extraReason + "-dismissKeyguard", true);
2995     }
2996 
2997     /**
2998      * Whether the alternate bouncer is showing.
2999      */
setAlternateBouncerShowing(boolean showing)3000     public void setAlternateBouncerShowing(boolean showing) {
3001         mAlternateBouncerShowing = showing;
3002         if (mAlternateBouncerShowing) {
3003             updateFaceListeningState(BIOMETRIC_ACTION_START,
3004                     FACE_AUTH_TRIGGERED_ALTERNATE_BIOMETRIC_BOUNCER_SHOWN);
3005             requestActiveUnlock(
3006                     ActiveUnlockConfig.ActiveUnlockRequestOrigin.UNLOCK_INTENT,
3007                     "alternateBouncer");
3008         }
3009         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
3010     }
3011 
3012     /**
3013      * If the current state of the device allows for triggering active unlock. This does not
3014      * include active unlock availability.
3015      */
canTriggerActiveUnlockBasedOnDeviceState()3016     public boolean canTriggerActiveUnlockBasedOnDeviceState() {
3017         return shouldTriggerActiveUnlock(/* shouldLog */ false);
3018     }
3019 
shouldTriggerActiveUnlock()3020     private boolean shouldTriggerActiveUnlock() {
3021         return shouldTriggerActiveUnlock(/* shouldLog */ true);
3022     }
3023 
shouldTriggerActiveUnlock(boolean shouldLog)3024     private boolean shouldTriggerActiveUnlock(boolean shouldLog) {
3025         // Triggers:
3026         final boolean triggerActiveUnlockForAssistant = shouldTriggerActiveUnlockForAssistant();
3027         final boolean awakeKeyguard = mPrimaryBouncerFullyShown || mAlternateBouncerShowing
3028                 || (isKeyguardVisible() && !mGoingToSleep
3029                 && mStatusBarState != StatusBarState.SHADE_LOCKED);
3030 
3031         // Gates:
3032         final int user = getCurrentUser();
3033 
3034         // No need to trigger active unlock if we're already unlocked or don't have
3035         // pin/pattern/password setup
3036         final boolean userCanDismissLockScreen = getUserCanSkipBouncer(user)
3037                 || !mLockPatternUtils.isSecure(user);
3038 
3039         // Don't trigger active unlock if fp is locked out
3040         final boolean fpLockedOut = isFingerprintLockedOut();
3041 
3042         // Don't trigger active unlock if primary auth is required
3043         final boolean primaryAuthRequired = !isUnlockingWithTrustAgentAllowed();
3044 
3045         final boolean shouldTriggerActiveUnlock =
3046                 (mAuthInterruptActive || triggerActiveUnlockForAssistant || awakeKeyguard)
3047                         && !mSwitchingUser
3048                         && !userCanDismissLockScreen
3049                         && !fpLockedOut
3050                         && !primaryAuthRequired
3051                         && !mKeyguardGoingAway
3052                         && !mSecureCameraLaunched;
3053 
3054         if (shouldLog) {
3055             // Aggregate relevant fields for debug logging.
3056             logListenerModelData(
3057                     new KeyguardActiveUnlockModel(
3058                             System.currentTimeMillis(),
3059                             user,
3060                             shouldTriggerActiveUnlock,
3061                             awakeKeyguard,
3062                             mAuthInterruptActive,
3063                             fpLockedOut,
3064                             primaryAuthRequired,
3065                             mSwitchingUser,
3066                             triggerActiveUnlockForAssistant,
3067                             userCanDismissLockScreen));
3068         }
3069 
3070         return shouldTriggerActiveUnlock;
3071     }
3072 
shouldListenForFingerprintAssistant()3073     private boolean shouldListenForFingerprintAssistant() {
3074         BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(getCurrentUser());
3075         return mAssistantVisible && mKeyguardOccluded
3076                 && !(fingerprint != null && fingerprint.mAuthenticated)
3077                 && !mUserHasTrust.get(getCurrentUser(), false);
3078     }
3079 
shouldListenForFaceAssistant()3080     private boolean shouldListenForFaceAssistant() {
3081         BiometricAuthenticated face = mUserFaceAuthenticated.get(getCurrentUser());
3082         return mAssistantVisible
3083                 // There can be intermediate states where mKeyguardShowing is false but
3084                 // mKeyguardOccluded is true, we don't want to run face auth in such a scenario.
3085                 && (mKeyguardShowing && mKeyguardOccluded)
3086                 && !(face != null && face.mAuthenticated)
3087                 && !mUserHasTrust.get(getCurrentUser(), false);
3088     }
3089 
shouldTriggerActiveUnlockForAssistant()3090     private boolean shouldTriggerActiveUnlockForAssistant() {
3091         return mAssistantVisible && mKeyguardOccluded
3092                 && !mUserHasTrust.get(getCurrentUser(), false);
3093     }
3094 
3095     @VisibleForTesting
shouldListenForFingerprint(boolean isUdfps)3096     protected boolean shouldListenForFingerprint(boolean isUdfps) {
3097         final int user = getCurrentUser();
3098         final boolean userDoesNotHaveTrust = !getUserHasTrust(user);
3099         final boolean shouldListenForFingerprintAssistant = shouldListenForFingerprintAssistant();
3100         final boolean shouldListenKeyguardState =
3101                 isKeyguardVisible()
3102                         || !mDeviceInteractive
3103                         || (mPrimaryBouncerIsOrWillBeShowing && !mKeyguardGoingAway)
3104                         || mGoingToSleep
3105                         || shouldListenForFingerprintAssistant
3106                         || (mKeyguardOccluded && mIsDreaming)
3107                         || (mKeyguardOccluded && userDoesNotHaveTrust && mKeyguardShowing
3108                         && (mOccludingAppRequestingFp
3109                         || isUdfps
3110                         || mAlternateBouncerShowing
3111                         || mAllowFingerprintOnCurrentOccludingActivity
3112                 )
3113             );
3114 
3115         // Only listen if this KeyguardUpdateMonitor belongs to the system user. There is an
3116         // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware.
3117         final boolean biometricEnabledForUser = mBiometricEnabledForUser.get(user);
3118         final boolean userCanSkipBouncer = getUserCanSkipBouncer(user);
3119         final boolean fingerprintDisabledForUser = isFingerprintDisabled(user);
3120         final boolean shouldListenUserState =
3121                 !mSwitchingUser
3122                         && !fingerprintDisabledForUser
3123                         && (!mKeyguardGoingAway || !mDeviceInteractive)
3124                         && mIsSystemUser
3125                         && biometricEnabledForUser
3126                         && !isUserInLockdown(user);
3127         final boolean strongerAuthRequired = !isUnlockingWithFingerprintAllowed();
3128         final boolean isSideFps = isSfpsSupported() && isSfpsEnrolled();
3129         final boolean shouldListenBouncerState =
3130                 !strongerAuthRequired || !mPrimaryBouncerIsOrWillBeShowing;
3131 
3132         final boolean shouldListenUdfpsState = !isUdfps
3133                 || (!userCanSkipBouncer
3134                 && !strongerAuthRequired
3135                 && userDoesNotHaveTrust);
3136 
3137         boolean shouldListenSideFpsState = true;
3138         if (isSideFps) {
3139             final boolean interactiveToAuthEnabled =
3140                     mFingerprintInteractiveToAuthProvider != null &&
3141                             mFingerprintInteractiveToAuthProvider.isEnabled(getCurrentUser());
3142             shouldListenSideFpsState =
3143                     interactiveToAuthEnabled ? isDeviceInteractive() && !mGoingToSleep : true;
3144         }
3145 
3146         boolean shouldListen = shouldListenKeyguardState && shouldListenUserState
3147                 && shouldListenBouncerState && shouldListenUdfpsState
3148                 && shouldListenSideFpsState;
3149         logListenerModelData(
3150                 new KeyguardFingerprintListenModel(
3151                     System.currentTimeMillis(),
3152                     user,
3153                     shouldListen,
3154                     mAllowFingerprintOnCurrentOccludingActivity,
3155                     mAlternateBouncerShowing,
3156                     biometricEnabledForUser,
3157                     mPrimaryBouncerIsOrWillBeShowing,
3158                     userCanSkipBouncer,
3159                     mCredentialAttempted,
3160                     mDeviceInteractive,
3161                     mIsDreaming,
3162                     fingerprintDisabledForUser,
3163                     mFingerprintLockedOut,
3164                     mGoingToSleep,
3165                     mKeyguardGoingAway,
3166                     isKeyguardVisible(),
3167                     mKeyguardOccluded,
3168                     mOccludingAppRequestingFp,
3169                     shouldListenSideFpsState,
3170                     shouldListenForFingerprintAssistant,
3171                     strongerAuthRequired,
3172                     mSwitchingUser,
3173                     mIsSystemUser,
3174                     isUdfps,
3175                     userDoesNotHaveTrust));
3176 
3177         return shouldListen;
3178     }
3179 
3180     /**
3181      * If face auth is allows to scan on this exact moment.
3182      */
shouldListenForFace()3183     public boolean shouldListenForFace() {
3184         if (mFaceManager == null) {
3185             // Device does not have face auth
3186             return false;
3187         }
3188 
3189         if (isFaceAuthInteractorEnabled()) {
3190             return mFaceAuthInteractor.canFaceAuthRun();
3191         }
3192 
3193         final boolean statusBarShadeLocked = mStatusBarState == StatusBarState.SHADE_LOCKED;
3194         final boolean awakeKeyguard = isKeyguardVisible() && mDeviceInteractive
3195                 && !statusBarShadeLocked;
3196         final int user = getCurrentUser();
3197         final boolean faceAuthAllowed = isUnlockingWithBiometricAllowed(FACE);
3198         final boolean canBypass = mKeyguardBypassController != null
3199                 && mKeyguardBypassController.canBypass();
3200         // There's no reason to ask the HAL for authentication when the user can dismiss the
3201         // bouncer because the user is trusted, unless we're bypassing and need to auto-dismiss
3202         // the lock screen even when TrustAgents are keeping the device unlocked.
3203         final boolean userNotTrustedOrDetectionIsNeeded = !getUserHasTrust(user) || canBypass;
3204 
3205         // If the device supports face detection (without authentication), if bypass is enabled,
3206         // allow face detection to happen even if stronger auth is required. When face is detected,
3207         // we show the bouncer. However, if the user manually locked down the device themselves,
3208         // never attempt to detect face.
3209         final boolean supportsDetect = isFaceSupported()
3210                 && mFaceSensorProperties.get(0).supportsFaceDetection
3211                 && canBypass && !mPrimaryBouncerIsOrWillBeShowing
3212                 && !isUserInLockdown(user);
3213         final boolean faceAuthAllowedOrDetectionIsNeeded = faceAuthAllowed || supportsDetect;
3214 
3215         // If the face or fp has recently been authenticated do not attempt to authenticate again.
3216         final boolean faceAndFpNotAuthenticated = !getUserUnlockedWithBiometric(user);
3217         final boolean faceDisabledForUser = isFaceDisabled(user);
3218         final boolean biometricEnabledForUser = mBiometricEnabledForUser.get(user);
3219         final boolean shouldListenForFaceAssistant = shouldListenForFaceAssistant();
3220         final boolean isUdfpsFingerDown = mAuthController.isUdfpsFingerDown();
3221         final boolean isPostureAllowedForFaceAuth = doesPostureAllowFaceAuth(mPostureState);
3222         // Only listen if this KeyguardUpdateMonitor belongs to the system user. There is an
3223         // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware.
3224         final boolean shouldListen =
3225                 (mPrimaryBouncerFullyShown
3226                         || mAuthInterruptActive
3227                         || mOccludingAppRequestingFace
3228                         || awakeKeyguard
3229                         || shouldListenForFaceAssistant
3230                         || isUdfpsFingerDown
3231                         || mAlternateBouncerShowing)
3232                 && !mSwitchingUser && !faceDisabledForUser && userNotTrustedOrDetectionIsNeeded
3233                 && !mKeyguardGoingAway && biometricEnabledForUser
3234                 && faceAuthAllowedOrDetectionIsNeeded && mIsSystemUser
3235                 && (!mSecureCameraLaunched || mAlternateBouncerShowing)
3236                 && faceAndFpNotAuthenticated
3237                 && !mGoingToSleep
3238                 && isPostureAllowedForFaceAuth
3239                 && mAllowedDisplayStateWhileAwakeForFaceAuth;
3240 
3241         // Aggregate relevant fields for debug logging.
3242         logListenerModelData(
3243                 new KeyguardFaceListenModel(
3244                     System.currentTimeMillis(),
3245                     user,
3246                     shouldListen,
3247                     mAllowedDisplayStateWhileAwakeForFaceAuth,
3248                     mAlternateBouncerShowing,
3249                     mAuthInterruptActive,
3250                     biometricEnabledForUser,
3251                     mPrimaryBouncerFullyShown,
3252                     faceAndFpNotAuthenticated,
3253                     faceAuthAllowed,
3254                     faceDisabledForUser,
3255                     isFaceLockedOut(),
3256                     mGoingToSleep,
3257                     awakeKeyguard,
3258                     mKeyguardGoingAway,
3259                     shouldListenForFaceAssistant,
3260                     mOccludingAppRequestingFace,
3261                     isPostureAllowedForFaceAuth,
3262                     mSecureCameraLaunched,
3263                     supportsDetect,
3264                     mSwitchingUser,
3265                     mIsSystemUser,
3266                     isUdfpsFingerDown,
3267                     userNotTrustedOrDetectionIsNeeded));
3268 
3269         return shouldListen;
3270     }
3271 
doesPostureAllowFaceAuth(@evicePostureInt int posture)3272     private boolean doesPostureAllowFaceAuth(@DevicePostureInt int posture) {
3273         return mConfigFaceAuthSupportedPosture == DEVICE_POSTURE_UNKNOWN
3274                 || (posture == mConfigFaceAuthSupportedPosture);
3275     }
3276 
3277     /**
3278      * If the current device posture allows face auth to run.
3279      */
doesCurrentPostureAllowFaceAuth()3280     public boolean doesCurrentPostureAllowFaceAuth() {
3281         return doesPostureAllowFaceAuth(mPostureState);
3282     }
3283 
logListenerModelData(@onNull KeyguardListenModel model)3284     private void logListenerModelData(@NonNull KeyguardListenModel model) {
3285         mLogger.logKeyguardListenerModel(model);
3286         if (model instanceof KeyguardFingerprintListenModel) {
3287             mFingerprintListenBuffer.insert((KeyguardFingerprintListenModel) model);
3288         } else if (model instanceof KeyguardActiveUnlockModel) {
3289             mActiveUnlockTriggerBuffer.insert((KeyguardActiveUnlockModel) model);
3290         } else if (model instanceof KeyguardFaceListenModel) {
3291             mFaceListenBuffer.insert((KeyguardFaceListenModel) model);
3292         }
3293     }
3294 
startListeningForFingerprint()3295     private void startListeningForFingerprint() {
3296         final int userId = getCurrentUser();
3297         final boolean unlockPossible = isUnlockWithFingerprintPossible(userId);
3298         if (mFingerprintCancelSignal != null) {
3299             mLogger.logUnexpectedFpCancellationSignalState(
3300                     mFingerprintRunningState,
3301                     unlockPossible);
3302         }
3303 
3304         if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING) {
3305             setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING);
3306             return;
3307         }
3308         if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
3309             // Waiting for restart via handleFingerprintError().
3310             return;
3311         }
3312 
3313         if (unlockPossible) {
3314             mFingerprintCancelSignal = new CancellationSignal();
3315 
3316             if (!isUnlockingWithFingerprintAllowed()) {
3317                 mLogger.v("startListeningForFingerprint - detect");
3318                 mFpm.detectFingerprint(
3319                         mFingerprintCancelSignal,
3320                         mFingerprintDetectionCallback,
3321                         new FingerprintAuthenticateOptions.Builder()
3322                                 .setUserId(userId)
3323                                 .build());
3324             } else {
3325                 mLogger.v("startListeningForFingerprint");
3326                 mFpm.authenticate(null /* crypto */, mFingerprintCancelSignal,
3327                         mFingerprintAuthenticationCallback,
3328                         null /* handler */,
3329                         new FingerprintAuthenticateOptions.Builder()
3330                                 .setUserId(userId)
3331                                 .build()
3332                 );
3333             }
3334             setFingerprintRunningState(BIOMETRIC_STATE_RUNNING);
3335         }
3336     }
3337 
startListeningForFace(@onNull FaceAuthUiEvent faceAuthUiEvent)3338     private void startListeningForFace(@NonNull FaceAuthUiEvent faceAuthUiEvent) {
3339         final int userId = getCurrentUser();
3340         final boolean unlockPossible = isUnlockWithFacePossible(userId);
3341         if (mFaceCancelSignal != null) {
3342             mLogger.logUnexpectedFaceCancellationSignalState(mFaceRunningState, unlockPossible);
3343         }
3344 
3345         if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING) {
3346             setFaceRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING);
3347             return;
3348         } else if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
3349             // Waiting for ERROR_CANCELED before requesting auth again
3350             return;
3351         }
3352         mLogger.logStartedListeningForFace(mFaceRunningState, faceAuthUiEvent);
3353         mUiEventLogger.logWithInstanceIdAndPosition(
3354                 faceAuthUiEvent,
3355                 0,
3356                 null,
3357                 getKeyguardSessionId(),
3358                 faceAuthUiEvent.getExtraInfo()
3359         );
3360         mLogger.logFaceUnlockPossible(unlockPossible);
3361         if (unlockPossible) {
3362             mFaceCancelSignal = new CancellationSignal();
3363 
3364             final FaceAuthenticateOptions faceAuthenticateOptions =
3365                     new SysUiFaceAuthenticateOptions(
3366                             userId,
3367                             faceAuthUiEvent,
3368                             faceAuthUiEvent == FACE_AUTH_UPDATED_STARTED_WAKING_UP
3369                                     ? faceAuthUiEvent.getExtraInfo()
3370                                     : WAKE_REASON_UNKNOWN
3371                     ).toFaceAuthenticateOptions();
3372             // This would need to be updated for multi-sensor devices
3373             final boolean supportsFaceDetection = isFaceSupported()
3374                     && mFaceSensorProperties.get(0).supportsFaceDetection;
3375             if (!isUnlockingWithBiometricAllowed(FACE)) {
3376                 final boolean udfpsFingerprintAuthRunning = isUdfpsSupported()
3377                         && isFingerprintDetectionRunning();
3378                 if (supportsFaceDetection && !udfpsFingerprintAuthRunning) {
3379                     // Run face detection. (If a face is detected, show the bouncer.)
3380                     mLogger.v("startListeningForFace - detect");
3381                     mFaceManager.detectFace(mFaceCancelSignal, mFaceDetectionCallback,
3382                             faceAuthenticateOptions);
3383                 } else {
3384                     // Don't run face detection. Instead, inform the user
3385                     // face auth is unavailable and how to proceed.
3386                     // (ie: "Use fingerprint instead" or "Swipe up to open")
3387                     mLogger.v("Ignoring \"startListeningForFace - detect\". "
3388                             + "Informing user face isn't available.");
3389                     mFaceAuthenticationCallback.onAuthenticationHelp(
3390                             BIOMETRIC_HELP_FACE_NOT_AVAILABLE,
3391                             mContext.getResources().getString(
3392                                     R.string.keyguard_face_unlock_unavailable)
3393                     );
3394                     return;
3395                 }
3396             } else {
3397                 mLogger.v("startListeningForFace - authenticate");
3398                 final boolean isBypassEnabled = mKeyguardBypassController != null
3399                         && mKeyguardBypassController.isBypassEnabled();
3400                 mFaceManager.authenticate(null /* crypto */, mFaceCancelSignal,
3401                         mFaceAuthenticationCallback, null /* handler */,
3402                         faceAuthenticateOptions);
3403             }
3404             setFaceRunningState(BIOMETRIC_STATE_RUNNING);
3405         }
3406     }
3407 
isFingerprintLockedOut()3408     public boolean isFingerprintLockedOut() {
3409         return mFingerprintLockedOut || mFingerprintLockedOutPermanent;
3410     }
3411 
isFaceLockedOut()3412     public boolean isFaceLockedOut() {
3413         if (isFaceAuthInteractorEnabled()) {
3414             return getFaceAuthInteractor().isLockedOut();
3415         }
3416         return mFaceLockedOutPermanent;
3417     }
3418 
3419     /**
3420      * If biometrics hardware is available, not disabled, and user has enrolled templates.
3421      * This does NOT check if the device is encrypted or in lockdown.
3422      *
3423      * @param userId User that's trying to unlock.
3424      * @return {@code true} if possible.
3425      */
isUnlockingWithBiometricsPossible(int userId)3426     public boolean isUnlockingWithBiometricsPossible(int userId) {
3427         return isUnlockWithFacePossible(userId) || isUnlockWithFingerprintPossible(userId);
3428     }
3429 
3430     /**
3431      * If non-strong (i.e. weak or convenience) biometrics hardware is available, not disabled, and
3432      * user has enrolled templates. This does NOT check if the device is encrypted or in lockdown.
3433      *
3434      * @param userId User that's trying to unlock.
3435      * @return {@code true} if possible.
3436      */
isUnlockingWithNonStrongBiometricsPossible(int userId)3437     public boolean isUnlockingWithNonStrongBiometricsPossible(int userId) {
3438         return (!isFaceClass3() && isUnlockWithFacePossible(userId))
3439                 || (isFingerprintClass3() && isUnlockWithFingerprintPossible(userId));
3440     }
3441 
3442     @SuppressLint("MissingPermission")
3443     @VisibleForTesting
isUnlockWithFingerprintPossible(int userId)3444     boolean isUnlockWithFingerprintPossible(int userId) {
3445         // TODO (b/242022358), make this rely on onEnrollmentChanged event and update it only once.
3446         boolean newFpEnrolled = isFingerprintSupported()
3447                 && !isFingerprintDisabled(userId) && mFpm.hasEnrolledTemplates(userId);
3448         Boolean oldFpEnrolled = mIsUnlockWithFingerprintPossible.getOrDefault(userId, false);
3449         if (oldFpEnrolled != newFpEnrolled) {
3450             mLogger.logFpEnrolledUpdated(userId, oldFpEnrolled, newFpEnrolled);
3451         }
3452         mIsUnlockWithFingerprintPossible.put(userId, newFpEnrolled);
3453         return mIsUnlockWithFingerprintPossible.get(userId);
3454     }
3455 
3456     /**
3457      * Cached value for whether fingerprint is enrolled and possible to use for authentication.
3458      * Note: checking fingerprint enrollment directly with the AuthController requires an IPC.
3459      */
getCachedIsUnlockWithFingerprintPossible(int userId)3460     public boolean getCachedIsUnlockWithFingerprintPossible(int userId) {
3461         return mIsUnlockWithFingerprintPossible.getOrDefault(userId, false);
3462     }
3463 
3464     /**
3465      * @deprecated This is being migrated to use modern architecture.
3466      */
3467     @Deprecated
isUnlockWithFacePossible(int userId)3468     private boolean isUnlockWithFacePossible(int userId) {
3469         if (isFaceAuthInteractorEnabled()) {
3470             return getFaceAuthInteractor().canFaceAuthRun();
3471         }
3472         return isFaceAuthEnabledForUser(userId) && !isFaceDisabled(userId);
3473     }
3474 
3475     /**
3476      * If face hardware is available, user has enrolled and enabled auth via setting.
3477      *
3478      * @deprecated This is being migrated to use modern architecture.
3479      */
3480     @Deprecated
isFaceAuthEnabledForUser(int userId)3481     public boolean isFaceAuthEnabledForUser(int userId) {
3482         // TODO (b/242022358), make this rely on onEnrollmentChanged event and update it only once.
3483         updateFaceEnrolled(userId);
3484         return mIsFaceEnrolled;
3485     }
3486 
notifyAboutEnrollmentChange(@iometricAuthenticator.Modality int modality)3487     private void notifyAboutEnrollmentChange(@BiometricAuthenticator.Modality int modality) {
3488         BiometricSourceType biometricSourceType;
3489         if (modality == TYPE_FINGERPRINT) {
3490             biometricSourceType = FINGERPRINT;
3491         } else if (modality == TYPE_FACE) {
3492             biometricSourceType = FACE;
3493         } else {
3494             return;
3495         }
3496         mLogger.notifyAboutEnrollmentsChanged(biometricSourceType);
3497         Assert.isMainThread();
3498         for (int i = 0; i < mCallbacks.size(); i++) {
3499             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3500             if (cb != null) {
3501                 cb.onBiometricEnrollmentStateChanged(biometricSourceType);
3502             }
3503         }
3504     }
3505 
stopListeningForFingerprint()3506     private void stopListeningForFingerprint() {
3507         mLogger.v("stopListeningForFingerprint()");
3508         if (mFingerprintRunningState == BIOMETRIC_STATE_RUNNING) {
3509             if (mFingerprintCancelSignal != null) {
3510                 mFingerprintCancelSignal.cancel();
3511                 mFingerprintCancelSignal = null;
3512                 mHandler.removeCallbacks(mFpCancelNotReceived);
3513                 mHandler.postDelayed(mFpCancelNotReceived, DEFAULT_CANCEL_SIGNAL_TIMEOUT);
3514             }
3515             setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING);
3516         }
3517         if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
3518             setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING);
3519         }
3520     }
3521 
stopListeningForFace(@onNull FaceAuthUiEvent faceAuthUiEvent)3522     private void stopListeningForFace(@NonNull FaceAuthUiEvent faceAuthUiEvent) {
3523         if (isFaceAuthInteractorEnabled()) return;
3524         mLogger.v("stopListeningForFace()");
3525         mLogger.logStoppedListeningForFace(mFaceRunningState, faceAuthUiEvent.getReason());
3526         mUiEventLogger.log(faceAuthUiEvent, getKeyguardSessionId());
3527         if (mFaceRunningState == BIOMETRIC_STATE_RUNNING) {
3528             if (mFaceCancelSignal != null) {
3529                 mFaceCancelSignal.cancel();
3530                 mFaceCancelSignal = null;
3531                 mHandler.removeCallbacks(mFaceCancelNotReceived);
3532                 mHandler.postDelayed(mFaceCancelNotReceived, DEFAULT_CANCEL_SIGNAL_TIMEOUT);
3533             }
3534             setFaceRunningState(BIOMETRIC_STATE_CANCELLING);
3535         }
3536         if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
3537             setFaceRunningState(BIOMETRIC_STATE_CANCELLING);
3538         }
3539     }
3540 
isDeviceProvisionedInSettingsDb()3541     private boolean isDeviceProvisionedInSettingsDb() {
3542         return Settings.Global.getInt(mContext.getContentResolver(),
3543                 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
3544     }
3545 
watchForDeviceProvisioning()3546     private void watchForDeviceProvisioning() {
3547         mDeviceProvisionedObserver = new ContentObserver(mHandler) {
3548             @Override
3549             public void onChange(boolean selfChange) {
3550                 super.onChange(selfChange);
3551                 mDeviceProvisioned = isDeviceProvisionedInSettingsDb();
3552                 if (mDeviceProvisioned) {
3553                     mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED);
3554                 }
3555                 mLogger.logDeviceProvisionedState(mDeviceProvisioned);
3556             }
3557         };
3558 
3559         mContext.getContentResolver().registerContentObserver(
3560                 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
3561                 false, mDeviceProvisionedObserver);
3562 
3563         // prevent a race condition between where we check the flag and where we register the
3564         // observer by grabbing the value once again...
3565         boolean provisioned = isDeviceProvisionedInSettingsDb();
3566         if (provisioned != mDeviceProvisioned) {
3567             mDeviceProvisioned = provisioned;
3568             if (mDeviceProvisioned) {
3569                 mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED);
3570             }
3571         }
3572     }
3573 
3574     /**
3575      * Handle {@link #MSG_DPM_STATE_CHANGED} which can change primary authentication methods to
3576      * pin/pattern/password/none.
3577      */
handleDevicePolicyManagerStateChanged(int userId)3578     private void handleDevicePolicyManagerStateChanged(int userId) {
3579         Assert.isMainThread();
3580         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
3581         updateSecondaryLockscreenRequirement(userId);
3582 
3583         for (int i = 0; i < mCallbacks.size(); i++) {
3584             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3585             if (cb != null) {
3586                 cb.onDevicePolicyManagerStateChanged();
3587             }
3588         }
3589     }
3590 
3591     /**
3592      * Handle {@link #MSG_USER_SWITCHING}
3593      */
3594     @VisibleForTesting
handleUserSwitching(int userId, CountDownLatch latch)3595     void handleUserSwitching(int userId, CountDownLatch latch) {
3596         mLogger.logUserSwitching(userId, "from UserTracker");
3597         Assert.isMainThread();
3598         clearBiometricRecognized();
3599         boolean trustUsuallyManaged = mTrustManager.isTrustUsuallyManaged(userId);
3600         mLogger.logTrustUsuallyManagedUpdated(userId, mUserTrustIsUsuallyManaged.get(userId),
3601                 trustUsuallyManaged, "userSwitching");
3602         mUserTrustIsUsuallyManaged.put(userId, trustUsuallyManaged);
3603         for (int i = 0; i < mCallbacks.size(); i++) {
3604             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3605             if (cb != null) {
3606                 cb.onUserSwitching(userId);
3607             }
3608         }
3609         latch.countDown();
3610     }
3611 
3612     /**
3613      * Handle {@link #MSG_USER_SWITCH_COMPLETE}
3614      */
3615     @VisibleForTesting
handleUserSwitchComplete(int userId)3616     void handleUserSwitchComplete(int userId) {
3617         mLogger.logUserSwitchComplete(userId, "from UserTracker");
3618         Assert.isMainThread();
3619         for (int i = 0; i < mCallbacks.size(); i++) {
3620             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3621             if (cb != null) {
3622                 cb.onUserSwitchComplete(userId);
3623             }
3624         }
3625 
3626         // Immediately stop previous biometric listening states.
3627         // Resetting lockout states updates the biometric listening states.
3628         if (isFaceSupported()) {
3629             stopListeningForFace(FACE_AUTH_UPDATED_USER_SWITCHING);
3630             handleFaceLockoutReset(mFaceManager.getLockoutModeForUser(
3631                     mFaceSensorProperties.get(0).sensorId, userId));
3632         }
3633         if (isFingerprintSupported()) {
3634             stopListeningForFingerprint();
3635             handleFingerprintLockoutReset(mFpm.getLockoutModeForUser(
3636                     mFingerprintSensorProperties.get(0).sensorId, userId));
3637         }
3638 
3639         mInteractionJankMonitor.end(InteractionJankMonitor.CUJ_USER_SWITCH);
3640         mLatencyTracker.onActionEnd(LatencyTracker.ACTION_USER_SWITCH);
3641     }
3642 
3643     /**
3644      * Handle {@link #MSG_DEVICE_PROVISIONED}
3645      */
handleDeviceProvisioned()3646     private void handleDeviceProvisioned() {
3647         Assert.isMainThread();
3648         for (int i = 0; i < mCallbacks.size(); i++) {
3649             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3650             if (cb != null) {
3651                 cb.onDeviceProvisioned();
3652             }
3653         }
3654         if (mDeviceProvisionedObserver != null) {
3655             // We don't need the observer anymore...
3656             mContext.getContentResolver().unregisterContentObserver(mDeviceProvisionedObserver);
3657             mDeviceProvisionedObserver = null;
3658         }
3659     }
3660 
3661     /**
3662      * Handle {@link #MSG_PHONE_STATE_CHANGED}
3663      */
handlePhoneStateChanged(String newState)3664     private void handlePhoneStateChanged(String newState) {
3665         Assert.isMainThread();
3666         mLogger.logPhoneStateChanged(newState);
3667         if (TelephonyManager.EXTRA_STATE_IDLE.equals(newState)) {
3668             mPhoneState = TelephonyManager.CALL_STATE_IDLE;
3669         } else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(newState)) {
3670             mPhoneState = TelephonyManager.CALL_STATE_OFFHOOK;
3671         } else if (TelephonyManager.EXTRA_STATE_RINGING.equals(newState)) {
3672             mPhoneState = TelephonyManager.CALL_STATE_RINGING;
3673         }
3674         for (int i = 0; i < mCallbacks.size(); i++) {
3675             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3676             if (cb != null) {
3677                 cb.onPhoneStateChanged(mPhoneState);
3678             }
3679         }
3680     }
3681 
3682     /**
3683      * Handle {@link #MSG_TIME_UPDATE}
3684      */
handleTimeUpdate()3685     private void handleTimeUpdate() {
3686         Assert.isMainThread();
3687         for (int i = 0; i < mCallbacks.size(); i++) {
3688             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3689             if (cb != null) {
3690                 cb.onTimeChanged();
3691             }
3692         }
3693     }
3694 
3695     /**
3696      * Handle (@line #MSG_TIMEZONE_UPDATE}
3697      */
handleTimeZoneUpdate(String timeZone)3698     private void handleTimeZoneUpdate(String timeZone) {
3699         Assert.isMainThread();
3700         mLogger.d("handleTimeZoneUpdate");
3701         for (int i = 0; i < mCallbacks.size(); i++) {
3702             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3703             if (cb != null) {
3704                 cb.onTimeZoneChanged(TimeZone.getTimeZone(timeZone));
3705                 // Also notify callbacks about time change to remain compatible.
3706                 cb.onTimeChanged();
3707             }
3708         }
3709     }
3710 
3711     /**
3712      * Handle (@line #MSG_TIME_FORMAT_UPDATE}
3713      *
3714      * @param timeFormat "12" for 12-hour format, "24" for 24-hour format
3715      */
handleTimeFormatUpdate(String timeFormat)3716     private void handleTimeFormatUpdate(String timeFormat) {
3717         Assert.isMainThread();
3718         mLogger.logTimeFormatChanged(timeFormat);
3719         for (int i = 0; i < mCallbacks.size(); i++) {
3720             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3721             if (cb != null) {
3722                 cb.onTimeFormatChanged(timeFormat);
3723             }
3724         }
3725     }
3726 
3727     /**
3728      * @param data the weather data (temp, conditions, unit) for weather clock to use
3729      */
sendWeatherData(WeatherData data)3730     public void sendWeatherData(WeatherData data) {
3731         mHandler.post(()-> {
3732             handleWeatherDataUpdate(data); });
3733     }
3734 
handleWeatherDataUpdate(WeatherData data)3735     private void handleWeatherDataUpdate(WeatherData data) {
3736         Assert.isMainThread();
3737         for (int i = 0; i < mCallbacks.size(); i++) {
3738             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3739             if (cb != null) {
3740                 cb.onWeatherDataChanged(data);
3741             }
3742         }
3743     }
3744 
3745     /**
3746      * Handle {@link #MSG_BATTERY_UPDATE}
3747      */
handleBatteryUpdate(BatteryStatus status)3748     private void handleBatteryUpdate(BatteryStatus status) {
3749         Assert.isMainThread();
3750         final boolean batteryUpdateInteresting = isBatteryUpdateInteresting(mBatteryStatus, status);
3751         mBatteryStatus = status;
3752         if (batteryUpdateInteresting) {
3753             mLogger.logHandleBatteryUpdate(mBatteryStatus);
3754             for (int i = 0; i < mCallbacks.size(); i++) {
3755                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3756                 if (cb != null) {
3757                     cb.onRefreshBatteryInfo(status);
3758                 }
3759             }
3760         }
3761     }
3762 
3763     /**
3764      * Handle Telephony status during Boot for CarrierText display policy
3765      */
3766     @VisibleForTesting
updateTelephonyCapable(boolean capable)3767     void updateTelephonyCapable(boolean capable) {
3768         Assert.isMainThread();
3769         if (capable == mTelephonyCapable) {
3770             return;
3771         }
3772         mTelephonyCapable = capable;
3773         for (int i = 0; i < mCallbacks.size(); i++) {
3774             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3775             if (cb != null) {
3776                 cb.onTelephonyCapable(mTelephonyCapable);
3777             }
3778         }
3779     }
3780 
3781     /**
3782      * Handle {@link #MSG_SIM_STATE_CHANGE}
3783      */
3784     @VisibleForTesting
handleSimStateChange(int subId, int slotId, int state)3785     void handleSimStateChange(int subId, int slotId, int state) {
3786         Assert.isMainThread();
3787         mLogger.logSimState(subId, slotId, state);
3788 
3789         boolean becameAbsent = false;
3790         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
3791             mLogger.w("invalid subId in handleSimStateChange()");
3792             /* Only handle No SIM(ABSENT) and Card Error(CARD_IO_ERROR) due to
3793              * handleServiceStateChange() handle other case */
3794             if (state == TelephonyManager.SIM_STATE_ABSENT) {
3795                 updateTelephonyCapable(true);
3796                 // Even though the subscription is not valid anymore, we need to notify that the
3797                 // SIM card was removed so we can update the UI.
3798                 becameAbsent = true;
3799                 for (SimData data : mSimDatas.values()) {
3800                     // Set the SIM state of all SimData associated with that slot to ABSENT se we
3801                     // do not move back into PIN/PUK locked and not detect the change below.
3802                     if (data.slotId == slotId) {
3803                         data.simState = TelephonyManager.SIM_STATE_ABSENT;
3804                     }
3805                 }
3806             } else if (state == TelephonyManager.SIM_STATE_CARD_IO_ERROR) {
3807                 updateTelephonyCapable(true);
3808             }
3809         }
3810 
3811         becameAbsent |= ABSENT_SIM_STATE_LIST.contains(state);
3812 
3813         // TODO(b/327476182): Preserve SIM_STATE_CARD_IO_ERROR sims in a separate data source.
3814         SimData data = mSimDatas.get(subId);
3815         final boolean changed;
3816         if (data == null) {
3817             data = new SimData(state, slotId, subId);
3818             mSimDatas.put(subId, data);
3819             changed = true; // no data yet; force update
3820         } else {
3821             changed = (data.simState != state || data.subId != subId || data.slotId != slotId);
3822             data.simState = state;
3823             data.subId = subId;
3824             data.slotId = slotId;
3825         }
3826         if ((changed || becameAbsent)) {
3827             for (int i = 0; i < mCallbacks.size(); i++) {
3828                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3829                 if (cb != null) {
3830                     cb.onSimStateChanged(subId, slotId, state);
3831                 }
3832             }
3833         }
3834     }
3835 
3836     /**
3837      * Handle {@link #MSG_SERVICE_STATE_CHANGE}
3838      */
3839     @VisibleForTesting
handleServiceStateChange(int subId, ServiceState serviceState)3840     void handleServiceStateChange(int subId, ServiceState serviceState) {
3841         mLogger.logServiceStateChange(subId, serviceState);
3842 
3843         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
3844             mLogger.w("invalid subId in handleServiceStateChange()");
3845             return;
3846         } else {
3847             updateTelephonyCapable(true);
3848         }
3849 
3850         mServiceStates.put(subId, serviceState);
3851 
3852         callbacksRefreshCarrierInfo();
3853     }
3854 
3855     /**
3856      * Handle {@link #MSG_SERVICE_PROVIDERS_UPDATED}
3857      */
handleServiceProvidersUpdated(Intent intent)3858     private void handleServiceProvidersUpdated(Intent intent) {
3859         mLogger.logServiceProvidersUpdated(intent);
3860         callbacksRefreshCarrierInfo();
3861     }
3862 
3863     /**
3864      * Whether the keyguard is showing and not occluded.
3865      */
isKeyguardVisible()3866     public boolean isKeyguardVisible() {
3867         return mKeyguardShowing && !mKeyguardOccluded;
3868     }
3869 
3870     /**
3871      * Handle {@link #MSG_KEYGUARD_RESET}
3872      */
3873     @VisibleForTesting
handleKeyguardReset()3874     protected void handleKeyguardReset() {
3875         mLogger.d("handleKeyguardReset");
3876         updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
3877                 FACE_AUTH_UPDATED_KEYGUARD_RESET);
3878         mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition();
3879     }
3880 
resolveNeedsSlowUnlockTransition()3881     private boolean resolveNeedsSlowUnlockTransition() {
3882         if (isUserUnlocked(getCurrentUser())) {
3883             return false;
3884         }
3885         Intent homeIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME);
3886         ResolveInfo resolveInfo = mPackageManager.resolveActivityAsUser(homeIntent,
3887                 0 /* flags */, getCurrentUser());
3888 
3889         if (resolveInfo == null) {
3890             mLogger.w("resolveNeedsSlowUnlockTransition: returning false since activity could "
3891                             + "not be resolved.");
3892             return false;
3893         }
3894 
3895         return FALLBACK_HOME_COMPONENT.equals(resolveInfo.getComponentInfo().getComponentName());
3896     }
3897 
3898     /**
3899      * Handle {@link #MSG_KEYGUARD_BOUNCER_CHANGED}
3900      *
3901      * @see #sendPrimaryBouncerChanged(boolean, boolean)
3902      */
handlePrimaryBouncerChanged(int primaryBouncerIsOrWillBeShowing, int primaryBouncerFullyShown)3903     private void handlePrimaryBouncerChanged(int primaryBouncerIsOrWillBeShowing,
3904             int primaryBouncerFullyShown) {
3905         Assert.isMainThread();
3906         final boolean wasPrimaryBouncerIsOrWillBeShowing = mPrimaryBouncerIsOrWillBeShowing;
3907         final boolean wasPrimaryBouncerFullyShown = mPrimaryBouncerFullyShown;
3908         mPrimaryBouncerIsOrWillBeShowing = primaryBouncerIsOrWillBeShowing == 1;
3909         mPrimaryBouncerFullyShown = primaryBouncerFullyShown == 1;
3910         mLogger.logPrimaryKeyguardBouncerChanged(mPrimaryBouncerIsOrWillBeShowing,
3911                 mPrimaryBouncerFullyShown);
3912 
3913         if (mPrimaryBouncerFullyShown) {
3914             // If the bouncer is shown, always clear this flag. This can happen in the following
3915             // situations: 1) Default camera with SHOW_WHEN_LOCKED is not chosen yet. 2) Secure
3916             // camera requests dismiss keyguard (tapping on photos for example). When these happen,
3917             // face auth should resume.
3918             mSecureCameraLaunched = false;
3919         } else {
3920             mCredentialAttempted = false;
3921         }
3922 
3923         if (wasPrimaryBouncerIsOrWillBeShowing != mPrimaryBouncerIsOrWillBeShowing) {
3924             for (int i = 0; i < mCallbacks.size(); i++) {
3925                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3926                 if (cb != null) {
3927                     cb.onKeyguardBouncerStateChanged(mPrimaryBouncerIsOrWillBeShowing);
3928                 }
3929             }
3930             updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
3931         }
3932 
3933         if (wasPrimaryBouncerFullyShown != mPrimaryBouncerFullyShown) {
3934             if (mPrimaryBouncerFullyShown) {
3935                 requestActiveUnlock(
3936                         ActiveUnlockConfig.ActiveUnlockRequestOrigin.UNLOCK_INTENT,
3937                         "bouncerFullyShown");
3938             }
3939             for (int i = 0; i < mCallbacks.size(); i++) {
3940                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3941                 if (cb != null) {
3942                     cb.onKeyguardBouncerFullyShowingChanged(mPrimaryBouncerFullyShown);
3943                 }
3944             }
3945             updateFaceListeningState(BIOMETRIC_ACTION_UPDATE,
3946                     FACE_AUTH_UPDATED_PRIMARY_BOUNCER_SHOWN);
3947         }
3948     }
3949 
3950     /**
3951      * Handle {@link #MSG_REQUIRE_NFC_UNLOCK}
3952      */
handleRequireUnlockForNfc()3953     private void handleRequireUnlockForNfc() {
3954         Assert.isMainThread();
3955         for (int i = 0; i < mCallbacks.size(); i++) {
3956             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3957             if (cb != null) {
3958                 cb.onRequireUnlockForNfc();
3959             }
3960         }
3961     }
3962 
3963     /**
3964      * Handle {@link #MSG_KEYGUARD_DISMISS_ANIMATION_FINISHED}
3965      */
handleKeyguardDismissAnimationFinished()3966     private void handleKeyguardDismissAnimationFinished() {
3967         Assert.isMainThread();
3968         for (int i = 0; i < mCallbacks.size(); i++) {
3969             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3970             if (cb != null) {
3971                 cb.onKeyguardDismissAnimationFinished();
3972             }
3973         }
3974     }
3975 
3976     /**
3977      * Handle {@link #MSG_REPORT_EMERGENCY_CALL_ACTION}
3978      */
handleReportEmergencyCallAction()3979     private void handleReportEmergencyCallAction() {
3980         Assert.isMainThread();
3981         for (int i = 0; i < mCallbacks.size(); i++) {
3982             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
3983             if (cb != null) {
3984                 cb.onEmergencyCallAction();
3985             }
3986         }
3987     }
3988 
isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current)3989     private boolean isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current) {
3990         final boolean nowPluggedIn = current.isPluggedIn();
3991         final boolean wasPluggedIn = old.isPluggedIn();
3992         final boolean stateChangedWhilePluggedIn = wasPluggedIn && nowPluggedIn
3993                 && (old.status != current.status);
3994 
3995         // change in plug state is always interesting
3996         if (wasPluggedIn != nowPluggedIn || stateChangedWhilePluggedIn) {
3997             return true;
3998         }
3999 
4000         // change in battery level
4001         if (old.level != current.level) {
4002             return true;
4003         }
4004 
4005         // change in charging current while plugged in
4006         if (nowPluggedIn && current.maxChargingWattage != old.maxChargingWattage) {
4007             return true;
4008         }
4009 
4010         // change in battery is present or not
4011         if (old.present != current.present) {
4012             return true;
4013         }
4014 
4015         // change in the incompatible charger
4016         if (!old.incompatibleCharger.equals(current.incompatibleCharger)) {
4017             return true;
4018         }
4019 
4020         // change in charging status
4021         return current.chargingStatus != old.chargingStatus;
4022     }
4023 
4024     /**
4025      * Remove the given observer's callback.
4026      *
4027      * @param callback The callback to remove
4028      */
removeCallback(KeyguardUpdateMonitorCallback callback)4029     public void removeCallback(KeyguardUpdateMonitorCallback callback) {
4030         Assert.isMainThread();
4031         mLogger.logUnregisterCallback(callback);
4032 
4033         mCallbacks.removeIf(el -> el.get() == callback);
4034     }
4035 
4036     /**
4037      * Register to receive notifications about general keyguard information
4038      * (see {@link KeyguardUpdateMonitorCallback}.
4039      *
4040      * @param callback The callback to register. Stay away from passing anonymous instances
4041      *                 as they will likely be dereferenced. Ensure that the callback is a class
4042      *                 field to persist it.
4043      */
registerCallback(KeyguardUpdateMonitorCallback callback)4044     public void registerCallback(KeyguardUpdateMonitorCallback callback) {
4045         Assert.isMainThread();
4046         mLogger.logRegisterCallback(callback);
4047         // Prevent adding duplicate callbacks
4048 
4049         for (int i = 0; i < mCallbacks.size(); i++) {
4050             if (mCallbacks.get(i).get() == callback) {
4051                 mLogger.logException(
4052                         new Exception("Called by"),
4053                         "Object tried to add another callback");
4054                 return;
4055             }
4056         }
4057         mCallbacks.add(new WeakReference<>(callback));
4058         removeCallback(null); // remove unused references
4059         sendUpdates(callback);
4060     }
4061 
setKeyguardBypassController(KeyguardBypassController keyguardBypassController)4062     public void setKeyguardBypassController(KeyguardBypassController keyguardBypassController) {
4063         mKeyguardBypassController = keyguardBypassController;
4064     }
4065 
isSwitchingUser()4066     public boolean isSwitchingUser() {
4067         return mSwitchingUser;
4068     }
4069 
4070     @AnyThread
setSwitchingUser(boolean switching)4071     public void setSwitchingUser(boolean switching) {
4072         if (switching) {
4073             mLogger.logUserSwitching(getCurrentUser(), "from setSwitchingUser");
4074         } else {
4075             mLogger.logUserSwitchComplete(getCurrentUser(), "from setSwitchingUser");
4076         }
4077         mSwitchingUser = switching;
4078         // Since this comes in on a binder thread, we need to post it first
4079         mHandler.post(() -> updateBiometricListeningState(BIOMETRIC_ACTION_UPDATE,
4080                 FACE_AUTH_UPDATED_USER_SWITCHING));
4081     }
4082 
sendUpdates(KeyguardUpdateMonitorCallback callback)4083     private void sendUpdates(KeyguardUpdateMonitorCallback callback) {
4084         // Notify listener of the current state
4085         callback.onRefreshBatteryInfo(mBatteryStatus);
4086         callback.onTimeChanged();
4087         callback.onPhoneStateChanged(mPhoneState);
4088         callback.onRefreshCarrierInfo();
4089         callback.onKeyguardVisibilityChanged(isKeyguardVisible());
4090         callback.onTelephonyCapable(mTelephonyCapable);
4091 
4092         for (Entry<Integer, SimData> data : mSimDatas.entrySet()) {
4093             final SimData state = data.getValue();
4094             callback.onSimStateChanged(state.subId, state.slotId, state.simState);
4095         }
4096     }
4097 
sendKeyguardReset()4098     public void sendKeyguardReset() {
4099         mHandler.obtainMessage(MSG_KEYGUARD_RESET).sendToTarget();
4100     }
4101 
4102     /**
4103      * @see #handlePrimaryBouncerChanged(int, int)
4104      */
sendPrimaryBouncerChanged(boolean primaryBouncerIsOrWillBeShowing, boolean primaryBouncerFullyShown)4105     public void sendPrimaryBouncerChanged(boolean primaryBouncerIsOrWillBeShowing,
4106             boolean primaryBouncerFullyShown) {
4107         mLogger.logSendPrimaryBouncerChanged(primaryBouncerIsOrWillBeShowing,
4108                 primaryBouncerFullyShown);
4109         Message message = mHandler.obtainMessage(MSG_KEYGUARD_BOUNCER_CHANGED);
4110         message.arg1 = primaryBouncerIsOrWillBeShowing ? 1 : 0;
4111         message.arg2 = primaryBouncerFullyShown ? 1 : 0;
4112         message.sendToTarget();
4113     }
4114 
4115     /**
4116      * Report that the user successfully entered the SIM PIN or PUK/SIM PIN so we
4117      * have the information earlier than waiting for the intent
4118      * broadcast from the telephony code.
4119      *
4120      * NOTE: Because handleSimStateChange() invokes callbacks immediately without going
4121      * through mHandler, this *must* be called from the UI thread.
4122      */
4123     @MainThread
reportSimUnlocked(int subId)4124     public void reportSimUnlocked(int subId) {
4125         mLogger.logSimUnlocked(subId);
4126         handleSimStateChange(subId, getSlotId(subId), TelephonyManager.SIM_STATE_READY);
4127     }
4128 
4129     /**
4130      * Report that the emergency call button has been pressed and the emergency dialer is
4131      * about to be displayed.
4132      *
4133      * @param bypassHandler runs immediately.
4134      *
4135      *                      NOTE: Must be called from UI thread if bypassHandler == true.
4136      */
reportEmergencyCallAction(boolean bypassHandler)4137     public void reportEmergencyCallAction(boolean bypassHandler) {
4138         if (!bypassHandler) {
4139             mHandler.obtainMessage(MSG_REPORT_EMERGENCY_CALL_ACTION).sendToTarget();
4140         } else {
4141             Assert.isMainThread();
4142             handleReportEmergencyCallAction();
4143         }
4144     }
4145 
4146     /**
4147      * @return Whether the device is provisioned (whether they have gone through
4148      * the setup wizard)
4149      */
isDeviceProvisioned()4150     public boolean isDeviceProvisioned() {
4151         return mDeviceProvisioned;
4152     }
4153 
getServiceState(int subId)4154     public ServiceState getServiceState(int subId) {
4155         return mServiceStates.get(subId);
4156     }
4157 
clearBiometricRecognized()4158     public void clearBiometricRecognized() {
4159         clearBiometricRecognized(UserHandle.USER_NULL);
4160     }
4161 
clearBiometricRecognizedWhenKeyguardDone(int unlockedUser)4162     public void clearBiometricRecognizedWhenKeyguardDone(int unlockedUser) {
4163         clearBiometricRecognized(unlockedUser);
4164     }
4165 
clearBiometricRecognized(int unlockedUser)4166     private void clearBiometricRecognized(int unlockedUser) {
4167         Assert.isMainThread();
4168         mUserFingerprintAuthenticated.clear();
4169         mUserFaceAuthenticated.clear();
4170         mTrustManager.clearAllBiometricRecognized(FINGERPRINT, unlockedUser);
4171         mTrustManager.clearAllBiometricRecognized(FACE, unlockedUser);
4172         mLogger.d("clearBiometricRecognized");
4173 
4174         for (int i = 0; i < mCallbacks.size(); i++) {
4175             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
4176             if (cb != null) {
4177                 cb.onBiometricsCleared();
4178             }
4179         }
4180     }
4181 
isSimPinVoiceSecure()4182     public boolean isSimPinVoiceSecure() {
4183         // TODO: only count SIMs that handle voice
4184         return isSimPinSecure();
4185     }
4186 
4187     /**
4188      * If any SIM cards are currently secure.
4189      *
4190      * @see #isSimPinSecure(int)
4191      */
isSimPinSecure()4192     public boolean isSimPinSecure() {
4193         // True if any SIM is pin secure
4194         for (SubscriptionInfo info : getSubscriptionInfo(false /* forceReload */)) {
4195             if (isSimPinSecure(getSimState(info.getSubscriptionId()))) return true;
4196         }
4197         return false;
4198     }
4199 
getSimState(int subId)4200     public int getSimState(int subId) {
4201         if (mSimDatas.containsKey(subId)) {
4202             return mSimDatas.get(subId).simState;
4203         } else {
4204             return TelephonyManager.SIM_STATE_UNKNOWN;
4205         }
4206     }
4207 
getSlotId(int subId)4208     private int getSlotId(int subId) {
4209         if (!mSimDatas.containsKey(subId)) {
4210             refreshSimState(subId, SubscriptionManager.getSlotIndex(subId));
4211         }
4212         return mSimDatas.get(subId).slotId;
4213     }
4214 
4215     private final TaskStackChangeListener mTaskStackListener = new TaskStackChangeListener() {
4216         @Override
4217         public void onTaskStackChangedBackground() {
4218             try {
4219                 if (mFeatureFlags.isEnabled(Flags.FP_LISTEN_OCCLUDING_APPS)) {
4220                     RootTaskInfo standardTask = mActivityTaskManager.getRootTaskInfo(
4221                             WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
4222                     final boolean previousState = mAllowFingerprintOnCurrentOccludingActivity;
4223                     mAllowFingerprintOnCurrentOccludingActivity =
4224                             standardTask != null && standardTask.topActivity != null
4225                                     && !TextUtils.isEmpty(standardTask.topActivity.getPackageName())
4226                                     && mAllowFingerprintOnOccludingActivitiesFromPackage.contains(
4227                                             standardTask.topActivity.getPackageName())
4228                                     && standardTask.visible;
4229                     if (mAllowFingerprintOnCurrentOccludingActivity != previousState) {
4230                         mLogger.allowFingerprintOnCurrentOccludingActivityChanged(
4231                                 mAllowFingerprintOnCurrentOccludingActivity);
4232                         updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE);
4233                     }
4234                 }
4235 
4236                 RootTaskInfo assistantTask = mActivityTaskManager.getRootTaskInfo(
4237                         WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_ASSISTANT);
4238                 if (assistantTask == null) {
4239                     return;
4240                 }
4241                 mLogger.logTaskStackChangedForAssistant(assistantTask.visible);
4242                 mHandler.sendMessage(mHandler.obtainMessage(MSG_ASSISTANT_STACK_CHANGED,
4243                         assistantTask.visible));
4244             } catch (RemoteException e) {
4245                 mLogger.logException(e, "unable to check task stack ");
4246             }
4247         }
4248     };
4249 
4250     /**
4251      * @return true if and only if the state has changed for the specified {@code slotId}
4252      */
refreshSimState(int subId, int slotId)4253     private boolean refreshSimState(int subId, int slotId) {
4254         int state = mTelephonyManager.getSimState(slotId);
4255         SimData data = mSimDatas.get(subId);
4256         final boolean changed;
4257         if (data == null) {
4258             data = new SimData(state, slotId, subId);
4259             mSimDatas.put(subId, data);
4260             changed = true; // no data yet; force update
4261         } else {
4262             changed = data.simState != state;
4263             data.simState = state;
4264         }
4265         return changed;
4266     }
4267 
4268     /**
4269      * If the {@code state} is currently requiring a SIM PIN, PUK, or is disabled.
4270      */
isSimPinSecure(int state)4271     public static boolean isSimPinSecure(int state) {
4272         return (state == TelephonyManager.SIM_STATE_PIN_REQUIRED
4273                 || state == TelephonyManager.SIM_STATE_PUK_REQUIRED
4274                 || state == TelephonyManager.SIM_STATE_PERM_DISABLED);
4275     }
4276 
4277     // TODO: use these callbacks elsewhere in place of the existing notifyScreen*()
4278     // (KeyguardViewMediator, KeyguardSecurityContainer)
4279     /**
4280      * Dispatch wakeup events to:
4281      *  - update biometric listening states
4282      *  - send to registered KeyguardUpdateMonitorCallbacks
4283      */
dispatchStartedWakingUp(@owerManager.WakeReason int pmWakeReason)4284     public void dispatchStartedWakingUp(@PowerManager.WakeReason int pmWakeReason) {
4285         synchronized (this) {
4286             mDeviceInteractive = true;
4287         }
4288         mHandler.sendMessage(mHandler.obtainMessage(MSG_STARTED_WAKING_UP, pmWakeReason, 0));
4289     }
4290 
dispatchStartedGoingToSleep(int why)4291     public void dispatchStartedGoingToSleep(int why) {
4292         mHandler.sendMessage(mHandler.obtainMessage(MSG_STARTED_GOING_TO_SLEEP, why, 0));
4293     }
4294 
dispatchFinishedGoingToSleep(int why)4295     public void dispatchFinishedGoingToSleep(int why) {
4296         synchronized (this) {
4297             mDeviceInteractive = false;
4298         }
4299         mHandler.sendMessage(mHandler.obtainMessage(MSG_FINISHED_GOING_TO_SLEEP, why, 0));
4300     }
4301 
dispatchScreenTurnedOff()4302     public void dispatchScreenTurnedOff() {
4303         mHandler.sendEmptyMessage(MSG_SCREEN_TURNED_OFF);
4304     }
4305 
dispatchDreamingStarted()4306     public void dispatchDreamingStarted() {
4307         mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 1, 0));
4308     }
4309 
dispatchDreamingStopped()4310     public void dispatchDreamingStopped() {
4311         mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 0, 0));
4312     }
4313 
4314     /**
4315      * Sends a message to update the keyguard going away state on the main thread.
4316      *
4317      * @param goingAway Whether the keyguard is going away.
4318      */
dispatchKeyguardGoingAway(boolean goingAway)4319     public void dispatchKeyguardGoingAway(boolean goingAway) {
4320         mHandler.sendMessage(mHandler.obtainMessage(MSG_KEYGUARD_GOING_AWAY, goingAway));
4321     }
4322 
4323     /**
4324      * Sends a message to notify the keyguard dismiss animation is finished.
4325      */
dispatchKeyguardDismissAnimationFinished()4326     public void dispatchKeyguardDismissAnimationFinished() {
4327         mHandler.sendEmptyMessage(MSG_KEYGUARD_DISMISS_ANIMATION_FINISHED);
4328     }
4329 
4330     /**
4331      * @return true when the screen is on (including when a screensaver is showing),
4332      * false when the screen is OFF or DOZE (including showing AOD UI)
4333      */
isDeviceInteractive()4334     public boolean isDeviceInteractive() {
4335         return mDeviceInteractive;
4336     }
4337 
isGoingToSleep()4338     public boolean isGoingToSleep() {
4339         return mGoingToSleep;
4340     }
4341 
4342     /**
4343      * Find the next SubscriptionId for a SIM in the given state, favoring lower slot numbers first.
4344      *
4345      * @return subid or {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID} if none found
4346      */
getNextSubIdForState(int state)4347     public int getNextSubIdForState(int state) {
4348         List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */);
4349         int resultId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
4350         int bestSlotId = Integer.MAX_VALUE; // Favor lowest slot first
4351         for (int i = 0; i < list.size(); i++) {
4352             final SubscriptionInfo info = list.get(i);
4353             final int id = info.getSubscriptionId();
4354             int slotId = getSlotId(id);
4355             if (state == getSimState(id) && bestSlotId > slotId) {
4356                 resultId = id;
4357                 bestSlotId = slotId;
4358             }
4359         }
4360         return resultId;
4361     }
4362 
getSubscriptionInfoForSubId(int subId)4363     public SubscriptionInfo getSubscriptionInfoForSubId(int subId) {
4364         List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */);
4365         for (int i = 0; i < list.size(); i++) {
4366             SubscriptionInfo info = list.get(i);
4367             if (subId == info.getSubscriptionId()) return info;
4368         }
4369         return null; // not found
4370     }
4371 
4372     /**
4373      * @return a cached version of DevicePolicyManager.isLogoutEnabled()
4374      */
isLogoutEnabled()4375     public boolean isLogoutEnabled() {
4376         return mLogoutEnabled;
4377     }
4378 
updateLogoutEnabled()4379     private void updateLogoutEnabled() {
4380         Assert.isMainThread();
4381         boolean logoutEnabled = mDevicePolicyManager.isLogoutEnabled();
4382         if (mLogoutEnabled != logoutEnabled) {
4383             mLogoutEnabled = logoutEnabled;
4384 
4385             for (int i = 0; i < mCallbacks.size(); i++) {
4386                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
4387                 if (cb != null) {
4388                     cb.onLogoutEnabledChanged();
4389                 }
4390             }
4391         }
4392     }
4393 
getBiometricLockoutDelay()4394     protected int getBiometricLockoutDelay() {
4395         return BIOMETRIC_LOCKOUT_RESET_DELAY_MS;
4396     }
4397 
4398     @VisibleForTesting
isFingerprintClass3()4399     protected boolean isFingerprintClass3() {
4400         // This assumes that there is at most one fingerprint sensor property
4401         return isFingerprintSupported() && isClass3Biometric(mFingerprintSensorProperties.get(0));
4402     }
4403 
4404     @VisibleForTesting
isFaceClass3()4405     protected boolean isFaceClass3() {
4406         // This assumes that there is at most one face sensor property
4407         return isFaceSupported() && isClass3Biometric(mFaceSensorProperties.get(0));
4408     }
4409 
isClass3Biometric(SensorPropertiesInternal sensorProperties)4410     private boolean isClass3Biometric(SensorPropertiesInternal sensorProperties) {
4411         return sensorProperties.sensorStrength == SensorProperties.STRENGTH_STRONG;
4412     }
4413 
4414     /**
4415      * Unregister all listeners.
4416      */
destroy()4417     public void destroy() {
4418         mStatusBarStateController.removeCallback(mStatusBarStateControllerListener);
4419         mTelephonyListenerManager.removeActiveDataSubscriptionIdListener(mPhoneStateListener);
4420         mSubscriptionManager.removeOnSubscriptionsChangedListener(mSubscriptionListener);
4421         if (isFaceAuthInteractorEnabled()) {
4422             mFaceAuthInteractor.unregisterListener(mFaceAuthenticationListener);
4423         }
4424 
4425         if (mDeviceProvisionedObserver != null) {
4426             mContext.getContentResolver().unregisterContentObserver(mDeviceProvisionedObserver);
4427         }
4428 
4429         if (mTimeFormatChangeObserver != null) {
4430             mContext.getContentResolver().unregisterContentObserver(mTimeFormatChangeObserver);
4431         }
4432 
4433         mUserTracker.removeCallback(mUserChangedCallback);
4434 
4435         mTaskStackChangeListeners.unregisterTaskStackListener(mTaskStackListener);
4436 
4437         mBroadcastDispatcher.unregisterReceiver(mBroadcastReceiver);
4438         mBroadcastDispatcher.unregisterReceiver(mBroadcastAllReceiver);
4439 
4440         mLockPatternUtils.unregisterStrongAuthTracker(mStrongAuthTracker);
4441         mTrustManager.unregisterTrustListener(this);
4442         mDisplayTracker.removeCallback(mDisplayCallback);
4443 
4444         mHandler.removeCallbacksAndMessages(null);
4445     }
4446 
4447     @SuppressLint("MissingPermission")
4448     @Override
dump(@onNull PrintWriter pw, @NonNull String[] args)4449     public void dump(@NonNull PrintWriter pw, @NonNull String[] args) {
4450         pw.println("KeyguardUpdateMonitor state:");
4451         pw.println("  getUserHasTrust()=" + getUserHasTrust(getCurrentUser()));
4452         pw.println("  getUserUnlockedWithBiometric()="
4453                 + getUserUnlockedWithBiometric(getCurrentUser()));
4454         pw.println("  isFaceAuthInteractorEnabled: " + isFaceAuthInteractorEnabled());
4455         pw.println("  SIM States:");
4456         for (SimData data : mSimDatas.values()) {
4457             pw.println("    " + data.toString());
4458         }
4459         pw.println("  Subs:");
4460         if (mSubscriptionInfo != null) {
4461             for (int i = 0; i < mSubscriptionInfo.size(); i++) {
4462                 pw.println("    " + mSubscriptionInfo.get(i));
4463             }
4464         }
4465         pw.println("  Current active data subId=" + mActiveMobileDataSubscription);
4466         pw.println("  Service states:");
4467         for (int subId : mServiceStates.keySet()) {
4468             pw.println("    " + subId + "=" + mServiceStates.get(subId));
4469         }
4470         if (isFingerprintSupported()) {
4471             final int userId = mUserTracker.getUserId();
4472             final int strongAuthFlags = mStrongAuthTracker.getStrongAuthForUser(userId);
4473             BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(userId);
4474             pw.println("  Fingerprint state (user=" + userId + ")");
4475             pw.println("    isFingerprintClass3=" + isFingerprintClass3());
4476             pw.println("    areAllFpAuthenticatorsRegistered="
4477                     + mAuthController.areAllFingerprintAuthenticatorsRegistered());
4478             pw.println("    allowed="
4479                     + (fingerprint != null
4480                             && isUnlockingWithBiometricAllowed(fingerprint.mIsStrongBiometric)));
4481             pw.println("    auth'd=" + (fingerprint != null && fingerprint.mAuthenticated));
4482             pw.println("    authSinceBoot="
4483                     + getStrongAuthTracker().hasUserAuthenticatedSinceBoot());
4484             pw.println("    disabled(DPM)=" + isFingerprintDisabled(userId));
4485             pw.println("    possible=" + isUnlockWithFingerprintPossible(userId));
4486             pw.println("    listening: actual=" + mFingerprintRunningState
4487                     + " expected=" + (shouldListenForFingerprint(isUdfpsEnrolled()) ? 1 : 0));
4488             pw.println("    strongAuthFlags=" + Integer.toHexString(strongAuthFlags));
4489             pw.println("    trustManaged=" + getUserTrustIsManaged(userId));
4490             pw.println("    mFingerprintLockedOut=" + mFingerprintLockedOut);
4491             pw.println("    mFingerprintLockedOutPermanent=" + mFingerprintLockedOutPermanent);
4492             pw.println("    enabledByUser=" + mBiometricEnabledForUser.get(userId));
4493             pw.println("    mKeyguardOccluded=" + mKeyguardOccluded);
4494             pw.println("    mIsDreaming=" + mIsDreaming);
4495             pw.println("    mFingerprintListenOnOccludingActivitiesFromPackage="
4496                     + mAllowFingerprintOnOccludingActivitiesFromPackage);
4497             if (isUdfpsSupported()) {
4498                 pw.println("        udfpsEnrolled=" + isUdfpsEnrolled());
4499                 pw.println("        shouldListenForUdfps=" + shouldListenForFingerprint(true));
4500                 pw.println("        mPrimaryBouncerIsOrWillBeShowing="
4501                         + mPrimaryBouncerIsOrWillBeShowing);
4502                 pw.println("        mStatusBarState=" + StatusBarState.toString(mStatusBarState));
4503                 pw.println("        mAlternateBouncerShowing=" + mAlternateBouncerShowing);
4504             } else if (isSfpsSupported()) {
4505                 pw.println("        sfpsEnrolled=" + isSfpsEnrolled());
4506                 pw.println("        shouldListenForSfps=" + shouldListenForFingerprint(false));
4507                 if (isSfpsEnrolled()) {
4508                     final boolean interactiveToAuthEnabled =
4509                                     mFingerprintInteractiveToAuthProvider != null &&
4510                                             mFingerprintInteractiveToAuthProvider
4511                                             .isEnabled(getCurrentUser());
4512                     pw.println("        interactiveToAuthEnabled="
4513                             + interactiveToAuthEnabled);
4514                 }
4515             }
4516             new DumpsysTableLogger(
4517                     "KeyguardFingerprintListen",
4518                     KeyguardFingerprintListenModel.TABLE_HEADERS,
4519                     mFingerprintListenBuffer.toList()
4520             ).printTableData(pw);
4521         } else if (mFpm != null && mFingerprintSensorProperties.isEmpty()) {
4522             final int userId = mUserTracker.getUserId();
4523             pw.println("  Fingerprint state (user=" + userId + ")");
4524             pw.println("    mFingerprintSensorProperties.isEmpty="
4525                     + mFingerprintSensorProperties.isEmpty());
4526             pw.println("    mFpm.isHardwareDetected="
4527                     + mFpm.isHardwareDetected());
4528 
4529             new DumpsysTableLogger(
4530                     "KeyguardFingerprintListen",
4531                     KeyguardFingerprintListenModel.TABLE_HEADERS,
4532                     mFingerprintListenBuffer.toList()
4533             ).printTableData(pw);
4534         }
4535         if (isFaceSupported()) {
4536             final int userId = mUserTracker.getUserId();
4537             final int strongAuthFlags = mStrongAuthTracker.getStrongAuthForUser(userId);
4538             BiometricAuthenticated face = mUserFaceAuthenticated.get(userId);
4539             pw.println("  Face authentication state (user=" + userId + ")");
4540             pw.println("    isFaceClass3=" + isFaceClass3());
4541             pw.println("    allowed="
4542                     + (face != null && isUnlockingWithBiometricAllowed(face.mIsStrongBiometric)));
4543             pw.println("    auth'd="
4544                     + (face != null && face.mAuthenticated));
4545             pw.println("    authSinceBoot="
4546                     + getStrongAuthTracker().hasUserAuthenticatedSinceBoot());
4547             pw.println("    disabled(DPM)=" + isFaceDisabled(userId));
4548             pw.println("    possible=" + isUnlockWithFacePossible(userId));
4549             pw.println("    listening: actual=" + mFaceRunningState
4550                     + " expected=(" + (shouldListenForFace() ? 1 : 0));
4551             pw.println("    strongAuthFlags=" + Integer.toHexString(strongAuthFlags));
4552             pw.println("    isNonStrongBiometricAllowedAfterIdleTimeout="
4553                     + mStrongAuthTracker.isNonStrongBiometricAllowedAfterIdleTimeout(userId));
4554             pw.println("    trustManaged=" + getUserTrustIsManaged(userId));
4555             pw.println("    mFaceLockedOutPermanent=" + mFaceLockedOutPermanent);
4556             pw.println("    enabledByUser=" + mBiometricEnabledForUser.get(userId));
4557             pw.println("    mSecureCameraLaunched=" + mSecureCameraLaunched);
4558             pw.println("    mPrimaryBouncerFullyShown=" + mPrimaryBouncerFullyShown);
4559             pw.println("    mNeedsSlowUnlockTransition=" + mNeedsSlowUnlockTransition);
4560             new DumpsysTableLogger(
4561                     "KeyguardFaceListen",
4562                     KeyguardFaceListenModel.TABLE_HEADERS,
4563                     mFaceListenBuffer.toList()
4564             ).printTableData(pw);
4565         } else if (mFaceManager != null && mFaceSensorProperties.isEmpty()) {
4566             final int userId = mUserTracker.getUserId();
4567             pw.println("  Face state (user=" + userId + ")");
4568             pw.println("    mFaceSensorProperties.isEmpty="
4569                     + mFaceSensorProperties.isEmpty());
4570             pw.println("    mFaceManager.isHardwareDetected="
4571                     + mFaceManager.isHardwareDetected());
4572 
4573             new DumpsysTableLogger(
4574                     "KeyguardFaceListen",
4575                     KeyguardFingerprintListenModel.TABLE_HEADERS,
4576                     mFingerprintListenBuffer.toList()
4577             ).printTableData(pw);
4578         }
4579         pw.println("ActiveUnlockRunning="
4580                 + mTrustManager.isActiveUnlockRunning(KeyguardUpdateMonitor.getCurrentUser()));
4581         new DumpsysTableLogger(
4582                 "KeyguardActiveUnlockTriggers",
4583                 KeyguardActiveUnlockModel.TABLE_HEADERS,
4584                 mActiveUnlockTriggerBuffer.toList()
4585         ).printTableData(pw);
4586     }
4587 
4588     /**
4589      * Schedules a watchdog for the face and fingerprint BiometricScheduler.
4590      * Cancels all operations in the scheduler if it is hung for 10 seconds.
4591      */
startBiometricWatchdog()4592     public void startBiometricWatchdog() {
4593         final boolean isFaceAuthInteractorEnabled = isFaceAuthInteractorEnabled();
4594         mBackgroundExecutor.execute(() -> {
4595             Trace.beginSection("#startBiometricWatchdog");
4596             if (mFaceManager != null && !isFaceAuthInteractorEnabled) {
4597                 mLogger.scheduleWatchdog("face");
4598                 mFaceManager.scheduleWatchdog();
4599             }
4600             if (mFpm != null) {
4601                 mLogger.scheduleWatchdog("fingerprint");
4602                 mFpm.scheduleWatchdog();
4603             }
4604             Trace.endSection();
4605         });
4606     }
4607 }
4608