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