blob: a355fa4750eb88229291e660d0ce365e2c9d7ce6 [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;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080071import android.os.storage.IMountService;
72import android.os.storage.StorageManager;
Wale Ogunwalef80170f2016-02-04 15:12:29 -080073import android.provider.Settings;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070074import android.util.IntArray;
Suprabh Shukla4fe508b2015-11-20 18:22:57 -080075import android.util.Pair;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070076import android.util.Slog;
77import android.util.SparseArray;
Wale Ogunwalef80170f2016-02-04 15:12:29 -080078import android.util.SparseBooleanArray;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070079import android.util.SparseIntArray;
80
81import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080082import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070083import com.android.internal.util.ArrayUtils;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000084import com.android.internal.widget.LockPatternUtils;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070085import com.android.server.pm.UserManagerService;
86
87import java.io.PrintWriter;
88import java.util.ArrayList;
89import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070090import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070091import java.util.List;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070092import java.util.Set;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070093
94/**
95 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
96 */
97final class UserController {
98 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
99 // Maximum number of users we allow to be running at a time.
100 static final int MAX_RUNNING_USERS = 3;
101
102 // Amount of time we wait for observers to handle a user switch before
103 // giving up on them and unfreezing the screen.
104 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
105
106 private final ActivityManagerService mService;
107 private final Handler mHandler;
108
109 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700110 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700111 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700112 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700113
114 /**
115 * Which users have been started, so are allowed to run code.
116 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800117 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700118 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800119
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700120 /**
121 * LRU list of history of current users. Most recently current is at the end.
122 */
123 private final ArrayList<Integer> mUserLru = new ArrayList<>();
124
125 /**
126 * Constant array of the users that are currently started.
127 */
128 private int[] mStartedUserArray = new int[] { 0 };
129
130 // If there are multiple profiles for the current user, their ids are here
131 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700132 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700133
134 /**
135 * Mapping from each known user ID to the profile group ID it is associated with.
136 */
137 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
138
139 /**
140 * Registered observers of the user switching mechanics.
141 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700142 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700143 = new RemoteCallbackList<>();
144
145 /**
146 * Currently active user switch.
147 */
148 Object mCurUserSwitchCallback;
149
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700150 private volatile UserManagerService mUserManager;
151
Clara Bayarria1771112015-12-18 16:29:18 +0000152 private final LockPatternUtils mLockPatternUtils;
153
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800154 // Set of users who have completed the set-up process.
155 private final SparseBooleanArray mSetupCompletedUsers = new SparseBooleanArray();
156 private final UserSetupCompleteContentObserver mUserSetupCompleteContentObserver;
157
158 private class UserSetupCompleteContentObserver extends ContentObserver {
159 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(USER_SETUP_COMPLETE);
160
161 public UserSetupCompleteContentObserver(Handler handler) {
162 super(handler);
163 }
164
165 void register(ContentResolver resolver) {
166 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
167 synchronized (mService) {
168 updateCurrentUserSetupCompleteLocked();
169 }
170 }
171
172 @Override
173 public void onChange(boolean selfChange, Uri uri) {
174 if (mUserSetupComplete.equals(uri)) {
175 synchronized (mService) {
176 updateCurrentUserSetupCompleteLocked();
177 }
178 }
179 }
180 }
181
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700182 UserController(ActivityManagerService service) {
183 mService = service;
184 mHandler = mService.mHandler;
185 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800186 final UserState uss = new UserState(UserHandle.SYSTEM);
187 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700188 mUserLru.add(UserHandle.USER_SYSTEM);
Clara Bayarria1771112015-12-18 16:29:18 +0000189 mLockPatternUtils = new LockPatternUtils(mService.mContext);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700190 updateStartedUserArrayLocked();
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800191 mUserSetupCompleteContentObserver = new UserSetupCompleteContentObserver(mHandler);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700192 }
193
194 void finishUserSwitch(UserState uss) {
195 synchronized (mService) {
196 finishUserBoot(uss);
197
198 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700199 stopRunningUsersLocked(MAX_RUNNING_USERS);
200 }
201 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700202
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700203 void stopRunningUsersLocked(int maxRunningUsers) {
204 int num = mUserLru.size();
205 int i = 0;
206 while (num > maxRunningUsers && i < mUserLru.size()) {
207 Integer oldUserId = mUserLru.get(i);
208 UserState oldUss = mStartedUsers.get(oldUserId);
209 if (oldUss == null) {
210 // Shouldn't happen, but be sane if it does.
211 mUserLru.remove(i);
212 num--;
213 continue;
214 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700215 if (oldUss.state == UserState.STATE_STOPPING
216 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700217 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700218 num--;
219 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700220 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700221 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700222 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
223 // Owner/System user and current user can't be stopped. We count it as running
224 // when it is not a pure system user.
225 if (UserInfo.isSystemOnly(oldUserId)) {
226 num--;
227 }
228 i++;
229 continue;
230 }
231 // This is a user to be stopped.
232 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
233 num--;
234 }
235 num--;
236 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700237 }
238 }
239
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800240 private void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700241 finishUserBoot(uss, null);
242 }
243
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800244 private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700245 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700246 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700247 // Bail if we ended up with a stale user
248 if (mStartedUsers.get(userId) != uss) return;
249
250 // We always walk through all the user lifecycle states to send
251 // consistent developer events. We step into RUNNING_LOCKED here,
252 // but we might immediately step into RUNNING below if the user
253 // storage is already unlocked.
254 if (uss.state == UserState.STATE_BOOTING) {
255 uss.setState(UserState.STATE_RUNNING_LOCKED);
256
257 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700258 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeya242f822015-12-17 15:38:20 -0700259 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
260 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700261 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
262 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
263 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
264 }
265
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700266 maybeUnlockUser(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700267 }
268 }
269
270 /**
271 * Consider stepping from {@link UserState#STATE_RUNNING_LOCKED} into
272 * {@link UserState#STATE_RUNNING}, which only occurs if the user storage is
273 * actually unlocked.
274 */
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700275 void finishUserUnlock(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700276 final int userId = uss.mHandle.getIdentifier();
277 synchronized (mService) {
278 // Bail if we ended up with a stale user
279 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
280
281 // Only keep marching forward if user is actually unlocked
282 if (!isUserKeyUnlocked(userId)) return;
283
284 if (uss.state == UserState.STATE_RUNNING_LOCKED) {
285 uss.setState(UserState.STATE_RUNNING);
286
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700287 // Give user manager a chance to prepare app storage
288 mUserManager.onBeforeUnlockUser(userId);
289
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700290 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
291
292 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700293 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700294 unlockedIntent.addFlags(
295 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
296 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
297 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
298 userId);
299
300 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
301 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -0800302 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
303 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700304 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
305 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700306 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700307 }
308 }
309 }
310
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700311 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700312 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
313 != PackageManager.PERMISSION_GRANTED) {
314 String msg = "Permission Denial: switchUser() from pid="
315 + Binder.getCallingPid()
316 + ", uid=" + Binder.getCallingUid()
317 + " requires " + INTERACT_ACROSS_USERS_FULL;
318 Slog.w(TAG, msg);
319 throw new SecurityException(msg);
320 }
321 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
322 throw new IllegalArgumentException("Can't stop system user " + userId);
323 }
324 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
325 userId);
326 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700327 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700328 }
329 }
330
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700331 /**
332 * Stops the user along with its related users. The method calls
333 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
334 */
335 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
336 if (userId == UserHandle.USER_SYSTEM) {
337 return USER_OP_ERROR_IS_SYSTEM;
338 }
339 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700340 return USER_OP_IS_CURRENT;
341 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700342 int[] usersToStop = getUsersToStopLocked(userId);
343 // If one of related users is system or current, no related users should be stopped
344 for (int i = 0; i < usersToStop.length; i++) {
345 int relatedUserId = usersToStop[i];
346 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
347 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
348 + relatedUserId);
349 // We still need to stop the requested user if it's a force stop.
350 if (force) {
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800351 Slog.i(TAG,
352 "Force stop user " + userId + ". Related users will not be stopped");
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700353 stopSingleUserLocked(userId, callback);
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800354 return USER_OP_SUCCESS;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700355 }
356 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
357 }
358 }
359 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
360 for (int userIdToStop : usersToStop) {
361 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
362 }
363 return USER_OP_SUCCESS;
364 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700365
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700366 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
367 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700368 final UserState uss = mStartedUsers.get(userId);
369 if (uss == null) {
370 // User is not started, nothing to do... but we do need to
371 // callback if requested.
372 if (callback != null) {
373 mHandler.post(new Runnable() {
374 @Override
375 public void run() {
376 try {
377 callback.userStopped(userId);
378 } catch (RemoteException e) {
379 }
380 }
381 });
382 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700383 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700384 }
385
386 if (callback != null) {
387 uss.mStopCallbacks.add(callback);
388 }
389
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700390 if (uss.state != UserState.STATE_STOPPING
391 && uss.state != UserState.STATE_SHUTDOWN) {
392 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700393 updateStartedUserArrayLocked();
394
395 long ident = Binder.clearCallingIdentity();
396 try {
397 // We are going to broadcast ACTION_USER_STOPPING and then
398 // once that is done send a final ACTION_SHUTDOWN and then
399 // stop the user.
400 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
401 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
402 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
403 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
404 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
405 // This is the result receiver for the final shutdown broadcast.
406 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
407 @Override
408 public void performReceive(Intent intent, int resultCode, String data,
409 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
410 finishUserStop(uss);
411 }
412 };
413 // This is the result receiver for the initial stopping broadcast.
414 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
415 @Override
416 public void performReceive(Intent intent, int resultCode, String data,
417 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
418 // On to the next.
419 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700420 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700421 // Whoops, we are being started back up. Abort, abort!
422 return;
423 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700424 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700425 }
426 mService.mBatteryStatsService.noteEvent(
427 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
428 Integer.toString(userId), userId);
429 mService.mSystemServiceManager.stopUser(userId);
430 mService.broadcastIntentLocked(null, null, shutdownIntent,
431 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700432 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700433 }
434 };
435 // Kick things off.
436 mService.broadcastIntentLocked(null, null, stoppingIntent,
437 null, stoppingReceiver, 0, null, null,
438 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700439 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700440 } finally {
441 Binder.restoreCallingIdentity(ident);
442 }
443 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700444 }
445
446 void finishUserStop(UserState uss) {
447 final int userId = uss.mHandle.getIdentifier();
448 boolean stopped;
449 ArrayList<IStopUserCallback> callbacks;
450 synchronized (mService) {
451 callbacks = new ArrayList<>(uss.mStopCallbacks);
452 if (mStartedUsers.get(userId) != uss) {
453 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700454 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700455 stopped = false;
456 } else {
457 stopped = true;
458 // User can no longer run.
459 mStartedUsers.remove(userId);
460 mUserLru.remove(Integer.valueOf(userId));
461 updateStartedUserArrayLocked();
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800462 mSetupCompletedUsers.delete(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700463
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800464 mService.onUserStoppedLocked(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700465 // Clean up all state and processes associated with the user.
466 // Kill all the processes for the user.
467 forceStopUserLocked(userId, "finish user");
468 }
469 }
470
471 for (int i = 0; i < callbacks.size(); i++) {
472 try {
473 if (stopped) callbacks.get(i).userStopped(userId);
474 else callbacks.get(i).userStopAborted(userId);
475 } catch (RemoteException e) {
476 }
477 }
478
479 if (stopped) {
480 mService.mSystemServiceManager.cleanupUser(userId);
481 synchronized (mService) {
482 mService.mStackSupervisor.removeUserLocked(userId);
483 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100484 // Remove the user if it is ephemeral.
485 if (getUserInfo(userId).isEphemeral()) {
486 mUserManager.removeUser(userId);
487 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700488 }
489 }
490
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700491 /**
492 * Determines the list of users that should be stopped together with the specified
493 * {@code userId}. The returned list includes {@code userId}.
494 */
495 private @NonNull int[] getUsersToStopLocked(int userId) {
496 int startedUsersSize = mStartedUsers.size();
497 IntArray userIds = new IntArray();
498 userIds.add(userId);
499 synchronized (mUserProfileGroupIdsSelfLocked) {
500 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
501 UserInfo.NO_PROFILE_GROUP_ID);
502 for (int i = 0; i < startedUsersSize; i++) {
503 UserState uss = mStartedUsers.valueAt(i);
504 int startedUserId = uss.mHandle.getIdentifier();
505 // Skip unrelated users (profileGroupId mismatch)
506 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
507 UserInfo.NO_PROFILE_GROUP_ID);
508 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
509 && (userGroupId == startedUserGroupId);
510 // userId has already been added
511 boolean sameUserId = startedUserId == userId;
512 if (!sameGroup || sameUserId) {
513 continue;
514 }
515 userIds.add(startedUserId);
516 }
517 }
518 return userIds.toArray();
519 }
520
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700521 private void forceStopUserLocked(int userId, String reason) {
522 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
523 userId, reason);
524 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
525 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
526 | Intent.FLAG_RECEIVER_FOREGROUND);
527 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
528 mService.broadcastIntentLocked(null, null, intent,
529 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700530 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700531 }
532
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700533 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100534 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700535 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100536 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700537 synchronized (mService) {
538 final int num = mUserLru.size();
539 for (int i = 0; i < num; i++) {
540 Integer oldUserId = mUserLru.get(i);
541 UserState oldUss = mStartedUsers.get(oldUserId);
542 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700543 || oldUss.state == UserState.STATE_STOPPING
544 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700545 continue;
546 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700547 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100548 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700549 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700550 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700551 break;
552 }
553 }
554 }
555 }
556
557 void startProfilesLocked() {
558 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700559 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700560 mCurrentUserId, false /* enabledOnly */);
561 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
562 for (UserInfo user : profiles) {
563 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
Rubin Xuf13c9802016-01-21 18:06:00 +0000564 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700565 profilesToStart.add(user);
566 }
567 }
568 final int profilesToStartSize = profilesToStart.size();
569 int i = 0;
570 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
571 startUser(profilesToStart.get(i).id, /* foreground= */ false);
572 }
573 if (i < profilesToStartSize) {
574 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
575 }
576 }
577
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700578 private UserManagerService getUserManager() {
579 UserManagerService userManager = mUserManager;
580 if (userManager == null) {
581 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
582 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
583 }
584 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700585 }
586
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700587 private IMountService getMountService() {
588 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
589 }
590
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700591 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700592 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800593 if (mountService != null) {
594 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700595 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800596 } catch (RemoteException e) {
597 throw e.rethrowAsRuntimeException();
598 }
599 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700600 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
601 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800602 }
603 }
604
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700605 boolean startUser(final int userId, final boolean foreground) {
606 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
607 != PackageManager.PERMISSION_GRANTED) {
608 String msg = "Permission Denial: switchUser() from pid="
609 + Binder.getCallingPid()
610 + ", uid=" + Binder.getCallingUid()
611 + " requires " + INTERACT_ACROSS_USERS_FULL;
612 Slog.w(TAG, msg);
613 throw new SecurityException(msg);
614 }
615
616 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
617
618 final long ident = Binder.clearCallingIdentity();
619 try {
620 synchronized (mService) {
621 final int oldUserId = mCurrentUserId;
622 if (oldUserId == userId) {
623 return true;
624 }
625
626 mService.mStackSupervisor.setLockTaskModeLocked(null,
627 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
628
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700629 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700630 if (userInfo == null) {
631 Slog.w(TAG, "No user info for user #" + userId);
632 return false;
633 }
634 if (foreground && userInfo.isManagedProfile()) {
635 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
636 return false;
637 }
638
639 if (foreground) {
640 mService.mWindowManager.startFreezingScreen(
641 R.anim.screen_user_exit, R.anim.screen_user_enter);
642 }
643
644 boolean needStart = false;
645
646 // If the user we are switching to is not currently started, then
647 // we need to start it now.
648 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700649 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700650 updateStartedUserArrayLocked();
651 needStart = true;
652 }
653
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800654 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700655 final Integer userIdInt = userId;
656 mUserLru.remove(userIdInt);
657 mUserLru.add(userIdInt);
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800658 updateCurrentUserSetupCompleteLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700659
660 if (foreground) {
661 mCurrentUserId = userId;
662 mService.updateUserConfigurationLocked();
663 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
664 updateCurrentProfileIdsLocked();
665 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
666 // Once the internal notion of the active user has switched, we lock the device
667 // with the option to show the user switcher on the keyguard.
668 mService.mWindowManager.lockNow(null);
669 } else {
670 final Integer currentUserIdInt = mCurrentUserId;
671 updateCurrentProfileIdsLocked();
672 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
673 mUserLru.remove(currentUserIdInt);
674 mUserLru.add(currentUserIdInt);
675 }
676
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700677 // Make sure user is in the started state. If it is currently
678 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700679 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700680 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
681 // so we can just fairly silently bring the user back from
682 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700683 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700684 updateStartedUserArrayLocked();
685 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700686 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700687 // This means ACTION_SHUTDOWN has been sent, so we will
688 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700689 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700690 updateStartedUserArrayLocked();
691 needStart = true;
692 }
693
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700694 if (uss.state == UserState.STATE_BOOTING) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700695 // Give user manager a chance to propagate user restrictions
696 // to other services and prepare app storage
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800697 getUserManager().onBeforeStartUser(userId);
698
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700699 // Booting up a new user, need to tell system services about it.
700 // Note that this is on the same handler as scheduling of broadcasts,
701 // which is important because it needs to go first.
702 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
703 }
704
705 if (foreground) {
706 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
707 oldUserId));
708 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
709 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
710 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
711 oldUserId, userId, uss));
712 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
713 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
714 }
715
716 if (needStart) {
717 // Send USER_STARTED broadcast
718 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
719 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
720 | Intent.FLAG_RECEIVER_FOREGROUND);
721 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
722 mService.broadcastIntentLocked(null, null, intent,
723 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700724 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700725 }
726
727 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
728 if (userId != UserHandle.USER_SYSTEM) {
729 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
730 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
731 mService.broadcastIntentLocked(null, null, intent, null,
732 new IIntentReceiver.Stub() {
733 public void performReceive(Intent intent, int resultCode,
734 String data, Bundle extras, boolean ordered,
735 boolean sticky, int sendingUser) {
736 onUserInitialized(uss, foreground, oldUserId, userId);
737 }
738 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700739 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700740 uss.initializing = true;
741 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700742 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700743 }
744 }
745
746 if (foreground) {
747 if (!uss.initializing) {
748 moveUserToForegroundLocked(uss, oldUserId, userId);
749 }
750 } else {
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800751 mService.mUserController.finishUserBoot(uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700752 }
753
754 if (needStart) {
755 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
756 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
757 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
758 mService.broadcastIntentLocked(null, null, intent,
759 null, new IIntentReceiver.Stub() {
760 @Override
761 public void performReceive(Intent intent, int resultCode,
762 String data, Bundle extras, boolean ordered, boolean sticky,
763 int sendingUser) throws RemoteException {
764 }
765 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700766 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
767 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700768 }
769 }
770 } finally {
771 Binder.restoreCallingIdentity(ident);
772 }
773
774 return true;
775 }
776
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700777 /**
778 * Start user, if its not already running, and bring it to foreground.
779 */
780 boolean startUserInForeground(final int userId, Dialog dlg) {
781 boolean result = startUser(userId, /* foreground */ true);
782 dlg.dismiss();
783 return result;
784 }
785
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000786 boolean unlockUser(final int userId, byte[] token, byte[] secret) {
Jeff Sharkeyba512352015-11-12 20:17:45 -0800787 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
788 != PackageManager.PERMISSION_GRANTED) {
789 String msg = "Permission Denial: unlockUser() from pid="
790 + Binder.getCallingPid()
791 + ", uid=" + Binder.getCallingUid()
792 + " requires " + INTERACT_ACROSS_USERS_FULL;
793 Slog.w(TAG, msg);
794 throw new SecurityException(msg);
795 }
796
Jeff Sharkey8924e872015-11-30 12:52:10 -0700797 final long binderToken = Binder.clearCallingIdentity();
798 try {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000799 return unlockUserCleared(userId, token, secret);
Jeff Sharkey8924e872015-11-30 12:52:10 -0700800 } finally {
801 Binder.restoreCallingIdentity(binderToken);
802 }
803 }
804
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700805 /**
806 * Attempt to unlock user without a credential token. This typically
807 * succeeds when the device doesn't have credential-encrypted storage, or
808 * when the the credential-encrypted storage isn't tied to a user-provided
809 * PIN or pattern.
810 */
811 boolean maybeUnlockUser(final int userId) {
812 // Try unlocking storage using empty token
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000813 return unlockUserCleared(userId, null, null);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700814 }
815
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000816 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret) {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700817 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700818 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700819 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700820 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700821 }
822
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700823 if (!isUserKeyUnlocked(userId)) {
824 final UserInfo userInfo = getUserInfo(userId);
825 final IMountService mountService = getMountService();
826 try {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000827 mountService.unlockUserKey(userId, userInfo.serialNumber, token, secret);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700828 } catch (RemoteException | RuntimeException e) {
829 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
830 return false;
831 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800832 }
833
834 synchronized (mService) {
835 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700836 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800837 }
838
839 return true;
840 }
841
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800842 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700843 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800844 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
845 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700846 d.show();
847 }
848
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700849 void dispatchForegroundProfileChanged(int userId) {
850 final int observerCount = mUserSwitchObservers.beginBroadcast();
851 for (int i = 0; i < observerCount; i++) {
852 try {
853 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
854 } catch (RemoteException e) {
855 // Ignore
856 }
857 }
858 mUserSwitchObservers.finishBroadcast();
859 }
860
861 /** Called on handler thread */
862 void dispatchUserSwitchComplete(int userId) {
863 final int observerCount = mUserSwitchObservers.beginBroadcast();
864 for (int i = 0; i < observerCount; i++) {
865 try {
866 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
867 } catch (RemoteException e) {
868 }
869 }
870 mUserSwitchObservers.finishBroadcast();
871 }
872
Wale Ogunwalef80170f2016-02-04 15:12:29 -0800873 void updateCurrentUserSetupCompleteLocked() {
874 final ContentResolver cr = mService.mContext.getContentResolver();
875 final boolean setupComplete =
876 Settings.Secure.getIntForUser(cr, USER_SETUP_COMPLETE, 0, mCurrentUserId) != 0;
877 mSetupCompletedUsers.put(mCurrentUserId, setupComplete);
878 }
879
880 boolean isUserSetupCompleteLocked(int userId) {
881 return mSetupCompletedUsers.get(userId);
882 }
883
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700884 private void stopBackgroundUsersIfEnforced(int oldUserId) {
885 // Never stop system user
886 if (oldUserId == UserHandle.USER_SYSTEM) {
887 return;
888 }
889 // For now, only check for user restriction. Additional checks can be added here
890 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
891 oldUserId);
892 if (!disallowRunInBg) {
893 return;
894 }
895 synchronized (mService) {
896 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
897 + " and related users");
898 stopUsersLocked(oldUserId, false, null);
899 }
900 }
901
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700902 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
903 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800904 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700905 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
906 }
907 }
908
909 void dispatchUserSwitch(final UserState uss, final int oldUserId,
910 final int newUserId) {
911 final int observerCount = mUserSwitchObservers.beginBroadcast();
912 if (observerCount > 0) {
913 final IRemoteCallback callback = new IRemoteCallback.Stub() {
914 int mCount = 0;
915 @Override
916 public void sendResult(Bundle data) throws RemoteException {
917 synchronized (mService) {
918 if (mCurUserSwitchCallback == this) {
919 mCount++;
920 if (mCount == observerCount) {
921 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
922 }
923 }
924 }
925 }
926 };
927 synchronized (mService) {
928 uss.switching = true;
929 mCurUserSwitchCallback = callback;
930 }
931 for (int i = 0; i < observerCount; i++) {
932 try {
933 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
934 newUserId, callback);
935 } catch (RemoteException e) {
936 }
937 }
938 } else {
939 synchronized (mService) {
940 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
941 }
942 }
943 mUserSwitchObservers.finishBroadcast();
944 }
945
946 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
947 mCurUserSwitchCallback = null;
948 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
949 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
950 oldUserId, newUserId, uss));
951 }
952
953 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700954 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700955 }
956
957 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
958 synchronized (mService) {
959 if (foreground) {
960 moveUserToForegroundLocked(uss, oldUserId, newUserId);
961 }
962 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700963 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700964 }
965
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700966 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700967 boolean clearInitializing, boolean clearSwitching) {
968 boolean unfrozen = false;
969 synchronized (mService) {
970 if (clearInitializing) {
971 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700972 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700973 }
974 if (clearSwitching) {
975 uss.switching = false;
976 }
977 if (!uss.switching && !uss.initializing) {
978 mService.mWindowManager.stopFreezingScreen();
979 unfrozen = true;
980 }
981 }
982 if (unfrozen) {
983 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
984 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
985 newUserId, 0));
986 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100987 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700988 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700989 }
990
991 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
992 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
993 if (homeInFront) {
994 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
995 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800996 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700997 }
998 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700999 getUserManager().onUserForeground(newUserId);
1000 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1001 }
1002
1003 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1004 long ident = Binder.clearCallingIdentity();
1005 try {
1006 Intent intent;
1007 if (oldUserId >= 0) {
1008 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
1009 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
1010 int count = profiles.size();
1011 for (int i = 0; i < count; i++) {
1012 int profileUserId = profiles.get(i).id;
1013 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1014 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1015 | Intent.FLAG_RECEIVER_FOREGROUND);
1016 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1017 mService.broadcastIntentLocked(null, null, intent,
1018 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1019 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1020 }
1021 }
1022 if (newUserId >= 0) {
1023 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
1024 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
1025 int count = profiles.size();
1026 for (int i = 0; i < count; i++) {
1027 int profileUserId = profiles.get(i).id;
1028 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1029 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1030 | Intent.FLAG_RECEIVER_FOREGROUND);
1031 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1032 mService.broadcastIntentLocked(null, null, intent,
1033 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1034 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1035 }
1036 intent = new Intent(Intent.ACTION_USER_SWITCHED);
1037 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1038 | Intent.FLAG_RECEIVER_FOREGROUND);
1039 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
1040 mService.broadcastIntentLocked(null, null, intent,
1041 null, null, 0, null, null,
1042 new String[] {android.Manifest.permission.MANAGE_USERS},
1043 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1044 UserHandle.USER_ALL);
1045 }
1046 } finally {
1047 Binder.restoreCallingIdentity(ident);
1048 }
1049 }
1050
1051
1052 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1053 int allowMode, String name, String callerPackage) {
1054 final int callingUserId = UserHandle.getUserId(callingUid);
1055 if (callingUserId == userId) {
1056 return userId;
1057 }
1058
1059 // Note that we may be accessing mCurrentUserId outside of a lock...
1060 // shouldn't be a big deal, if this is being called outside
1061 // of a locked context there is intrinsically a race with
1062 // the value the caller will receive and someone else changing it.
1063 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1064 // we will switch to the calling user if access to the current user fails.
1065 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1066
1067 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1068 final boolean allow;
1069 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1070 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1071 // If the caller has this permission, they always pass go. And collect $200.
1072 allow = true;
1073 } else if (allowMode == ALLOW_FULL_ONLY) {
1074 // We require full access, sucks to be you.
1075 allow = false;
1076 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1077 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1078 // If the caller does not have either permission, they are always doomed.
1079 allow = false;
1080 } else if (allowMode == ALLOW_NON_FULL) {
1081 // We are blanket allowing non-full access, you lucky caller!
1082 allow = true;
1083 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1084 // We may or may not allow this depending on whether the two users are
1085 // in the same profile.
1086 allow = isSameProfileGroup(callingUserId, targetUserId);
1087 } else {
1088 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1089 }
1090 if (!allow) {
1091 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1092 // In this case, they would like to just execute as their
1093 // owner user instead of failing.
1094 targetUserId = callingUserId;
1095 } else {
1096 StringBuilder builder = new StringBuilder(128);
1097 builder.append("Permission Denial: ");
1098 builder.append(name);
1099 if (callerPackage != null) {
1100 builder.append(" from ");
1101 builder.append(callerPackage);
1102 }
1103 builder.append(" asks to run as user ");
1104 builder.append(userId);
1105 builder.append(" but is calling from user ");
1106 builder.append(UserHandle.getUserId(callingUid));
1107 builder.append("; this requires ");
1108 builder.append(INTERACT_ACROSS_USERS_FULL);
1109 if (allowMode != ALLOW_FULL_ONLY) {
1110 builder.append(" or ");
1111 builder.append(INTERACT_ACROSS_USERS);
1112 }
1113 String msg = builder.toString();
1114 Slog.w(TAG, msg);
1115 throw new SecurityException(msg);
1116 }
1117 }
1118 }
1119 if (!allowAll && targetUserId < 0) {
1120 throw new IllegalArgumentException(
1121 "Call does not support special user #" + targetUserId);
1122 }
1123 // Check shell permission
1124 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1125 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1126 throw new SecurityException("Shell does not have permission to access user "
1127 + targetUserId + "\n " + Debug.getCallers(3));
1128 }
1129 }
1130 return targetUserId;
1131 }
1132
1133 int unsafeConvertIncomingUserLocked(int userId) {
1134 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1135 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001136 }
1137
1138 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1139 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1140 != PackageManager.PERMISSION_GRANTED) {
1141 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1142 + Binder.getCallingPid()
1143 + ", uid=" + Binder.getCallingUid()
1144 + " requires " + INTERACT_ACROSS_USERS_FULL;
1145 Slog.w(TAG, msg);
1146 throw new SecurityException(msg);
1147 }
1148
1149 mUserSwitchObservers.register(observer);
1150 }
1151
1152 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1153 mUserSwitchObservers.unregister(observer);
1154 }
1155
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001156 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001157 return mStartedUsers.get(userId);
1158 }
1159
1160 boolean hasStartedUserState(int userId) {
1161 return mStartedUsers.get(userId) != null;
1162 }
1163
1164 private void updateStartedUserArrayLocked() {
1165 int num = 0;
1166 for (int i = 0; i < mStartedUsers.size(); i++) {
1167 UserState uss = mStartedUsers.valueAt(i);
1168 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001169 if (uss.state != UserState.STATE_STOPPING
1170 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001171 num++;
1172 }
1173 }
1174 mStartedUserArray = new int[num];
1175 num = 0;
1176 for (int i = 0; i < mStartedUsers.size(); i++) {
1177 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001178 if (uss.state != UserState.STATE_STOPPING
1179 && uss.state != UserState.STATE_SHUTDOWN) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -08001180 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001181 }
1182 }
1183 }
1184
1185 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1186 for (int i = 0; i < mStartedUsers.size(); i++) {
1187 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001188 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001189 }
1190 }
1191
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001192 void onSystemReady() {
1193 updateCurrentProfileIdsLocked();
1194 mUserSetupCompleteContentObserver.register(mService.mContext.getContentResolver());
1195 }
1196
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001197 /**
1198 * Refreshes the list of users related to the current user when either a
1199 * user switch happens or when a new related user is started in the
1200 * background.
1201 */
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001202 private void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001203 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001204 false /* enabledOnly */);
1205 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1206 for (int i = 0; i < currentProfileIds.length; i++) {
1207 currentProfileIds[i] = profiles.get(i).id;
1208 }
1209 mCurrentProfileIds = currentProfileIds;
1210
1211 synchronized (mUserProfileGroupIdsSelfLocked) {
1212 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001213 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001214 for (int i = 0; i < users.size(); i++) {
1215 UserInfo user = users.get(i);
1216 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1217 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1218 }
1219 }
1220 }
1221 }
1222
1223 int[] getStartedUserArrayLocked() {
1224 return mStartedUserArray;
1225 }
1226
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001227 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001228 UserState state = getStartedUserStateLocked(userId);
1229 if (state == null) {
1230 return false;
1231 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001232 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001233 return true;
1234 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001235
1236 final boolean unlocked;
1237 switch (state.state) {
1238 case UserState.STATE_STOPPING:
1239 case UserState.STATE_SHUTDOWN:
1240 default:
1241 return false;
1242
1243 case UserState.STATE_BOOTING:
1244 case UserState.STATE_RUNNING_LOCKED:
1245 unlocked = false;
1246 break;
1247
1248 case UserState.STATE_RUNNING:
1249 unlocked = true;
1250 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001251 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001252
1253 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1254 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001255 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001256 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1257 return unlocked;
1258 }
1259
1260 // One way or another, we're running!
1261 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001262 }
1263
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001264 UserInfo getCurrentUser() {
1265 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1266 != PackageManager.PERMISSION_GRANTED) && (
1267 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1268 != PackageManager.PERMISSION_GRANTED)) {
1269 String msg = "Permission Denial: getCurrentUser() from pid="
1270 + Binder.getCallingPid()
1271 + ", uid=" + Binder.getCallingUid()
1272 + " requires " + INTERACT_ACROSS_USERS;
1273 Slog.w(TAG, msg);
1274 throw new SecurityException(msg);
1275 }
1276 synchronized (mService) {
1277 return getCurrentUserLocked();
1278 }
1279 }
1280
1281 UserInfo getCurrentUserLocked() {
1282 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001283 return getUserInfo(userId);
1284 }
1285
1286 int getCurrentOrTargetUserIdLocked() {
1287 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001288 }
1289
1290 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001291 return mCurrentUserId;
1292 }
1293
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001294 private boolean isCurrentUserLocked(int userId) {
Amith Yamasani458ac462015-12-18 11:21:31 -08001295 return userId == getCurrentOrTargetUserIdLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001296 }
1297
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001298 int setTargetUserIdLocked(int targetUserId) {
1299 return mTargetUserId = targetUserId;
1300 }
1301
1302 int[] getUsers() {
1303 UserManagerService ums = getUserManager();
1304 return ums != null ? ums.getUserIds() : new int[] { 0 };
1305 }
1306
1307 UserInfo getUserInfo(int userId) {
1308 return getUserManager().getUserInfo(userId);
1309 }
1310
1311 int[] getUserIds() {
1312 return getUserManager().getUserIds();
1313 }
1314
1315 boolean exists(int userId) {
1316 return getUserManager().exists(userId);
1317 }
1318
1319 boolean hasUserRestriction(String restriction, int userId) {
1320 return getUserManager().hasUserRestriction(restriction, userId);
1321 }
1322
1323 Set<Integer> getProfileIds(int userId) {
1324 Set<Integer> userIds = new HashSet<>();
1325 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1326 false /* enabledOnly */);
1327 for (UserInfo user : profiles) {
1328 userIds.add(user.id);
1329 }
1330 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001331 }
1332
1333 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1334 synchronized (mUserProfileGroupIdsSelfLocked) {
1335 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1336 UserInfo.NO_PROFILE_GROUP_ID);
1337 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1338 UserInfo.NO_PROFILE_GROUP_ID);
1339 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1340 && callingProfile == targetProfile;
1341 }
1342 }
1343
1344 boolean isCurrentProfileLocked(int userId) {
1345 return ArrayUtils.contains(mCurrentProfileIds, userId);
1346 }
1347
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001348 int[] getCurrentProfileIdsLocked() {
1349 return mCurrentProfileIds;
1350 }
1351
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001352 /**
1353 * Returns whether the given user requires credential entry at this time. This is used to
1354 * intercept activity launches for work apps when the Work Challenge is present.
1355 */
1356 boolean shouldConfirmCredentials(int userId) {
Clara Bayarria1771112015-12-18 16:29:18 +00001357 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001358 return false;
1359 }
1360 final KeyguardManager km = (KeyguardManager) mService.mContext
1361 .getSystemService(KEYGUARD_SERVICE);
Clara Bayarria1771112015-12-18 16:29:18 +00001362 return km.isDeviceLocked(userId);
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001363 }
1364
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001365 void dump(PrintWriter pw, boolean dumpAll) {
1366 pw.println(" mStartedUsers:");
1367 for (int i = 0; i < mStartedUsers.size(); i++) {
1368 UserState uss = mStartedUsers.valueAt(i);
1369 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1370 pw.print(": "); uss.dump("", pw);
1371 }
1372 pw.print(" mStartedUserArray: [");
1373 for (int i = 0; i < mStartedUserArray.length; i++) {
1374 if (i > 0) pw.print(", ");
1375 pw.print(mStartedUserArray[i]);
1376 }
1377 pw.println("]");
1378 pw.print(" mUserLru: [");
1379 for (int i = 0; i < mUserLru.size(); i++) {
1380 if (i > 0) pw.print(", ");
1381 pw.print(mUserLru.get(i));
1382 }
1383 pw.println("]");
1384 if (dumpAll) {
1385 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1386 }
1387 synchronized (mUserProfileGroupIdsSelfLocked) {
1388 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1389 pw.println(" mUserProfileGroupIds:");
1390 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1391 pw.print(" User #");
1392 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1393 pw.print(" -> profile #");
1394 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1395 }
1396 }
1397 }
1398 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001399}