blob: 195465c96a314f645ba35e0b7b954d1ee8cff69d [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;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070025import static android.os.Process.SYSTEM_UID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070026import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
27import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
28import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070029import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
30import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
31import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
32import static com.android.server.am.ActivityManagerService.MY_PID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070033import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
34import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
35import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
36import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -070037import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070038import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
39
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070040import android.annotation.NonNull;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070041import android.app.ActivityManager;
42import android.app.AppOpsManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070043import android.app.Dialog;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070044import android.app.IStopUserCallback;
45import android.app.IUserSwitchObserver;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070046import android.content.Context;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070047import android.content.IIntentReceiver;
48import android.content.Intent;
49import android.content.pm.PackageManager;
50import android.content.pm.UserInfo;
51import android.os.BatteryStats;
52import android.os.Binder;
53import android.os.Bundle;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070054import android.os.Debug;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070055import android.os.Handler;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070056import android.os.IBinder;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070057import android.os.IRemoteCallback;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070058import android.os.IUserManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070059import android.os.Process;
60import android.os.RemoteCallbackList;
61import android.os.RemoteException;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070062import android.os.ServiceManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070063import android.os.UserHandle;
64import android.os.UserManager;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080065import android.os.storage.IMountService;
66import android.os.storage.StorageManager;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070067import android.util.IntArray;
Suprabh Shukla4fe508b2015-11-20 18:22:57 -080068import android.util.Pair;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070069import android.util.Slog;
70import android.util.SparseArray;
71import android.util.SparseIntArray;
72
73import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080074import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070075import com.android.internal.util.ArrayUtils;
76import com.android.server.pm.UserManagerService;
77
78import java.io.PrintWriter;
79import java.util.ArrayList;
80import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070081import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070082import java.util.List;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070083import java.util.Set;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070084
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070085import libcore.util.EmptyArray;
86
Fyodor Kupolov610acda2015-10-19 18:44:07 -070087/**
88 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
89 */
90final class UserController {
91 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
92 // Maximum number of users we allow to be running at a time.
93 static final int MAX_RUNNING_USERS = 3;
94
95 // Amount of time we wait for observers to handle a user switch before
96 // giving up on them and unfreezing the screen.
97 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
98
99 private final ActivityManagerService mService;
100 private final Handler mHandler;
101
102 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700103 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700104 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700105 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700106
107 /**
108 * Which users have been started, so are allowed to run code.
109 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800110 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700111 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800112
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700113 /**
114 * LRU list of history of current users. Most recently current is at the end.
115 */
116 private final ArrayList<Integer> mUserLru = new ArrayList<>();
117
118 /**
119 * Constant array of the users that are currently started.
120 */
121 private int[] mStartedUserArray = new int[] { 0 };
122
123 // If there are multiple profiles for the current user, their ids are here
124 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700125 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700126
127 /**
128 * Mapping from each known user ID to the profile group ID it is associated with.
129 */
130 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
131
132 /**
133 * Registered observers of the user switching mechanics.
134 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700135 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700136 = new RemoteCallbackList<>();
137
138 /**
139 * Currently active user switch.
140 */
141 Object mCurUserSwitchCallback;
142
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700143 private volatile UserManagerService mUserManager;
144
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700145 UserController(ActivityManagerService service) {
146 mService = service;
147 mHandler = mService.mHandler;
148 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800149 final UserState uss = new UserState(UserHandle.SYSTEM);
150 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700151 mUserLru.add(UserHandle.USER_SYSTEM);
152 updateStartedUserArrayLocked();
153 }
154
155 void finishUserSwitch(UserState uss) {
156 synchronized (mService) {
157 finishUserBoot(uss);
158
159 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700160 stopRunningUsersLocked(MAX_RUNNING_USERS);
161 }
162 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700163
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700164 void stopRunningUsersLocked(int maxRunningUsers) {
165 int num = mUserLru.size();
166 int i = 0;
167 while (num > maxRunningUsers && i < mUserLru.size()) {
168 Integer oldUserId = mUserLru.get(i);
169 UserState oldUss = mStartedUsers.get(oldUserId);
170 if (oldUss == null) {
171 // Shouldn't happen, but be sane if it does.
172 mUserLru.remove(i);
173 num--;
174 continue;
175 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700176 if (oldUss.state == UserState.STATE_STOPPING
177 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700178 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700179 num--;
180 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700181 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700182 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700183 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
184 // Owner/System user and current user can't be stopped. We count it as running
185 // when it is not a pure system user.
186 if (UserInfo.isSystemOnly(oldUserId)) {
187 num--;
188 }
189 i++;
190 continue;
191 }
192 // This is a user to be stopped.
193 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
194 num--;
195 }
196 num--;
197 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700198 }
199 }
200
201 void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700202 finishUserBoot(uss, null);
203 }
204
205 void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
206 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700207 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700208 // Bail if we ended up with a stale user
209 if (mStartedUsers.get(userId) != uss) return;
210
211 // We always walk through all the user lifecycle states to send
212 // consistent developer events. We step into RUNNING_LOCKED here,
213 // but we might immediately step into RUNNING below if the user
214 // storage is already unlocked.
215 if (uss.state == UserState.STATE_BOOTING) {
216 uss.setState(UserState.STATE_RUNNING_LOCKED);
217
218 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700219 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
220 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700221 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
222 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
223 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
224 }
225
226 maybeFinishUserUnlock(uss);
227 }
228 }
229
230 /**
231 * Consider stepping from {@link UserState#STATE_RUNNING_LOCKED} into
232 * {@link UserState#STATE_RUNNING}, which only occurs if the user storage is
233 * actually unlocked.
234 */
235 void maybeFinishUserUnlock(UserState uss) {
236 final int userId = uss.mHandle.getIdentifier();
237 synchronized (mService) {
238 // Bail if we ended up with a stale user
239 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
240
241 // Only keep marching forward if user is actually unlocked
242 if (!isUserKeyUnlocked(userId)) return;
243
244 if (uss.state == UserState.STATE_RUNNING_LOCKED) {
245 uss.setState(UserState.STATE_RUNNING);
246
247 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
248
249 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
250 unlockedIntent.addFlags(
251 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
252 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
253 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
254 userId);
255
256 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
257 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
258 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
259 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
260 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700261 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700262 }
263 }
264 }
265
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700266 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700267 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
268 != PackageManager.PERMISSION_GRANTED) {
269 String msg = "Permission Denial: switchUser() from pid="
270 + Binder.getCallingPid()
271 + ", uid=" + Binder.getCallingUid()
272 + " requires " + INTERACT_ACROSS_USERS_FULL;
273 Slog.w(TAG, msg);
274 throw new SecurityException(msg);
275 }
276 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
277 throw new IllegalArgumentException("Can't stop system user " + userId);
278 }
279 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
280 userId);
281 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700282 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700283 }
284 }
285
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700286 /**
287 * Stops the user along with its related users. The method calls
288 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
289 */
290 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
291 if (userId == UserHandle.USER_SYSTEM) {
292 return USER_OP_ERROR_IS_SYSTEM;
293 }
294 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700295 return USER_OP_IS_CURRENT;
296 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700297 int[] usersToStop = getUsersToStopLocked(userId);
298 // If one of related users is system or current, no related users should be stopped
299 for (int i = 0; i < usersToStop.length; i++) {
300 int relatedUserId = usersToStop[i];
301 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
302 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
303 + relatedUserId);
304 // We still need to stop the requested user if it's a force stop.
305 if (force) {
306 stopSingleUserLocked(userId, callback);
307 }
308 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
309 }
310 }
311 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
312 for (int userIdToStop : usersToStop) {
313 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
314 }
315 return USER_OP_SUCCESS;
316 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700317
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700318 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
319 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700320 final UserState uss = mStartedUsers.get(userId);
321 if (uss == null) {
322 // User is not started, nothing to do... but we do need to
323 // callback if requested.
324 if (callback != null) {
325 mHandler.post(new Runnable() {
326 @Override
327 public void run() {
328 try {
329 callback.userStopped(userId);
330 } catch (RemoteException e) {
331 }
332 }
333 });
334 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700335 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700336 }
337
338 if (callback != null) {
339 uss.mStopCallbacks.add(callback);
340 }
341
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700342 if (uss.state != UserState.STATE_STOPPING
343 && uss.state != UserState.STATE_SHUTDOWN) {
344 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700345 updateStartedUserArrayLocked();
346
347 long ident = Binder.clearCallingIdentity();
348 try {
349 // We are going to broadcast ACTION_USER_STOPPING and then
350 // once that is done send a final ACTION_SHUTDOWN and then
351 // stop the user.
352 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
353 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
354 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
355 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
356 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
357 // This is the result receiver for the final shutdown broadcast.
358 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
359 @Override
360 public void performReceive(Intent intent, int resultCode, String data,
361 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
362 finishUserStop(uss);
363 }
364 };
365 // This is the result receiver for the initial stopping broadcast.
366 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
367 @Override
368 public void performReceive(Intent intent, int resultCode, String data,
369 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
370 // On to the next.
371 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700372 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700373 // Whoops, we are being started back up. Abort, abort!
374 return;
375 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700376 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700377 }
378 mService.mBatteryStatsService.noteEvent(
379 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
380 Integer.toString(userId), userId);
381 mService.mSystemServiceManager.stopUser(userId);
382 mService.broadcastIntentLocked(null, null, shutdownIntent,
383 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700384 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700385 }
386 };
387 // Kick things off.
388 mService.broadcastIntentLocked(null, null, stoppingIntent,
389 null, stoppingReceiver, 0, null, null,
390 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700391 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700392 } finally {
393 Binder.restoreCallingIdentity(ident);
394 }
395 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700396 }
397
398 void finishUserStop(UserState uss) {
399 final int userId = uss.mHandle.getIdentifier();
400 boolean stopped;
401 ArrayList<IStopUserCallback> callbacks;
402 synchronized (mService) {
403 callbacks = new ArrayList<>(uss.mStopCallbacks);
404 if (mStartedUsers.get(userId) != uss) {
405 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700406 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700407 stopped = false;
408 } else {
409 stopped = true;
410 // User can no longer run.
411 mStartedUsers.remove(userId);
412 mUserLru.remove(Integer.valueOf(userId));
413 updateStartedUserArrayLocked();
414
415 // Clean up all state and processes associated with the user.
416 // Kill all the processes for the user.
417 forceStopUserLocked(userId, "finish user");
418 }
419 }
420
421 for (int i = 0; i < callbacks.size(); i++) {
422 try {
423 if (stopped) callbacks.get(i).userStopped(userId);
424 else callbacks.get(i).userStopAborted(userId);
425 } catch (RemoteException e) {
426 }
427 }
428
429 if (stopped) {
430 mService.mSystemServiceManager.cleanupUser(userId);
431 synchronized (mService) {
432 mService.mStackSupervisor.removeUserLocked(userId);
433 }
434 }
435 }
436
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700437 /**
438 * Determines the list of users that should be stopped together with the specified
439 * {@code userId}. The returned list includes {@code userId}.
440 */
441 private @NonNull int[] getUsersToStopLocked(int userId) {
442 int startedUsersSize = mStartedUsers.size();
443 IntArray userIds = new IntArray();
444 userIds.add(userId);
445 synchronized (mUserProfileGroupIdsSelfLocked) {
446 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
447 UserInfo.NO_PROFILE_GROUP_ID);
448 for (int i = 0; i < startedUsersSize; i++) {
449 UserState uss = mStartedUsers.valueAt(i);
450 int startedUserId = uss.mHandle.getIdentifier();
451 // Skip unrelated users (profileGroupId mismatch)
452 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
453 UserInfo.NO_PROFILE_GROUP_ID);
454 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
455 && (userGroupId == startedUserGroupId);
456 // userId has already been added
457 boolean sameUserId = startedUserId == userId;
458 if (!sameGroup || sameUserId) {
459 continue;
460 }
461 userIds.add(startedUserId);
462 }
463 }
464 return userIds.toArray();
465 }
466
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700467 private void forceStopUserLocked(int userId, String reason) {
468 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
469 userId, reason);
470 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
471 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
472 | Intent.FLAG_RECEIVER_FOREGROUND);
473 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
474 mService.broadcastIntentLocked(null, null, intent,
475 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700476 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700477 }
478
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700479 /**
480 * Stops the guest user if it has gone to the background.
481 */
482 private void stopGuestUserIfBackground() {
483 synchronized (mService) {
484 final int num = mUserLru.size();
485 for (int i = 0; i < num; i++) {
486 Integer oldUserId = mUserLru.get(i);
487 UserState oldUss = mStartedUsers.get(oldUserId);
488 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700489 || oldUss.state == UserState.STATE_STOPPING
490 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700491 continue;
492 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700493 UserInfo userInfo = getUserInfo(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700494 if (userInfo.isGuest()) {
495 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700496 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700497 break;
498 }
499 }
500 }
501 }
502
503 void startProfilesLocked() {
504 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700505 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700506 mCurrentUserId, false /* enabledOnly */);
507 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
508 for (UserInfo user : profiles) {
509 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
510 && user.id != mCurrentUserId) {
511 profilesToStart.add(user);
512 }
513 }
514 final int profilesToStartSize = profilesToStart.size();
515 int i = 0;
516 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
517 startUser(profilesToStart.get(i).id, /* foreground= */ false);
518 }
519 if (i < profilesToStartSize) {
520 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
521 }
522 }
523
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700524 private UserManagerService getUserManager() {
525 UserManagerService userManager = mUserManager;
526 if (userManager == null) {
527 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
528 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
529 }
530 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700531 }
532
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700533 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800534 final IMountService mountService = IMountService.Stub
Jeff Sharkeyba512352015-11-12 20:17:45 -0800535 .asInterface(ServiceManager.getService("mount"));
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800536 if (mountService != null) {
537 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700538 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800539 } catch (RemoteException e) {
540 throw e.rethrowAsRuntimeException();
541 }
542 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700543 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
544 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800545 }
546 }
547
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700548 boolean startUser(final int userId, final boolean foreground) {
549 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
550 != PackageManager.PERMISSION_GRANTED) {
551 String msg = "Permission Denial: switchUser() from pid="
552 + Binder.getCallingPid()
553 + ", uid=" + Binder.getCallingUid()
554 + " requires " + INTERACT_ACROSS_USERS_FULL;
555 Slog.w(TAG, msg);
556 throw new SecurityException(msg);
557 }
558
559 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
560
561 final long ident = Binder.clearCallingIdentity();
562 try {
563 synchronized (mService) {
564 final int oldUserId = mCurrentUserId;
565 if (oldUserId == userId) {
566 return true;
567 }
568
569 mService.mStackSupervisor.setLockTaskModeLocked(null,
570 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
571
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700572 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700573 if (userInfo == null) {
574 Slog.w(TAG, "No user info for user #" + userId);
575 return false;
576 }
577 if (foreground && userInfo.isManagedProfile()) {
578 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
579 return false;
580 }
581
582 if (foreground) {
583 mService.mWindowManager.startFreezingScreen(
584 R.anim.screen_user_exit, R.anim.screen_user_enter);
585 }
586
587 boolean needStart = false;
588
589 // If the user we are switching to is not currently started, then
590 // we need to start it now.
591 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700592 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700593 updateStartedUserArrayLocked();
594 needStart = true;
595 }
596
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800597 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700598 final Integer userIdInt = userId;
599 mUserLru.remove(userIdInt);
600 mUserLru.add(userIdInt);
601
602 if (foreground) {
603 mCurrentUserId = userId;
604 mService.updateUserConfigurationLocked();
605 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
606 updateCurrentProfileIdsLocked();
607 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
608 // Once the internal notion of the active user has switched, we lock the device
609 // with the option to show the user switcher on the keyguard.
610 mService.mWindowManager.lockNow(null);
611 } else {
612 final Integer currentUserIdInt = mCurrentUserId;
613 updateCurrentProfileIdsLocked();
614 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
615 mUserLru.remove(currentUserIdInt);
616 mUserLru.add(currentUserIdInt);
617 }
618
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700619 // Make sure user is in the started state. If it is currently
620 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700621 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700622 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
623 // so we can just fairly silently bring the user back from
624 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700625 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700626 updateStartedUserArrayLocked();
627 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700628 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700629 // This means ACTION_SHUTDOWN has been sent, so we will
630 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700631 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700632 updateStartedUserArrayLocked();
633 needStart = true;
634 }
635
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700636 if (uss.state == UserState.STATE_BOOTING) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800637 // Let user manager propagate user restrictions to other services.
638 getUserManager().onBeforeStartUser(userId);
639
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700640 // Booting up a new user, need to tell system services about it.
641 // Note that this is on the same handler as scheduling of broadcasts,
642 // which is important because it needs to go first.
643 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
644 }
645
646 if (foreground) {
647 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
648 oldUserId));
649 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
650 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
651 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
652 oldUserId, userId, uss));
653 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
654 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
655 }
656
657 if (needStart) {
658 // Send USER_STARTED broadcast
659 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
660 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
661 | Intent.FLAG_RECEIVER_FOREGROUND);
662 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
663 mService.broadcastIntentLocked(null, null, intent,
664 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700665 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700666 }
667
668 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
669 if (userId != UserHandle.USER_SYSTEM) {
670 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
671 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
672 mService.broadcastIntentLocked(null, null, intent, null,
673 new IIntentReceiver.Stub() {
674 public void performReceive(Intent intent, int resultCode,
675 String data, Bundle extras, boolean ordered,
676 boolean sticky, int sendingUser) {
677 onUserInitialized(uss, foreground, oldUserId, userId);
678 }
679 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700680 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700681 uss.initializing = true;
682 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700683 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700684 }
685 }
686
687 if (foreground) {
688 if (!uss.initializing) {
689 moveUserToForegroundLocked(uss, oldUserId, userId);
690 }
691 } else {
692 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
693 }
694
695 if (needStart) {
696 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
697 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
698 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
699 mService.broadcastIntentLocked(null, null, intent,
700 null, new IIntentReceiver.Stub() {
701 @Override
702 public void performReceive(Intent intent, int resultCode,
703 String data, Bundle extras, boolean ordered, boolean sticky,
704 int sendingUser) throws RemoteException {
705 }
706 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700707 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
708 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700709 }
710 }
711 } finally {
712 Binder.restoreCallingIdentity(ident);
713 }
714
715 return true;
716 }
717
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700718 /**
719 * Start user, if its not already running, and bring it to foreground.
720 */
721 boolean startUserInForeground(final int userId, Dialog dlg) {
722 boolean result = startUser(userId, /* foreground */ true);
723 dlg.dismiss();
724 return result;
725 }
726
Jeff Sharkeyba512352015-11-12 20:17:45 -0800727 boolean unlockUser(final int userId, byte[] token) {
728 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
729 != PackageManager.PERMISSION_GRANTED) {
730 String msg = "Permission Denial: unlockUser() from pid="
731 + Binder.getCallingPid()
732 + ", uid=" + Binder.getCallingUid()
733 + " requires " + INTERACT_ACROSS_USERS_FULL;
734 Slog.w(TAG, msg);
735 throw new SecurityException(msg);
736 }
737
Jeff Sharkey8924e872015-11-30 12:52:10 -0700738 final long binderToken = Binder.clearCallingIdentity();
739 try {
740 return unlockUserCleared(userId, token);
741 } finally {
742 Binder.restoreCallingIdentity(binderToken);
743 }
744 }
745
746 boolean unlockUserCleared(final int userId, byte[] token) {
747 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700748 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700749 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700750 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700751 }
752
Jeff Sharkeyba512352015-11-12 20:17:45 -0800753 final UserInfo userInfo = getUserInfo(userId);
754 final IMountService mountService = IMountService.Stub
755 .asInterface(ServiceManager.getService("mount"));
756 try {
757 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
758 } catch (RemoteException e) {
759 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
Jeff Sharkey8924e872015-11-30 12:52:10 -0700760 return false;
Jeff Sharkeyba512352015-11-12 20:17:45 -0800761 }
762
763 synchronized (mService) {
764 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700765 maybeFinishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800766 }
767
768 return true;
769 }
770
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800771 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700772 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800773 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
774 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700775 d.show();
776 }
777
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700778 void dispatchForegroundProfileChanged(int userId) {
779 final int observerCount = mUserSwitchObservers.beginBroadcast();
780 for (int i = 0; i < observerCount; i++) {
781 try {
782 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
783 } catch (RemoteException e) {
784 // Ignore
785 }
786 }
787 mUserSwitchObservers.finishBroadcast();
788 }
789
790 /** Called on handler thread */
791 void dispatchUserSwitchComplete(int userId) {
792 final int observerCount = mUserSwitchObservers.beginBroadcast();
793 for (int i = 0; i < observerCount; i++) {
794 try {
795 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
796 } catch (RemoteException e) {
797 }
798 }
799 mUserSwitchObservers.finishBroadcast();
800 }
801
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700802 private void stopBackgroundUsersIfEnforced(int oldUserId) {
803 // Never stop system user
804 if (oldUserId == UserHandle.USER_SYSTEM) {
805 return;
806 }
807 // For now, only check for user restriction. Additional checks can be added here
808 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
809 oldUserId);
810 if (!disallowRunInBg) {
811 return;
812 }
813 synchronized (mService) {
814 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
815 + " and related users");
816 stopUsersLocked(oldUserId, false, null);
817 }
818 }
819
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700820 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
821 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800822 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700823 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
824 }
825 }
826
827 void dispatchUserSwitch(final UserState uss, final int oldUserId,
828 final int newUserId) {
829 final int observerCount = mUserSwitchObservers.beginBroadcast();
830 if (observerCount > 0) {
831 final IRemoteCallback callback = new IRemoteCallback.Stub() {
832 int mCount = 0;
833 @Override
834 public void sendResult(Bundle data) throws RemoteException {
835 synchronized (mService) {
836 if (mCurUserSwitchCallback == this) {
837 mCount++;
838 if (mCount == observerCount) {
839 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
840 }
841 }
842 }
843 }
844 };
845 synchronized (mService) {
846 uss.switching = true;
847 mCurUserSwitchCallback = callback;
848 }
849 for (int i = 0; i < observerCount; i++) {
850 try {
851 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
852 newUserId, callback);
853 } catch (RemoteException e) {
854 }
855 }
856 } else {
857 synchronized (mService) {
858 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
859 }
860 }
861 mUserSwitchObservers.finishBroadcast();
862 }
863
864 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
865 mCurUserSwitchCallback = null;
866 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
867 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
868 oldUserId, newUserId, uss));
869 }
870
871 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700872 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700873 }
874
875 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
876 synchronized (mService) {
877 if (foreground) {
878 moveUserToForegroundLocked(uss, oldUserId, newUserId);
879 }
880 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700881 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700882 }
883
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700884 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700885 boolean clearInitializing, boolean clearSwitching) {
886 boolean unfrozen = false;
887 synchronized (mService) {
888 if (clearInitializing) {
889 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700890 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700891 }
892 if (clearSwitching) {
893 uss.switching = false;
894 }
895 if (!uss.switching && !uss.initializing) {
896 mService.mWindowManager.stopFreezingScreen();
897 unfrozen = true;
898 }
899 }
900 if (unfrozen) {
901 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
902 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
903 newUserId, 0));
904 }
905 stopGuestUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700906 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700907 }
908
909 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
910 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
911 if (homeInFront) {
912 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
913 } else {
914 mService.mStackSupervisor.resumeTopActivitiesLocked();
915 }
916 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700917 getUserManager().onUserForeground(newUserId);
918 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
919 }
920
921 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
922 long ident = Binder.clearCallingIdentity();
923 try {
924 Intent intent;
925 if (oldUserId >= 0) {
926 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
927 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
928 int count = profiles.size();
929 for (int i = 0; i < count; i++) {
930 int profileUserId = profiles.get(i).id;
931 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
932 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
933 | Intent.FLAG_RECEIVER_FOREGROUND);
934 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
935 mService.broadcastIntentLocked(null, null, intent,
936 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
937 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
938 }
939 }
940 if (newUserId >= 0) {
941 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
942 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
943 int count = profiles.size();
944 for (int i = 0; i < count; i++) {
945 int profileUserId = profiles.get(i).id;
946 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
947 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
948 | Intent.FLAG_RECEIVER_FOREGROUND);
949 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
950 mService.broadcastIntentLocked(null, null, intent,
951 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
952 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
953 }
954 intent = new Intent(Intent.ACTION_USER_SWITCHED);
955 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
956 | Intent.FLAG_RECEIVER_FOREGROUND);
957 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
958 mService.broadcastIntentLocked(null, null, intent,
959 null, null, 0, null, null,
960 new String[] {android.Manifest.permission.MANAGE_USERS},
961 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
962 UserHandle.USER_ALL);
963 }
964 } finally {
965 Binder.restoreCallingIdentity(ident);
966 }
967 }
968
969
970 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
971 int allowMode, String name, String callerPackage) {
972 final int callingUserId = UserHandle.getUserId(callingUid);
973 if (callingUserId == userId) {
974 return userId;
975 }
976
977 // Note that we may be accessing mCurrentUserId outside of a lock...
978 // shouldn't be a big deal, if this is being called outside
979 // of a locked context there is intrinsically a race with
980 // the value the caller will receive and someone else changing it.
981 // We assume that USER_CURRENT_OR_SELF will use the current user; later
982 // we will switch to the calling user if access to the current user fails.
983 int targetUserId = unsafeConvertIncomingUserLocked(userId);
984
985 if (callingUid != 0 && callingUid != SYSTEM_UID) {
986 final boolean allow;
987 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
988 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
989 // If the caller has this permission, they always pass go. And collect $200.
990 allow = true;
991 } else if (allowMode == ALLOW_FULL_ONLY) {
992 // We require full access, sucks to be you.
993 allow = false;
994 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
995 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
996 // If the caller does not have either permission, they are always doomed.
997 allow = false;
998 } else if (allowMode == ALLOW_NON_FULL) {
999 // We are blanket allowing non-full access, you lucky caller!
1000 allow = true;
1001 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1002 // We may or may not allow this depending on whether the two users are
1003 // in the same profile.
1004 allow = isSameProfileGroup(callingUserId, targetUserId);
1005 } else {
1006 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1007 }
1008 if (!allow) {
1009 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1010 // In this case, they would like to just execute as their
1011 // owner user instead of failing.
1012 targetUserId = callingUserId;
1013 } else {
1014 StringBuilder builder = new StringBuilder(128);
1015 builder.append("Permission Denial: ");
1016 builder.append(name);
1017 if (callerPackage != null) {
1018 builder.append(" from ");
1019 builder.append(callerPackage);
1020 }
1021 builder.append(" asks to run as user ");
1022 builder.append(userId);
1023 builder.append(" but is calling from user ");
1024 builder.append(UserHandle.getUserId(callingUid));
1025 builder.append("; this requires ");
1026 builder.append(INTERACT_ACROSS_USERS_FULL);
1027 if (allowMode != ALLOW_FULL_ONLY) {
1028 builder.append(" or ");
1029 builder.append(INTERACT_ACROSS_USERS);
1030 }
1031 String msg = builder.toString();
1032 Slog.w(TAG, msg);
1033 throw new SecurityException(msg);
1034 }
1035 }
1036 }
1037 if (!allowAll && targetUserId < 0) {
1038 throw new IllegalArgumentException(
1039 "Call does not support special user #" + targetUserId);
1040 }
1041 // Check shell permission
1042 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1043 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1044 throw new SecurityException("Shell does not have permission to access user "
1045 + targetUserId + "\n " + Debug.getCallers(3));
1046 }
1047 }
1048 return targetUserId;
1049 }
1050
1051 int unsafeConvertIncomingUserLocked(int userId) {
1052 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1053 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001054 }
1055
1056 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1057 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1058 != PackageManager.PERMISSION_GRANTED) {
1059 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1060 + Binder.getCallingPid()
1061 + ", uid=" + Binder.getCallingUid()
1062 + " requires " + INTERACT_ACROSS_USERS_FULL;
1063 Slog.w(TAG, msg);
1064 throw new SecurityException(msg);
1065 }
1066
1067 mUserSwitchObservers.register(observer);
1068 }
1069
1070 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1071 mUserSwitchObservers.unregister(observer);
1072 }
1073
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001074 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001075 return mStartedUsers.get(userId);
1076 }
1077
1078 boolean hasStartedUserState(int userId) {
1079 return mStartedUsers.get(userId) != null;
1080 }
1081
1082 private void updateStartedUserArrayLocked() {
1083 int num = 0;
1084 for (int i = 0; i < mStartedUsers.size(); i++) {
1085 UserState uss = mStartedUsers.valueAt(i);
1086 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001087 if (uss.state != UserState.STATE_STOPPING
1088 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001089 num++;
1090 }
1091 }
1092 mStartedUserArray = new int[num];
1093 num = 0;
1094 for (int i = 0; i < mStartedUsers.size(); i++) {
1095 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001096 if (uss.state != UserState.STATE_STOPPING
1097 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001098 mStartedUserArray[num] = mStartedUsers.keyAt(i);
1099 num++;
1100 }
1101 }
1102 }
1103
1104 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1105 for (int i = 0; i < mStartedUsers.size(); i++) {
1106 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001107 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001108 }
1109 }
1110
1111 /**
1112 * Refreshes the list of users related to the current user when either a
1113 * user switch happens or when a new related user is started in the
1114 * background.
1115 */
1116 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001117 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001118 false /* enabledOnly */);
1119 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1120 for (int i = 0; i < currentProfileIds.length; i++) {
1121 currentProfileIds[i] = profiles.get(i).id;
1122 }
1123 mCurrentProfileIds = currentProfileIds;
1124
1125 synchronized (mUserProfileGroupIdsSelfLocked) {
1126 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001127 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001128 for (int i = 0; i < users.size(); i++) {
1129 UserInfo user = users.get(i);
1130 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1131 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1132 }
1133 }
1134 }
1135 }
1136
1137 int[] getStartedUserArrayLocked() {
1138 return mStartedUserArray;
1139 }
1140
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001141 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001142 UserState state = getStartedUserStateLocked(userId);
1143 if (state == null) {
1144 return false;
1145 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001146 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001147 return true;
1148 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001149
1150 final boolean unlocked;
1151 switch (state.state) {
1152 case UserState.STATE_STOPPING:
1153 case UserState.STATE_SHUTDOWN:
1154 default:
1155 return false;
1156
1157 case UserState.STATE_BOOTING:
1158 case UserState.STATE_RUNNING_LOCKED:
1159 unlocked = false;
1160 break;
1161
1162 case UserState.STATE_RUNNING:
1163 unlocked = true;
1164 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001165 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001166
1167 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1168 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001169 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001170 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1171 return unlocked;
1172 }
1173
1174 // One way or another, we're running!
1175 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001176 }
1177
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001178 UserInfo getCurrentUser() {
1179 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1180 != PackageManager.PERMISSION_GRANTED) && (
1181 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1182 != PackageManager.PERMISSION_GRANTED)) {
1183 String msg = "Permission Denial: getCurrentUser() from pid="
1184 + Binder.getCallingPid()
1185 + ", uid=" + Binder.getCallingUid()
1186 + " requires " + INTERACT_ACROSS_USERS;
1187 Slog.w(TAG, msg);
1188 throw new SecurityException(msg);
1189 }
1190 synchronized (mService) {
1191 return getCurrentUserLocked();
1192 }
1193 }
1194
1195 UserInfo getCurrentUserLocked() {
1196 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001197 return getUserInfo(userId);
1198 }
1199
1200 int getCurrentOrTargetUserIdLocked() {
1201 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001202 }
1203
1204 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001205 return mCurrentUserId;
1206 }
1207
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001208 private boolean isCurrentUserLocked(int userId) {
1209 return mCurrentUserId == userId || mTargetUserId == userId;
1210 }
1211
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001212 int setTargetUserIdLocked(int targetUserId) {
1213 return mTargetUserId = targetUserId;
1214 }
1215
1216 int[] getUsers() {
1217 UserManagerService ums = getUserManager();
1218 return ums != null ? ums.getUserIds() : new int[] { 0 };
1219 }
1220
1221 UserInfo getUserInfo(int userId) {
1222 return getUserManager().getUserInfo(userId);
1223 }
1224
1225 int[] getUserIds() {
1226 return getUserManager().getUserIds();
1227 }
1228
1229 boolean exists(int userId) {
1230 return getUserManager().exists(userId);
1231 }
1232
1233 boolean hasUserRestriction(String restriction, int userId) {
1234 return getUserManager().hasUserRestriction(restriction, userId);
1235 }
1236
1237 Set<Integer> getProfileIds(int userId) {
1238 Set<Integer> userIds = new HashSet<>();
1239 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1240 false /* enabledOnly */);
1241 for (UserInfo user : profiles) {
1242 userIds.add(user.id);
1243 }
1244 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001245 }
1246
1247 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1248 synchronized (mUserProfileGroupIdsSelfLocked) {
1249 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1250 UserInfo.NO_PROFILE_GROUP_ID);
1251 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1252 UserInfo.NO_PROFILE_GROUP_ID);
1253 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1254 && callingProfile == targetProfile;
1255 }
1256 }
1257
1258 boolean isCurrentProfileLocked(int userId) {
1259 return ArrayUtils.contains(mCurrentProfileIds, userId);
1260 }
1261
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001262 int[] getCurrentProfileIdsLocked() {
1263 return mCurrentProfileIds;
1264 }
1265
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001266 void dump(PrintWriter pw, boolean dumpAll) {
1267 pw.println(" mStartedUsers:");
1268 for (int i = 0; i < mStartedUsers.size(); i++) {
1269 UserState uss = mStartedUsers.valueAt(i);
1270 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1271 pw.print(": "); uss.dump("", pw);
1272 }
1273 pw.print(" mStartedUserArray: [");
1274 for (int i = 0; i < mStartedUserArray.length; i++) {
1275 if (i > 0) pw.print(", ");
1276 pw.print(mStartedUserArray[i]);
1277 }
1278 pw.println("]");
1279 pw.print(" mUserLru: [");
1280 for (int i = 0; i < mUserLru.size(); i++) {
1281 if (i > 0) pw.print(", ");
1282 pw.print(mUserLru.get(i));
1283 }
1284 pw.println("]");
1285 if (dumpAll) {
1286 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1287 }
1288 synchronized (mUserProfileGroupIdsSelfLocked) {
1289 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1290 pw.println(" mUserProfileGroupIds:");
1291 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1292 pw.print(" User #");
1293 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1294 pw.print(" -> profile #");
1295 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1296 }
1297 }
1298 }
1299 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001300}