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