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 fingerprint authentication after a successful try. This should 290 * be slightly longer than the time between onFingerprintAuthenticated and 291 * setKeyguardGoingAway(true). 292 */ 293 private static final int FINGERPRINT_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 FINGERPRINT_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 // Only authenticate face once when assistant is visible 784 mAssistantVisible = false; 785 786 // Report unlock with strong or non-strong biometric 787 reportSuccessfulBiometricUnlock(isStrongBiometric, userId); 788 789 Trace.endSection(); 790 } 791 handleFaceAuthFailed()792 private void handleFaceAuthFailed() { 793 Assert.isMainThread(); 794 setFaceRunningState(BIOMETRIC_STATE_STOPPED); 795 for (int i = 0; i < mCallbacks.size(); i++) { 796 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 797 if (cb != null) { 798 cb.onBiometricAuthFailed(BiometricSourceType.FACE); 799 } 800 } 801 handleFaceHelp(BIOMETRIC_HELP_FACE_NOT_RECOGNIZED, 802 mContext.getString(R.string.kg_face_not_recognized)); 803 } 804 handleFaceAcquired(int acquireInfo)805 private void handleFaceAcquired(int acquireInfo) { 806 Assert.isMainThread(); 807 if (acquireInfo != FaceManager.FACE_ACQUIRED_GOOD) { 808 return; 809 } 810 if (DEBUG_FACE) Log.d(TAG, "Face acquired"); 811 for (int i = 0; i < mCallbacks.size(); i++) { 812 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 813 if (cb != null) { 814 cb.onBiometricAcquired(BiometricSourceType.FACE); 815 } 816 } 817 } 818 handleFaceAuthenticated(int authUserId, boolean isStrongBiometric)819 private void handleFaceAuthenticated(int authUserId, boolean isStrongBiometric) { 820 Trace.beginSection("KeyGuardUpdateMonitor#handlerFaceAuthenticated"); 821 try { 822 if (mGoingToSleep) { 823 Log.d(TAG, "Aborted successful auth because device is going to sleep."); 824 return; 825 } 826 final int userId; 827 try { 828 userId = ActivityManager.getService().getCurrentUser().id; 829 } catch (RemoteException e) { 830 Log.e(TAG, "Failed to get current user id: ", e); 831 return; 832 } 833 if (userId != authUserId) { 834 Log.d(TAG, "Face authenticated for wrong user: " + authUserId); 835 return; 836 } 837 if (isFaceDisabled(userId)) { 838 Log.d(TAG, "Face authentication disabled by DPM for userId: " + userId); 839 return; 840 } 841 if (DEBUG_FACE) Log.d(TAG, "Face auth succeeded for user " + userId); 842 onFaceAuthenticated(userId, isStrongBiometric); 843 } finally { 844 setFaceRunningState(BIOMETRIC_STATE_STOPPED); 845 } 846 Trace.endSection(); 847 } 848 handleFaceHelp(int msgId, String helpString)849 private void handleFaceHelp(int msgId, String helpString) { 850 Assert.isMainThread(); 851 if (DEBUG_FACE) Log.d(TAG, "Face help received: " + helpString); 852 for (int i = 0; i < mCallbacks.size(); i++) { 853 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 854 if (cb != null) { 855 cb.onBiometricHelp(msgId, helpString, BiometricSourceType.FACE); 856 } 857 } 858 } 859 860 private Runnable mRetryFaceAuthentication = new Runnable() { 861 @Override 862 public void run() { 863 Log.w(TAG, "Retrying face after HW unavailable, attempt " + 864 mHardwareFaceUnavailableRetryCount); 865 updateFaceListeningState(); 866 } 867 }; 868 handleFaceError(int msgId, String errString)869 private void handleFaceError(int msgId, String errString) { 870 Assert.isMainThread(); 871 if (DEBUG_FACE) Log.d(TAG, "Face error received: " + errString); 872 if (msgId == FaceManager.FACE_ERROR_CANCELED && mHandler.hasCallbacks(mCancelNotReceived)) { 873 mHandler.removeCallbacks(mCancelNotReceived); 874 } 875 876 if (msgId == FaceManager.FACE_ERROR_CANCELED 877 && mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { 878 setFaceRunningState(BIOMETRIC_STATE_STOPPED); 879 updateFaceListeningState(); 880 } else { 881 setFaceRunningState(BIOMETRIC_STATE_STOPPED); 882 } 883 884 if (msgId == FaceManager.FACE_ERROR_HW_UNAVAILABLE 885 || msgId == FaceManager.FACE_ERROR_UNABLE_TO_PROCESS) { 886 if (mHardwareFaceUnavailableRetryCount < HAL_ERROR_RETRY_MAX) { 887 mHardwareFaceUnavailableRetryCount++; 888 mHandler.removeCallbacks(mRetryFaceAuthentication); 889 mHandler.postDelayed(mRetryFaceAuthentication, HAL_ERROR_RETRY_TIMEOUT); 890 } 891 } 892 893 if (msgId == FaceManager.FACE_ERROR_LOCKOUT_PERMANENT) { 894 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, 895 getCurrentUser()); 896 } 897 898 for (int i = 0; i < mCallbacks.size(); i++) { 899 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 900 if (cb != null) { 901 cb.onBiometricError(msgId, errString, 902 BiometricSourceType.FACE); 903 } 904 } 905 } 906 handleFaceLockoutReset()907 private void handleFaceLockoutReset() { 908 updateFaceListeningState(); 909 } 910 setFaceRunningState(int faceRunningState)911 private void setFaceRunningState(int faceRunningState) { 912 boolean wasRunning = mFaceRunningState == BIOMETRIC_STATE_RUNNING; 913 boolean isRunning = faceRunningState == BIOMETRIC_STATE_RUNNING; 914 mFaceRunningState = faceRunningState; 915 Log.d(TAG, "faceRunningState: " + mFaceRunningState); 916 // Clients of KeyguardUpdateMonitor don't care about the internal state or about the 917 // asynchronousness of the cancel cycle. So only notify them if the actually running state 918 // has changed. 919 if (wasRunning != isRunning) { 920 notifyFaceRunningStateChanged(); 921 } 922 } 923 notifyFaceRunningStateChanged()924 private void notifyFaceRunningStateChanged() { 925 Assert.isMainThread(); 926 for (int i = 0; i < mCallbacks.size(); i++) { 927 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 928 if (cb != null) { 929 cb.onBiometricRunningStateChanged(isFaceDetectionRunning(), 930 BiometricSourceType.FACE); 931 } 932 } 933 } 934 handleFaceUnlockStateChanged(boolean running, int userId)935 private void handleFaceUnlockStateChanged(boolean running, int userId) { 936 Assert.isMainThread(); 937 mUserFaceUnlockRunning.put(userId, running); 938 for (int i = 0; i < mCallbacks.size(); i++) { 939 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 940 if (cb != null) { 941 cb.onFaceUnlockStateChanged(running, userId); 942 } 943 } 944 } 945 isFaceUnlockRunning(int userId)946 public boolean isFaceUnlockRunning(int userId) { 947 return mUserFaceUnlockRunning.get(userId); 948 } 949 isFingerprintDetectionRunning()950 public boolean isFingerprintDetectionRunning() { 951 return mFingerprintRunningState == BIOMETRIC_STATE_RUNNING; 952 } 953 isFaceDetectionRunning()954 public boolean isFaceDetectionRunning() { 955 return mFaceRunningState == BIOMETRIC_STATE_RUNNING; 956 } 957 isTrustDisabled(int userId)958 private boolean isTrustDisabled(int userId) { 959 // Don't allow trust agent if device is secured with a SIM PIN. This is here 960 // mainly because there's no other way to prompt the user to enter their SIM PIN 961 // once they get past the keyguard screen. 962 final boolean disabledBySimPin = isSimPinSecure(); 963 return disabledBySimPin; 964 } 965 isFingerprintDisabled(int userId)966 private boolean isFingerprintDisabled(int userId) { 967 final DevicePolicyManager dpm = 968 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); 969 return dpm != null && (dpm.getKeyguardDisabledFeatures(null, userId) 970 & DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT) != 0 971 || isSimPinSecure(); 972 } 973 isFaceDisabled(int userId)974 private boolean isFaceDisabled(int userId) { 975 final DevicePolicyManager dpm = 976 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); 977 // TODO(b/140035044) 978 return whitelistIpcs(() -> dpm != null && (dpm.getKeyguardDisabledFeatures(null, userId) 979 & DevicePolicyManager.KEYGUARD_DISABLE_FACE) != 0 980 || isSimPinSecure()); 981 } 982 983 getUserCanSkipBouncer(int userId)984 public boolean getUserCanSkipBouncer(int userId) { 985 return getUserHasTrust(userId) || getUserUnlockedWithBiometric(userId); 986 } 987 getUserHasTrust(int userId)988 public boolean getUserHasTrust(int userId) { 989 return !isTrustDisabled(userId) && mUserHasTrust.get(userId); 990 } 991 992 /** 993 * Returns whether the user is unlocked with biometrics. 994 */ getUserUnlockedWithBiometric(int userId)995 public boolean getUserUnlockedWithBiometric(int userId) { 996 BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(userId); 997 BiometricAuthenticated face = mUserFaceAuthenticated.get(userId); 998 boolean fingerprintAllowed = fingerprint != null && fingerprint.mAuthenticated 999 && isUnlockingWithBiometricAllowed(fingerprint.mIsStrongBiometric); 1000 boolean faceAllowed = face != null && face.mAuthenticated 1001 && isUnlockingWithBiometricAllowed(face.mIsStrongBiometric); 1002 return fingerprintAllowed || faceAllowed; 1003 } 1004 getUserTrustIsManaged(int userId)1005 public boolean getUserTrustIsManaged(int userId) { 1006 return mUserTrustIsManaged.get(userId) && !isTrustDisabled(userId); 1007 } 1008 updateSecondaryLockscreenRequirement(int userId)1009 private void updateSecondaryLockscreenRequirement(int userId) { 1010 Intent oldIntent = mSecondaryLockscreenRequirement.get(userId); 1011 boolean enabled = mDevicePolicyManager.isSecondaryLockscreenEnabled(UserHandle.of(userId)); 1012 boolean changed = false; 1013 1014 if (enabled && (oldIntent == null)) { 1015 ComponentName supervisorComponent = 1016 mDevicePolicyManager.getProfileOwnerOrDeviceOwnerSupervisionComponent( 1017 UserHandle.of(userId)); 1018 if (supervisorComponent == null) { 1019 Log.e(TAG, "No Profile Owner or Device Owner supervision app found for User " 1020 + userId); 1021 } else { 1022 Intent intent = 1023 new Intent(DevicePolicyManager.ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE) 1024 .setPackage(supervisorComponent.getPackageName()); 1025 ResolveInfo resolveInfo = mContext.getPackageManager().resolveService(intent, 0); 1026 if (resolveInfo != null && resolveInfo.serviceInfo != null) { 1027 Intent launchIntent = 1028 new Intent().setComponent(resolveInfo.serviceInfo.getComponentName()); 1029 mSecondaryLockscreenRequirement.put(userId, launchIntent); 1030 changed = true; 1031 } 1032 } 1033 } else if (!enabled && (oldIntent != null)) { 1034 mSecondaryLockscreenRequirement.put(userId, null); 1035 changed = true; 1036 } 1037 if (changed) { 1038 for (int i = 0; i < mCallbacks.size(); i++) { 1039 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1040 if (cb != null) { 1041 cb.onSecondaryLockscreenRequirementChanged(userId); 1042 } 1043 } 1044 } 1045 } 1046 1047 /** 1048 * Returns an Intent by which to bind to a service that will provide additional security screen 1049 * content that must be shown prior to dismissing the keyguard for this user. 1050 */ getSecondaryLockscreenRequirement(int userId)1051 public Intent getSecondaryLockscreenRequirement(int userId) { 1052 return mSecondaryLockscreenRequirement.get(userId); 1053 } 1054 1055 /** 1056 * Cached version of {@link TrustManager#isTrustUsuallyManaged(int)}. 1057 */ isTrustUsuallyManaged(int userId)1058 public boolean isTrustUsuallyManaged(int userId) { 1059 Assert.isMainThread(); 1060 return mUserTrustIsUsuallyManaged.get(userId); 1061 } 1062 isUnlockingWithBiometricAllowed(boolean isStrongBiometric)1063 public boolean isUnlockingWithBiometricAllowed(boolean isStrongBiometric) { 1064 return mStrongAuthTracker.isUnlockingWithBiometricAllowed(isStrongBiometric); 1065 } 1066 isUserInLockdown(int userId)1067 public boolean isUserInLockdown(int userId) { 1068 return containsFlag(mStrongAuthTracker.getStrongAuthForUser(userId), 1069 STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN); 1070 } 1071 isEncryptedOrLockdown(int userId)1072 private boolean isEncryptedOrLockdown(int userId) { 1073 final int strongAuth = mStrongAuthTracker.getStrongAuthForUser(userId); 1074 final boolean isLockDown = 1075 containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) 1076 || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN); 1077 final boolean isEncrypted = containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_BOOT); 1078 return isEncrypted || isLockDown; 1079 } 1080 userNeedsStrongAuth()1081 public boolean userNeedsStrongAuth() { 1082 return mStrongAuthTracker.getStrongAuthForUser(getCurrentUser()) 1083 != LockPatternUtils.StrongAuthTracker.STRONG_AUTH_NOT_REQUIRED; 1084 } 1085 containsFlag(int haystack, int needle)1086 private boolean containsFlag(int haystack, int needle) { 1087 return (haystack & needle) != 0; 1088 } 1089 needsSlowUnlockTransition()1090 public boolean needsSlowUnlockTransition() { 1091 return mNeedsSlowUnlockTransition; 1092 } 1093 getStrongAuthTracker()1094 public StrongAuthTracker getStrongAuthTracker() { 1095 return mStrongAuthTracker; 1096 } 1097 notifyStrongAuthStateChanged(int userId)1098 private void notifyStrongAuthStateChanged(int userId) { 1099 Assert.isMainThread(); 1100 for (int i = 0; i < mCallbacks.size(); i++) { 1101 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1102 if (cb != null) { 1103 cb.onStrongAuthStateChanged(userId); 1104 } 1105 } 1106 } 1107 isScreenOn()1108 public boolean isScreenOn() { 1109 return mScreenOn; 1110 } 1111 dispatchErrorMessage(CharSequence message)1112 private void dispatchErrorMessage(CharSequence message) { 1113 Assert.isMainThread(); 1114 for (int i = 0; i < mCallbacks.size(); i++) { 1115 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1116 if (cb != null) { 1117 cb.onTrustAgentErrorMessage(message); 1118 } 1119 } 1120 } 1121 1122 @VisibleForTesting setAssistantVisible(boolean assistantVisible)1123 void setAssistantVisible(boolean assistantVisible) { 1124 mAssistantVisible = assistantVisible; 1125 updateBiometricListeningState(); 1126 } 1127 1128 static class DisplayClientState { 1129 public int clientGeneration; 1130 public boolean clearing; 1131 public PendingIntent intent; 1132 public int playbackState; 1133 public long playbackEventTime; 1134 } 1135 1136 private DisplayClientState mDisplayClientState = new DisplayClientState(); 1137 1138 @VisibleForTesting 1139 protected final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 1140 1141 @Override 1142 public void onReceive(Context context, Intent intent) { 1143 final String action = intent.getAction(); 1144 if (DEBUG) Log.d(TAG, "received broadcast " + action); 1145 1146 if (Intent.ACTION_TIME_TICK.equals(action) 1147 || Intent.ACTION_TIME_CHANGED.equals(action)) { 1148 mHandler.sendEmptyMessage(MSG_TIME_UPDATE); 1149 } else if (Intent.ACTION_TIMEZONE_CHANGED.equals(action)) { 1150 final Message msg = mHandler.obtainMessage( 1151 MSG_TIMEZONE_UPDATE, intent.getStringExtra(Intent.EXTRA_TIMEZONE)); 1152 mHandler.sendMessage(msg); 1153 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { 1154 1155 final Message msg = mHandler.obtainMessage( 1156 MSG_BATTERY_UPDATE, new BatteryStatus(intent)); 1157 mHandler.sendMessage(msg); 1158 } else if (Intent.ACTION_SIM_STATE_CHANGED.equals(action)) { 1159 SimData args = SimData.fromIntent(intent); 1160 // ACTION_SIM_STATE_CHANGED is rebroadcast after unlocking the device to 1161 // keep compatibility with apps that aren't direct boot aware. 1162 // SysUI should just ignore this broadcast because it was already received 1163 // and processed previously. 1164 if (intent.getBooleanExtra(Intent.EXTRA_REBROADCAST_ON_UNLOCK, false)) { 1165 // Guarantee mTelephonyCapable state after SysUI crash and restart 1166 if (args.simState == TelephonyManager.SIM_STATE_ABSENT) { 1167 mHandler.obtainMessage(MSG_TELEPHONY_CAPABLE, true).sendToTarget(); 1168 } 1169 return; 1170 } 1171 if (DEBUG_SIM_STATES) { 1172 Log.v(TAG, "action " + action 1173 + " state: " + intent.getStringExtra( 1174 Intent.EXTRA_SIM_STATE) 1175 + " slotId: " + args.slotId + " subid: " + args.subId); 1176 } 1177 mHandler.obtainMessage(MSG_SIM_STATE_CHANGE, args.subId, args.slotId, args.simState) 1178 .sendToTarget(); 1179 } else if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(action)) { 1180 String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); 1181 mHandler.sendMessage(mHandler.obtainMessage(MSG_PHONE_STATE_CHANGED, state)); 1182 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { 1183 mHandler.sendEmptyMessage(MSG_AIRPLANE_MODE_CHANGED); 1184 } else if (Intent.ACTION_SERVICE_STATE.equals(action)) { 1185 ServiceState serviceState = ServiceState.newFromBundle(intent.getExtras()); 1186 int subId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, 1187 SubscriptionManager.INVALID_SUBSCRIPTION_ID); 1188 if (DEBUG) { 1189 Log.v(TAG, "action " + action + " serviceState=" + serviceState + " subId=" 1190 + subId); 1191 } 1192 mHandler.sendMessage( 1193 mHandler.obtainMessage(MSG_SERVICE_STATE_CHANGE, subId, 0, serviceState)); 1194 } else if (TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED.equals(action)) { 1195 mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED); 1196 } else if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals( 1197 action)) { 1198 mHandler.sendEmptyMessage(MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED); 1199 } 1200 } 1201 }; 1202 1203 @VisibleForTesting 1204 protected final BroadcastReceiver mBroadcastAllReceiver = new BroadcastReceiver() { 1205 1206 @Override 1207 public void onReceive(Context context, Intent intent) { 1208 final String action = intent.getAction(); 1209 if (AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED.equals(action)) { 1210 mHandler.sendEmptyMessage(MSG_TIME_UPDATE); 1211 } else if (Intent.ACTION_USER_INFO_CHANGED.equals(action)) { 1212 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_INFO_CHANGED, 1213 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, getSendingUserId()), 0)); 1214 } else if (ACTION_FACE_UNLOCK_STARTED.equals(action)) { 1215 Trace.beginSection( 1216 "KeyguardUpdateMonitor.mBroadcastAllReceiver#onReceive " 1217 + "ACTION_FACE_UNLOCK_STARTED"); 1218 mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_UNLOCK_STATE_CHANGED, 1, 1219 getSendingUserId())); 1220 Trace.endSection(); 1221 } else if (ACTION_FACE_UNLOCK_STOPPED.equals(action)) { 1222 mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_UNLOCK_STATE_CHANGED, 0, 1223 getSendingUserId())); 1224 } else if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED 1225 .equals(action)) { 1226 mHandler.sendMessage(mHandler.obtainMessage(MSG_DPM_STATE_CHANGED, 1227 getSendingUserId())); 1228 } else if (ACTION_USER_UNLOCKED.equals(action)) { 1229 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_UNLOCKED, 1230 getSendingUserId(), 0)); 1231 } else if (ACTION_USER_STOPPED.equals(action)) { 1232 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_STOPPED, 1233 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1), 0)); 1234 } else if (ACTION_USER_REMOVED.equals(action)) { 1235 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_REMOVED, 1236 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1), 0)); 1237 } 1238 } 1239 }; 1240 1241 private final FingerprintManager.LockoutResetCallback mFingerprintLockoutResetCallback 1242 = new FingerprintManager.LockoutResetCallback() { 1243 @Override 1244 public void onLockoutReset() { 1245 handleFingerprintLockoutReset(); 1246 } 1247 }; 1248 1249 private final FaceManager.LockoutResetCallback mFaceLockoutResetCallback 1250 = new FaceManager.LockoutResetCallback() { 1251 @Override 1252 public void onLockoutReset() { 1253 handleFaceLockoutReset(); 1254 } 1255 }; 1256 1257 // Trigger the fingerprint success path so the bouncer can be shown 1258 private final FingerprintManager.FingerprintDetectionCallback mFingerprintDetectionCallback 1259 = this::handleFingerprintAuthenticated; 1260 1261 private FingerprintManager.AuthenticationCallback mFingerprintAuthenticationCallback 1262 = new AuthenticationCallback() { 1263 1264 @Override 1265 public void onAuthenticationFailed() { 1266 handleFingerprintAuthFailed(); 1267 } 1268 1269 @Override 1270 public void onAuthenticationSucceeded(AuthenticationResult result) { 1271 Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationSucceeded"); 1272 handleFingerprintAuthenticated(result.getUserId(), result.isStrongBiometric()); 1273 Trace.endSection(); 1274 } 1275 1276 @Override 1277 public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { 1278 handleFingerprintHelp(helpMsgId, helpString.toString()); 1279 } 1280 1281 @Override 1282 public void onAuthenticationError(int errMsgId, CharSequence errString) { 1283 handleFingerprintError(errMsgId, errString.toString()); 1284 } 1285 1286 @Override 1287 public void onAuthenticationAcquired(int acquireInfo) { 1288 handleFingerprintAcquired(acquireInfo); 1289 } 1290 }; 1291 1292 @VisibleForTesting 1293 FaceManager.AuthenticationCallback mFaceAuthenticationCallback 1294 = new FaceManager.AuthenticationCallback() { 1295 1296 @Override 1297 public void onAuthenticationFailed() { 1298 handleFaceAuthFailed(); 1299 } 1300 1301 @Override 1302 public void onAuthenticationSucceeded(FaceManager.AuthenticationResult result) { 1303 Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationSucceeded"); 1304 handleFaceAuthenticated(result.getUserId(), result.isStrongBiometric()); 1305 Trace.endSection(); 1306 } 1307 1308 @Override 1309 public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { 1310 handleFaceHelp(helpMsgId, helpString.toString()); 1311 } 1312 1313 @Override 1314 public void onAuthenticationError(int errMsgId, CharSequence errString) { 1315 handleFaceError(errMsgId, errString.toString()); 1316 } 1317 1318 @Override 1319 public void onAuthenticationAcquired(int acquireInfo) { 1320 handleFaceAcquired(acquireInfo); 1321 } 1322 }; 1323 1324 private CancellationSignal mFingerprintCancelSignal; 1325 private CancellationSignal mFaceCancelSignal; 1326 private FingerprintManager mFpm; 1327 private FaceManager mFaceManager; 1328 private boolean mFingerprintLockedOut; 1329 private TelephonyManager mTelephonyManager; 1330 1331 /** 1332 * When we receive a 1333 * {@link com.android.internal.telephony.TelephonyIntents#ACTION_SIM_STATE_CHANGED} broadcast, 1334 * and then pass a result via our handler to {@link KeyguardUpdateMonitor#handleSimStateChange}, 1335 * we need a single object to pass to the handler. This class helps decode 1336 * the intent and provide a {@link SimCard.State} result. 1337 */ 1338 private static class SimData { 1339 public int simState; 1340 public int slotId; 1341 public int subId; 1342 SimData(int state, int slot, int id)1343 SimData(int state, int slot, int id) { 1344 simState = state; 1345 slotId = slot; 1346 subId = id; 1347 } 1348 fromIntent(Intent intent)1349 static SimData fromIntent(Intent intent) { 1350 int state; 1351 if (!Intent.ACTION_SIM_STATE_CHANGED.equals(intent.getAction())) { 1352 throw new IllegalArgumentException("only handles intent ACTION_SIM_STATE_CHANGED"); 1353 } 1354 String stateExtra = intent.getStringExtra(Intent.EXTRA_SIM_STATE); 1355 int slotId = intent.getIntExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0); 1356 int subId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, 1357 SubscriptionManager.INVALID_SUBSCRIPTION_ID); 1358 if (Intent.SIM_STATE_ABSENT.equals(stateExtra)) { 1359 final String absentReason = intent 1360 .getStringExtra(Intent.EXTRA_SIM_LOCKED_REASON); 1361 1362 if (Intent.SIM_ABSENT_ON_PERM_DISABLED.equals( 1363 absentReason)) { 1364 state = TelephonyManager.SIM_STATE_PERM_DISABLED; 1365 } else { 1366 state = TelephonyManager.SIM_STATE_ABSENT; 1367 } 1368 } else if (Intent.SIM_STATE_READY.equals(stateExtra)) { 1369 state = TelephonyManager.SIM_STATE_READY; 1370 } else if (Intent.SIM_STATE_LOCKED.equals(stateExtra)) { 1371 final String lockedReason = intent 1372 .getStringExtra(Intent.EXTRA_SIM_LOCKED_REASON); 1373 if (Intent.SIM_LOCKED_ON_PIN.equals(lockedReason)) { 1374 state = TelephonyManager.SIM_STATE_PIN_REQUIRED; 1375 } else if (Intent.SIM_LOCKED_ON_PUK.equals(lockedReason)) { 1376 state = TelephonyManager.SIM_STATE_PUK_REQUIRED; 1377 } else { 1378 state = TelephonyManager.SIM_STATE_UNKNOWN; 1379 } 1380 } else if (Intent.SIM_LOCKED_NETWORK.equals(stateExtra)) { 1381 state = TelephonyManager.SIM_STATE_NETWORK_LOCKED; 1382 } else if (Intent.SIM_STATE_CARD_IO_ERROR.equals(stateExtra)) { 1383 state = TelephonyManager.SIM_STATE_CARD_IO_ERROR; 1384 } else if (Intent.SIM_STATE_LOADED.equals(stateExtra) 1385 || Intent.SIM_STATE_IMSI.equals(stateExtra)) { 1386 // This is required because telephony doesn't return to "READY" after 1387 // these state transitions. See bug 7197471. 1388 state = TelephonyManager.SIM_STATE_READY; 1389 } else { 1390 state = TelephonyManager.SIM_STATE_UNKNOWN; 1391 } 1392 return new SimData(state, slotId, subId); 1393 } 1394 1395 @Override toString()1396 public String toString() { 1397 return "SimData{state=" + simState + ",slotId=" + slotId + ",subId=" + subId + "}"; 1398 } 1399 } 1400 1401 public static class StrongAuthTracker extends LockPatternUtils.StrongAuthTracker { 1402 private final Consumer<Integer> mStrongAuthRequiredChangedCallback; 1403 StrongAuthTracker(Context context, Consumer<Integer> strongAuthRequiredChangedCallback)1404 public StrongAuthTracker(Context context, 1405 Consumer<Integer> strongAuthRequiredChangedCallback) { 1406 super(context); 1407 mStrongAuthRequiredChangedCallback = strongAuthRequiredChangedCallback; 1408 } 1409 isUnlockingWithBiometricAllowed(boolean isStrongBiometric)1410 public boolean isUnlockingWithBiometricAllowed(boolean isStrongBiometric) { 1411 int userId = getCurrentUser(); 1412 return isBiometricAllowedForUser(isStrongBiometric, userId); 1413 } 1414 hasUserAuthenticatedSinceBoot()1415 public boolean hasUserAuthenticatedSinceBoot() { 1416 int userId = getCurrentUser(); 1417 return (getStrongAuthForUser(userId) 1418 & STRONG_AUTH_REQUIRED_AFTER_BOOT) == 0; 1419 } 1420 1421 @Override onStrongAuthRequiredChanged(int userId)1422 public void onStrongAuthRequiredChanged(int userId) { 1423 mStrongAuthRequiredChangedCallback.accept(userId); 1424 } 1425 } 1426 handleStartedWakingUp()1427 protected void handleStartedWakingUp() { 1428 Trace.beginSection("KeyguardUpdateMonitor#handleStartedWakingUp"); 1429 Assert.isMainThread(); 1430 updateBiometricListeningState(); 1431 for (int i = 0; i < mCallbacks.size(); i++) { 1432 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1433 if (cb != null) { 1434 cb.onStartedWakingUp(); 1435 } 1436 } 1437 Trace.endSection(); 1438 } 1439 handleStartedGoingToSleep(int arg1)1440 protected void handleStartedGoingToSleep(int arg1) { 1441 Assert.isMainThread(); 1442 mLockIconPressed = false; 1443 clearBiometricRecognized(); 1444 for (int i = 0; i < mCallbacks.size(); i++) { 1445 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1446 if (cb != null) { 1447 cb.onStartedGoingToSleep(arg1); 1448 } 1449 } 1450 mGoingToSleep = true; 1451 updateBiometricListeningState(); 1452 } 1453 handleFinishedGoingToSleep(int arg1)1454 protected void handleFinishedGoingToSleep(int arg1) { 1455 Assert.isMainThread(); 1456 mGoingToSleep = false; 1457 for (int i = 0; i < mCallbacks.size(); i++) { 1458 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1459 if (cb != null) { 1460 cb.onFinishedGoingToSleep(arg1); 1461 } 1462 } 1463 updateBiometricListeningState(); 1464 } 1465 handleScreenTurnedOn()1466 private void handleScreenTurnedOn() { 1467 Assert.isMainThread(); 1468 for (int i = 0; i < mCallbacks.size(); i++) { 1469 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1470 if (cb != null) { 1471 cb.onScreenTurnedOn(); 1472 } 1473 } 1474 } 1475 handleScreenTurnedOff()1476 private void handleScreenTurnedOff() { 1477 final String tag = "KeyguardUpdateMonitor#handleScreenTurnedOff"; 1478 DejankUtils.startDetectingBlockingIpcs(tag); 1479 Assert.isMainThread(); 1480 mHardwareFingerprintUnavailableRetryCount = 0; 1481 mHardwareFaceUnavailableRetryCount = 0; 1482 for (int i = 0; i < mCallbacks.size(); i++) { 1483 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1484 if (cb != null) { 1485 cb.onScreenTurnedOff(); 1486 } 1487 } 1488 DejankUtils.stopDetectingBlockingIpcs(tag); 1489 } 1490 handleDreamingStateChanged(int dreamStart)1491 private void handleDreamingStateChanged(int dreamStart) { 1492 Assert.isMainThread(); 1493 mIsDreaming = dreamStart == 1; 1494 for (int i = 0; i < mCallbacks.size(); i++) { 1495 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1496 if (cb != null) { 1497 cb.onDreamingStateChanged(mIsDreaming); 1498 } 1499 } 1500 updateBiometricListeningState(); 1501 } 1502 handleUserInfoChanged(int userId)1503 private void handleUserInfoChanged(int userId) { 1504 Assert.isMainThread(); 1505 for (int i = 0; i < mCallbacks.size(); i++) { 1506 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1507 if (cb != null) { 1508 cb.onUserInfoChanged(userId); 1509 } 1510 } 1511 } 1512 handleUserUnlocked(int userId)1513 private void handleUserUnlocked(int userId) { 1514 Assert.isMainThread(); 1515 mUserIsUnlocked.put(userId, true); 1516 mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition(); 1517 for (int i = 0; i < mCallbacks.size(); i++) { 1518 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1519 if (cb != null) { 1520 cb.onUserUnlocked(); 1521 } 1522 } 1523 } 1524 handleUserStopped(int userId)1525 private void handleUserStopped(int userId) { 1526 Assert.isMainThread(); 1527 mUserIsUnlocked.put(userId, mUserManager.isUserUnlocked(userId)); 1528 } 1529 1530 @VisibleForTesting handleUserRemoved(int userId)1531 void handleUserRemoved(int userId) { 1532 Assert.isMainThread(); 1533 mUserIsUnlocked.delete(userId); 1534 mUserTrustIsUsuallyManaged.delete(userId); 1535 } 1536 handleKeyguardGoingAway(boolean goingAway)1537 private void handleKeyguardGoingAway(boolean goingAway) { 1538 Assert.isMainThread(); 1539 setKeyguardGoingAway(goingAway); 1540 } 1541 1542 @VisibleForTesting setStrongAuthTracker(@onNull StrongAuthTracker tracker)1543 protected void setStrongAuthTracker(@NonNull StrongAuthTracker tracker) { 1544 if (mStrongAuthTracker != null) { 1545 mLockPatternUtils.unregisterStrongAuthTracker(mStrongAuthTracker); 1546 } 1547 1548 mStrongAuthTracker = tracker; 1549 mLockPatternUtils.registerStrongAuthTracker(mStrongAuthTracker); 1550 } 1551 registerRingerTracker()1552 private void registerRingerTracker() { 1553 mRingerModeTracker.getRingerMode().observeForever(mRingerModeObserver); 1554 } 1555 1556 @VisibleForTesting 1557 @Inject KeyguardUpdateMonitor( Context context, @Main Looper mainLooper, BroadcastDispatcher broadcastDispatcher, DumpManager dumpManager, RingerModeTracker ringerModeTracker, @Background Executor backgroundExecutor, StatusBarStateController statusBarStateController, LockPatternUtils lockPatternUtils)1558 protected KeyguardUpdateMonitor( 1559 Context context, 1560 @Main Looper mainLooper, 1561 BroadcastDispatcher broadcastDispatcher, 1562 DumpManager dumpManager, 1563 RingerModeTracker ringerModeTracker, 1564 @Background Executor backgroundExecutor, 1565 StatusBarStateController statusBarStateController, 1566 LockPatternUtils lockPatternUtils) { 1567 mContext = context; 1568 mSubscriptionManager = SubscriptionManager.from(context); 1569 mDeviceProvisioned = isDeviceProvisionedInSettingsDb(); 1570 mStrongAuthTracker = new StrongAuthTracker(context, this::notifyStrongAuthStateChanged); 1571 mBackgroundExecutor = backgroundExecutor; 1572 mBroadcastDispatcher = broadcastDispatcher; 1573 mRingerModeTracker = ringerModeTracker; 1574 mStatusBarStateController = statusBarStateController; 1575 mLockPatternUtils = lockPatternUtils; 1576 dumpManager.registerDumpable(getClass().getName(), this); 1577 1578 mHandler = new Handler(mainLooper) { 1579 @Override 1580 public void handleMessage(Message msg) { 1581 switch (msg.what) { 1582 case MSG_TIME_UPDATE: 1583 handleTimeUpdate(); 1584 break; 1585 case MSG_TIMEZONE_UPDATE: 1586 handleTimeZoneUpdate((String) msg.obj); 1587 break; 1588 case MSG_BATTERY_UPDATE: 1589 handleBatteryUpdate((BatteryStatus) msg.obj); 1590 break; 1591 case MSG_SIM_STATE_CHANGE: 1592 handleSimStateChange(msg.arg1, msg.arg2, (int) msg.obj); 1593 break; 1594 case MSG_RINGER_MODE_CHANGED: 1595 handleRingerModeChange(msg.arg1); 1596 break; 1597 case MSG_PHONE_STATE_CHANGED: 1598 handlePhoneStateChanged((String) msg.obj); 1599 break; 1600 case MSG_DEVICE_PROVISIONED: 1601 handleDeviceProvisioned(); 1602 break; 1603 case MSG_DPM_STATE_CHANGED: 1604 handleDevicePolicyManagerStateChanged(msg.arg1); 1605 break; 1606 case MSG_USER_SWITCHING: 1607 handleUserSwitching(msg.arg1, (IRemoteCallback) msg.obj); 1608 break; 1609 case MSG_USER_SWITCH_COMPLETE: 1610 handleUserSwitchComplete(msg.arg1); 1611 break; 1612 case MSG_KEYGUARD_RESET: 1613 handleKeyguardReset(); 1614 break; 1615 case MSG_KEYGUARD_BOUNCER_CHANGED: 1616 handleKeyguardBouncerChanged(msg.arg1); 1617 break; 1618 case MSG_USER_INFO_CHANGED: 1619 handleUserInfoChanged(msg.arg1); 1620 break; 1621 case MSG_REPORT_EMERGENCY_CALL_ACTION: 1622 handleReportEmergencyCallAction(); 1623 break; 1624 case MSG_STARTED_GOING_TO_SLEEP: 1625 handleStartedGoingToSleep(msg.arg1); 1626 break; 1627 case MSG_FINISHED_GOING_TO_SLEEP: 1628 handleFinishedGoingToSleep(msg.arg1); 1629 break; 1630 case MSG_STARTED_WAKING_UP: 1631 Trace.beginSection("KeyguardUpdateMonitor#handler MSG_STARTED_WAKING_UP"); 1632 handleStartedWakingUp(); 1633 Trace.endSection(); 1634 break; 1635 case MSG_FACE_UNLOCK_STATE_CHANGED: 1636 Trace.beginSection( 1637 "KeyguardUpdateMonitor#handler MSG_FACE_UNLOCK_STATE_CHANGED"); 1638 handleFaceUnlockStateChanged(msg.arg1 != 0, msg.arg2); 1639 Trace.endSection(); 1640 break; 1641 case MSG_SIM_SUBSCRIPTION_INFO_CHANGED: 1642 handleSimSubscriptionInfoChanged(); 1643 break; 1644 case MSG_AIRPLANE_MODE_CHANGED: 1645 handleAirplaneModeChanged(); 1646 break; 1647 case MSG_SERVICE_STATE_CHANGE: 1648 handleServiceStateChange(msg.arg1, (ServiceState) msg.obj); 1649 break; 1650 case MSG_SCREEN_TURNED_ON: 1651 handleScreenTurnedOn(); 1652 break; 1653 case MSG_SCREEN_TURNED_OFF: 1654 Trace.beginSection("KeyguardUpdateMonitor#handler MSG_SCREEN_TURNED_ON"); 1655 handleScreenTurnedOff(); 1656 Trace.endSection(); 1657 break; 1658 case MSG_DREAMING_STATE_CHANGED: 1659 handleDreamingStateChanged(msg.arg1); 1660 break; 1661 case MSG_USER_UNLOCKED: 1662 handleUserUnlocked(msg.arg1); 1663 break; 1664 case MSG_USER_STOPPED: 1665 handleUserStopped(msg.arg1); 1666 break; 1667 case MSG_USER_REMOVED: 1668 handleUserRemoved(msg.arg1); 1669 break; 1670 case MSG_ASSISTANT_STACK_CHANGED: 1671 setAssistantVisible((boolean) msg.obj); 1672 break; 1673 case MSG_BIOMETRIC_AUTHENTICATION_CONTINUE: 1674 updateBiometricListeningState(); 1675 break; 1676 case MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED: 1677 updateLogoutEnabled(); 1678 break; 1679 case MSG_TELEPHONY_CAPABLE: 1680 updateTelephonyCapable((boolean) msg.obj); 1681 break; 1682 case MSG_KEYGUARD_GOING_AWAY: 1683 handleKeyguardGoingAway((boolean) msg.obj); 1684 break; 1685 default: 1686 super.handleMessage(msg); 1687 break; 1688 } 1689 } 1690 }; 1691 1692 // Since device can't be un-provisioned, we only need to register a content observer 1693 // to update mDeviceProvisioned when we are... 1694 if (!mDeviceProvisioned) { 1695 watchForDeviceProvisioning(); 1696 } 1697 1698 // Take a guess at initial SIM state, battery status and PLMN until we get an update 1699 mBatteryStatus = new BatteryStatus(BATTERY_STATUS_UNKNOWN, 100, 0, 0, 0, true); 1700 1701 // Watch for interesting updates 1702 final IntentFilter filter = new IntentFilter(); 1703 filter.addAction(Intent.ACTION_TIME_TICK); 1704 filter.addAction(Intent.ACTION_TIME_CHANGED); 1705 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 1706 filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); 1707 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); 1708 filter.addAction(Intent.ACTION_SIM_STATE_CHANGED); 1709 filter.addAction(Intent.ACTION_SERVICE_STATE); 1710 filter.addAction(TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED); 1711 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); 1712 filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 1713 mBroadcastDispatcher.registerReceiverWithHandler(mBroadcastReceiver, filter, mHandler); 1714 // Since ACTION_SERVICE_STATE is being moved to a non-sticky broadcast, trigger the 1715 // listener now with the service state from the default sub. 1716 mBackgroundExecutor.execute(() -> { 1717 int subId = SubscriptionManager.getDefaultSubscriptionId(); 1718 ServiceState serviceState = mContext.getSystemService(TelephonyManager.class) 1719 .getServiceStateForSubscriber(subId); 1720 mHandler.sendMessage( 1721 mHandler.obtainMessage(MSG_SERVICE_STATE_CHANGE, subId, 0, serviceState)); 1722 1723 // Get initial state. Relying on Sticky behavior until API for getting info. 1724 if (mBatteryStatus == null) { 1725 Intent intent = mContext.registerReceiver( 1726 null, 1727 new IntentFilter(Intent.ACTION_BATTERY_CHANGED) 1728 ); 1729 if (intent != null && mBatteryStatus == null) { 1730 mBroadcastReceiver.onReceive(mContext, intent); 1731 } 1732 } 1733 }); 1734 1735 mHandler.post(this::registerRingerTracker); 1736 1737 final IntentFilter allUserFilter = new IntentFilter(); 1738 allUserFilter.addAction(Intent.ACTION_USER_INFO_CHANGED); 1739 allUserFilter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED); 1740 allUserFilter.addAction(ACTION_FACE_UNLOCK_STARTED); 1741 allUserFilter.addAction(ACTION_FACE_UNLOCK_STOPPED); 1742 allUserFilter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 1743 allUserFilter.addAction(ACTION_USER_UNLOCKED); 1744 allUserFilter.addAction(ACTION_USER_STOPPED); 1745 allUserFilter.addAction(ACTION_USER_REMOVED); 1746 mBroadcastDispatcher.registerReceiverWithHandler(mBroadcastAllReceiver, allUserFilter, 1747 mHandler, UserHandle.ALL); 1748 1749 mSubscriptionManager.addOnSubscriptionsChangedListener(mSubscriptionListener); 1750 try { 1751 ActivityManager.getService().registerUserSwitchObserver(mUserSwitchObserver, TAG); 1752 } catch (RemoteException e) { 1753 e.rethrowAsRuntimeException(); 1754 } 1755 1756 mTrustManager = context.getSystemService(TrustManager.class); 1757 mTrustManager.registerTrustListener(this); 1758 1759 setStrongAuthTracker(mStrongAuthTracker); 1760 1761 mDreamManager = IDreamManager.Stub.asInterface( 1762 ServiceManager.getService(DreamService.DREAM_SERVICE)); 1763 1764 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) { 1765 mFpm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE); 1766 } 1767 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) { 1768 mFaceManager = (FaceManager) context.getSystemService(Context.FACE_SERVICE); 1769 } 1770 1771 if (mFpm != null || mFaceManager != null) { 1772 mBiometricManager = context.getSystemService(BiometricManager.class); 1773 mBiometricManager.registerEnabledOnKeyguardCallback(mBiometricEnabledCallback); 1774 } 1775 1776 updateBiometricListeningState(); 1777 if (mFpm != null) { 1778 mFpm.addLockoutResetCallback(mFingerprintLockoutResetCallback); 1779 } 1780 if (mFaceManager != null) { 1781 mFaceManager.addLockoutResetCallback(mFaceLockoutResetCallback); 1782 } 1783 1784 mIsAutomotive = isAutomotive(); 1785 1786 ActivityManagerWrapper.getInstance().registerTaskStackListener(mTaskStackListener); 1787 mUserManager = context.getSystemService(UserManager.class); 1788 mIsPrimaryUser = mUserManager.isPrimaryUser(); 1789 int user = ActivityManager.getCurrentUser(); 1790 mUserIsUnlocked.put(user, mUserManager.isUserUnlocked(user)); 1791 mDevicePolicyManager = context.getSystemService(DevicePolicyManager.class); 1792 mLogoutEnabled = mDevicePolicyManager.isLogoutEnabled(); 1793 updateSecondaryLockscreenRequirement(user); 1794 List<UserInfo> allUsers = mUserManager.getUsers(); 1795 for (UserInfo userInfo : allUsers) { 1796 mUserTrustIsUsuallyManaged.put(userInfo.id, 1797 mTrustManager.isTrustUsuallyManaged(userInfo.id)); 1798 } 1799 updateAirplaneModeState(); 1800 1801 mTelephonyManager = 1802 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 1803 if (mTelephonyManager != null) { 1804 mTelephonyManager.listen(mPhoneStateListener, 1805 LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE); 1806 // Set initial sim states values. 1807 for (int slot = 0; slot < mTelephonyManager.getActiveModemCount(); slot++) { 1808 int state = mTelephonyManager.getSimState(slot); 1809 int[] subIds = mSubscriptionManager.getSubscriptionIds(slot); 1810 if (subIds != null) { 1811 for (int subId : subIds) { 1812 mHandler.obtainMessage(MSG_SIM_STATE_CHANGE, subId, slot, state) 1813 .sendToTarget(); 1814 } 1815 } 1816 } 1817 } 1818 } 1819 1820 private final UserSwitchObserver mUserSwitchObserver = new UserSwitchObserver() { 1821 @Override 1822 public void onUserSwitching(int newUserId, IRemoteCallback reply) { 1823 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCHING, 1824 newUserId, 0, reply)); 1825 } 1826 1827 @Override 1828 public void onUserSwitchComplete(int newUserId) throws RemoteException { 1829 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCH_COMPLETE, 1830 newUserId, 0)); 1831 } 1832 }; 1833 updateAirplaneModeState()1834 private void updateAirplaneModeState() { 1835 // ACTION_AIRPLANE_MODE_CHANGED do not broadcast if device set AirplaneMode ON and boot 1836 if (!WirelessUtils.isAirplaneModeOn(mContext) 1837 || mHandler.hasMessages(MSG_AIRPLANE_MODE_CHANGED)) { 1838 return; 1839 } 1840 mHandler.sendEmptyMessage(MSG_AIRPLANE_MODE_CHANGED); 1841 } 1842 updateBiometricListeningState()1843 private void updateBiometricListeningState() { 1844 updateFingerprintListeningState(); 1845 updateFaceListeningState(); 1846 } 1847 updateFingerprintListeningState()1848 private void updateFingerprintListeningState() { 1849 // If this message exists, we should not authenticate again until this message is 1850 // consumed by the handler 1851 if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) { 1852 return; 1853 } 1854 mHandler.removeCallbacks(mRetryFingerprintAuthentication); 1855 boolean shouldListenForFingerprint = shouldListenForFingerprint(); 1856 boolean runningOrRestarting = mFingerprintRunningState == BIOMETRIC_STATE_RUNNING 1857 || mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING; 1858 if (runningOrRestarting && !shouldListenForFingerprint) { 1859 stopListeningForFingerprint(); 1860 } else if (!runningOrRestarting && shouldListenForFingerprint) { 1861 startListeningForFingerprint(); 1862 } 1863 } 1864 1865 /** 1866 * If a user is encrypted or not. 1867 * This is NOT related to the lock screen being visible or not. 1868 * 1869 * @param userId The user. 1870 * @return {@code true} when encrypted. 1871 * @see UserManager#isUserUnlocked() 1872 * @see Intent#ACTION_USER_UNLOCKED 1873 */ isUserUnlocked(int userId)1874 public boolean isUserUnlocked(int userId) { 1875 return mUserIsUnlocked.get(userId); 1876 } 1877 1878 /** 1879 * Called whenever passive authentication is requested or aborted by a sensor. 1880 * 1881 * @param active If the interrupt started or ended. 1882 */ onAuthInterruptDetected(boolean active)1883 public void onAuthInterruptDetected(boolean active) { 1884 if (DEBUG) Log.d(TAG, "onAuthInterruptDetected(" + active + ")"); 1885 if (mAuthInterruptActive == active) { 1886 return; 1887 } 1888 mAuthInterruptActive = active; 1889 updateFaceListeningState(); 1890 } 1891 1892 /** 1893 * Requests face authentication if we're on a state where it's allowed. 1894 * This will re-trigger auth in case it fails. 1895 */ requestFaceAuth()1896 public void requestFaceAuth() { 1897 if (DEBUG) Log.d(TAG, "requestFaceAuth()"); 1898 updateFaceListeningState(); 1899 } 1900 1901 /** 1902 * In case face auth is running, cancel it. 1903 */ cancelFaceAuth()1904 public void cancelFaceAuth() { 1905 stopListeningForFace(); 1906 } 1907 updateFaceListeningState()1908 private void updateFaceListeningState() { 1909 // If this message exists, we should not authenticate again until this message is 1910 // consumed by the handler 1911 if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) { 1912 return; 1913 } 1914 mHandler.removeCallbacks(mRetryFaceAuthentication); 1915 boolean shouldListenForFace = shouldListenForFace(); 1916 if (mFaceRunningState == BIOMETRIC_STATE_RUNNING && !shouldListenForFace) { 1917 stopListeningForFace(); 1918 } else if (mFaceRunningState != BIOMETRIC_STATE_RUNNING && shouldListenForFace) { 1919 startListeningForFace(); 1920 } 1921 } 1922 shouldListenForFingerprintAssistant()1923 private boolean shouldListenForFingerprintAssistant() { 1924 BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(getCurrentUser()); 1925 return mAssistantVisible && mKeyguardOccluded 1926 && !(fingerprint != null && fingerprint.mAuthenticated) 1927 && !mUserHasTrust.get(getCurrentUser(), false); 1928 } 1929 shouldListenForFaceAssistant()1930 private boolean shouldListenForFaceAssistant() { 1931 BiometricAuthenticated face = mUserFaceAuthenticated.get(getCurrentUser()); 1932 return mAssistantVisible && mKeyguardOccluded 1933 && !(face != null && face.mAuthenticated) 1934 && !mUserHasTrust.get(getCurrentUser(), false); 1935 } 1936 shouldListenForFingerprint()1937 private boolean shouldListenForFingerprint() { 1938 final boolean allowedOnBouncer = 1939 !(mFingerprintLockedOut && mBouncer && mCredentialAttempted); 1940 1941 // Only listen if this KeyguardUpdateMonitor belongs to the primary user. There is an 1942 // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware. 1943 final boolean shouldListen = (mKeyguardIsVisible || !mDeviceInteractive || 1944 (mBouncer && !mKeyguardGoingAway) || mGoingToSleep || 1945 shouldListenForFingerprintAssistant() || (mKeyguardOccluded && mIsDreaming)) 1946 && !mSwitchingUser && !isFingerprintDisabled(getCurrentUser()) 1947 && (!mKeyguardGoingAway || !mDeviceInteractive) && mIsPrimaryUser 1948 && allowedOnBouncer; 1949 return shouldListen; 1950 } 1951 1952 /** 1953 * If face auth is allows to scan on this exact moment. 1954 */ shouldListenForFace()1955 public boolean shouldListenForFace() { 1956 final boolean statusBarShadeLocked = 1957 mStatusBarStateController.getState() == StatusBarState.SHADE_LOCKED; 1958 final boolean awakeKeyguard = mKeyguardIsVisible && mDeviceInteractive && !mGoingToSleep 1959 && !statusBarShadeLocked; 1960 final int user = getCurrentUser(); 1961 final int strongAuth = mStrongAuthTracker.getStrongAuthForUser(user); 1962 final boolean isLockDown = 1963 containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) 1964 || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN); 1965 final boolean isEncryptedOrTimedOut = 1966 containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_BOOT) 1967 || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_TIMEOUT); 1968 1969 boolean canBypass = mKeyguardBypassController != null 1970 && mKeyguardBypassController.canBypass(); 1971 // There's no reason to ask the HAL for authentication when the user can dismiss the 1972 // bouncer, unless we're bypassing and need to auto-dismiss the lock screen even when 1973 // TrustAgents or biometrics are keeping the device unlocked. 1974 boolean becauseCannotSkipBouncer = !getUserCanSkipBouncer(user) || canBypass; 1975 1976 // Scan even when encrypted or timeout to show a preemptive bouncer when bypassing. 1977 // Lock-down mode shouldn't scan, since it is more explicit. 1978 boolean strongAuthAllowsScanning = (!isEncryptedOrTimedOut || canBypass && !mBouncer) 1979 && !isLockDown; 1980 1981 // Only listen if this KeyguardUpdateMonitor belongs to the primary user. There is an 1982 // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware. 1983 final boolean shouldListen = 1984 (mBouncer || mAuthInterruptActive || awakeKeyguard 1985 || shouldListenForFaceAssistant()) 1986 && !mSwitchingUser && !isFaceDisabled(user) && becauseCannotSkipBouncer 1987 && !mKeyguardGoingAway && mFaceSettingEnabledForUser.get(user) && !mLockIconPressed 1988 && strongAuthAllowsScanning && mIsPrimaryUser 1989 && !mSecureCameraLaunched; 1990 1991 // Aggregate relevant fields for debug logging. 1992 if (DEBUG_FACE || DEBUG_SPEW) { 1993 final KeyguardFaceListenModel model = new KeyguardFaceListenModel( 1994 System.currentTimeMillis(), 1995 user, 1996 shouldListen, 1997 mBouncer, 1998 mAuthInterruptActive, 1999 awakeKeyguard, 2000 shouldListenForFaceAssistant(), 2001 mSwitchingUser, 2002 isFaceDisabled(user), 2003 becauseCannotSkipBouncer, 2004 mKeyguardGoingAway, 2005 mFaceSettingEnabledForUser.get(user), 2006 mLockIconPressed, 2007 strongAuthAllowsScanning, 2008 mIsPrimaryUser, 2009 mSecureCameraLaunched); 2010 maybeLogFaceListenerModelData(model); 2011 } 2012 2013 return shouldListen; 2014 } 2015 maybeLogFaceListenerModelData(KeyguardFaceListenModel model)2016 private void maybeLogFaceListenerModelData(KeyguardFaceListenModel model) { 2017 // Too chatty, but very useful when debugging issues. 2018 if (DEBUG_SPEW) { 2019 Log.v(TAG, model.toString()); 2020 } 2021 2022 // Add model data to the historical buffer. 2023 if (DEBUG_FACE && mFaceRunningState != BIOMETRIC_STATE_RUNNING 2024 && model.isListeningForFace()) { 2025 if (mFaceListenModels == null) { 2026 mFaceListenModels = new ArrayDeque<>(FACE_LISTEN_CALLS_QUEUE_SIZE); 2027 } 2028 if (mFaceListenModels.size() >= FACE_LISTEN_CALLS_QUEUE_SIZE) { 2029 mFaceListenModels.remove(); 2030 } 2031 mFaceListenModels.add(model); 2032 } 2033 } 2034 2035 /** 2036 * Whenever the lock icon is long pressed, disabling trust agents. 2037 * This means that we cannot auth passively (face) until the user presses power. 2038 */ onLockIconPressed()2039 public void onLockIconPressed() { 2040 mLockIconPressed = true; 2041 final int userId = getCurrentUser(); 2042 mUserFaceAuthenticated.put(userId, null); 2043 updateFaceListeningState(); 2044 mStrongAuthTracker.onStrongAuthRequiredChanged(userId); 2045 } 2046 startListeningForFingerprint()2047 private void startListeningForFingerprint() { 2048 if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING) { 2049 setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING); 2050 return; 2051 } 2052 if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { 2053 // Waiting for restart via handleFingerprintError(). 2054 return; 2055 } 2056 if (DEBUG) Log.v(TAG, "startListeningForFingerprint()"); 2057 int userId = getCurrentUser(); 2058 if (isUnlockWithFingerprintPossible(userId)) { 2059 if (mFingerprintCancelSignal != null) { 2060 mFingerprintCancelSignal.cancel(); 2061 } 2062 mFingerprintCancelSignal = new CancellationSignal(); 2063 2064 if (isEncryptedOrLockdown(userId)) { 2065 mFpm.detectFingerprint(mFingerprintCancelSignal, mFingerprintDetectionCallback, 2066 userId); 2067 } else { 2068 mFpm.authenticate(null, mFingerprintCancelSignal, 0, 2069 mFingerprintAuthenticationCallback, null, userId); 2070 } 2071 2072 setFingerprintRunningState(BIOMETRIC_STATE_RUNNING); 2073 } 2074 } 2075 startListeningForFace()2076 private void startListeningForFace() { 2077 if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING) { 2078 setFaceRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING); 2079 return; 2080 } 2081 if (DEBUG) Log.v(TAG, "startListeningForFace()"); 2082 int userId = getCurrentUser(); 2083 if (isUnlockWithFacePossible(userId)) { 2084 if (mFaceCancelSignal != null) { 2085 mFaceCancelSignal.cancel(); 2086 } 2087 mFaceCancelSignal = new CancellationSignal(); 2088 mFaceManager.authenticate(null, mFaceCancelSignal, 0, 2089 mFaceAuthenticationCallback, null, userId); 2090 setFaceRunningState(BIOMETRIC_STATE_RUNNING); 2091 } 2092 } 2093 2094 /** 2095 * If biometrics hardware is available, not disabled, and user has enrolled templates. 2096 * This does NOT check if the device is encrypted or in lockdown. 2097 * 2098 * @param userId User that's trying to unlock. 2099 * @return {@code true} if possible. 2100 */ isUnlockingWithBiometricsPossible(int userId)2101 public boolean isUnlockingWithBiometricsPossible(int userId) { 2102 return isUnlockWithFacePossible(userId) || isUnlockWithFingerprintPossible(userId); 2103 } 2104 isUnlockWithFingerprintPossible(int userId)2105 private boolean isUnlockWithFingerprintPossible(int userId) { 2106 return mFpm != null && mFpm.isHardwareDetected() && !isFingerprintDisabled(userId) 2107 && mFpm.hasEnrolledTemplates(userId); 2108 } 2109 isUnlockWithFacePossible(int userId)2110 private boolean isUnlockWithFacePossible(int userId) { 2111 return isFaceAuthEnabledForUser(userId) && !isFaceDisabled(userId); 2112 } 2113 2114 /** 2115 * If face hardware is available, user has enrolled and enabled auth via setting. 2116 */ isFaceAuthEnabledForUser(int userId)2117 public boolean isFaceAuthEnabledForUser(int userId) { 2118 // TODO(b/140034352) 2119 return whitelistIpcs(() -> mFaceManager != null && mFaceManager.isHardwareDetected() 2120 && mFaceManager.hasEnrolledTemplates(userId) 2121 && mFaceSettingEnabledForUser.get(userId)); 2122 } 2123 stopListeningForFingerprint()2124 private void stopListeningForFingerprint() { 2125 if (DEBUG) Log.v(TAG, "stopListeningForFingerprint()"); 2126 if (mFingerprintRunningState == BIOMETRIC_STATE_RUNNING) { 2127 if (mFingerprintCancelSignal != null) { 2128 mFingerprintCancelSignal.cancel(); 2129 mFingerprintCancelSignal = null; 2130 if (!mHandler.hasCallbacks(mCancelNotReceived)) { 2131 mHandler.postDelayed(mCancelNotReceived, DEFAULT_CANCEL_SIGNAL_TIMEOUT); 2132 } 2133 } 2134 setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING); 2135 } 2136 if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { 2137 setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING); 2138 } 2139 } 2140 stopListeningForFace()2141 private void stopListeningForFace() { 2142 if (DEBUG) Log.v(TAG, "stopListeningForFace()"); 2143 if (mFaceRunningState == BIOMETRIC_STATE_RUNNING) { 2144 if (mFaceCancelSignal != null) { 2145 mFaceCancelSignal.cancel(); 2146 mFaceCancelSignal = null; 2147 if (!mHandler.hasCallbacks(mCancelNotReceived)) { 2148 mHandler.postDelayed(mCancelNotReceived, DEFAULT_CANCEL_SIGNAL_TIMEOUT); 2149 } 2150 } 2151 setFaceRunningState(BIOMETRIC_STATE_CANCELLING); 2152 } 2153 if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { 2154 setFaceRunningState(BIOMETRIC_STATE_CANCELLING); 2155 } 2156 } 2157 isDeviceProvisionedInSettingsDb()2158 private boolean isDeviceProvisionedInSettingsDb() { 2159 return Settings.Global.getInt(mContext.getContentResolver(), 2160 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 2161 } 2162 watchForDeviceProvisioning()2163 private void watchForDeviceProvisioning() { 2164 mDeviceProvisionedObserver = new ContentObserver(mHandler) { 2165 @Override 2166 public void onChange(boolean selfChange) { 2167 super.onChange(selfChange); 2168 mDeviceProvisioned = isDeviceProvisionedInSettingsDb(); 2169 if (mDeviceProvisioned) { 2170 mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED); 2171 } 2172 if (DEBUG) Log.d(TAG, "DEVICE_PROVISIONED state = " + mDeviceProvisioned); 2173 } 2174 }; 2175 2176 mContext.getContentResolver().registerContentObserver( 2177 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), 2178 false, mDeviceProvisionedObserver); 2179 2180 // prevent a race condition between where we check the flag and where we register the 2181 // observer by grabbing the value once again... 2182 boolean provisioned = isDeviceProvisionedInSettingsDb(); 2183 if (provisioned != mDeviceProvisioned) { 2184 mDeviceProvisioned = provisioned; 2185 if (mDeviceProvisioned) { 2186 mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED); 2187 } 2188 } 2189 } 2190 2191 /** 2192 * Update the state whether Keyguard currently has a lockscreen wallpaper. 2193 * 2194 * @param hasLockscreenWallpaper Whether Keyguard has a lockscreen wallpaper. 2195 */ setHasLockscreenWallpaper(boolean hasLockscreenWallpaper)2196 public void setHasLockscreenWallpaper(boolean hasLockscreenWallpaper) { 2197 Assert.isMainThread(); 2198 if (hasLockscreenWallpaper != mHasLockscreenWallpaper) { 2199 mHasLockscreenWallpaper = hasLockscreenWallpaper; 2200 for (int i = 0; i < mCallbacks.size(); i++) { 2201 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2202 if (cb != null) { 2203 cb.onHasLockscreenWallpaperChanged(hasLockscreenWallpaper); 2204 } 2205 } 2206 } 2207 } 2208 2209 /** 2210 * @return Whether Keyguard has a lockscreen wallpaper. 2211 */ hasLockscreenWallpaper()2212 public boolean hasLockscreenWallpaper() { 2213 return mHasLockscreenWallpaper; 2214 } 2215 2216 /** 2217 * Handle {@link #MSG_DPM_STATE_CHANGED} 2218 */ handleDevicePolicyManagerStateChanged(int userId)2219 private void handleDevicePolicyManagerStateChanged(int userId) { 2220 Assert.isMainThread(); 2221 updateFingerprintListeningState(); 2222 updateSecondaryLockscreenRequirement(userId); 2223 for (int i = 0; i < mCallbacks.size(); i++) { 2224 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2225 if (cb != null) { 2226 cb.onDevicePolicyManagerStateChanged(); 2227 } 2228 } 2229 } 2230 2231 /** 2232 * Handle {@link #MSG_USER_SWITCHING} 2233 */ 2234 @VisibleForTesting handleUserSwitching(int userId, IRemoteCallback reply)2235 void handleUserSwitching(int userId, IRemoteCallback reply) { 2236 Assert.isMainThread(); 2237 clearBiometricRecognized(); 2238 mUserTrustIsUsuallyManaged.put(userId, mTrustManager.isTrustUsuallyManaged(userId)); 2239 for (int i = 0; i < mCallbacks.size(); i++) { 2240 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2241 if (cb != null) { 2242 cb.onUserSwitching(userId); 2243 } 2244 } 2245 try { 2246 reply.sendResult(null); 2247 } catch (RemoteException e) { 2248 } 2249 } 2250 2251 /** 2252 * Handle {@link #MSG_USER_SWITCH_COMPLETE} 2253 */ handleUserSwitchComplete(int userId)2254 private void handleUserSwitchComplete(int userId) { 2255 Assert.isMainThread(); 2256 for (int i = 0; i < mCallbacks.size(); i++) { 2257 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2258 if (cb != null) { 2259 cb.onUserSwitchComplete(userId); 2260 } 2261 } 2262 } 2263 2264 /** 2265 * Handle {@link #MSG_DEVICE_PROVISIONED} 2266 */ handleDeviceProvisioned()2267 private void handleDeviceProvisioned() { 2268 Assert.isMainThread(); 2269 for (int i = 0; i < mCallbacks.size(); i++) { 2270 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2271 if (cb != null) { 2272 cb.onDeviceProvisioned(); 2273 } 2274 } 2275 if (mDeviceProvisionedObserver != null) { 2276 // We don't need the observer anymore... 2277 mContext.getContentResolver().unregisterContentObserver(mDeviceProvisionedObserver); 2278 mDeviceProvisionedObserver = null; 2279 } 2280 } 2281 2282 /** 2283 * Handle {@link #MSG_PHONE_STATE_CHANGED} 2284 */ handlePhoneStateChanged(String newState)2285 private void handlePhoneStateChanged(String newState) { 2286 Assert.isMainThread(); 2287 if (DEBUG) Log.d(TAG, "handlePhoneStateChanged(" + newState + ")"); 2288 if (TelephonyManager.EXTRA_STATE_IDLE.equals(newState)) { 2289 mPhoneState = TelephonyManager.CALL_STATE_IDLE; 2290 } else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(newState)) { 2291 mPhoneState = TelephonyManager.CALL_STATE_OFFHOOK; 2292 } else if (TelephonyManager.EXTRA_STATE_RINGING.equals(newState)) { 2293 mPhoneState = TelephonyManager.CALL_STATE_RINGING; 2294 } 2295 for (int i = 0; i < mCallbacks.size(); i++) { 2296 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2297 if (cb != null) { 2298 cb.onPhoneStateChanged(mPhoneState); 2299 } 2300 } 2301 } 2302 2303 /** 2304 * Handle {@link #MSG_RINGER_MODE_CHANGED} 2305 */ handleRingerModeChange(int mode)2306 private void handleRingerModeChange(int mode) { 2307 Assert.isMainThread(); 2308 if (DEBUG) Log.d(TAG, "handleRingerModeChange(" + mode + ")"); 2309 mRingMode = mode; 2310 for (int i = 0; i < mCallbacks.size(); i++) { 2311 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2312 if (cb != null) { 2313 cb.onRingerModeChanged(mode); 2314 } 2315 } 2316 } 2317 2318 /** 2319 * Handle {@link #MSG_TIME_UPDATE} 2320 */ handleTimeUpdate()2321 private void handleTimeUpdate() { 2322 Assert.isMainThread(); 2323 if (DEBUG) Log.d(TAG, "handleTimeUpdate"); 2324 for (int i = 0; i < mCallbacks.size(); i++) { 2325 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2326 if (cb != null) { 2327 cb.onTimeChanged(); 2328 } 2329 } 2330 } 2331 2332 /** 2333 * Handle (@line #MSG_TIMEZONE_UPDATE} 2334 */ handleTimeZoneUpdate(String timeZone)2335 private void handleTimeZoneUpdate(String timeZone) { 2336 Assert.isMainThread(); 2337 if (DEBUG) Log.d(TAG, "handleTimeZoneUpdate"); 2338 for (int i = 0; i < mCallbacks.size(); i++) { 2339 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2340 if (cb != null) { 2341 cb.onTimeZoneChanged(TimeZone.getTimeZone(timeZone)); 2342 // Also notify callbacks about time change to remain compatible. 2343 cb.onTimeChanged(); 2344 } 2345 } 2346 } 2347 2348 /** 2349 * Handle {@link #MSG_BATTERY_UPDATE} 2350 */ handleBatteryUpdate(BatteryStatus status)2351 private void handleBatteryUpdate(BatteryStatus status) { 2352 Assert.isMainThread(); 2353 if (DEBUG) Log.d(TAG, "handleBatteryUpdate"); 2354 final boolean batteryUpdateInteresting = isBatteryUpdateInteresting(mBatteryStatus, status); 2355 mBatteryStatus = status; 2356 if (batteryUpdateInteresting) { 2357 for (int i = 0; i < mCallbacks.size(); i++) { 2358 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2359 if (cb != null) { 2360 cb.onRefreshBatteryInfo(status); 2361 } 2362 } 2363 } 2364 } 2365 2366 /** 2367 * Handle Telephony status during Boot for CarrierText display policy 2368 */ 2369 @VisibleForTesting updateTelephonyCapable(boolean capable)2370 void updateTelephonyCapable(boolean capable) { 2371 Assert.isMainThread(); 2372 if (capable == mTelephonyCapable) { 2373 return; 2374 } 2375 mTelephonyCapable = capable; 2376 for (int i = 0; i < mCallbacks.size(); i++) { 2377 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2378 if (cb != null) { 2379 cb.onTelephonyCapable(mTelephonyCapable); 2380 } 2381 } 2382 } 2383 2384 /** 2385 * Handle {@link #MSG_SIM_STATE_CHANGE} 2386 */ 2387 @VisibleForTesting handleSimStateChange(int subId, int slotId, int state)2388 void handleSimStateChange(int subId, int slotId, int state) { 2389 Assert.isMainThread(); 2390 if (DEBUG_SIM_STATES) { 2391 Log.d(TAG, "handleSimStateChange(subId=" + subId + ", slotId=" 2392 + slotId + ", state=" + state + ")"); 2393 } 2394 2395 boolean becameAbsent = false; 2396 if (!SubscriptionManager.isValidSubscriptionId(subId)) { 2397 Log.w(TAG, "invalid subId in handleSimStateChange()"); 2398 /* Only handle No SIM(ABSENT) and Card Error(CARD_IO_ERROR) due to 2399 * handleServiceStateChange() handle other case */ 2400 if (state == TelephonyManager.SIM_STATE_ABSENT) { 2401 updateTelephonyCapable(true); 2402 // Even though the subscription is not valid anymore, we need to notify that the 2403 // SIM card was removed so we can update the UI. 2404 becameAbsent = true; 2405 for (SimData data : mSimDatas.values()) { 2406 // Set the SIM state of all SimData associated with that slot to ABSENT se we 2407 // do not move back into PIN/PUK locked and not detect the change below. 2408 if (data.slotId == slotId) { 2409 data.simState = TelephonyManager.SIM_STATE_ABSENT; 2410 } 2411 } 2412 } else if (state == TelephonyManager.SIM_STATE_CARD_IO_ERROR) { 2413 updateTelephonyCapable(true); 2414 } else { 2415 return; 2416 } 2417 } 2418 2419 SimData data = mSimDatas.get(subId); 2420 final boolean changed; 2421 if (data == null) { 2422 data = new SimData(state, slotId, subId); 2423 mSimDatas.put(subId, data); 2424 changed = true; // no data yet; force update 2425 } else { 2426 changed = (data.simState != state || data.subId != subId || data.slotId != slotId); 2427 data.simState = state; 2428 data.subId = subId; 2429 data.slotId = slotId; 2430 } 2431 if ((changed || becameAbsent) && state != TelephonyManager.SIM_STATE_UNKNOWN) { 2432 for (int i = 0; i < mCallbacks.size(); i++) { 2433 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2434 if (cb != null) { 2435 cb.onSimStateChanged(subId, slotId, state); 2436 } 2437 } 2438 } 2439 } 2440 2441 /** 2442 * Handle {@link #MSG_SERVICE_STATE_CHANGE} 2443 */ 2444 @VisibleForTesting handleServiceStateChange(int subId, ServiceState serviceState)2445 void handleServiceStateChange(int subId, ServiceState serviceState) { 2446 if (DEBUG) { 2447 Log.d(TAG, 2448 "handleServiceStateChange(subId=" + subId + ", serviceState=" + serviceState); 2449 } 2450 2451 if (!SubscriptionManager.isValidSubscriptionId(subId)) { 2452 Log.w(TAG, "invalid subId in handleServiceStateChange()"); 2453 return; 2454 } else { 2455 updateTelephonyCapable(true); 2456 } 2457 2458 mServiceStates.put(subId, serviceState); 2459 2460 callbacksRefreshCarrierInfo(); 2461 } 2462 isKeyguardVisible()2463 public boolean isKeyguardVisible() { 2464 return mKeyguardIsVisible; 2465 } 2466 2467 /** 2468 * Notifies that the visibility state of Keyguard has changed. 2469 * 2470 * <p>Needs to be called from the main thread. 2471 */ onKeyguardVisibilityChanged(boolean showing)2472 public void onKeyguardVisibilityChanged(boolean showing) { 2473 Assert.isMainThread(); 2474 Log.d(TAG, "onKeyguardVisibilityChanged(" + showing + ")"); 2475 mKeyguardIsVisible = showing; 2476 2477 if (showing) { 2478 mSecureCameraLaunched = false; 2479 } 2480 2481 for (int i = 0; i < mCallbacks.size(); i++) { 2482 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2483 if (cb != null) { 2484 cb.onKeyguardVisibilityChangedRaw(showing); 2485 } 2486 } 2487 updateBiometricListeningState(); 2488 } 2489 2490 /** 2491 * Handle {@link #MSG_KEYGUARD_RESET} 2492 */ handleKeyguardReset()2493 private void handleKeyguardReset() { 2494 if (DEBUG) Log.d(TAG, "handleKeyguardReset"); 2495 updateBiometricListeningState(); 2496 mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition(); 2497 } 2498 resolveNeedsSlowUnlockTransition()2499 private boolean resolveNeedsSlowUnlockTransition() { 2500 if (isUserUnlocked(getCurrentUser())) { 2501 return false; 2502 } 2503 Intent homeIntent = new Intent(Intent.ACTION_MAIN) 2504 .addCategory(Intent.CATEGORY_HOME); 2505 ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(homeIntent, 2506 0 /* flags */); 2507 2508 // TODO(b/160971249): Replace in the future by resolving activity as user. 2509 if (resolveInfo == null && mIsAutomotive) { 2510 Log.w(TAG, "resolveNeedsSlowUnlockTransition: returning false since activity " 2511 + "could not be resolved."); 2512 return false; 2513 } 2514 2515 return FALLBACK_HOME_COMPONENT.equals(resolveInfo.getComponentInfo().getComponentName()); 2516 } 2517 2518 /** 2519 * Handle {@link #MSG_KEYGUARD_BOUNCER_CHANGED} 2520 * 2521 * @see #sendKeyguardBouncerChanged(boolean) 2522 */ handleKeyguardBouncerChanged(int bouncer)2523 private void handleKeyguardBouncerChanged(int bouncer) { 2524 Assert.isMainThread(); 2525 if (DEBUG) Log.d(TAG, "handleKeyguardBouncerChanged(" + bouncer + ")"); 2526 boolean isBouncer = (bouncer == 1); 2527 mBouncer = isBouncer; 2528 2529 if (isBouncer) { 2530 // If the bouncer is shown, always clear this flag. This can happen in the following 2531 // situations: 1) Default camera with SHOW_WHEN_LOCKED is not chosen yet. 2) Secure 2532 // camera requests dismiss keyguard (tapping on photos for example). When these happen, 2533 // face auth should resume. 2534 mSecureCameraLaunched = false; 2535 } else { 2536 mCredentialAttempted = false; 2537 } 2538 2539 for (int i = 0; i < mCallbacks.size(); i++) { 2540 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2541 if (cb != null) { 2542 cb.onKeyguardBouncerChanged(isBouncer); 2543 } 2544 } 2545 updateBiometricListeningState(); 2546 } 2547 2548 /** 2549 * Handle {@link #MSG_REPORT_EMERGENCY_CALL_ACTION} 2550 */ handleReportEmergencyCallAction()2551 private void handleReportEmergencyCallAction() { 2552 Assert.isMainThread(); 2553 for (int i = 0; i < mCallbacks.size(); i++) { 2554 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2555 if (cb != null) { 2556 cb.onEmergencyCallAction(); 2557 } 2558 } 2559 } 2560 isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current)2561 private boolean isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current) { 2562 final boolean nowPluggedIn = current.isPluggedIn(); 2563 final boolean wasPluggedIn = old.isPluggedIn(); 2564 final boolean stateChangedWhilePluggedIn = wasPluggedIn && nowPluggedIn 2565 && (old.status != current.status); 2566 final boolean nowPresent = current.present; 2567 final boolean wasPresent = old.present; 2568 2569 // change in plug state is always interesting 2570 if (wasPluggedIn != nowPluggedIn || stateChangedWhilePluggedIn) { 2571 return true; 2572 } 2573 2574 // change in battery level 2575 if (old.level != current.level) { 2576 return true; 2577 } 2578 2579 // change in charging current while plugged in 2580 if (nowPluggedIn && current.maxChargingWattage != old.maxChargingWattage) { 2581 return true; 2582 } 2583 2584 // change in battery overheat 2585 if (current.health != old.health) { 2586 return true; 2587 } 2588 2589 // Battery either showed up or disappeared 2590 if (wasPresent != nowPresent) { 2591 return true; 2592 } 2593 2594 return false; 2595 } 2596 isAutomotive()2597 private boolean isAutomotive() { 2598 return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE); 2599 } 2600 2601 /** 2602 * Remove the given observer's callback. 2603 * 2604 * @param callback The callback to remove 2605 */ removeCallback(KeyguardUpdateMonitorCallback callback)2606 public void removeCallback(KeyguardUpdateMonitorCallback callback) { 2607 Assert.isMainThread(); 2608 if (DEBUG) { 2609 Log.v(TAG, "*** unregister callback for " + callback); 2610 } 2611 2612 mCallbacks.removeIf(el -> el.get() == callback); 2613 } 2614 2615 /** 2616 * Register to receive notifications about general keyguard information 2617 * (see {@link InfoCallback}. 2618 * 2619 * @param callback The callback to register 2620 */ registerCallback(KeyguardUpdateMonitorCallback callback)2621 public void registerCallback(KeyguardUpdateMonitorCallback callback) { 2622 Assert.isMainThread(); 2623 if (DEBUG) Log.v(TAG, "*** register callback for " + callback); 2624 // Prevent adding duplicate callbacks 2625 2626 for (int i = 0; i < mCallbacks.size(); i++) { 2627 if (mCallbacks.get(i).get() == callback) { 2628 if (DEBUG) { 2629 Log.e(TAG, "Object tried to add another callback", 2630 new Exception("Called by")); 2631 } 2632 return; 2633 } 2634 } 2635 mCallbacks.add(new WeakReference<>(callback)); 2636 removeCallback(null); // remove unused references 2637 sendUpdates(callback); 2638 } 2639 setKeyguardBypassController(KeyguardBypassController keyguardBypassController)2640 public void setKeyguardBypassController(KeyguardBypassController keyguardBypassController) { 2641 mKeyguardBypassController = keyguardBypassController; 2642 } 2643 isSwitchingUser()2644 public boolean isSwitchingUser() { 2645 return mSwitchingUser; 2646 } 2647 2648 @AnyThread setSwitchingUser(boolean switching)2649 public void setSwitchingUser(boolean switching) { 2650 mSwitchingUser = switching; 2651 // Since this comes in on a binder thread, we need to post if first 2652 mHandler.post(mUpdateBiometricListeningState); 2653 } 2654 sendUpdates(KeyguardUpdateMonitorCallback callback)2655 private void sendUpdates(KeyguardUpdateMonitorCallback callback) { 2656 // Notify listener of the current state 2657 callback.onRefreshBatteryInfo(mBatteryStatus); 2658 callback.onTimeChanged(); 2659 callback.onRingerModeChanged(mRingMode); 2660 callback.onPhoneStateChanged(mPhoneState); 2661 callback.onRefreshCarrierInfo(); 2662 callback.onClockVisibilityChanged(); 2663 callback.onKeyguardVisibilityChangedRaw(mKeyguardIsVisible); 2664 callback.onTelephonyCapable(mTelephonyCapable); 2665 for (Entry<Integer, SimData> data : mSimDatas.entrySet()) { 2666 final SimData state = data.getValue(); 2667 callback.onSimStateChanged(state.subId, state.slotId, state.simState); 2668 } 2669 } 2670 sendKeyguardReset()2671 public void sendKeyguardReset() { 2672 mHandler.obtainMessage(MSG_KEYGUARD_RESET).sendToTarget(); 2673 } 2674 2675 /** 2676 * @see #handleKeyguardBouncerChanged(int) 2677 */ sendKeyguardBouncerChanged(boolean showingBouncer)2678 public void sendKeyguardBouncerChanged(boolean showingBouncer) { 2679 if (DEBUG) Log.d(TAG, "sendKeyguardBouncerChanged(" + showingBouncer + ")"); 2680 Message message = mHandler.obtainMessage(MSG_KEYGUARD_BOUNCER_CHANGED); 2681 message.arg1 = showingBouncer ? 1 : 0; 2682 message.sendToTarget(); 2683 } 2684 2685 /** 2686 * Report that the user successfully entered the SIM PIN or PUK/SIM PIN so we 2687 * have the information earlier than waiting for the intent 2688 * broadcast from the telephony code. 2689 * 2690 * NOTE: Because handleSimStateChange() invokes callbacks immediately without going 2691 * through mHandler, this *must* be called from the UI thread. 2692 */ 2693 @MainThread reportSimUnlocked(int subId)2694 public void reportSimUnlocked(int subId) { 2695 if (DEBUG_SIM_STATES) Log.v(TAG, "reportSimUnlocked(subId=" + subId + ")"); 2696 handleSimStateChange(subId, getSlotId(subId), TelephonyManager.SIM_STATE_READY); 2697 } 2698 2699 /** 2700 * Report that the emergency call button has been pressed and the emergency dialer is 2701 * about to be displayed. 2702 * 2703 * @param bypassHandler runs immediately. 2704 * 2705 * NOTE: Must be called from UI thread if bypassHandler == true. 2706 */ reportEmergencyCallAction(boolean bypassHandler)2707 public void reportEmergencyCallAction(boolean bypassHandler) { 2708 if (!bypassHandler) { 2709 mHandler.obtainMessage(MSG_REPORT_EMERGENCY_CALL_ACTION).sendToTarget(); 2710 } else { 2711 Assert.isMainThread(); 2712 handleReportEmergencyCallAction(); 2713 } 2714 } 2715 2716 /** 2717 * @return Whether the device is provisioned (whether they have gone through 2718 * the setup wizard) 2719 */ isDeviceProvisioned()2720 public boolean isDeviceProvisioned() { 2721 return mDeviceProvisioned; 2722 } 2723 getServiceState(int subId)2724 public ServiceState getServiceState(int subId) { 2725 return mServiceStates.get(subId); 2726 } 2727 clearBiometricRecognized()2728 public void clearBiometricRecognized() { 2729 Assert.isMainThread(); 2730 mUserFingerprintAuthenticated.clear(); 2731 mUserFaceAuthenticated.clear(); 2732 mTrustManager.clearAllBiometricRecognized(BiometricSourceType.FINGERPRINT); 2733 mTrustManager.clearAllBiometricRecognized(BiometricSourceType.FACE); 2734 2735 for (int i = 0; i < mCallbacks.size(); i++) { 2736 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2737 if (cb != null) { 2738 cb.onBiometricsCleared(); 2739 } 2740 } 2741 } 2742 isSimPinVoiceSecure()2743 public boolean isSimPinVoiceSecure() { 2744 // TODO: only count SIMs that handle voice 2745 return isSimPinSecure(); 2746 } 2747 2748 /** 2749 * If any SIM cards are currently secure. 2750 * 2751 * @see #isSimPinSecure(State) 2752 */ isSimPinSecure()2753 public boolean isSimPinSecure() { 2754 // True if any SIM is pin secure 2755 for (SubscriptionInfo info : getSubscriptionInfo(false /* forceReload */)) { 2756 if (isSimPinSecure(getSimState(info.getSubscriptionId()))) return true; 2757 } 2758 return false; 2759 } 2760 getSimState(int subId)2761 public int getSimState(int subId) { 2762 if (mSimDatas.containsKey(subId)) { 2763 return mSimDatas.get(subId).simState; 2764 } else { 2765 return TelephonyManager.SIM_STATE_UNKNOWN; 2766 } 2767 } 2768 getSlotId(int subId)2769 private int getSlotId(int subId) { 2770 if (!mSimDatas.containsKey(subId)) { 2771 refreshSimState(subId, SubscriptionManager.getSlotIndex(subId)); 2772 } 2773 return mSimDatas.get(subId).slotId; 2774 } 2775 2776 private final TaskStackChangeListener 2777 mTaskStackListener = new TaskStackChangeListener() { 2778 @Override 2779 public void onTaskStackChangedBackground() { 2780 try { 2781 ActivityManager.StackInfo info = ActivityTaskManager.getService().getStackInfo( 2782 WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_ASSISTANT); 2783 if (info == null) { 2784 return; 2785 } 2786 mHandler.sendMessage(mHandler.obtainMessage(MSG_ASSISTANT_STACK_CHANGED, 2787 info.visible)); 2788 } catch (RemoteException e) { 2789 Log.e(TAG, "unable to check task stack", e); 2790 } 2791 } 2792 }; 2793 2794 /** 2795 * @return true if and only if the state has changed for the specified {@code slotId} 2796 */ refreshSimState(int subId, int slotId)2797 private boolean refreshSimState(int subId, int slotId) { 2798 final TelephonyManager tele = 2799 (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 2800 int state = (tele != null) ? 2801 tele.getSimState(slotId) : TelephonyManager.SIM_STATE_UNKNOWN; 2802 SimData data = mSimDatas.get(subId); 2803 final boolean changed; 2804 if (data == null) { 2805 data = new SimData(state, slotId, subId); 2806 mSimDatas.put(subId, data); 2807 changed = true; // no data yet; force update 2808 } else { 2809 changed = data.simState != state; 2810 data.simState = state; 2811 } 2812 return changed; 2813 } 2814 2815 /** 2816 * If the {@code state} is currently requiring a SIM PIN, PUK, or is disabled. 2817 */ isSimPinSecure(int state)2818 public static boolean isSimPinSecure(int state) { 2819 return (state == TelephonyManager.SIM_STATE_PIN_REQUIRED 2820 || state == TelephonyManager.SIM_STATE_PUK_REQUIRED 2821 || state == TelephonyManager.SIM_STATE_PERM_DISABLED); 2822 } 2823 getCachedDisplayClientState()2824 public DisplayClientState getCachedDisplayClientState() { 2825 return mDisplayClientState; 2826 } 2827 2828 // TODO: use these callbacks elsewhere in place of the existing notifyScreen*() 2829 // (KeyguardViewMediator, KeyguardHostView) dispatchStartedWakingUp()2830 public void dispatchStartedWakingUp() { 2831 synchronized (this) { 2832 mDeviceInteractive = true; 2833 } 2834 mHandler.sendEmptyMessage(MSG_STARTED_WAKING_UP); 2835 } 2836 dispatchStartedGoingToSleep(int why)2837 public void dispatchStartedGoingToSleep(int why) { 2838 mHandler.sendMessage(mHandler.obtainMessage(MSG_STARTED_GOING_TO_SLEEP, why, 0)); 2839 } 2840 dispatchFinishedGoingToSleep(int why)2841 public void dispatchFinishedGoingToSleep(int why) { 2842 synchronized (this) { 2843 mDeviceInteractive = false; 2844 } 2845 mHandler.sendMessage(mHandler.obtainMessage(MSG_FINISHED_GOING_TO_SLEEP, why, 0)); 2846 } 2847 dispatchScreenTurnedOn()2848 public void dispatchScreenTurnedOn() { 2849 synchronized (this) { 2850 mScreenOn = true; 2851 } 2852 mHandler.sendEmptyMessage(MSG_SCREEN_TURNED_ON); 2853 } 2854 dispatchScreenTurnedOff()2855 public void dispatchScreenTurnedOff() { 2856 synchronized (this) { 2857 mScreenOn = false; 2858 } 2859 mHandler.sendEmptyMessage(MSG_SCREEN_TURNED_OFF); 2860 } 2861 dispatchDreamingStarted()2862 public void dispatchDreamingStarted() { 2863 mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 1, 0)); 2864 } 2865 dispatchDreamingStopped()2866 public void dispatchDreamingStopped() { 2867 mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 0, 0)); 2868 } 2869 2870 /** 2871 * Sends a message to update the keyguard going away state on the main thread. 2872 * 2873 * @param goingAway Whether the keyguard is going away. 2874 */ dispatchKeyguardGoingAway(boolean goingAway)2875 public void dispatchKeyguardGoingAway(boolean goingAway) { 2876 mHandler.sendMessage(mHandler.obtainMessage(MSG_KEYGUARD_GOING_AWAY, goingAway)); 2877 } 2878 isDeviceInteractive()2879 public boolean isDeviceInteractive() { 2880 return mDeviceInteractive; 2881 } 2882 isGoingToSleep()2883 public boolean isGoingToSleep() { 2884 return mGoingToSleep; 2885 } 2886 2887 /** 2888 * Find the next SubscriptionId for a SIM in the given state, favoring lower slot numbers first. 2889 * 2890 * @return subid or {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID} if none found 2891 */ getNextSubIdForState(int state)2892 public int getNextSubIdForState(int state) { 2893 List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */); 2894 int resultId = SubscriptionManager.INVALID_SUBSCRIPTION_ID; 2895 int bestSlotId = Integer.MAX_VALUE; // Favor lowest slot first 2896 for (int i = 0; i < list.size(); i++) { 2897 final SubscriptionInfo info = list.get(i); 2898 final int id = info.getSubscriptionId(); 2899 int slotId = getSlotId(id); 2900 if (state == getSimState(id) && bestSlotId > slotId) { 2901 resultId = id; 2902 bestSlotId = slotId; 2903 } 2904 } 2905 return resultId; 2906 } 2907 getSubscriptionInfoForSubId(int subId)2908 public SubscriptionInfo getSubscriptionInfoForSubId(int subId) { 2909 List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */); 2910 for (int i = 0; i < list.size(); i++) { 2911 SubscriptionInfo info = list.get(i); 2912 if (subId == info.getSubscriptionId()) return info; 2913 } 2914 return null; // not found 2915 } 2916 2917 /** 2918 * @return a cached version of DevicePolicyManager.isLogoutEnabled() 2919 */ isLogoutEnabled()2920 public boolean isLogoutEnabled() { 2921 return mLogoutEnabled; 2922 } 2923 updateLogoutEnabled()2924 private void updateLogoutEnabled() { 2925 Assert.isMainThread(); 2926 boolean logoutEnabled = mDevicePolicyManager.isLogoutEnabled(); 2927 if (mLogoutEnabled != logoutEnabled) { 2928 mLogoutEnabled = logoutEnabled; 2929 2930 for (int i = 0; i < mCallbacks.size(); i++) { 2931 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 2932 if (cb != null) { 2933 cb.onLogoutEnabledChanged(); 2934 } 2935 } 2936 } 2937 } 2938 2939 /** 2940 * Unregister all listeners. 2941 */ destroy()2942 public void destroy() { 2943 // TODO: inject these dependencies: 2944 TelephonyManager telephony = 2945 (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 2946 if (telephony != null) { 2947 telephony.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE); 2948 } 2949 2950 mSubscriptionManager.removeOnSubscriptionsChangedListener(mSubscriptionListener); 2951 2952 if (mDeviceProvisionedObserver != null) { 2953 mContext.getContentResolver().unregisterContentObserver(mDeviceProvisionedObserver); 2954 } 2955 2956 try { 2957 ActivityManager.getService().unregisterUserSwitchObserver(mUserSwitchObserver); 2958 } catch (RemoteException e) { 2959 Log.d(TAG, "RemoteException onDestroy. cannot unregister userSwitchObserver"); 2960 } 2961 2962 ActivityManagerWrapper.getInstance().unregisterTaskStackListener(mTaskStackListener); 2963 2964 mBroadcastDispatcher.unregisterReceiver(mBroadcastReceiver); 2965 mBroadcastDispatcher.unregisterReceiver(mBroadcastAllReceiver); 2966 mRingerModeTracker.getRingerMode().removeObserver(mRingerModeObserver); 2967 2968 mLockPatternUtils.unregisterStrongAuthTracker(mStrongAuthTracker); 2969 mTrustManager.unregisterTrustListener(this); 2970 2971 mHandler.removeCallbacksAndMessages(null); 2972 } 2973 2974 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2975 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2976 pw.println("KeyguardUpdateMonitor state:"); 2977 pw.println(" SIM States:"); 2978 for (SimData data : mSimDatas.values()) { 2979 pw.println(" " + data.toString()); 2980 } 2981 pw.println(" Subs:"); 2982 if (mSubscriptionInfo != null) { 2983 for (int i = 0; i < mSubscriptionInfo.size(); i++) { 2984 pw.println(" " + mSubscriptionInfo.get(i)); 2985 } 2986 } 2987 pw.println(" Current active data subId=" + mActiveMobileDataSubscription); 2988 pw.println(" Service states:"); 2989 for (int subId : mServiceStates.keySet()) { 2990 pw.println(" " + subId + "=" + mServiceStates.get(subId)); 2991 } 2992 if (mFpm != null && mFpm.isHardwareDetected()) { 2993 final int userId = ActivityManager.getCurrentUser(); 2994 final int strongAuthFlags = mStrongAuthTracker.getStrongAuthForUser(userId); 2995 BiometricAuthenticated fingerprint = mUserFingerprintAuthenticated.get(userId); 2996 pw.println(" Fingerprint state (user=" + userId + ")"); 2997 pw.println(" allowed=" 2998 + (fingerprint != null 2999 && isUnlockingWithBiometricAllowed(fingerprint.mIsStrongBiometric))); 3000 pw.println(" auth'd=" + (fingerprint != null && fingerprint.mAuthenticated)); 3001 pw.println(" authSinceBoot=" 3002 + getStrongAuthTracker().hasUserAuthenticatedSinceBoot()); 3003 pw.println(" disabled(DPM)=" + isFingerprintDisabled(userId)); 3004 pw.println(" possible=" + isUnlockWithFingerprintPossible(userId)); 3005 pw.println(" listening: actual=" + mFingerprintRunningState 3006 + " expected=" + (shouldListenForFingerprint() ? 1 : 0)); 3007 pw.println(" strongAuthFlags=" + Integer.toHexString(strongAuthFlags)); 3008 pw.println(" trustManaged=" + getUserTrustIsManaged(userId)); 3009 } 3010 if (mFaceManager != null && mFaceManager.isHardwareDetected()) { 3011 final int userId = ActivityManager.getCurrentUser(); 3012 final int strongAuthFlags = mStrongAuthTracker.getStrongAuthForUser(userId); 3013 BiometricAuthenticated face = mUserFaceAuthenticated.get(userId); 3014 pw.println(" Face authentication state (user=" + userId + ")"); 3015 pw.println(" allowed=" 3016 + (face != null && isUnlockingWithBiometricAllowed(face.mIsStrongBiometric))); 3017 pw.println(" auth'd=" 3018 + (face != null && face.mAuthenticated)); 3019 pw.println(" authSinceBoot=" 3020 + getStrongAuthTracker().hasUserAuthenticatedSinceBoot()); 3021 pw.println(" disabled(DPM)=" + isFaceDisabled(userId)); 3022 pw.println(" possible=" + isUnlockWithFacePossible(userId)); 3023 pw.println(" strongAuthFlags=" + Integer.toHexString(strongAuthFlags)); 3024 pw.println(" trustManaged=" + getUserTrustIsManaged(userId)); 3025 pw.println(" enabledByUser=" + mFaceSettingEnabledForUser.get(userId)); 3026 pw.println(" mSecureCameraLaunched=" + mSecureCameraLaunched); 3027 } 3028 if (mFaceListenModels != null && !mFaceListenModels.isEmpty()) { 3029 final SimpleDateFormat dateFormat = 3030 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US); 3031 pw.println(" Face listen results (last " + FACE_LISTEN_CALLS_QUEUE_SIZE + " calls):"); 3032 for (final KeyguardFaceListenModel model : mFaceListenModels) { 3033 final String time = dateFormat.format(new Date(model.getTimeMillis())); 3034 pw.println(" " + time + " " + model.toString()); 3035 } 3036 } 3037 if (mIsAutomotive) { 3038 pw.println(" Running on Automotive build"); 3039 } 3040 } 3041 } 3042