blob: 6e51316bfb73993551f8502157d8a256f9699439 [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
85/**
86 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
87 */
88final class UserController {
89 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
90 // Maximum number of users we allow to be running at a time.
91 static final int MAX_RUNNING_USERS = 3;
92
93 // Amount of time we wait for observers to handle a user switch before
94 // giving up on them and unfreezing the screen.
95 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
96
97 private final ActivityManagerService mService;
98 private final Handler mHandler;
99
100 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700101 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700102 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700103 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700104
105 /**
106 * Which users have been started, so are allowed to run code.
107 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800108 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700109 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800110
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700111 /**
112 * LRU list of history of current users. Most recently current is at the end.
113 */
114 private final ArrayList<Integer> mUserLru = new ArrayList<>();
115
116 /**
117 * Constant array of the users that are currently started.
118 */
119 private int[] mStartedUserArray = new int[] { 0 };
120
121 // If there are multiple profiles for the current user, their ids are here
122 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700123 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700124
125 /**
126 * Mapping from each known user ID to the profile group ID it is associated with.
127 */
128 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
129
130 /**
131 * Registered observers of the user switching mechanics.
132 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700133 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700134 = new RemoteCallbackList<>();
135
136 /**
137 * Currently active user switch.
138 */
139 Object mCurUserSwitchCallback;
140
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700141 private volatile UserManagerService mUserManager;
142
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700143 UserController(ActivityManagerService service) {
144 mService = service;
145 mHandler = mService.mHandler;
146 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800147 final UserState uss = new UserState(UserHandle.SYSTEM);
148 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700149 mUserLru.add(UserHandle.USER_SYSTEM);
150 updateStartedUserArrayLocked();
151 }
152
153 void finishUserSwitch(UserState uss) {
154 synchronized (mService) {
155 finishUserBoot(uss);
156
157 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700158 stopRunningUsersLocked(MAX_RUNNING_USERS);
159 }
160 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700161
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700162 void stopRunningUsersLocked(int maxRunningUsers) {
163 int num = mUserLru.size();
164 int i = 0;
165 while (num > maxRunningUsers && i < mUserLru.size()) {
166 Integer oldUserId = mUserLru.get(i);
167 UserState oldUss = mStartedUsers.get(oldUserId);
168 if (oldUss == null) {
169 // Shouldn't happen, but be sane if it does.
170 mUserLru.remove(i);
171 num--;
172 continue;
173 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700174 if (oldUss.state == UserState.STATE_STOPPING
175 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700176 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700177 num--;
178 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700179 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700180 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700181 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
182 // Owner/System user and current user can't be stopped. We count it as running
183 // when it is not a pure system user.
184 if (UserInfo.isSystemOnly(oldUserId)) {
185 num--;
186 }
187 i++;
188 continue;
189 }
190 // This is a user to be stopped.
191 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
192 num--;
193 }
194 num--;
195 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700196 }
197 }
198
199 void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700200 finishUserBoot(uss, null);
201 }
202
203 void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
204 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700205 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700206 // Bail if we ended up with a stale user
207 if (mStartedUsers.get(userId) != uss) return;
208
209 // We always walk through all the user lifecycle states to send
210 // consistent developer events. We step into RUNNING_LOCKED here,
211 // but we might immediately step into RUNNING below if the user
212 // storage is already unlocked.
213 if (uss.state == UserState.STATE_BOOTING) {
214 uss.setState(UserState.STATE_RUNNING_LOCKED);
215
216 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700217 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeya242f822015-12-17 15:38:20 -0700218 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
219 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700220 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
221 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
222 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
223 }
224
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700225 maybeUnlockUser(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700226 }
227 }
228
229 /**
230 * Consider stepping from {@link UserState#STATE_RUNNING_LOCKED} into
231 * {@link UserState#STATE_RUNNING}, which only occurs if the user storage is
232 * actually unlocked.
233 */
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700234 void finishUserUnlock(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700235 final int userId = uss.mHandle.getIdentifier();
236 synchronized (mService) {
237 // Bail if we ended up with a stale user
238 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
239
240 // Only keep marching forward if user is actually unlocked
241 if (!isUserKeyUnlocked(userId)) return;
242
243 if (uss.state == UserState.STATE_RUNNING_LOCKED) {
244 uss.setState(UserState.STATE_RUNNING);
245
246 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
247
248 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700249 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700250 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);
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -0800258 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
259 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700260 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
261 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700262 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700263 }
264 }
265 }
266
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700267 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700268 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
269 != PackageManager.PERMISSION_GRANTED) {
270 String msg = "Permission Denial: switchUser() from pid="
271 + Binder.getCallingPid()
272 + ", uid=" + Binder.getCallingUid()
273 + " requires " + INTERACT_ACROSS_USERS_FULL;
274 Slog.w(TAG, msg);
275 throw new SecurityException(msg);
276 }
277 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
278 throw new IllegalArgumentException("Can't stop system user " + userId);
279 }
280 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
281 userId);
282 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700283 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700284 }
285 }
286
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700287 /**
288 * Stops the user along with its related users. The method calls
289 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
290 */
291 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
292 if (userId == UserHandle.USER_SYSTEM) {
293 return USER_OP_ERROR_IS_SYSTEM;
294 }
295 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700296 return USER_OP_IS_CURRENT;
297 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700298 int[] usersToStop = getUsersToStopLocked(userId);
299 // If one of related users is system or current, no related users should be stopped
300 for (int i = 0; i < usersToStop.length; i++) {
301 int relatedUserId = usersToStop[i];
302 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
303 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
304 + relatedUserId);
305 // We still need to stop the requested user if it's a force stop.
306 if (force) {
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800307 Slog.i(TAG,
308 "Force stop user " + userId + ". Related users will not be stopped");
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700309 stopSingleUserLocked(userId, callback);
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800310 return USER_OP_SUCCESS;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700311 }
312 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
313 }
314 }
315 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
316 for (int userIdToStop : usersToStop) {
317 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
318 }
319 return USER_OP_SUCCESS;
320 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700321
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700322 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
323 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700324 final UserState uss = mStartedUsers.get(userId);
325 if (uss == null) {
326 // User is not started, nothing to do... but we do need to
327 // callback if requested.
328 if (callback != null) {
329 mHandler.post(new Runnable() {
330 @Override
331 public void run() {
332 try {
333 callback.userStopped(userId);
334 } catch (RemoteException e) {
335 }
336 }
337 });
338 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700339 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700340 }
341
342 if (callback != null) {
343 uss.mStopCallbacks.add(callback);
344 }
345
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700346 if (uss.state != UserState.STATE_STOPPING
347 && uss.state != UserState.STATE_SHUTDOWN) {
348 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700349 updateStartedUserArrayLocked();
350
351 long ident = Binder.clearCallingIdentity();
352 try {
353 // We are going to broadcast ACTION_USER_STOPPING and then
354 // once that is done send a final ACTION_SHUTDOWN and then
355 // stop the user.
356 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
357 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
358 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
359 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
360 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
361 // This is the result receiver for the final shutdown broadcast.
362 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
363 @Override
364 public void performReceive(Intent intent, int resultCode, String data,
365 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
366 finishUserStop(uss);
367 }
368 };
369 // This is the result receiver for the initial stopping broadcast.
370 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
371 @Override
372 public void performReceive(Intent intent, int resultCode, String data,
373 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
374 // On to the next.
375 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700376 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700377 // Whoops, we are being started back up. Abort, abort!
378 return;
379 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700380 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700381 }
382 mService.mBatteryStatsService.noteEvent(
383 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
384 Integer.toString(userId), userId);
385 mService.mSystemServiceManager.stopUser(userId);
386 mService.broadcastIntentLocked(null, null, shutdownIntent,
387 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700388 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700389 }
390 };
391 // Kick things off.
392 mService.broadcastIntentLocked(null, null, stoppingIntent,
393 null, stoppingReceiver, 0, null, null,
394 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700395 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700396 } finally {
397 Binder.restoreCallingIdentity(ident);
398 }
399 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700400 }
401
402 void finishUserStop(UserState uss) {
403 final int userId = uss.mHandle.getIdentifier();
404 boolean stopped;
405 ArrayList<IStopUserCallback> callbacks;
406 synchronized (mService) {
407 callbacks = new ArrayList<>(uss.mStopCallbacks);
408 if (mStartedUsers.get(userId) != uss) {
409 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700410 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700411 stopped = false;
412 } else {
413 stopped = true;
414 // User can no longer run.
415 mStartedUsers.remove(userId);
416 mUserLru.remove(Integer.valueOf(userId));
417 updateStartedUserArrayLocked();
418
419 // Clean up all state and processes associated with the user.
420 // Kill all the processes for the user.
421 forceStopUserLocked(userId, "finish user");
422 }
423 }
424
425 for (int i = 0; i < callbacks.size(); i++) {
426 try {
427 if (stopped) callbacks.get(i).userStopped(userId);
428 else callbacks.get(i).userStopAborted(userId);
429 } catch (RemoteException e) {
430 }
431 }
432
433 if (stopped) {
434 mService.mSystemServiceManager.cleanupUser(userId);
435 synchronized (mService) {
436 mService.mStackSupervisor.removeUserLocked(userId);
437 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100438 // Remove the user if it is ephemeral.
439 if (getUserInfo(userId).isEphemeral()) {
440 mUserManager.removeUser(userId);
441 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700442 }
443 }
444
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700445 /**
446 * Determines the list of users that should be stopped together with the specified
447 * {@code userId}. The returned list includes {@code userId}.
448 */
449 private @NonNull int[] getUsersToStopLocked(int userId) {
450 int startedUsersSize = mStartedUsers.size();
451 IntArray userIds = new IntArray();
452 userIds.add(userId);
453 synchronized (mUserProfileGroupIdsSelfLocked) {
454 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
455 UserInfo.NO_PROFILE_GROUP_ID);
456 for (int i = 0; i < startedUsersSize; i++) {
457 UserState uss = mStartedUsers.valueAt(i);
458 int startedUserId = uss.mHandle.getIdentifier();
459 // Skip unrelated users (profileGroupId mismatch)
460 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
461 UserInfo.NO_PROFILE_GROUP_ID);
462 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
463 && (userGroupId == startedUserGroupId);
464 // userId has already been added
465 boolean sameUserId = startedUserId == userId;
466 if (!sameGroup || sameUserId) {
467 continue;
468 }
469 userIds.add(startedUserId);
470 }
471 }
472 return userIds.toArray();
473 }
474
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700475 private void forceStopUserLocked(int userId, String reason) {
476 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
477 userId, reason);
478 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
479 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
480 | Intent.FLAG_RECEIVER_FOREGROUND);
481 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
482 mService.broadcastIntentLocked(null, null, intent,
483 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700484 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700485 }
486
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700487 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100488 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700489 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100490 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700491 synchronized (mService) {
492 final int num = mUserLru.size();
493 for (int i = 0; i < num; i++) {
494 Integer oldUserId = mUserLru.get(i);
495 UserState oldUss = mStartedUsers.get(oldUserId);
496 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700497 || oldUss.state == UserState.STATE_STOPPING
498 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700499 continue;
500 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700501 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100502 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700503 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700504 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700505 break;
506 }
507 }
508 }
509 }
510
511 void startProfilesLocked() {
512 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700513 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700514 mCurrentUserId, false /* enabledOnly */);
515 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
516 for (UserInfo user : profiles) {
517 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
518 && user.id != mCurrentUserId) {
519 profilesToStart.add(user);
520 }
521 }
522 final int profilesToStartSize = profilesToStart.size();
523 int i = 0;
524 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
525 startUser(profilesToStart.get(i).id, /* foreground= */ false);
526 }
527 if (i < profilesToStartSize) {
528 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
529 }
530 }
531
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700532 private UserManagerService getUserManager() {
533 UserManagerService userManager = mUserManager;
534 if (userManager == null) {
535 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
536 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
537 }
538 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700539 }
540
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700541 private IMountService getMountService() {
542 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
543 }
544
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700545 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700546 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800547 if (mountService != null) {
548 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700549 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800550 } catch (RemoteException e) {
551 throw e.rethrowAsRuntimeException();
552 }
553 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700554 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
555 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800556 }
557 }
558
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700559 boolean startUser(final int userId, final boolean foreground) {
560 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
561 != PackageManager.PERMISSION_GRANTED) {
562 String msg = "Permission Denial: switchUser() from pid="
563 + Binder.getCallingPid()
564 + ", uid=" + Binder.getCallingUid()
565 + " requires " + INTERACT_ACROSS_USERS_FULL;
566 Slog.w(TAG, msg);
567 throw new SecurityException(msg);
568 }
569
570 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
571
572 final long ident = Binder.clearCallingIdentity();
573 try {
574 synchronized (mService) {
575 final int oldUserId = mCurrentUserId;
576 if (oldUserId == userId) {
577 return true;
578 }
579
580 mService.mStackSupervisor.setLockTaskModeLocked(null,
581 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
582
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700583 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700584 if (userInfo == null) {
585 Slog.w(TAG, "No user info for user #" + userId);
586 return false;
587 }
588 if (foreground && userInfo.isManagedProfile()) {
589 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
590 return false;
591 }
592
593 if (foreground) {
594 mService.mWindowManager.startFreezingScreen(
595 R.anim.screen_user_exit, R.anim.screen_user_enter);
596 }
597
598 boolean needStart = false;
599
600 // If the user we are switching to is not currently started, then
601 // we need to start it now.
602 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700603 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700604 updateStartedUserArrayLocked();
605 needStart = true;
606 }
607
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800608 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700609 final Integer userIdInt = userId;
610 mUserLru.remove(userIdInt);
611 mUserLru.add(userIdInt);
612
613 if (foreground) {
614 mCurrentUserId = userId;
615 mService.updateUserConfigurationLocked();
616 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
617 updateCurrentProfileIdsLocked();
618 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
619 // Once the internal notion of the active user has switched, we lock the device
620 // with the option to show the user switcher on the keyguard.
621 mService.mWindowManager.lockNow(null);
622 } else {
623 final Integer currentUserIdInt = mCurrentUserId;
624 updateCurrentProfileIdsLocked();
625 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
626 mUserLru.remove(currentUserIdInt);
627 mUserLru.add(currentUserIdInt);
628 }
629
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700630 // Make sure user is in the started state. If it is currently
631 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700632 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700633 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
634 // so we can just fairly silently bring the user back from
635 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700636 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700637 updateStartedUserArrayLocked();
638 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700639 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700640 // This means ACTION_SHUTDOWN has been sent, so we will
641 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700642 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700643 updateStartedUserArrayLocked();
644 needStart = true;
645 }
646
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700647 if (uss.state == UserState.STATE_BOOTING) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800648 // Let user manager propagate user restrictions to other services.
649 getUserManager().onBeforeStartUser(userId);
650
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700651 // Booting up a new user, need to tell system services about it.
652 // Note that this is on the same handler as scheduling of broadcasts,
653 // which is important because it needs to go first.
654 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
655 }
656
657 if (foreground) {
658 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
659 oldUserId));
660 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
661 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
662 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
663 oldUserId, userId, uss));
664 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
665 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
666 }
667
668 if (needStart) {
669 // Send USER_STARTED broadcast
670 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
671 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
672 | Intent.FLAG_RECEIVER_FOREGROUND);
673 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
674 mService.broadcastIntentLocked(null, null, intent,
675 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700676 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700677 }
678
679 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
680 if (userId != UserHandle.USER_SYSTEM) {
681 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
682 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
683 mService.broadcastIntentLocked(null, null, intent, null,
684 new IIntentReceiver.Stub() {
685 public void performReceive(Intent intent, int resultCode,
686 String data, Bundle extras, boolean ordered,
687 boolean sticky, int sendingUser) {
688 onUserInitialized(uss, foreground, oldUserId, userId);
689 }
690 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700691 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700692 uss.initializing = true;
693 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700694 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700695 }
696 }
697
698 if (foreground) {
699 if (!uss.initializing) {
700 moveUserToForegroundLocked(uss, oldUserId, userId);
701 }
702 } else {
703 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
704 }
705
706 if (needStart) {
707 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
708 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
709 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
710 mService.broadcastIntentLocked(null, null, intent,
711 null, new IIntentReceiver.Stub() {
712 @Override
713 public void performReceive(Intent intent, int resultCode,
714 String data, Bundle extras, boolean ordered, boolean sticky,
715 int sendingUser) throws RemoteException {
716 }
717 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700718 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
719 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700720 }
721 }
722 } finally {
723 Binder.restoreCallingIdentity(ident);
724 }
725
726 return true;
727 }
728
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700729 /**
730 * Start user, if its not already running, and bring it to foreground.
731 */
732 boolean startUserInForeground(final int userId, Dialog dlg) {
733 boolean result = startUser(userId, /* foreground */ true);
734 dlg.dismiss();
735 return result;
736 }
737
Jeff Sharkeyba512352015-11-12 20:17:45 -0800738 boolean unlockUser(final int userId, byte[] token) {
739 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
740 != PackageManager.PERMISSION_GRANTED) {
741 String msg = "Permission Denial: unlockUser() from pid="
742 + Binder.getCallingPid()
743 + ", uid=" + Binder.getCallingUid()
744 + " requires " + INTERACT_ACROSS_USERS_FULL;
745 Slog.w(TAG, msg);
746 throw new SecurityException(msg);
747 }
748
Jeff Sharkey8924e872015-11-30 12:52:10 -0700749 final long binderToken = Binder.clearCallingIdentity();
750 try {
751 return unlockUserCleared(userId, token);
752 } finally {
753 Binder.restoreCallingIdentity(binderToken);
754 }
755 }
756
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700757 /**
758 * Attempt to unlock user without a credential token. This typically
759 * succeeds when the device doesn't have credential-encrypted storage, or
760 * when the the credential-encrypted storage isn't tied to a user-provided
761 * PIN or pattern.
762 */
763 boolean maybeUnlockUser(final int userId) {
764 // Try unlocking storage using empty token
765 return unlockUserCleared(userId, null);
766 }
767
Jeff Sharkey8924e872015-11-30 12:52:10 -0700768 boolean unlockUserCleared(final int userId, byte[] token) {
769 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700770 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700771 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700772 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700773 }
774
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700775 if (!isUserKeyUnlocked(userId)) {
776 final UserInfo userInfo = getUserInfo(userId);
777 final IMountService mountService = getMountService();
778 try {
779 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
780 } catch (RemoteException | RuntimeException e) {
781 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
782 return false;
783 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800784 }
785
786 synchronized (mService) {
787 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700788 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800789 }
790
791 return true;
792 }
793
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800794 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700795 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800796 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
797 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700798 d.show();
799 }
800
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700801 void dispatchForegroundProfileChanged(int userId) {
802 final int observerCount = mUserSwitchObservers.beginBroadcast();
803 for (int i = 0; i < observerCount; i++) {
804 try {
805 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
806 } catch (RemoteException e) {
807 // Ignore
808 }
809 }
810 mUserSwitchObservers.finishBroadcast();
811 }
812
813 /** Called on handler thread */
814 void dispatchUserSwitchComplete(int userId) {
815 final int observerCount = mUserSwitchObservers.beginBroadcast();
816 for (int i = 0; i < observerCount; i++) {
817 try {
818 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
819 } catch (RemoteException e) {
820 }
821 }
822 mUserSwitchObservers.finishBroadcast();
823 }
824
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700825 private void stopBackgroundUsersIfEnforced(int oldUserId) {
826 // Never stop system user
827 if (oldUserId == UserHandle.USER_SYSTEM) {
828 return;
829 }
830 // For now, only check for user restriction. Additional checks can be added here
831 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
832 oldUserId);
833 if (!disallowRunInBg) {
834 return;
835 }
836 synchronized (mService) {
837 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
838 + " and related users");
839 stopUsersLocked(oldUserId, false, null);
840 }
841 }
842
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700843 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
844 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800845 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700846 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
847 }
848 }
849
850 void dispatchUserSwitch(final UserState uss, final int oldUserId,
851 final int newUserId) {
852 final int observerCount = mUserSwitchObservers.beginBroadcast();
853 if (observerCount > 0) {
854 final IRemoteCallback callback = new IRemoteCallback.Stub() {
855 int mCount = 0;
856 @Override
857 public void sendResult(Bundle data) throws RemoteException {
858 synchronized (mService) {
859 if (mCurUserSwitchCallback == this) {
860 mCount++;
861 if (mCount == observerCount) {
862 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
863 }
864 }
865 }
866 }
867 };
868 synchronized (mService) {
869 uss.switching = true;
870 mCurUserSwitchCallback = callback;
871 }
872 for (int i = 0; i < observerCount; i++) {
873 try {
874 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
875 newUserId, callback);
876 } catch (RemoteException e) {
877 }
878 }
879 } else {
880 synchronized (mService) {
881 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
882 }
883 }
884 mUserSwitchObservers.finishBroadcast();
885 }
886
887 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
888 mCurUserSwitchCallback = null;
889 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
890 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
891 oldUserId, newUserId, uss));
892 }
893
894 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700895 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700896 }
897
898 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
899 synchronized (mService) {
900 if (foreground) {
901 moveUserToForegroundLocked(uss, oldUserId, newUserId);
902 }
903 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700904 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700905 }
906
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700907 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700908 boolean clearInitializing, boolean clearSwitching) {
909 boolean unfrozen = false;
910 synchronized (mService) {
911 if (clearInitializing) {
912 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700913 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700914 }
915 if (clearSwitching) {
916 uss.switching = false;
917 }
918 if (!uss.switching && !uss.initializing) {
919 mService.mWindowManager.stopFreezingScreen();
920 unfrozen = true;
921 }
922 }
923 if (unfrozen) {
924 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
925 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
926 newUserId, 0));
927 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100928 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700929 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700930 }
931
932 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
933 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
934 if (homeInFront) {
935 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
936 } else {
937 mService.mStackSupervisor.resumeTopActivitiesLocked();
938 }
939 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700940 getUserManager().onUserForeground(newUserId);
941 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
942 }
943
944 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
945 long ident = Binder.clearCallingIdentity();
946 try {
947 Intent intent;
948 if (oldUserId >= 0) {
949 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
950 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
951 int count = profiles.size();
952 for (int i = 0; i < count; i++) {
953 int profileUserId = profiles.get(i).id;
954 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
955 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
956 | Intent.FLAG_RECEIVER_FOREGROUND);
957 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
958 mService.broadcastIntentLocked(null, null, intent,
959 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
960 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
961 }
962 }
963 if (newUserId >= 0) {
964 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
965 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
966 int count = profiles.size();
967 for (int i = 0; i < count; i++) {
968 int profileUserId = profiles.get(i).id;
969 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
970 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
971 | Intent.FLAG_RECEIVER_FOREGROUND);
972 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
973 mService.broadcastIntentLocked(null, null, intent,
974 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
975 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
976 }
977 intent = new Intent(Intent.ACTION_USER_SWITCHED);
978 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
979 | Intent.FLAG_RECEIVER_FOREGROUND);
980 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
981 mService.broadcastIntentLocked(null, null, intent,
982 null, null, 0, null, null,
983 new String[] {android.Manifest.permission.MANAGE_USERS},
984 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
985 UserHandle.USER_ALL);
986 }
987 } finally {
988 Binder.restoreCallingIdentity(ident);
989 }
990 }
991
992
993 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
994 int allowMode, String name, String callerPackage) {
995 final int callingUserId = UserHandle.getUserId(callingUid);
996 if (callingUserId == userId) {
997 return userId;
998 }
999
1000 // Note that we may be accessing mCurrentUserId outside of a lock...
1001 // shouldn't be a big deal, if this is being called outside
1002 // of a locked context there is intrinsically a race with
1003 // the value the caller will receive and someone else changing it.
1004 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1005 // we will switch to the calling user if access to the current user fails.
1006 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1007
1008 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1009 final boolean allow;
1010 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1011 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1012 // If the caller has this permission, they always pass go. And collect $200.
1013 allow = true;
1014 } else if (allowMode == ALLOW_FULL_ONLY) {
1015 // We require full access, sucks to be you.
1016 allow = false;
1017 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1018 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1019 // If the caller does not have either permission, they are always doomed.
1020 allow = false;
1021 } else if (allowMode == ALLOW_NON_FULL) {
1022 // We are blanket allowing non-full access, you lucky caller!
1023 allow = true;
1024 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1025 // We may or may not allow this depending on whether the two users are
1026 // in the same profile.
1027 allow = isSameProfileGroup(callingUserId, targetUserId);
1028 } else {
1029 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1030 }
1031 if (!allow) {
1032 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1033 // In this case, they would like to just execute as their
1034 // owner user instead of failing.
1035 targetUserId = callingUserId;
1036 } else {
1037 StringBuilder builder = new StringBuilder(128);
1038 builder.append("Permission Denial: ");
1039 builder.append(name);
1040 if (callerPackage != null) {
1041 builder.append(" from ");
1042 builder.append(callerPackage);
1043 }
1044 builder.append(" asks to run as user ");
1045 builder.append(userId);
1046 builder.append(" but is calling from user ");
1047 builder.append(UserHandle.getUserId(callingUid));
1048 builder.append("; this requires ");
1049 builder.append(INTERACT_ACROSS_USERS_FULL);
1050 if (allowMode != ALLOW_FULL_ONLY) {
1051 builder.append(" or ");
1052 builder.append(INTERACT_ACROSS_USERS);
1053 }
1054 String msg = builder.toString();
1055 Slog.w(TAG, msg);
1056 throw new SecurityException(msg);
1057 }
1058 }
1059 }
1060 if (!allowAll && targetUserId < 0) {
1061 throw new IllegalArgumentException(
1062 "Call does not support special user #" + targetUserId);
1063 }
1064 // Check shell permission
1065 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1066 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1067 throw new SecurityException("Shell does not have permission to access user "
1068 + targetUserId + "\n " + Debug.getCallers(3));
1069 }
1070 }
1071 return targetUserId;
1072 }
1073
1074 int unsafeConvertIncomingUserLocked(int userId) {
1075 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1076 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001077 }
1078
1079 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1080 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1081 != PackageManager.PERMISSION_GRANTED) {
1082 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1083 + Binder.getCallingPid()
1084 + ", uid=" + Binder.getCallingUid()
1085 + " requires " + INTERACT_ACROSS_USERS_FULL;
1086 Slog.w(TAG, msg);
1087 throw new SecurityException(msg);
1088 }
1089
1090 mUserSwitchObservers.register(observer);
1091 }
1092
1093 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1094 mUserSwitchObservers.unregister(observer);
1095 }
1096
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001097 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001098 return mStartedUsers.get(userId);
1099 }
1100
1101 boolean hasStartedUserState(int userId) {
1102 return mStartedUsers.get(userId) != null;
1103 }
1104
1105 private void updateStartedUserArrayLocked() {
1106 int num = 0;
1107 for (int i = 0; i < mStartedUsers.size(); i++) {
1108 UserState uss = mStartedUsers.valueAt(i);
1109 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001110 if (uss.state != UserState.STATE_STOPPING
1111 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001112 num++;
1113 }
1114 }
1115 mStartedUserArray = new int[num];
1116 num = 0;
1117 for (int i = 0; i < mStartedUsers.size(); i++) {
1118 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001119 if (uss.state != UserState.STATE_STOPPING
1120 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001121 mStartedUserArray[num] = mStartedUsers.keyAt(i);
1122 num++;
1123 }
1124 }
1125 }
1126
1127 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1128 for (int i = 0; i < mStartedUsers.size(); i++) {
1129 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001130 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001131 }
1132 }
1133
1134 /**
1135 * Refreshes the list of users related to the current user when either a
1136 * user switch happens or when a new related user is started in the
1137 * background.
1138 */
1139 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001140 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001141 false /* enabledOnly */);
1142 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1143 for (int i = 0; i < currentProfileIds.length; i++) {
1144 currentProfileIds[i] = profiles.get(i).id;
1145 }
1146 mCurrentProfileIds = currentProfileIds;
1147
1148 synchronized (mUserProfileGroupIdsSelfLocked) {
1149 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001150 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001151 for (int i = 0; i < users.size(); i++) {
1152 UserInfo user = users.get(i);
1153 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1154 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1155 }
1156 }
1157 }
1158 }
1159
1160 int[] getStartedUserArrayLocked() {
1161 return mStartedUserArray;
1162 }
1163
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001164 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001165 UserState state = getStartedUserStateLocked(userId);
1166 if (state == null) {
1167 return false;
1168 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001169 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001170 return true;
1171 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001172
1173 final boolean unlocked;
1174 switch (state.state) {
1175 case UserState.STATE_STOPPING:
1176 case UserState.STATE_SHUTDOWN:
1177 default:
1178 return false;
1179
1180 case UserState.STATE_BOOTING:
1181 case UserState.STATE_RUNNING_LOCKED:
1182 unlocked = false;
1183 break;
1184
1185 case UserState.STATE_RUNNING:
1186 unlocked = true;
1187 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001188 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001189
1190 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1191 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001192 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001193 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1194 return unlocked;
1195 }
1196
1197 // One way or another, we're running!
1198 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001199 }
1200
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001201 UserInfo getCurrentUser() {
1202 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1203 != PackageManager.PERMISSION_GRANTED) && (
1204 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1205 != PackageManager.PERMISSION_GRANTED)) {
1206 String msg = "Permission Denial: getCurrentUser() from pid="
1207 + Binder.getCallingPid()
1208 + ", uid=" + Binder.getCallingUid()
1209 + " requires " + INTERACT_ACROSS_USERS;
1210 Slog.w(TAG, msg);
1211 throw new SecurityException(msg);
1212 }
1213 synchronized (mService) {
1214 return getCurrentUserLocked();
1215 }
1216 }
1217
1218 UserInfo getCurrentUserLocked() {
1219 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001220 return getUserInfo(userId);
1221 }
1222
1223 int getCurrentOrTargetUserIdLocked() {
1224 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001225 }
1226
1227 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001228 return mCurrentUserId;
1229 }
1230
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001231 private boolean isCurrentUserLocked(int userId) {
Amith Yamasani458ac462015-12-18 11:21:31 -08001232 return userId == getCurrentOrTargetUserIdLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001233 }
1234
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001235 int setTargetUserIdLocked(int targetUserId) {
1236 return mTargetUserId = targetUserId;
1237 }
1238
1239 int[] getUsers() {
1240 UserManagerService ums = getUserManager();
1241 return ums != null ? ums.getUserIds() : new int[] { 0 };
1242 }
1243
1244 UserInfo getUserInfo(int userId) {
1245 return getUserManager().getUserInfo(userId);
1246 }
1247
1248 int[] getUserIds() {
1249 return getUserManager().getUserIds();
1250 }
1251
1252 boolean exists(int userId) {
1253 return getUserManager().exists(userId);
1254 }
1255
1256 boolean hasUserRestriction(String restriction, int userId) {
1257 return getUserManager().hasUserRestriction(restriction, userId);
1258 }
1259
1260 Set<Integer> getProfileIds(int userId) {
1261 Set<Integer> userIds = new HashSet<>();
1262 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1263 false /* enabledOnly */);
1264 for (UserInfo user : profiles) {
1265 userIds.add(user.id);
1266 }
1267 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001268 }
1269
1270 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1271 synchronized (mUserProfileGroupIdsSelfLocked) {
1272 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1273 UserInfo.NO_PROFILE_GROUP_ID);
1274 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1275 UserInfo.NO_PROFILE_GROUP_ID);
1276 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1277 && callingProfile == targetProfile;
1278 }
1279 }
1280
1281 boolean isCurrentProfileLocked(int userId) {
1282 return ArrayUtils.contains(mCurrentProfileIds, userId);
1283 }
1284
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001285 int[] getCurrentProfileIdsLocked() {
1286 return mCurrentProfileIds;
1287 }
1288
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001289 void dump(PrintWriter pw, boolean dumpAll) {
1290 pw.println(" mStartedUsers:");
1291 for (int i = 0; i < mStartedUsers.size(); i++) {
1292 UserState uss = mStartedUsers.valueAt(i);
1293 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1294 pw.print(": "); uss.dump("", pw);
1295 }
1296 pw.print(" mStartedUserArray: [");
1297 for (int i = 0; i < mStartedUserArray.length; i++) {
1298 if (i > 0) pw.print(", ");
1299 pw.print(mStartedUserArray[i]);
1300 }
1301 pw.println("]");
1302 pw.print(" mUserLru: [");
1303 for (int i = 0; i < mUserLru.size(); i++) {
1304 if (i > 0) pw.print(", ");
1305 pw.print(mUserLru.get(i));
1306 }
1307 pw.println("]");
1308 if (dumpAll) {
1309 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1310 }
1311 synchronized (mUserProfileGroupIdsSelfLocked) {
1312 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1313 pw.println(" mUserProfileGroupIds:");
1314 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1315 pw.print(" User #");
1316 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1317 pw.print(" -> profile #");
1318 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1319 }
1320 }
1321 }
1322 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001323}