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