• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017, 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.server.wm;
18 
19 import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
20 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
21 import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
22 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
23 import static android.content.Context.DEVICE_POLICY_SERVICE;
24 import static android.content.Context.STATUS_BAR_SERVICE;
25 import static android.content.Intent.ACTION_CALL_EMERGENCY;
26 import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_ALWAYS;
27 import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_DEFAULT;
28 import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_IF_ALLOWLISTED;
29 import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_NEVER;
30 import static android.os.UserHandle.USER_ALL;
31 import static android.os.UserHandle.USER_CURRENT;
32 import static android.telecom.TelecomManager.EMERGENCY_DIALER_COMPONENT;
33 
34 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_LOCKTASK;
35 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
36 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
37 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
38 
39 import android.annotation.NonNull;
40 import android.annotation.Nullable;
41 import android.app.Activity;
42 import android.app.ActivityManager;
43 import android.app.StatusBarManager;
44 import android.app.admin.DevicePolicyManager;
45 import android.app.admin.IDevicePolicyManager;
46 import android.content.ComponentName;
47 import android.content.Context;
48 import android.content.Intent;
49 import android.os.Binder;
50 import android.os.Debug;
51 import android.os.Handler;
52 import android.os.IBinder;
53 import android.os.RemoteException;
54 import android.os.ServiceManager;
55 import android.os.UserHandle;
56 import android.provider.Settings;
57 import android.telecom.TelecomManager;
58 import android.util.Pair;
59 import android.util.Slog;
60 import android.util.SparseArray;
61 import android.util.SparseIntArray;
62 
63 import com.android.internal.annotations.VisibleForTesting;
64 import com.android.internal.policy.IKeyguardDismissCallback;
65 import com.android.internal.protolog.common.ProtoLog;
66 import com.android.internal.statusbar.IStatusBarService;
67 import com.android.internal.widget.LockPatternUtils;
68 import com.android.server.LocalServices;
69 import com.android.server.am.ActivityManagerService;
70 import com.android.server.statusbar.StatusBarManagerInternal;
71 
72 import java.io.PrintWriter;
73 import java.util.ArrayList;
74 import java.util.Arrays;
75 
76 /**
77  * Helper class that deals with all things related to task locking. This includes the screen pinning
78  * mode that can be launched via System UI as well as the fully locked mode that can be achieved
79  * on fully managed devices.
80  *
81  * Note: All methods in this class should only be called with the ActivityTaskManagerService lock
82  * held.
83  *
84  * @see Activity#startLockTask()
85  * @see Activity#stopLockTask()
86  */
87 public class LockTaskController {
88     private static final String TAG = TAG_WITH_CLASS_NAME ? "LockTaskController" : TAG_ATM;
89     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
90 
91     @VisibleForTesting
92     static final int STATUS_BAR_MASK_LOCKED = StatusBarManager.DISABLE_MASK
93             & (~StatusBarManager.DISABLE_EXPAND)
94             & (~StatusBarManager.DISABLE_NOTIFICATION_TICKER)
95             & (~StatusBarManager.DISABLE_SYSTEM_INFO)
96             & (~StatusBarManager.DISABLE_BACK);
97     @VisibleForTesting
98     static final int STATUS_BAR_MASK_PINNED = StatusBarManager.DISABLE_MASK
99             & (~StatusBarManager.DISABLE_BACK)
100             & (~StatusBarManager.DISABLE_HOME)
101             & (~StatusBarManager.DISABLE_RECENT);
102 
103     private static final SparseArray<Pair<Integer, Integer>> STATUS_BAR_FLAG_MAP_LOCKED;
104     static {
105         STATUS_BAR_FLAG_MAP_LOCKED = new SparseArray<>();
106 
STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO, new Pair<>(StatusBarManager.DISABLE_CLOCK, StatusBarManager.DISABLE2_SYSTEM_ICONS))107         STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO,
108                 new Pair<>(StatusBarManager.DISABLE_CLOCK, StatusBarManager.DISABLE2_SYSTEM_ICONS));
109 
STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS, new Pair<>(StatusBarManager.DISABLE_NOTIFICATION_ICONS | StatusBarManager.DISABLE_NOTIFICATION_ALERTS, StatusBarManager.DISABLE2_NOTIFICATION_SHADE))110         STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS,
111                 new Pair<>(StatusBarManager.DISABLE_NOTIFICATION_ICONS
112                         | StatusBarManager.DISABLE_NOTIFICATION_ALERTS,
113                         StatusBarManager.DISABLE2_NOTIFICATION_SHADE));
114 
STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_HOME, new Pair<>(StatusBarManager.DISABLE_HOME, StatusBarManager.DISABLE2_NONE))115         STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_HOME,
116                 new Pair<>(StatusBarManager.DISABLE_HOME, StatusBarManager.DISABLE2_NONE));
117 
STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW, new Pair<>(StatusBarManager.DISABLE_RECENT, StatusBarManager.DISABLE2_NONE))118         STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW,
119                 new Pair<>(StatusBarManager.DISABLE_RECENT, StatusBarManager.DISABLE2_NONE));
120 
STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS, new Pair<>(StatusBarManager.DISABLE_NONE, StatusBarManager.DISABLE2_GLOBAL_ACTIONS))121         STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
122                 new Pair<>(StatusBarManager.DISABLE_NONE,
123                         StatusBarManager.DISABLE2_GLOBAL_ACTIONS));
124     }
125 
126     /** Tag used for disabling of keyguard */
127     private static final String LOCK_TASK_TAG = "Lock-to-App";
128 
129     /** Can't be put in lockTask mode. */
130     static final int LOCK_TASK_AUTH_DONT_LOCK = 0;
131     /** Can enter app pinning with user approval. Can never start over existing lockTask task. */
132     static final int LOCK_TASK_AUTH_PINNABLE = 1;
133     /** Starts in LOCK_TASK_MODE_LOCKED automatically. Can start over existing lockTask task. */
134     static final int LOCK_TASK_AUTH_LAUNCHABLE = 2;
135     /** Can enter lockTask without user approval. Can start over existing lockTask task. */
136     static final int LOCK_TASK_AUTH_ALLOWLISTED = 3;
137     /** Priv-app that starts in LOCK_TASK_MODE_LOCKED automatically. Can start over existing
138      * lockTask task. */
139     static final int LOCK_TASK_AUTH_LAUNCHABLE_PRIV = 4;
140 
141     private final IBinder mToken = new LockTaskToken();
142     private final ActivityTaskSupervisor mSupervisor;
143     private final Context mContext;
144     private final TaskChangeNotificationController mTaskChangeNotificationController;
145 
146     // The following system services cannot be final, because they do not exist when this class
147     // is instantiated during device boot
148     @VisibleForTesting
149     IStatusBarService mStatusBarService;
150     @VisibleForTesting
151     IDevicePolicyManager mDevicePolicyManager;
152     @VisibleForTesting
153     WindowManagerService mWindowManager;
154     @VisibleForTesting
155     LockPatternUtils mLockPatternUtils;
156     @VisibleForTesting
157     TelecomManager mTelecomManager;
158 
159     /**
160      * The chain of tasks in LockTask mode, in the order of when they first entered LockTask mode.
161      *
162      * The first task in the list, which started the current LockTask session, is called the root
163      * task. It coincides with the Home task in a typical multi-app kiosk deployment. When there are
164      * more than one locked tasks, the root task can't be finished. Nor can it be moved to the back
165      * of the stack by {@link Task#moveTaskToBack(Task)};
166      *
167      * Calling {@link Activity#stopLockTask()} on the root task will finish all tasks but itself in
168      * this list, and the device will exit LockTask mode.
169      *
170      * The list is empty if LockTask is inactive.
171      */
172     private final ArrayList<Task> mLockTaskModeTasks = new ArrayList<>();
173 
174     /**
175      * Packages that are allowed to be launched into the lock task mode for each user.
176      */
177     private final SparseArray<String[]> mLockTaskPackages = new SparseArray<>();
178 
179     /**
180      * Features that are allowed by DPC to show during LockTask mode.
181      */
182     private final SparseIntArray mLockTaskFeatures = new SparseIntArray();
183 
184     /**
185      * Store the current lock task mode. Possible values:
186      * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
187      * {@link ActivityManager#LOCK_TASK_MODE_PINNED}
188      */
189     private volatile int mLockTaskModeState = LOCK_TASK_MODE_NONE;
190 
191     /**
192      * This is ActivityTaskSupervisor's Handler.
193      */
194     private final Handler mHandler;
195 
196     /**
197      * Stores the user for which we're trying to dismiss the keyguard and then subsequently
198      * disable it.
199      *
200      * Tracking this ensures we don't mistakenly disable the keyguard if we've stopped trying to
201      * between the dismiss request and when it succeeds.
202      *
203      * Must only be accessed from the Handler thread.
204      */
205     private int mPendingDisableFromDismiss = UserHandle.USER_NULL;
206 
LockTaskController(Context context, ActivityTaskSupervisor supervisor, Handler handler, TaskChangeNotificationController taskChangeNotificationController)207     LockTaskController(Context context, ActivityTaskSupervisor supervisor,
208             Handler handler, TaskChangeNotificationController taskChangeNotificationController) {
209         mContext = context;
210         mSupervisor = supervisor;
211         mHandler = handler;
212         mTaskChangeNotificationController = taskChangeNotificationController;
213     }
214 
215     /**
216      * Set the window manager instance used in this class. This is necessary, because the window
217      * manager does not exist during instantiation of this class.
218      */
setWindowManager(WindowManagerService windowManager)219     void setWindowManager(WindowManagerService windowManager) {
220         mWindowManager = windowManager;
221     }
222 
223     /**
224      * @return the current lock task state. This can be any of
225      * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
226      * {@link ActivityManager#LOCK_TASK_MODE_PINNED}.
227      */
getLockTaskModeState()228     int getLockTaskModeState() {
229         return mLockTaskModeState;
230     }
231 
232     /**
233      * @return whether the given task is locked at the moment. Locked tasks cannot be moved to the
234      * back of the stack.
235      */
236     @VisibleForTesting
isTaskLocked(Task task)237     boolean isTaskLocked(Task task) {
238         return mLockTaskModeTasks.contains(task);
239     }
240 
241     /**
242      * @return {@code true} whether this task first started the current LockTask session.
243      */
isRootTask(Task task)244     private boolean isRootTask(Task task) {
245         return mLockTaskModeTasks.indexOf(task) == 0;
246     }
247 
248     /**
249      * @return whether the given activity is blocked from finishing, because it is the only activity
250      * of the last locked task and finishing it would mean that lock task mode is ended illegally.
251      */
activityBlockedFromFinish(ActivityRecord activity)252     boolean activityBlockedFromFinish(ActivityRecord activity) {
253         final Task task = activity.getTask();
254         if (activity == task.getRootActivity()
255                 && activity == task.getTopNonFinishingActivity()
256                 && task.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV
257                 && isRootTask(task)) {
258             Slog.i(TAG, "Not finishing task in lock task mode");
259             showLockTaskToast();
260             return true;
261         }
262         return false;
263     }
264 
265     /**
266      * @return whether the given task can be moved to the back of the stack with
267      * {@link Task#moveTaskToBack(Task)}
268      * @see #mLockTaskModeTasks
269      */
canMoveTaskToBack(Task task)270     boolean canMoveTaskToBack(Task task) {
271         if (isRootTask(task)) {
272             showLockTaskToast();
273             return false;
274         }
275         return true;
276     }
277 
278     /**
279      * @return whether the requested task auth is allowed to be locked.
280      */
isTaskAuthAllowlisted(int lockTaskAuth)281     static boolean isTaskAuthAllowlisted(int lockTaskAuth) {
282         switch(lockTaskAuth) {
283             case LOCK_TASK_AUTH_ALLOWLISTED:
284             case LOCK_TASK_AUTH_LAUNCHABLE:
285             case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
286                 return true;
287             case LOCK_TASK_AUTH_PINNABLE:
288             case LOCK_TASK_AUTH_DONT_LOCK:
289             default:
290                 return false;
291         }
292     }
293 
294     /**
295      * @return whether the requested task is disallowed to be launched.
296      */
isLockTaskModeViolation(Task task)297     boolean isLockTaskModeViolation(Task task) {
298         return isLockTaskModeViolation(task, false);
299     }
300 
301     /**
302      * @param isNewClearTask whether the task would be cleared as part of the operation.
303      * @return whether the requested task is disallowed to be launched.
304      */
isLockTaskModeViolation(Task task, boolean isNewClearTask)305     boolean isLockTaskModeViolation(Task task, boolean isNewClearTask) {
306         // TODO: Double check what's going on here. If the task is already in lock task mode, it's
307         // likely allowlisted, so will return false below.
308         if (isTaskLocked(task) && !isNewClearTask) {
309             // If the task is already at the top and won't be cleared, then allow the operation
310         } else if (isLockTaskModeViolationInternal(task, task.mUserId, task.intent,
311                 task.mLockTaskAuth)) {
312             showLockTaskToast();
313             return true;
314         }
315         return false;
316     }
317 
318     /**
319      * @param activity an activity that is going to be started in a new task as the root activity.
320      * @return whether the given activity is allowed to be launched.
321      */
isNewTaskLockTaskModeViolation(ActivityRecord activity)322     boolean isNewTaskLockTaskModeViolation(ActivityRecord activity) {
323         // Use the belong task (if any) to perform the lock task checks
324         if (activity.getTask() != null) {
325             return isLockTaskModeViolation(activity.getTask());
326         }
327 
328         int auth = getLockTaskAuth(activity, null /* task */);
329         if (isLockTaskModeViolationInternal(activity, activity.mUserId, activity.intent, auth)) {
330             showLockTaskToast();
331             return true;
332         }
333         return false;
334     }
335 
336     /**
337      * @return the root task of the lock task.
338      */
getRootTask()339     Task getRootTask() {
340         if (mLockTaskModeTasks.isEmpty()) {
341             return null;
342         }
343         return mLockTaskModeTasks.get(0);
344     }
345 
isLockTaskModeViolationInternal(WindowContainer wc, int userId, Intent intent, int taskAuth)346     private boolean isLockTaskModeViolationInternal(WindowContainer wc, int userId,
347             Intent intent, int taskAuth) {
348         // Allow recents activity if enabled by policy
349         if (wc.isActivityTypeRecents() && isRecentsAllowed(userId)) {
350             return false;
351         }
352 
353         // Allow emergency calling when the device is protected by a locked keyguard
354         if (isKeyguardAllowed(userId) && isEmergencyCallIntent(intent)) {
355             return false;
356         }
357 
358         // Allow the dream to start during lock task mode
359         if (wc.isActivityTypeDream()) {
360             return false;
361         }
362 
363         return !(isTaskAuthAllowlisted(taskAuth) || mLockTaskModeTasks.isEmpty());
364     }
365 
isRecentsAllowed(int userId)366     private boolean isRecentsAllowed(int userId) {
367         return (getLockTaskFeaturesForUser(userId)
368                 & DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW) != 0;
369     }
370 
isKeyguardAllowed(int userId)371     private boolean isKeyguardAllowed(int userId) {
372         return (getLockTaskFeaturesForUser(userId)
373                 & DevicePolicyManager.LOCK_TASK_FEATURE_KEYGUARD) != 0;
374     }
375 
isBlockingInTaskEnabled(int userId)376     private boolean isBlockingInTaskEnabled(int userId) {
377         return (getLockTaskFeaturesForUser(userId)
378                 & DevicePolicyManager.LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK) != 0;
379     }
380 
isActivityAllowed(int userId, String packageName, int lockTaskLaunchMode)381     boolean isActivityAllowed(int userId, String packageName, int lockTaskLaunchMode) {
382         if (mLockTaskModeState != LOCK_TASK_MODE_LOCKED || !isBlockingInTaskEnabled(userId)) {
383             return true;
384         }
385         switch (lockTaskLaunchMode) {
386             case LOCK_TASK_LAUNCH_MODE_ALWAYS:
387                 return true;
388             case LOCK_TASK_LAUNCH_MODE_NEVER:
389                 return false;
390             default:
391         }
392         return isPackageAllowlisted(userId, packageName);
393     }
394 
isEmergencyCallIntent(Intent intent)395     private boolean isEmergencyCallIntent(Intent intent) {
396         if (intent == null) {
397             return false;
398         }
399 
400         // 1. The emergency keypad activity launched on top of the keyguard
401         if (EMERGENCY_DIALER_COMPONENT.equals(intent.getComponent())) {
402             return true;
403         }
404 
405         // 2. The intent sent by the keypad, which is handled by Telephony
406         if (ACTION_CALL_EMERGENCY.equals(intent.getAction())) {
407             return true;
408         }
409 
410         // 3. Telephony then starts the default package for making the call
411         final TelecomManager tm = getTelecomManager();
412         final String dialerPackage = tm != null ? tm.getSystemDialerPackage() : null;
413         if (dialerPackage != null && dialerPackage.equals(intent.getComponent().getPackageName())) {
414             return true;
415         }
416 
417         return false;
418     }
419 
420     /**
421      * Stop the current lock task mode.
422      *
423      * This is called by {@link ActivityManagerService} and performs various checks before actually
424      * finishing the locked task.
425      *
426      * @param task the task that requested the end of lock task mode ({@code null} for quitting app
427      *             pinning mode)
428      * @param isSystemCaller indicates whether this request comes from the system via
429      *                       {@link ActivityTaskManagerService#stopSystemLockTaskMode()}. If
430      *                       {@code true}, it means the user intends to stop pinned mode through UI;
431      *                       otherwise, it's called by an app and we need to stop locked or pinned
432      *                       mode, subject to checks.
433      * @param callingUid the caller that requested the end of lock task mode.
434      * @throws IllegalArgumentException if the calling task is invalid (e.g., {@code null} or not in
435      *                                  foreground)
436      * @throws SecurityException if the caller is not authorized to stop the lock task mode, i.e. if
437      *                           they differ from the one that launched lock task mode.
438      */
stopLockTaskMode(@ullable Task task, boolean isSystemCaller, int callingUid)439     void stopLockTaskMode(@Nullable Task task, boolean isSystemCaller, int callingUid) {
440         if (mLockTaskModeState == LOCK_TASK_MODE_NONE) {
441             return;
442         }
443 
444         if (isSystemCaller) {
445             if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
446                 clearLockedTasks("stopAppPinning");
447             } else {
448                 Slog.e(TAG_LOCKTASK, "Attempted to stop LockTask with isSystemCaller=true");
449                 showLockTaskToast();
450             }
451 
452         } else {
453             // Ensure calling activity is not null
454             if (task == null) {
455                 throw new IllegalArgumentException("can't stop LockTask for null task");
456             }
457 
458             // Ensure the same caller for startLockTaskMode and stopLockTaskMode.
459             // It is possible lockTaskMode was started by the system process because
460             // android:lockTaskMode is set to a locking value in the application manifest
461             // instead of the app calling startLockTaskMode. In this case
462             // {@link Task.mLockTaskUid} will be 0, so we compare the callingUid to the
463             // {@link Task.effectiveUid} instead. Also caller with
464             // {@link MANAGE_ACTIVITY_TASKS} can stop any lock task.
465             if (callingUid != task.mLockTaskUid
466                     && (task.mLockTaskUid != 0 || callingUid != task.effectiveUid)) {
467                 throw new SecurityException("Invalid uid, expected " + task.mLockTaskUid
468                         + " callingUid=" + callingUid + " effectiveUid=" + task.effectiveUid);
469             }
470 
471             // We don't care if it's pinned or locked mode; this will stop it anyways.
472             clearLockedTask(task);
473         }
474     }
475 
476     /**
477      * Clear all locked tasks and request the end of LockTask mode.
478      *
479      * This method is called by UserController when starting a new foreground user, and,
480      * unlike {@link #stopLockTaskMode(Task, boolean, int)}, it doesn't perform the checks.
481      */
clearLockedTasks(String reason)482     void clearLockedTasks(String reason) {
483         ProtoLog.i(WM_DEBUG_LOCKTASK, "clearLockedTasks: %s", reason);
484         if (!mLockTaskModeTasks.isEmpty()) {
485             clearLockedTask(mLockTaskModeTasks.get(0));
486         }
487     }
488 
489     /**
490      * Clear one locked task from LockTask mode.
491      *
492      * If the requested task is the root task (see {@link #mLockTaskModeTasks}), then all locked
493      * tasks are cleared. Otherwise, only the requested task is cleared. LockTask mode is stopped
494      * when the last locked task is cleared.
495      *
496      * @param task the task to be cleared from LockTask mode.
497      */
clearLockedTask(final Task task)498     void clearLockedTask(final Task task) {
499         if (task == null || mLockTaskModeTasks.isEmpty()) return;
500 
501         if (task == mLockTaskModeTasks.get(0)) {
502             // We're removing the root task while there are other locked tasks. Therefore we should
503             // clear all locked tasks in reverse order.
504             for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx > 0; --taskNdx) {
505                 clearLockedTask(mLockTaskModeTasks.get(taskNdx));
506             }
507         }
508 
509         removeLockedTask(task);
510         if (mLockTaskModeTasks.isEmpty()) {
511             return;
512         }
513         task.performClearTaskLocked();
514         mSupervisor.mRootWindowContainer.resumeFocusedTasksTopActivities();
515     }
516 
517     /**
518      * Remove the given task from the locked task list. If this was the last task in the list,
519      * lock task mode is stopped.
520      */
removeLockedTask(final Task task)521     private void removeLockedTask(final Task task) {
522         if (!mLockTaskModeTasks.remove(task)) {
523             return;
524         }
525         ProtoLog.d(WM_DEBUG_LOCKTASK, "removeLockedTask: removed %s", task);
526         if (mLockTaskModeTasks.isEmpty()) {
527             ProtoLog.d(WM_DEBUG_LOCKTASK, "removeLockedTask: task=%s last task, "
528                     + "reverting locktask mode. Callers=%s", task, Debug.getCallers(3));
529             mHandler.post(() -> performStopLockTask(task.mUserId));
530         }
531     }
532 
533     // This method should only be called on the handler thread
performStopLockTask(int userId)534     private void performStopLockTask(int userId) {
535         // Update the internal mLockTaskModeState early to avoid the scenario that SysUI queries
536         // mLockTaskModeState (from setStatusBarState) and gets staled state.
537         // TODO: revisit this approach.
538         // The race condition raised above can be addressed by moving this function out of handler
539         // thread, which makes it guarded by ATMS#mGlobalLock as ATMS#getLockTaskModeState.
540         final int oldLockTaskModeState = mLockTaskModeState;
541         mLockTaskModeState = LOCK_TASK_MODE_NONE;
542         mTaskChangeNotificationController.notifyLockTaskModeChanged(mLockTaskModeState);
543         // When lock task ends, we enable the status bars.
544         try {
545             setStatusBarState(mLockTaskModeState, userId);
546             setKeyguardState(mLockTaskModeState, userId);
547             if (oldLockTaskModeState == LOCK_TASK_MODE_PINNED) {
548                 lockKeyguardIfNeeded(userId);
549             }
550             if (getDevicePolicyManager() != null) {
551                 getDevicePolicyManager().notifyLockTaskModeChanged(false, null, userId);
552             }
553             if (oldLockTaskModeState == LOCK_TASK_MODE_PINNED) {
554                 getStatusBarService().showPinningEnterExitToast(false /* entering */);
555             }
556             mWindowManager.onLockTaskStateChanged(mLockTaskModeState);
557         } catch (RemoteException ex) {
558             throw new RuntimeException(ex);
559         }
560     }
561 
562     /**
563      * Show the lock task violation toast. Currently we only show toast for screen pinning mode, and
564      * no-op if the device is in locked mode.
565      */
showLockTaskToast()566     void showLockTaskToast() {
567         if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
568             try {
569                 getStatusBarService().showPinningEscapeToast();
570             } catch (RemoteException e) {
571                 Slog.e(TAG, "Failed to send pinning escape toast", e);
572             }
573         }
574     }
575 
576     // Starting lock task
577 
578     /**
579      * Method to start lock task mode on a given task.
580      *
581      * @param task the task that should be locked.
582      * @param isSystemCaller indicates whether this request was initiated by the system via
583      *                       {@link ActivityTaskManagerService#startSystemLockTaskMode(int)}. If
584      *                       {@code true}, this intends to start pinned mode; otherwise, we look
585      *                       at the calling task's mLockTaskAuth to decide which mode to start.
586      * @param callingUid the caller that requested the launch of lock task mode.
587      */
startLockTaskMode(@onNull Task task, boolean isSystemCaller, int callingUid)588     void startLockTaskMode(@NonNull Task task, boolean isSystemCaller, int callingUid) {
589         if (!isSystemCaller) {
590             task.mLockTaskUid = callingUid;
591             if (task.mLockTaskAuth == LOCK_TASK_AUTH_PINNABLE) {
592                 // startLockTask() called by app, but app is not part of lock task allowlist. Show
593                 // app pinning request. We will come back here with isSystemCaller true.
594                 ProtoLog.w(WM_DEBUG_LOCKTASK, "Mode default, asking user");
595                 StatusBarManagerInternal statusBarManager = LocalServices.getService(
596                         StatusBarManagerInternal.class);
597                 if (statusBarManager != null) {
598                     statusBarManager.showScreenPinningRequest(task.mTaskId);
599                 }
600                 return;
601             }
602         }
603 
604         // System can only initiate screen pinning, not full lock task mode
605         ProtoLog.w(WM_DEBUG_LOCKTASK, "%s", isSystemCaller ? "Locking pinned" : "Locking fully");
606         setLockTaskMode(task, isSystemCaller ? LOCK_TASK_MODE_PINNED : LOCK_TASK_MODE_LOCKED,
607                 "startLockTask", true);
608     }
609 
610     /**
611      * Start lock task mode on the given task.
612      * @param lockTaskModeState whether fully locked or pinned mode.
613      * @param andResume whether the task should be brought to foreground as part of the operation.
614      */
setLockTaskMode(@onNull Task task, int lockTaskModeState, String reason, boolean andResume)615     private void setLockTaskMode(@NonNull Task task, int lockTaskModeState,
616                                  String reason, boolean andResume) {
617         // Should have already been checked, but do it again.
618         if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
619             ProtoLog.w(WM_DEBUG_LOCKTASK,
620                     "setLockTaskMode: Can't lock due to auth");
621             return;
622         }
623         if (isLockTaskModeViolation(task)) {
624             Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
625             return;
626         }
627 
628         final Intent taskIntent = task.intent;
629         if (mLockTaskModeTasks.isEmpty() && taskIntent != null) {
630             mSupervisor.mRecentTasks.onLockTaskModeStateChanged(lockTaskModeState, task.mUserId);
631             // Start lock task on the handler thread
632             mHandler.post(() -> performStartLockTask(
633                     taskIntent.getComponent().getPackageName(),
634                     task.mUserId,
635                     lockTaskModeState));
636         }
637         ProtoLog.w(WM_DEBUG_LOCKTASK, "setLockTaskMode: Locking to %s Callers=%s",
638                 task, Debug.getCallers(4));
639 
640         if (!mLockTaskModeTasks.contains(task)) {
641             mLockTaskModeTasks.add(task);
642         }
643 
644         if (task.mLockTaskUid == -1) {
645             task.mLockTaskUid = task.effectiveUid;
646         }
647 
648         if (andResume) {
649             mSupervisor.findTaskToMoveToFront(task, 0, null, reason,
650                     lockTaskModeState != LOCK_TASK_MODE_NONE);
651             mSupervisor.mRootWindowContainer.resumeFocusedTasksTopActivities();
652             final Task rootTask = task.getRootTask();
653             if (rootTask != null) {
654                 rootTask.mDisplayContent.executeAppTransition();
655             }
656         } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
657             mSupervisor.handleNonResizableTaskIfNeeded(task, WINDOWING_MODE_UNDEFINED,
658                     mSupervisor.mRootWindowContainer.getDefaultTaskDisplayArea(),
659                     task.getRootTask(), true /* forceNonResizable */);
660         }
661     }
662 
663     // This method should only be called on the handler thread
performStartLockTask(String packageName, int userId, int lockTaskModeState)664     private void performStartLockTask(String packageName, int userId, int lockTaskModeState) {
665         // When lock task starts, we disable the status bars.
666         try {
667             if (lockTaskModeState == LOCK_TASK_MODE_PINNED) {
668                 getStatusBarService().showPinningEnterExitToast(true /* entering */);
669             }
670             mWindowManager.onLockTaskStateChanged(lockTaskModeState);
671             mLockTaskModeState = lockTaskModeState;
672             mTaskChangeNotificationController.notifyLockTaskModeChanged(mLockTaskModeState);
673             setStatusBarState(lockTaskModeState, userId);
674             setKeyguardState(lockTaskModeState, userId);
675             if (getDevicePolicyManager() != null) {
676                 getDevicePolicyManager().notifyLockTaskModeChanged(true, packageName, userId);
677             }
678         } catch (RemoteException ex) {
679             throw new RuntimeException(ex);
680         }
681     }
682 
683     /**
684      * Update packages that are allowed to be launched in lock task mode.
685      * @param userId Which user this allowlist is associated with
686      * @param packages The allowlist of packages allowed in lock task mode
687      * @see #mLockTaskPackages
688      */
updateLockTaskPackages(int userId, String[] packages)689     void updateLockTaskPackages(int userId, String[] packages) {
690         mLockTaskPackages.put(userId, packages);
691 
692         boolean taskChanged = false;
693         for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
694             final Task lockedTask = mLockTaskModeTasks.get(taskNdx);
695             final boolean wasAllowlisted = lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE
696                     || lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_ALLOWLISTED;
697             lockedTask.setLockTaskAuth();
698             final boolean isAllowlisted = lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE
699                     || lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_ALLOWLISTED;
700 
701             if (mLockTaskModeState != LOCK_TASK_MODE_LOCKED
702                     || lockedTask.mUserId != userId
703                     || !wasAllowlisted || isAllowlisted) {
704                 continue;
705             }
706 
707             // Terminate locked tasks that have recently lost allowlist authorization.
708             ProtoLog.d(WM_DEBUG_LOCKTASK, "onLockTaskPackagesUpdated: removing %s"
709                     + " mLockTaskAuth()=%s", lockedTask, lockedTask.lockTaskAuthToString());
710             removeLockedTask(lockedTask);
711             lockedTask.performClearTaskLocked();
712             taskChanged = true;
713         }
714 
715         mSupervisor.mRootWindowContainer.forAllTasks(Task::setLockTaskAuth);
716 
717         final ActivityRecord r = mSupervisor.mRootWindowContainer.topRunningActivity();
718         final Task task = (r != null) ? r.getTask() : null;
719         if (mLockTaskModeTasks.isEmpty() && task!= null
720                 && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
721             // This task must have just been authorized.
722             ProtoLog.d(WM_DEBUG_LOCKTASK, "onLockTaskPackagesUpdated: starting new "
723                     + "locktask task=%s", task);
724             setLockTaskMode(task, LOCK_TASK_MODE_LOCKED, "package updated", false);
725             taskChanged = true;
726         }
727 
728         if (taskChanged) {
729             mSupervisor.mRootWindowContainer.resumeFocusedTasksTopActivities();
730         }
731     }
732 
getLockTaskAuth(@ullable ActivityRecord rootActivity, @Nullable Task task)733     int getLockTaskAuth(@Nullable ActivityRecord rootActivity, @Nullable Task task) {
734         if (rootActivity == null && task == null) {
735             return LOCK_TASK_AUTH_DONT_LOCK;
736         }
737         if (rootActivity == null) {
738             return LOCK_TASK_AUTH_PINNABLE;
739         }
740 
741         final String pkg = (task == null || task.realActivity == null) ? rootActivity.packageName
742                 : task.realActivity.getPackageName();
743         final int userId = task != null ? task.mUserId : rootActivity.mUserId;
744         int lockTaskAuth = LOCK_TASK_AUTH_DONT_LOCK;
745         switch (rootActivity.lockTaskLaunchMode) {
746             case LOCK_TASK_LAUNCH_MODE_DEFAULT:
747                 lockTaskAuth = isPackageAllowlisted(userId, pkg)
748                         ? LOCK_TASK_AUTH_ALLOWLISTED : LOCK_TASK_AUTH_PINNABLE;
749                 break;
750 
751             case LOCK_TASK_LAUNCH_MODE_NEVER:
752                 lockTaskAuth = LOCK_TASK_AUTH_DONT_LOCK;
753                 break;
754 
755             case LOCK_TASK_LAUNCH_MODE_ALWAYS:
756                 lockTaskAuth = LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
757                 break;
758 
759             case LOCK_TASK_LAUNCH_MODE_IF_ALLOWLISTED:
760                 lockTaskAuth = isPackageAllowlisted(userId, pkg)
761                         ? LOCK_TASK_AUTH_LAUNCHABLE : LOCK_TASK_AUTH_PINNABLE;
762                 break;
763         }
764         return lockTaskAuth;
765     }
766 
isPackageAllowlisted(int userId, String pkg)767     boolean isPackageAllowlisted(int userId, String pkg) {
768         if (pkg == null) {
769             return false;
770         }
771         String[] allowlist;
772         allowlist = mLockTaskPackages.get(userId);
773         if (allowlist == null) {
774             return false;
775         }
776         for (String allowlistedPkg : allowlist) {
777             if (pkg.equals(allowlistedPkg)) {
778                 return true;
779             }
780         }
781         return false;
782     }
783 
784     /**
785      * Update the UI features that are enabled for LockTask mode.
786      * @param userId Which user these feature flags are associated with
787      * @param flags Bitfield of feature flags
788      * @see DevicePolicyManager#setLockTaskFeatures(ComponentName, int)
789      */
updateLockTaskFeatures(int userId, int flags)790     void updateLockTaskFeatures(int userId, int flags) {
791         int oldFlags = getLockTaskFeaturesForUser(userId);
792         if (flags == oldFlags) {
793             return;
794         }
795 
796         mLockTaskFeatures.put(userId, flags);
797         if (!mLockTaskModeTasks.isEmpty() && userId == mLockTaskModeTasks.get(0).mUserId) {
798             mHandler.post(() -> {
799                 if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
800                     setStatusBarState(mLockTaskModeState, userId);
801                     setKeyguardState(mLockTaskModeState, userId);
802                 }
803             });
804         }
805     }
806 
807     /**
808      * Helper method for configuring the status bar disabled state.
809      * Should only be called on the handler thread to avoid race.
810      */
setStatusBarState(int lockTaskModeState, int userId)811     private void setStatusBarState(int lockTaskModeState, int userId) {
812         IStatusBarService statusBar = getStatusBarService();
813         if (statusBar == null) {
814             Slog.e(TAG, "Can't find StatusBarService");
815             return;
816         }
817 
818         // Default state, when lockTaskModeState == LOCK_TASK_MODE_NONE
819         int flags1 = StatusBarManager.DISABLE_NONE;
820         int flags2 = StatusBarManager.DISABLE2_NONE;
821 
822         if (lockTaskModeState == LOCK_TASK_MODE_PINNED) {
823             flags1 = STATUS_BAR_MASK_PINNED;
824 
825         } else if (lockTaskModeState == LOCK_TASK_MODE_LOCKED) {
826             int lockTaskFeatures = getLockTaskFeaturesForUser(userId);
827             Pair<Integer, Integer> statusBarFlags = getStatusBarDisableFlags(lockTaskFeatures);
828             flags1 = statusBarFlags.first;
829             flags2 = statusBarFlags.second;
830         }
831 
832         try {
833             statusBar.disable(flags1, mToken, mContext.getPackageName());
834             statusBar.disable2(flags2, mToken, mContext.getPackageName());
835         } catch (RemoteException e) {
836             Slog.e(TAG, "Failed to set status bar flags", e);
837         }
838     }
839 
840     /**
841      * Helper method for configuring the keyguard disabled state.
842      * Should only be called on the handler thread to avoid race.
843      */
setKeyguardState(int lockTaskModeState, int userId)844     private void setKeyguardState(int lockTaskModeState, int userId) {
845         mPendingDisableFromDismiss = UserHandle.USER_NULL;
846         if (lockTaskModeState == LOCK_TASK_MODE_NONE) {
847             mWindowManager.reenableKeyguard(mToken, userId);
848 
849         } else if (lockTaskModeState == LOCK_TASK_MODE_LOCKED) {
850             if (isKeyguardAllowed(userId)) {
851                 mWindowManager.reenableKeyguard(mToken, userId);
852             } else {
853                 // If keyguard is not secure and it is locked, dismiss the keyguard before
854                 // disabling it, which avoids the platform to think the keyguard is still on.
855                 if (mWindowManager.isKeyguardLocked() && !mWindowManager.isKeyguardSecure(userId)) {
856                     mPendingDisableFromDismiss = userId;
857                     mWindowManager.dismissKeyguard(new IKeyguardDismissCallback.Stub() {
858                         @Override
859                         public void onDismissError() throws RemoteException {
860                             Slog.i(TAG, "setKeyguardState: failed to dismiss keyguard");
861                         }
862 
863                         @Override
864                         public void onDismissSucceeded() throws RemoteException {
865                             mHandler.post(
866                                     () -> {
867                                         if (mPendingDisableFromDismiss == userId) {
868                                             mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG,
869                                                     userId);
870                                             mPendingDisableFromDismiss = UserHandle.USER_NULL;
871                                         }
872                                     });
873                         }
874 
875                         @Override
876                         public void onDismissCancelled() throws RemoteException {
877                             Slog.i(TAG, "setKeyguardState: dismiss cancelled");
878                         }
879                     }, null);
880                 } else {
881                     mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG, userId);
882                 }
883             }
884 
885         } else { // lockTaskModeState == LOCK_TASK_MODE_PINNED
886             mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG, userId);
887         }
888     }
889 
890     /**
891      * Helper method for locking the device immediately. This may be necessary when the device
892      * leaves the pinned mode.
893      */
lockKeyguardIfNeeded(int userId)894     private void lockKeyguardIfNeeded(int userId) {
895         if (shouldLockKeyguard(userId)) {
896             mWindowManager.lockNow(null);
897             mWindowManager.dismissKeyguard(null /* callback */, null /* message */);
898             getLockPatternUtils().requireCredentialEntry(USER_ALL);
899         }
900     }
901 
shouldLockKeyguard(int userId)902     private boolean shouldLockKeyguard(int userId) {
903         // This functionality should be kept consistent with
904         // com.android.settings.security.ScreenPinningSettings (see b/127605586)
905         try {
906             return Settings.Secure.getIntForUser(
907                     mContext.getContentResolver(),
908                     Settings.Secure.LOCK_TO_APP_EXIT_LOCKED, USER_CURRENT) != 0;
909         } catch (Settings.SettingNotFoundException e) {
910             // Log to SafetyNet for b/127605586
911             android.util.EventLog.writeEvent(0x534e4554, "127605586", -1, "");
912             return getLockPatternUtils().isSecure(userId);
913         }
914     }
915 
916     /**
917      * Translates from LockTask feature flags to StatusBarManager disable and disable2 flags.
918      * @param lockTaskFlags Bitfield of flags as per
919      *                      {@link DevicePolicyManager#setLockTaskFeatures(ComponentName, int)}
920      * @return A {@link Pair} of {@link StatusBarManager#disable(int)} and
921      *         {@link StatusBarManager#disable2(int)} flags
922      */
923     @VisibleForTesting
getStatusBarDisableFlags(int lockTaskFlags)924     Pair<Integer, Integer> getStatusBarDisableFlags(int lockTaskFlags) {
925         // Everything is disabled by default
926         int flags1 = StatusBarManager.DISABLE_MASK;
927         int flags2 = StatusBarManager.DISABLE2_MASK;
928         for (int i = STATUS_BAR_FLAG_MAP_LOCKED.size() - 1; i >= 0; i--) {
929             Pair<Integer, Integer> statusBarFlags = STATUS_BAR_FLAG_MAP_LOCKED.valueAt(i);
930             if ((STATUS_BAR_FLAG_MAP_LOCKED.keyAt(i) & lockTaskFlags) != 0) {
931                 flags1 &= ~statusBarFlags.first;
932                 flags2 &= ~statusBarFlags.second;
933             }
934         }
935         // Some flags are not used for LockTask purposes, so we mask them
936         flags1 &= STATUS_BAR_MASK_LOCKED;
937         return new Pair<>(flags1, flags2);
938     }
939 
940     /**
941      * @param packageName The package to check
942      * @return Whether the package is the base of any locked task
943      */
isBaseOfLockedTask(String packageName)944     boolean isBaseOfLockedTask(String packageName) {
945         for (int i = 0; i < mLockTaskModeTasks.size(); i++) {
946             final Intent bi = mLockTaskModeTasks.get(i).getBaseIntent();
947             if (bi != null && packageName.equals(bi.getComponent()
948                     .getPackageName())) {
949                 return true;
950             }
951         }
952         return false;
953     }
954 
955     /**
956      * Gets the cached value of LockTask feature flags for a specific user.
957      */
getLockTaskFeaturesForUser(int userId)958     private int getLockTaskFeaturesForUser(int userId) {
959         return mLockTaskFeatures.get(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
960     }
961 
962     // Should only be called on the handler thread
963     @Nullable
getStatusBarService()964     private IStatusBarService getStatusBarService() {
965         if (mStatusBarService == null) {
966             mStatusBarService = IStatusBarService.Stub.asInterface(
967                     ServiceManager.checkService(STATUS_BAR_SERVICE));
968             if (mStatusBarService == null) {
969                 Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
970             }
971         }
972         return mStatusBarService;
973     }
974 
975     // Should only be called on the handler thread
976     @Nullable
getDevicePolicyManager()977     private IDevicePolicyManager getDevicePolicyManager() {
978         if (mDevicePolicyManager == null) {
979             mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
980                     ServiceManager.checkService(DEVICE_POLICY_SERVICE));
981             if (mDevicePolicyManager == null) {
982                 Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
983             }
984         }
985         return mDevicePolicyManager;
986     }
987 
988     @NonNull
getLockPatternUtils()989     private LockPatternUtils getLockPatternUtils() {
990         if (mLockPatternUtils == null) {
991             // We don't preserve the LPU object to save memory
992             return new LockPatternUtils(mContext);
993         }
994         return mLockPatternUtils;
995     }
996 
997     @Nullable
getTelecomManager()998     private TelecomManager getTelecomManager() {
999         if (mTelecomManager == null) {
1000             // We don't preserve the TelecomManager object to save memory
1001             return mContext.getSystemService(TelecomManager.class);
1002         }
1003         return mTelecomManager;
1004     }
1005 
dump(PrintWriter pw, String prefix)1006     public void dump(PrintWriter pw, String prefix) {
1007         pw.println(prefix + "LockTaskController:");
1008         prefix = prefix + "  ";
1009         pw.println(prefix + "mLockTaskModeState=" + lockTaskModeToString());
1010         pw.println(prefix + "mLockTaskModeTasks=");
1011         for (int i = 0; i < mLockTaskModeTasks.size(); ++i) {
1012             pw.println(prefix + "  #" + i + " " + mLockTaskModeTasks.get(i));
1013         }
1014         pw.println(prefix + "mLockTaskPackages (userId:packages)=");
1015         for (int i = 0; i < mLockTaskPackages.size(); ++i) {
1016             pw.println(prefix + "  u" + mLockTaskPackages.keyAt(i)
1017                     + ":" + Arrays.toString(mLockTaskPackages.valueAt(i)));
1018         }
1019         pw.println();
1020     }
1021 
lockTaskModeToString()1022     private String lockTaskModeToString() {
1023         switch (mLockTaskModeState) {
1024             case LOCK_TASK_MODE_LOCKED:
1025                 return "LOCKED";
1026             case LOCK_TASK_MODE_PINNED:
1027                 return "PINNED";
1028             case LOCK_TASK_MODE_NONE:
1029                 return "NONE";
1030             default: return "unknown=" + mLockTaskModeState;
1031         }
1032     }
1033 
1034     /** Marker class for the token used to disable keyguard. */
1035     static class LockTaskToken extends Binder {
LockTaskToken()1036         private LockTaskToken() {
1037         }
1038     }
1039 }
1040