blob: addffd33d74669328ab11e78b1e65c267f8ee14f [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;
Wale Ogunwalef80170f2016-02-04 15:12:29 -080027import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
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;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070035import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
36import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
37import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
38import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -070039import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070040import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
41
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070042import android.annotation.NonNull;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070043import android.app.ActivityManager;
44import android.app.AppOpsManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070045import android.app.Dialog;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070046import android.app.IStopUserCallback;
47import android.app.IUserSwitchObserver;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000048import android.app.KeyguardManager;
Wale Ogunwalef80170f2016-02-04 15:12:29 -080049import android.content.ContentResolver;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070050import android.content.Context;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070051import android.content.IIntentReceiver;
52import android.content.Intent;
53import android.content.pm.PackageManager;
54import android.content.pm.UserInfo;
Wale Ogunwalef80170f2016-02-04 15:12:29 -080055import android.database.ContentObserver;
56import android.net.Uri;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070057import android.os.BatteryStats;
58import android.os.Binder;
59import android.os.Bundle;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070060import android.os.Debug;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070061import android.os.Handler;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070062import android.os.IBinder;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070063import android.os.IRemoteCallback;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070064import android.os.IUserManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070065import android.os.Process;
66import android.os.RemoteCallbackList;
67import android.os.RemoteException;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070068import android.os.ServiceManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070069import android.os.UserHandle;
70import android.os.UserManager;
Lenka Trochtova1ddda472016-02-12 10:42:12 +010071import android.os.UserManagerInternal;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080072import android.os.storage.IMountService;
73import android.os.storage.StorageManager;
Wale Ogunwalef80170f2016-02-04 15:12:29 -080074import android.provider.Settings;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070075import android.util.IntArray;
Suprabh Shukla4fe508b2015-11-20 18:22:57 -080076import android.util.Pair;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070077import android.util.Slog;
78import android.util.SparseArray;
Wale Ogunwalef80170f2016-02-04 15:12:29 -080079import android.util.SparseBooleanArray;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070080import android.util.SparseIntArray;
81
82import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080083import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070084import com.android.internal.util.ArrayUtils;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000085import com.android.internal.widget.LockPatternUtils;
Lenka Trochtova1ddda472016-02-12 10:42:12 +010086import com.android.server.LocalServices;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070087import com.android.server.pm.UserManagerService;
88
89import java.io.PrintWriter;
90import java.util.ArrayList;
91import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070092import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070093import java.util.List;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070094import java.util.Set;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070095
96/**
97 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
98 */
99final class UserController {
100 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
101 // Maximum number of users we allow to be running at a time.
102 static final int MAX_RUNNING_USERS = 3;
103
104 // Amount of time we wait for observers to handle a user switch before
105 // giving up on them and unfreezing the screen.
106 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
107
108 private final ActivityManagerService mService;
109 private final Handler mHandler;
110
111 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700112 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700113 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700114 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700115
116 /**
117 * Which users have been started, so are allowed to run code.
118 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800119 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700120 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800121
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700122 /**
123 * LRU list of history of current users. Most recently current is at the end.
124 */
125 private final ArrayList<Integer> mUserLru = new ArrayList<>();
126
127 /**
128 * Constant array of the users that are currently started.
129 */
130 private int[] mStartedUserArray = new int[] { 0 };
131
132 // If there are multiple profiles for the current user, their ids are here
133 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700134 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700135
136 /**
137 * Mapping from each known user ID to the profile group ID it is associated with.
138 */
139 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
140
141 /**
142 * Registered observers of the user switching mechanics.
143 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700144 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700145 = new RemoteCallbackList<>();
146
147 /**
148 * Currently active user switch.
149 */
150 Object mCurUserSwitchCallback;
151
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700152 private volatile UserManagerService mUserManager;
153
Clara Bayarria1771112015-12-18 16:29:18 +0000154 private final LockPatternUtils mLockPatternUtils;
155
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800156 // Set of users who have completed the set-up process.
157 private final SparseBooleanArray mSetupCompletedUsers = new SparseBooleanArray();
158 private final UserSetupCompleteContentObserver mUserSetupCompleteContentObserver;
159
160 private class UserSetupCompleteContentObserver extends ContentObserver {
161 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(USER_SETUP_COMPLETE);
162
163 public UserSetupCompleteContentObserver(Handler handler) {
164 super(handler);
165 }
166
167 void register(ContentResolver resolver) {
168 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
169 synchronized (mService) {
Rubin Xu5eb0f3b2016-02-12 13:47:04 +0000170 updateUserSetupCompleteLocked(UserHandle.USER_ALL);
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800171 }
172 }
173
174 @Override
Rubin Xu5eb0f3b2016-02-12 13:47:04 +0000175 public void onChange(boolean selfChange, Uri uri, int userId) {
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800176 if (mUserSetupComplete.equals(uri)) {
177 synchronized (mService) {
Rubin Xu5eb0f3b2016-02-12 13:47:04 +0000178 updateUserSetupCompleteLocked(userId);
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800179 }
180 }
181 }
182 }
183
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700184 UserController(ActivityManagerService service) {
185 mService = service;
186 mHandler = mService.mHandler;
187 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800188 final UserState uss = new UserState(UserHandle.SYSTEM);
189 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700190 mUserLru.add(UserHandle.USER_SYSTEM);
Clara Bayarria1771112015-12-18 16:29:18 +0000191 mLockPatternUtils = new LockPatternUtils(mService.mContext);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700192 updateStartedUserArrayLocked();
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800193 mUserSetupCompleteContentObserver = new UserSetupCompleteContentObserver(mHandler);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700194 }
195
196 void finishUserSwitch(UserState uss) {
197 synchronized (mService) {
198 finishUserBoot(uss);
199
200 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700201 stopRunningUsersLocked(MAX_RUNNING_USERS);
202 }
203 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700204
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700205 void stopRunningUsersLocked(int maxRunningUsers) {
206 int num = mUserLru.size();
207 int i = 0;
208 while (num > maxRunningUsers && i < mUserLru.size()) {
209 Integer oldUserId = mUserLru.get(i);
210 UserState oldUss = mStartedUsers.get(oldUserId);
211 if (oldUss == null) {
212 // Shouldn't happen, but be sane if it does.
213 mUserLru.remove(i);
214 num--;
215 continue;
216 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700217 if (oldUss.state == UserState.STATE_STOPPING
218 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700219 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700220 num--;
221 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700222 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700223 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700224 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
225 // Owner/System user and current user can't be stopped. We count it as running
226 // when it is not a pure system user.
227 if (UserInfo.isSystemOnly(oldUserId)) {
228 num--;
229 }
230 i++;
231 continue;
232 }
233 // This is a user to be stopped.
234 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
235 num--;
236 }
237 num--;
238 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700239 }
240 }
241
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800242 private void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700243 finishUserBoot(uss, null);
244 }
245
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800246 private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700247 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700248 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700249 // Bail if we ended up with a stale user
250 if (mStartedUsers.get(userId) != uss) return;
251
252 // We always walk through all the user lifecycle states to send
253 // consistent developer events. We step into RUNNING_LOCKED here,
254 // but we might immediately step into RUNNING below if the user
255 // storage is already unlocked.
256 if (uss.state == UserState.STATE_BOOTING) {
257 uss.setState(UserState.STATE_RUNNING_LOCKED);
258
259 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700260 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeya242f822015-12-17 15:38:20 -0700261 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
262 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700263 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
264 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
265 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
266 }
267
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700268 maybeUnlockUser(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700269 }
270 }
271
272 /**
273 * Consider stepping from {@link UserState#STATE_RUNNING_LOCKED} into
274 * {@link UserState#STATE_RUNNING}, which only occurs if the user storage is
275 * actually unlocked.
276 */
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700277 void finishUserUnlock(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700278 final int userId = uss.mHandle.getIdentifier();
279 synchronized (mService) {
280 // Bail if we ended up with a stale user
281 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
282
283 // Only keep marching forward if user is actually unlocked
284 if (!isUserKeyUnlocked(userId)) return;
285
286 if (uss.state == UserState.STATE_RUNNING_LOCKED) {
287 uss.setState(UserState.STATE_RUNNING);
288
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700289 // Give user manager a chance to prepare app storage
290 mUserManager.onBeforeUnlockUser(userId);
291
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700292 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
293
294 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700295 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700296 unlockedIntent.addFlags(
297 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
298 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
299 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
300 userId);
301
Kenny Guyb1b30262016-02-09 16:02:35 +0000302 if (getUserInfo(userId).isManagedProfile()) {
303 UserInfo parent = getUserManager().getProfileParent(userId);
304 if (parent != null) {
305 final Intent profileUnlockedIntent = new Intent(
306 Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
Rubin Xub5f00492016-02-15 13:50:18 +0000307 profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
308 profileUnlockedIntent.addFlags(
Kenny Guyb1b30262016-02-09 16:02:35 +0000309 Intent.FLAG_RECEIVER_REGISTERED_ONLY
310 | Intent.FLAG_RECEIVER_FOREGROUND);
311 mService.broadcastIntentLocked(null, null, profileUnlockedIntent,
312 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
313 null, false, false, MY_PID, SYSTEM_UID,
314 parent.id);
315 }
316 }
317
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700318 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
319 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -0800320 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
321 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700322 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
323 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700324 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700325 }
326 }
327 }
328
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700329 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700330 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
331 != PackageManager.PERMISSION_GRANTED) {
332 String msg = "Permission Denial: switchUser() from pid="
333 + Binder.getCallingPid()
334 + ", uid=" + Binder.getCallingUid()
335 + " requires " + INTERACT_ACROSS_USERS_FULL;
336 Slog.w(TAG, msg);
337 throw new SecurityException(msg);
338 }
339 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
340 throw new IllegalArgumentException("Can't stop system user " + userId);
341 }
342 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
343 userId);
344 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700345 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700346 }
347 }
348
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700349 /**
350 * Stops the user along with its related users. The method calls
351 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
352 */
353 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
354 if (userId == UserHandle.USER_SYSTEM) {
355 return USER_OP_ERROR_IS_SYSTEM;
356 }
357 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700358 return USER_OP_IS_CURRENT;
359 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700360 int[] usersToStop = getUsersToStopLocked(userId);
361 // If one of related users is system or current, no related users should be stopped
362 for (int i = 0; i < usersToStop.length; i++) {
363 int relatedUserId = usersToStop[i];
364 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
365 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
366 + relatedUserId);
367 // We still need to stop the requested user if it's a force stop.
368 if (force) {
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800369 Slog.i(TAG,
370 "Force stop user " + userId + ". Related users will not be stopped");
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700371 stopSingleUserLocked(userId, callback);
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800372 return USER_OP_SUCCESS;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700373 }
374 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
375 }
376 }
377 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
378 for (int userIdToStop : usersToStop) {
379 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
380 }
381 return USER_OP_SUCCESS;
382 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700383
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700384 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
385 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700386 final UserState uss = mStartedUsers.get(userId);
387 if (uss == null) {
388 // User is not started, nothing to do... but we do need to
389 // callback if requested.
390 if (callback != null) {
391 mHandler.post(new Runnable() {
392 @Override
393 public void run() {
394 try {
395 callback.userStopped(userId);
396 } catch (RemoteException e) {
397 }
398 }
399 });
400 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700401 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700402 }
403
404 if (callback != null) {
405 uss.mStopCallbacks.add(callback);
406 }
407
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700408 if (uss.state != UserState.STATE_STOPPING
409 && uss.state != UserState.STATE_SHUTDOWN) {
410 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700411 updateStartedUserArrayLocked();
412
413 long ident = Binder.clearCallingIdentity();
414 try {
415 // We are going to broadcast ACTION_USER_STOPPING and then
416 // once that is done send a final ACTION_SHUTDOWN and then
417 // stop the user.
418 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
419 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
420 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
421 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
422 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
423 // This is the result receiver for the final shutdown broadcast.
424 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
425 @Override
426 public void performReceive(Intent intent, int resultCode, String data,
427 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
428 finishUserStop(uss);
429 }
430 };
431 // This is the result receiver for the initial stopping broadcast.
432 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
433 @Override
434 public void performReceive(Intent intent, int resultCode, String data,
435 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
436 // On to the next.
437 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700438 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700439 // Whoops, we are being started back up. Abort, abort!
440 return;
441 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700442 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700443 }
444 mService.mBatteryStatsService.noteEvent(
445 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
446 Integer.toString(userId), userId);
447 mService.mSystemServiceManager.stopUser(userId);
448 mService.broadcastIntentLocked(null, null, shutdownIntent,
449 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700450 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700451 }
452 };
453 // Kick things off.
454 mService.broadcastIntentLocked(null, null, stoppingIntent,
455 null, stoppingReceiver, 0, null, null,
456 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700457 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700458 } finally {
459 Binder.restoreCallingIdentity(ident);
460 }
461 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700462 }
463
464 void finishUserStop(UserState uss) {
465 final int userId = uss.mHandle.getIdentifier();
466 boolean stopped;
467 ArrayList<IStopUserCallback> callbacks;
468 synchronized (mService) {
469 callbacks = new ArrayList<>(uss.mStopCallbacks);
470 if (mStartedUsers.get(userId) != uss) {
471 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700472 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700473 stopped = false;
474 } else {
475 stopped = true;
476 // User can no longer run.
477 mStartedUsers.remove(userId);
478 mUserLru.remove(Integer.valueOf(userId));
479 updateStartedUserArrayLocked();
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800480 mSetupCompletedUsers.delete(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700481
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800482 mService.onUserStoppedLocked(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700483 // Clean up all state and processes associated with the user.
484 // Kill all the processes for the user.
485 forceStopUserLocked(userId, "finish user");
486 }
487 }
488
489 for (int i = 0; i < callbacks.size(); i++) {
490 try {
491 if (stopped) callbacks.get(i).userStopped(userId);
492 else callbacks.get(i).userStopAborted(userId);
493 } catch (RemoteException e) {
494 }
495 }
496
497 if (stopped) {
498 mService.mSystemServiceManager.cleanupUser(userId);
499 synchronized (mService) {
500 mService.mStackSupervisor.removeUserLocked(userId);
501 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100502 // Remove the user if it is ephemeral.
503 if (getUserInfo(userId).isEphemeral()) {
504 mUserManager.removeUser(userId);
505 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700506 }
507 }
508
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700509 /**
510 * Determines the list of users that should be stopped together with the specified
511 * {@code userId}. The returned list includes {@code userId}.
512 */
513 private @NonNull int[] getUsersToStopLocked(int userId) {
514 int startedUsersSize = mStartedUsers.size();
515 IntArray userIds = new IntArray();
516 userIds.add(userId);
517 synchronized (mUserProfileGroupIdsSelfLocked) {
518 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
519 UserInfo.NO_PROFILE_GROUP_ID);
520 for (int i = 0; i < startedUsersSize; i++) {
521 UserState uss = mStartedUsers.valueAt(i);
522 int startedUserId = uss.mHandle.getIdentifier();
523 // Skip unrelated users (profileGroupId mismatch)
524 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
525 UserInfo.NO_PROFILE_GROUP_ID);
526 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
527 && (userGroupId == startedUserGroupId);
528 // userId has already been added
529 boolean sameUserId = startedUserId == userId;
530 if (!sameGroup || sameUserId) {
531 continue;
532 }
533 userIds.add(startedUserId);
534 }
535 }
536 return userIds.toArray();
537 }
538
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700539 private void forceStopUserLocked(int userId, String reason) {
540 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
541 userId, reason);
542 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
543 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
544 | Intent.FLAG_RECEIVER_FOREGROUND);
545 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
546 mService.broadcastIntentLocked(null, null, intent,
547 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700548 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700549 }
550
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700551 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100552 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700553 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100554 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700555 synchronized (mService) {
556 final int num = mUserLru.size();
557 for (int i = 0; i < num; i++) {
558 Integer oldUserId = mUserLru.get(i);
559 UserState oldUss = mStartedUsers.get(oldUserId);
560 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700561 || oldUss.state == UserState.STATE_STOPPING
562 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700563 continue;
564 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700565 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtova1ddda472016-02-12 10:42:12 +0100566 if (userInfo.isEphemeral()) {
567 LocalServices.getService(UserManagerInternal.class)
568 .onEphemeralUserStop(oldUserId);
569 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100570 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700571 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700572 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700573 break;
574 }
575 }
576 }
577 }
578
579 void startProfilesLocked() {
580 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700581 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700582 mCurrentUserId, false /* enabledOnly */);
583 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
584 for (UserInfo user : profiles) {
585 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
Rubin Xuf13c9802016-01-21 18:06:00 +0000586 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700587 profilesToStart.add(user);
588 }
589 }
590 final int profilesToStartSize = profilesToStart.size();
591 int i = 0;
592 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
593 startUser(profilesToStart.get(i).id, /* foreground= */ false);
594 }
595 if (i < profilesToStartSize) {
596 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
597 }
598 }
599
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700600 private UserManagerService getUserManager() {
601 UserManagerService userManager = mUserManager;
602 if (userManager == null) {
603 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
604 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
605 }
606 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700607 }
608
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700609 private IMountService getMountService() {
610 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
611 }
612
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700613 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700614 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800615 if (mountService != null) {
616 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700617 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800618 } catch (RemoteException e) {
619 throw e.rethrowAsRuntimeException();
620 }
621 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700622 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
623 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800624 }
625 }
626
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700627 boolean startUser(final int userId, final boolean foreground) {
628 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
629 != PackageManager.PERMISSION_GRANTED) {
630 String msg = "Permission Denial: switchUser() from pid="
631 + Binder.getCallingPid()
632 + ", uid=" + Binder.getCallingUid()
633 + " requires " + INTERACT_ACROSS_USERS_FULL;
634 Slog.w(TAG, msg);
635 throw new SecurityException(msg);
636 }
637
638 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
639
640 final long ident = Binder.clearCallingIdentity();
641 try {
642 synchronized (mService) {
643 final int oldUserId = mCurrentUserId;
644 if (oldUserId == userId) {
645 return true;
646 }
647
648 mService.mStackSupervisor.setLockTaskModeLocked(null,
649 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
650
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700651 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700652 if (userInfo == null) {
653 Slog.w(TAG, "No user info for user #" + userId);
654 return false;
655 }
656 if (foreground && userInfo.isManagedProfile()) {
657 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
658 return false;
659 }
660
661 if (foreground) {
662 mService.mWindowManager.startFreezingScreen(
663 R.anim.screen_user_exit, R.anim.screen_user_enter);
664 }
665
666 boolean needStart = false;
667
668 // If the user we are switching to is not currently started, then
669 // we need to start it now.
670 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700671 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700672 updateStartedUserArrayLocked();
673 needStart = true;
674 }
675
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800676 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700677 final Integer userIdInt = userId;
678 mUserLru.remove(userIdInt);
679 mUserLru.add(userIdInt);
Rubin Xu5eb0f3b2016-02-12 13:47:04 +0000680 updateUserSetupCompleteLocked(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700681
682 if (foreground) {
683 mCurrentUserId = userId;
684 mService.updateUserConfigurationLocked();
685 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
686 updateCurrentProfileIdsLocked();
687 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
688 // Once the internal notion of the active user has switched, we lock the device
689 // with the option to show the user switcher on the keyguard.
690 mService.mWindowManager.lockNow(null);
691 } else {
692 final Integer currentUserIdInt = mCurrentUserId;
693 updateCurrentProfileIdsLocked();
694 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
695 mUserLru.remove(currentUserIdInt);
696 mUserLru.add(currentUserIdInt);
697 }
698
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700699 // Make sure user is in the started state. If it is currently
700 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700701 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700702 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
703 // so we can just fairly silently bring the user back from
704 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700705 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700706 updateStartedUserArrayLocked();
707 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700708 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700709 // This means ACTION_SHUTDOWN has been sent, so we will
710 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700711 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700712 updateStartedUserArrayLocked();
713 needStart = true;
714 }
715
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700716 if (uss.state == UserState.STATE_BOOTING) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700717 // Give user manager a chance to propagate user restrictions
718 // to other services and prepare app storage
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800719 getUserManager().onBeforeStartUser(userId);
720
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700721 // Booting up a new user, need to tell system services about it.
722 // Note that this is on the same handler as scheduling of broadcasts,
723 // which is important because it needs to go first.
724 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
725 }
726
727 if (foreground) {
728 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
729 oldUserId));
730 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
731 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
732 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
733 oldUserId, userId, uss));
734 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
735 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
736 }
737
738 if (needStart) {
739 // Send USER_STARTED broadcast
740 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
741 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
742 | Intent.FLAG_RECEIVER_FOREGROUND);
743 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
744 mService.broadcastIntentLocked(null, null, intent,
745 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700746 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700747 }
748
749 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
750 if (userId != UserHandle.USER_SYSTEM) {
751 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
752 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
753 mService.broadcastIntentLocked(null, null, intent, null,
754 new IIntentReceiver.Stub() {
755 public void performReceive(Intent intent, int resultCode,
756 String data, Bundle extras, boolean ordered,
757 boolean sticky, int sendingUser) {
758 onUserInitialized(uss, foreground, oldUserId, userId);
759 }
760 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700761 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700762 uss.initializing = true;
763 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700764 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700765 }
766 }
767
768 if (foreground) {
769 if (!uss.initializing) {
770 moveUserToForegroundLocked(uss, oldUserId, userId);
771 }
772 } else {
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800773 mService.mUserController.finishUserBoot(uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700774 }
775
776 if (needStart) {
777 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
778 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
779 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
780 mService.broadcastIntentLocked(null, null, intent,
781 null, new IIntentReceiver.Stub() {
782 @Override
783 public void performReceive(Intent intent, int resultCode,
784 String data, Bundle extras, boolean ordered, boolean sticky,
785 int sendingUser) throws RemoteException {
786 }
787 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700788 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
789 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700790 }
791 }
792 } finally {
793 Binder.restoreCallingIdentity(ident);
794 }
795
796 return true;
797 }
798
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700799 /**
800 * Start user, if its not already running, and bring it to foreground.
801 */
802 boolean startUserInForeground(final int userId, Dialog dlg) {
803 boolean result = startUser(userId, /* foreground */ true);
804 dlg.dismiss();
805 return result;
806 }
807
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000808 boolean unlockUser(final int userId, byte[] token, byte[] secret) {
Jeff Sharkeyba512352015-11-12 20:17:45 -0800809 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
810 != PackageManager.PERMISSION_GRANTED) {
811 String msg = "Permission Denial: unlockUser() from pid="
812 + Binder.getCallingPid()
813 + ", uid=" + Binder.getCallingUid()
814 + " requires " + INTERACT_ACROSS_USERS_FULL;
815 Slog.w(TAG, msg);
816 throw new SecurityException(msg);
817 }
818
Jeff Sharkey8924e872015-11-30 12:52:10 -0700819 final long binderToken = Binder.clearCallingIdentity();
820 try {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000821 return unlockUserCleared(userId, token, secret);
Jeff Sharkey8924e872015-11-30 12:52:10 -0700822 } finally {
823 Binder.restoreCallingIdentity(binderToken);
824 }
825 }
826
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700827 /**
828 * Attempt to unlock user without a credential token. This typically
829 * succeeds when the device doesn't have credential-encrypted storage, or
830 * when the the credential-encrypted storage isn't tied to a user-provided
831 * PIN or pattern.
832 */
833 boolean maybeUnlockUser(final int userId) {
834 // Try unlocking storage using empty token
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000835 return unlockUserCleared(userId, null, null);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700836 }
837
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000838 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret) {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700839 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700840 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700841 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700842 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700843 }
844
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700845 if (!isUserKeyUnlocked(userId)) {
846 final UserInfo userInfo = getUserInfo(userId);
847 final IMountService mountService = getMountService();
848 try {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000849 mountService.unlockUserKey(userId, userInfo.serialNumber, token, secret);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700850 } catch (RemoteException | RuntimeException e) {
851 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
852 return false;
853 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800854 }
855
856 synchronized (mService) {
857 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700858 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800859 }
860
861 return true;
862 }
863
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800864 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700865 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800866 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
867 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700868 d.show();
869 }
870
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700871 void dispatchForegroundProfileChanged(int userId) {
872 final int observerCount = mUserSwitchObservers.beginBroadcast();
873 for (int i = 0; i < observerCount; i++) {
874 try {
875 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
876 } catch (RemoteException e) {
877 // Ignore
878 }
879 }
880 mUserSwitchObservers.finishBroadcast();
881 }
882
883 /** Called on handler thread */
884 void dispatchUserSwitchComplete(int userId) {
885 final int observerCount = mUserSwitchObservers.beginBroadcast();
886 for (int i = 0; i < observerCount; i++) {
887 try {
888 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
889 } catch (RemoteException e) {
890 }
891 }
892 mUserSwitchObservers.finishBroadcast();
893 }
894
Rubin Xu5eb0f3b2016-02-12 13:47:04 +0000895 void updateUserSetupCompleteLocked(int userId) {
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800896 final ContentResolver cr = mService.mContext.getContentResolver();
Rubin Xufaf9bdc2016-02-12 17:22:48 +0000897 for (int i = mStartedUsers.size() - 1; i >= 0; i--) {
898 int startedUser = mStartedUsers.keyAt(i);
899 if (startedUser == userId || userId == UserHandle.USER_ALL) {
900 final boolean setupComplete =
901 Settings.Secure.getIntForUser(cr, USER_SETUP_COMPLETE, 0, startedUser) != 0;
902 mSetupCompletedUsers.put(startedUser, setupComplete);
903 }
Rubin Xu5eb0f3b2016-02-12 13:47:04 +0000904 }
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800905 }
906
907 boolean isUserSetupCompleteLocked(int userId) {
908 return mSetupCompletedUsers.get(userId);
909 }
910
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700911 private void stopBackgroundUsersIfEnforced(int oldUserId) {
912 // Never stop system user
913 if (oldUserId == UserHandle.USER_SYSTEM) {
914 return;
915 }
916 // For now, only check for user restriction. Additional checks can be added here
917 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
918 oldUserId);
919 if (!disallowRunInBg) {
920 return;
921 }
922 synchronized (mService) {
923 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
924 + " and related users");
925 stopUsersLocked(oldUserId, false, null);
926 }
927 }
928
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700929 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
930 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800931 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700932 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
933 }
934 }
935
936 void dispatchUserSwitch(final UserState uss, final int oldUserId,
937 final int newUserId) {
938 final int observerCount = mUserSwitchObservers.beginBroadcast();
939 if (observerCount > 0) {
940 final IRemoteCallback callback = new IRemoteCallback.Stub() {
941 int mCount = 0;
942 @Override
943 public void sendResult(Bundle data) throws RemoteException {
944 synchronized (mService) {
945 if (mCurUserSwitchCallback == this) {
946 mCount++;
947 if (mCount == observerCount) {
948 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
949 }
950 }
951 }
952 }
953 };
954 synchronized (mService) {
955 uss.switching = true;
956 mCurUserSwitchCallback = callback;
957 }
958 for (int i = 0; i < observerCount; i++) {
959 try {
960 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
961 newUserId, callback);
962 } catch (RemoteException e) {
963 }
964 }
965 } else {
966 synchronized (mService) {
967 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
968 }
969 }
970 mUserSwitchObservers.finishBroadcast();
971 }
972
973 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
974 mCurUserSwitchCallback = null;
975 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
976 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
977 oldUserId, newUserId, uss));
978 }
979
980 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700981 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700982 }
983
984 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
985 synchronized (mService) {
986 if (foreground) {
987 moveUserToForegroundLocked(uss, oldUserId, newUserId);
988 }
989 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700990 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700991 }
992
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700993 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700994 boolean clearInitializing, boolean clearSwitching) {
995 boolean unfrozen = false;
996 synchronized (mService) {
997 if (clearInitializing) {
998 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700999 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001000 }
1001 if (clearSwitching) {
1002 uss.switching = false;
1003 }
1004 if (!uss.switching && !uss.initializing) {
1005 mService.mWindowManager.stopFreezingScreen();
1006 unfrozen = true;
1007 }
1008 }
1009 if (unfrozen) {
1010 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
1011 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
1012 newUserId, 0));
1013 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +01001014 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001015 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001016 }
1017
1018 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
1019 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
1020 if (homeInFront) {
1021 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
1022 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001023 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001024 }
1025 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001026 getUserManager().onUserForeground(newUserId);
1027 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1028 }
1029
1030 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1031 long ident = Binder.clearCallingIdentity();
1032 try {
1033 Intent intent;
1034 if (oldUserId >= 0) {
1035 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
1036 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
1037 int count = profiles.size();
1038 for (int i = 0; i < count; i++) {
1039 int profileUserId = profiles.get(i).id;
1040 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1041 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1042 | Intent.FLAG_RECEIVER_FOREGROUND);
1043 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1044 mService.broadcastIntentLocked(null, null, intent,
1045 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1046 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1047 }
1048 }
1049 if (newUserId >= 0) {
1050 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
1051 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
1052 int count = profiles.size();
1053 for (int i = 0; i < count; i++) {
1054 int profileUserId = profiles.get(i).id;
1055 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1056 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1057 | Intent.FLAG_RECEIVER_FOREGROUND);
1058 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1059 mService.broadcastIntentLocked(null, null, intent,
1060 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1061 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1062 }
1063 intent = new Intent(Intent.ACTION_USER_SWITCHED);
1064 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1065 | Intent.FLAG_RECEIVER_FOREGROUND);
1066 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
1067 mService.broadcastIntentLocked(null, null, intent,
1068 null, null, 0, null, null,
1069 new String[] {android.Manifest.permission.MANAGE_USERS},
1070 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1071 UserHandle.USER_ALL);
1072 }
1073 } finally {
1074 Binder.restoreCallingIdentity(ident);
1075 }
1076 }
1077
1078
1079 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1080 int allowMode, String name, String callerPackage) {
1081 final int callingUserId = UserHandle.getUserId(callingUid);
1082 if (callingUserId == userId) {
1083 return userId;
1084 }
1085
1086 // Note that we may be accessing mCurrentUserId outside of a lock...
1087 // shouldn't be a big deal, if this is being called outside
1088 // of a locked context there is intrinsically a race with
1089 // the value the caller will receive and someone else changing it.
1090 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1091 // we will switch to the calling user if access to the current user fails.
1092 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1093
1094 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1095 final boolean allow;
1096 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1097 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1098 // If the caller has this permission, they always pass go. And collect $200.
1099 allow = true;
1100 } else if (allowMode == ALLOW_FULL_ONLY) {
1101 // We require full access, sucks to be you.
1102 allow = false;
1103 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1104 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1105 // If the caller does not have either permission, they are always doomed.
1106 allow = false;
1107 } else if (allowMode == ALLOW_NON_FULL) {
1108 // We are blanket allowing non-full access, you lucky caller!
1109 allow = true;
1110 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1111 // We may or may not allow this depending on whether the two users are
1112 // in the same profile.
1113 allow = isSameProfileGroup(callingUserId, targetUserId);
1114 } else {
1115 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1116 }
1117 if (!allow) {
1118 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1119 // In this case, they would like to just execute as their
1120 // owner user instead of failing.
1121 targetUserId = callingUserId;
1122 } else {
1123 StringBuilder builder = new StringBuilder(128);
1124 builder.append("Permission Denial: ");
1125 builder.append(name);
1126 if (callerPackage != null) {
1127 builder.append(" from ");
1128 builder.append(callerPackage);
1129 }
1130 builder.append(" asks to run as user ");
1131 builder.append(userId);
1132 builder.append(" but is calling from user ");
1133 builder.append(UserHandle.getUserId(callingUid));
1134 builder.append("; this requires ");
1135 builder.append(INTERACT_ACROSS_USERS_FULL);
1136 if (allowMode != ALLOW_FULL_ONLY) {
1137 builder.append(" or ");
1138 builder.append(INTERACT_ACROSS_USERS);
1139 }
1140 String msg = builder.toString();
1141 Slog.w(TAG, msg);
1142 throw new SecurityException(msg);
1143 }
1144 }
1145 }
1146 if (!allowAll && targetUserId < 0) {
1147 throw new IllegalArgumentException(
1148 "Call does not support special user #" + targetUserId);
1149 }
1150 // Check shell permission
1151 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1152 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1153 throw new SecurityException("Shell does not have permission to access user "
1154 + targetUserId + "\n " + Debug.getCallers(3));
1155 }
1156 }
1157 return targetUserId;
1158 }
1159
1160 int unsafeConvertIncomingUserLocked(int userId) {
1161 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1162 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001163 }
1164
1165 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1166 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1167 != PackageManager.PERMISSION_GRANTED) {
1168 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1169 + Binder.getCallingPid()
1170 + ", uid=" + Binder.getCallingUid()
1171 + " requires " + INTERACT_ACROSS_USERS_FULL;
1172 Slog.w(TAG, msg);
1173 throw new SecurityException(msg);
1174 }
1175
1176 mUserSwitchObservers.register(observer);
1177 }
1178
1179 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1180 mUserSwitchObservers.unregister(observer);
1181 }
1182
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001183 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001184 return mStartedUsers.get(userId);
1185 }
1186
1187 boolean hasStartedUserState(int userId) {
1188 return mStartedUsers.get(userId) != null;
1189 }
1190
1191 private void updateStartedUserArrayLocked() {
1192 int num = 0;
1193 for (int i = 0; i < mStartedUsers.size(); i++) {
1194 UserState uss = mStartedUsers.valueAt(i);
1195 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001196 if (uss.state != UserState.STATE_STOPPING
1197 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001198 num++;
1199 }
1200 }
1201 mStartedUserArray = new int[num];
1202 num = 0;
1203 for (int i = 0; i < mStartedUsers.size(); i++) {
1204 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001205 if (uss.state != UserState.STATE_STOPPING
1206 && uss.state != UserState.STATE_SHUTDOWN) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -08001207 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001208 }
1209 }
1210 }
1211
1212 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1213 for (int i = 0; i < mStartedUsers.size(); i++) {
1214 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001215 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001216 }
1217 }
1218
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001219 void onSystemReady() {
1220 updateCurrentProfileIdsLocked();
1221 mUserSetupCompleteContentObserver.register(mService.mContext.getContentResolver());
1222 }
1223
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001224 /**
1225 * Refreshes the list of users related to the current user when either a
1226 * user switch happens or when a new related user is started in the
1227 * background.
1228 */
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001229 private void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001230 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001231 false /* enabledOnly */);
1232 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1233 for (int i = 0; i < currentProfileIds.length; i++) {
1234 currentProfileIds[i] = profiles.get(i).id;
1235 }
1236 mCurrentProfileIds = currentProfileIds;
1237
1238 synchronized (mUserProfileGroupIdsSelfLocked) {
1239 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001240 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001241 for (int i = 0; i < users.size(); i++) {
1242 UserInfo user = users.get(i);
1243 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1244 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1245 }
1246 }
1247 }
1248 }
1249
1250 int[] getStartedUserArrayLocked() {
1251 return mStartedUserArray;
1252 }
1253
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001254 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001255 UserState state = getStartedUserStateLocked(userId);
1256 if (state == null) {
1257 return false;
1258 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001259 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001260 return true;
1261 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001262
1263 final boolean unlocked;
1264 switch (state.state) {
1265 case UserState.STATE_STOPPING:
1266 case UserState.STATE_SHUTDOWN:
1267 default:
1268 return false;
1269
1270 case UserState.STATE_BOOTING:
1271 case UserState.STATE_RUNNING_LOCKED:
1272 unlocked = false;
1273 break;
1274
1275 case UserState.STATE_RUNNING:
1276 unlocked = true;
1277 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001278 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001279
1280 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1281 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001282 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001283 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1284 return unlocked;
1285 }
1286
1287 // One way or another, we're running!
1288 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001289 }
1290
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001291 UserInfo getCurrentUser() {
1292 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1293 != PackageManager.PERMISSION_GRANTED) && (
1294 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1295 != PackageManager.PERMISSION_GRANTED)) {
1296 String msg = "Permission Denial: getCurrentUser() from pid="
1297 + Binder.getCallingPid()
1298 + ", uid=" + Binder.getCallingUid()
1299 + " requires " + INTERACT_ACROSS_USERS;
1300 Slog.w(TAG, msg);
1301 throw new SecurityException(msg);
1302 }
1303 synchronized (mService) {
1304 return getCurrentUserLocked();
1305 }
1306 }
1307
1308 UserInfo getCurrentUserLocked() {
1309 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001310 return getUserInfo(userId);
1311 }
1312
1313 int getCurrentOrTargetUserIdLocked() {
1314 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001315 }
1316
1317 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001318 return mCurrentUserId;
1319 }
1320
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001321 private boolean isCurrentUserLocked(int userId) {
Amith Yamasani458ac462015-12-18 11:21:31 -08001322 return userId == getCurrentOrTargetUserIdLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001323 }
1324
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001325 int setTargetUserIdLocked(int targetUserId) {
1326 return mTargetUserId = targetUserId;
1327 }
1328
1329 int[] getUsers() {
1330 UserManagerService ums = getUserManager();
1331 return ums != null ? ums.getUserIds() : new int[] { 0 };
1332 }
1333
1334 UserInfo getUserInfo(int userId) {
1335 return getUserManager().getUserInfo(userId);
1336 }
1337
1338 int[] getUserIds() {
1339 return getUserManager().getUserIds();
1340 }
1341
1342 boolean exists(int userId) {
1343 return getUserManager().exists(userId);
1344 }
1345
1346 boolean hasUserRestriction(String restriction, int userId) {
1347 return getUserManager().hasUserRestriction(restriction, userId);
1348 }
1349
1350 Set<Integer> getProfileIds(int userId) {
1351 Set<Integer> userIds = new HashSet<>();
1352 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1353 false /* enabledOnly */);
1354 for (UserInfo user : profiles) {
1355 userIds.add(user.id);
1356 }
1357 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001358 }
1359
1360 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1361 synchronized (mUserProfileGroupIdsSelfLocked) {
1362 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1363 UserInfo.NO_PROFILE_GROUP_ID);
1364 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1365 UserInfo.NO_PROFILE_GROUP_ID);
1366 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1367 && callingProfile == targetProfile;
1368 }
1369 }
1370
1371 boolean isCurrentProfileLocked(int userId) {
1372 return ArrayUtils.contains(mCurrentProfileIds, userId);
1373 }
1374
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001375 int[] getCurrentProfileIdsLocked() {
1376 return mCurrentProfileIds;
1377 }
1378
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001379 /**
1380 * Returns whether the given user requires credential entry at this time. This is used to
1381 * intercept activity launches for work apps when the Work Challenge is present.
1382 */
1383 boolean shouldConfirmCredentials(int userId) {
Rubin Xub93522a2016-02-23 18:21:48 +00001384 synchronized (mService) {
1385 if (mStartedUsers.get(userId) == null) {
1386 return false;
1387 }
1388 }
Clara Bayarria1771112015-12-18 16:29:18 +00001389 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001390 return false;
1391 }
1392 final KeyguardManager km = (KeyguardManager) mService.mContext
1393 .getSystemService(KEYGUARD_SERVICE);
Clara Bayarria1771112015-12-18 16:29:18 +00001394 return km.isDeviceLocked(userId);
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001395 }
1396
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001397 void dump(PrintWriter pw, boolean dumpAll) {
1398 pw.println(" mStartedUsers:");
1399 for (int i = 0; i < mStartedUsers.size(); i++) {
1400 UserState uss = mStartedUsers.valueAt(i);
1401 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1402 pw.print(": "); uss.dump("", pw);
1403 }
1404 pw.print(" mStartedUserArray: [");
1405 for (int i = 0; i < mStartedUserArray.length; i++) {
1406 if (i > 0) pw.print(", ");
1407 pw.print(mStartedUserArray[i]);
1408 }
1409 pw.println("]");
1410 pw.print(" mUserLru: [");
1411 for (int i = 0; i < mUserLru.size(); i++) {
1412 if (i > 0) pw.print(", ");
1413 pw.print(mUserLru.get(i));
1414 }
1415 pw.println("]");
1416 if (dumpAll) {
1417 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1418 }
1419 synchronized (mUserProfileGroupIdsSelfLocked) {
1420 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1421 pw.println(" mUserProfileGroupIds:");
1422 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1423 pw.print(" User #");
1424 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1425 pw.print(" -> profile #");
1426 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1427 }
1428 }
1429 }
1430 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001431}