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.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT; 20 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; 21 import static android.content.Intent.ACTION_USER_REMOVED; 22 import static android.content.Intent.ACTION_USER_STOPPED; 23 import static android.content.Intent.ACTION_USER_UNLOCKED; 24 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN; 25 import static android.telephony.PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE; 26 27 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_BOOT; 28 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW; 29 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT; 30 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_TIMEOUT; 31 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN; 32 import static com.android.systemui.DejankUtils.whitelistIpcs; 33 34 import android.annotation.AnyThread; 35 import android.annotation.MainThread; 36 import android.annotation.NonNull; 37 import android.app.ActivityManager; 38 import android.app.ActivityTaskManager; 39 import android.app.AlarmManager; 40 import android.app.PendingIntent; 41 import android.app.UserSwitchObserver; 42 import android.app.admin.DevicePolicyManager; 43 import android.app.trust.TrustManager; 44 import android.content.BroadcastReceiver; 45 import android.content.ComponentName; 46 import android.content.Context; 47 import android.content.Intent; 48 import android.content.IntentFilter; 49 import android.content.pm.IPackageManager; 50 import android.content.pm.PackageManager; 51 import android.content.pm.ResolveInfo; 52 import android.content.pm.UserInfo; 53 import android.database.ContentObserver; 54 import android.hardware.biometrics.BiometricManager; 55 import android.hardware.biometrics.BiometricSourceType; 56 import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback; 57 import android.hardware.face.FaceManager; 58 import android.hardware.fingerprint.FingerprintManager; 59 import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback; 60 import android.hardware.fingerprint.FingerprintManager.AuthenticationResult; 61 import android.os.Build; 62 import android.os.CancellationSignal; 63 import android.os.Handler; 64 import android.os.IRemoteCallback; 65 import android.os.Looper; 66 import android.os.Message; 67 import android.os.RemoteException; 68 import android.os.ServiceManager; 69 import android.os.Trace; 70 import android.os.UserHandle; 71 import android.os.UserManager; 72 import android.provider.Settings; 73 import android.service.dreams.DreamService; 74 import android.service.dreams.IDreamManager; 75 import android.telephony.CarrierConfigManager; 76 import android.telephony.PhoneStateListener; 77 import android.telephony.ServiceState; 78 import android.telephony.SubscriptionInfo; 79 import android.telephony.SubscriptionManager; 80 import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener; 81 import android.telephony.TelephonyManager; 82 import android.util.Log; 83 import android.util.SparseArray; 84 import android.util.SparseBooleanArray; 85 86 import androidx.lifecycle.Observer; 87 88 import com.android.internal.annotations.VisibleForTesting; 89 import com.android.internal.widget.LockPatternUtils; 90 import com.android.settingslib.WirelessUtils; 91 import com.android.settingslib.fuelgauge.BatteryStatus; 92 import com.android.systemui.DejankUtils; 93 import com.android.systemui.Dumpable; 94 import com.android.systemui.R; 95 import com.android.systemui.broadcast.BroadcastDispatcher; 96 import com.android.systemui.dagger.qualifiers.Background; 97 import com.android.systemui.dagger.qualifiers.Main; 98 import com.android.systemui.dump.DumpManager; 99 import com.android.systemui.plugins.statusbar.StatusBarStateController; 100 import com.android.systemui.shared.system.ActivityManagerWrapper; 101 import com.android.systemui.shared.system.TaskStackChangeListener; 102 import com.android.systemui.statusbar.StatusBarState; 103 import com.android.systemui.statusbar.phone.KeyguardBypassController; 104 import com.android.systemui.util.Assert; 105 import com.android.systemui.util.RingerModeTracker; 106 107 import com.google.android.collect.Lists; 108 109 import java.io.FileDescriptor; 110 import java.io.PrintWriter; 111 import java.lang.ref.WeakReference; 112 import java.text.SimpleDateFormat; 113 import java.util.ArrayDeque; 114 import java.util.ArrayList; 115 import java.util.Date; 116 import java.util.HashMap; 117 import java.util.List; 118 import java.util.Locale; 119 import java.util.Map; 120 import java.util.Map.Entry; 121 import java.util.TimeZone; 122 import java.util.concurrent.Executor; 123 import java.util.function.Consumer; 124 125 import javax.inject.Inject; 126 import javax.inject.Singleton; 127 128 /** 129 * Watches for updates that may be interesting to the keyguard, and provides 130 * the up to date information as well as a registration for callbacks that care 131 * to be updated. 132 */ 133 @Singleton 134 public class KeyguardUpdateMonitor implements TrustManager.TrustListener, Dumpable { 135 136 private static final String TAG = "KeyguardUpdateMonitor"; 137 private static final boolean DEBUG = KeyguardConstants.DEBUG; 138 private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES; 139 private static final boolean DEBUG_FACE = Build.IS_DEBUGGABLE; 140 private static final boolean DEBUG_SPEW = false; 141 private static final int LOW_BATTERY_THRESHOLD = 20; 142 143 private static final String ACTION_FACE_UNLOCK_STARTED 144 = "com.android.facelock.FACE_UNLOCK_STARTED"; 145 private static final String ACTION_FACE_UNLOCK_STOPPED 146 = "com.android.facelock.FACE_UNLOCK_STOPPED"; 147 148 // Callback messages 149 private static final int MSG_TIME_UPDATE = 301; 150 private static final int MSG_BATTERY_UPDATE = 302; 151 private static final int MSG_SIM_STATE_CHANGE = 304; 152 private static final int MSG_RINGER_MODE_CHANGED = 305; 153 private static final int MSG_PHONE_STATE_CHANGED = 306; 154 private static final int MSG_DEVICE_PROVISIONED = 308; 155 private static final int MSG_DPM_STATE_CHANGED = 309; 156 private static final int MSG_USER_SWITCHING = 310; 157 private static final int MSG_KEYGUARD_RESET = 312; 158 private static final int MSG_USER_SWITCH_COMPLETE = 314; 159 private static final int MSG_USER_INFO_CHANGED = 317; 160 private static final int MSG_REPORT_EMERGENCY_CALL_ACTION = 318; 161 private static final int MSG_STARTED_WAKING_UP = 319; 162 private static final int MSG_FINISHED_GOING_TO_SLEEP = 320; 163 private static final int MSG_STARTED_GOING_TO_SLEEP = 321; 164 private static final int MSG_KEYGUARD_BOUNCER_CHANGED = 322; 165 private static final int MSG_FACE_UNLOCK_STATE_CHANGED = 327; 166 private static final int MSG_SIM_SUBSCRIPTION_INFO_CHANGED = 328; 167 private static final int MSG_AIRPLANE_MODE_CHANGED = 329; 168 private static final int MSG_SERVICE_STATE_CHANGE = 330; 169 private static final int MSG_SCREEN_TURNED_ON = 331; 170 private static final int MSG_SCREEN_TURNED_OFF = 332; 171 private static final int MSG_DREAMING_STATE_CHANGED = 333; 172 private static final int MSG_USER_UNLOCKED = 334; 173 private static final int MSG_ASSISTANT_STACK_CHANGED = 335; 174 private static final int MSG_BIOMETRIC_AUTHENTICATION_CONTINUE = 336; 175 private static final int MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED = 337; 176 private static final int MSG_TELEPHONY_CAPABLE = 338; 177 private static final int MSG_TIMEZONE_UPDATE = 339; 178 private static final int MSG_USER_STOPPED = 340; 179 private static final int MSG_USER_REMOVED = 341; 180 private static final int MSG_KEYGUARD_GOING_AWAY = 342; 181 182 /** Biometric authentication state: Not listening. */ 183 private static final int BIOMETRIC_STATE_STOPPED = 0; 184 185 /** Biometric authentication state: Listening. */ 186 private static final int BIOMETRIC_STATE_RUNNING = 1; 187 188 /** 189 * Biometric authentication: Cancelling and waiting for the relevant biometric service to 190 * send us the confirmation that cancellation has happened. 191 */ 192 private static final int BIOMETRIC_STATE_CANCELLING = 2; 193 194 /** 195 * Biometric state: During cancelling we got another request to start listening, so when we 196 * receive the cancellation done signal, we should start listening again. 197 */ 198 private static final int BIOMETRIC_STATE_CANCELLING_RESTARTING = 3; 199 200 private static final int BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED = -1; 201 public static final int BIOMETRIC_HELP_FACE_NOT_RECOGNIZED = -2; 202 203 private static final int DEFAULT_CHARGING_VOLTAGE_MICRO_VOLT = 5000000; 204 /** 205 * If no cancel signal has been received after this amount of time, set the biometric running 206 * state to stopped to allow Keyguard to retry authentication. 207 */ 208 private static final int DEFAULT_CANCEL_SIGNAL_TIMEOUT = 3000; 209 210 private static final ComponentName FALLBACK_HOME_COMPONENT = new ComponentName( 211 "com.android.settings", "com.android.settings.FallbackHome"); 212 213 214 /** 215 * If true, the system is in the half-boot-to-decryption-screen state. 216 * Prudently disable lockscreen. 217 */ 218 public static final boolean CORE_APPS_ONLY; 219 220 static { 221 try { 222 CORE_APPS_ONLY = IPackageManager.Stub.asInterface( 223 ServiceManager.getService("package")).isOnlyCoreApps(); 224 } catch (RemoteException e) { 225 throw e.rethrowFromSystemServer(); 226 } 227 } 228 229 private final Context mContext; 230 private final boolean mIsPrimaryUser; 231 private final boolean mIsAutomotive; 232 private final StatusBarStateController mStatusBarStateController; 233 HashMap<Integer, SimData> mSimDatas = new HashMap<>(); 234 HashMap<Integer, ServiceState> mServiceStates = new HashMap<Integer, ServiceState>(); 235 236 private int mRingMode; 237 private int mPhoneState; 238 private boolean mKeyguardIsVisible; 239 private boolean mCredentialAttempted; 240 private boolean mKeyguardGoingAway; 241 private boolean mGoingToSleep; 242 private boolean mBouncer; 243 private boolean mAuthInterruptActive; 244 private boolean mNeedsSlowUnlockTransition; 245 private boolean mHasLockscreenWallpaper; 246 private boolean mAssistantVisible; 247 private boolean mKeyguardOccluded; 248 private boolean mSecureCameraLaunched; 249 @VisibleForTesting 250 protected boolean mTelephonyCapable; 251 252 // Device provisioning state 253 private boolean mDeviceProvisioned; 254 255 // Battery status 256 @VisibleForTesting 257 BatteryStatus mBatteryStatus; 258 259 private StrongAuthTracker mStrongAuthTracker; 260 261 private final ArrayList<WeakReference<KeyguardUpdateMonitorCallback>> 262 mCallbacks = Lists.newArrayList(); 263 private ContentObserver mDeviceProvisionedObserver; 264 265 private boolean mSwitchingUser; 266 267 private boolean mDeviceInteractive; 268 private boolean mScreenOn; 269 private SubscriptionManager mSubscriptionManager; 270 private List<SubscriptionInfo> mSubscriptionInfo; 271 private TrustManager mTrustManager; 272 private UserManager mUserManager; 273 private KeyguardBypassController mKeyguardBypassController; 274 private RingerModeTracker mRingerModeTracker; 275 private int mFingerprintRunningState = BIOMETRIC_STATE_STOPPED; 276 private int mFaceRunningState = BIOMETRIC_STATE_STOPPED; 277 private LockPatternUtils mLockPatternUtils; 278 private final IDreamManager mDreamManager; 279 private boolean mIsDreaming; 280 private final DevicePolicyManager mDevicePolicyManager; 281 private final BroadcastDispatcher mBroadcastDispatcher; 282 private boolean mLogoutEnabled; 283 // If the user long pressed the lock icon, disabling face auth for the current session. 284 private boolean mLockIconPressed; 285 private int mActiveMobileDataSubscription = SubscriptionManager.INVALID_SUBSCRIPTION_ID; 286 private final Executor mBackgroundExecutor; 287 288 /** 289 * Short delay before restarting biometric authentication after a successful try 290 * This should be slightly longer than the time between on<biometric>Authenticated 291 * (e.g. onFingerprintAuthenticated) and setKeyguardGoingAway(true). 292 */ 293 private static final int BIOMETRIC_CONTINUE_DELAY_MS = 500; 294 295 // If the HAL dies or is unable to authenticate, keyguard should retry after a short delay 296 private int mHardwareFingerprintUnavailableRetryCount = 0; 297 private int mHardwareFaceUnavailableRetryCount = 0; 298 private static final int HAL_ERROR_RETRY_TIMEOUT = 500; // ms 299 private static final int HAL_ERROR_RETRY_MAX = 10; 300 301 private final Runnable mCancelNotReceived = new Runnable() { 302 @Override 303 public void run() { 304 Log.w(TAG, "Cancel not received, transitioning to STOPPED"); 305 mFingerprintRunningState = mFaceRunningState = BIOMETRIC_STATE_STOPPED; 306 updateBiometricListeningState(); 307 } 308 }; 309 310 private final Handler mHandler; 311 312 private final Observer<Integer> mRingerModeObserver = new Observer<Integer>() { 313 @Override 314 public void onChanged(Integer ringer) { 315 mHandler.obtainMessage(MSG_RINGER_MODE_CHANGED, ringer, 0).sendToTarget(); 316 } 317 }; 318 319 private SparseBooleanArray mFaceSettingEnabledForUser = new SparseBooleanArray(); 320 private BiometricManager mBiometricManager; 321 private IBiometricEnabledOnKeyguardCallback mBiometricEnabledCallback = 322 new IBiometricEnabledOnKeyguardCallback.Stub() { 323 @Override 324 public void onChanged(BiometricSourceType type, boolean enabled, int userId) 325 throws RemoteException { 326 if (type == BiometricSourceType.FACE) { 327 mFaceSettingEnabledForUser.put(userId, enabled); 328 updateFaceListeningState(); 329 } 330 } 331 }; 332 333 @VisibleForTesting 334 public PhoneStateListener mPhoneStateListener = new PhoneStateListener() { 335 @Override 336 public void onActiveDataSubscriptionIdChanged(int subId) { 337 mActiveMobileDataSubscription = subId; 338 mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED); 339 } 340 }; 341 342 private OnSubscriptionsChangedListener mSubscriptionListener = 343 new OnSubscriptionsChangedListener() { 344 @Override 345 public void onSubscriptionsChanged() { 346 mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED); 347 } 348 }; 349 350 @VisibleForTesting 351 static class BiometricAuthenticated { 352 private final boolean mAuthenticated; 353 private final boolean mIsStrongBiometric; 354 BiometricAuthenticated(boolean authenticated, boolean isStrongBiometric)355 BiometricAuthenticated(boolean authenticated, boolean isStrongBiometric) { 356 this.mAuthenticated = authenticated; 357 this.mIsStrongBiometric = isStrongBiometric; 358 } 359 } 360 361 private SparseBooleanArray mUserIsUnlocked = new SparseBooleanArray(); 362 private SparseBooleanArray mUserHasTrust = new SparseBooleanArray(); 363 private SparseBooleanArray mUserTrustIsManaged = new SparseBooleanArray(); 364 private SparseBooleanArray mUserTrustIsUsuallyManaged = new SparseBooleanArray(); 365 private SparseBooleanArray mUserFaceUnlockRunning = new SparseBooleanArray(); 366 private Map<Integer, Intent> mSecondaryLockscreenRequirement = new HashMap<Integer, Intent>(); 367 368 @VisibleForTesting 369 SparseArray<BiometricAuthenticated> mUserFingerprintAuthenticated = new SparseArray<>(); 370 @VisibleForTesting 371 SparseArray<BiometricAuthenticated> mUserFaceAuthenticated = new SparseArray<>(); 372 373 // Keep track of recent calls to shouldListenForFace() for debugging. 374 private static final int FACE_LISTEN_CALLS_QUEUE_SIZE = 20; 375 private ArrayDeque<KeyguardFaceListenModel> mFaceListenModels; 376 377 private static int sCurrentUser; 378 private Runnable mUpdateBiometricListeningState = this::updateBiometricListeningState; 379 setCurrentUser(int currentUser)380 public synchronized static void setCurrentUser(int currentUser) { 381 sCurrentUser = currentUser; 382 } 383 getCurrentUser()384 public synchronized static int getCurrentUser() { 385 return sCurrentUser; 386 } 387 388 @Override onTrustChanged(boolean enabled, int userId, int flags)389 public void onTrustChanged(boolean enabled, int userId, int flags) { 390 Assert.isMainThread(); 391 mUserHasTrust.put(userId, enabled); 392 for (int i = 0; i < mCallbacks.size(); i++) { 393 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 394 if (cb != null) { 395 cb.onTrustChanged(userId); 396 if (enabled && flags != 0) { 397 cb.onTrustGrantedWithFlags(flags, userId); 398 } 399 } 400 } 401 } 402 403 @Override onTrustError(CharSequence message)404 public void onTrustError(CharSequence message) { 405 dispatchErrorMessage(message); 406 } 407 handleSimSubscriptionInfoChanged()408 private void handleSimSubscriptionInfoChanged() { 409 Assert.isMainThread(); 410 if (DEBUG_SIM_STATES) { 411 Log.v(TAG, "onSubscriptionInfoChanged()"); 412 List<SubscriptionInfo> sil = mSubscriptionManager 413 .getCompleteActiveSubscriptionInfoList(); 414 if (sil != null) { 415 for (SubscriptionInfo subInfo : sil) { 416 Log.v(TAG, "SubInfo:" + subInfo); 417 } 418 } else { 419 Log.v(TAG, "onSubscriptionInfoChanged: list is null"); 420 } 421 } 422 List<SubscriptionInfo> subscriptionInfos = getSubscriptionInfo(true /* forceReload */); 423 424 // Hack level over 9000: Because the subscription id is not yet valid when we see the 425 // first update in handleSimStateChange, we need to force refresh all all SIM states 426 // so the subscription id for them is consistent. 427 ArrayList<SubscriptionInfo> changedSubscriptions = new ArrayList<>(); 428 for (int i = 0; i < subscriptionInfos.size(); i++) { 429 SubscriptionInfo info = subscriptionInfos.get(i); 430 boolean changed = refreshSimState(info.getSubscriptionId(), info.getSimSlotIndex()); 431 if (changed) { 432 changedSubscriptions.add(info); 433 } 434 } 435 for (int i = 0; i < changedSubscriptions.size(); i++) { 436 SimData data = mSimDatas.get(changedSubscriptions.get(i).getSubscriptionId()); 437 for (int j = 0; j < mCallbacks.size(); j++) { 438 KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get(); 439 if (cb != null) { 440 cb.onSimStateChanged(data.subId, data.slotId, data.simState); 441 } 442 } 443 } 444 callbacksRefreshCarrierInfo(); 445 } 446 handleAirplaneModeChanged()447 private void handleAirplaneModeChanged() { 448 callbacksRefreshCarrierInfo(); 449 } 450 callbacksRefreshCarrierInfo()451 private void callbacksRefreshCarrierInfo() { 452 Assert.isMainThread(); 453 for (int i = 0; i < mCallbacks.size(); i++) { 454 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 455 if (cb != null) { 456 cb.onRefreshCarrierInfo(); 457 } 458 } 459 } 460 461 /** 462 * @return List of SubscriptionInfo records, maybe empty but never null. 463 */ getSubscriptionInfo(boolean forceReload)464 public List<SubscriptionInfo> getSubscriptionInfo(boolean forceReload) { 465 List<SubscriptionInfo> sil = mSubscriptionInfo; 466 if (sil == null || forceReload) { 467 sil = mSubscriptionManager.getCompleteActiveSubscriptionInfoList(); 468 } 469 if (sil == null) { 470 // getCompleteActiveSubscriptionInfoList was null callers expect an empty list. 471 mSubscriptionInfo = new ArrayList<SubscriptionInfo>(); 472 } else { 473 mSubscriptionInfo = sil; 474 } 475 return new ArrayList<>(mSubscriptionInfo); 476 } 477 478 /** 479 * This method returns filtered list of SubscriptionInfo from {@link #getSubscriptionInfo}. 480 * above. Maybe empty but never null. 481 * 482 * In DSDS mode if both subscriptions are grouped and one is opportunistic, we filter out one 483 * of them based on carrier config. e.g. In this case we should only show one carrier name 484 * on the status bar and quick settings. 485 */ getFilteredSubscriptionInfo(boolean forceReload)486 public List<SubscriptionInfo> getFilteredSubscriptionInfo(boolean forceReload) { 487 List<SubscriptionInfo> subscriptions = getSubscriptionInfo(false); 488 if (subscriptions.size() == 2) { 489 SubscriptionInfo info1 = subscriptions.get(0); 490 SubscriptionInfo info2 = subscriptions.get(1); 491 if (info1.getGroupUuid() != null && info1.getGroupUuid().equals(info2.getGroupUuid())) { 492 // If both subscriptions are primary, show both. 493 if (!info1.isOpportunistic() && !info2.isOpportunistic()) return subscriptions; 494 495 // If carrier required, always show signal bar of primary subscription. 496 // Otherwise, show whichever subscription is currently active for Internet. 497 boolean alwaysShowPrimary = CarrierConfigManager.getDefaultConfig() 498 .getBoolean(CarrierConfigManager 499 .KEY_ALWAYS_SHOW_PRIMARY_SIGNAL_BAR_IN_OPPORTUNISTIC_NETWORK_BOOLEAN); 500 if (alwaysShowPrimary) { 501 subscriptions.remove(info1.isOpportunistic() ? info1 : info2); 502 } else { 503 subscriptions.remove(info1.getSubscriptionId() == mActiveMobileDataSubscription 504 ? info2 : info1); 505 } 506 507 } 508 } 509 510 return subscriptions; 511 } 512 513 @Override onTrustManagedChanged(boolean managed, int userId)514 public void onTrustManagedChanged(boolean managed, int userId) { 515 Assert.isMainThread(); 516 mUserTrustIsManaged.put(userId, managed); 517 mUserTrustIsUsuallyManaged.put(userId, mTrustManager.isTrustUsuallyManaged(userId)); 518 for (int i = 0; i < mCallbacks.size(); i++) { 519 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 520 if (cb != null) { 521 cb.onTrustManagedChanged(userId); 522 } 523 } 524 } 525 526 /** 527 * Updates KeyguardUpdateMonitor's internal state to know if credential was attempted on 528 * bouncer. Note that this does not care if the credential was correct/incorrect. This is 529 * cleared when the user leaves the bouncer (unlocked, screen off, back to lockscreen, etc) 530 */ setCredentialAttempted()531 public void setCredentialAttempted() { 532 mCredentialAttempted = true; 533 updateBiometricListeningState(); 534 } 535 536 /** 537 * Updates KeyguardUpdateMonitor's internal state to know if keyguard is going away. 538 */ setKeyguardGoingAway(boolean goingAway)539 public void setKeyguardGoingAway(boolean goingAway) { 540 mKeyguardGoingAway = goingAway; 541 updateBiometricListeningState(); 542 } 543 544 /** 545 * Updates KeyguardUpdateMonitor's internal state to know if keyguard is occluded 546 */ setKeyguardOccluded(boolean occluded)547 public void setKeyguardOccluded(boolean occluded) { 548 mKeyguardOccluded = occluded; 549 updateBiometricListeningState(); 550 } 551 552 /** 553 * Invoked when the secure camera is launched. 554 */ onCameraLaunched()555 public void onCameraLaunched() { 556 mSecureCameraLaunched = true; 557 updateBiometricListeningState(); 558 } 559 560 /** 561 * @return a cached version of DreamManager.isDreaming() 562 */ isDreaming()563 public boolean isDreaming() { 564 return mIsDreaming; 565 } 566 567 /** 568 * If the device is dreaming, awakens the device 569 */ awakenFromDream()570 public void awakenFromDream() { 571 if (mIsDreaming && mDreamManager != null) { 572 try { 573 mDreamManager.awaken(); 574 } catch (RemoteException e) { 575 Log.e(TAG, "Unable to awaken from dream"); 576 } 577 } 578 } 579 580 @VisibleForTesting onFingerprintAuthenticated(int userId, boolean isStrongBiometric)581 protected void onFingerprintAuthenticated(int userId, boolean isStrongBiometric) { 582 Assert.isMainThread(); 583 Trace.beginSection("KeyGuardUpdateMonitor#onFingerPrintAuthenticated"); 584 mUserFingerprintAuthenticated.put(userId, 585 new BiometricAuthenticated(true, isStrongBiometric)); 586 // Update/refresh trust state only if user can skip bouncer 587 if (getUserCanSkipBouncer(userId)) { 588 mTrustManager.unlockedByBiometricForUser(userId, BiometricSourceType.FINGERPRINT); 589 } 590 // Don't send cancel if authentication succeeds 591 mFingerprintCancelSignal = null; 592 for (int i = 0; i < mCallbacks.size(); i++) { 593 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 594 if (cb != null) { 595 cb.onBiometricAuthenticated(userId, BiometricSourceType.FINGERPRINT, 596 isStrongBiometric); 597 } 598 } 599 600 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE), 601 BIOMETRIC_CONTINUE_DELAY_MS); 602 603 // Only authenticate fingerprint once when assistant is visible 604 mAssistantVisible = false; 605 606 // Report unlock with strong or non-strong biometric 607 reportSuccessfulBiometricUnlock(isStrongBiometric, userId); 608 609 Trace.endSection(); 610 } 611 reportSuccessfulBiometricUnlock(boolean isStrongBiometric, int userId)612 private void reportSuccessfulBiometricUnlock(boolean isStrongBiometric, int userId) { 613 mBackgroundExecutor.execute(new Runnable() { 614 @Override 615 public void run() { 616 mLockPatternUtils.reportSuccessfulBiometricUnlock(isStrongBiometric, userId); 617 } 618 }); 619 } 620 handleFingerprintAuthFailed()621 private void handleFingerprintAuthFailed() { 622 Assert.isMainThread(); 623 for (int i = 0; i < mCallbacks.size(); i++) { 624 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 625 if (cb != null) { 626 cb.onBiometricAuthFailed(BiometricSourceType.FINGERPRINT); 627 } 628 } 629 handleFingerprintHelp(BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED, 630 mContext.getString(R.string.kg_fingerprint_not_recognized)); 631 } 632 handleFingerprintAcquired(int acquireInfo)633 private void handleFingerprintAcquired(int acquireInfo) { 634 Assert.isMainThread(); 635 if (acquireInfo != FingerprintManager.FINGERPRINT_ACQUIRED_GOOD) { 636 return; 637 } 638 for (int i = 0; i < mCallbacks.size(); i++) { 639 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 640 if (cb != null) { 641 cb.onBiometricAcquired(BiometricSourceType.FINGERPRINT); 642 } 643 } 644 } 645 handleFingerprintAuthenticated(int authUserId, boolean isStrongBiometric)646 private void handleFingerprintAuthenticated(int authUserId, boolean isStrongBiometric) { 647 Trace.beginSection("KeyGuardUpdateMonitor#handlerFingerPrintAuthenticated"); 648 try { 649 final int userId; 650 try { 651 userId = ActivityManager.getService().getCurrentUser().id; 652 } catch (RemoteException e) { 653 Log.e(TAG, "Failed to get current user id: ", e); 654 return; 655 } 656 if (userId != authUserId) { 657 Log.d(TAG, "Fingerprint authenticated for wrong user: " + authUserId); 658 return; 659 } 660 if (isFingerprintDisabled(userId)) { 661 Log.d(TAG, "Fingerprint disabled by DPM for userId: " + userId); 662 return; 663 } 664 onFingerprintAuthenticated(userId, isStrongBiometric); 665 } finally { 666 setFingerprintRunningState(BIOMETRIC_STATE_STOPPED); 667 } 668 Trace.endSection(); 669 } 670 handleFingerprintHelp(int msgId, String helpString)671 private void handleFingerprintHelp(int msgId, String helpString) { 672 Assert.isMainThread(); 673 for (int i = 0; i < mCallbacks.size(); i++) { 674 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 675 if (cb != null) { 676 cb.onBiometricHelp(msgId, helpString, BiometricSourceType.FINGERPRINT); 677 } 678 } 679 } 680 681 private Runnable mRetryFingerprintAuthentication = new Runnable() { 682 @Override 683 public void run() { 684 Log.w(TAG, "Retrying fingerprint after HW unavailable, attempt " + 685 mHardwareFingerprintUnavailableRetryCount); 686 updateFingerprintListeningState(); 687 } 688 }; 689 handleFingerprintError(int msgId, String errString)690 private void handleFingerprintError(int msgId, String errString) { 691 Assert.isMainThread(); 692 if (msgId == FingerprintManager.FINGERPRINT_ERROR_CANCELED && mHandler.hasCallbacks( 693 mCancelNotReceived)) { 694 mHandler.removeCallbacks(mCancelNotReceived); 695 } 696 697 if (msgId == FingerprintManager.FINGERPRINT_ERROR_CANCELED 698 && mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { 699 setFingerprintRunningState(BIOMETRIC_STATE_STOPPED); 700 updateFingerprintListeningState(); 701 } else { 702 setFingerprintRunningState(BIOMETRIC_STATE_STOPPED); 703 mFingerprintCancelSignal = null; 704 mFaceCancelSignal = null; 705 } 706 707 if (msgId == FingerprintManager.FINGERPRINT_ERROR_HW_UNAVAILABLE) { 708 if (mHardwareFingerprintUnavailableRetryCount < HAL_ERROR_RETRY_MAX) { 709 mHardwareFingerprintUnavailableRetryCount++; 710 mHandler.removeCallbacks(mRetryFingerprintAuthentication); 711 mHandler.postDelayed(mRetryFingerprintAuthentication, HAL_ERROR_RETRY_TIMEOUT); 712 } 713 } 714 715 if (msgId == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT_PERMANENT) { 716 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, 717 getCurrentUser()); 718 } 719 720 if (msgId == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT 721 || msgId == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT_PERMANENT) { 722 mFingerprintLockedOut = true; 723 } 724 725 for (int i = 0; i < mCallbacks.size(); i++) { 726 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 727 if (cb != null) { 728 cb.onBiometricError(msgId, errString, BiometricSourceType.FINGERPRINT); 729 } 730 } 731 } 732 handleFingerprintLockoutReset()733 private void handleFingerprintLockoutReset() { 734 mFingerprintLockedOut = false; 735 updateFingerprintListeningState(); 736 } 737 setFingerprintRunningState(int fingerprintRunningState)738 private void setFingerprintRunningState(int fingerprintRunningState) { 739 boolean wasRunning = mFingerprintRunningState == BIOMETRIC_STATE_RUNNING; 740 boolean isRunning = fingerprintRunningState == BIOMETRIC_STATE_RUNNING; 741 mFingerprintRunningState = fingerprintRunningState; 742 Log.d(TAG, "fingerprintRunningState: " + mFingerprintRunningState); 743 // Clients of KeyguardUpdateMonitor don't care about the internal state about the 744 // asynchronousness of the cancel cycle. So only notify them if the actually running state 745 // has changed. 746 if (wasRunning != isRunning) { 747 notifyFingerprintRunningStateChanged(); 748 } 749 } 750 notifyFingerprintRunningStateChanged()751 private void notifyFingerprintRunningStateChanged() { 752 Assert.isMainThread(); 753 for (int i = 0; i < mCallbacks.size(); i++) { 754 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 755 if (cb != null) { 756 cb.onBiometricRunningStateChanged(isFingerprintDetectionRunning(), 757 BiometricSourceType.FINGERPRINT); 758 } 759 } 760 } 761 762 @VisibleForTesting onFaceAuthenticated(int userId, boolean isStrongBiometric)763 protected void onFaceAuthenticated(int userId, boolean isStrongBiometric) { 764 Trace.beginSection("KeyGuardUpdateMonitor#onFaceAuthenticated"); 765 Assert.isMainThread(); 766 mUserFaceAuthenticated.put(userId, 767 new BiometricAuthenticated(true, isStrongBiometric)); 768 // Update/refresh trust state only if user can skip bouncer 769 if (getUserCanSkipBouncer(userId)) { 770 mTrustManager.unlockedByBiometricForUser(userId, BiometricSourceType.FACE); 771 } 772 // Don't send cancel if authentication succeeds 773 mFaceCancelSignal = null; 774 for (int i = 0; i < mCallbacks.size(); i++) { 775 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 776 if (cb != null) { 777 cb.onBiometricAuthenticated(userId, 778 BiometricSourceType.FACE, 779 isStrongBiometric); 780 } 781 } 782 783 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE), 784 BIOMETRIC_CONTINUE_DELAY_MS); 785 786 // Only authenticate face once when assistant is visible 787 mAssistantVisible = false; 788 789 // Report unlock with strong or non-strong biometric 790 reportSuccessfulBiometricUnlock(isStrongBiometric, userId); 791 792 Trace.endSection(); 793 } 794 handleFaceAuthFailed()795 private void handleFaceAuthFailed() { 796 Assert.isMainThread(); 797 setFaceRunningState(BIOMETRIC_STATE_STOPPED); 798 for (int i = 0; i < mCallbacks.size(); i++) { 799 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 800 if (cb != null) { 801 cb.onBiometricAuthFailed(BiometricSourceType.FACE); 802 } 803 } 804 handleFaceHelp(BIOMETRIC_HELP_FACE_NOT_RECOGNIZED, 805 mContext.getString(R.string.kg_face_not_recognized)); 806 } 807 handleFaceAcquired(int acquireInfo)808 private void handleFaceAcquired(int acquireInfo) { 809 Assert.isMainThread(); 810 if (acquireInfo != FaceManager.FACE_ACQUIRED_GOOD) { 811 return; 812 } 813 if (DEBUG_FACE) Log.d(TAG, "Face acquired"); 814 for (int i = 0; i < mCallbacks.size(); i++) { 815 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 816 if (cb != null) { 817 cb.onBiometricAcquired(BiometricSourceType.FACE); 818 } 819 } 820 } 821 handleFaceAuthenticated(int authUserId, boolean isStrongBiometric)822 private void handleFaceAuthenticated(int authUserId, boolean isStrongBiometric) { 823 Trace.beginSection("KeyGuardUpdateMonitor#handlerFaceAuthenticated"); 824 try { 825 if (mGoingToSleep) { 826 Log.d(TAG, "Aborted successful auth because device is going to sleep."); 827 return; 828 } 829 final int userId; 830 try { 831 userId = ActivityManager.getService().getCurrentUser().id; 832 } catch (RemoteException e) { 833 Log.e(TAG, "Failed to get current user id: ", e); 834 return; 835 } 836 if (userId != authUserId) { 837 Log.d(TAG, "Face authenticated for wrong user: " + authUserId); 838 return; 839 } 840 if (isFaceDisabled(userId)) { 841 Log.d(TAG, "Face authentication disabled by DPM for userId: " + userId); 842 return; 843 } 844 if (DEBUG_FACE) Log.d(TAG, "Face auth succeeded for user " + userId); 845 onFaceAuthenticated(userId, isStrongBiometric); 846 } finally { 847 setFaceRunningState(BIOMETRIC_STATE_STOPPED); 848 } 849 Trace.endSection(); 850 } 851 handleFaceHelp(int msgId, String helpString)852 private void handleFaceHelp(int msgId, String helpString) { 853 Assert.isMainThread(); 854 if (DEBUG_FACE) Log.d(TAG, "Face help received: " + helpString); 855 for (int i = 0; i < mCallbacks.size(); i++) { 856 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 857 if (cb != null) { 858 cb.onBiometricHelp(msgId, helpString, BiometricSourceType.FACE); 859 } 860 } 861 } 862 863 private Runnable mRetryFaceAuthentication = new Runnable() { 864 @Override 865 public void run() { 866 Log.w(TAG, "Retrying face after HW unavailable, attempt " + 867 mHardwareFaceUnavailableRetryCount); 868 updateFaceListeningState(); 869 } 870 }; 871 handleFaceError(int msgId, String errString)872 private void handleFaceError(int msgId, String errString) { 873 Assert.isMainThread(); 874 if (DEBUG_FACE) Log.d(TAG, "Face error received: " + errString); 875 if (msgId == FaceManager.FACE_ERROR_CANCELED && mHandler.hasCallbacks(mCancelNotReceived)) { 876 mHandler.removeCallbacks(mCancelNotReceived); 877 } 878 879 if (msgId == FaceManager.FACE_ERROR_CANCELED 880 && mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { 881 setFaceRunningState(BIOMETRIC_STATE_STOPPED); 882 updateFaceListeningState(); 883 } else { 884 setFaceRunningState(BIOMETRIC_STATE_STOPPED); 885 } 886 887 if (msgId == FaceManager.FACE_ERROR_HW_UNAVAILABLE 888 || msgId == FaceManager.FACE_ERROR_UNABLE_TO_PROCESS) { 889 if (mHardwareFaceUnavailableRetryCount < HAL_ERROR_RETRY_MAX) { 890 mHardwareFaceUnavailableRetryCount++; 891 mHandler.removeCallbacks(mRetryFaceAuthentication); 892 mHandler.postDelayed(mRetryFaceAuthentication, HAL_ERROR_RETRY_TIMEOUT); 893 } 894 } 895 896 if (msgId == FaceManager.FACE_ERROR_LOCKOUT_PERMANENT) { 897 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, 898 getCurrentUser()); 899 } 900 901 for (int i = 0; i < mCallbacks.size(); i++) { 902 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 903 if (cb != null) { 904 cb.onBiometricError(msgId, errString, 905 BiometricSourceType.FACE); 906 } 907 } 908 } 909 handleFaceLockoutReset()910 private void handleFaceLockoutReset() { 911 updateFaceListeningState(); 912 } 913 setFaceRunningState(int faceRunningState)914 private void setFaceRunningState(int faceRunningState) { 915 boolean wasRunning = mFaceRunningState == BIOMETRIC_STATE_RUNNING; 916 boolean isRunning = faceRunningState == BIOMETRIC_STATE_RUNNING; 917 mFaceRunningState = faceRunningState; 918 Log.d(TAG, "faceRunningState: " + mFaceRunningState); 919 // Clients of KeyguardUpdateMonitor don't care about the internal state or about the 920 // asynchronousness of the cancel cycle. So only notify them if the actually running state 921 // has changed. 922 if (wasRunning != isRunning) { 923 notifyFaceRunningStateChanged(); 924 } 925 } 926 notifyFaceRunningStateChanged()927 private void notifyFaceRunningStateChanged() { 928 Assert.isMainThread(); 929 for (int i = 0; i < mCallbacks.size(); i++) { 930 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 931 if (cb != null) { 932 cb.onBiometricRunningStateChanged(isFaceDetectionRunning(), 933 BiometricSourceType.FACE); 934 } 935 } 936 } 937 handleFaceUnlockStateChanged(boolean running, int userId)938 private void handleFaceUnlockStateChanged(boolean running, int userId) { 939 Assert.isMainThread(); 940 mUserFaceUnlockRunning.put(userId, running); 941 for (int i = 0; i < mCallbacks.size(); i++) { 942 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 943 if (cb != null) { 944 cb.onFaceUnlockStateChanged(running, userId); 945 } 946 } 947 } 948 isFaceUnlockRunning(int userId)949 public boolean isFaceUnlockRunning(int userId) { 950 return mUserFaceUnlockRunning.get(userId); 951 } 952 isFingerprintDetectionRunning()953 public boolean isFingerprintDetectionRunning() { 954 return mFingerprintRunningState == BIOMETRIC_STATE_RUNNING; 955 } 956 isFaceDetectionRunning()957 public boolean isFaceDetectionRunning() { 958 return mFaceRunningState == BIOMETRIC_STATE_RUNNING; 959 } 960 isTrustDisabled(int userId)961 private boolean isTrustDisabled(int userId) { 962 // Don't allow trust agent if device is secured with a SIM PIN. This is here 963 // mainly because there's no other way to prompt the user to enter their SIM PIN 964 // once they get past the keyguard screen. 965 final boolean disabledBySimPin = isSimPinSecure(); 966 return disabledBySimPin; 967 } 968 isFingerprintDisabled(int userId)969 private boolean isFingerprintDisabled(int userId) { 970 final DevicePolicyManager dpm = 971 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); 972 return dpm != null && (dpm.getKeyguardDisabledFeatures(null, userId) 973 & DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT) != 0 974 || isSimPinSecure(); 975 } 976 isFaceDisabled(int userId)977 private boolean isFaceDisabled(int userId) { 978 final DevicePolicyManager dpm = 979 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); 980 // TODO(b/140035044) 981 return whitelistIpcs(() -> dpm != null && (dpm.getKeyguardDisabledFeatures(null, userId) 982 & DevicePolicyManager.KEYGUARD_DISABLE_FACE) != 0 983 || isSimPinSecure()); 984 } 985 986 getUserCanSkipBouncer(int userId)987 public boolean getUserCanSkipBouncer(int userId) { 988 return getUserHasTrust(userId) || getUserUnlockedWithBiometric(userId); 989 } 990 getUserHasTrust(int userId)991 public boolean getUserHasTrust(int userId) { 992 return !isTrustDisabled(userId) && mUserHasTrust.get(userId); 993 } 994 995 /** 996 * Returns whether the user is unlocked with biometrics. 997 */ getUserUnlockedWithBiometric(int userId)998 public boolean getUserUnlockedWithBiometric(int userId) { 999 BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(userId); 1000 BiometricAuthenticated face = mUserFaceAuthenticated.get(userId); 1001 boolean fingerprintAllowed = fingerprint != null && fingerprint.mAuthenticated 1002 && isUnlockingWithBiometricAllowed(fingerprint.mIsStrongBiometric); 1003 boolean faceAllowed = face != null && face.mAuthenticated 1004 && isUnlockingWithBiometricAllowed(face.mIsStrongBiometric); 1005 return fingerprintAllowed || faceAllowed; 1006 } 1007 getUserTrustIsManaged(int userId)1008 public boolean getUserTrustIsManaged(int userId) { 1009 return mUserTrustIsManaged.get(userId) && !isTrustDisabled(userId); 1010 } 1011 updateSecondaryLockscreenRequirement(int userId)1012 private void updateSecondaryLockscreenRequirement(int userId) { 1013 Intent oldIntent = mSecondaryLockscreenRequirement.get(userId); 1014 boolean enabled = mDevicePolicyManager.isSecondaryLockscreenEnabled(UserHandle.of(userId)); 1015 boolean changed = false; 1016 1017 if (enabled && (oldIntent == null)) { 1018 ComponentName supervisorComponent = 1019 mDevicePolicyManager.getProfileOwnerOrDeviceOwnerSupervisionComponent( 1020 UserHandle.of(userId)); 1021 if (supervisorComponent == null) { 1022 Log.e(TAG, "No Profile Owner or Device Owner supervision app found for User " 1023 + userId); 1024 } else { 1025 Intent intent = 1026 new Intent(DevicePolicyManager.ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE) 1027 .setPackage(supervisorComponent.getPackageName()); 1028 ResolveInfo resolveInfo = mContext.getPackageManager().resolveService(intent, 0); 1029 if (resolveInfo != null && resolveInfo.serviceInfo != null) { 1030 Intent launchIntent = 1031 new Intent().setComponent(resolveInfo.serviceInfo.getComponentName()); 1032 mSecondaryLockscreenRequirement.put(userId, launchIntent); 1033 changed = true; 1034 } 1035 } 1036 } else if (!enabled && (oldIntent != null)) { 1037 mSecondaryLockscreenRequirement.put(userId, null); 1038 changed = true; 1039 } 1040 if (changed) { 1041 for (int i = 0; i < mCallbacks.size(); i++) { 1042 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1043 if (cb != null) { 1044 cb.onSecondaryLockscreenRequirementChanged(userId); 1045 } 1046 } 1047 } 1048 } 1049 1050 /** 1051 * Returns an Intent by which to bind to a service that will provide additional security screen 1052 * content that must be shown prior to dismissing the keyguard for this user. 1053 */ getSecondaryLockscreenRequirement(int userId)1054 public Intent getSecondaryLockscreenRequirement(int userId) { 1055 return mSecondaryLockscreenRequirement.get(userId); 1056 } 1057 1058 /** 1059 * Cached version of {@link TrustManager#isTrustUsuallyManaged(int)}. 1060 */ isTrustUsuallyManaged(int userId)1061 public boolean isTrustUsuallyManaged(int userId) { 1062 Assert.isMainThread(); 1063 return mUserTrustIsUsuallyManaged.get(userId); 1064 } 1065 isUnlockingWithBiometricAllowed(boolean isStrongBiometric)1066 public boolean isUnlockingWithBiometricAllowed(boolean isStrongBiometric) { 1067 return mStrongAuthTracker.isUnlockingWithBiometricAllowed(isStrongBiometric); 1068 } 1069 isUserInLockdown(int userId)1070 public boolean isUserInLockdown(int userId) { 1071 return containsFlag(mStrongAuthTracker.getStrongAuthForUser(userId), 1072 STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN); 1073 } 1074 userNeedsStrongAuth()1075 public boolean userNeedsStrongAuth() { 1076 return mStrongAuthTracker.getStrongAuthForUser(getCurrentUser()) 1077 != LockPatternUtils.StrongAuthTracker.STRONG_AUTH_NOT_REQUIRED; 1078 } 1079 containsFlag(int haystack, int needle)1080 private boolean containsFlag(int haystack, int needle) { 1081 return (haystack & needle) != 0; 1082 } 1083 needsSlowUnlockTransition()1084 public boolean needsSlowUnlockTransition() { 1085 return mNeedsSlowUnlockTransition; 1086 } 1087 getStrongAuthTracker()1088 public StrongAuthTracker getStrongAuthTracker() { 1089 return mStrongAuthTracker; 1090 } 1091 notifyStrongAuthStateChanged(int userId)1092 private void notifyStrongAuthStateChanged(int userId) { 1093 Assert.isMainThread(); 1094 for (int i = 0; i < mCallbacks.size(); i++) { 1095 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1096 if (cb != null) { 1097 cb.onStrongAuthStateChanged(userId); 1098 } 1099 } 1100 } 1101 isScreenOn()1102 public boolean isScreenOn() { 1103 return mScreenOn; 1104 } 1105 dispatchErrorMessage(CharSequence message)1106 private void dispatchErrorMessage(CharSequence message) { 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.onTrustAgentErrorMessage(message); 1112 } 1113 } 1114 } 1115 1116 @VisibleForTesting setAssistantVisible(boolean assistantVisible)1117 void setAssistantVisible(boolean assistantVisible) { 1118 mAssistantVisible = assistantVisible; 1119 updateBiometricListeningState(); 1120 } 1121 1122 static class DisplayClientState { 1123 public int clientGeneration; 1124 public boolean clearing; 1125 public PendingIntent intent; 1126 public int playbackState; 1127 public long playbackEventTime; 1128 } 1129 1130 private DisplayClientState mDisplayClientState = new DisplayClientState(); 1131 1132 @VisibleForTesting 1133 protected final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 1134 1135 @Override 1136 public void onReceive(Context context, Intent intent) { 1137 final String action = intent.getAction(); 1138 if (DEBUG) Log.d(TAG, "received broadcast " + action); 1139 1140 if (Intent.ACTION_TIME_TICK.equals(action) 1141 || Intent.ACTION_TIME_CHANGED.equals(action)) { 1142 mHandler.sendEmptyMessage(MSG_TIME_UPDATE); 1143 } else if (Intent.ACTION_TIMEZONE_CHANGED.equals(action)) { 1144 final Message msg = mHandler.obtainMessage( 1145 MSG_TIMEZONE_UPDATE, intent.getStringExtra(Intent.EXTRA_TIMEZONE)); 1146 mHandler.sendMessage(msg); 1147 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { 1148 1149 final Message msg = mHandler.obtainMessage( 1150 MSG_BATTERY_UPDATE, new BatteryStatus(intent)); 1151 mHandler.sendMessage(msg); 1152 } else if (Intent.ACTION_SIM_STATE_CHANGED.equals(action)) { 1153 SimData args = SimData.fromIntent(intent); 1154 // ACTION_SIM_STATE_CHANGED is rebroadcast after unlocking the device to 1155 // keep compatibility with apps that aren't direct boot aware. 1156 // SysUI should just ignore this broadcast because it was already received 1157 // and processed previously. 1158 if (intent.getBooleanExtra(Intent.EXTRA_REBROADCAST_ON_UNLOCK, false)) { 1159 // Guarantee mTelephonyCapable state after SysUI crash and restart 1160 if (args.simState == TelephonyManager.SIM_STATE_ABSENT) { 1161 mHandler.obtainMessage(MSG_TELEPHONY_CAPABLE, true).sendToTarget(); 1162 } 1163 return; 1164 } 1165 if (DEBUG_SIM_STATES) { 1166 Log.v(TAG, "action " + action 1167 + " state: " + intent.getStringExtra( 1168 Intent.EXTRA_SIM_STATE) 1169 + " slotId: " + args.slotId + " subid: " + args.subId); 1170 } 1171 mHandler.obtainMessage(MSG_SIM_STATE_CHANGE, args.subId, args.slotId, args.simState) 1172 .sendToTarget(); 1173 } else if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(action)) { 1174 String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); 1175 mHandler.sendMessage(mHandler.obtainMessage(MSG_PHONE_STATE_CHANGED, state)); 1176 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { 1177 mHandler.sendEmptyMessage(MSG_AIRPLANE_MODE_CHANGED); 1178 } else if (Intent.ACTION_SERVICE_STATE.equals(action)) { 1179 ServiceState serviceState = ServiceState.newFromBundle(intent.getExtras()); 1180 int subId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, 1181 SubscriptionManager.INVALID_SUBSCRIPTION_ID); 1182 if (DEBUG) { 1183 Log.v(TAG, "action " + action + " serviceState=" + serviceState + " subId=" 1184 + subId); 1185 } 1186 mHandler.sendMessage( 1187 mHandler.obtainMessage(MSG_SERVICE_STATE_CHANGE, subId, 0, serviceState)); 1188 } else if (TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED.equals(action)) { 1189 mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED); 1190 } else if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals( 1191 action)) { 1192 mHandler.sendEmptyMessage(MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED); 1193 } 1194 } 1195 }; 1196 1197 @VisibleForTesting 1198 protected final BroadcastReceiver mBroadcastAllReceiver = new BroadcastReceiver() { 1199 1200 @Override 1201 public void onReceive(Context context, Intent intent) { 1202 final String action = intent.getAction(); 1203 if (AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED.equals(action)) { 1204 mHandler.sendEmptyMessage(MSG_TIME_UPDATE); 1205 } else if (Intent.ACTION_USER_INFO_CHANGED.equals(action)) { 1206 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_INFO_CHANGED, 1207 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, getSendingUserId()), 0)); 1208 } else if (ACTION_FACE_UNLOCK_STARTED.equals(action)) { 1209 Trace.beginSection( 1210 "KeyguardUpdateMonitor.mBroadcastAllReceiver#onReceive " 1211 + "ACTION_FACE_UNLOCK_STARTED"); 1212 mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_UNLOCK_STATE_CHANGED, 1, 1213 getSendingUserId())); 1214 Trace.endSection(); 1215 } else if (ACTION_FACE_UNLOCK_STOPPED.equals(action)) { 1216 mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_UNLOCK_STATE_CHANGED, 0, 1217 getSendingUserId())); 1218 } else if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED 1219 .equals(action)) { 1220 mHandler.sendMessage(mHandler.obtainMessage(MSG_DPM_STATE_CHANGED, 1221 getSendingUserId())); 1222 } else if (ACTION_USER_UNLOCKED.equals(action)) { 1223 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_UNLOCKED, 1224 getSendingUserId(), 0)); 1225 } else if (ACTION_USER_STOPPED.equals(action)) { 1226 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_STOPPED, 1227 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1), 0)); 1228 } else if (ACTION_USER_REMOVED.equals(action)) { 1229 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_REMOVED, 1230 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1), 0)); 1231 } 1232 } 1233 }; 1234 1235 private final FingerprintManager.LockoutResetCallback mFingerprintLockoutResetCallback 1236 = new FingerprintManager.LockoutResetCallback() { 1237 @Override 1238 public void onLockoutReset() { 1239 handleFingerprintLockoutReset(); 1240 } 1241 }; 1242 1243 private final FaceManager.LockoutResetCallback mFaceLockoutResetCallback 1244 = new FaceManager.LockoutResetCallback() { 1245 @Override 1246 public void onLockoutReset() { 1247 handleFaceLockoutReset(); 1248 } 1249 }; 1250 1251 private FingerprintManager.AuthenticationCallback mFingerprintAuthenticationCallback 1252 = new AuthenticationCallback() { 1253 1254 @Override 1255 public void onAuthenticationFailed() { 1256 handleFingerprintAuthFailed(); 1257 } 1258 1259 @Override 1260 public void onAuthenticationSucceeded(AuthenticationResult result) { 1261 Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationSucceeded"); 1262 handleFingerprintAuthenticated(result.getUserId(), result.isStrongBiometric()); 1263 Trace.endSection(); 1264 } 1265 1266 @Override 1267 public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { 1268 handleFingerprintHelp(helpMsgId, helpString.toString()); 1269 } 1270 1271 @Override 1272 public void onAuthenticationError(int errMsgId, CharSequence errString) { 1273 handleFingerprintError(errMsgId, errString.toString()); 1274 } 1275 1276 @Override 1277 public void onAuthenticationAcquired(int acquireInfo) { 1278 handleFingerprintAcquired(acquireInfo); 1279 } 1280 }; 1281 1282 @VisibleForTesting 1283 FaceManager.AuthenticationCallback mFaceAuthenticationCallback 1284 = new FaceManager.AuthenticationCallback() { 1285 1286 @Override 1287 public void onAuthenticationFailed() { 1288 handleFaceAuthFailed(); 1289 } 1290 1291 @Override 1292 public void onAuthenticationSucceeded(FaceManager.AuthenticationResult result) { 1293 Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationSucceeded"); 1294 handleFaceAuthenticated(result.getUserId(), result.isStrongBiometric()); 1295 Trace.endSection(); 1296 } 1297 1298 @Override 1299 public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { 1300 handleFaceHelp(helpMsgId, helpString.toString()); 1301 } 1302 1303 @Override 1304 public void onAuthenticationError(int errMsgId, CharSequence errString) { 1305 handleFaceError(errMsgId, errString.toString()); 1306 } 1307 1308 @Override 1309 public void onAuthenticationAcquired(int acquireInfo) { 1310 handleFaceAcquired(acquireInfo); 1311 } 1312 }; 1313 1314 private CancellationSignal mFingerprintCancelSignal; 1315 private CancellationSignal mFaceCancelSignal; 1316 private FingerprintManager mFpm; 1317 private FaceManager mFaceManager; 1318 private boolean mFingerprintLockedOut; 1319 private TelephonyManager mTelephonyManager; 1320 1321 /** 1322 * When we receive a 1323 * {@link com.android.internal.telephony.TelephonyIntents#ACTION_SIM_STATE_CHANGED} broadcast, 1324 * and then pass a result via our handler to {@link KeyguardUpdateMonitor#handleSimStateChange}, 1325 * we need a single object to pass to the handler. This class helps decode 1326 * the intent and provide a {@link SimCard.State} result. 1327 */ 1328 private static class SimData { 1329 public int simState; 1330 public int slotId; 1331 public int subId; 1332 SimData(int state, int slot, int id)1333 SimData(int state, int slot, int id) { 1334 simState = state; 1335 slotId = slot; 1336 subId = id; 1337 } 1338 fromIntent(Intent intent)1339 static SimData fromIntent(Intent intent) { 1340 int state; 1341 if (!Intent.ACTION_SIM_STATE_CHANGED.equals(intent.getAction())) { 1342 throw new IllegalArgumentException("only handles intent ACTION_SIM_STATE_CHANGED"); 1343 } 1344 String stateExtra = intent.getStringExtra(Intent.EXTRA_SIM_STATE); 1345 int slotId = intent.getIntExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0); 1346 int subId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, 1347 SubscriptionManager.INVALID_SUBSCRIPTION_ID); 1348 if (Intent.SIM_STATE_ABSENT.equals(stateExtra)) { 1349 final String absentReason = intent 1350 .getStringExtra(Intent.EXTRA_SIM_LOCKED_REASON); 1351 1352 if (Intent.SIM_ABSENT_ON_PERM_DISABLED.equals( 1353 absentReason)) { 1354 state = TelephonyManager.SIM_STATE_PERM_DISABLED; 1355 } else { 1356 state = TelephonyManager.SIM_STATE_ABSENT; 1357 } 1358 } else if (Intent.SIM_STATE_READY.equals(stateExtra)) { 1359 state = TelephonyManager.SIM_STATE_READY; 1360 } else if (Intent.SIM_STATE_LOCKED.equals(stateExtra)) { 1361 final String lockedReason = intent 1362 .getStringExtra(Intent.EXTRA_SIM_LOCKED_REASON); 1363 if (Intent.SIM_LOCKED_ON_PIN.equals(lockedReason)) { 1364 state = TelephonyManager.SIM_STATE_PIN_REQUIRED; 1365 } else if (Intent.SIM_LOCKED_ON_PUK.equals(lockedReason)) { 1366 state = TelephonyManager.SIM_STATE_PUK_REQUIRED; 1367 } else { 1368 state = TelephonyManager.SIM_STATE_UNKNOWN; 1369 } 1370 } else if (Intent.SIM_LOCKED_NETWORK.equals(stateExtra)) { 1371 state = TelephonyManager.SIM_STATE_NETWORK_LOCKED; 1372 } else if (Intent.SIM_STATE_CARD_IO_ERROR.equals(stateExtra)) { 1373 state = TelephonyManager.SIM_STATE_CARD_IO_ERROR; 1374 } else if (Intent.SIM_STATE_LOADED.equals(stateExtra) 1375 || Intent.SIM_STATE_IMSI.equals(stateExtra)) { 1376 // This is required because telephony doesn't return to "READY" after 1377 // these state transitions. See bug 7197471. 1378 state = TelephonyManager.SIM_STATE_READY; 1379 } else { 1380 state = TelephonyManager.SIM_STATE_UNKNOWN; 1381 } 1382 return new SimData(state, slotId, subId); 1383 } 1384 1385 @Override toString()1386 public String toString() { 1387 return "SimData{state=" + simState + ",slotId=" + slotId + ",subId=" + subId + "}"; 1388 } 1389 } 1390 1391 public static class StrongAuthTracker extends LockPatternUtils.StrongAuthTracker { 1392 private final Consumer<Integer> mStrongAuthRequiredChangedCallback; 1393 StrongAuthTracker(Context context, Consumer<Integer> strongAuthRequiredChangedCallback)1394 public StrongAuthTracker(Context context, 1395 Consumer<Integer> strongAuthRequiredChangedCallback) { 1396 super(context); 1397 mStrongAuthRequiredChangedCallback = strongAuthRequiredChangedCallback; 1398 } 1399 isUnlockingWithBiometricAllowed(boolean isStrongBiometric)1400 public boolean isUnlockingWithBiometricAllowed(boolean isStrongBiometric) { 1401 int userId = getCurrentUser(); 1402 return isBiometricAllowedForUser(isStrongBiometric, userId); 1403 } 1404 hasUserAuthenticatedSinceBoot()1405 public boolean hasUserAuthenticatedSinceBoot() { 1406 int userId = getCurrentUser(); 1407 return (getStrongAuthForUser(userId) 1408 & STRONG_AUTH_REQUIRED_AFTER_BOOT) == 0; 1409 } 1410 1411 @Override onStrongAuthRequiredChanged(int userId)1412 public void onStrongAuthRequiredChanged(int userId) { 1413 mStrongAuthRequiredChangedCallback.accept(userId); 1414 } 1415 } 1416 handleStartedWakingUp()1417 protected void handleStartedWakingUp() { 1418 Trace.beginSection("KeyguardUpdateMonitor#handleStartedWakingUp"); 1419 Assert.isMainThread(); 1420 updateBiometricListeningState(); 1421 for (int i = 0; i < mCallbacks.size(); i++) { 1422 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1423 if (cb != null) { 1424 cb.onStartedWakingUp(); 1425 } 1426 } 1427 Trace.endSection(); 1428 } 1429 handleStartedGoingToSleep(int arg1)1430 protected void handleStartedGoingToSleep(int arg1) { 1431 Assert.isMainThread(); 1432 mLockIconPressed = false; 1433 clearBiometricRecognized(); 1434 for (int i = 0; i < mCallbacks.size(); i++) { 1435 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1436 if (cb != null) { 1437 cb.onStartedGoingToSleep(arg1); 1438 } 1439 } 1440 mGoingToSleep = true; 1441 updateBiometricListeningState(); 1442 } 1443 handleFinishedGoingToSleep(int arg1)1444 protected void handleFinishedGoingToSleep(int arg1) { 1445 Assert.isMainThread(); 1446 mGoingToSleep = false; 1447 for (int i = 0; i < mCallbacks.size(); i++) { 1448 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1449 if (cb != null) { 1450 cb.onFinishedGoingToSleep(arg1); 1451 } 1452 } 1453 updateBiometricListeningState(); 1454 } 1455 handleScreenTurnedOn()1456 private void handleScreenTurnedOn() { 1457 Assert.isMainThread(); 1458 for (int i = 0; i < mCallbacks.size(); i++) { 1459 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1460 if (cb != null) { 1461 cb.onScreenTurnedOn(); 1462 } 1463 } 1464 } 1465 handleScreenTurnedOff()1466 private void handleScreenTurnedOff() { 1467 final String tag = "KeyguardUpdateMonitor#handleScreenTurnedOff"; 1468 DejankUtils.startDetectingBlockingIpcs(tag); 1469 Assert.isMainThread(); 1470 mHardwareFingerprintUnavailableRetryCount = 0; 1471 mHardwareFaceUnavailableRetryCount = 0; 1472 for (int i = 0; i < mCallbacks.size(); i++) { 1473 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1474 if (cb != null) { 1475 cb.onScreenTurnedOff(); 1476 } 1477 } 1478 DejankUtils.stopDetectingBlockingIpcs(tag); 1479 } 1480 handleDreamingStateChanged(int dreamStart)1481 private void handleDreamingStateChanged(int dreamStart) { 1482 Assert.isMainThread(); 1483 mIsDreaming = dreamStart == 1; 1484 for (int i = 0; i < mCallbacks.size(); i++) { 1485 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1486 if (cb != null) { 1487 cb.onDreamingStateChanged(mIsDreaming); 1488 } 1489 } 1490 updateBiometricListeningState(); 1491 } 1492 handleUserInfoChanged(int userId)1493 private void handleUserInfoChanged(int userId) { 1494 Assert.isMainThread(); 1495 for (int i = 0; i < mCallbacks.size(); i++) { 1496 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1497 if (cb != null) { 1498 cb.onUserInfoChanged(userId); 1499 } 1500 } 1501 } 1502 handleUserUnlocked(int userId)1503 private void handleUserUnlocked(int userId) { 1504 Assert.isMainThread(); 1505 mUserIsUnlocked.put(userId, true); 1506 mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition(); 1507 for (int i = 0; i < mCallbacks.size(); i++) { 1508 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1509 if (cb != null) { 1510 cb.onUserUnlocked(); 1511 } 1512 } 1513 } 1514 handleUserStopped(int userId)1515 private void handleUserStopped(int userId) { 1516 Assert.isMainThread(); 1517 mUserIsUnlocked.put(userId, mUserManager.isUserUnlocked(userId)); 1518 } 1519 1520 @VisibleForTesting handleUserRemoved(int userId)1521 void handleUserRemoved(int userId) { 1522 Assert.isMainThread(); 1523 mUserIsUnlocked.delete(userId); 1524 mUserTrustIsUsuallyManaged.delete(userId); 1525 } 1526 handleKeyguardGoingAway(boolean goingAway)1527 private void handleKeyguardGoingAway(boolean goingAway) { 1528 Assert.isMainThread(); 1529 setKeyguardGoingAway(goingAway); 1530 } 1531 1532 @VisibleForTesting setStrongAuthTracker(@onNull StrongAuthTracker tracker)1533 protected void setStrongAuthTracker(@NonNull StrongAuthTracker tracker) { 1534 if (mStrongAuthTracker != null) { 1535 mLockPatternUtils.unregisterStrongAuthTracker(mStrongAuthTracker); 1536 } 1537 1538 mStrongAuthTracker = tracker; 1539 mLockPatternUtils.registerStrongAuthTracker(mStrongAuthTracker); 1540 } 1541 registerRingerTracker()1542 private void registerRingerTracker() { 1543 mRingerModeTracker.getRingerMode().observeForever(mRingerModeObserver); 1544 } 1545 1546 @VisibleForTesting 1547 @Inject KeyguardUpdateMonitor( Context context, @Main Looper mainLooper, BroadcastDispatcher broadcastDispatcher, DumpManager dumpManager, RingerModeTracker ringerModeTracker, @Background Executor backgroundExecutor, StatusBarStateController statusBarStateController, LockPatternUtils lockPatternUtils)1548 protected KeyguardUpdateMonitor( 1549 Context context, 1550 @Main Looper mainLooper, 1551 BroadcastDispatcher broadcastDispatcher, 1552 DumpManager dumpManager, 1553 RingerModeTracker ringerModeTracker, 1554 @Background Executor backgroundExecutor, 1555 StatusBarStateController statusBarStateController, 1556 LockPatternUtils lockPatternUtils) { 1557 mContext = context; 1558 mSubscriptionManager = SubscriptionManager.from(context); 1559 mDeviceProvisioned = isDeviceProvisionedInSettingsDb(); 1560 mStrongAuthTracker = new StrongAuthTracker(context, this::notifyStrongAuthStateChanged); 1561 mBackgroundExecutor = backgroundExecutor; 1562 mBroadcastDispatcher = broadcastDispatcher; 1563 mRingerModeTracker = ringerModeTracker; 1564 mStatusBarStateController = statusBarStateController; 1565 mLockPatternUtils = lockPatternUtils; 1566 dumpManager.registerDumpable(getClass().getName(), this); 1567 1568 mHandler = new Handler(mainLooper) { 1569 @Override 1570 public void handleMessage(Message msg) { 1571 switch (msg.what) { 1572 case MSG_TIME_UPDATE: 1573 handleTimeUpdate(); 1574 break; 1575 case MSG_TIMEZONE_UPDATE: 1576 handleTimeZoneUpdate((String) msg.obj); 1577 break; 1578 case MSG_BATTERY_UPDATE: 1579 handleBatteryUpdate((BatteryStatus) msg.obj); 1580 break; 1581 case MSG_SIM_STATE_CHANGE: 1582 handleSimStateChange(msg.arg1, msg.arg2, (int) msg.obj); 1583 break; 1584 case MSG_RINGER_MODE_CHANGED: 1585 handleRingerModeChange(msg.arg1); 1586 break; 1587 case MSG_PHONE_STATE_CHANGED: 1588 handlePhoneStateChanged((String) msg.obj); 1589 break; 1590 case MSG_DEVICE_PROVISIONED: 1591 handleDeviceProvisioned(); 1592 break; 1593 case MSG_DPM_STATE_CHANGED: 1594 handleDevicePolicyManagerStateChanged(msg.arg1); 1595 break; 1596 case MSG_USER_SWITCHING: 1597 handleUserSwitching(msg.arg1, (IRemoteCallback) msg.obj); 1598 break; 1599 case MSG_USER_SWITCH_COMPLETE: 1600 handleUserSwitchComplete(msg.arg1); 1601 break; 1602 case MSG_KEYGUARD_RESET: 1603 handleKeyguardReset(); 1604 break; 1605 case MSG_KEYGUARD_BOUNCER_CHANGED: 1606 handleKeyguardBouncerChanged(msg.arg1); 1607 break; 1608 case MSG_USER_INFO_CHANGED: 1609 handleUserInfoChanged(msg.arg1); 1610 break; 1611 case MSG_REPORT_EMERGENCY_CALL_ACTION: 1612 handleReportEmergencyCallAction(); 1613 break; 1614 case MSG_STARTED_GOING_TO_SLEEP: 1615 handleStartedGoingToSleep(msg.arg1); 1616 break; 1617 case MSG_FINISHED_GOING_TO_SLEEP: 1618 handleFinishedGoingToSleep(msg.arg1); 1619 break; 1620 case MSG_STARTED_WAKING_UP: 1621 Trace.beginSection("KeyguardUpdateMonitor#handler MSG_STARTED_WAKING_UP"); 1622 handleStartedWakingUp(); 1623 Trace.endSection(); 1624 break; 1625 case MSG_FACE_UNLOCK_STATE_CHANGED: 1626 Trace.beginSection( 1627 "KeyguardUpdateMonitor#handler MSG_FACE_UNLOCK_STATE_CHANGED"); 1628 handleFaceUnlockStateChanged(msg.arg1 != 0, msg.arg2); 1629 Trace.endSection(); 1630 break; 1631 case MSG_SIM_SUBSCRIPTION_INFO_CHANGED: 1632 handleSimSubscriptionInfoChanged(); 1633 break; 1634 case MSG_AIRPLANE_MODE_CHANGED: 1635 handleAirplaneModeChanged(); 1636 break; 1637 case MSG_SERVICE_STATE_CHANGE: 1638 handleServiceStateChange(msg.arg1, (ServiceState) msg.obj); 1639 break; 1640 case MSG_SCREEN_TURNED_ON: 1641 handleScreenTurnedOn(); 1642 break; 1643 case MSG_SCREEN_TURNED_OFF: 1644 Trace.beginSection("KeyguardUpdateMonitor#handler MSG_SCREEN_TURNED_ON"); 1645 handleScreenTurnedOff(); 1646 Trace.endSection(); 1647 break; 1648 case MSG_DREAMING_STATE_CHANGED: 1649 handleDreamingStateChanged(msg.arg1); 1650 break; 1651 case MSG_USER_UNLOCKED: 1652 handleUserUnlocked(msg.arg1); 1653 break; 1654 case MSG_USER_STOPPED: 1655 handleUserStopped(msg.arg1); 1656 break; 1657 case MSG_USER_REMOVED: 1658 handleUserRemoved(msg.arg1); 1659 break; 1660 case MSG_ASSISTANT_STACK_CHANGED: 1661 setAssistantVisible((boolean) msg.obj); 1662 break; 1663 case MSG_BIOMETRIC_AUTHENTICATION_CONTINUE: 1664 updateBiometricListeningState(); 1665 break; 1666 case MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED: 1667 updateLogoutEnabled(); 1668 break; 1669 case MSG_TELEPHONY_CAPABLE: 1670 updateTelephonyCapable((boolean) msg.obj); 1671 break; 1672 case MSG_KEYGUARD_GOING_AWAY: 1673 handleKeyguardGoingAway((boolean) msg.obj); 1674 break; 1675 default: 1676 super.handleMessage(msg); 1677 break; 1678 } 1679 } 1680 }; 1681 1682 // Since device can't be un-provisioned, we only need to register a content observer 1683 // to update mDeviceProvisioned when we are... 1684 if (!mDeviceProvisioned) { 1685 watchForDeviceProvisioning(); 1686 } 1687 1688 // Take a guess at initial SIM state, battery status and PLMN until we get an update 1689 mBatteryStatus = new BatteryStatus(BATTERY_STATUS_UNKNOWN, 100, 0, 0, 0); 1690 1691 // Watch for interesting updates 1692 final IntentFilter filter = new IntentFilter(); 1693 filter.addAction(Intent.ACTION_TIME_TICK); 1694 filter.addAction(Intent.ACTION_TIME_CHANGED); 1695 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 1696 filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); 1697 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); 1698 filter.addAction(Intent.ACTION_SIM_STATE_CHANGED); 1699 filter.addAction(Intent.ACTION_SERVICE_STATE); 1700 filter.addAction(TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED); 1701 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); 1702 filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 1703 mBroadcastDispatcher.registerReceiverWithHandler(mBroadcastReceiver, filter, mHandler); 1704 // Since ACTION_SERVICE_STATE is being moved to a non-sticky broadcast, trigger the 1705 // listener now with the service state from the default sub. 1706 mBackgroundExecutor.execute(() -> { 1707 int subId = SubscriptionManager.getDefaultSubscriptionId(); 1708 ServiceState serviceState = mContext.getSystemService(TelephonyManager.class) 1709 .getServiceStateForSubscriber(subId); 1710 mHandler.sendMessage( 1711 mHandler.obtainMessage(MSG_SERVICE_STATE_CHANGE, subId, 0, serviceState)); 1712 1713 // Get initial state. Relying on Sticky behavior until API for getting info. 1714 if (mBatteryStatus == null) { 1715 Intent intent = mContext.registerReceiver( 1716 null, 1717 new IntentFilter(Intent.ACTION_BATTERY_CHANGED) 1718 ); 1719 if (intent != null && mBatteryStatus == null) { 1720 mBroadcastReceiver.onReceive(mContext, intent); 1721 } 1722 } 1723 }); 1724 1725 mHandler.post(this::registerRingerTracker); 1726 1727 final IntentFilter allUserFilter = new IntentFilter(); 1728 allUserFilter.addAction(Intent.ACTION_USER_INFO_CHANGED); 1729 allUserFilter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED); 1730 allUserFilter.addAction(ACTION_FACE_UNLOCK_STARTED); 1731 allUserFilter.addAction(ACTION_FACE_UNLOCK_STOPPED); 1732 allUserFilter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 1733 allUserFilter.addAction(ACTION_USER_UNLOCKED); 1734 allUserFilter.addAction(ACTION_USER_STOPPED); 1735 allUserFilter.addAction(ACTION_USER_REMOVED); 1736 mBroadcastDispatcher.registerReceiverWithHandler(mBroadcastAllReceiver, allUserFilter, 1737 mHandler, UserHandle.ALL); 1738 1739 mSubscriptionManager.addOnSubscriptionsChangedListener(mSubscriptionListener); 1740 try { 1741 ActivityManager.getService().registerUserSwitchObserver(mUserSwitchObserver, TAG); 1742 } catch (RemoteException e) { 1743 e.rethrowAsRuntimeException(); 1744 } 1745 1746 mTrustManager = context.getSystemService(TrustManager.class); 1747 mTrustManager.registerTrustListener(this); 1748 1749 setStrongAuthTracker(mStrongAuthTracker); 1750 1751 mDreamManager = IDreamManager.Stub.asInterface( 1752 ServiceManager.getService(DreamService.DREAM_SERVICE)); 1753 1754 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) { 1755 mFpm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE); 1756 } 1757 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) { 1758 mFaceManager = (FaceManager) context.getSystemService(Context.FACE_SERVICE); 1759 } 1760 1761 if (mFpm != null || mFaceManager != null) { 1762 mBiometricManager = context.getSystemService(BiometricManager.class); 1763 mBiometricManager.registerEnabledOnKeyguardCallback(mBiometricEnabledCallback); 1764 } 1765 1766 updateBiometricListeningState(); 1767 if (mFpm != null) { 1768 mFpm.addLockoutResetCallback(mFingerprintLockoutResetCallback); 1769 } 1770 if (mFaceManager != null) { 1771 mFaceManager.addLockoutResetCallback(mFaceLockoutResetCallback); 1772 } 1773 1774 mIsAutomotive = isAutomotive(); 1775 1776 ActivityManagerWrapper.getInstance().registerTaskStackListener(mTaskStackListener); 1777 mUserManager = context.getSystemService(UserManager.class); 1778 mIsPrimaryUser = mUserManager.isPrimaryUser(); 1779 int user = ActivityManager.getCurrentUser(); 1780 mUserIsUnlocked.put(user, mUserManager.isUserUnlocked(user)); 1781 mDevicePolicyManager = context.getSystemService(DevicePolicyManager.class); 1782 mLogoutEnabled = mDevicePolicyManager.isLogoutEnabled(); 1783 updateSecondaryLockscreenRequirement(user); 1784 List<UserInfo> allUsers = mUserManager.getUsers(); 1785 for (UserInfo userInfo : allUsers) { 1786 mUserTrustIsUsuallyManaged.put(userInfo.id, 1787 mTrustManager.isTrustUsuallyManaged(userInfo.id)); 1788 } 1789 updateAirplaneModeState(); 1790 1791 mTelephonyManager = 1792 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 1793 if (mTelephonyManager != null) { 1794 mTelephonyManager.listen(mPhoneStateListener, 1795 LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE); 1796 // Set initial sim states values. 1797 for (int slot = 0; slot < mTelephonyManager.getActiveModemCount(); slot++) { 1798 int state = mTelephonyManager.getSimState(slot); 1799 int[] subIds = mSubscriptionManager.getSubscriptionIds(slot); 1800 if (subIds != null) { 1801 for (int subId : subIds) { 1802 mHandler.obtainMessage(MSG_SIM_STATE_CHANGE, subId, slot, state) 1803 .sendToTarget(); 1804 } 1805 } 1806 } 1807 } 1808 } 1809 1810 private final UserSwitchObserver mUserSwitchObserver = new UserSwitchObserver() { 1811 @Override 1812 public void onUserSwitching(int newUserId, IRemoteCallback reply) { 1813 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCHING, 1814 newUserId, 0, reply)); 1815 } 1816 1817 @Override 1818 public void onUserSwitchComplete(int newUserId) throws RemoteException { 1819 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCH_COMPLETE, 1820 newUserId, 0)); 1821 } 1822 }; 1823 updateAirplaneModeState()1824 private void updateAirplaneModeState() { 1825 // ACTION_AIRPLANE_MODE_CHANGED do not broadcast if device set AirplaneMode ON and boot 1826 if (!WirelessUtils.isAirplaneModeOn(mContext) 1827 || mHandler.hasMessages(MSG_AIRPLANE_MODE_CHANGED)) { 1828 return; 1829 } 1830 mHandler.sendEmptyMessage(MSG_AIRPLANE_MODE_CHANGED); 1831 } 1832 updateBiometricListeningState()1833 private void updateBiometricListeningState() { 1834 updateFingerprintListeningState(); 1835 updateFaceListeningState(); 1836 } 1837 updateFingerprintListeningState()1838 private void updateFingerprintListeningState() { 1839 // If this message exists, we should not authenticate again until this message is 1840 // consumed by the handler 1841 if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) { 1842 return; 1843 } 1844 mHandler.removeCallbacks(mRetryFingerprintAuthentication); 1845 boolean shouldListenForFingerprint = shouldListenForFingerprint(); 1846 boolean runningOrRestarting = mFingerprintRunningState == BIOMETRIC_STATE_RUNNING 1847 || mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING; 1848 if (runningOrRestarting && !shouldListenForFingerprint) { 1849 stopListeningForFingerprint(); 1850 } else if (!runningOrRestarting && shouldListenForFingerprint) { 1851 startListeningForFingerprint(); 1852 } 1853 } 1854 1855 /** 1856 * If a user is encrypted or not. 1857 * This is NOT related to the lock screen being visible or not. 1858 * 1859 * @param userId The user. 1860 * @return {@code true} when encrypted. 1861 * @see UserManager#isUserUnlocked() 1862 * @see Intent#ACTION_USER_UNLOCKED 1863 */ isUserUnlocked(int userId)1864 public boolean isUserUnlocked(int userId) { 1865 return mUserIsUnlocked.get(userId); 1866 } 1867 1868 /** 1869 * Called whenever passive authentication is requested or aborted by a sensor. 1870 * 1871 * @param active If the interrupt started or ended. 1872 */ onAuthInterruptDetected(boolean active)1873 public void onAuthInterruptDetected(boolean active) { 1874 if (DEBUG) Log.d(TAG, "onAuthInterruptDetected(" + active + ")"); 1875 if (mAuthInterruptActive == active) { 1876 return; 1877 } 1878 mAuthInterruptActive = active; 1879 updateFaceListeningState(); 1880 } 1881 1882 /** 1883 * Requests face authentication if we're on a state where it's allowed. 1884 * This will re-trigger auth in case it fails. 1885 */ requestFaceAuth()1886 public void requestFaceAuth() { 1887 if (DEBUG) Log.d(TAG, "requestFaceAuth()"); 1888 updateFaceListeningState(); 1889 } 1890 1891 /** 1892 * In case face auth is running, cancel it. 1893 */ cancelFaceAuth()1894 public void cancelFaceAuth() { 1895 stopListeningForFace(); 1896 } 1897 updateFaceListeningState()1898 private void updateFaceListeningState() { 1899 // If this message exists, we should not authenticate again until this message is 1900 // consumed by the handler 1901 if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) { 1902 return; 1903 } 1904 mHandler.removeCallbacks(mRetryFaceAuthentication); 1905 boolean shouldListenForFace = shouldListenForFace(); 1906 if (mFaceRunningState == BIOMETRIC_STATE_RUNNING && !shouldListenForFace) { 1907 stopListeningForFace(); 1908 } else if (mFaceRunningState != BIOMETRIC_STATE_RUNNING && shouldListenForFace) { 1909 startListeningForFace(); 1910 } 1911 } 1912 shouldListenForFingerprintAssistant()1913 private boolean shouldListenForFingerprintAssistant() { 1914 BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(getCurrentUser()); 1915 return mAssistantVisible && mKeyguardOccluded 1916 && !(fingerprint != null && fingerprint.mAuthenticated) 1917 && !mUserHasTrust.get(getCurrentUser(), false); 1918 } 1919 shouldListenForFaceAssistant()1920 private boolean shouldListenForFaceAssistant() { 1921 BiometricAuthenticated face = mUserFaceAuthenticated.get(getCurrentUser()); 1922 return mAssistantVisible && mKeyguardOccluded 1923 && !(face != null && face.mAuthenticated) 1924 && !mUserHasTrust.get(getCurrentUser(), false); 1925 } 1926 shouldListenForFingerprint()1927 private boolean shouldListenForFingerprint() { 1928 final boolean allowedOnBouncer = 1929 !(mFingerprintLockedOut && mBouncer && mCredentialAttempted); 1930 1931 // Only listen if this KeyguardUpdateMonitor belongs to the primary user. There is an 1932 // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware. 1933 final boolean shouldListen = (mKeyguardIsVisible || !mDeviceInteractive || 1934 (mBouncer && !mKeyguardGoingAway) || mGoingToSleep || 1935 shouldListenForFingerprintAssistant() || (mKeyguardOccluded && mIsDreaming)) 1936 && !mSwitchingUser && !isFingerprintDisabled(getCurrentUser()) 1937 && (!mKeyguardGoingAway || !mDeviceInteractive) && mIsPrimaryUser 1938 && allowedOnBouncer; 1939 return shouldListen; 1940 } 1941 1942 /** 1943 * If face auth is allows to scan on this exact moment. 1944 */ shouldListenForFace()1945 public boolean shouldListenForFace() { 1946 final boolean statusBarShadeLocked = 1947 mStatusBarStateController.getState() == StatusBarState.SHADE_LOCKED; 1948 final boolean awakeKeyguard = mKeyguardIsVisible && mDeviceInteractive && !mGoingToSleep 1949 && !statusBarShadeLocked; 1950 final int user = getCurrentUser(); 1951 final int strongAuth = mStrongAuthTracker.getStrongAuthForUser(user); 1952 final boolean isLockDown = 1953 containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) 1954 || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN); 1955 final boolean isEncryptedOrTimedOut = 1956 containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_BOOT) 1957 || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_TIMEOUT); 1958 1959 boolean canBypass = mKeyguardBypassController != null 1960 && mKeyguardBypassController.canBypass(); 1961 // There's no reason to ask the HAL for authentication when the user can dismiss the 1962 // bouncer, unless we're bypassing and need to auto-dismiss the lock screen even when 1963 // TrustAgents or biometrics are keeping the device unlocked. 1964 boolean becauseCannotSkipBouncer = !getUserCanSkipBouncer(user) || canBypass; 1965 1966 // Scan even when encrypted or timeout to show a preemptive bouncer when bypassing. 1967 // Lock-down mode shouldn't scan, since it is more explicit. 1968 boolean strongAuthAllowsScanning = (!isEncryptedOrTimedOut || canBypass && !mBouncer) 1969 && !isLockDown; 1970 1971 // Only listen if this KeyguardUpdateMonitor belongs to the primary user. There is an 1972 // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware. 1973 final boolean shouldListen = 1974 (mBouncer || mAuthInterruptActive || awakeKeyguard 1975 || shouldListenForFaceAssistant()) 1976 && !mSwitchingUser && !isFaceDisabled(user) && becauseCannotSkipBouncer 1977 && !mKeyguardGoingAway && mFaceSettingEnabledForUser.get(user) && !mLockIconPressed 1978 && strongAuthAllowsScanning && mIsPrimaryUser 1979 && !mSecureCameraLaunched; 1980 1981 // Aggregate relevant fields for debug logging. 1982 if (DEBUG_FACE || DEBUG_SPEW) { 1983 final KeyguardFaceListenModel model = new KeyguardFaceListenModel( 1984 System.currentTimeMillis(), 1985 user, 1986 shouldListen, 1987 mBouncer, 1988 mAuthInterruptActive, 1989 awakeKeyguard, 1990 shouldListenForFaceAssistant(), 1991 mSwitchingUser, 1992 isFaceDisabled(user), 1993 becauseCannotSkipBouncer, 1994 mKeyguardGoingAway, 1995 mFaceSettingEnabledForUser.get(user), 1996 mLockIconPressed, 1997 strongAuthAllowsScanning, 1998 mIsPrimaryUser, 1999 mSecureCameraLaunched); 2000 maybeLogFaceListenerModelData(model); 2001 } 2002 2003 return shouldListen; 2004 } 2005 maybeLogFaceListenerModelData(KeyguardFaceListenModel model)2006 private void maybeLogFaceListenerModelData(KeyguardFaceListenModel model) { 2007 // Too chatty, but very useful when debugging issues. 2008 if (DEBUG_SPEW) { 2009 Log.v(TAG, model.toString()); 2010 } 2011 2012 // Add model data to the historical buffer. 2013 if (DEBUG_FACE && mFaceRunningState != BIOMETRIC_STATE_RUNNING 2014 && model.isListeningForFace()) { 2015 if (mFaceListenModels == null) { 2016 mFaceListenModels = new ArrayDeque<>(FACE_LISTEN_CALLS_QUEUE_SIZE); 2017 } 2018 if (mFaceListenModels.size() >= FACE_LISTEN_CALLS_QUEUE_SIZE) { 2019 mFaceListenModels.remove(); 2020 } 2021 mFaceListenModels.add(model); 2022 } 2023 } 2024 2025 /** 2026 * Whenever the lock icon is long pressed, disabling trust agents. 2027 * This means that we cannot auth passively (face) until the user presses power. 2028 */ onLockIconPressed()2029 public void onLockIconPressed() { 2030 mLockIconPressed = true; 2031 final int userId = getCurrentUser(); 2032 mUserFaceAuthenticated.put(userId, null); 2033 updateFaceListeningState(); 2034 mStrongAuthTracker.onStrongAuthRequiredChanged(userId); 2035 } 2036 startListeningForFingerprint()2037 private void startListeningForFingerprint() { 2038 if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING) { 2039 setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING); 2040 return; 2041 } 2042 if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { 2043 // Waiting for restart via handleFingerprintError(). 2044 return; 2045 } 2046 if (DEBUG) Log.v(TAG, "startListeningForFingerprint()"); 2047 int userId = getCurrentUser(); 2048 if (isUnlockWithFingerprintPossible(userId)) { 2049 if (mFingerprintCancelSignal != null) { 2050 mFingerprintCancelSignal.cancel(); 2051 } 2052 mFingerprintCancelSignal = new CancellationSignal(); 2053 mFpm.authenticate(null, mFingerprintCancelSignal, 0, mFingerprintAuthenticationCallback, 2054 null, userId); 2055 setFingerprintRunningState(BIOMETRIC_STATE_RUNNING); 2056 } 2057 } 2058 startListeningForFace()2059 private void startListeningForFace() { 2060 if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING) { 2061 setFaceRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING); 2062 return; 2063 } 2064 if (DEBUG) Log.v(TAG, "startListeningForFace()"); 2065 int userId = getCurrentUser(); 2066 if (isUnlockWithFacePossible(userId)) { 2067 if (mFaceCancelSignal != null) { 2068 mFaceCancelSignal.cancel(); 2069 } 2070 mFaceCancelSignal = new CancellationSignal(); 2071 mFaceManager.authenticate(null, mFaceCancelSignal, 0, 2072 mFaceAuthenticationCallback, null, userId); 2073 setFaceRunningState(BIOMETRIC_STATE_RUNNING); 2074 } 2075 } 2076 2077 /** 2078 * If biometrics hardware is available, not disabled, and user has enrolled templates. 2079 * This does NOT check if the device is encrypted or in lockdown. 2080 * 2081 * @param userId User that's trying to unlock. 2082 * @return {@code true} if possible. 2083 */ isUnlockingWithBiometricsPossible(int userId)2084 public boolean isUnlockingWithBiometricsPossible(int userId) { 2085 return isUnlockWithFacePossible(userId) || isUnlockWithFingerprintPossible(userId); 2086 } 2087 isUnlockWithFingerprintPossible(int userId)2088 private boolean isUnlockWithFingerprintPossible(int userId) { 2089 return mFpm != null && mFpm.isHardwareDetected() && !isFingerprintDisabled(userId) 2090 && mFpm.getEnrolledFingerprints(userId).size() > 0; 2091 } 2092 isUnlockWithFacePossible(int userId)2093 private boolean isUnlockWithFacePossible(int userId) { 2094 return isFaceAuthEnabledForUser(userId) && !isFaceDisabled(userId); 2095 } 2096 2097 /** 2098 * If face hardware is available, user has enrolled and enabled auth via setting. 2099 */ isFaceAuthEnabledForUser(int userId)2100 public boolean isFaceAuthEnabledForUser(int userId) { 2101 // TODO(b/140034352) 2102 return whitelistIpcs(() -> mFaceManager != null && mFaceManager.isHardwareDetected() 2103 && mFaceManager.hasEnrolledTemplates(userId) 2104 && mFaceSettingEnabledForUser.get(userId)); 2105 } 2106 stopListeningForFingerprint()2107 private void stopListeningForFingerprint() { 2108 if (DEBUG) Log.v(TAG, "stopListeningForFingerprint()"); 2109 if (mFingerprintRunningState == BIOMETRIC_STATE_RUNNING) { 2110 if (mFingerprintCancelSignal != null) { 2111 mFingerprintCancelSignal.cancel(); 2112 mFingerprintCancelSignal = null; 2113 if (!mHandler.hasCallbacks(mCancelNotReceived)) { 2114 mHandler.postDelayed(mCancelNotReceived, DEFAULT_CANCEL_SIGNAL_TIMEOUT); 2115 } 2116 } 2117 setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING); 2118 } 2119 if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { 2120 setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING); 2121 } 2122 } 2123 stopListeningForFace()2124 private void stopListeningForFace() { 2125 if (DEBUG) Log.v(TAG, "stopListeningForFace()"); 2126 if (mFaceRunningState == BIOMETRIC_STATE_RUNNING) { 2127 if (mFaceCancelSignal != null) { 2128 mFaceCancelSignal.cancel(); 2129 mFaceCancelSignal = null; 2130 if (!mHandler.hasCallbacks(mCancelNotReceived)) { 2131 mHandler.postDelayed(mCancelNotReceived, DEFAULT_CANCEL_SIGNAL_TIMEOUT); 2132 } 2133 } 2134 setFaceRunningState(BIOMETRIC_STATE_CANCELLING); 2135 } 2136 if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { 2137 setFaceRunningState(BIOMETRIC_STATE_CANCELLING); 2138 } 2139 } 2140 isDeviceProvisionedInSettingsDb()2141 private boolean isDeviceProvisionedInSettingsDb() { 2142 return Settings.Global.getInt(mContext.getContentResolver(), 2143 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 2144 } 2145 watchForDeviceProvisioning()2146 private void watchForDeviceProvisioning() { 2147 mDeviceProvisionedObserver = new ContentObserver(mHandler) { 2148 @Override 2149 public void onChange(boolean selfChange) { 2150 super.onChange(selfChange); 2151 mDeviceProvisioned = isDeviceProvisionedInSettingsDb(); 2152 if (mDeviceProvisioned) { 2153 mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED); 2154 } 2155 if (DEBUG) Log.d(TAG, "DEVICE_PROVISIONED state = " + mDeviceProvisioned); 2156 } 2157 }; 2158 2159 mContext.getContentResolver().registerContentObserver( 2160 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), 2161 false, mDeviceProvisionedObserver); 2162 2163 // prevent a race condition between where we check the flag and where we register the 2164 // observer by grabbing the value once again... 2165 boolean provisioned = isDeviceProvisionedInSettingsDb(); 2166 if (provisioned != mDeviceProvisioned) { 2167 mDeviceProvisioned = provisioned; 2168 if (mDeviceProvisioned) { 2169 mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED); 2170 } 2171 } 2172 } 2173 2174 /** 2175 * Update the state whether Keyguard currently has a lockscreen wallpaper. 2176 * 2177 * @param hasLockscreenWallpaper Whether Keyguard has a lockscreen wallpaper. 2178 */ setHasLockscreenWallpaper(boolean hasLockscreenWallpaper)2179 public void setHasLockscreenWallpaper(boolean hasLockscreenWallpaper) { 2180 Assert.isMainThread(); 2181 if (hasLockscreenWallpaper != mHasLockscreenWallpaper) { 2182 mHasLockscreenWallpaper = hasLockscreenWallpaper; 2183 for (int i = 0; i < mCallbacks.size(); i++) { 2184 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2185 if (cb != null) { 2186 cb.onHasLockscreenWallpaperChanged(hasLockscreenWallpaper); 2187 } 2188 } 2189 } 2190 } 2191 2192 /** 2193 * @return Whether Keyguard has a lockscreen wallpaper. 2194 */ hasLockscreenWallpaper()2195 public boolean hasLockscreenWallpaper() { 2196 return mHasLockscreenWallpaper; 2197 } 2198 2199 /** 2200 * Handle {@link #MSG_DPM_STATE_CHANGED} 2201 */ handleDevicePolicyManagerStateChanged(int userId)2202 private void handleDevicePolicyManagerStateChanged(int userId) { 2203 Assert.isMainThread(); 2204 updateFingerprintListeningState(); 2205 updateSecondaryLockscreenRequirement(userId); 2206 for (int i = 0; i < mCallbacks.size(); i++) { 2207 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2208 if (cb != null) { 2209 cb.onDevicePolicyManagerStateChanged(); 2210 } 2211 } 2212 } 2213 2214 /** 2215 * Handle {@link #MSG_USER_SWITCHING} 2216 */ 2217 @VisibleForTesting handleUserSwitching(int userId, IRemoteCallback reply)2218 void handleUserSwitching(int userId, IRemoteCallback reply) { 2219 Assert.isMainThread(); 2220 clearBiometricRecognized(); 2221 mUserTrustIsUsuallyManaged.put(userId, mTrustManager.isTrustUsuallyManaged(userId)); 2222 for (int i = 0; i < mCallbacks.size(); i++) { 2223 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2224 if (cb != null) { 2225 cb.onUserSwitching(userId); 2226 } 2227 } 2228 try { 2229 reply.sendResult(null); 2230 } catch (RemoteException e) { 2231 } 2232 } 2233 2234 /** 2235 * Handle {@link #MSG_USER_SWITCH_COMPLETE} 2236 */ handleUserSwitchComplete(int userId)2237 private void handleUserSwitchComplete(int userId) { 2238 Assert.isMainThread(); 2239 for (int i = 0; i < mCallbacks.size(); i++) { 2240 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2241 if (cb != null) { 2242 cb.onUserSwitchComplete(userId); 2243 } 2244 } 2245 } 2246 2247 /** 2248 * Handle {@link #MSG_DEVICE_PROVISIONED} 2249 */ handleDeviceProvisioned()2250 private void handleDeviceProvisioned() { 2251 Assert.isMainThread(); 2252 for (int i = 0; i < mCallbacks.size(); i++) { 2253 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2254 if (cb != null) { 2255 cb.onDeviceProvisioned(); 2256 } 2257 } 2258 if (mDeviceProvisionedObserver != null) { 2259 // We don't need the observer anymore... 2260 mContext.getContentResolver().unregisterContentObserver(mDeviceProvisionedObserver); 2261 mDeviceProvisionedObserver = null; 2262 } 2263 } 2264 2265 /** 2266 * Handle {@link #MSG_PHONE_STATE_CHANGED} 2267 */ handlePhoneStateChanged(String newState)2268 private void handlePhoneStateChanged(String newState) { 2269 Assert.isMainThread(); 2270 if (DEBUG) Log.d(TAG, "handlePhoneStateChanged(" + newState + ")"); 2271 if (TelephonyManager.EXTRA_STATE_IDLE.equals(newState)) { 2272 mPhoneState = TelephonyManager.CALL_STATE_IDLE; 2273 } else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(newState)) { 2274 mPhoneState = TelephonyManager.CALL_STATE_OFFHOOK; 2275 } else if (TelephonyManager.EXTRA_STATE_RINGING.equals(newState)) { 2276 mPhoneState = TelephonyManager.CALL_STATE_RINGING; 2277 } 2278 for (int i = 0; i < mCallbacks.size(); i++) { 2279 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2280 if (cb != null) { 2281 cb.onPhoneStateChanged(mPhoneState); 2282 } 2283 } 2284 } 2285 2286 /** 2287 * Handle {@link #MSG_RINGER_MODE_CHANGED} 2288 */ handleRingerModeChange(int mode)2289 private void handleRingerModeChange(int mode) { 2290 Assert.isMainThread(); 2291 if (DEBUG) Log.d(TAG, "handleRingerModeChange(" + mode + ")"); 2292 mRingMode = mode; 2293 for (int i = 0; i < mCallbacks.size(); i++) { 2294 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2295 if (cb != null) { 2296 cb.onRingerModeChanged(mode); 2297 } 2298 } 2299 } 2300 2301 /** 2302 * Handle {@link #MSG_TIME_UPDATE} 2303 */ handleTimeUpdate()2304 private void handleTimeUpdate() { 2305 Assert.isMainThread(); 2306 if (DEBUG) Log.d(TAG, "handleTimeUpdate"); 2307 for (int i = 0; i < mCallbacks.size(); i++) { 2308 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2309 if (cb != null) { 2310 cb.onTimeChanged(); 2311 } 2312 } 2313 } 2314 2315 /** 2316 * Handle (@line #MSG_TIMEZONE_UPDATE} 2317 */ handleTimeZoneUpdate(String timeZone)2318 private void handleTimeZoneUpdate(String timeZone) { 2319 Assert.isMainThread(); 2320 if (DEBUG) Log.d(TAG, "handleTimeZoneUpdate"); 2321 for (int i = 0; i < mCallbacks.size(); i++) { 2322 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2323 if (cb != null) { 2324 cb.onTimeZoneChanged(TimeZone.getTimeZone(timeZone)); 2325 // Also notify callbacks about time change to remain compatible. 2326 cb.onTimeChanged(); 2327 } 2328 } 2329 } 2330 2331 /** 2332 * Handle {@link #MSG_BATTERY_UPDATE} 2333 */ handleBatteryUpdate(BatteryStatus status)2334 private void handleBatteryUpdate(BatteryStatus status) { 2335 Assert.isMainThread(); 2336 if (DEBUG) Log.d(TAG, "handleBatteryUpdate"); 2337 final boolean batteryUpdateInteresting = isBatteryUpdateInteresting(mBatteryStatus, status); 2338 mBatteryStatus = status; 2339 if (batteryUpdateInteresting) { 2340 for (int i = 0; i < mCallbacks.size(); i++) { 2341 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2342 if (cb != null) { 2343 cb.onRefreshBatteryInfo(status); 2344 } 2345 } 2346 } 2347 } 2348 2349 /** 2350 * Handle Telephony status during Boot for CarrierText display policy 2351 */ 2352 @VisibleForTesting updateTelephonyCapable(boolean capable)2353 void updateTelephonyCapable(boolean capable) { 2354 Assert.isMainThread(); 2355 if (capable == mTelephonyCapable) { 2356 return; 2357 } 2358 mTelephonyCapable = capable; 2359 for (int i = 0; i < mCallbacks.size(); i++) { 2360 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2361 if (cb != null) { 2362 cb.onTelephonyCapable(mTelephonyCapable); 2363 } 2364 } 2365 } 2366 2367 /** 2368 * Handle {@link #MSG_SIM_STATE_CHANGE} 2369 */ 2370 @VisibleForTesting handleSimStateChange(int subId, int slotId, int state)2371 void handleSimStateChange(int subId, int slotId, int state) { 2372 Assert.isMainThread(); 2373 if (DEBUG_SIM_STATES) { 2374 Log.d(TAG, "handleSimStateChange(subId=" + subId + ", slotId=" 2375 + slotId + ", state=" + state + ")"); 2376 } 2377 2378 boolean becameAbsent = false; 2379 if (!SubscriptionManager.isValidSubscriptionId(subId)) { 2380 Log.w(TAG, "invalid subId in handleSimStateChange()"); 2381 /* Only handle No SIM(ABSENT) and Card Error(CARD_IO_ERROR) due to 2382 * handleServiceStateChange() handle other case */ 2383 if (state == TelephonyManager.SIM_STATE_ABSENT) { 2384 updateTelephonyCapable(true); 2385 // Even though the subscription is not valid anymore, we need to notify that the 2386 // SIM card was removed so we can update the UI. 2387 becameAbsent = true; 2388 for (SimData data : mSimDatas.values()) { 2389 // Set the SIM state of all SimData associated with that slot to ABSENT se we 2390 // do not move back into PIN/PUK locked and not detect the change below. 2391 if (data.slotId == slotId) { 2392 data.simState = TelephonyManager.SIM_STATE_ABSENT; 2393 } 2394 } 2395 } else if (state == TelephonyManager.SIM_STATE_CARD_IO_ERROR) { 2396 updateTelephonyCapable(true); 2397 } else { 2398 return; 2399 } 2400 } 2401 2402 SimData data = mSimDatas.get(subId); 2403 final boolean changed; 2404 if (data == null) { 2405 data = new SimData(state, slotId, subId); 2406 mSimDatas.put(subId, data); 2407 changed = true; // no data yet; force update 2408 } else { 2409 changed = (data.simState != state || data.subId != subId || data.slotId != slotId); 2410 data.simState = state; 2411 data.subId = subId; 2412 data.slotId = slotId; 2413 } 2414 if ((changed || becameAbsent) && state != TelephonyManager.SIM_STATE_UNKNOWN) { 2415 for (int i = 0; i < mCallbacks.size(); i++) { 2416 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2417 if (cb != null) { 2418 cb.onSimStateChanged(subId, slotId, state); 2419 } 2420 } 2421 } 2422 } 2423 2424 /** 2425 * Handle {@link #MSG_SERVICE_STATE_CHANGE} 2426 */ 2427 @VisibleForTesting handleServiceStateChange(int subId, ServiceState serviceState)2428 void handleServiceStateChange(int subId, ServiceState serviceState) { 2429 if (DEBUG) { 2430 Log.d(TAG, 2431 "handleServiceStateChange(subId=" + subId + ", serviceState=" + serviceState); 2432 } 2433 2434 if (!SubscriptionManager.isValidSubscriptionId(subId)) { 2435 Log.w(TAG, "invalid subId in handleServiceStateChange()"); 2436 return; 2437 } else { 2438 updateTelephonyCapable(true); 2439 } 2440 2441 mServiceStates.put(subId, serviceState); 2442 2443 callbacksRefreshCarrierInfo(); 2444 } 2445 isKeyguardVisible()2446 public boolean isKeyguardVisible() { 2447 return mKeyguardIsVisible; 2448 } 2449 2450 /** 2451 * Notifies that the visibility state of Keyguard has changed. 2452 * 2453 * <p>Needs to be called from the main thread. 2454 */ onKeyguardVisibilityChanged(boolean showing)2455 public void onKeyguardVisibilityChanged(boolean showing) { 2456 Assert.isMainThread(); 2457 Log.d(TAG, "onKeyguardVisibilityChanged(" + showing + ")"); 2458 mKeyguardIsVisible = showing; 2459 2460 if (showing) { 2461 mSecureCameraLaunched = false; 2462 } 2463 2464 for (int i = 0; i < mCallbacks.size(); i++) { 2465 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2466 if (cb != null) { 2467 cb.onKeyguardVisibilityChangedRaw(showing); 2468 } 2469 } 2470 updateBiometricListeningState(); 2471 } 2472 2473 /** 2474 * Handle {@link #MSG_KEYGUARD_RESET} 2475 */ handleKeyguardReset()2476 private void handleKeyguardReset() { 2477 if (DEBUG) Log.d(TAG, "handleKeyguardReset"); 2478 updateBiometricListeningState(); 2479 mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition(); 2480 } 2481 resolveNeedsSlowUnlockTransition()2482 private boolean resolveNeedsSlowUnlockTransition() { 2483 if (isUserUnlocked(getCurrentUser())) { 2484 return false; 2485 } 2486 Intent homeIntent = new Intent(Intent.ACTION_MAIN) 2487 .addCategory(Intent.CATEGORY_HOME); 2488 ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(homeIntent, 2489 0 /* flags */); 2490 2491 // TODO(b/160971249): Replace in the future by resolving activity as user. 2492 if (resolveInfo == null && mIsAutomotive) { 2493 Log.w(TAG, "resolveNeedsSlowUnlockTransition: returning false since activity " 2494 + "could not be resolved."); 2495 return false; 2496 } 2497 2498 return FALLBACK_HOME_COMPONENT.equals(resolveInfo.getComponentInfo().getComponentName()); 2499 } 2500 2501 /** 2502 * Handle {@link #MSG_KEYGUARD_BOUNCER_CHANGED} 2503 * 2504 * @see #sendKeyguardBouncerChanged(boolean) 2505 */ handleKeyguardBouncerChanged(int bouncer)2506 private void handleKeyguardBouncerChanged(int bouncer) { 2507 Assert.isMainThread(); 2508 if (DEBUG) Log.d(TAG, "handleKeyguardBouncerChanged(" + bouncer + ")"); 2509 boolean isBouncer = (bouncer == 1); 2510 mBouncer = isBouncer; 2511 2512 if (isBouncer) { 2513 // If the bouncer is shown, always clear this flag. This can happen in the following 2514 // situations: 1) Default camera with SHOW_WHEN_LOCKED is not chosen yet. 2) Secure 2515 // camera requests dismiss keyguard (tapping on photos for example). When these happen, 2516 // face auth should resume. 2517 mSecureCameraLaunched = false; 2518 } else { 2519 mCredentialAttempted = false; 2520 } 2521 2522 for (int i = 0; i < mCallbacks.size(); i++) { 2523 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2524 if (cb != null) { 2525 cb.onKeyguardBouncerChanged(isBouncer); 2526 } 2527 } 2528 updateBiometricListeningState(); 2529 } 2530 2531 /** 2532 * Handle {@link #MSG_REPORT_EMERGENCY_CALL_ACTION} 2533 */ handleReportEmergencyCallAction()2534 private void handleReportEmergencyCallAction() { 2535 Assert.isMainThread(); 2536 for (int i = 0; i < mCallbacks.size(); i++) { 2537 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2538 if (cb != null) { 2539 cb.onEmergencyCallAction(); 2540 } 2541 } 2542 } 2543 isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current)2544 private boolean isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current) { 2545 final boolean nowPluggedIn = current.isPluggedIn(); 2546 final boolean wasPluggedIn = old.isPluggedIn(); 2547 final boolean stateChangedWhilePluggedIn = wasPluggedIn && nowPluggedIn 2548 && (old.status != current.status); 2549 2550 // change in plug state is always interesting 2551 if (wasPluggedIn != nowPluggedIn || stateChangedWhilePluggedIn) { 2552 return true; 2553 } 2554 2555 // change in battery level 2556 if (old.level != current.level) { 2557 return true; 2558 } 2559 2560 // change in charging current while plugged in 2561 if (nowPluggedIn && current.maxChargingWattage != old.maxChargingWattage) { 2562 return true; 2563 } 2564 2565 return false; 2566 } 2567 isAutomotive()2568 private boolean isAutomotive() { 2569 return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE); 2570 } 2571 2572 /** 2573 * Remove the given observer's callback. 2574 * 2575 * @param callback The callback to remove 2576 */ removeCallback(KeyguardUpdateMonitorCallback callback)2577 public void removeCallback(KeyguardUpdateMonitorCallback callback) { 2578 Assert.isMainThread(); 2579 if (DEBUG) { 2580 Log.v(TAG, "*** unregister callback for " + callback); 2581 } 2582 2583 mCallbacks.removeIf(el -> el.get() == callback); 2584 } 2585 2586 /** 2587 * Register to receive notifications about general keyguard information 2588 * (see {@link InfoCallback}. 2589 * 2590 * @param callback The callback to register 2591 */ registerCallback(KeyguardUpdateMonitorCallback callback)2592 public void registerCallback(KeyguardUpdateMonitorCallback callback) { 2593 Assert.isMainThread(); 2594 if (DEBUG) Log.v(TAG, "*** register callback for " + callback); 2595 // Prevent adding duplicate callbacks 2596 2597 for (int i = 0; i < mCallbacks.size(); i++) { 2598 if (mCallbacks.get(i).get() == callback) { 2599 if (DEBUG) { 2600 Log.e(TAG, "Object tried to add another callback", 2601 new Exception("Called by")); 2602 } 2603 return; 2604 } 2605 } 2606 mCallbacks.add(new WeakReference<>(callback)); 2607 removeCallback(null); // remove unused references 2608 sendUpdates(callback); 2609 } 2610 setKeyguardBypassController(KeyguardBypassController keyguardBypassController)2611 public void setKeyguardBypassController(KeyguardBypassController keyguardBypassController) { 2612 mKeyguardBypassController = keyguardBypassController; 2613 } 2614 isSwitchingUser()2615 public boolean isSwitchingUser() { 2616 return mSwitchingUser; 2617 } 2618 2619 @AnyThread setSwitchingUser(boolean switching)2620 public void setSwitchingUser(boolean switching) { 2621 mSwitchingUser = switching; 2622 // Since this comes in on a binder thread, we need to post if first 2623 mHandler.post(mUpdateBiometricListeningState); 2624 } 2625 sendUpdates(KeyguardUpdateMonitorCallback callback)2626 private void sendUpdates(KeyguardUpdateMonitorCallback callback) { 2627 // Notify listener of the current state 2628 callback.onRefreshBatteryInfo(mBatteryStatus); 2629 callback.onTimeChanged(); 2630 callback.onRingerModeChanged(mRingMode); 2631 callback.onPhoneStateChanged(mPhoneState); 2632 callback.onRefreshCarrierInfo(); 2633 callback.onClockVisibilityChanged(); 2634 callback.onKeyguardVisibilityChangedRaw(mKeyguardIsVisible); 2635 callback.onTelephonyCapable(mTelephonyCapable); 2636 for (Entry<Integer, SimData> data : mSimDatas.entrySet()) { 2637 final SimData state = data.getValue(); 2638 callback.onSimStateChanged(state.subId, state.slotId, state.simState); 2639 } 2640 } 2641 sendKeyguardReset()2642 public void sendKeyguardReset() { 2643 mHandler.obtainMessage(MSG_KEYGUARD_RESET).sendToTarget(); 2644 } 2645 2646 /** 2647 * @see #handleKeyguardBouncerChanged(int) 2648 */ sendKeyguardBouncerChanged(boolean showingBouncer)2649 public void sendKeyguardBouncerChanged(boolean showingBouncer) { 2650 if (DEBUG) Log.d(TAG, "sendKeyguardBouncerChanged(" + showingBouncer + ")"); 2651 Message message = mHandler.obtainMessage(MSG_KEYGUARD_BOUNCER_CHANGED); 2652 message.arg1 = showingBouncer ? 1 : 0; 2653 message.sendToTarget(); 2654 } 2655 2656 /** 2657 * Report that the user successfully entered the SIM PIN or PUK/SIM PIN so we 2658 * have the information earlier than waiting for the intent 2659 * broadcast from the telephony code. 2660 * 2661 * NOTE: Because handleSimStateChange() invokes callbacks immediately without going 2662 * through mHandler, this *must* be called from the UI thread. 2663 */ 2664 @MainThread reportSimUnlocked(int subId)2665 public void reportSimUnlocked(int subId) { 2666 if (DEBUG_SIM_STATES) Log.v(TAG, "reportSimUnlocked(subId=" + subId + ")"); 2667 handleSimStateChange(subId, getSlotId(subId), TelephonyManager.SIM_STATE_READY); 2668 } 2669 2670 /** 2671 * Report that the emergency call button has been pressed and the emergency dialer is 2672 * about to be displayed. 2673 * 2674 * @param bypassHandler runs immediately. 2675 * 2676 * NOTE: Must be called from UI thread if bypassHandler == true. 2677 */ reportEmergencyCallAction(boolean bypassHandler)2678 public void reportEmergencyCallAction(boolean bypassHandler) { 2679 if (!bypassHandler) { 2680 mHandler.obtainMessage(MSG_REPORT_EMERGENCY_CALL_ACTION).sendToTarget(); 2681 } else { 2682 Assert.isMainThread(); 2683 handleReportEmergencyCallAction(); 2684 } 2685 } 2686 2687 /** 2688 * @return Whether the device is provisioned (whether they have gone through 2689 * the setup wizard) 2690 */ isDeviceProvisioned()2691 public boolean isDeviceProvisioned() { 2692 return mDeviceProvisioned; 2693 } 2694 getServiceState(int subId)2695 public ServiceState getServiceState(int subId) { 2696 return mServiceStates.get(subId); 2697 } 2698 clearBiometricRecognized()2699 public void clearBiometricRecognized() { 2700 Assert.isMainThread(); 2701 mUserFingerprintAuthenticated.clear(); 2702 mUserFaceAuthenticated.clear(); 2703 mTrustManager.clearAllBiometricRecognized(BiometricSourceType.FINGERPRINT); 2704 mTrustManager.clearAllBiometricRecognized(BiometricSourceType.FACE); 2705 2706 for (int i = 0; i < mCallbacks.size(); i++) { 2707 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2708 if (cb != null) { 2709 cb.onBiometricsCleared(); 2710 } 2711 } 2712 } 2713 isSimPinVoiceSecure()2714 public boolean isSimPinVoiceSecure() { 2715 // TODO: only count SIMs that handle voice 2716 return isSimPinSecure(); 2717 } 2718 2719 /** 2720 * If any SIM cards are currently secure. 2721 * 2722 * @see #isSimPinSecure(State) 2723 */ isSimPinSecure()2724 public boolean isSimPinSecure() { 2725 // True if any SIM is pin secure 2726 for (SubscriptionInfo info : getSubscriptionInfo(false /* forceReload */)) { 2727 if (isSimPinSecure(getSimState(info.getSubscriptionId()))) return true; 2728 } 2729 return false; 2730 } 2731 getSimState(int subId)2732 public int getSimState(int subId) { 2733 if (mSimDatas.containsKey(subId)) { 2734 return mSimDatas.get(subId).simState; 2735 } else { 2736 return TelephonyManager.SIM_STATE_UNKNOWN; 2737 } 2738 } 2739 getSlotId(int subId)2740 private int getSlotId(int subId) { 2741 if (!mSimDatas.containsKey(subId)) { 2742 refreshSimState(subId, SubscriptionManager.getSlotIndex(subId)); 2743 } 2744 return mSimDatas.get(subId).slotId; 2745 } 2746 2747 private final TaskStackChangeListener 2748 mTaskStackListener = new TaskStackChangeListener() { 2749 @Override 2750 public void onTaskStackChangedBackground() { 2751 try { 2752 ActivityManager.StackInfo info = ActivityTaskManager.getService().getStackInfo( 2753 WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_ASSISTANT); 2754 if (info == null) { 2755 return; 2756 } 2757 mHandler.sendMessage(mHandler.obtainMessage(MSG_ASSISTANT_STACK_CHANGED, 2758 info.visible)); 2759 } catch (RemoteException e) { 2760 Log.e(TAG, "unable to check task stack", e); 2761 } 2762 } 2763 }; 2764 2765 /** 2766 * @return true if and only if the state has changed for the specified {@code slotId} 2767 */ refreshSimState(int subId, int slotId)2768 private boolean refreshSimState(int subId, int slotId) { 2769 final TelephonyManager tele = 2770 (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 2771 int state = (tele != null) ? 2772 tele.getSimState(slotId) : TelephonyManager.SIM_STATE_UNKNOWN; 2773 SimData data = mSimDatas.get(subId); 2774 final boolean changed; 2775 if (data == null) { 2776 data = new SimData(state, slotId, subId); 2777 mSimDatas.put(subId, data); 2778 changed = true; // no data yet; force update 2779 } else { 2780 changed = data.simState != state; 2781 data.simState = state; 2782 } 2783 return changed; 2784 } 2785 2786 /** 2787 * If the {@code state} is currently requiring a SIM PIN, PUK, or is disabled. 2788 */ isSimPinSecure(int state)2789 public static boolean isSimPinSecure(int state) { 2790 return (state == TelephonyManager.SIM_STATE_PIN_REQUIRED 2791 || state == TelephonyManager.SIM_STATE_PUK_REQUIRED 2792 || state == TelephonyManager.SIM_STATE_PERM_DISABLED); 2793 } 2794 getCachedDisplayClientState()2795 public DisplayClientState getCachedDisplayClientState() { 2796 return mDisplayClientState; 2797 } 2798 2799 // TODO: use these callbacks elsewhere in place of the existing notifyScreen*() 2800 // (KeyguardViewMediator, KeyguardHostView) dispatchStartedWakingUp()2801 public void dispatchStartedWakingUp() { 2802 synchronized (this) { 2803 mDeviceInteractive = true; 2804 } 2805 mHandler.sendEmptyMessage(MSG_STARTED_WAKING_UP); 2806 } 2807 dispatchStartedGoingToSleep(int why)2808 public void dispatchStartedGoingToSleep(int why) { 2809 mHandler.sendMessage(mHandler.obtainMessage(MSG_STARTED_GOING_TO_SLEEP, why, 0)); 2810 } 2811 dispatchFinishedGoingToSleep(int why)2812 public void dispatchFinishedGoingToSleep(int why) { 2813 synchronized (this) { 2814 mDeviceInteractive = false; 2815 } 2816 mHandler.sendMessage(mHandler.obtainMessage(MSG_FINISHED_GOING_TO_SLEEP, why, 0)); 2817 } 2818 dispatchScreenTurnedOn()2819 public void dispatchScreenTurnedOn() { 2820 synchronized (this) { 2821 mScreenOn = true; 2822 } 2823 mHandler.sendEmptyMessage(MSG_SCREEN_TURNED_ON); 2824 } 2825 dispatchScreenTurnedOff()2826 public void dispatchScreenTurnedOff() { 2827 synchronized (this) { 2828 mScreenOn = false; 2829 } 2830 mHandler.sendEmptyMessage(MSG_SCREEN_TURNED_OFF); 2831 } 2832 dispatchDreamingStarted()2833 public void dispatchDreamingStarted() { 2834 mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 1, 0)); 2835 } 2836 dispatchDreamingStopped()2837 public void dispatchDreamingStopped() { 2838 mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 0, 0)); 2839 } 2840 2841 /** 2842 * Sends a message to update the keyguard going away state on the main thread. 2843 * 2844 * @param goingAway Whether the keyguard is going away. 2845 */ dispatchKeyguardGoingAway(boolean goingAway)2846 public void dispatchKeyguardGoingAway(boolean goingAway) { 2847 mHandler.sendMessage(mHandler.obtainMessage(MSG_KEYGUARD_GOING_AWAY, goingAway)); 2848 } 2849 isDeviceInteractive()2850 public boolean isDeviceInteractive() { 2851 return mDeviceInteractive; 2852 } 2853 isGoingToSleep()2854 public boolean isGoingToSleep() { 2855 return mGoingToSleep; 2856 } 2857 2858 /** 2859 * Find the next SubscriptionId for a SIM in the given state, favoring lower slot numbers first. 2860 * 2861 * @return subid or {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID} if none found 2862 */ getNextSubIdForState(int state)2863 public int getNextSubIdForState(int state) { 2864 List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */); 2865 int resultId = SubscriptionManager.INVALID_SUBSCRIPTION_ID; 2866 int bestSlotId = Integer.MAX_VALUE; // Favor lowest slot first 2867 for (int i = 0; i < list.size(); i++) { 2868 final SubscriptionInfo info = list.get(i); 2869 final int id = info.getSubscriptionId(); 2870 int slotId = getSlotId(id); 2871 if (state == getSimState(id) && bestSlotId > slotId) { 2872 resultId = id; 2873 bestSlotId = slotId; 2874 } 2875 } 2876 return resultId; 2877 } 2878 getSubscriptionInfoForSubId(int subId)2879 public SubscriptionInfo getSubscriptionInfoForSubId(int subId) { 2880 List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */); 2881 for (int i = 0; i < list.size(); i++) { 2882 SubscriptionInfo info = list.get(i); 2883 if (subId == info.getSubscriptionId()) return info; 2884 } 2885 return null; // not found 2886 } 2887 2888 /** 2889 * @return a cached version of DevicePolicyManager.isLogoutEnabled() 2890 */ isLogoutEnabled()2891 public boolean isLogoutEnabled() { 2892 return mLogoutEnabled; 2893 } 2894 updateLogoutEnabled()2895 private void updateLogoutEnabled() { 2896 Assert.isMainThread(); 2897 boolean logoutEnabled = mDevicePolicyManager.isLogoutEnabled(); 2898 if (mLogoutEnabled != logoutEnabled) { 2899 mLogoutEnabled = logoutEnabled; 2900 2901 for (int i = 0; i < mCallbacks.size(); i++) { 2902 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2903 if (cb != null) { 2904 cb.onLogoutEnabledChanged(); 2905 } 2906 } 2907 } 2908 } 2909 2910 /** 2911 * Unregister all listeners. 2912 */ destroy()2913 public void destroy() { 2914 // TODO: inject these dependencies: 2915 TelephonyManager telephony = 2916 (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 2917 if (telephony != null) { 2918 telephony.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE); 2919 } 2920 2921 mSubscriptionManager.removeOnSubscriptionsChangedListener(mSubscriptionListener); 2922 2923 if (mDeviceProvisionedObserver != null) { 2924 mContext.getContentResolver().unregisterContentObserver(mDeviceProvisionedObserver); 2925 } 2926 2927 try { 2928 ActivityManager.getService().unregisterUserSwitchObserver(mUserSwitchObserver); 2929 } catch (RemoteException e) { 2930 Log.d(TAG, "RemoteException onDestroy. cannot unregister userSwitchObserver"); 2931 } 2932 2933 ActivityManagerWrapper.getInstance().unregisterTaskStackListener(mTaskStackListener); 2934 2935 mBroadcastDispatcher.unregisterReceiver(mBroadcastReceiver); 2936 mBroadcastDispatcher.unregisterReceiver(mBroadcastAllReceiver); 2937 mRingerModeTracker.getRingerMode().removeObserver(mRingerModeObserver); 2938 2939 mLockPatternUtils.unregisterStrongAuthTracker(mStrongAuthTracker); 2940 mTrustManager.unregisterTrustListener(this); 2941 2942 mHandler.removeCallbacksAndMessages(null); 2943 } 2944 2945 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2946 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2947 pw.println("KeyguardUpdateMonitor state:"); 2948 pw.println(" SIM States:"); 2949 for (SimData data : mSimDatas.values()) { 2950 pw.println(" " + data.toString()); 2951 } 2952 pw.println(" Subs:"); 2953 if (mSubscriptionInfo != null) { 2954 for (int i = 0; i < mSubscriptionInfo.size(); i++) { 2955 pw.println(" " + mSubscriptionInfo.get(i)); 2956 } 2957 } 2958 pw.println(" Current active data subId=" + mActiveMobileDataSubscription); 2959 pw.println(" Service states:"); 2960 for (int subId : mServiceStates.keySet()) { 2961 pw.println(" " + subId + "=" + mServiceStates.get(subId)); 2962 } 2963 if (mFpm != null && mFpm.isHardwareDetected()) { 2964 final int userId = ActivityManager.getCurrentUser(); 2965 final int strongAuthFlags = mStrongAuthTracker.getStrongAuthForUser(userId); 2966 BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(userId); 2967 pw.println(" Fingerprint state (user=" + userId + ")"); 2968 pw.println(" allowed=" 2969 + (fingerprint != null 2970 && isUnlockingWithBiometricAllowed(fingerprint.mIsStrongBiometric))); 2971 pw.println(" auth'd=" + (fingerprint != null && fingerprint.mAuthenticated)); 2972 pw.println(" authSinceBoot=" 2973 + getStrongAuthTracker().hasUserAuthenticatedSinceBoot()); 2974 pw.println(" disabled(DPM)=" + isFingerprintDisabled(userId)); 2975 pw.println(" possible=" + isUnlockWithFingerprintPossible(userId)); 2976 pw.println(" listening: actual=" + mFingerprintRunningState 2977 + " expected=" + (shouldListenForFingerprint() ? 1 : 0)); 2978 pw.println(" strongAuthFlags=" + Integer.toHexString(strongAuthFlags)); 2979 pw.println(" trustManaged=" + getUserTrustIsManaged(userId)); 2980 } 2981 if (mFaceManager != null && mFaceManager.isHardwareDetected()) { 2982 final int userId = ActivityManager.getCurrentUser(); 2983 final int strongAuthFlags = mStrongAuthTracker.getStrongAuthForUser(userId); 2984 BiometricAuthenticated face = mUserFaceAuthenticated.get(userId); 2985 pw.println(" Face authentication state (user=" + userId + ")"); 2986 pw.println(" allowed=" 2987 + (face != null && isUnlockingWithBiometricAllowed(face.mIsStrongBiometric))); 2988 pw.println(" auth'd=" 2989 + (face != null && face.mAuthenticated)); 2990 pw.println(" authSinceBoot=" 2991 + getStrongAuthTracker().hasUserAuthenticatedSinceBoot()); 2992 pw.println(" disabled(DPM)=" + isFaceDisabled(userId)); 2993 pw.println(" possible=" + isUnlockWithFacePossible(userId)); 2994 pw.println(" strongAuthFlags=" + Integer.toHexString(strongAuthFlags)); 2995 pw.println(" trustManaged=" + getUserTrustIsManaged(userId)); 2996 pw.println(" enabledByUser=" + mFaceSettingEnabledForUser.get(userId)); 2997 pw.println(" mSecureCameraLaunched=" + mSecureCameraLaunched); 2998 } 2999 if (mFaceListenModels != null && !mFaceListenModels.isEmpty()) { 3000 final SimpleDateFormat dateFormat = 3001 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US); 3002 pw.println(" Face listen results (last " + FACE_LISTEN_CALLS_QUEUE_SIZE + " calls):"); 3003 for (final KeyguardFaceListenModel model : mFaceListenModels) { 3004 final String time = dateFormat.format(new Date(model.getTimeMillis())); 3005 pw.println(" " + time + " " + model.toString()); 3006 } 3007 } 3008 if (mIsAutomotive) { 3009 pw.println(" Running on Automotive build"); 3010 } 3011 } 3012 } 3013