blob: 20b1e6058224cb2ede34dcf2a1277e52e4e96bd3 [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) {
307 stopSingleUserLocked(userId, callback);
308 }
309 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
310 }
311 }
312 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
313 for (int userIdToStop : usersToStop) {
314 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
315 }
316 return USER_OP_SUCCESS;
317 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700318
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700319 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
320 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700321 final UserState uss = mStartedUsers.get(userId);
322 if (uss == null) {
323 // User is not started, nothing to do... but we do need to
324 // callback if requested.
325 if (callback != null) {
326 mHandler.post(new Runnable() {
327 @Override
328 public void run() {
329 try {
330 callback.userStopped(userId);
331 } catch (RemoteException e) {
332 }
333 }
334 });
335 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700336 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700337 }
338
339 if (callback != null) {
340 uss.mStopCallbacks.add(callback);
341 }
342
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700343 if (uss.state != UserState.STATE_STOPPING
344 && uss.state != UserState.STATE_SHUTDOWN) {
345 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700346 updateStartedUserArrayLocked();
347
348 long ident = Binder.clearCallingIdentity();
349 try {
350 // We are going to broadcast ACTION_USER_STOPPING and then
351 // once that is done send a final ACTION_SHUTDOWN and then
352 // stop the user.
353 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
354 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
355 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
356 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
357 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
358 // This is the result receiver for the final shutdown broadcast.
359 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
360 @Override
361 public void performReceive(Intent intent, int resultCode, String data,
362 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
363 finishUserStop(uss);
364 }
365 };
366 // This is the result receiver for the initial stopping broadcast.
367 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
368 @Override
369 public void performReceive(Intent intent, int resultCode, String data,
370 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
371 // On to the next.
372 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700373 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700374 // Whoops, we are being started back up. Abort, abort!
375 return;
376 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700377 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700378 }
379 mService.mBatteryStatsService.noteEvent(
380 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
381 Integer.toString(userId), userId);
382 mService.mSystemServiceManager.stopUser(userId);
383 mService.broadcastIntentLocked(null, null, shutdownIntent,
384 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700385 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700386 }
387 };
388 // Kick things off.
389 mService.broadcastIntentLocked(null, null, stoppingIntent,
390 null, stoppingReceiver, 0, null, null,
391 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700392 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700393 } finally {
394 Binder.restoreCallingIdentity(ident);
395 }
396 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700397 }
398
399 void finishUserStop(UserState uss) {
400 final int userId = uss.mHandle.getIdentifier();
401 boolean stopped;
402 ArrayList<IStopUserCallback> callbacks;
403 synchronized (mService) {
404 callbacks = new ArrayList<>(uss.mStopCallbacks);
405 if (mStartedUsers.get(userId) != uss) {
406 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700407 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700408 stopped = false;
409 } else {
410 stopped = true;
411 // User can no longer run.
412 mStartedUsers.remove(userId);
413 mUserLru.remove(Integer.valueOf(userId));
414 updateStartedUserArrayLocked();
415
416 // Clean up all state and processes associated with the user.
417 // Kill all the processes for the user.
418 forceStopUserLocked(userId, "finish user");
419 }
420 }
421
422 for (int i = 0; i < callbacks.size(); i++) {
423 try {
424 if (stopped) callbacks.get(i).userStopped(userId);
425 else callbacks.get(i).userStopAborted(userId);
426 } catch (RemoteException e) {
427 }
428 }
429
430 if (stopped) {
431 mService.mSystemServiceManager.cleanupUser(userId);
432 synchronized (mService) {
433 mService.mStackSupervisor.removeUserLocked(userId);
434 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100435 // Remove the user if it is ephemeral.
436 if (getUserInfo(userId).isEphemeral()) {
437 mUserManager.removeUser(userId);
438 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700439 }
440 }
441
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700442 /**
443 * Determines the list of users that should be stopped together with the specified
444 * {@code userId}. The returned list includes {@code userId}.
445 */
446 private @NonNull int[] getUsersToStopLocked(int userId) {
447 int startedUsersSize = mStartedUsers.size();
448 IntArray userIds = new IntArray();
449 userIds.add(userId);
450 synchronized (mUserProfileGroupIdsSelfLocked) {
451 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
452 UserInfo.NO_PROFILE_GROUP_ID);
453 for (int i = 0; i < startedUsersSize; i++) {
454 UserState uss = mStartedUsers.valueAt(i);
455 int startedUserId = uss.mHandle.getIdentifier();
456 // Skip unrelated users (profileGroupId mismatch)
457 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
458 UserInfo.NO_PROFILE_GROUP_ID);
459 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
460 && (userGroupId == startedUserGroupId);
461 // userId has already been added
462 boolean sameUserId = startedUserId == userId;
463 if (!sameGroup || sameUserId) {
464 continue;
465 }
466 userIds.add(startedUserId);
467 }
468 }
469 return userIds.toArray();
470 }
471
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700472 private void forceStopUserLocked(int userId, String reason) {
473 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
474 userId, reason);
475 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
476 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
477 | Intent.FLAG_RECEIVER_FOREGROUND);
478 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
479 mService.broadcastIntentLocked(null, null, intent,
480 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700481 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700482 }
483
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700484 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100485 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700486 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100487 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700488 synchronized (mService) {
489 final int num = mUserLru.size();
490 for (int i = 0; i < num; i++) {
491 Integer oldUserId = mUserLru.get(i);
492 UserState oldUss = mStartedUsers.get(oldUserId);
493 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700494 || oldUss.state == UserState.STATE_STOPPING
495 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700496 continue;
497 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700498 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100499 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700500 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700501 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700502 break;
503 }
504 }
505 }
506 }
507
508 void startProfilesLocked() {
509 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700510 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700511 mCurrentUserId, false /* enabledOnly */);
512 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
513 for (UserInfo user : profiles) {
514 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
515 && user.id != mCurrentUserId) {
516 profilesToStart.add(user);
517 }
518 }
519 final int profilesToStartSize = profilesToStart.size();
520 int i = 0;
521 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
522 startUser(profilesToStart.get(i).id, /* foreground= */ false);
523 }
524 if (i < profilesToStartSize) {
525 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
526 }
527 }
528
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700529 private UserManagerService getUserManager() {
530 UserManagerService userManager = mUserManager;
531 if (userManager == null) {
532 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
533 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
534 }
535 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700536 }
537
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700538 private IMountService getMountService() {
539 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
540 }
541
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700542 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700543 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800544 if (mountService != null) {
545 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700546 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800547 } catch (RemoteException e) {
548 throw e.rethrowAsRuntimeException();
549 }
550 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700551 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
552 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800553 }
554 }
555
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700556 boolean startUser(final int userId, final boolean foreground) {
557 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
558 != PackageManager.PERMISSION_GRANTED) {
559 String msg = "Permission Denial: switchUser() from pid="
560 + Binder.getCallingPid()
561 + ", uid=" + Binder.getCallingUid()
562 + " requires " + INTERACT_ACROSS_USERS_FULL;
563 Slog.w(TAG, msg);
564 throw new SecurityException(msg);
565 }
566
567 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
568
569 final long ident = Binder.clearCallingIdentity();
570 try {
571 synchronized (mService) {
572 final int oldUserId = mCurrentUserId;
573 if (oldUserId == userId) {
574 return true;
575 }
576
577 mService.mStackSupervisor.setLockTaskModeLocked(null,
578 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
579
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700580 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700581 if (userInfo == null) {
582 Slog.w(TAG, "No user info for user #" + userId);
583 return false;
584 }
585 if (foreground && userInfo.isManagedProfile()) {
586 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
587 return false;
588 }
589
590 if (foreground) {
591 mService.mWindowManager.startFreezingScreen(
592 R.anim.screen_user_exit, R.anim.screen_user_enter);
593 }
594
595 boolean needStart = false;
596
597 // If the user we are switching to is not currently started, then
598 // we need to start it now.
599 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700600 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700601 updateStartedUserArrayLocked();
602 needStart = true;
603 }
604
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800605 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700606 final Integer userIdInt = userId;
607 mUserLru.remove(userIdInt);
608 mUserLru.add(userIdInt);
609
610 if (foreground) {
611 mCurrentUserId = userId;
612 mService.updateUserConfigurationLocked();
613 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
614 updateCurrentProfileIdsLocked();
615 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
616 // Once the internal notion of the active user has switched, we lock the device
617 // with the option to show the user switcher on the keyguard.
618 mService.mWindowManager.lockNow(null);
619 } else {
620 final Integer currentUserIdInt = mCurrentUserId;
621 updateCurrentProfileIdsLocked();
622 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
623 mUserLru.remove(currentUserIdInt);
624 mUserLru.add(currentUserIdInt);
625 }
626
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700627 // Make sure user is in the started state. If it is currently
628 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700629 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700630 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
631 // so we can just fairly silently bring the user back from
632 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700633 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700634 updateStartedUserArrayLocked();
635 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700636 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700637 // This means ACTION_SHUTDOWN has been sent, so we will
638 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700639 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700640 updateStartedUserArrayLocked();
641 needStart = true;
642 }
643
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700644 if (uss.state == UserState.STATE_BOOTING) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800645 // Let user manager propagate user restrictions to other services.
646 getUserManager().onBeforeStartUser(userId);
647
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700648 // Booting up a new user, need to tell system services about it.
649 // Note that this is on the same handler as scheduling of broadcasts,
650 // which is important because it needs to go first.
651 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
652 }
653
654 if (foreground) {
655 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
656 oldUserId));
657 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
658 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
659 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
660 oldUserId, userId, uss));
661 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
662 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
663 }
664
665 if (needStart) {
666 // Send USER_STARTED broadcast
667 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
668 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
669 | Intent.FLAG_RECEIVER_FOREGROUND);
670 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
671 mService.broadcastIntentLocked(null, null, intent,
672 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700673 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700674 }
675
676 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
677 if (userId != UserHandle.USER_SYSTEM) {
678 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
679 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
680 mService.broadcastIntentLocked(null, null, intent, null,
681 new IIntentReceiver.Stub() {
682 public void performReceive(Intent intent, int resultCode,
683 String data, Bundle extras, boolean ordered,
684 boolean sticky, int sendingUser) {
685 onUserInitialized(uss, foreground, oldUserId, userId);
686 }
687 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700688 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700689 uss.initializing = true;
690 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700691 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700692 }
693 }
694
695 if (foreground) {
696 if (!uss.initializing) {
697 moveUserToForegroundLocked(uss, oldUserId, userId);
698 }
699 } else {
700 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
701 }
702
703 if (needStart) {
704 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
705 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
706 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
707 mService.broadcastIntentLocked(null, null, intent,
708 null, new IIntentReceiver.Stub() {
709 @Override
710 public void performReceive(Intent intent, int resultCode,
711 String data, Bundle extras, boolean ordered, boolean sticky,
712 int sendingUser) throws RemoteException {
713 }
714 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700715 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
716 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700717 }
718 }
719 } finally {
720 Binder.restoreCallingIdentity(ident);
721 }
722
723 return true;
724 }
725
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700726 /**
727 * Start user, if its not already running, and bring it to foreground.
728 */
729 boolean startUserInForeground(final int userId, Dialog dlg) {
730 boolean result = startUser(userId, /* foreground */ true);
731 dlg.dismiss();
732 return result;
733 }
734
Jeff Sharkeyba512352015-11-12 20:17:45 -0800735 boolean unlockUser(final int userId, byte[] token) {
736 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
737 != PackageManager.PERMISSION_GRANTED) {
738 String msg = "Permission Denial: unlockUser() from pid="
739 + Binder.getCallingPid()
740 + ", uid=" + Binder.getCallingUid()
741 + " requires " + INTERACT_ACROSS_USERS_FULL;
742 Slog.w(TAG, msg);
743 throw new SecurityException(msg);
744 }
745
Jeff Sharkey8924e872015-11-30 12:52:10 -0700746 final long binderToken = Binder.clearCallingIdentity();
747 try {
748 return unlockUserCleared(userId, token);
749 } finally {
750 Binder.restoreCallingIdentity(binderToken);
751 }
752 }
753
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700754 /**
755 * Attempt to unlock user without a credential token. This typically
756 * succeeds when the device doesn't have credential-encrypted storage, or
757 * when the the credential-encrypted storage isn't tied to a user-provided
758 * PIN or pattern.
759 */
760 boolean maybeUnlockUser(final int userId) {
761 // Try unlocking storage using empty token
762 return unlockUserCleared(userId, null);
763 }
764
Jeff Sharkey8924e872015-11-30 12:52:10 -0700765 boolean unlockUserCleared(final int userId, byte[] token) {
766 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700767 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700768 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700769 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700770 }
771
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700772 if (!isUserKeyUnlocked(userId)) {
773 final UserInfo userInfo = getUserInfo(userId);
774 final IMountService mountService = getMountService();
775 try {
776 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
777 } catch (RemoteException | RuntimeException e) {
778 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
779 return false;
780 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800781 }
782
783 synchronized (mService) {
784 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700785 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800786 }
787
788 return true;
789 }
790
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800791 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700792 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800793 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
794 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700795 d.show();
796 }
797
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700798 void dispatchForegroundProfileChanged(int userId) {
799 final int observerCount = mUserSwitchObservers.beginBroadcast();
800 for (int i = 0; i < observerCount; i++) {
801 try {
802 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
803 } catch (RemoteException e) {
804 // Ignore
805 }
806 }
807 mUserSwitchObservers.finishBroadcast();
808 }
809
810 /** Called on handler thread */
811 void dispatchUserSwitchComplete(int userId) {
812 final int observerCount = mUserSwitchObservers.beginBroadcast();
813 for (int i = 0; i < observerCount; i++) {
814 try {
815 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
816 } catch (RemoteException e) {
817 }
818 }
819 mUserSwitchObservers.finishBroadcast();
820 }
821
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700822 private void stopBackgroundUsersIfEnforced(int oldUserId) {
823 // Never stop system user
824 if (oldUserId == UserHandle.USER_SYSTEM) {
825 return;
826 }
827 // For now, only check for user restriction. Additional checks can be added here
828 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
829 oldUserId);
830 if (!disallowRunInBg) {
831 return;
832 }
833 synchronized (mService) {
834 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
835 + " and related users");
836 stopUsersLocked(oldUserId, false, null);
837 }
838 }
839
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700840 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
841 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800842 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700843 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
844 }
845 }
846
847 void dispatchUserSwitch(final UserState uss, final int oldUserId,
848 final int newUserId) {
849 final int observerCount = mUserSwitchObservers.beginBroadcast();
850 if (observerCount > 0) {
851 final IRemoteCallback callback = new IRemoteCallback.Stub() {
852 int mCount = 0;
853 @Override
854 public void sendResult(Bundle data) throws RemoteException {
855 synchronized (mService) {
856 if (mCurUserSwitchCallback == this) {
857 mCount++;
858 if (mCount == observerCount) {
859 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
860 }
861 }
862 }
863 }
864 };
865 synchronized (mService) {
866 uss.switching = true;
867 mCurUserSwitchCallback = callback;
868 }
869 for (int i = 0; i < observerCount; i++) {
870 try {
871 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
872 newUserId, callback);
873 } catch (RemoteException e) {
874 }
875 }
876 } else {
877 synchronized (mService) {
878 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
879 }
880 }
881 mUserSwitchObservers.finishBroadcast();
882 }
883
884 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
885 mCurUserSwitchCallback = null;
886 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
887 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
888 oldUserId, newUserId, uss));
889 }
890
891 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700892 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700893 }
894
895 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
896 synchronized (mService) {
897 if (foreground) {
898 moveUserToForegroundLocked(uss, oldUserId, newUserId);
899 }
900 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700901 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700902 }
903
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700904 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700905 boolean clearInitializing, boolean clearSwitching) {
906 boolean unfrozen = false;
907 synchronized (mService) {
908 if (clearInitializing) {
909 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700910 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700911 }
912 if (clearSwitching) {
913 uss.switching = false;
914 }
915 if (!uss.switching && !uss.initializing) {
916 mService.mWindowManager.stopFreezingScreen();
917 unfrozen = true;
918 }
919 }
920 if (unfrozen) {
921 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
922 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
923 newUserId, 0));
924 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100925 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700926 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700927 }
928
929 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
930 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
931 if (homeInFront) {
932 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
933 } else {
934 mService.mStackSupervisor.resumeTopActivitiesLocked();
935 }
936 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700937 getUserManager().onUserForeground(newUserId);
938 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
939 }
940
941 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
942 long ident = Binder.clearCallingIdentity();
943 try {
944 Intent intent;
945 if (oldUserId >= 0) {
946 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
947 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
948 int count = profiles.size();
949 for (int i = 0; i < count; i++) {
950 int profileUserId = profiles.get(i).id;
951 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
952 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
953 | Intent.FLAG_RECEIVER_FOREGROUND);
954 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
955 mService.broadcastIntentLocked(null, null, intent,
956 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
957 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
958 }
959 }
960 if (newUserId >= 0) {
961 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
962 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
963 int count = profiles.size();
964 for (int i = 0; i < count; i++) {
965 int profileUserId = profiles.get(i).id;
966 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
967 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
968 | Intent.FLAG_RECEIVER_FOREGROUND);
969 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
970 mService.broadcastIntentLocked(null, null, intent,
971 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
972 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
973 }
974 intent = new Intent(Intent.ACTION_USER_SWITCHED);
975 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
976 | Intent.FLAG_RECEIVER_FOREGROUND);
977 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
978 mService.broadcastIntentLocked(null, null, intent,
979 null, null, 0, null, null,
980 new String[] {android.Manifest.permission.MANAGE_USERS},
981 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
982 UserHandle.USER_ALL);
983 }
984 } finally {
985 Binder.restoreCallingIdentity(ident);
986 }
987 }
988
989
990 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
991 int allowMode, String name, String callerPackage) {
992 final int callingUserId = UserHandle.getUserId(callingUid);
993 if (callingUserId == userId) {
994 return userId;
995 }
996
997 // Note that we may be accessing mCurrentUserId outside of a lock...
998 // shouldn't be a big deal, if this is being called outside
999 // of a locked context there is intrinsically a race with
1000 // the value the caller will receive and someone else changing it.
1001 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1002 // we will switch to the calling user if access to the current user fails.
1003 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1004
1005 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1006 final boolean allow;
1007 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1008 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1009 // If the caller has this permission, they always pass go. And collect $200.
1010 allow = true;
1011 } else if (allowMode == ALLOW_FULL_ONLY) {
1012 // We require full access, sucks to be you.
1013 allow = false;
1014 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1015 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1016 // If the caller does not have either permission, they are always doomed.
1017 allow = false;
1018 } else if (allowMode == ALLOW_NON_FULL) {
1019 // We are blanket allowing non-full access, you lucky caller!
1020 allow = true;
1021 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1022 // We may or may not allow this depending on whether the two users are
1023 // in the same profile.
1024 allow = isSameProfileGroup(callingUserId, targetUserId);
1025 } else {
1026 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1027 }
1028 if (!allow) {
1029 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1030 // In this case, they would like to just execute as their
1031 // owner user instead of failing.
1032 targetUserId = callingUserId;
1033 } else {
1034 StringBuilder builder = new StringBuilder(128);
1035 builder.append("Permission Denial: ");
1036 builder.append(name);
1037 if (callerPackage != null) {
1038 builder.append(" from ");
1039 builder.append(callerPackage);
1040 }
1041 builder.append(" asks to run as user ");
1042 builder.append(userId);
1043 builder.append(" but is calling from user ");
1044 builder.append(UserHandle.getUserId(callingUid));
1045 builder.append("; this requires ");
1046 builder.append(INTERACT_ACROSS_USERS_FULL);
1047 if (allowMode != ALLOW_FULL_ONLY) {
1048 builder.append(" or ");
1049 builder.append(INTERACT_ACROSS_USERS);
1050 }
1051 String msg = builder.toString();
1052 Slog.w(TAG, msg);
1053 throw new SecurityException(msg);
1054 }
1055 }
1056 }
1057 if (!allowAll && targetUserId < 0) {
1058 throw new IllegalArgumentException(
1059 "Call does not support special user #" + targetUserId);
1060 }
1061 // Check shell permission
1062 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1063 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1064 throw new SecurityException("Shell does not have permission to access user "
1065 + targetUserId + "\n " + Debug.getCallers(3));
1066 }
1067 }
1068 return targetUserId;
1069 }
1070
1071 int unsafeConvertIncomingUserLocked(int userId) {
1072 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1073 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001074 }
1075
1076 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1077 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1078 != PackageManager.PERMISSION_GRANTED) {
1079 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1080 + Binder.getCallingPid()
1081 + ", uid=" + Binder.getCallingUid()
1082 + " requires " + INTERACT_ACROSS_USERS_FULL;
1083 Slog.w(TAG, msg);
1084 throw new SecurityException(msg);
1085 }
1086
1087 mUserSwitchObservers.register(observer);
1088 }
1089
1090 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1091 mUserSwitchObservers.unregister(observer);
1092 }
1093
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001094 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001095 return mStartedUsers.get(userId);
1096 }
1097
1098 boolean hasStartedUserState(int userId) {
1099 return mStartedUsers.get(userId) != null;
1100 }
1101
1102 private void updateStartedUserArrayLocked() {
1103 int num = 0;
1104 for (int i = 0; i < mStartedUsers.size(); i++) {
1105 UserState uss = mStartedUsers.valueAt(i);
1106 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001107 if (uss.state != UserState.STATE_STOPPING
1108 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001109 num++;
1110 }
1111 }
1112 mStartedUserArray = new int[num];
1113 num = 0;
1114 for (int i = 0; i < mStartedUsers.size(); i++) {
1115 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001116 if (uss.state != UserState.STATE_STOPPING
1117 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001118 mStartedUserArray[num] = mStartedUsers.keyAt(i);
1119 num++;
1120 }
1121 }
1122 }
1123
1124 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1125 for (int i = 0; i < mStartedUsers.size(); i++) {
1126 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001127 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001128 }
1129 }
1130
1131 /**
1132 * Refreshes the list of users related to the current user when either a
1133 * user switch happens or when a new related user is started in the
1134 * background.
1135 */
1136 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001137 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001138 false /* enabledOnly */);
1139 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1140 for (int i = 0; i < currentProfileIds.length; i++) {
1141 currentProfileIds[i] = profiles.get(i).id;
1142 }
1143 mCurrentProfileIds = currentProfileIds;
1144
1145 synchronized (mUserProfileGroupIdsSelfLocked) {
1146 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001147 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001148 for (int i = 0; i < users.size(); i++) {
1149 UserInfo user = users.get(i);
1150 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1151 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1152 }
1153 }
1154 }
1155 }
1156
1157 int[] getStartedUserArrayLocked() {
1158 return mStartedUserArray;
1159 }
1160
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001161 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001162 UserState state = getStartedUserStateLocked(userId);
1163 if (state == null) {
1164 return false;
1165 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001166 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001167 return true;
1168 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001169
1170 final boolean unlocked;
1171 switch (state.state) {
1172 case UserState.STATE_STOPPING:
1173 case UserState.STATE_SHUTDOWN:
1174 default:
1175 return false;
1176
1177 case UserState.STATE_BOOTING:
1178 case UserState.STATE_RUNNING_LOCKED:
1179 unlocked = false;
1180 break;
1181
1182 case UserState.STATE_RUNNING:
1183 unlocked = true;
1184 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001185 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001186
1187 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1188 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001189 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001190 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1191 return unlocked;
1192 }
1193
1194 // One way or another, we're running!
1195 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001196 }
1197
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001198 UserInfo getCurrentUser() {
1199 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1200 != PackageManager.PERMISSION_GRANTED) && (
1201 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1202 != PackageManager.PERMISSION_GRANTED)) {
1203 String msg = "Permission Denial: getCurrentUser() from pid="
1204 + Binder.getCallingPid()
1205 + ", uid=" + Binder.getCallingUid()
1206 + " requires " + INTERACT_ACROSS_USERS;
1207 Slog.w(TAG, msg);
1208 throw new SecurityException(msg);
1209 }
1210 synchronized (mService) {
1211 return getCurrentUserLocked();
1212 }
1213 }
1214
1215 UserInfo getCurrentUserLocked() {
1216 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001217 return getUserInfo(userId);
1218 }
1219
1220 int getCurrentOrTargetUserIdLocked() {
1221 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001222 }
1223
1224 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001225 return mCurrentUserId;
1226 }
1227
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001228 private boolean isCurrentUserLocked(int userId) {
Amith Yamasani458ac462015-12-18 11:21:31 -08001229 return userId == getCurrentOrTargetUserIdLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001230 }
1231
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001232 int setTargetUserIdLocked(int targetUserId) {
1233 return mTargetUserId = targetUserId;
1234 }
1235
1236 int[] getUsers() {
1237 UserManagerService ums = getUserManager();
1238 return ums != null ? ums.getUserIds() : new int[] { 0 };
1239 }
1240
1241 UserInfo getUserInfo(int userId) {
1242 return getUserManager().getUserInfo(userId);
1243 }
1244
1245 int[] getUserIds() {
1246 return getUserManager().getUserIds();
1247 }
1248
1249 boolean exists(int userId) {
1250 return getUserManager().exists(userId);
1251 }
1252
1253 boolean hasUserRestriction(String restriction, int userId) {
1254 return getUserManager().hasUserRestriction(restriction, userId);
1255 }
1256
1257 Set<Integer> getProfileIds(int userId) {
1258 Set<Integer> userIds = new HashSet<>();
1259 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1260 false /* enabledOnly */);
1261 for (UserInfo user : profiles) {
1262 userIds.add(user.id);
1263 }
1264 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001265 }
1266
1267 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1268 synchronized (mUserProfileGroupIdsSelfLocked) {
1269 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1270 UserInfo.NO_PROFILE_GROUP_ID);
1271 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1272 UserInfo.NO_PROFILE_GROUP_ID);
1273 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1274 && callingProfile == targetProfile;
1275 }
1276 }
1277
1278 boolean isCurrentProfileLocked(int userId) {
1279 return ArrayUtils.contains(mCurrentProfileIds, userId);
1280 }
1281
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001282 int[] getCurrentProfileIdsLocked() {
1283 return mCurrentProfileIds;
1284 }
1285
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001286 void dump(PrintWriter pw, boolean dumpAll) {
1287 pw.println(" mStartedUsers:");
1288 for (int i = 0; i < mStartedUsers.size(); i++) {
1289 UserState uss = mStartedUsers.valueAt(i);
1290 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1291 pw.print(": "); uss.dump("", pw);
1292 }
1293 pw.print(" mStartedUserArray: [");
1294 for (int i = 0; i < mStartedUserArray.length; i++) {
1295 if (i > 0) pw.print(", ");
1296 pw.print(mStartedUserArray[i]);
1297 }
1298 pw.println("]");
1299 pw.print(" mUserLru: [");
1300 for (int i = 0; i < mUserLru.size(); i++) {
1301 if (i > 0) pw.print(", ");
1302 pw.print(mUserLru.get(i));
1303 }
1304 pw.println("]");
1305 if (dumpAll) {
1306 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1307 }
1308 synchronized (mUserProfileGroupIdsSelfLocked) {
1309 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1310 pw.println(" mUserProfileGroupIds:");
1311 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1312 pw.print(" User #");
1313 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1314 pw.print(" -> profile #");
1315 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1316 }
1317 }
1318 }
1319 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001320}