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