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