blob: 56757ca28c5b242665ccbe1f8b6222a07fe511ec [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;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070027import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
28import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
29import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070030import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
31import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
32import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
33import static com.android.server.am.ActivityManagerService.MY_PID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070034import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
35import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
36import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
37import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -070038import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070039import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
40
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070041import android.annotation.NonNull;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070042import android.app.ActivityManager;
43import android.app.AppOpsManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070044import android.app.Dialog;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070045import android.app.IStopUserCallback;
46import android.app.IUserSwitchObserver;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000047import android.app.KeyguardManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070048import android.content.Context;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070049import android.content.IIntentReceiver;
50import android.content.Intent;
51import android.content.pm.PackageManager;
52import android.content.pm.UserInfo;
53import android.os.BatteryStats;
54import android.os.Binder;
55import android.os.Bundle;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070056import android.os.Debug;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070057import android.os.Handler;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070058import android.os.IBinder;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070059import android.os.IRemoteCallback;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070060import android.os.IUserManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070061import android.os.Process;
62import android.os.RemoteCallbackList;
63import android.os.RemoteException;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070064import android.os.ServiceManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070065import android.os.UserHandle;
66import android.os.UserManager;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080067import android.os.storage.IMountService;
68import android.os.storage.StorageManager;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070069import android.util.IntArray;
Suprabh Shukla4fe508b2015-11-20 18:22:57 -080070import android.util.Pair;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070071import android.util.Slog;
72import android.util.SparseArray;
73import android.util.SparseIntArray;
74
75import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080076import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070077import com.android.internal.util.ArrayUtils;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000078import com.android.internal.widget.LockPatternUtils;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070079import com.android.server.pm.UserManagerService;
80
81import java.io.PrintWriter;
82import java.util.ArrayList;
83import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070084import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070085import java.util.List;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070086import java.util.Set;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070087
88/**
89 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
90 */
91final class UserController {
92 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
93 // Maximum number of users we allow to be running at a time.
94 static final int MAX_RUNNING_USERS = 3;
95
96 // Amount of time we wait for observers to handle a user switch before
97 // giving up on them and unfreezing the screen.
98 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
99
100 private final ActivityManagerService mService;
101 private final Handler mHandler;
102
103 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700104 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700105 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700106 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700107
108 /**
109 * Which users have been started, so are allowed to run code.
110 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800111 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700112 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800113
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700114 /**
115 * LRU list of history of current users. Most recently current is at the end.
116 */
117 private final ArrayList<Integer> mUserLru = new ArrayList<>();
118
119 /**
120 * Constant array of the users that are currently started.
121 */
122 private int[] mStartedUserArray = new int[] { 0 };
123
124 // If there are multiple profiles for the current user, their ids are here
125 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700126 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700127
128 /**
129 * Mapping from each known user ID to the profile group ID it is associated with.
130 */
131 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
132
133 /**
134 * Registered observers of the user switching mechanics.
135 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700136 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700137 = new RemoteCallbackList<>();
138
139 /**
140 * Currently active user switch.
141 */
142 Object mCurUserSwitchCallback;
143
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700144 private volatile UserManagerService mUserManager;
145
Clara Bayarria1771112015-12-18 16:29:18 +0000146 private final LockPatternUtils mLockPatternUtils;
147
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700148 UserController(ActivityManagerService service) {
149 mService = service;
150 mHandler = mService.mHandler;
151 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800152 final UserState uss = new UserState(UserHandle.SYSTEM);
153 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700154 mUserLru.add(UserHandle.USER_SYSTEM);
Clara Bayarria1771112015-12-18 16:29:18 +0000155 mLockPatternUtils = new LockPatternUtils(mService.mContext);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700156 updateStartedUserArrayLocked();
157 }
158
159 void finishUserSwitch(UserState uss) {
160 synchronized (mService) {
161 finishUserBoot(uss);
162
163 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700164 stopRunningUsersLocked(MAX_RUNNING_USERS);
165 }
166 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700167
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700168 void stopRunningUsersLocked(int maxRunningUsers) {
169 int num = mUserLru.size();
170 int i = 0;
171 while (num > maxRunningUsers && i < mUserLru.size()) {
172 Integer oldUserId = mUserLru.get(i);
173 UserState oldUss = mStartedUsers.get(oldUserId);
174 if (oldUss == null) {
175 // Shouldn't happen, but be sane if it does.
176 mUserLru.remove(i);
177 num--;
178 continue;
179 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700180 if (oldUss.state == UserState.STATE_STOPPING
181 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700182 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700183 num--;
184 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700185 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700186 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700187 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
188 // Owner/System user and current user can't be stopped. We count it as running
189 // when it is not a pure system user.
190 if (UserInfo.isSystemOnly(oldUserId)) {
191 num--;
192 }
193 i++;
194 continue;
195 }
196 // This is a user to be stopped.
197 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
198 num--;
199 }
200 num--;
201 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700202 }
203 }
204
205 void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700206 finishUserBoot(uss, null);
207 }
208
209 void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
210 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700211 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700212 // Bail if we ended up with a stale user
213 if (mStartedUsers.get(userId) != uss) return;
214
215 // We always walk through all the user lifecycle states to send
216 // consistent developer events. We step into RUNNING_LOCKED here,
217 // but we might immediately step into RUNNING below if the user
218 // storage is already unlocked.
219 if (uss.state == UserState.STATE_BOOTING) {
220 uss.setState(UserState.STATE_RUNNING_LOCKED);
221
222 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700223 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeya242f822015-12-17 15:38:20 -0700224 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
225 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700226 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
227 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
228 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
229 }
230
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700231 maybeUnlockUser(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700232 }
233 }
234
235 /**
236 * Consider stepping from {@link UserState#STATE_RUNNING_LOCKED} into
237 * {@link UserState#STATE_RUNNING}, which only occurs if the user storage is
238 * actually unlocked.
239 */
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700240 void finishUserUnlock(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700241 final int userId = uss.mHandle.getIdentifier();
242 synchronized (mService) {
243 // Bail if we ended up with a stale user
244 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
245
246 // Only keep marching forward if user is actually unlocked
247 if (!isUserKeyUnlocked(userId)) return;
248
249 if (uss.state == UserState.STATE_RUNNING_LOCKED) {
250 uss.setState(UserState.STATE_RUNNING);
251
252 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
253
254 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700255 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700256 unlockedIntent.addFlags(
257 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
258 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
259 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
260 userId);
261
262 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
263 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -0800264 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
265 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700266 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
267 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700268 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700269 }
270 }
271 }
272
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700273 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700274 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
275 != PackageManager.PERMISSION_GRANTED) {
276 String msg = "Permission Denial: switchUser() from pid="
277 + Binder.getCallingPid()
278 + ", uid=" + Binder.getCallingUid()
279 + " requires " + INTERACT_ACROSS_USERS_FULL;
280 Slog.w(TAG, msg);
281 throw new SecurityException(msg);
282 }
283 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
284 throw new IllegalArgumentException("Can't stop system user " + userId);
285 }
286 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
287 userId);
288 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700289 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700290 }
291 }
292
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700293 /**
294 * Stops the user along with its related users. The method calls
295 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
296 */
297 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
298 if (userId == UserHandle.USER_SYSTEM) {
299 return USER_OP_ERROR_IS_SYSTEM;
300 }
301 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700302 return USER_OP_IS_CURRENT;
303 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700304 int[] usersToStop = getUsersToStopLocked(userId);
305 // If one of related users is system or current, no related users should be stopped
306 for (int i = 0; i < usersToStop.length; i++) {
307 int relatedUserId = usersToStop[i];
308 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
309 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
310 + relatedUserId);
311 // We still need to stop the requested user if it's a force stop.
312 if (force) {
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800313 Slog.i(TAG,
314 "Force stop user " + userId + ". Related users will not be stopped");
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700315 stopSingleUserLocked(userId, callback);
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800316 return USER_OP_SUCCESS;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700317 }
318 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
319 }
320 }
321 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
322 for (int userIdToStop : usersToStop) {
323 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
324 }
325 return USER_OP_SUCCESS;
326 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700327
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700328 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
329 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700330 final UserState uss = mStartedUsers.get(userId);
331 if (uss == null) {
332 // User is not started, nothing to do... but we do need to
333 // callback if requested.
334 if (callback != null) {
335 mHandler.post(new Runnable() {
336 @Override
337 public void run() {
338 try {
339 callback.userStopped(userId);
340 } catch (RemoteException e) {
341 }
342 }
343 });
344 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700345 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700346 }
347
348 if (callback != null) {
349 uss.mStopCallbacks.add(callback);
350 }
351
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700352 if (uss.state != UserState.STATE_STOPPING
353 && uss.state != UserState.STATE_SHUTDOWN) {
354 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700355 updateStartedUserArrayLocked();
356
357 long ident = Binder.clearCallingIdentity();
358 try {
359 // We are going to broadcast ACTION_USER_STOPPING and then
360 // once that is done send a final ACTION_SHUTDOWN and then
361 // stop the user.
362 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
363 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
364 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
365 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
366 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
367 // This is the result receiver for the final shutdown broadcast.
368 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
369 @Override
370 public void performReceive(Intent intent, int resultCode, String data,
371 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
372 finishUserStop(uss);
373 }
374 };
375 // This is the result receiver for the initial stopping broadcast.
376 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
377 @Override
378 public void performReceive(Intent intent, int resultCode, String data,
379 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
380 // On to the next.
381 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700382 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700383 // Whoops, we are being started back up. Abort, abort!
384 return;
385 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700386 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700387 }
388 mService.mBatteryStatsService.noteEvent(
389 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
390 Integer.toString(userId), userId);
391 mService.mSystemServiceManager.stopUser(userId);
392 mService.broadcastIntentLocked(null, null, shutdownIntent,
393 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700394 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700395 }
396 };
397 // Kick things off.
398 mService.broadcastIntentLocked(null, null, stoppingIntent,
399 null, stoppingReceiver, 0, null, null,
400 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700401 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700402 } finally {
403 Binder.restoreCallingIdentity(ident);
404 }
405 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700406 }
407
408 void finishUserStop(UserState uss) {
409 final int userId = uss.mHandle.getIdentifier();
410 boolean stopped;
411 ArrayList<IStopUserCallback> callbacks;
412 synchronized (mService) {
413 callbacks = new ArrayList<>(uss.mStopCallbacks);
414 if (mStartedUsers.get(userId) != uss) {
415 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700416 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700417 stopped = false;
418 } else {
419 stopped = true;
420 // User can no longer run.
421 mStartedUsers.remove(userId);
422 mUserLru.remove(Integer.valueOf(userId));
423 updateStartedUserArrayLocked();
424
425 // Clean up all state and processes associated with the user.
426 // Kill all the processes for the user.
427 forceStopUserLocked(userId, "finish user");
428 }
429 }
430
431 for (int i = 0; i < callbacks.size(); i++) {
432 try {
433 if (stopped) callbacks.get(i).userStopped(userId);
434 else callbacks.get(i).userStopAborted(userId);
435 } catch (RemoteException e) {
436 }
437 }
438
439 if (stopped) {
440 mService.mSystemServiceManager.cleanupUser(userId);
441 synchronized (mService) {
442 mService.mStackSupervisor.removeUserLocked(userId);
443 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100444 // Remove the user if it is ephemeral.
445 if (getUserInfo(userId).isEphemeral()) {
446 mUserManager.removeUser(userId);
447 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700448 }
449 }
450
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700451 /**
452 * Determines the list of users that should be stopped together with the specified
453 * {@code userId}. The returned list includes {@code userId}.
454 */
455 private @NonNull int[] getUsersToStopLocked(int userId) {
456 int startedUsersSize = mStartedUsers.size();
457 IntArray userIds = new IntArray();
458 userIds.add(userId);
459 synchronized (mUserProfileGroupIdsSelfLocked) {
460 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
461 UserInfo.NO_PROFILE_GROUP_ID);
462 for (int i = 0; i < startedUsersSize; i++) {
463 UserState uss = mStartedUsers.valueAt(i);
464 int startedUserId = uss.mHandle.getIdentifier();
465 // Skip unrelated users (profileGroupId mismatch)
466 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
467 UserInfo.NO_PROFILE_GROUP_ID);
468 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
469 && (userGroupId == startedUserGroupId);
470 // userId has already been added
471 boolean sameUserId = startedUserId == userId;
472 if (!sameGroup || sameUserId) {
473 continue;
474 }
475 userIds.add(startedUserId);
476 }
477 }
478 return userIds.toArray();
479 }
480
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700481 private void forceStopUserLocked(int userId, String reason) {
482 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
483 userId, reason);
484 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
485 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
486 | Intent.FLAG_RECEIVER_FOREGROUND);
487 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
488 mService.broadcastIntentLocked(null, null, intent,
489 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700490 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700491 }
492
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700493 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100494 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700495 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100496 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700497 synchronized (mService) {
498 final int num = mUserLru.size();
499 for (int i = 0; i < num; i++) {
500 Integer oldUserId = mUserLru.get(i);
501 UserState oldUss = mStartedUsers.get(oldUserId);
502 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700503 || oldUss.state == UserState.STATE_STOPPING
504 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700505 continue;
506 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700507 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100508 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700509 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700510 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700511 break;
512 }
513 }
514 }
515 }
516
517 void startProfilesLocked() {
518 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700519 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700520 mCurrentUserId, false /* enabledOnly */);
521 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
522 for (UserInfo user : profiles) {
523 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
524 && user.id != mCurrentUserId) {
525 profilesToStart.add(user);
526 }
527 }
528 final int profilesToStartSize = profilesToStart.size();
529 int i = 0;
530 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
531 startUser(profilesToStart.get(i).id, /* foreground= */ false);
532 }
533 if (i < profilesToStartSize) {
534 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
535 }
536 }
537
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700538 private UserManagerService getUserManager() {
539 UserManagerService userManager = mUserManager;
540 if (userManager == null) {
541 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
542 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
543 }
544 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700545 }
546
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700547 private IMountService getMountService() {
548 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
549 }
550
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700551 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700552 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800553 if (mountService != null) {
554 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700555 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800556 } catch (RemoteException e) {
557 throw e.rethrowAsRuntimeException();
558 }
559 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700560 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
561 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800562 }
563 }
564
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700565 boolean startUser(final int userId, final boolean foreground) {
566 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
567 != PackageManager.PERMISSION_GRANTED) {
568 String msg = "Permission Denial: switchUser() from pid="
569 + Binder.getCallingPid()
570 + ", uid=" + Binder.getCallingUid()
571 + " requires " + INTERACT_ACROSS_USERS_FULL;
572 Slog.w(TAG, msg);
573 throw new SecurityException(msg);
574 }
575
576 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
577
578 final long ident = Binder.clearCallingIdentity();
579 try {
580 synchronized (mService) {
581 final int oldUserId = mCurrentUserId;
582 if (oldUserId == userId) {
583 return true;
584 }
585
586 mService.mStackSupervisor.setLockTaskModeLocked(null,
587 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
588
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700589 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700590 if (userInfo == null) {
591 Slog.w(TAG, "No user info for user #" + userId);
592 return false;
593 }
594 if (foreground && userInfo.isManagedProfile()) {
595 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
596 return false;
597 }
598
599 if (foreground) {
600 mService.mWindowManager.startFreezingScreen(
601 R.anim.screen_user_exit, R.anim.screen_user_enter);
602 }
603
604 boolean needStart = false;
605
606 // If the user we are switching to is not currently started, then
607 // we need to start it now.
608 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700609 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700610 updateStartedUserArrayLocked();
611 needStart = true;
612 }
613
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800614 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700615 final Integer userIdInt = userId;
616 mUserLru.remove(userIdInt);
617 mUserLru.add(userIdInt);
618
619 if (foreground) {
620 mCurrentUserId = userId;
621 mService.updateUserConfigurationLocked();
622 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
623 updateCurrentProfileIdsLocked();
624 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
625 // Once the internal notion of the active user has switched, we lock the device
626 // with the option to show the user switcher on the keyguard.
627 mService.mWindowManager.lockNow(null);
628 } else {
629 final Integer currentUserIdInt = mCurrentUserId;
630 updateCurrentProfileIdsLocked();
631 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
632 mUserLru.remove(currentUserIdInt);
633 mUserLru.add(currentUserIdInt);
634 }
635
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700636 // Make sure user is in the started state. If it is currently
637 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700638 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700639 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
640 // so we can just fairly silently bring the user back from
641 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700642 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700643 updateStartedUserArrayLocked();
644 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700645 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700646 // This means ACTION_SHUTDOWN has been sent, so we will
647 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700648 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700649 updateStartedUserArrayLocked();
650 needStart = true;
651 }
652
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700653 if (uss.state == UserState.STATE_BOOTING) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800654 // Let user manager propagate user restrictions to other services.
655 getUserManager().onBeforeStartUser(userId);
656
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700657 // Booting up a new user, need to tell system services about it.
658 // Note that this is on the same handler as scheduling of broadcasts,
659 // which is important because it needs to go first.
660 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
661 }
662
663 if (foreground) {
664 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
665 oldUserId));
666 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
667 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
668 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
669 oldUserId, userId, uss));
670 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
671 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
672 }
673
674 if (needStart) {
675 // Send USER_STARTED broadcast
676 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
677 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
678 | Intent.FLAG_RECEIVER_FOREGROUND);
679 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
680 mService.broadcastIntentLocked(null, null, intent,
681 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700682 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700683 }
684
685 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
686 if (userId != UserHandle.USER_SYSTEM) {
687 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
688 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
689 mService.broadcastIntentLocked(null, null, intent, null,
690 new IIntentReceiver.Stub() {
691 public void performReceive(Intent intent, int resultCode,
692 String data, Bundle extras, boolean ordered,
693 boolean sticky, int sendingUser) {
694 onUserInitialized(uss, foreground, oldUserId, userId);
695 }
696 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700697 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700698 uss.initializing = true;
699 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700700 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700701 }
702 }
703
704 if (foreground) {
705 if (!uss.initializing) {
706 moveUserToForegroundLocked(uss, oldUserId, userId);
707 }
708 } else {
709 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
710 }
711
712 if (needStart) {
713 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
714 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
715 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
716 mService.broadcastIntentLocked(null, null, intent,
717 null, new IIntentReceiver.Stub() {
718 @Override
719 public void performReceive(Intent intent, int resultCode,
720 String data, Bundle extras, boolean ordered, boolean sticky,
721 int sendingUser) throws RemoteException {
722 }
723 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700724 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
725 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700726 }
727 }
728 } finally {
729 Binder.restoreCallingIdentity(ident);
730 }
731
732 return true;
733 }
734
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700735 /**
736 * Start user, if its not already running, and bring it to foreground.
737 */
738 boolean startUserInForeground(final int userId, Dialog dlg) {
739 boolean result = startUser(userId, /* foreground */ true);
740 dlg.dismiss();
741 return result;
742 }
743
Jeff Sharkeyba512352015-11-12 20:17:45 -0800744 boolean unlockUser(final int userId, byte[] token) {
745 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
746 != PackageManager.PERMISSION_GRANTED) {
747 String msg = "Permission Denial: unlockUser() from pid="
748 + Binder.getCallingPid()
749 + ", uid=" + Binder.getCallingUid()
750 + " requires " + INTERACT_ACROSS_USERS_FULL;
751 Slog.w(TAG, msg);
752 throw new SecurityException(msg);
753 }
754
Jeff Sharkey8924e872015-11-30 12:52:10 -0700755 final long binderToken = Binder.clearCallingIdentity();
756 try {
757 return unlockUserCleared(userId, token);
758 } finally {
759 Binder.restoreCallingIdentity(binderToken);
760 }
761 }
762
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700763 /**
764 * Attempt to unlock user without a credential token. This typically
765 * succeeds when the device doesn't have credential-encrypted storage, or
766 * when the the credential-encrypted storage isn't tied to a user-provided
767 * PIN or pattern.
768 */
769 boolean maybeUnlockUser(final int userId) {
770 // Try unlocking storage using empty token
771 return unlockUserCleared(userId, null);
772 }
773
Jeff Sharkey8924e872015-11-30 12:52:10 -0700774 boolean unlockUserCleared(final int userId, byte[] token) {
775 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700776 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700777 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700778 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700779 }
780
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700781 if (!isUserKeyUnlocked(userId)) {
782 final UserInfo userInfo = getUserInfo(userId);
783 final IMountService mountService = getMountService();
784 try {
785 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
786 } catch (RemoteException | RuntimeException e) {
787 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
788 return false;
789 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800790 }
791
792 synchronized (mService) {
793 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700794 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800795 }
796
797 return true;
798 }
799
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800800 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700801 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800802 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
803 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700804 d.show();
805 }
806
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700807 void dispatchForegroundProfileChanged(int userId) {
808 final int observerCount = mUserSwitchObservers.beginBroadcast();
809 for (int i = 0; i < observerCount; i++) {
810 try {
811 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
812 } catch (RemoteException e) {
813 // Ignore
814 }
815 }
816 mUserSwitchObservers.finishBroadcast();
817 }
818
819 /** Called on handler thread */
820 void dispatchUserSwitchComplete(int userId) {
821 final int observerCount = mUserSwitchObservers.beginBroadcast();
822 for (int i = 0; i < observerCount; i++) {
823 try {
824 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
825 } catch (RemoteException e) {
826 }
827 }
828 mUserSwitchObservers.finishBroadcast();
829 }
830
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700831 private void stopBackgroundUsersIfEnforced(int oldUserId) {
832 // Never stop system user
833 if (oldUserId == UserHandle.USER_SYSTEM) {
834 return;
835 }
836 // For now, only check for user restriction. Additional checks can be added here
837 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
838 oldUserId);
839 if (!disallowRunInBg) {
840 return;
841 }
842 synchronized (mService) {
843 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
844 + " and related users");
845 stopUsersLocked(oldUserId, false, null);
846 }
847 }
848
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700849 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
850 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800851 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700852 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
853 }
854 }
855
856 void dispatchUserSwitch(final UserState uss, final int oldUserId,
857 final int newUserId) {
858 final int observerCount = mUserSwitchObservers.beginBroadcast();
859 if (observerCount > 0) {
860 final IRemoteCallback callback = new IRemoteCallback.Stub() {
861 int mCount = 0;
862 @Override
863 public void sendResult(Bundle data) throws RemoteException {
864 synchronized (mService) {
865 if (mCurUserSwitchCallback == this) {
866 mCount++;
867 if (mCount == observerCount) {
868 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
869 }
870 }
871 }
872 }
873 };
874 synchronized (mService) {
875 uss.switching = true;
876 mCurUserSwitchCallback = callback;
877 }
878 for (int i = 0; i < observerCount; i++) {
879 try {
880 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
881 newUserId, callback);
882 } catch (RemoteException e) {
883 }
884 }
885 } else {
886 synchronized (mService) {
887 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
888 }
889 }
890 mUserSwitchObservers.finishBroadcast();
891 }
892
893 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
894 mCurUserSwitchCallback = null;
895 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
896 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
897 oldUserId, newUserId, uss));
898 }
899
900 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700901 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700902 }
903
904 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
905 synchronized (mService) {
906 if (foreground) {
907 moveUserToForegroundLocked(uss, oldUserId, newUserId);
908 }
909 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700910 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700911 }
912
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700913 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700914 boolean clearInitializing, boolean clearSwitching) {
915 boolean unfrozen = false;
916 synchronized (mService) {
917 if (clearInitializing) {
918 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700919 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700920 }
921 if (clearSwitching) {
922 uss.switching = false;
923 }
924 if (!uss.switching && !uss.initializing) {
925 mService.mWindowManager.stopFreezingScreen();
926 unfrozen = true;
927 }
928 }
929 if (unfrozen) {
930 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
931 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
932 newUserId, 0));
933 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100934 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700935 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700936 }
937
938 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
939 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
940 if (homeInFront) {
941 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
942 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800943 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700944 }
945 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700946 getUserManager().onUserForeground(newUserId);
947 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
948 }
949
950 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
951 long ident = Binder.clearCallingIdentity();
952 try {
953 Intent intent;
954 if (oldUserId >= 0) {
955 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
956 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
957 int count = profiles.size();
958 for (int i = 0; i < count; i++) {
959 int profileUserId = profiles.get(i).id;
960 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
961 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
962 | Intent.FLAG_RECEIVER_FOREGROUND);
963 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
964 mService.broadcastIntentLocked(null, null, intent,
965 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
966 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
967 }
968 }
969 if (newUserId >= 0) {
970 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
971 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
972 int count = profiles.size();
973 for (int i = 0; i < count; i++) {
974 int profileUserId = profiles.get(i).id;
975 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
976 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
977 | Intent.FLAG_RECEIVER_FOREGROUND);
978 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
979 mService.broadcastIntentLocked(null, null, intent,
980 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
981 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
982 }
983 intent = new Intent(Intent.ACTION_USER_SWITCHED);
984 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
985 | Intent.FLAG_RECEIVER_FOREGROUND);
986 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
987 mService.broadcastIntentLocked(null, null, intent,
988 null, null, 0, null, null,
989 new String[] {android.Manifest.permission.MANAGE_USERS},
990 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
991 UserHandle.USER_ALL);
992 }
993 } finally {
994 Binder.restoreCallingIdentity(ident);
995 }
996 }
997
998
999 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1000 int allowMode, String name, String callerPackage) {
1001 final int callingUserId = UserHandle.getUserId(callingUid);
1002 if (callingUserId == userId) {
1003 return userId;
1004 }
1005
1006 // Note that we may be accessing mCurrentUserId outside of a lock...
1007 // shouldn't be a big deal, if this is being called outside
1008 // of a locked context there is intrinsically a race with
1009 // the value the caller will receive and someone else changing it.
1010 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1011 // we will switch to the calling user if access to the current user fails.
1012 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1013
1014 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1015 final boolean allow;
1016 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1017 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1018 // If the caller has this permission, they always pass go. And collect $200.
1019 allow = true;
1020 } else if (allowMode == ALLOW_FULL_ONLY) {
1021 // We require full access, sucks to be you.
1022 allow = false;
1023 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1024 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1025 // If the caller does not have either permission, they are always doomed.
1026 allow = false;
1027 } else if (allowMode == ALLOW_NON_FULL) {
1028 // We are blanket allowing non-full access, you lucky caller!
1029 allow = true;
1030 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1031 // We may or may not allow this depending on whether the two users are
1032 // in the same profile.
1033 allow = isSameProfileGroup(callingUserId, targetUserId);
1034 } else {
1035 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1036 }
1037 if (!allow) {
1038 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1039 // In this case, they would like to just execute as their
1040 // owner user instead of failing.
1041 targetUserId = callingUserId;
1042 } else {
1043 StringBuilder builder = new StringBuilder(128);
1044 builder.append("Permission Denial: ");
1045 builder.append(name);
1046 if (callerPackage != null) {
1047 builder.append(" from ");
1048 builder.append(callerPackage);
1049 }
1050 builder.append(" asks to run as user ");
1051 builder.append(userId);
1052 builder.append(" but is calling from user ");
1053 builder.append(UserHandle.getUserId(callingUid));
1054 builder.append("; this requires ");
1055 builder.append(INTERACT_ACROSS_USERS_FULL);
1056 if (allowMode != ALLOW_FULL_ONLY) {
1057 builder.append(" or ");
1058 builder.append(INTERACT_ACROSS_USERS);
1059 }
1060 String msg = builder.toString();
1061 Slog.w(TAG, msg);
1062 throw new SecurityException(msg);
1063 }
1064 }
1065 }
1066 if (!allowAll && targetUserId < 0) {
1067 throw new IllegalArgumentException(
1068 "Call does not support special user #" + targetUserId);
1069 }
1070 // Check shell permission
1071 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1072 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1073 throw new SecurityException("Shell does not have permission to access user "
1074 + targetUserId + "\n " + Debug.getCallers(3));
1075 }
1076 }
1077 return targetUserId;
1078 }
1079
1080 int unsafeConvertIncomingUserLocked(int userId) {
1081 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1082 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001083 }
1084
1085 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1086 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1087 != PackageManager.PERMISSION_GRANTED) {
1088 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1089 + Binder.getCallingPid()
1090 + ", uid=" + Binder.getCallingUid()
1091 + " requires " + INTERACT_ACROSS_USERS_FULL;
1092 Slog.w(TAG, msg);
1093 throw new SecurityException(msg);
1094 }
1095
1096 mUserSwitchObservers.register(observer);
1097 }
1098
1099 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1100 mUserSwitchObservers.unregister(observer);
1101 }
1102
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001103 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001104 return mStartedUsers.get(userId);
1105 }
1106
1107 boolean hasStartedUserState(int userId) {
1108 return mStartedUsers.get(userId) != null;
1109 }
1110
1111 private void updateStartedUserArrayLocked() {
1112 int num = 0;
1113 for (int i = 0; i < mStartedUsers.size(); i++) {
1114 UserState uss = mStartedUsers.valueAt(i);
1115 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001116 if (uss.state != UserState.STATE_STOPPING
1117 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001118 num++;
1119 }
1120 }
1121 mStartedUserArray = new int[num];
1122 num = 0;
1123 for (int i = 0; i < mStartedUsers.size(); i++) {
1124 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001125 if (uss.state != UserState.STATE_STOPPING
1126 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001127 mStartedUserArray[num] = mStartedUsers.keyAt(i);
1128 num++;
1129 }
1130 }
1131 }
1132
1133 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1134 for (int i = 0; i < mStartedUsers.size(); i++) {
1135 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001136 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001137 }
1138 }
1139
1140 /**
1141 * Refreshes the list of users related to the current user when either a
1142 * user switch happens or when a new related user is started in the
1143 * background.
1144 */
1145 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001146 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001147 false /* enabledOnly */);
1148 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1149 for (int i = 0; i < currentProfileIds.length; i++) {
1150 currentProfileIds[i] = profiles.get(i).id;
1151 }
1152 mCurrentProfileIds = currentProfileIds;
1153
1154 synchronized (mUserProfileGroupIdsSelfLocked) {
1155 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001156 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001157 for (int i = 0; i < users.size(); i++) {
1158 UserInfo user = users.get(i);
1159 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1160 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1161 }
1162 }
1163 }
1164 }
1165
1166 int[] getStartedUserArrayLocked() {
1167 return mStartedUserArray;
1168 }
1169
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001170 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001171 UserState state = getStartedUserStateLocked(userId);
1172 if (state == null) {
1173 return false;
1174 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001175 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001176 return true;
1177 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001178
1179 final boolean unlocked;
1180 switch (state.state) {
1181 case UserState.STATE_STOPPING:
1182 case UserState.STATE_SHUTDOWN:
1183 default:
1184 return false;
1185
1186 case UserState.STATE_BOOTING:
1187 case UserState.STATE_RUNNING_LOCKED:
1188 unlocked = false;
1189 break;
1190
1191 case UserState.STATE_RUNNING:
1192 unlocked = true;
1193 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001194 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001195
1196 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1197 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001198 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001199 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1200 return unlocked;
1201 }
1202
1203 // One way or another, we're running!
1204 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001205 }
1206
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001207 UserInfo getCurrentUser() {
1208 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1209 != PackageManager.PERMISSION_GRANTED) && (
1210 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1211 != PackageManager.PERMISSION_GRANTED)) {
1212 String msg = "Permission Denial: getCurrentUser() from pid="
1213 + Binder.getCallingPid()
1214 + ", uid=" + Binder.getCallingUid()
1215 + " requires " + INTERACT_ACROSS_USERS;
1216 Slog.w(TAG, msg);
1217 throw new SecurityException(msg);
1218 }
1219 synchronized (mService) {
1220 return getCurrentUserLocked();
1221 }
1222 }
1223
1224 UserInfo getCurrentUserLocked() {
1225 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001226 return getUserInfo(userId);
1227 }
1228
1229 int getCurrentOrTargetUserIdLocked() {
1230 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001231 }
1232
1233 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001234 return mCurrentUserId;
1235 }
1236
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001237 private boolean isCurrentUserLocked(int userId) {
Amith Yamasani458ac462015-12-18 11:21:31 -08001238 return userId == getCurrentOrTargetUserIdLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001239 }
1240
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001241 int setTargetUserIdLocked(int targetUserId) {
1242 return mTargetUserId = targetUserId;
1243 }
1244
1245 int[] getUsers() {
1246 UserManagerService ums = getUserManager();
1247 return ums != null ? ums.getUserIds() : new int[] { 0 };
1248 }
1249
1250 UserInfo getUserInfo(int userId) {
1251 return getUserManager().getUserInfo(userId);
1252 }
1253
1254 int[] getUserIds() {
1255 return getUserManager().getUserIds();
1256 }
1257
1258 boolean exists(int userId) {
1259 return getUserManager().exists(userId);
1260 }
1261
1262 boolean hasUserRestriction(String restriction, int userId) {
1263 return getUserManager().hasUserRestriction(restriction, userId);
1264 }
1265
1266 Set<Integer> getProfileIds(int userId) {
1267 Set<Integer> userIds = new HashSet<>();
1268 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1269 false /* enabledOnly */);
1270 for (UserInfo user : profiles) {
1271 userIds.add(user.id);
1272 }
1273 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001274 }
1275
1276 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1277 synchronized (mUserProfileGroupIdsSelfLocked) {
1278 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1279 UserInfo.NO_PROFILE_GROUP_ID);
1280 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1281 UserInfo.NO_PROFILE_GROUP_ID);
1282 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1283 && callingProfile == targetProfile;
1284 }
1285 }
1286
1287 boolean isCurrentProfileLocked(int userId) {
1288 return ArrayUtils.contains(mCurrentProfileIds, userId);
1289 }
1290
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001291 int[] getCurrentProfileIdsLocked() {
1292 return mCurrentProfileIds;
1293 }
1294
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001295 /**
1296 * Returns whether the given user requires credential entry at this time. This is used to
1297 * intercept activity launches for work apps when the Work Challenge is present.
1298 */
1299 boolean shouldConfirmCredentials(int userId) {
Clara Bayarria1771112015-12-18 16:29:18 +00001300 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001301 return false;
1302 }
1303 final KeyguardManager km = (KeyguardManager) mService.mContext
1304 .getSystemService(KEYGUARD_SERVICE);
Clara Bayarria1771112015-12-18 16:29:18 +00001305 return km.isDeviceLocked(userId);
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001306 }
1307
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001308 void dump(PrintWriter pw, boolean dumpAll) {
1309 pw.println(" mStartedUsers:");
1310 for (int i = 0; i < mStartedUsers.size(); i++) {
1311 UserState uss = mStartedUsers.valueAt(i);
1312 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1313 pw.print(": "); uss.dump("", pw);
1314 }
1315 pw.print(" mStartedUserArray: [");
1316 for (int i = 0; i < mStartedUserArray.length; i++) {
1317 if (i > 0) pw.print(", ");
1318 pw.print(mStartedUserArray[i]);
1319 }
1320 pw.println("]");
1321 pw.print(" mUserLru: [");
1322 for (int i = 0; i < mUserLru.size(); i++) {
1323 if (i > 0) pw.print(", ");
1324 pw.print(mUserLru.get(i));
1325 }
1326 pw.println("]");
1327 if (dumpAll) {
1328 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1329 }
1330 synchronized (mUserProfileGroupIdsSelfLocked) {
1331 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1332 pw.println(" mUserProfileGroupIds:");
1333 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1334 pw.print(" User #");
1335 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1336 pw.print(" -> profile #");
1337 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1338 }
1339 }
1340 }
1341 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001342}