blob: 9c8ba5a15b9557db08601b3acca9ae7fcbab8c62 [file] [log] [blame]
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001/*
2 * Copyright (C) 2015 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
17package com.android.server.am;
18
19import static android.Manifest.permission.INTERACT_ACROSS_USERS;
20import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070021import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
22import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070023import static android.app.ActivityManager.USER_OP_IS_CURRENT;
24import static android.app.ActivityManager.USER_OP_SUCCESS;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000025import static android.content.Context.KEYGUARD_SERVICE;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070026import static android.os.Process.SYSTEM_UID;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060027
Fyodor Kupolov610acda2015-10-19 18:44:07 -070028import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
29import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
30import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070031import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
32import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
33import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
34import static com.android.server.am.ActivityManagerService.MY_PID;
Sudheer Shanka2c4522c2016-08-27 20:53:28 -070035import static com.android.server.am.ActivityManagerService.REPORT_LOCKED_BOOT_COMPLETE_MSG;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070036import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
37import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
38import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
39import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -070040import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070041import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060042import static com.android.server.am.UserState.STATE_BOOTING;
43import static com.android.server.am.UserState.STATE_RUNNING_LOCKED;
44import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED;
45import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070046
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070047import android.annotation.NonNull;
Tony Mak8c536f92016-03-21 12:20:41 +000048import android.annotation.UserIdInt;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070049import android.app.ActivityManager;
Fyodor Kupolov4ba91b92017-01-20 18:12:35 -080050import android.app.AppGlobals;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070051import android.app.AppOpsManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070052import android.app.Dialog;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070053import android.app.IStopUserCallback;
54import android.app.IUserSwitchObserver;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000055import android.app.KeyguardManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070056import android.content.Context;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070057import android.content.IIntentReceiver;
58import android.content.Intent;
Fyodor Kupolov4ba91b92017-01-20 18:12:35 -080059import android.content.pm.IPackageManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070060import android.content.pm.PackageManager;
61import android.content.pm.UserInfo;
62import android.os.BatteryStats;
63import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060064import android.os.Build;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070065import android.os.Bundle;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070066import android.os.Debug;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070067import android.os.Handler;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070068import android.os.IBinder;
Jeff Sharkey84a4c972016-04-18 15:36:39 -060069import android.os.IProgressListener;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070070import android.os.IRemoteCallback;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070071import android.os.IUserManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070072import android.os.Process;
73import android.os.RemoteCallbackList;
74import android.os.RemoteException;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070075import android.os.ServiceManager;
James Hawkins899608a2016-05-27 11:15:06 -070076import android.os.SystemClock;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070077import android.os.UserHandle;
78import android.os.UserManager;
Lenka Trochtova1ddda472016-02-12 10:42:12 +010079import android.os.UserManagerInternal;
Sudheer Shanka2250d562016-11-07 15:41:02 -080080import android.os.storage.IStorageManager;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080081import android.os.storage.StorageManager;
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -070082import android.util.ArraySet;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070083import android.util.IntArray;
Suprabh Shukla4fe508b2015-11-20 18:22:57 -080084import android.util.Pair;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070085import android.util.Slog;
86import android.util.SparseArray;
87import android.util.SparseIntArray;
88
89import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080090import com.android.internal.annotations.GuardedBy;
Fyodor Kupolovd6038db2016-06-22 16:53:19 -070091import com.android.internal.annotations.VisibleForTesting;
James Hawkins899608a2016-05-27 11:15:06 -070092import com.android.internal.logging.MetricsLogger;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070093import com.android.internal.util.ArrayUtils;
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -070094import com.android.internal.util.Preconditions;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000095import com.android.internal.widget.LockPatternUtils;
Lenka Trochtova1ddda472016-02-12 10:42:12 +010096import com.android.server.LocalServices;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070097import com.android.server.pm.UserManagerService;
Fyodor Kupolovd6038db2016-06-22 16:53:19 -070098import com.android.server.wm.WindowManagerService;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070099
100import java.io.PrintWriter;
101import java.util.ArrayList;
102import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700103import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700104import java.util.List;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600105import java.util.Objects;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700106import java.util.Set;
Fyodor Kupolov38641832016-06-28 17:37:09 -0700107import java.util.concurrent.atomic.AtomicInteger;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700108
109/**
110 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
111 */
112final class UserController {
113 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
Jeff Sharkeyfd241082016-04-19 15:58:24 -0600114
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700115 // Maximum number of users we allow to be running at a time.
116 static final int MAX_RUNNING_USERS = 3;
117
118 // Amount of time we wait for observers to handle a user switch before
119 // giving up on them and unfreezing the screen.
Fyodor Kupolov0e0986e2016-09-22 18:01:36 -0700120 static final int USER_SWITCH_TIMEOUT = 3 * 1000;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700121
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700122 private final Object mLock;
123 private final Injector mInjector;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700124 private final Handler mHandler;
125
Fyodor Kupolovdcb26bb2017-05-09 17:06:52 -0700126 // Holds the current foreground user's id. Use mLock when updating
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700127 @GuardedBy("mLock")
Fyodor Kupolovdcb26bb2017-05-09 17:06:52 -0700128 private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
129 // Holds the target user's id during a user switch. The value of mCurrentUserId will be updated
130 // once target user goes into the foreground. Use mLock when updating
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700131 @GuardedBy("mLock")
Fyodor Kupolovdcb26bb2017-05-09 17:06:52 -0700132 private volatile int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700133
134 /**
135 * Which users have been started, so are allowed to run code.
136 */
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700137 @GuardedBy("mLock")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700138 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800139
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700140 /**
141 * LRU list of history of current users. Most recently current is at the end.
142 */
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700143 @GuardedBy("mLock")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700144 private final ArrayList<Integer> mUserLru = new ArrayList<>();
145
146 /**
147 * Constant array of the users that are currently started.
148 */
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700149 @GuardedBy("mLock")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700150 private int[] mStartedUserArray = new int[] { 0 };
151
152 // If there are multiple profiles for the current user, their ids are here
153 // Currently only the primary user can have managed profiles
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700154 @GuardedBy("mLock")
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700155 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700156
157 /**
158 * Mapping from each known user ID to the profile group ID it is associated with.
159 */
160 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
161
162 /**
163 * Registered observers of the user switching mechanics.
164 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700165 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700166 = new RemoteCallbackList<>();
167
Evan Rosky3e0c25b2016-08-09 12:43:33 -0700168 boolean mUserSwitchUiEnabled = true;
Evan Rosky18396452016-07-27 15:19:37 -0700169
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700170 /**
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -0700171 * Currently active user switch callbacks.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700172 */
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700173 @GuardedBy("mLock")
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -0700174 private volatile ArraySet<String> mCurWaitingUserSwitchCallbacks;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700175
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700176 private volatile UserManagerService mUserManager;
177
Clara Bayarria1771112015-12-18 16:29:18 +0000178 private final LockPatternUtils mLockPatternUtils;
179
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700180 UserController(ActivityManagerService service) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700181 this(new Injector(service));
182 }
183
184 @VisibleForTesting
185 UserController(Injector injector) {
186 mInjector = injector;
187 mLock = injector.getLock();
188 mHandler = injector.getHandler();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700189 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800190 final UserState uss = new UserState(UserHandle.SYSTEM);
191 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700192 mUserLru.add(UserHandle.USER_SYSTEM);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700193 mLockPatternUtils = mInjector.getLockPatternUtils();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700194 updateStartedUserArrayLocked();
195 }
196
197 void finishUserSwitch(UserState uss) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700198 synchronized (mLock) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700199 finishUserBoot(uss);
200
201 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700202 stopRunningUsersLocked(MAX_RUNNING_USERS);
203 }
204 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700205
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700206 void stopRunningUsersLocked(int maxRunningUsers) {
207 int num = mUserLru.size();
208 int i = 0;
209 while (num > maxRunningUsers && i < mUserLru.size()) {
210 Integer oldUserId = mUserLru.get(i);
211 UserState oldUss = mStartedUsers.get(oldUserId);
212 if (oldUss == null) {
213 // Shouldn't happen, but be sane if it does.
214 mUserLru.remove(i);
215 num--;
216 continue;
217 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700218 if (oldUss.state == UserState.STATE_STOPPING
219 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700220 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700221 num--;
222 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700223 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700224 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700225 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
226 // Owner/System user and current user can't be stopped. We count it as running
227 // when it is not a pure system user.
228 if (UserInfo.isSystemOnly(oldUserId)) {
229 num--;
230 }
231 i++;
232 continue;
233 }
234 // This is a user to be stopped.
235 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
236 num--;
237 }
238 num--;
239 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700240 }
241 }
242
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800243 private void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700244 finishUserBoot(uss, null);
245 }
246
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800247 private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700248 final int userId = uss.mHandle.getIdentifier();
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -0700249
Fyodor Kupolovc94c2492016-04-20 17:44:00 -0700250 Slog.d(TAG, "Finishing user boot " + userId);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700251 synchronized (mLock) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700252 // Bail if we ended up with a stale user
253 if (mStartedUsers.get(userId) != uss) return;
254
255 // We always walk through all the user lifecycle states to send
256 // consistent developer events. We step into RUNNING_LOCKED here,
257 // but we might immediately step into RUNNING below if the user
258 // storage is already unlocked.
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600259 if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700260 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
Fyodor Kupolov4ba91b92017-01-20 18:12:35 -0800261 // Do not report secondary users, runtime restarts or first boot/upgrade
262 if (userId == UserHandle.USER_SYSTEM
263 && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
Fyodor Kupolov1d87e402017-01-10 18:34:10 -0800264 int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000);
265 MetricsLogger.histogram(mInjector.getContext(),
266 "framework_locked_boot_completed", uptimeSeconds);
Fyodor Kupolov24e12dc2017-01-17 12:20:36 -0800267 final int MAX_UPTIME_SECONDS = 120;
268 if (uptimeSeconds > MAX_UPTIME_SECONDS) {
269 Slog.wtf("SystemServerTiming",
270 "finishUserBoot took too long. uptimeSeconds=" + uptimeSeconds);
271 }
Fyodor Kupolov1d87e402017-01-10 18:34:10 -0800272 }
James Hawkins899608a2016-05-27 11:15:06 -0700273
Sudheer Shanka2c4522c2016-08-27 20:53:28 -0700274 mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG,
275 userId, 0));
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700276 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700277 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeya242f822015-12-17 15:38:20 -0700278 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
279 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700280 mInjector.broadcastIntentLocked(intent, null, resultTo, 0, null, null,
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700281 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
282 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
283 }
284
Jeff Sharkey7661a312016-04-07 12:39:57 -0600285 // We need to delay unlocking managed profiles until the parent user
286 // is also unlocked.
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700287 if (mInjector.getUserManager().isManagedProfile(userId)) {
288 final UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
Jeff Sharkey7661a312016-04-07 12:39:57 -0600289 if (parent != null
290 && isUserRunningLocked(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
291 Slog.d(TAG, "User " + userId + " (parent " + parent.id
292 + "): attempting unlock because parent is unlocked");
293 maybeUnlockUser(userId);
294 } else {
Fyodor Kupolovc94c2492016-04-20 17:44:00 -0700295 String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
296 Slog.d(TAG, "User " + userId + " (parent " + parentId
Jeff Sharkey7661a312016-04-07 12:39:57 -0600297 + "): delaying unlock because parent is locked");
298 }
Jeff Sharkey5dab7132016-04-07 01:20:58 -0600299 } else {
300 maybeUnlockUser(userId);
301 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700302 }
303 }
304
305 /**
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600306 * Step from {@link UserState#STATE_RUNNING_LOCKED} to
307 * {@link UserState#STATE_RUNNING_UNLOCKING}.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700308 */
Jeff Sharkey84a4c972016-04-18 15:36:39 -0600309 private void finishUserUnlocking(final UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700310 final int userId = uss.mHandle.getIdentifier();
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +0200311 boolean proceedWithUnlock = false;
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700312 synchronized (mLock) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700313 // Bail if we ended up with a stale user
314 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
315
316 // Only keep marching forward if user is actually unlocked
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600317 if (!StorageManager.isUserKeyUnlocked(userId)) return;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700318
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600319 if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700320 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +0200321 proceedWithUnlock = true;
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600322 }
323 }
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +0200324
325 if (proceedWithUnlock) {
326 uss.mUnlockProgress.start();
327
328 // Prepare app storage before we go any further
329 uss.mUnlockProgress.setProgress(5,
Jorim Jaggi526694e2016-08-03 17:15:23 +0200330 mInjector.getContext().getString(R.string.android_start_title));
331 mInjector.getUserManager().onBeforeUnlockUser(userId);
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +0200332 uss.mUnlockProgress.setProgress(20);
333
334 // Dispatch unlocked to system services; when fully dispatched,
335 // that calls through to the next "unlocked" phase
336 mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss)
337 .sendToTarget();
338 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600339 }
340
341 /**
342 * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
343 * {@link UserState#STATE_RUNNING_UNLOCKED}.
344 */
345 void finishUserUnlocked(final UserState uss) {
346 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700347 synchronized (mLock) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600348 // Bail if we ended up with a stale user
349 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
350
351 // Only keep marching forward if user is actually unlocked
352 if (!StorageManager.isUserKeyUnlocked(userId)) return;
353
354 if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700355 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600356 uss.mUnlockProgress.finish();
Jeff Sharkey083807d2016-04-06 14:07:09 -0600357
Jeff Sharkey155e5d62016-04-11 12:13:06 -0600358 // Dispatch unlocked to external apps
359 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
360 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
361 unlockedIntent.addFlags(
362 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700363 mInjector.broadcastIntentLocked(unlockedIntent, null, null, 0, null,
Jeff Sharkey155e5d62016-04-11 12:13:06 -0600364 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
365 userId);
366
367 if (getUserInfo(userId).isManagedProfile()) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700368 UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
Jeff Sharkey155e5d62016-04-11 12:13:06 -0600369 if (parent != null) {
370 final Intent profileUnlockedIntent = new Intent(
371 Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
372 profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
373 profileUnlockedIntent.addFlags(
374 Intent.FLAG_RECEIVER_REGISTERED_ONLY
375 | Intent.FLAG_RECEIVER_FOREGROUND);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700376 mInjector.broadcastIntentLocked(profileUnlockedIntent,
Jeff Sharkey155e5d62016-04-11 12:13:06 -0600377 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
378 null, false, false, MY_PID, SYSTEM_UID,
379 parent.id);
380 }
381 }
382
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600383 // Send PRE_BOOT broadcasts if user fingerprint changed; we
384 // purposefully block sending BOOT_COMPLETED until after all
385 // PRE_BOOT receivers are finished to avoid ANR'ing apps
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600386 final UserInfo info = getUserInfo(userId);
387 if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
Jeff Sharkey24d94912016-07-07 12:33:48 -0600388 // Suppress double notifications for managed profiles that
Jeff Sharkeyba066572016-07-18 10:11:36 -0600389 // were unlocked automatically as part of their parent user
390 // being unlocked.
391 final boolean quiet;
392 if (info.isManagedProfile()) {
393 quiet = !uss.tokenProvided
394 || !mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
395 } else {
396 quiet = false;
397 }
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700398 mInjector.sendPreBootBroadcast(userId, quiet,
399 () -> finishUserUnlockedCompleted(uss));
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600400 } else {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600401 finishUserUnlockedCompleted(uss);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600402 }
403 }
404 }
405 }
406
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600407 private void finishUserUnlockedCompleted(UserState uss) {
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600408 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700409 synchronized (mLock) {
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600410 // Bail if we ended up with a stale user
411 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
Fyodor Kupolovc94c2492016-04-20 17:44:00 -0700412 final UserInfo userInfo = getUserInfo(userId);
413 if (userInfo == null) {
414 return;
415 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600416
417 // Only keep marching forward if user is actually unlocked
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600418 if (!StorageManager.isUserKeyUnlocked(userId)) return;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600419
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600420 // Remember that we logged in
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700421 mInjector.getUserManager().onUserLoggedIn(userId);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600422
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600423 if (!userInfo.isInitialized()) {
424 if (userId != UserHandle.USER_SYSTEM) {
425 Slog.d(TAG, "Initializing user #" + userId);
426 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Christopher Tate42a386b2016-11-07 12:21:21 -0800427 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
428 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700429 mInjector.broadcastIntentLocked(intent, null,
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600430 new IIntentReceiver.Stub() {
431 @Override
432 public void performReceive(Intent intent, int resultCode,
433 String data, Bundle extras, boolean ordered,
434 boolean sticky, int sendingUser) {
435 // Note: performReceive is called with mService lock held
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700436 mInjector.getUserManager().makeInitialized(userInfo.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600437 }
438 }, 0, null, null, null, AppOpsManager.OP_NONE,
439 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolovc94c2492016-04-20 17:44:00 -0700440 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700441 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600442
Fyodor Kupolov5ddcca72017-04-28 17:38:10 -0700443 Slog.i(TAG, "Sending BOOT_COMPLETE user #" + userId);
Fyodor Kupolov4ba91b92017-01-20 18:12:35 -0800444 // Do not report secondary users, runtime restarts or first boot/upgrade
445 if (userId == UserHandle.USER_SYSTEM
446 && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
Fyodor Kupolov1d87e402017-01-10 18:34:10 -0800447 int uptimeSeconds = (int) (SystemClock.elapsedRealtime() / 1000);
448 MetricsLogger.histogram(mInjector.getContext(), "framework_boot_completed",
449 uptimeSeconds);
450 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600451 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
452 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
453 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
454 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Fyodor Kupolov5ddcca72017-04-28 17:38:10 -0700455 mInjector.broadcastIntentLocked(bootIntent, null, new IIntentReceiver.Stub() {
456 @Override
457 public void performReceive(Intent intent, int resultCode, String data,
458 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
459 throws RemoteException {
460 Slog.i(UserController.TAG, "Finished processing BOOT_COMPLETED for u" + userId);
461 }
462 }, 0, null, null,
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600463 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
464 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700465 }
466 }
467
Andrew Scull85a63bc2016-10-24 13:47:47 +0100468 int restartUser(final int userId, final boolean foreground) {
469 return stopUser(userId, /* force */ true, new IStopUserCallback.Stub() {
470 @Override
471 public void userStopped(final int userId) {
472 // Post to the same handler that this callback is called from to ensure the user
473 // cleanup is complete before restarting.
474 mHandler.post(() -> startUser(userId, foreground));
475 }
476 @Override
477 public void userStopAborted(final int userId) {}
478 });
479 }
480
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700481 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700482 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700483 != PackageManager.PERMISSION_GRANTED) {
484 String msg = "Permission Denial: switchUser() from pid="
485 + Binder.getCallingPid()
486 + ", uid=" + Binder.getCallingUid()
487 + " requires " + INTERACT_ACROSS_USERS_FULL;
488 Slog.w(TAG, msg);
489 throw new SecurityException(msg);
490 }
491 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
492 throw new IllegalArgumentException("Can't stop system user " + userId);
493 }
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700494 mInjector.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
495 synchronized (mLock) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700496 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700497 }
498 }
499
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700500 /**
501 * Stops the user along with its related users. The method calls
502 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
503 */
504 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
505 if (userId == UserHandle.USER_SYSTEM) {
506 return USER_OP_ERROR_IS_SYSTEM;
507 }
508 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700509 return USER_OP_IS_CURRENT;
510 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700511 int[] usersToStop = getUsersToStopLocked(userId);
512 // If one of related users is system or current, no related users should be stopped
513 for (int i = 0; i < usersToStop.length; i++) {
514 int relatedUserId = usersToStop[i];
515 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
516 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
517 + relatedUserId);
518 // We still need to stop the requested user if it's a force stop.
519 if (force) {
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800520 Slog.i(TAG,
521 "Force stop user " + userId + ". Related users will not be stopped");
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700522 stopSingleUserLocked(userId, callback);
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800523 return USER_OP_SUCCESS;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700524 }
525 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
526 }
527 }
528 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
529 for (int userIdToStop : usersToStop) {
530 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
531 }
532 return USER_OP_SUCCESS;
533 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700534
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700535 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
536 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700537 final UserState uss = mStartedUsers.get(userId);
538 if (uss == null) {
539 // User is not started, nothing to do... but we do need to
540 // callback if requested.
541 if (callback != null) {
542 mHandler.post(new Runnable() {
543 @Override
544 public void run() {
545 try {
546 callback.userStopped(userId);
547 } catch (RemoteException e) {
548 }
549 }
550 });
551 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700552 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700553 }
554
555 if (callback != null) {
556 uss.mStopCallbacks.add(callback);
557 }
558
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700559 if (uss.state != UserState.STATE_STOPPING
560 && uss.state != UserState.STATE_SHUTDOWN) {
561 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700562 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700563 updateStartedUserArrayLocked();
564
565 long ident = Binder.clearCallingIdentity();
566 try {
567 // We are going to broadcast ACTION_USER_STOPPING and then
568 // once that is done send a final ACTION_SHUTDOWN and then
569 // stop the user.
570 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
571 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
572 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
573 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700574 // This is the result receiver for the initial stopping broadcast.
575 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
576 @Override
577 public void performReceive(Intent intent, int resultCode, String data,
578 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Amith Yamasani98c05562016-03-30 13:15:26 -0700579 mHandler.post(new Runnable() {
580 @Override
581 public void run() {
582 finishUserStopping(userId, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700583 }
Amith Yamasani98c05562016-03-30 13:15:26 -0700584 });
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700585 }
586 };
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700587 // Clear broadcast queue for the user to avoid delivering stale broadcasts
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700588 mInjector.clearBroadcastQueueForUserLocked(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700589 // Kick things off.
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700590 mInjector.broadcastIntentLocked(stoppingIntent,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700591 null, stoppingReceiver, 0, null, null,
592 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700593 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700594 } finally {
595 Binder.restoreCallingIdentity(ident);
596 }
597 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700598 }
599
Amith Yamasani98c05562016-03-30 13:15:26 -0700600 void finishUserStopping(final int userId, final UserState uss) {
601 // On to the next.
602 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
Christopher Tate98946b92017-06-13 12:11:09 -0700603 shutdownIntent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Amith Yamasani98c05562016-03-30 13:15:26 -0700604 // This is the result receiver for the final shutdown broadcast.
605 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
606 @Override
607 public void performReceive(Intent intent, int resultCode, String data,
608 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
609 mHandler.post(new Runnable() {
610 @Override
611 public void run() {
612 finishUserStopped(uss);
613 }
614 });
615 }
616 };
617
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700618 synchronized (mLock) {
Amith Yamasani98c05562016-03-30 13:15:26 -0700619 if (uss.state != UserState.STATE_STOPPING) {
620 // Whoops, we are being started back up. Abort, abort!
621 return;
622 }
623 uss.setState(UserState.STATE_SHUTDOWN);
624 }
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700625 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
Amith Yamasani98c05562016-03-30 13:15:26 -0700626
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700627 mInjector.batteryStatsServiceNoteEvent(
Amith Yamasani98c05562016-03-30 13:15:26 -0700628 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
629 Integer.toString(userId), userId);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700630 mInjector.systemServiceManagerStopUser(userId);
Amith Yamasani98c05562016-03-30 13:15:26 -0700631
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700632 synchronized (mLock) {
633 mInjector.broadcastIntentLocked(shutdownIntent,
Amith Yamasani98c05562016-03-30 13:15:26 -0700634 null, shutdownReceiver, 0, null, null, null,
635 AppOpsManager.OP_NONE,
636 null, true, false, MY_PID, SYSTEM_UID, userId);
637 }
638 }
639
640 void finishUserStopped(UserState uss) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700641 final int userId = uss.mHandle.getIdentifier();
642 boolean stopped;
643 ArrayList<IStopUserCallback> callbacks;
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700644 synchronized (mLock) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700645 callbacks = new ArrayList<>(uss.mStopCallbacks);
646 if (mStartedUsers.get(userId) != uss) {
647 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700648 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700649 stopped = false;
650 } else {
651 stopped = true;
652 // User can no longer run.
653 mStartedUsers.remove(userId);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700654 mInjector.getUserManagerInternal().removeUserState(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700655 mUserLru.remove(Integer.valueOf(userId));
656 updateStartedUserArrayLocked();
657
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700658 mInjector.activityManagerOnUserStopped(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700659 // Clean up all state and processes associated with the user.
660 // Kill all the processes for the user.
661 forceStopUserLocked(userId, "finish user");
662 }
663 }
664
665 for (int i = 0; i < callbacks.size(); i++) {
666 try {
667 if (stopped) callbacks.get(i).userStopped(userId);
668 else callbacks.get(i).userStopAborted(userId);
669 } catch (RemoteException e) {
670 }
671 }
672
673 if (stopped) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700674 mInjector.systemServiceManagerCleanupUser(userId);
675 synchronized (mLock) {
Tony Mak5c2cf032017-04-03 18:38:23 +0100676 mInjector.getActivityStackSupervisor().removeUserLocked(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700677 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100678 // Remove the user if it is ephemeral.
679 if (getUserInfo(userId).isEphemeral()) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700680 mInjector.getUserManager().removeUser(userId);
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100681 }
Pavel Grafov0502a4c2017-07-27 17:27:35 +0100682 // Evict the user's credential encryption key.
683 try {
684 getStorageManager().lockUserKey(userId);
685 } catch (RemoteException re) {
686 throw re.rethrowAsRuntimeException();
687 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700688 }
689 }
690
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700691 /**
692 * Determines the list of users that should be stopped together with the specified
693 * {@code userId}. The returned list includes {@code userId}.
694 */
695 private @NonNull int[] getUsersToStopLocked(int userId) {
696 int startedUsersSize = mStartedUsers.size();
697 IntArray userIds = new IntArray();
698 userIds.add(userId);
699 synchronized (mUserProfileGroupIdsSelfLocked) {
700 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
701 UserInfo.NO_PROFILE_GROUP_ID);
702 for (int i = 0; i < startedUsersSize; i++) {
703 UserState uss = mStartedUsers.valueAt(i);
704 int startedUserId = uss.mHandle.getIdentifier();
705 // Skip unrelated users (profileGroupId mismatch)
706 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
707 UserInfo.NO_PROFILE_GROUP_ID);
708 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
709 && (userGroupId == startedUserGroupId);
710 // userId has already been added
711 boolean sameUserId = startedUserId == userId;
712 if (!sameGroup || sameUserId) {
713 continue;
714 }
715 userIds.add(startedUserId);
716 }
717 }
718 return userIds.toArray();
719 }
720
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700721 private void forceStopUserLocked(int userId, String reason) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700722 mInjector.activityManagerForceStopPackageLocked(userId, reason);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700723 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
724 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
725 | Intent.FLAG_RECEIVER_FOREGROUND);
726 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700727 mInjector.broadcastIntentLocked(intent,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700728 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700729 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700730 }
731
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700732 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100733 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700734 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100735 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700736 synchronized (mLock) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700737 final int num = mUserLru.size();
738 for (int i = 0; i < num; i++) {
739 Integer oldUserId = mUserLru.get(i);
740 UserState oldUss = mStartedUsers.get(oldUserId);
741 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700742 || oldUss.state == UserState.STATE_STOPPING
743 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700744 continue;
745 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700746 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtova1ddda472016-02-12 10:42:12 +0100747 if (userInfo.isEphemeral()) {
748 LocalServices.getService(UserManagerInternal.class)
749 .onEphemeralUserStop(oldUserId);
750 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100751 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700752 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700753 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700754 break;
755 }
756 }
757 }
758 }
759
760 void startProfilesLocked() {
761 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700762 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700763 mCurrentUserId, false /* enabledOnly */);
764 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
765 for (UserInfo user : profiles) {
766 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
Rubin Xuf13c9802016-01-21 18:06:00 +0000767 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700768 profilesToStart.add(user);
769 }
770 }
771 final int profilesToStartSize = profilesToStart.size();
772 int i = 0;
773 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
774 startUser(profilesToStart.get(i).id, /* foreground= */ false);
775 }
776 if (i < profilesToStartSize) {
777 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
778 }
779 }
780
Sudheer Shanka2250d562016-11-07 15:41:02 -0800781 private IStorageManager getStorageManager() {
782 return IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700783 }
784
Fyodor Kupolovc94c2492016-04-20 17:44:00 -0700785 /**
786 * Start user, if its not already running.
787 * <p>The user will be brought to the foreground, if {@code foreground} parameter is set.
788 * When starting the user, multiple intents will be broadcast in the following order:</p>
789 * <ul>
790 * <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
791 * <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
792 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
793 * <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
794 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
795 * <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
796 * Sent only if {@code foreground} parameter is true
797 * <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
798 * of the new fg user
799 * <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
800 * the new user
801 * <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
802 * <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
803 * new user. Sent only when the user is booting after a system update.
804 * <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
805 * new user. Sent only the first time a user is starting.
806 * <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
807 * user. Indicates that the user has finished booting.
808 * </ul>
809 *
810 * @param userId ID of the user to start
811 * @param foreground true if user should be brought to the foreground
812 * @return true if the user has been successfully started
813 */
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700814 boolean startUser(final int userId, final boolean foreground) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700815 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700816 != PackageManager.PERMISSION_GRANTED) {
817 String msg = "Permission Denial: switchUser() from pid="
818 + Binder.getCallingPid()
819 + ", uid=" + Binder.getCallingUid()
820 + " requires " + INTERACT_ACROSS_USERS_FULL;
821 Slog.w(TAG, msg);
822 throw new SecurityException(msg);
823 }
824
Fyodor Kupolovc94c2492016-04-20 17:44:00 -0700825 Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700826
827 final long ident = Binder.clearCallingIdentity();
828 try {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700829 synchronized (mLock) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700830 final int oldUserId = mCurrentUserId;
831 if (oldUserId == userId) {
832 return true;
833 }
834
Tony Mak5c2cf032017-04-03 18:38:23 +0100835 if (foreground) {
836 mInjector.getActivityStackSupervisor().setLockTaskModeLocked(
837 null, ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
838 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700839
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700840 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700841 if (userInfo == null) {
842 Slog.w(TAG, "No user info for user #" + userId);
843 return false;
844 }
845 if (foreground && userInfo.isManagedProfile()) {
846 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
847 return false;
848 }
849
Evan Rosky18396452016-07-27 15:19:37 -0700850 if (foreground && mUserSwitchUiEnabled) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700851 mInjector.getWindowManager().startFreezingScreen(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700852 R.anim.screen_user_exit, R.anim.screen_user_enter);
853 }
854
855 boolean needStart = false;
856
857 // If the user we are switching to is not currently started, then
858 // we need to start it now.
859 if (mStartedUsers.get(userId) == null) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000860 UserState userState = new UserState(UserHandle.of(userId));
861 mStartedUsers.put(userId, userState);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700862 mInjector.getUserManagerInternal().setUserState(userId, userState.state);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700863 updateStartedUserArrayLocked();
864 needStart = true;
865 }
866
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800867 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700868 final Integer userIdInt = userId;
869 mUserLru.remove(userIdInt);
870 mUserLru.add(userIdInt);
871
872 if (foreground) {
873 mCurrentUserId = userId;
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700874 mInjector.updateUserConfigurationLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700875 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
876 updateCurrentProfileIdsLocked();
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700877 mInjector.getWindowManager().setCurrentUser(userId, mCurrentProfileIds);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700878 // Once the internal notion of the active user has switched, we lock the device
879 // with the option to show the user switcher on the keyguard.
Evan Rosky18396452016-07-27 15:19:37 -0700880 if (mUserSwitchUiEnabled) {
881 mInjector.getWindowManager().setSwitchingUser(true);
882 mInjector.getWindowManager().lockNow(null);
883 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700884 } else {
885 final Integer currentUserIdInt = mCurrentUserId;
886 updateCurrentProfileIdsLocked();
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700887 mInjector.getWindowManager().setCurrentProfileIds(mCurrentProfileIds);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700888 mUserLru.remove(currentUserIdInt);
889 mUserLru.add(currentUserIdInt);
890 }
891
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700892 // Make sure user is in the started state. If it is currently
893 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700894 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700895 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
896 // so we can just fairly silently bring the user back from
897 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700898 uss.setState(uss.lastState);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700899 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700900 updateStartedUserArrayLocked();
901 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700902 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700903 // This means ACTION_SHUTDOWN has been sent, so we will
904 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700905 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700906 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700907 updateStartedUserArrayLocked();
908 needStart = true;
909 }
910
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700911 if (uss.state == UserState.STATE_BOOTING) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700912 // Give user manager a chance to propagate user restrictions
913 // to other services and prepare app storage
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700914 mInjector.getUserManager().onBeforeStartUser(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800915
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700916 // Booting up a new user, need to tell system services about it.
917 // Note that this is on the same handler as scheduling of broadcasts,
918 // which is important because it needs to go first.
919 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
920 }
921
922 if (foreground) {
923 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
924 oldUserId));
925 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
926 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
927 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
928 oldUserId, userId, uss));
929 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
930 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
931 }
932
933 if (needStart) {
934 // Send USER_STARTED broadcast
935 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
936 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
937 | Intent.FLAG_RECEIVER_FOREGROUND);
938 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700939 mInjector.broadcastIntentLocked(intent,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700940 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700941 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700942 }
943
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700944 if (foreground) {
Fyodor Kupolovc94c2492016-04-20 17:44:00 -0700945 moveUserToForegroundLocked(uss, oldUserId, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700946 } else {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700947 finishUserBoot(uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700948 }
949
950 if (needStart) {
951 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
952 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
953 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700954 mInjector.broadcastIntentLocked(intent,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700955 null, new IIntentReceiver.Stub() {
956 @Override
957 public void performReceive(Intent intent, int resultCode,
958 String data, Bundle extras, boolean ordered, boolean sticky,
959 int sendingUser) throws RemoteException {
960 }
961 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700962 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
963 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700964 }
965 }
966 } finally {
967 Binder.restoreCallingIdentity(ident);
968 }
969
970 return true;
971 }
972
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700973 /**
974 * Start user, if its not already running, and bring it to foreground.
975 */
Evan Rosky18396452016-07-27 15:19:37 -0700976 void startUserInForeground(final int targetUserId) {
977 boolean success = startUser(targetUserId, /* foreground */ true);
978 if (!success) {
979 mInjector.getWindowManager().setSwitchingUser(false);
980 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700981 }
982
Jeff Sharkey84a4c972016-04-18 15:36:39 -0600983 boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -0700984 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
Jeff Sharkeyba512352015-11-12 20:17:45 -0800985 != PackageManager.PERMISSION_GRANTED) {
986 String msg = "Permission Denial: unlockUser() from pid="
987 + Binder.getCallingPid()
988 + ", uid=" + Binder.getCallingUid()
989 + " requires " + INTERACT_ACROSS_USERS_FULL;
990 Slog.w(TAG, msg);
991 throw new SecurityException(msg);
992 }
993
Jeff Sharkey8924e872015-11-30 12:52:10 -0700994 final long binderToken = Binder.clearCallingIdentity();
995 try {
Jeff Sharkey84a4c972016-04-18 15:36:39 -0600996 return unlockUserCleared(userId, token, secret, listener);
Jeff Sharkey8924e872015-11-30 12:52:10 -0700997 } finally {
998 Binder.restoreCallingIdentity(binderToken);
999 }
1000 }
1001
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001002 /**
1003 * Attempt to unlock user without a credential token. This typically
1004 * succeeds when the device doesn't have credential-encrypted storage, or
1005 * when the the credential-encrypted storage isn't tied to a user-provided
1006 * PIN or pattern.
1007 */
1008 boolean maybeUnlockUser(final int userId) {
1009 // Try unlocking storage using empty token
Jeff Sharkey84a4c972016-04-18 15:36:39 -06001010 return unlockUserCleared(userId, null, null, null);
1011 }
1012
1013 private static void notifyFinished(int userId, IProgressListener listener) {
1014 if (listener == null) return;
1015 try {
1016 listener.onFinished(userId, null);
1017 } catch (RemoteException ignored) {
1018 }
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001019 }
1020
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001021 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
Jeff Sharkey84a4c972016-04-18 15:36:39 -06001022 IProgressListener listener) {
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +02001023 UserState uss;
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001024 synchronized (mLock) {
Ricky Wai4266fee2016-05-23 15:33:04 +01001025 // TODO Move this block outside of synchronized if it causes lock contention
1026 if (!StorageManager.isUserKeyUnlocked(userId)) {
1027 final UserInfo userInfo = getUserInfo(userId);
Sudheer Shanka2250d562016-11-07 15:41:02 -08001028 final IStorageManager storageManager = getStorageManager();
Ricky Wai4266fee2016-05-23 15:33:04 +01001029 try {
1030 // We always want to unlock user storage, even user is not started yet
Sudheer Shanka2250d562016-11-07 15:41:02 -08001031 storageManager.unlockUserKey(userId, userInfo.serialNumber, token, secret);
Ricky Wai4266fee2016-05-23 15:33:04 +01001032 } catch (RemoteException | RuntimeException e) {
1033 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
1034 }
1035 }
Jeff Sharkey84a4c972016-04-18 15:36:39 -06001036 // Bail if user isn't actually running, otherwise register the given
1037 // listener to watch for unlock progress
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +02001038 uss = mStartedUsers.get(userId);
Ricky Waif6ef8282016-04-14 10:00:22 +01001039 if (uss == null) {
Jeff Sharkey84a4c972016-04-18 15:36:39 -06001040 notifyFinished(userId, listener);
Ricky Waif6ef8282016-04-14 10:00:22 +01001041 return false;
Jeff Sharkey84a4c972016-04-18 15:36:39 -06001042 } else {
1043 uss.mUnlockProgress.addListener(listener);
Jeff Sharkey24d94912016-07-07 12:33:48 -06001044 uss.tokenProvided = (token != null);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001045 }
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +02001046 }
Jeff Sharkey8924e872015-11-30 12:52:10 -07001047
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +02001048 finishUserUnlocking(uss);
1049
1050 final ArraySet<Integer> childProfilesToUnlock = new ArraySet<>();
Jorim Jaggi526694e2016-08-03 17:15:23 +02001051 synchronized (mLock) {
Jeff Sharkeyba512352015-11-12 20:17:45 -08001052
Jeff Sharkey7661a312016-04-07 12:39:57 -06001053 // We just unlocked a user, so let's now attempt to unlock any
1054 // managed profiles under that user.
Jeff Sharkey5dab7132016-04-07 01:20:58 -06001055 for (int i = 0; i < mStartedUsers.size(); i++) {
1056 final int testUserId = mStartedUsers.keyAt(i);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001057 final UserInfo parent = mInjector.getUserManager().getProfileParent(testUserId);
Jeff Sharkey5dab7132016-04-07 01:20:58 -06001058 if (parent != null && parent.id == userId && testUserId != userId) {
Jeff Sharkey7661a312016-04-07 12:39:57 -06001059 Slog.d(TAG, "User " + testUserId + " (parent " + parent.id
1060 + "): attempting unlock because parent was just unlocked");
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +02001061 childProfilesToUnlock.add(testUserId);
Jeff Sharkey5dab7132016-04-07 01:20:58 -06001062 }
1063 }
1064 }
1065
Jorim Jaggi6f4d7b32016-08-01 14:31:02 +02001066 final int size = childProfilesToUnlock.size();
1067 for (int i = 0; i < size; i++) {
1068 maybeUnlockUser(childProfilesToUnlock.valueAt(i));
1069 }
1070
Jeff Sharkeyba512352015-11-12 20:17:45 -08001071 return true;
1072 }
1073
Suprabh Shukla4fe508b2015-11-20 18:22:57 -08001074 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001075 // The dialog will show and then initiate the user switch by calling startUserInForeground
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001076 mInjector.showUserSwitchingDialog(fromToUserPair.first, fromToUserPair.second);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001077 }
1078
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001079 void dispatchForegroundProfileChanged(int userId) {
1080 final int observerCount = mUserSwitchObservers.beginBroadcast();
1081 for (int i = 0; i < observerCount; i++) {
1082 try {
1083 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
1084 } catch (RemoteException e) {
1085 // Ignore
1086 }
1087 }
1088 mUserSwitchObservers.finishBroadcast();
1089 }
1090
1091 /** Called on handler thread */
1092 void dispatchUserSwitchComplete(int userId) {
Evan Rosky18396452016-07-27 15:19:37 -07001093 mInjector.getWindowManager().setSwitchingUser(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001094 final int observerCount = mUserSwitchObservers.beginBroadcast();
1095 for (int i = 0; i < observerCount; i++) {
1096 try {
1097 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
1098 } catch (RemoteException e) {
1099 }
1100 }
1101 mUserSwitchObservers.finishBroadcast();
1102 }
1103
Sudheer Shanka2c4522c2016-08-27 20:53:28 -07001104 void dispatchLockedBootComplete(int userId) {
1105 final int observerCount = mUserSwitchObservers.beginBroadcast();
1106 for (int i = 0; i < observerCount; i++) {
1107 try {
1108 mUserSwitchObservers.getBroadcastItem(i).onLockedBootComplete(userId);
1109 } catch (RemoteException e) {
1110 // Ignore
1111 }
1112 }
1113 mUserSwitchObservers.finishBroadcast();
1114 }
1115
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001116 private void stopBackgroundUsersIfEnforced(int oldUserId) {
1117 // Never stop system user
1118 if (oldUserId == UserHandle.USER_SYSTEM) {
1119 return;
1120 }
1121 // For now, only check for user restriction. Additional checks can be added here
1122 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
1123 oldUserId);
1124 if (!disallowRunInBg) {
1125 return;
1126 }
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001127 synchronized (mLock) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001128 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
1129 + " and related users");
1130 stopUsersLocked(oldUserId, false, null);
1131 }
1132 }
1133
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001134 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001135 synchronized (mLock) {
1136 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001137 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1138 }
1139 }
1140
Fyodor Kupolovc94c2492016-04-20 17:44:00 -07001141 void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
1142 Slog.d(TAG, "Dispatch onUserSwitching oldUser #" + oldUserId + " newUser #" + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001143 final int observerCount = mUserSwitchObservers.beginBroadcast();
1144 if (observerCount > 0) {
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -07001145 final ArraySet<String> curWaitingUserSwitchCallbacks = new ArraySet<>();
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001146 synchronized (mLock) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001147 uss.switching = true;
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -07001148 mCurWaitingUserSwitchCallbacks = curWaitingUserSwitchCallbacks;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001149 }
Fyodor Kupolov38641832016-06-28 17:37:09 -07001150 final AtomicInteger waitingCallbacksCount = new AtomicInteger(observerCount);
Fyodor Kupolov0e0986e2016-09-22 18:01:36 -07001151 final long dispatchStartedTime = SystemClock.elapsedRealtime();
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001152 for (int i = 0; i < observerCount; i++) {
1153 try {
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -07001154 // Prepend with unique prefix to guarantee that keys are unique
1155 final String name = "#" + i + " " + mUserSwitchObservers.getBroadcastCookie(i);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001156 synchronized (mLock) {
Fyodor Kupolov599d43b2016-06-24 13:46:18 -07001157 curWaitingUserSwitchCallbacks.add(name);
1158 }
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -07001159 final IRemoteCallback callback = new IRemoteCallback.Stub() {
1160 @Override
1161 public void sendResult(Bundle data) throws RemoteException {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001162 synchronized (mLock) {
Fyodor Kupolov0e0986e2016-09-22 18:01:36 -07001163 long delay = SystemClock.elapsedRealtime() - dispatchStartedTime;
1164 if (delay > USER_SWITCH_TIMEOUT) {
1165 Slog.wtf(TAG, "User switch timeout: observer " + name
1166 + " sent result after " + delay + " ms");
1167 }
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -07001168 // Early return if this session is no longer valid
1169 if (curWaitingUserSwitchCallbacks
1170 != mCurWaitingUserSwitchCallbacks) {
1171 return;
1172 }
1173 curWaitingUserSwitchCallbacks.remove(name);
1174 // Continue switching if all callbacks have been notified
Fyodor Kupolov38641832016-06-28 17:37:09 -07001175 if (waitingCallbacksCount.decrementAndGet() == 0) {
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -07001176 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1177 }
1178 }
1179 }
1180 };
1181 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(newUserId, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001182 } catch (RemoteException e) {
1183 }
1184 }
1185 } else {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001186 synchronized (mLock) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001187 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1188 }
1189 }
1190 mUserSwitchObservers.finishBroadcast();
1191 }
1192
1193 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -07001194 mCurWaitingUserSwitchCallbacks = null;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001195 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1196 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
1197 oldUserId, newUserId, uss));
1198 }
1199
1200 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolovc94c2492016-04-20 17:44:00 -07001201 Slog.d(TAG, "Continue user switch oldUser #" + oldUserId + ", newUser #" + newUserId);
Evan Rosky18396452016-07-27 15:19:37 -07001202 if (mUserSwitchUiEnabled) {
1203 synchronized (mLock) {
1204 mInjector.getWindowManager().stopFreezingScreen();
1205 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001206 }
Fyodor Kupolovc94c2492016-04-20 17:44:00 -07001207 uss.switching = false;
1208 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
1209 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
1210 newUserId, 0));
Lenka Trochtovab4484ba2015-12-16 12:32:31 +01001211 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001212 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001213 }
1214
1215 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
Tony Mak5c2cf032017-04-03 18:38:23 +01001216 boolean homeInFront =
1217 mInjector.getActivityStackSupervisor().switchUserLocked(newUserId, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001218 if (homeInFront) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001219 mInjector.startHomeActivityLocked(newUserId, "moveUserToForeground");
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001220 } else {
Tony Mak5c2cf032017-04-03 18:38:23 +01001221 mInjector.getActivityStackSupervisor().resumeFocusedStackTopActivityLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001222 }
1223 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001224 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1225 }
1226
1227 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1228 long ident = Binder.clearCallingIdentity();
1229 try {
1230 Intent intent;
1231 if (oldUserId >= 0) {
1232 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001233 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(oldUserId, false);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001234 int count = profiles.size();
1235 for (int i = 0; i < count; i++) {
1236 int profileUserId = profiles.get(i).id;
1237 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1238 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1239 | Intent.FLAG_RECEIVER_FOREGROUND);
1240 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001241 mInjector.broadcastIntentLocked(intent,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001242 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1243 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1244 }
1245 }
1246 if (newUserId >= 0) {
1247 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001248 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(newUserId, false);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001249 int count = profiles.size();
1250 for (int i = 0; i < count; i++) {
1251 int profileUserId = profiles.get(i).id;
1252 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1253 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1254 | Intent.FLAG_RECEIVER_FOREGROUND);
1255 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001256 mInjector.broadcastIntentLocked(intent,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001257 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1258 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1259 }
1260 intent = new Intent(Intent.ACTION_USER_SWITCHED);
1261 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1262 | Intent.FLAG_RECEIVER_FOREGROUND);
1263 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001264 mInjector.broadcastIntentLocked(intent,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001265 null, null, 0, null, null,
1266 new String[] {android.Manifest.permission.MANAGE_USERS},
1267 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1268 UserHandle.USER_ALL);
1269 }
1270 } finally {
1271 Binder.restoreCallingIdentity(ident);
1272 }
1273 }
1274
1275
1276 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1277 int allowMode, String name, String callerPackage) {
1278 final int callingUserId = UserHandle.getUserId(callingUid);
1279 if (callingUserId == userId) {
1280 return userId;
1281 }
1282
1283 // Note that we may be accessing mCurrentUserId outside of a lock...
1284 // shouldn't be a big deal, if this is being called outside
1285 // of a locked context there is intrinsically a race with
1286 // the value the caller will receive and someone else changing it.
1287 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1288 // we will switch to the calling user if access to the current user fails.
1289 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1290
1291 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1292 final boolean allow;
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001293 if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001294 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1295 // If the caller has this permission, they always pass go. And collect $200.
1296 allow = true;
1297 } else if (allowMode == ALLOW_FULL_ONLY) {
1298 // We require full access, sucks to be you.
1299 allow = false;
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001300 } else if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001301 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1302 // If the caller does not have either permission, they are always doomed.
1303 allow = false;
1304 } else if (allowMode == ALLOW_NON_FULL) {
1305 // We are blanket allowing non-full access, you lucky caller!
1306 allow = true;
1307 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1308 // We may or may not allow this depending on whether the two users are
1309 // in the same profile.
1310 allow = isSameProfileGroup(callingUserId, targetUserId);
1311 } else {
1312 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1313 }
1314 if (!allow) {
1315 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1316 // In this case, they would like to just execute as their
1317 // owner user instead of failing.
1318 targetUserId = callingUserId;
1319 } else {
1320 StringBuilder builder = new StringBuilder(128);
1321 builder.append("Permission Denial: ");
1322 builder.append(name);
1323 if (callerPackage != null) {
1324 builder.append(" from ");
1325 builder.append(callerPackage);
1326 }
1327 builder.append(" asks to run as user ");
1328 builder.append(userId);
1329 builder.append(" but is calling from user ");
1330 builder.append(UserHandle.getUserId(callingUid));
1331 builder.append("; this requires ");
1332 builder.append(INTERACT_ACROSS_USERS_FULL);
1333 if (allowMode != ALLOW_FULL_ONLY) {
1334 builder.append(" or ");
1335 builder.append(INTERACT_ACROSS_USERS);
1336 }
1337 String msg = builder.toString();
1338 Slog.w(TAG, msg);
1339 throw new SecurityException(msg);
1340 }
1341 }
1342 }
1343 if (!allowAll && targetUserId < 0) {
1344 throw new IllegalArgumentException(
1345 "Call does not support special user #" + targetUserId);
1346 }
1347 // Check shell permission
1348 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1349 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1350 throw new SecurityException("Shell does not have permission to access user "
1351 + targetUserId + "\n " + Debug.getCallers(3));
1352 }
1353 }
1354 return targetUserId;
1355 }
1356
1357 int unsafeConvertIncomingUserLocked(int userId) {
1358 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1359 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001360 }
1361
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -07001362 void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
1363 Preconditions.checkNotNull(name, "Observer name cannot be null");
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001364 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001365 != PackageManager.PERMISSION_GRANTED) {
1366 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1367 + Binder.getCallingPid()
1368 + ", uid=" + Binder.getCallingUid()
1369 + " requires " + INTERACT_ACROSS_USERS_FULL;
1370 Slog.w(TAG, msg);
1371 throw new SecurityException(msg);
1372 }
Fyodor Kupolov0b77ef92016-06-20 17:16:52 -07001373 mUserSwitchObservers.register(observer, name);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001374 }
1375
1376 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1377 mUserSwitchObservers.unregister(observer);
1378 }
1379
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001380 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001381 return mStartedUsers.get(userId);
1382 }
1383
1384 boolean hasStartedUserState(int userId) {
1385 return mStartedUsers.get(userId) != null;
1386 }
1387
1388 private void updateStartedUserArrayLocked() {
1389 int num = 0;
1390 for (int i = 0; i < mStartedUsers.size(); i++) {
1391 UserState uss = mStartedUsers.valueAt(i);
1392 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001393 if (uss.state != UserState.STATE_STOPPING
1394 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001395 num++;
1396 }
1397 }
1398 mStartedUserArray = new int[num];
1399 num = 0;
1400 for (int i = 0; i < mStartedUsers.size(); i++) {
1401 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001402 if (uss.state != UserState.STATE_STOPPING
1403 && uss.state != UserState.STATE_SHUTDOWN) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -08001404 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001405 }
1406 }
1407 }
1408
1409 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1410 for (int i = 0; i < mStartedUsers.size(); i++) {
1411 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001412 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001413 }
1414 }
1415
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001416 void onSystemReady() {
1417 updateCurrentProfileIdsLocked();
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001418 }
1419
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001420 /**
1421 * Refreshes the list of users related to the current user when either a
1422 * user switch happens or when a new related user is started in the
1423 * background.
1424 */
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001425 private void updateCurrentProfileIdsLocked() {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001426 final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001427 false /* enabledOnly */);
1428 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1429 for (int i = 0; i < currentProfileIds.length; i++) {
1430 currentProfileIds[i] = profiles.get(i).id;
1431 }
1432 mCurrentProfileIds = currentProfileIds;
1433
1434 synchronized (mUserProfileGroupIdsSelfLocked) {
1435 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001436 final List<UserInfo> users = mInjector.getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001437 for (int i = 0; i < users.size(); i++) {
1438 UserInfo user = users.get(i);
1439 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1440 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1441 }
1442 }
1443 }
1444 }
1445
1446 int[] getStartedUserArrayLocked() {
1447 return mStartedUserArray;
1448 }
1449
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001450 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001451 UserState state = getStartedUserStateLocked(userId);
1452 if (state == null) {
1453 return false;
1454 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001455 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001456 return true;
1457 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001458 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001459 switch (state.state) {
1460 case UserState.STATE_BOOTING:
1461 case UserState.STATE_RUNNING_LOCKED:
1462 return true;
1463 default:
1464 return false;
1465 }
1466 }
1467 if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
1468 switch (state.state) {
1469 case UserState.STATE_RUNNING_UNLOCKING:
1470 case UserState.STATE_RUNNING_UNLOCKED:
1471 return true;
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001472 // In the stopping/shutdown state return unlock state of the user key
1473 case UserState.STATE_STOPPING:
1474 case UserState.STATE_SHUTDOWN:
1475 return StorageManager.isUserKeyUnlocked(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001476 default:
1477 return false;
1478 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001479 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001480 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001481 switch (state.state) {
1482 case UserState.STATE_RUNNING_UNLOCKED:
1483 return true;
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001484 // In the stopping/shutdown state return unlock state of the user key
1485 case UserState.STATE_STOPPING:
1486 case UserState.STATE_SHUTDOWN:
1487 return StorageManager.isUserKeyUnlocked(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001488 default:
1489 return false;
1490 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001491 }
1492
Fyodor Kupolova24e81219f2017-06-23 12:28:39 -07001493 return state.state != UserState.STATE_STOPPING && state.state != UserState.STATE_SHUTDOWN;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001494 }
1495
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001496 UserInfo getCurrentUser() {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001497 if ((mInjector.checkCallingPermission(INTERACT_ACROSS_USERS)
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001498 != PackageManager.PERMISSION_GRANTED) && (
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001499 mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001500 != PackageManager.PERMISSION_GRANTED)) {
1501 String msg = "Permission Denial: getCurrentUser() from pid="
1502 + Binder.getCallingPid()
1503 + ", uid=" + Binder.getCallingUid()
1504 + " requires " + INTERACT_ACROSS_USERS;
1505 Slog.w(TAG, msg);
1506 throw new SecurityException(msg);
1507 }
Fyodor Kupolovdcb26bb2017-05-09 17:06:52 -07001508
1509 // Optimization - if there is no pending user switch, return current id
1510 if (mTargetUserId == UserHandle.USER_NULL) {
1511 return getUserInfo(mCurrentUserId);
1512 }
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001513 synchronized (mLock) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001514 return getCurrentUserLocked();
1515 }
1516 }
1517
1518 UserInfo getCurrentUserLocked() {
1519 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001520 return getUserInfo(userId);
1521 }
1522
1523 int getCurrentOrTargetUserIdLocked() {
1524 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001525 }
1526
1527 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001528 return mCurrentUserId;
1529 }
1530
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001531 private boolean isCurrentUserLocked(int userId) {
Amith Yamasani458ac462015-12-18 11:21:31 -08001532 return userId == getCurrentOrTargetUserIdLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001533 }
1534
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001535 int setTargetUserIdLocked(int targetUserId) {
1536 return mTargetUserId = targetUserId;
1537 }
1538
1539 int[] getUsers() {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001540 UserManagerService ums = mInjector.getUserManager();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001541 return ums != null ? ums.getUserIds() : new int[] { 0 };
1542 }
1543
1544 UserInfo getUserInfo(int userId) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001545 return mInjector.getUserManager().getUserInfo(userId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001546 }
1547
1548 int[] getUserIds() {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001549 return mInjector.getUserManager().getUserIds();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001550 }
1551
1552 boolean exists(int userId) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001553 return mInjector.getUserManager().exists(userId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001554 }
1555
1556 boolean hasUserRestriction(String restriction, int userId) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001557 return mInjector.getUserManager().hasUserRestriction(restriction, userId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001558 }
1559
1560 Set<Integer> getProfileIds(int userId) {
1561 Set<Integer> userIds = new HashSet<>();
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001562 final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(userId,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001563 false /* enabledOnly */);
1564 for (UserInfo user : profiles) {
1565 userIds.add(user.id);
1566 }
1567 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001568 }
1569
1570 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
Makoto Onuki8198dea2016-07-28 13:10:42 -07001571 if (callingUserId == targetUserId) {
1572 return true;
1573 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001574 synchronized (mUserProfileGroupIdsSelfLocked) {
1575 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1576 UserInfo.NO_PROFILE_GROUP_ID);
1577 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1578 UserInfo.NO_PROFILE_GROUP_ID);
1579 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1580 && callingProfile == targetProfile;
1581 }
1582 }
1583
1584 boolean isCurrentProfileLocked(int userId) {
1585 return ArrayUtils.contains(mCurrentProfileIds, userId);
1586 }
1587
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001588 int[] getCurrentProfileIdsLocked() {
1589 return mCurrentProfileIds;
1590 }
1591
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001592 /**
1593 * Returns whether the given user requires credential entry at this time. This is used to
1594 * intercept activity launches for work apps when the Work Challenge is present.
1595 */
1596 boolean shouldConfirmCredentials(int userId) {
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001597 synchronized (mLock) {
Rubin Xub93522a2016-02-23 18:21:48 +00001598 if (mStartedUsers.get(userId) == null) {
1599 return false;
1600 }
1601 }
Clara Bayarria1771112015-12-18 16:29:18 +00001602 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001603 return false;
1604 }
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001605 final KeyguardManager km = mInjector.getKeyguardManager();
Tony Makae13e182016-05-17 16:36:14 +01001606 return km.isDeviceLocked(userId) && km.isDeviceSecure(userId);
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001607 }
1608
Tony Mak8c536f92016-03-21 12:20:41 +00001609 boolean isLockScreenDisabled(@UserIdInt int userId) {
1610 return mLockPatternUtils.isLockScreenDisabled(userId);
1611 }
1612
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001613 void dump(PrintWriter pw, boolean dumpAll) {
1614 pw.println(" mStartedUsers:");
1615 for (int i = 0; i < mStartedUsers.size(); i++) {
1616 UserState uss = mStartedUsers.valueAt(i);
1617 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1618 pw.print(": "); uss.dump("", pw);
1619 }
1620 pw.print(" mStartedUserArray: [");
1621 for (int i = 0; i < mStartedUserArray.length; i++) {
1622 if (i > 0) pw.print(", ");
1623 pw.print(mStartedUserArray[i]);
1624 }
1625 pw.println("]");
1626 pw.print(" mUserLru: [");
1627 for (int i = 0; i < mUserLru.size(); i++) {
1628 if (i > 0) pw.print(", ");
1629 pw.print(mUserLru.get(i));
1630 }
1631 pw.println("]");
1632 if (dumpAll) {
1633 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1634 }
1635 synchronized (mUserProfileGroupIdsSelfLocked) {
1636 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1637 pw.println(" mUserProfileGroupIds:");
1638 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1639 pw.print(" User #");
1640 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1641 pw.print(" -> profile #");
1642 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1643 }
1644 }
1645 }
1646 }
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001647
1648 @VisibleForTesting
1649 static class Injector {
1650 private final ActivityManagerService mService;
1651 private UserManagerService mUserManager;
1652 private UserManagerInternal mUserManagerInternal;
1653
1654 Injector(ActivityManagerService service) {
1655 mService = service;
1656 }
1657
1658 protected Object getLock() {
1659 return mService;
1660 }
1661
1662 protected Handler getHandler() {
1663 return mService.mHandler;
1664 }
1665
1666 protected Context getContext() {
1667 return mService.mContext;
1668 }
1669
1670 protected LockPatternUtils getLockPatternUtils() {
1671 return new LockPatternUtils(getContext());
1672 }
1673
1674 protected int broadcastIntentLocked(Intent intent, String resolvedType,
1675 IIntentReceiver resultTo, int resultCode, String resultData,
1676 Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
1677 boolean ordered, boolean sticky, int callingPid, int callingUid, int userId) {
1678 return mService.broadcastIntentLocked(null, null, intent, resolvedType, resultTo,
1679 resultCode, resultData, resultExtras, requiredPermissions, appOp, bOptions,
1680 ordered, sticky, callingPid, callingUid, userId);
1681 }
1682
1683 int checkCallingPermission(String permission) {
1684 return mService.checkCallingPermission(permission);
1685 }
1686
1687 WindowManagerService getWindowManager() {
1688 return mService.mWindowManager;
1689 }
1690 void activityManagerOnUserStopped(int userId) {
1691 mService.onUserStoppedLocked(userId);
1692 }
1693
1694 void systemServiceManagerCleanupUser(int userId) {
1695 mService.mSystemServiceManager.cleanupUser(userId);
1696 }
1697
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001698 protected UserManagerService getUserManager() {
1699 if (mUserManager == null) {
1700 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
1701 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
1702 }
1703 return mUserManager;
1704 }
1705
1706 UserManagerInternal getUserManagerInternal() {
1707 if (mUserManagerInternal == null) {
1708 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
1709 }
1710 return mUserManagerInternal;
1711 }
1712
1713 KeyguardManager getKeyguardManager() {
1714 return mService.mContext.getSystemService(KeyguardManager.class);
1715 }
1716
1717 void batteryStatsServiceNoteEvent(int code, String name, int uid) {
1718 mService.mBatteryStatsService.noteEvent(code, name, uid);
1719 }
1720
1721 void systemServiceManagerStopUser(int userId) {
1722 mService.mSystemServiceManager.stopUser(userId);
1723 }
1724
Fyodor Kupolov1d87e402017-01-10 18:34:10 -08001725 boolean isRuntimeRestarted() {
1726 return mService.mSystemServiceManager.isRuntimeRestarted();
1727 }
1728
Fyodor Kupolov4ba91b92017-01-20 18:12:35 -08001729 boolean isFirstBootOrUpgrade() {
1730 IPackageManager pm = AppGlobals.getPackageManager();
1731 try {
1732 return pm.isFirstBoot() || pm.isUpgrade();
1733 } catch (RemoteException e) {
1734 throw e.rethrowFromSystemServer();
1735 }
Fyodor Kupolov1d87e402017-01-10 18:34:10 -08001736 }
1737
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001738 void sendPreBootBroadcast(int userId, boolean quiet, final Runnable onFinish) {
1739 new PreBootBroadcaster(mService, userId, null, quiet) {
1740 @Override
1741 public void onFinished() {
1742 onFinish.run();
1743 }
1744 }.sendNext();
1745 }
1746
1747 void activityManagerForceStopPackageLocked(int userId, String reason) {
1748 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
1749 userId, reason);
1750 };
1751
1752 int checkComponentPermission(String permission, int pid, int uid, int owningUid,
1753 boolean exported) {
1754 return mService.checkComponentPermission(permission, pid, uid, owningUid, exported);
1755 }
1756
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001757 void startHomeActivityLocked(int userId, String reason) {
1758 mService.startHomeActivityLocked(userId, reason);
1759 }
1760
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001761 void updateUserConfigurationLocked() {
1762 mService.updateUserConfigurationLocked();
1763 }
1764
1765 void clearBroadcastQueueForUserLocked(int userId) {
1766 mService.clearBroadcastQueueForUserLocked(userId);
1767 }
1768
1769 void enforceShellRestriction(String restriction, int userId) {
1770 mService.enforceShellRestriction(restriction, userId);
1771 }
1772
1773 void showUserSwitchingDialog(UserInfo fromUser, UserInfo toUser) {
1774 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromUser, toUser,
1775 true /* above system */);
1776 d.show();
1777 }
Tony Mak5c2cf032017-04-03 18:38:23 +01001778
1779 ActivityStackSupervisor getActivityStackSupervisor() {
1780 return mService.mStackSupervisor;
1781 }
Fyodor Kupolovd6038db2016-06-22 16:53:19 -07001782 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001783}