blob: 62e78a456c98abcd04f20e126effe0d8a3216313 [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);
218 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700219 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
220 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
221 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
222 }
223
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700224 maybeUnlockUser(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700225 }
226 }
227
228 /**
229 * Consider stepping from {@link UserState#STATE_RUNNING_LOCKED} into
230 * {@link UserState#STATE_RUNNING}, which only occurs if the user storage is
231 * actually unlocked.
232 */
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700233 void finishUserUnlock(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700234 final int userId = uss.mHandle.getIdentifier();
235 synchronized (mService) {
236 // Bail if we ended up with a stale user
237 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
238
239 // Only keep marching forward if user is actually unlocked
240 if (!isUserKeyUnlocked(userId)) return;
241
242 if (uss.state == UserState.STATE_RUNNING_LOCKED) {
243 uss.setState(UserState.STATE_RUNNING);
244
245 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
246
247 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
248 unlockedIntent.addFlags(
249 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
250 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
251 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
252 userId);
253
254 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
255 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -0800256 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
257 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700258 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
259 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700260 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700261 }
262 }
263 }
264
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700265 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700266 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
267 != PackageManager.PERMISSION_GRANTED) {
268 String msg = "Permission Denial: switchUser() from pid="
269 + Binder.getCallingPid()
270 + ", uid=" + Binder.getCallingUid()
271 + " requires " + INTERACT_ACROSS_USERS_FULL;
272 Slog.w(TAG, msg);
273 throw new SecurityException(msg);
274 }
275 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
276 throw new IllegalArgumentException("Can't stop system user " + userId);
277 }
278 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
279 userId);
280 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700281 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700282 }
283 }
284
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700285 /**
286 * Stops the user along with its related users. The method calls
287 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
288 */
289 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
290 if (userId == UserHandle.USER_SYSTEM) {
291 return USER_OP_ERROR_IS_SYSTEM;
292 }
293 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700294 return USER_OP_IS_CURRENT;
295 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700296 int[] usersToStop = getUsersToStopLocked(userId);
297 // If one of related users is system or current, no related users should be stopped
298 for (int i = 0; i < usersToStop.length; i++) {
299 int relatedUserId = usersToStop[i];
300 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
301 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
302 + relatedUserId);
303 // We still need to stop the requested user if it's a force stop.
304 if (force) {
305 stopSingleUserLocked(userId, callback);
306 }
307 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
308 }
309 }
310 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
311 for (int userIdToStop : usersToStop) {
312 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
313 }
314 return USER_OP_SUCCESS;
315 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700316
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700317 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
318 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700319 final UserState uss = mStartedUsers.get(userId);
320 if (uss == null) {
321 // User is not started, nothing to do... but we do need to
322 // callback if requested.
323 if (callback != null) {
324 mHandler.post(new Runnable() {
325 @Override
326 public void run() {
327 try {
328 callback.userStopped(userId);
329 } catch (RemoteException e) {
330 }
331 }
332 });
333 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700334 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700335 }
336
337 if (callback != null) {
338 uss.mStopCallbacks.add(callback);
339 }
340
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700341 if (uss.state != UserState.STATE_STOPPING
342 && uss.state != UserState.STATE_SHUTDOWN) {
343 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700344 updateStartedUserArrayLocked();
345
346 long ident = Binder.clearCallingIdentity();
347 try {
348 // We are going to broadcast ACTION_USER_STOPPING and then
349 // once that is done send a final ACTION_SHUTDOWN and then
350 // stop the user.
351 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
352 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
353 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
354 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
355 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
356 // This is the result receiver for the final shutdown broadcast.
357 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
358 @Override
359 public void performReceive(Intent intent, int resultCode, String data,
360 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
361 finishUserStop(uss);
362 }
363 };
364 // This is the result receiver for the initial stopping broadcast.
365 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
366 @Override
367 public void performReceive(Intent intent, int resultCode, String data,
368 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
369 // On to the next.
370 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700371 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700372 // Whoops, we are being started back up. Abort, abort!
373 return;
374 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700375 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700376 }
377 mService.mBatteryStatsService.noteEvent(
378 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
379 Integer.toString(userId), userId);
380 mService.mSystemServiceManager.stopUser(userId);
381 mService.broadcastIntentLocked(null, null, shutdownIntent,
382 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700383 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700384 }
385 };
386 // Kick things off.
387 mService.broadcastIntentLocked(null, null, stoppingIntent,
388 null, stoppingReceiver, 0, null, null,
389 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700390 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700391 } finally {
392 Binder.restoreCallingIdentity(ident);
393 }
394 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700395 }
396
397 void finishUserStop(UserState uss) {
398 final int userId = uss.mHandle.getIdentifier();
399 boolean stopped;
400 ArrayList<IStopUserCallback> callbacks;
401 synchronized (mService) {
402 callbacks = new ArrayList<>(uss.mStopCallbacks);
403 if (mStartedUsers.get(userId) != uss) {
404 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700405 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700406 stopped = false;
407 } else {
408 stopped = true;
409 // User can no longer run.
410 mStartedUsers.remove(userId);
411 mUserLru.remove(Integer.valueOf(userId));
412 updateStartedUserArrayLocked();
413
414 // Clean up all state and processes associated with the user.
415 // Kill all the processes for the user.
416 forceStopUserLocked(userId, "finish user");
417 }
418 }
419
420 for (int i = 0; i < callbacks.size(); i++) {
421 try {
422 if (stopped) callbacks.get(i).userStopped(userId);
423 else callbacks.get(i).userStopAborted(userId);
424 } catch (RemoteException e) {
425 }
426 }
427
428 if (stopped) {
429 mService.mSystemServiceManager.cleanupUser(userId);
430 synchronized (mService) {
431 mService.mStackSupervisor.removeUserLocked(userId);
432 }
433 }
434 }
435
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700436 /**
437 * Determines the list of users that should be stopped together with the specified
438 * {@code userId}. The returned list includes {@code userId}.
439 */
440 private @NonNull int[] getUsersToStopLocked(int userId) {
441 int startedUsersSize = mStartedUsers.size();
442 IntArray userIds = new IntArray();
443 userIds.add(userId);
444 synchronized (mUserProfileGroupIdsSelfLocked) {
445 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
446 UserInfo.NO_PROFILE_GROUP_ID);
447 for (int i = 0; i < startedUsersSize; i++) {
448 UserState uss = mStartedUsers.valueAt(i);
449 int startedUserId = uss.mHandle.getIdentifier();
450 // Skip unrelated users (profileGroupId mismatch)
451 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
452 UserInfo.NO_PROFILE_GROUP_ID);
453 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
454 && (userGroupId == startedUserGroupId);
455 // userId has already been added
456 boolean sameUserId = startedUserId == userId;
457 if (!sameGroup || sameUserId) {
458 continue;
459 }
460 userIds.add(startedUserId);
461 }
462 }
463 return userIds.toArray();
464 }
465
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700466 private void forceStopUserLocked(int userId, String reason) {
467 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
468 userId, reason);
469 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
470 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
471 | Intent.FLAG_RECEIVER_FOREGROUND);
472 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
473 mService.broadcastIntentLocked(null, null, intent,
474 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700475 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700476 }
477
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700478 /**
479 * Stops the guest user if it has gone to the background.
480 */
481 private void stopGuestUserIfBackground() {
482 synchronized (mService) {
483 final int num = mUserLru.size();
484 for (int i = 0; i < num; i++) {
485 Integer oldUserId = mUserLru.get(i);
486 UserState oldUss = mStartedUsers.get(oldUserId);
487 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700488 || oldUss.state == UserState.STATE_STOPPING
489 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700490 continue;
491 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700492 UserInfo userInfo = getUserInfo(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700493 if (userInfo.isGuest()) {
494 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700495 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700496 break;
497 }
498 }
499 }
500 }
501
502 void startProfilesLocked() {
503 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700504 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700505 mCurrentUserId, false /* enabledOnly */);
506 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
507 for (UserInfo user : profiles) {
508 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
509 && user.id != mCurrentUserId) {
510 profilesToStart.add(user);
511 }
512 }
513 final int profilesToStartSize = profilesToStart.size();
514 int i = 0;
515 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
516 startUser(profilesToStart.get(i).id, /* foreground= */ false);
517 }
518 if (i < profilesToStartSize) {
519 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
520 }
521 }
522
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700523 private UserManagerService getUserManager() {
524 UserManagerService userManager = mUserManager;
525 if (userManager == null) {
526 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
527 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
528 }
529 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700530 }
531
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700532 private IMountService getMountService() {
533 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
534 }
535
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700536 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700537 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800538 if (mountService != null) {
539 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700540 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800541 } catch (RemoteException e) {
542 throw e.rethrowAsRuntimeException();
543 }
544 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700545 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
546 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800547 }
548 }
549
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700550 boolean startUser(final int userId, final boolean foreground) {
551 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
552 != PackageManager.PERMISSION_GRANTED) {
553 String msg = "Permission Denial: switchUser() from pid="
554 + Binder.getCallingPid()
555 + ", uid=" + Binder.getCallingUid()
556 + " requires " + INTERACT_ACROSS_USERS_FULL;
557 Slog.w(TAG, msg);
558 throw new SecurityException(msg);
559 }
560
561 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
562
563 final long ident = Binder.clearCallingIdentity();
564 try {
565 synchronized (mService) {
566 final int oldUserId = mCurrentUserId;
567 if (oldUserId == userId) {
568 return true;
569 }
570
571 mService.mStackSupervisor.setLockTaskModeLocked(null,
572 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
573
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700574 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700575 if (userInfo == null) {
576 Slog.w(TAG, "No user info for user #" + userId);
577 return false;
578 }
579 if (foreground && userInfo.isManagedProfile()) {
580 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
581 return false;
582 }
583
584 if (foreground) {
585 mService.mWindowManager.startFreezingScreen(
586 R.anim.screen_user_exit, R.anim.screen_user_enter);
587 }
588
589 boolean needStart = false;
590
591 // If the user we are switching to is not currently started, then
592 // we need to start it now.
593 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700594 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700595 updateStartedUserArrayLocked();
596 needStart = true;
597 }
598
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800599 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700600 final Integer userIdInt = userId;
601 mUserLru.remove(userIdInt);
602 mUserLru.add(userIdInt);
603
604 if (foreground) {
605 mCurrentUserId = userId;
606 mService.updateUserConfigurationLocked();
607 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
608 updateCurrentProfileIdsLocked();
609 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
610 // Once the internal notion of the active user has switched, we lock the device
611 // with the option to show the user switcher on the keyguard.
612 mService.mWindowManager.lockNow(null);
613 } else {
614 final Integer currentUserIdInt = mCurrentUserId;
615 updateCurrentProfileIdsLocked();
616 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
617 mUserLru.remove(currentUserIdInt);
618 mUserLru.add(currentUserIdInt);
619 }
620
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700621 // Make sure user is in the started state. If it is currently
622 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700623 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700624 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
625 // so we can just fairly silently bring the user back from
626 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700627 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700628 updateStartedUserArrayLocked();
629 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700630 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700631 // This means ACTION_SHUTDOWN has been sent, so we will
632 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700633 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700634 updateStartedUserArrayLocked();
635 needStart = true;
636 }
637
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700638 if (uss.state == UserState.STATE_BOOTING) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800639 // Let user manager propagate user restrictions to other services.
640 getUserManager().onBeforeStartUser(userId);
641
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700642 // Booting up a new user, need to tell system services about it.
643 // Note that this is on the same handler as scheduling of broadcasts,
644 // which is important because it needs to go first.
645 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
646 }
647
648 if (foreground) {
649 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
650 oldUserId));
651 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
652 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
653 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
654 oldUserId, userId, uss));
655 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
656 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
657 }
658
659 if (needStart) {
660 // Send USER_STARTED broadcast
661 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
662 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
663 | Intent.FLAG_RECEIVER_FOREGROUND);
664 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
665 mService.broadcastIntentLocked(null, null, intent,
666 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700667 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700668 }
669
670 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
671 if (userId != UserHandle.USER_SYSTEM) {
672 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
673 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
674 mService.broadcastIntentLocked(null, null, intent, null,
675 new IIntentReceiver.Stub() {
676 public void performReceive(Intent intent, int resultCode,
677 String data, Bundle extras, boolean ordered,
678 boolean sticky, int sendingUser) {
679 onUserInitialized(uss, foreground, oldUserId, userId);
680 }
681 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700682 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700683 uss.initializing = true;
684 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700685 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700686 }
687 }
688
689 if (foreground) {
690 if (!uss.initializing) {
691 moveUserToForegroundLocked(uss, oldUserId, userId);
692 }
693 } else {
694 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
695 }
696
697 if (needStart) {
698 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
699 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
700 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
701 mService.broadcastIntentLocked(null, null, intent,
702 null, new IIntentReceiver.Stub() {
703 @Override
704 public void performReceive(Intent intent, int resultCode,
705 String data, Bundle extras, boolean ordered, boolean sticky,
706 int sendingUser) throws RemoteException {
707 }
708 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700709 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
710 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700711 }
712 }
713 } finally {
714 Binder.restoreCallingIdentity(ident);
715 }
716
717 return true;
718 }
719
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700720 /**
721 * Start user, if its not already running, and bring it to foreground.
722 */
723 boolean startUserInForeground(final int userId, Dialog dlg) {
724 boolean result = startUser(userId, /* foreground */ true);
725 dlg.dismiss();
726 return result;
727 }
728
Jeff Sharkeyba512352015-11-12 20:17:45 -0800729 boolean unlockUser(final int userId, byte[] token) {
730 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
731 != PackageManager.PERMISSION_GRANTED) {
732 String msg = "Permission Denial: unlockUser() from pid="
733 + Binder.getCallingPid()
734 + ", uid=" + Binder.getCallingUid()
735 + " requires " + INTERACT_ACROSS_USERS_FULL;
736 Slog.w(TAG, msg);
737 throw new SecurityException(msg);
738 }
739
Jeff Sharkey8924e872015-11-30 12:52:10 -0700740 final long binderToken = Binder.clearCallingIdentity();
741 try {
742 return unlockUserCleared(userId, token);
743 } finally {
744 Binder.restoreCallingIdentity(binderToken);
745 }
746 }
747
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700748 /**
749 * Attempt to unlock user without a credential token. This typically
750 * succeeds when the device doesn't have credential-encrypted storage, or
751 * when the the credential-encrypted storage isn't tied to a user-provided
752 * PIN or pattern.
753 */
754 boolean maybeUnlockUser(final int userId) {
755 // Try unlocking storage using empty token
756 return unlockUserCleared(userId, null);
757 }
758
Jeff Sharkey8924e872015-11-30 12:52:10 -0700759 boolean unlockUserCleared(final int userId, byte[] token) {
760 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700761 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700762 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700763 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700764 }
765
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700766 if (!isUserKeyUnlocked(userId)) {
767 final UserInfo userInfo = getUserInfo(userId);
768 final IMountService mountService = getMountService();
769 try {
770 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
771 } catch (RemoteException | RuntimeException e) {
772 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
773 return false;
774 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800775 }
776
777 synchronized (mService) {
778 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700779 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800780 }
781
782 return true;
783 }
784
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800785 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700786 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800787 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
788 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700789 d.show();
790 }
791
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700792 void dispatchForegroundProfileChanged(int userId) {
793 final int observerCount = mUserSwitchObservers.beginBroadcast();
794 for (int i = 0; i < observerCount; i++) {
795 try {
796 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
797 } catch (RemoteException e) {
798 // Ignore
799 }
800 }
801 mUserSwitchObservers.finishBroadcast();
802 }
803
804 /** Called on handler thread */
805 void dispatchUserSwitchComplete(int userId) {
806 final int observerCount = mUserSwitchObservers.beginBroadcast();
807 for (int i = 0; i < observerCount; i++) {
808 try {
809 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
810 } catch (RemoteException e) {
811 }
812 }
813 mUserSwitchObservers.finishBroadcast();
814 }
815
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700816 private void stopBackgroundUsersIfEnforced(int oldUserId) {
817 // Never stop system user
818 if (oldUserId == UserHandle.USER_SYSTEM) {
819 return;
820 }
821 // For now, only check for user restriction. Additional checks can be added here
822 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
823 oldUserId);
824 if (!disallowRunInBg) {
825 return;
826 }
827 synchronized (mService) {
828 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
829 + " and related users");
830 stopUsersLocked(oldUserId, false, null);
831 }
832 }
833
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700834 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
835 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800836 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700837 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
838 }
839 }
840
841 void dispatchUserSwitch(final UserState uss, final int oldUserId,
842 final int newUserId) {
843 final int observerCount = mUserSwitchObservers.beginBroadcast();
844 if (observerCount > 0) {
845 final IRemoteCallback callback = new IRemoteCallback.Stub() {
846 int mCount = 0;
847 @Override
848 public void sendResult(Bundle data) throws RemoteException {
849 synchronized (mService) {
850 if (mCurUserSwitchCallback == this) {
851 mCount++;
852 if (mCount == observerCount) {
853 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
854 }
855 }
856 }
857 }
858 };
859 synchronized (mService) {
860 uss.switching = true;
861 mCurUserSwitchCallback = callback;
862 }
863 for (int i = 0; i < observerCount; i++) {
864 try {
865 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
866 newUserId, callback);
867 } catch (RemoteException e) {
868 }
869 }
870 } else {
871 synchronized (mService) {
872 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
873 }
874 }
875 mUserSwitchObservers.finishBroadcast();
876 }
877
878 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
879 mCurUserSwitchCallback = null;
880 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
881 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
882 oldUserId, newUserId, uss));
883 }
884
885 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700886 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700887 }
888
889 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
890 synchronized (mService) {
891 if (foreground) {
892 moveUserToForegroundLocked(uss, oldUserId, newUserId);
893 }
894 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700895 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700896 }
897
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700898 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700899 boolean clearInitializing, boolean clearSwitching) {
900 boolean unfrozen = false;
901 synchronized (mService) {
902 if (clearInitializing) {
903 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700904 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700905 }
906 if (clearSwitching) {
907 uss.switching = false;
908 }
909 if (!uss.switching && !uss.initializing) {
910 mService.mWindowManager.stopFreezingScreen();
911 unfrozen = true;
912 }
913 }
914 if (unfrozen) {
915 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
916 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
917 newUserId, 0));
918 }
919 stopGuestUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700920 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700921 }
922
923 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
924 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
925 if (homeInFront) {
926 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
927 } else {
928 mService.mStackSupervisor.resumeTopActivitiesLocked();
929 }
930 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700931 getUserManager().onUserForeground(newUserId);
932 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
933 }
934
935 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
936 long ident = Binder.clearCallingIdentity();
937 try {
938 Intent intent;
939 if (oldUserId >= 0) {
940 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
941 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
942 int count = profiles.size();
943 for (int i = 0; i < count; i++) {
944 int profileUserId = profiles.get(i).id;
945 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
946 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
947 | Intent.FLAG_RECEIVER_FOREGROUND);
948 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
949 mService.broadcastIntentLocked(null, null, intent,
950 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
951 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
952 }
953 }
954 if (newUserId >= 0) {
955 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
956 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
957 int count = profiles.size();
958 for (int i = 0; i < count; i++) {
959 int profileUserId = profiles.get(i).id;
960 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
961 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
962 | Intent.FLAG_RECEIVER_FOREGROUND);
963 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
964 mService.broadcastIntentLocked(null, null, intent,
965 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
966 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
967 }
968 intent = new Intent(Intent.ACTION_USER_SWITCHED);
969 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
970 | Intent.FLAG_RECEIVER_FOREGROUND);
971 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
972 mService.broadcastIntentLocked(null, null, intent,
973 null, null, 0, null, null,
974 new String[] {android.Manifest.permission.MANAGE_USERS},
975 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
976 UserHandle.USER_ALL);
977 }
978 } finally {
979 Binder.restoreCallingIdentity(ident);
980 }
981 }
982
983
984 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
985 int allowMode, String name, String callerPackage) {
986 final int callingUserId = UserHandle.getUserId(callingUid);
987 if (callingUserId == userId) {
988 return userId;
989 }
990
991 // Note that we may be accessing mCurrentUserId outside of a lock...
992 // shouldn't be a big deal, if this is being called outside
993 // of a locked context there is intrinsically a race with
994 // the value the caller will receive and someone else changing it.
995 // We assume that USER_CURRENT_OR_SELF will use the current user; later
996 // we will switch to the calling user if access to the current user fails.
997 int targetUserId = unsafeConvertIncomingUserLocked(userId);
998
999 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1000 final boolean allow;
1001 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1002 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1003 // If the caller has this permission, they always pass go. And collect $200.
1004 allow = true;
1005 } else if (allowMode == ALLOW_FULL_ONLY) {
1006 // We require full access, sucks to be you.
1007 allow = false;
1008 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1009 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1010 // If the caller does not have either permission, they are always doomed.
1011 allow = false;
1012 } else if (allowMode == ALLOW_NON_FULL) {
1013 // We are blanket allowing non-full access, you lucky caller!
1014 allow = true;
1015 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1016 // We may or may not allow this depending on whether the two users are
1017 // in the same profile.
1018 allow = isSameProfileGroup(callingUserId, targetUserId);
1019 } else {
1020 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1021 }
1022 if (!allow) {
1023 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1024 // In this case, they would like to just execute as their
1025 // owner user instead of failing.
1026 targetUserId = callingUserId;
1027 } else {
1028 StringBuilder builder = new StringBuilder(128);
1029 builder.append("Permission Denial: ");
1030 builder.append(name);
1031 if (callerPackage != null) {
1032 builder.append(" from ");
1033 builder.append(callerPackage);
1034 }
1035 builder.append(" asks to run as user ");
1036 builder.append(userId);
1037 builder.append(" but is calling from user ");
1038 builder.append(UserHandle.getUserId(callingUid));
1039 builder.append("; this requires ");
1040 builder.append(INTERACT_ACROSS_USERS_FULL);
1041 if (allowMode != ALLOW_FULL_ONLY) {
1042 builder.append(" or ");
1043 builder.append(INTERACT_ACROSS_USERS);
1044 }
1045 String msg = builder.toString();
1046 Slog.w(TAG, msg);
1047 throw new SecurityException(msg);
1048 }
1049 }
1050 }
1051 if (!allowAll && targetUserId < 0) {
1052 throw new IllegalArgumentException(
1053 "Call does not support special user #" + targetUserId);
1054 }
1055 // Check shell permission
1056 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1057 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1058 throw new SecurityException("Shell does not have permission to access user "
1059 + targetUserId + "\n " + Debug.getCallers(3));
1060 }
1061 }
1062 return targetUserId;
1063 }
1064
1065 int unsafeConvertIncomingUserLocked(int userId) {
1066 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1067 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001068 }
1069
1070 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1071 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1072 != PackageManager.PERMISSION_GRANTED) {
1073 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1074 + Binder.getCallingPid()
1075 + ", uid=" + Binder.getCallingUid()
1076 + " requires " + INTERACT_ACROSS_USERS_FULL;
1077 Slog.w(TAG, msg);
1078 throw new SecurityException(msg);
1079 }
1080
1081 mUserSwitchObservers.register(observer);
1082 }
1083
1084 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1085 mUserSwitchObservers.unregister(observer);
1086 }
1087
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001088 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001089 return mStartedUsers.get(userId);
1090 }
1091
1092 boolean hasStartedUserState(int userId) {
1093 return mStartedUsers.get(userId) != null;
1094 }
1095
1096 private void updateStartedUserArrayLocked() {
1097 int num = 0;
1098 for (int i = 0; i < mStartedUsers.size(); i++) {
1099 UserState uss = mStartedUsers.valueAt(i);
1100 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001101 if (uss.state != UserState.STATE_STOPPING
1102 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001103 num++;
1104 }
1105 }
1106 mStartedUserArray = new int[num];
1107 num = 0;
1108 for (int i = 0; i < mStartedUsers.size(); i++) {
1109 UserState uss = mStartedUsers.valueAt(i);
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 mStartedUserArray[num] = mStartedUsers.keyAt(i);
1113 num++;
1114 }
1115 }
1116 }
1117
1118 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1119 for (int i = 0; i < mStartedUsers.size(); i++) {
1120 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001121 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001122 }
1123 }
1124
1125 /**
1126 * Refreshes the list of users related to the current user when either a
1127 * user switch happens or when a new related user is started in the
1128 * background.
1129 */
1130 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001131 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001132 false /* enabledOnly */);
1133 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1134 for (int i = 0; i < currentProfileIds.length; i++) {
1135 currentProfileIds[i] = profiles.get(i).id;
1136 }
1137 mCurrentProfileIds = currentProfileIds;
1138
1139 synchronized (mUserProfileGroupIdsSelfLocked) {
1140 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001141 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001142 for (int i = 0; i < users.size(); i++) {
1143 UserInfo user = users.get(i);
1144 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1145 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1146 }
1147 }
1148 }
1149 }
1150
1151 int[] getStartedUserArrayLocked() {
1152 return mStartedUserArray;
1153 }
1154
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001155 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001156 UserState state = getStartedUserStateLocked(userId);
1157 if (state == null) {
1158 return false;
1159 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001160 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001161 return true;
1162 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001163
1164 final boolean unlocked;
1165 switch (state.state) {
1166 case UserState.STATE_STOPPING:
1167 case UserState.STATE_SHUTDOWN:
1168 default:
1169 return false;
1170
1171 case UserState.STATE_BOOTING:
1172 case UserState.STATE_RUNNING_LOCKED:
1173 unlocked = false;
1174 break;
1175
1176 case UserState.STATE_RUNNING:
1177 unlocked = true;
1178 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001179 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001180
1181 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1182 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001183 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001184 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1185 return unlocked;
1186 }
1187
1188 // One way or another, we're running!
1189 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001190 }
1191
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001192 UserInfo getCurrentUser() {
1193 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1194 != PackageManager.PERMISSION_GRANTED) && (
1195 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1196 != PackageManager.PERMISSION_GRANTED)) {
1197 String msg = "Permission Denial: getCurrentUser() from pid="
1198 + Binder.getCallingPid()
1199 + ", uid=" + Binder.getCallingUid()
1200 + " requires " + INTERACT_ACROSS_USERS;
1201 Slog.w(TAG, msg);
1202 throw new SecurityException(msg);
1203 }
1204 synchronized (mService) {
1205 return getCurrentUserLocked();
1206 }
1207 }
1208
1209 UserInfo getCurrentUserLocked() {
1210 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001211 return getUserInfo(userId);
1212 }
1213
1214 int getCurrentOrTargetUserIdLocked() {
1215 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001216 }
1217
1218 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001219 return mCurrentUserId;
1220 }
1221
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001222 private boolean isCurrentUserLocked(int userId) {
1223 return mCurrentUserId == userId || mTargetUserId == userId;
1224 }
1225
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001226 int setTargetUserIdLocked(int targetUserId) {
1227 return mTargetUserId = targetUserId;
1228 }
1229
1230 int[] getUsers() {
1231 UserManagerService ums = getUserManager();
1232 return ums != null ? ums.getUserIds() : new int[] { 0 };
1233 }
1234
1235 UserInfo getUserInfo(int userId) {
1236 return getUserManager().getUserInfo(userId);
1237 }
1238
1239 int[] getUserIds() {
1240 return getUserManager().getUserIds();
1241 }
1242
1243 boolean exists(int userId) {
1244 return getUserManager().exists(userId);
1245 }
1246
1247 boolean hasUserRestriction(String restriction, int userId) {
1248 return getUserManager().hasUserRestriction(restriction, userId);
1249 }
1250
1251 Set<Integer> getProfileIds(int userId) {
1252 Set<Integer> userIds = new HashSet<>();
1253 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1254 false /* enabledOnly */);
1255 for (UserInfo user : profiles) {
1256 userIds.add(user.id);
1257 }
1258 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001259 }
1260
1261 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1262 synchronized (mUserProfileGroupIdsSelfLocked) {
1263 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1264 UserInfo.NO_PROFILE_GROUP_ID);
1265 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1266 UserInfo.NO_PROFILE_GROUP_ID);
1267 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1268 && callingProfile == targetProfile;
1269 }
1270 }
1271
1272 boolean isCurrentProfileLocked(int userId) {
1273 return ArrayUtils.contains(mCurrentProfileIds, userId);
1274 }
1275
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001276 int[] getCurrentProfileIdsLocked() {
1277 return mCurrentProfileIds;
1278 }
1279
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001280 void dump(PrintWriter pw, boolean dumpAll) {
1281 pw.println(" mStartedUsers:");
1282 for (int i = 0; i < mStartedUsers.size(); i++) {
1283 UserState uss = mStartedUsers.valueAt(i);
1284 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1285 pw.print(": "); uss.dump("", pw);
1286 }
1287 pw.print(" mStartedUserArray: [");
1288 for (int i = 0; i < mStartedUserArray.length; i++) {
1289 if (i > 0) pw.print(", ");
1290 pw.print(mStartedUserArray[i]);
1291 }
1292 pw.println("]");
1293 pw.print(" mUserLru: [");
1294 for (int i = 0; i < mUserLru.size(); i++) {
1295 if (i > 0) pw.print(", ");
1296 pw.print(mUserLru.get(i));
1297 }
1298 pw.println("]");
1299 if (dumpAll) {
1300 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1301 }
1302 synchronized (mUserProfileGroupIdsSelfLocked) {
1303 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1304 pw.println(" mUserProfileGroupIds:");
1305 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1306 pw.print(" User #");
1307 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1308 pw.print(" -> profile #");
1309 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1310 }
1311 }
1312 }
1313 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001314}