blob: aef454ee6357fcb009993f28d4af5fff5f5365bc [file] [log] [blame]
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.am;
18
19import static android.Manifest.permission.INTERACT_ACROSS_USERS;
20import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070021import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
22import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070023import static android.app.ActivityManager.USER_OP_IS_CURRENT;
24import static android.app.ActivityManager.USER_OP_SUCCESS;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000025import static android.content.Context.KEYGUARD_SERVICE;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070026import static android.os.Process.SYSTEM_UID;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060027
Fyodor Kupolov610acda2015-10-19 18:44:07 -070028import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
29import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
30import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070031import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
32import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
33import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
34import static com.android.server.am.ActivityManagerService.MY_PID;
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;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060041import static com.android.server.am.UserState.STATE_BOOTING;
42import static com.android.server.am.UserState.STATE_RUNNING_LOCKED;
43import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED;
44import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070045
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070046import android.annotation.NonNull;
Tony Mak8c536f92016-03-21 12:20:41 +000047import android.annotation.UserIdInt;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070048import android.app.ActivityManager;
49import android.app.AppOpsManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070050import android.app.Dialog;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070051import android.app.IStopUserCallback;
52import android.app.IUserSwitchObserver;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000053import android.app.KeyguardManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070054import android.content.Context;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070055import android.content.IIntentReceiver;
56import android.content.Intent;
57import android.content.pm.PackageManager;
58import android.content.pm.UserInfo;
59import android.os.BatteryStats;
60import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060061import android.os.Build;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070062import android.os.Bundle;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070063import android.os.Debug;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070064import android.os.Handler;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070065import android.os.IBinder;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070066import android.os.IRemoteCallback;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070067import android.os.IUserManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070068import android.os.Process;
69import android.os.RemoteCallbackList;
70import android.os.RemoteException;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070071import android.os.ServiceManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070072import android.os.UserHandle;
73import android.os.UserManager;
Lenka Trochtova1ddda472016-02-12 10:42:12 +010074import android.os.UserManagerInternal;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080075import android.os.storage.IMountService;
76import android.os.storage.StorageManager;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070077import android.util.IntArray;
Suprabh Shukla4fe508b2015-11-20 18:22:57 -080078import android.util.Pair;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070079import android.util.Slog;
80import android.util.SparseArray;
81import android.util.SparseIntArray;
82
83import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080084import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070085import com.android.internal.util.ArrayUtils;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060086import com.android.internal.util.ProgressReporter;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000087import com.android.internal.widget.LockPatternUtils;
Lenka Trochtova1ddda472016-02-12 10:42:12 +010088import com.android.server.LocalServices;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070089import com.android.server.pm.UserManagerService;
90
91import java.io.PrintWriter;
92import java.util.ArrayList;
93import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070094import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070095import java.util.List;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060096import java.util.Objects;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070097import java.util.Set;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070098
99/**
100 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
101 */
102final class UserController {
103 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
104 // Maximum number of users we allow to be running at a time.
105 static final int MAX_RUNNING_USERS = 3;
106
107 // Amount of time we wait for observers to handle a user switch before
108 // giving up on them and unfreezing the screen.
109 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
110
111 private final ActivityManagerService mService;
112 private final Handler mHandler;
113
114 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700115 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700116 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700117 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700118
119 /**
120 * Which users have been started, so are allowed to run code.
121 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800122 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700123 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800124
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700125 /**
126 * LRU list of history of current users. Most recently current is at the end.
127 */
128 private final ArrayList<Integer> mUserLru = new ArrayList<>();
129
130 /**
131 * Constant array of the users that are currently started.
132 */
133 private int[] mStartedUserArray = new int[] { 0 };
134
135 // If there are multiple profiles for the current user, their ids are here
136 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700137 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700138
139 /**
140 * Mapping from each known user ID to the profile group ID it is associated with.
141 */
142 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
143
144 /**
145 * Registered observers of the user switching mechanics.
146 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700147 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700148 = new RemoteCallbackList<>();
149
150 /**
151 * Currently active user switch.
152 */
153 Object mCurUserSwitchCallback;
154
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700155 private volatile UserManagerService mUserManager;
156
Clara Bayarria1771112015-12-18 16:29:18 +0000157 private final LockPatternUtils mLockPatternUtils;
158
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700159 UserController(ActivityManagerService service) {
160 mService = service;
161 mHandler = mService.mHandler;
162 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800163 final UserState uss = new UserState(UserHandle.SYSTEM);
164 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700165 mUserLru.add(UserHandle.USER_SYSTEM);
Clara Bayarria1771112015-12-18 16:29:18 +0000166 mLockPatternUtils = new LockPatternUtils(mService.mContext);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700167 updateStartedUserArrayLocked();
168 }
169
170 void finishUserSwitch(UserState uss) {
171 synchronized (mService) {
172 finishUserBoot(uss);
173
174 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700175 stopRunningUsersLocked(MAX_RUNNING_USERS);
176 }
177 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700178
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700179 void stopRunningUsersLocked(int maxRunningUsers) {
180 int num = mUserLru.size();
181 int i = 0;
182 while (num > maxRunningUsers && i < mUserLru.size()) {
183 Integer oldUserId = mUserLru.get(i);
184 UserState oldUss = mStartedUsers.get(oldUserId);
185 if (oldUss == null) {
186 // Shouldn't happen, but be sane if it does.
187 mUserLru.remove(i);
188 num--;
189 continue;
190 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700191 if (oldUss.state == UserState.STATE_STOPPING
192 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700193 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700194 num--;
195 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700196 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700197 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700198 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
199 // Owner/System user and current user can't be stopped. We count it as running
200 // when it is not a pure system user.
201 if (UserInfo.isSystemOnly(oldUserId)) {
202 num--;
203 }
204 i++;
205 continue;
206 }
207 // This is a user to be stopped.
208 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
209 num--;
210 }
211 num--;
212 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700213 }
214 }
215
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800216 private void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700217 finishUserBoot(uss, null);
218 }
219
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800220 private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700221 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700222 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700223 // Bail if we ended up with a stale user
224 if (mStartedUsers.get(userId) != uss) return;
225
226 // We always walk through all the user lifecycle states to send
227 // consistent developer events. We step into RUNNING_LOCKED here,
228 // but we might immediately step into RUNNING below if the user
229 // storage is already unlocked.
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600230 if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700231 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700232 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeya242f822015-12-17 15:38:20 -0700233 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
234 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700235 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
236 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
237 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
238 }
239
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700240 maybeUnlockUser(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700241 }
242 }
243
244 /**
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600245 * Step from {@link UserState#STATE_RUNNING_LOCKED} to
246 * {@link UserState#STATE_RUNNING_UNLOCKING}.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700247 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600248 void finishUserUnlocking(final UserState uss, final ProgressReporter progress) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700249 final int userId = uss.mHandle.getIdentifier();
250 synchronized (mService) {
251 // Bail if we ended up with a stale user
252 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
253
254 // Only keep marching forward if user is actually unlocked
255 if (!isUserKeyUnlocked(userId)) return;
256
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600257 if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
258 // Prepare app storage before we go any further
259 progress.setProgress(5, mService.mContext.getString(R.string.android_start_title));
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700260 mUserManager.onBeforeUnlockUser(userId);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600261 progress.setProgress(20);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700262
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600263 // Send PRE_BOOT broadcasts if fingerprint changed
264 final UserInfo info = getUserInfo(userId);
265 if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
266 progress.startSegment(80);
267 new PreBootBroadcaster(mService, userId, progress) {
268 @Override
269 public void onFinished() {
270 finishUserUnlocked(uss, progress);
271 }
272 }.sendNext();
273 } else {
274 finishUserUnlocked(uss, progress);
275 }
276 }
277 }
278 }
279
280 /**
281 * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
282 * {@link UserState#STATE_RUNNING_UNLOCKED}.
283 */
284 void finishUserUnlocked(UserState uss, ProgressReporter progress) {
285 try {
286 finishUserUnlockedInternal(uss);
287 } finally {
288 progress.finish();
289 }
290 }
291
292 void finishUserUnlockedInternal(UserState uss) {
293 final int userId = uss.mHandle.getIdentifier();
294 synchronized (mService) {
295 // Bail if we ended up with a stale user
296 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
297
298 // Only keep marching forward if user is actually unlocked
299 if (!isUserKeyUnlocked(userId)) return;
300
301 if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
302 // Remember that we logged in
303 mUserManager.onUserLoggedIn(userId);
304
305 // Dispatch unlocked to system services
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700306 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
307
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600308 // Dispatch unlocked to external apps
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700309 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700310 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700311 unlockedIntent.addFlags(
312 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
313 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
314 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
315 userId);
316
Kenny Guyb1b30262016-02-09 16:02:35 +0000317 if (getUserInfo(userId).isManagedProfile()) {
318 UserInfo parent = getUserManager().getProfileParent(userId);
319 if (parent != null) {
320 final Intent profileUnlockedIntent = new Intent(
321 Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
Rubin Xub5f00492016-02-15 13:50:18 +0000322 profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
323 profileUnlockedIntent.addFlags(
Kenny Guyb1b30262016-02-09 16:02:35 +0000324 Intent.FLAG_RECEIVER_REGISTERED_ONLY
325 | Intent.FLAG_RECEIVER_FOREGROUND);
326 mService.broadcastIntentLocked(null, null, profileUnlockedIntent,
327 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
328 null, false, false, MY_PID, SYSTEM_UID,
329 parent.id);
330 }
331 }
332
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700333 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
334 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -0800335 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
336 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700337 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
338 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700339 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700340 }
341 }
342 }
343
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700344 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700345 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
346 != PackageManager.PERMISSION_GRANTED) {
347 String msg = "Permission Denial: switchUser() from pid="
348 + Binder.getCallingPid()
349 + ", uid=" + Binder.getCallingUid()
350 + " requires " + INTERACT_ACROSS_USERS_FULL;
351 Slog.w(TAG, msg);
352 throw new SecurityException(msg);
353 }
354 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
355 throw new IllegalArgumentException("Can't stop system user " + userId);
356 }
357 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
358 userId);
359 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700360 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700361 }
362 }
363
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700364 /**
365 * Stops the user along with its related users. The method calls
366 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
367 */
368 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
369 if (userId == UserHandle.USER_SYSTEM) {
370 return USER_OP_ERROR_IS_SYSTEM;
371 }
372 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700373 return USER_OP_IS_CURRENT;
374 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700375 int[] usersToStop = getUsersToStopLocked(userId);
376 // If one of related users is system or current, no related users should be stopped
377 for (int i = 0; i < usersToStop.length; i++) {
378 int relatedUserId = usersToStop[i];
379 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
380 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
381 + relatedUserId);
382 // We still need to stop the requested user if it's a force stop.
383 if (force) {
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800384 Slog.i(TAG,
385 "Force stop user " + userId + ". Related users will not be stopped");
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700386 stopSingleUserLocked(userId, callback);
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800387 return USER_OP_SUCCESS;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700388 }
389 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
390 }
391 }
392 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
393 for (int userIdToStop : usersToStop) {
394 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
395 }
396 return USER_OP_SUCCESS;
397 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700398
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700399 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
400 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700401 final UserState uss = mStartedUsers.get(userId);
402 if (uss == null) {
403 // User is not started, nothing to do... but we do need to
404 // callback if requested.
405 if (callback != null) {
406 mHandler.post(new Runnable() {
407 @Override
408 public void run() {
409 try {
410 callback.userStopped(userId);
411 } catch (RemoteException e) {
412 }
413 }
414 });
415 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700416 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700417 }
418
419 if (callback != null) {
420 uss.mStopCallbacks.add(callback);
421 }
422
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700423 if (uss.state != UserState.STATE_STOPPING
424 && uss.state != UserState.STATE_SHUTDOWN) {
425 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700426 updateStartedUserArrayLocked();
427
428 long ident = Binder.clearCallingIdentity();
429 try {
430 // We are going to broadcast ACTION_USER_STOPPING and then
431 // once that is done send a final ACTION_SHUTDOWN and then
432 // stop the user.
433 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
434 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
435 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
436 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700437 // This is the result receiver for the initial stopping broadcast.
438 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
439 @Override
440 public void performReceive(Intent intent, int resultCode, String data,
441 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Amith Yamasani98c05562016-03-30 13:15:26 -0700442 mHandler.post(new Runnable() {
443 @Override
444 public void run() {
445 finishUserStopping(userId, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700446 }
Amith Yamasani98c05562016-03-30 13:15:26 -0700447 });
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700448 }
449 };
450 // Kick things off.
451 mService.broadcastIntentLocked(null, null, stoppingIntent,
452 null, stoppingReceiver, 0, null, null,
453 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700454 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700455 } finally {
456 Binder.restoreCallingIdentity(ident);
457 }
458 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700459 }
460
Amith Yamasani98c05562016-03-30 13:15:26 -0700461 void finishUserStopping(final int userId, final UserState uss) {
462 // On to the next.
463 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
464 // This is the result receiver for the final shutdown broadcast.
465 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
466 @Override
467 public void performReceive(Intent intent, int resultCode, String data,
468 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
469 mHandler.post(new Runnable() {
470 @Override
471 public void run() {
472 finishUserStopped(uss);
473 }
474 });
475 }
476 };
477
478 synchronized (mService) {
479 if (uss.state != UserState.STATE_STOPPING) {
480 // Whoops, we are being started back up. Abort, abort!
481 return;
482 }
483 uss.setState(UserState.STATE_SHUTDOWN);
484 }
485
486 mService.mBatteryStatsService.noteEvent(
487 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
488 Integer.toString(userId), userId);
489 mService.mSystemServiceManager.stopUser(userId);
490
491 synchronized (mService) {
492 mService.broadcastIntentLocked(null, null, shutdownIntent,
493 null, shutdownReceiver, 0, null, null, null,
494 AppOpsManager.OP_NONE,
495 null, true, false, MY_PID, SYSTEM_UID, userId);
496 }
497 }
498
499 void finishUserStopped(UserState uss) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700500 final int userId = uss.mHandle.getIdentifier();
501 boolean stopped;
502 ArrayList<IStopUserCallback> callbacks;
503 synchronized (mService) {
504 callbacks = new ArrayList<>(uss.mStopCallbacks);
505 if (mStartedUsers.get(userId) != uss) {
506 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700507 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700508 stopped = false;
509 } else {
510 stopped = true;
511 // User can no longer run.
512 mStartedUsers.remove(userId);
513 mUserLru.remove(Integer.valueOf(userId));
514 updateStartedUserArrayLocked();
515
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800516 mService.onUserStoppedLocked(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700517 // Clean up all state and processes associated with the user.
518 // Kill all the processes for the user.
519 forceStopUserLocked(userId, "finish user");
520 }
521 }
522
523 for (int i = 0; i < callbacks.size(); i++) {
524 try {
525 if (stopped) callbacks.get(i).userStopped(userId);
526 else callbacks.get(i).userStopAborted(userId);
527 } catch (RemoteException e) {
528 }
529 }
530
531 if (stopped) {
532 mService.mSystemServiceManager.cleanupUser(userId);
533 synchronized (mService) {
534 mService.mStackSupervisor.removeUserLocked(userId);
535 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100536 // Remove the user if it is ephemeral.
537 if (getUserInfo(userId).isEphemeral()) {
538 mUserManager.removeUser(userId);
539 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700540 }
541 }
542
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700543 /**
544 * Determines the list of users that should be stopped together with the specified
545 * {@code userId}. The returned list includes {@code userId}.
546 */
547 private @NonNull int[] getUsersToStopLocked(int userId) {
548 int startedUsersSize = mStartedUsers.size();
549 IntArray userIds = new IntArray();
550 userIds.add(userId);
551 synchronized (mUserProfileGroupIdsSelfLocked) {
552 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
553 UserInfo.NO_PROFILE_GROUP_ID);
554 for (int i = 0; i < startedUsersSize; i++) {
555 UserState uss = mStartedUsers.valueAt(i);
556 int startedUserId = uss.mHandle.getIdentifier();
557 // Skip unrelated users (profileGroupId mismatch)
558 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
559 UserInfo.NO_PROFILE_GROUP_ID);
560 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
561 && (userGroupId == startedUserGroupId);
562 // userId has already been added
563 boolean sameUserId = startedUserId == userId;
564 if (!sameGroup || sameUserId) {
565 continue;
566 }
567 userIds.add(startedUserId);
568 }
569 }
570 return userIds.toArray();
571 }
572
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700573 private void forceStopUserLocked(int userId, String reason) {
574 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
575 userId, reason);
576 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
577 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
578 | Intent.FLAG_RECEIVER_FOREGROUND);
579 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
580 mService.broadcastIntentLocked(null, null, intent,
581 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700582 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700583 }
584
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700585 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100586 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700587 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100588 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700589 synchronized (mService) {
590 final int num = mUserLru.size();
591 for (int i = 0; i < num; i++) {
592 Integer oldUserId = mUserLru.get(i);
593 UserState oldUss = mStartedUsers.get(oldUserId);
594 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700595 || oldUss.state == UserState.STATE_STOPPING
596 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700597 continue;
598 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700599 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtova1ddda472016-02-12 10:42:12 +0100600 if (userInfo.isEphemeral()) {
601 LocalServices.getService(UserManagerInternal.class)
602 .onEphemeralUserStop(oldUserId);
603 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100604 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700605 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700606 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700607 break;
608 }
609 }
610 }
611 }
612
613 void startProfilesLocked() {
614 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700615 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700616 mCurrentUserId, false /* enabledOnly */);
617 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
618 for (UserInfo user : profiles) {
619 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
Rubin Xuf13c9802016-01-21 18:06:00 +0000620 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700621 profilesToStart.add(user);
622 }
623 }
624 final int profilesToStartSize = profilesToStart.size();
625 int i = 0;
626 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
627 startUser(profilesToStart.get(i).id, /* foreground= */ false);
628 }
629 if (i < profilesToStartSize) {
630 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
631 }
632 }
633
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700634 private UserManagerService getUserManager() {
635 UserManagerService userManager = mUserManager;
636 if (userManager == null) {
637 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
638 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
639 }
640 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700641 }
642
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700643 private IMountService getMountService() {
644 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
645 }
646
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700647 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700648 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800649 if (mountService != null) {
650 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700651 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800652 } catch (RemoteException e) {
653 throw e.rethrowAsRuntimeException();
654 }
655 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700656 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
Paul Lawrence20be5d62016-02-26 13:51:17 -0800657 return !StorageManager.isFileEncryptedNativeOrEmulated();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800658 }
659 }
660
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700661 boolean startUser(final int userId, final boolean foreground) {
662 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
663 != PackageManager.PERMISSION_GRANTED) {
664 String msg = "Permission Denial: switchUser() from pid="
665 + Binder.getCallingPid()
666 + ", uid=" + Binder.getCallingUid()
667 + " requires " + INTERACT_ACROSS_USERS_FULL;
668 Slog.w(TAG, msg);
669 throw new SecurityException(msg);
670 }
671
672 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
673
674 final long ident = Binder.clearCallingIdentity();
675 try {
676 synchronized (mService) {
677 final int oldUserId = mCurrentUserId;
678 if (oldUserId == userId) {
679 return true;
680 }
681
682 mService.mStackSupervisor.setLockTaskModeLocked(null,
683 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
684
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700685 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700686 if (userInfo == null) {
687 Slog.w(TAG, "No user info for user #" + userId);
688 return false;
689 }
690 if (foreground && userInfo.isManagedProfile()) {
691 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
692 return false;
693 }
694
695 if (foreground) {
696 mService.mWindowManager.startFreezingScreen(
697 R.anim.screen_user_exit, R.anim.screen_user_enter);
698 }
699
700 boolean needStart = false;
701
702 // If the user we are switching to is not currently started, then
703 // we need to start it now.
704 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700705 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700706 updateStartedUserArrayLocked();
707 needStart = true;
708 }
709
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800710 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700711 final Integer userIdInt = userId;
712 mUserLru.remove(userIdInt);
713 mUserLru.add(userIdInt);
714
715 if (foreground) {
716 mCurrentUserId = userId;
717 mService.updateUserConfigurationLocked();
718 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
719 updateCurrentProfileIdsLocked();
720 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
721 // Once the internal notion of the active user has switched, we lock the device
722 // with the option to show the user switcher on the keyguard.
723 mService.mWindowManager.lockNow(null);
724 } else {
725 final Integer currentUserIdInt = mCurrentUserId;
726 updateCurrentProfileIdsLocked();
727 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
728 mUserLru.remove(currentUserIdInt);
729 mUserLru.add(currentUserIdInt);
730 }
731
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700732 // Make sure user is in the started state. If it is currently
733 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700734 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700735 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
736 // so we can just fairly silently bring the user back from
737 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700738 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700739 updateStartedUserArrayLocked();
740 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700741 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700742 // This means ACTION_SHUTDOWN has been sent, so we will
743 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700744 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700745 updateStartedUserArrayLocked();
746 needStart = true;
747 }
748
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700749 if (uss.state == UserState.STATE_BOOTING) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700750 // Give user manager a chance to propagate user restrictions
751 // to other services and prepare app storage
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800752 getUserManager().onBeforeStartUser(userId);
753
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700754 // Booting up a new user, need to tell system services about it.
755 // Note that this is on the same handler as scheduling of broadcasts,
756 // which is important because it needs to go first.
757 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
758 }
759
760 if (foreground) {
761 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
762 oldUserId));
763 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
764 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
765 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
766 oldUserId, userId, uss));
767 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
768 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
769 }
770
771 if (needStart) {
772 // Send USER_STARTED broadcast
773 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
774 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
775 | Intent.FLAG_RECEIVER_FOREGROUND);
776 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
777 mService.broadcastIntentLocked(null, null, intent,
778 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700779 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700780 }
781
782 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
783 if (userId != UserHandle.USER_SYSTEM) {
784 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
785 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
786 mService.broadcastIntentLocked(null, null, intent, null,
787 new IIntentReceiver.Stub() {
Amith Yamasani98c05562016-03-30 13:15:26 -0700788 @Override
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700789 public void performReceive(Intent intent, int resultCode,
790 String data, Bundle extras, boolean ordered,
791 boolean sticky, int sendingUser) {
Amith Yamasani98c05562016-03-30 13:15:26 -0700792 mHandler.post(new Runnable() {
793 @Override
794 public void run() {
795 onUserInitialized(uss, foreground,
796 oldUserId, userId);
797 }
798 });
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700799 }
800 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700801 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700802 uss.initializing = true;
803 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700804 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700805 }
806 }
807
808 if (foreground) {
809 if (!uss.initializing) {
810 moveUserToForegroundLocked(uss, oldUserId, userId);
811 }
812 } else {
Fyodor Kupolov2e6acce2016-01-28 15:26:52 -0800813 mService.mUserController.finishUserBoot(uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700814 }
815
816 if (needStart) {
817 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
818 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
819 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
820 mService.broadcastIntentLocked(null, null, intent,
821 null, new IIntentReceiver.Stub() {
822 @Override
823 public void performReceive(Intent intent, int resultCode,
824 String data, Bundle extras, boolean ordered, boolean sticky,
825 int sendingUser) throws RemoteException {
826 }
827 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700828 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
829 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700830 }
831 }
832 } finally {
833 Binder.restoreCallingIdentity(ident);
834 }
835
836 return true;
837 }
838
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700839 /**
840 * Start user, if its not already running, and bring it to foreground.
841 */
842 boolean startUserInForeground(final int userId, Dialog dlg) {
843 boolean result = startUser(userId, /* foreground */ true);
844 dlg.dismiss();
845 return result;
846 }
847
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600848 boolean unlockUser(final int userId, byte[] token, byte[] secret, ProgressReporter progress) {
Jeff Sharkeyba512352015-11-12 20:17:45 -0800849 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
850 != PackageManager.PERMISSION_GRANTED) {
851 String msg = "Permission Denial: unlockUser() from pid="
852 + Binder.getCallingPid()
853 + ", uid=" + Binder.getCallingUid()
854 + " requires " + INTERACT_ACROSS_USERS_FULL;
855 Slog.w(TAG, msg);
856 throw new SecurityException(msg);
857 }
858
Jeff Sharkey8924e872015-11-30 12:52:10 -0700859 final long binderToken = Binder.clearCallingIdentity();
860 try {
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600861 return unlockUserCleared(userId, token, secret, progress);
Jeff Sharkey8924e872015-11-30 12:52:10 -0700862 } finally {
863 Binder.restoreCallingIdentity(binderToken);
864 }
865 }
866
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700867 /**
868 * Attempt to unlock user without a credential token. This typically
869 * succeeds when the device doesn't have credential-encrypted storage, or
870 * when the the credential-encrypted storage isn't tied to a user-provided
871 * PIN or pattern.
872 */
873 boolean maybeUnlockUser(final int userId) {
874 // Try unlocking storage using empty token
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600875 return unlockUserCleared(userId, null, null, ProgressReporter.NO_OP);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700876 }
877
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600878 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
879 ProgressReporter progress) {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700880 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700881 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700882 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600883 switch (uss.state) {
884 case STATE_RUNNING_UNLOCKING:
885 case STATE_RUNNING_UNLOCKED:
886 progress.finish();
887 return true;
888 }
Jeff Sharkey8924e872015-11-30 12:52:10 -0700889 }
890
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700891 if (!isUserKeyUnlocked(userId)) {
892 final UserInfo userInfo = getUserInfo(userId);
893 final IMountService mountService = getMountService();
894 try {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000895 mountService.unlockUserKey(userId, userInfo.serialNumber, token, secret);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700896 } catch (RemoteException | RuntimeException e) {
897 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600898 progress.finish();
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700899 return false;
900 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800901 }
902
903 synchronized (mService) {
904 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600905 finishUserUnlocking(uss, progress);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800906 }
907
908 return true;
909 }
910
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800911 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700912 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800913 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
914 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700915 d.show();
916 }
917
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700918 void dispatchForegroundProfileChanged(int userId) {
919 final int observerCount = mUserSwitchObservers.beginBroadcast();
920 for (int i = 0; i < observerCount; i++) {
921 try {
922 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
923 } catch (RemoteException e) {
924 // Ignore
925 }
926 }
927 mUserSwitchObservers.finishBroadcast();
928 }
929
930 /** Called on handler thread */
931 void dispatchUserSwitchComplete(int userId) {
932 final int observerCount = mUserSwitchObservers.beginBroadcast();
933 for (int i = 0; i < observerCount; i++) {
934 try {
935 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
936 } catch (RemoteException e) {
937 }
938 }
939 mUserSwitchObservers.finishBroadcast();
940 }
941
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700942 private void stopBackgroundUsersIfEnforced(int oldUserId) {
943 // Never stop system user
944 if (oldUserId == UserHandle.USER_SYSTEM) {
945 return;
946 }
947 // For now, only check for user restriction. Additional checks can be added here
948 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
949 oldUserId);
950 if (!disallowRunInBg) {
951 return;
952 }
953 synchronized (mService) {
954 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
955 + " and related users");
956 stopUsersLocked(oldUserId, false, null);
957 }
958 }
959
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700960 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
961 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800962 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700963 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
964 }
965 }
966
967 void dispatchUserSwitch(final UserState uss, final int oldUserId,
968 final int newUserId) {
969 final int observerCount = mUserSwitchObservers.beginBroadcast();
970 if (observerCount > 0) {
971 final IRemoteCallback callback = new IRemoteCallback.Stub() {
972 int mCount = 0;
973 @Override
974 public void sendResult(Bundle data) throws RemoteException {
975 synchronized (mService) {
976 if (mCurUserSwitchCallback == this) {
977 mCount++;
978 if (mCount == observerCount) {
979 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
980 }
981 }
982 }
983 }
984 };
985 synchronized (mService) {
986 uss.switching = true;
987 mCurUserSwitchCallback = callback;
988 }
989 for (int i = 0; i < observerCount; i++) {
990 try {
991 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
992 newUserId, callback);
993 } catch (RemoteException e) {
994 }
995 }
996 } else {
997 synchronized (mService) {
998 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
999 }
1000 }
1001 mUserSwitchObservers.finishBroadcast();
1002 }
1003
1004 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
1005 mCurUserSwitchCallback = null;
1006 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1007 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
1008 oldUserId, newUserId, uss));
1009 }
1010
1011 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001012 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001013 }
1014
1015 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
1016 synchronized (mService) {
1017 if (foreground) {
1018 moveUserToForegroundLocked(uss, oldUserId, newUserId);
1019 }
1020 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001021 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001022 }
1023
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001024 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001025 boolean clearInitializing, boolean clearSwitching) {
1026 boolean unfrozen = false;
1027 synchronized (mService) {
1028 if (clearInitializing) {
1029 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001030 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001031 }
1032 if (clearSwitching) {
1033 uss.switching = false;
1034 }
1035 if (!uss.switching && !uss.initializing) {
1036 mService.mWindowManager.stopFreezingScreen();
1037 unfrozen = true;
1038 }
1039 }
1040 if (unfrozen) {
1041 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
1042 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
1043 newUserId, 0));
1044 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +01001045 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001046 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001047 }
1048
1049 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
1050 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
1051 if (homeInFront) {
1052 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
1053 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001054 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001055 }
1056 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001057 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1058 }
1059
1060 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1061 long ident = Binder.clearCallingIdentity();
1062 try {
1063 Intent intent;
1064 if (oldUserId >= 0) {
1065 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
1066 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
1067 int count = profiles.size();
1068 for (int i = 0; i < count; i++) {
1069 int profileUserId = profiles.get(i).id;
1070 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1071 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1072 | Intent.FLAG_RECEIVER_FOREGROUND);
1073 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1074 mService.broadcastIntentLocked(null, null, intent,
1075 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1076 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1077 }
1078 }
1079 if (newUserId >= 0) {
1080 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
1081 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
1082 int count = profiles.size();
1083 for (int i = 0; i < count; i++) {
1084 int profileUserId = profiles.get(i).id;
1085 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1086 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1087 | Intent.FLAG_RECEIVER_FOREGROUND);
1088 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1089 mService.broadcastIntentLocked(null, null, intent,
1090 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1091 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1092 }
1093 intent = new Intent(Intent.ACTION_USER_SWITCHED);
1094 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1095 | Intent.FLAG_RECEIVER_FOREGROUND);
1096 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
1097 mService.broadcastIntentLocked(null, null, intent,
1098 null, null, 0, null, null,
1099 new String[] {android.Manifest.permission.MANAGE_USERS},
1100 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1101 UserHandle.USER_ALL);
1102 }
1103 } finally {
1104 Binder.restoreCallingIdentity(ident);
1105 }
1106 }
1107
1108
1109 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1110 int allowMode, String name, String callerPackage) {
1111 final int callingUserId = UserHandle.getUserId(callingUid);
1112 if (callingUserId == userId) {
1113 return userId;
1114 }
1115
1116 // Note that we may be accessing mCurrentUserId outside of a lock...
1117 // shouldn't be a big deal, if this is being called outside
1118 // of a locked context there is intrinsically a race with
1119 // the value the caller will receive and someone else changing it.
1120 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1121 // we will switch to the calling user if access to the current user fails.
1122 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1123
1124 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1125 final boolean allow;
1126 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1127 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1128 // If the caller has this permission, they always pass go. And collect $200.
1129 allow = true;
1130 } else if (allowMode == ALLOW_FULL_ONLY) {
1131 // We require full access, sucks to be you.
1132 allow = false;
1133 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1134 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1135 // If the caller does not have either permission, they are always doomed.
1136 allow = false;
1137 } else if (allowMode == ALLOW_NON_FULL) {
1138 // We are blanket allowing non-full access, you lucky caller!
1139 allow = true;
1140 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1141 // We may or may not allow this depending on whether the two users are
1142 // in the same profile.
1143 allow = isSameProfileGroup(callingUserId, targetUserId);
1144 } else {
1145 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1146 }
1147 if (!allow) {
1148 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1149 // In this case, they would like to just execute as their
1150 // owner user instead of failing.
1151 targetUserId = callingUserId;
1152 } else {
1153 StringBuilder builder = new StringBuilder(128);
1154 builder.append("Permission Denial: ");
1155 builder.append(name);
1156 if (callerPackage != null) {
1157 builder.append(" from ");
1158 builder.append(callerPackage);
1159 }
1160 builder.append(" asks to run as user ");
1161 builder.append(userId);
1162 builder.append(" but is calling from user ");
1163 builder.append(UserHandle.getUserId(callingUid));
1164 builder.append("; this requires ");
1165 builder.append(INTERACT_ACROSS_USERS_FULL);
1166 if (allowMode != ALLOW_FULL_ONLY) {
1167 builder.append(" or ");
1168 builder.append(INTERACT_ACROSS_USERS);
1169 }
1170 String msg = builder.toString();
1171 Slog.w(TAG, msg);
1172 throw new SecurityException(msg);
1173 }
1174 }
1175 }
1176 if (!allowAll && targetUserId < 0) {
1177 throw new IllegalArgumentException(
1178 "Call does not support special user #" + targetUserId);
1179 }
1180 // Check shell permission
1181 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1182 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1183 throw new SecurityException("Shell does not have permission to access user "
1184 + targetUserId + "\n " + Debug.getCallers(3));
1185 }
1186 }
1187 return targetUserId;
1188 }
1189
1190 int unsafeConvertIncomingUserLocked(int userId) {
1191 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1192 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001193 }
1194
1195 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1196 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1197 != PackageManager.PERMISSION_GRANTED) {
1198 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1199 + Binder.getCallingPid()
1200 + ", uid=" + Binder.getCallingUid()
1201 + " requires " + INTERACT_ACROSS_USERS_FULL;
1202 Slog.w(TAG, msg);
1203 throw new SecurityException(msg);
1204 }
1205
1206 mUserSwitchObservers.register(observer);
1207 }
1208
1209 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1210 mUserSwitchObservers.unregister(observer);
1211 }
1212
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001213 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001214 return mStartedUsers.get(userId);
1215 }
1216
1217 boolean hasStartedUserState(int userId) {
1218 return mStartedUsers.get(userId) != null;
1219 }
1220
1221 private void updateStartedUserArrayLocked() {
1222 int num = 0;
1223 for (int i = 0; i < mStartedUsers.size(); i++) {
1224 UserState uss = mStartedUsers.valueAt(i);
1225 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001226 if (uss.state != UserState.STATE_STOPPING
1227 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001228 num++;
1229 }
1230 }
1231 mStartedUserArray = new int[num];
1232 num = 0;
1233 for (int i = 0; i < mStartedUsers.size(); i++) {
1234 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001235 if (uss.state != UserState.STATE_STOPPING
1236 && uss.state != UserState.STATE_SHUTDOWN) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -08001237 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001238 }
1239 }
1240 }
1241
1242 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1243 for (int i = 0; i < mStartedUsers.size(); i++) {
1244 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001245 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001246 }
1247 }
1248
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001249 void onSystemReady() {
1250 updateCurrentProfileIdsLocked();
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001251 }
1252
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001253 /**
1254 * Refreshes the list of users related to the current user when either a
1255 * user switch happens or when a new related user is started in the
1256 * background.
1257 */
Wale Ogunwalef80170f2016-02-04 15:12:29 -08001258 private void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001259 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001260 false /* enabledOnly */);
1261 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1262 for (int i = 0; i < currentProfileIds.length; i++) {
1263 currentProfileIds[i] = profiles.get(i).id;
1264 }
1265 mCurrentProfileIds = currentProfileIds;
1266
1267 synchronized (mUserProfileGroupIdsSelfLocked) {
1268 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001269 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001270 for (int i = 0; i < users.size(); i++) {
1271 UserInfo user = users.get(i);
1272 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1273 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1274 }
1275 }
1276 }
1277 }
1278
1279 int[] getStartedUserArrayLocked() {
1280 return mStartedUserArray;
1281 }
1282
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001283 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001284 UserState state = getStartedUserStateLocked(userId);
1285 if (state == null) {
1286 return false;
1287 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001288 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001289 return true;
1290 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001291
1292 final boolean unlocked;
1293 switch (state.state) {
1294 case UserState.STATE_STOPPING:
1295 case UserState.STATE_SHUTDOWN:
1296 default:
1297 return false;
1298
1299 case UserState.STATE_BOOTING:
1300 case UserState.STATE_RUNNING_LOCKED:
1301 unlocked = false;
1302 break;
1303
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001304 case UserState.STATE_RUNNING_UNLOCKING:
1305 case UserState.STATE_RUNNING_UNLOCKED:
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001306 unlocked = true;
1307 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001308 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001309
1310 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1311 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001312 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001313 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1314 return unlocked;
1315 }
1316
1317 // One way or another, we're running!
1318 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001319 }
1320
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001321 UserInfo getCurrentUser() {
1322 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1323 != PackageManager.PERMISSION_GRANTED) && (
1324 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1325 != PackageManager.PERMISSION_GRANTED)) {
1326 String msg = "Permission Denial: getCurrentUser() from pid="
1327 + Binder.getCallingPid()
1328 + ", uid=" + Binder.getCallingUid()
1329 + " requires " + INTERACT_ACROSS_USERS;
1330 Slog.w(TAG, msg);
1331 throw new SecurityException(msg);
1332 }
1333 synchronized (mService) {
1334 return getCurrentUserLocked();
1335 }
1336 }
1337
1338 UserInfo getCurrentUserLocked() {
1339 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001340 return getUserInfo(userId);
1341 }
1342
1343 int getCurrentOrTargetUserIdLocked() {
1344 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001345 }
1346
1347 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001348 return mCurrentUserId;
1349 }
1350
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001351 private boolean isCurrentUserLocked(int userId) {
Amith Yamasani458ac462015-12-18 11:21:31 -08001352 return userId == getCurrentOrTargetUserIdLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001353 }
1354
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001355 int setTargetUserIdLocked(int targetUserId) {
1356 return mTargetUserId = targetUserId;
1357 }
1358
1359 int[] getUsers() {
1360 UserManagerService ums = getUserManager();
1361 return ums != null ? ums.getUserIds() : new int[] { 0 };
1362 }
1363
1364 UserInfo getUserInfo(int userId) {
1365 return getUserManager().getUserInfo(userId);
1366 }
1367
1368 int[] getUserIds() {
1369 return getUserManager().getUserIds();
1370 }
1371
1372 boolean exists(int userId) {
1373 return getUserManager().exists(userId);
1374 }
1375
1376 boolean hasUserRestriction(String restriction, int userId) {
1377 return getUserManager().hasUserRestriction(restriction, userId);
1378 }
1379
1380 Set<Integer> getProfileIds(int userId) {
1381 Set<Integer> userIds = new HashSet<>();
1382 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1383 false /* enabledOnly */);
1384 for (UserInfo user : profiles) {
1385 userIds.add(user.id);
1386 }
1387 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001388 }
1389
1390 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1391 synchronized (mUserProfileGroupIdsSelfLocked) {
1392 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1393 UserInfo.NO_PROFILE_GROUP_ID);
1394 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1395 UserInfo.NO_PROFILE_GROUP_ID);
1396 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1397 && callingProfile == targetProfile;
1398 }
1399 }
1400
1401 boolean isCurrentProfileLocked(int userId) {
1402 return ArrayUtils.contains(mCurrentProfileIds, userId);
1403 }
1404
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001405 int[] getCurrentProfileIdsLocked() {
1406 return mCurrentProfileIds;
1407 }
1408
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001409 /**
1410 * Returns whether the given user requires credential entry at this time. This is used to
1411 * intercept activity launches for work apps when the Work Challenge is present.
1412 */
1413 boolean shouldConfirmCredentials(int userId) {
Rubin Xub93522a2016-02-23 18:21:48 +00001414 synchronized (mService) {
1415 if (mStartedUsers.get(userId) == null) {
1416 return false;
1417 }
1418 }
Clara Bayarria1771112015-12-18 16:29:18 +00001419 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001420 return false;
1421 }
1422 final KeyguardManager km = (KeyguardManager) mService.mContext
1423 .getSystemService(KEYGUARD_SERVICE);
Clara Bayarria1771112015-12-18 16:29:18 +00001424 return km.isDeviceLocked(userId);
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001425 }
1426
Tony Mak8c536f92016-03-21 12:20:41 +00001427 boolean isLockScreenDisabled(@UserIdInt int userId) {
1428 return mLockPatternUtils.isLockScreenDisabled(userId);
1429 }
1430
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001431 void dump(PrintWriter pw, boolean dumpAll) {
1432 pw.println(" mStartedUsers:");
1433 for (int i = 0; i < mStartedUsers.size(); i++) {
1434 UserState uss = mStartedUsers.valueAt(i);
1435 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1436 pw.print(": "); uss.dump("", pw);
1437 }
1438 pw.print(" mStartedUserArray: [");
1439 for (int i = 0; i < mStartedUserArray.length; i++) {
1440 if (i > 0) pw.print(", ");
1441 pw.print(mStartedUserArray[i]);
1442 }
1443 pw.println("]");
1444 pw.print(" mUserLru: [");
1445 for (int i = 0; i < mUserLru.size(); i++) {
1446 if (i > 0) pw.print(", ");
1447 pw.print(mUserLru.get(i));
1448 }
1449 pw.println("]");
1450 if (dumpAll) {
1451 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1452 }
1453 synchronized (mUserProfileGroupIdsSelfLocked) {
1454 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1455 pw.println(" mUserProfileGroupIds:");
1456 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1457 pw.print(" User #");
1458 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1459 pw.print(" -> profile #");
1460 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1461 }
1462 }
1463 }
1464 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001465}