blob: ed71864591093127d043dbf517c804d434545c90 [file] [log] [blame]
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.am;
18
19import static android.Manifest.permission.INTERACT_ACROSS_USERS;
20import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070021import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
22import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070023import static android.app.ActivityManager.USER_OP_IS_CURRENT;
24import static android.app.ActivityManager.USER_OP_SUCCESS;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000025import static android.content.Context.KEYGUARD_SERVICE;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070026import static android.os.Process.SYSTEM_UID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070027import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
28import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
29import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070030import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
31import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
32import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
33import static com.android.server.am.ActivityManagerService.MY_PID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070034import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
35import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
36import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
37import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -070038import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070039import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
40
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070041import android.annotation.NonNull;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070042import android.app.ActivityManager;
43import android.app.AppOpsManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070044import android.app.Dialog;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070045import android.app.IStopUserCallback;
46import android.app.IUserSwitchObserver;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000047import android.app.KeyguardManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070048import android.content.Context;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070049import android.content.IIntentReceiver;
50import android.content.Intent;
51import android.content.pm.PackageManager;
52import android.content.pm.UserInfo;
53import android.os.BatteryStats;
54import android.os.Binder;
55import android.os.Bundle;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070056import android.os.Debug;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070057import android.os.Handler;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070058import android.os.IBinder;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070059import android.os.IRemoteCallback;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070060import android.os.IUserManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070061import android.os.Process;
62import android.os.RemoteCallbackList;
63import android.os.RemoteException;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070064import android.os.ServiceManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070065import android.os.UserHandle;
66import android.os.UserManager;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080067import android.os.storage.IMountService;
68import android.os.storage.StorageManager;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070069import android.util.IntArray;
Suprabh Shukla4fe508b2015-11-20 18:22:57 -080070import android.util.Pair;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070071import android.util.Slog;
72import android.util.SparseArray;
73import android.util.SparseIntArray;
74
75import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080076import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070077import com.android.internal.util.ArrayUtils;
Clara Bayarriea9b10e2015-12-04 15:36:26 +000078import com.android.internal.widget.LockPatternUtils;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070079import com.android.server.pm.UserManagerService;
80
81import java.io.PrintWriter;
82import java.util.ArrayList;
83import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070084import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070085import java.util.List;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070086import java.util.Set;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070087
88/**
89 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
90 */
91final class UserController {
92 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
93 // Maximum number of users we allow to be running at a time.
94 static final int MAX_RUNNING_USERS = 3;
95
96 // Amount of time we wait for observers to handle a user switch before
97 // giving up on them and unfreezing the screen.
98 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
99
100 private final ActivityManagerService mService;
101 private final Handler mHandler;
102
103 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700104 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700105 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700106 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700107
108 /**
109 * Which users have been started, so are allowed to run code.
110 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800111 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700112 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800113
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700114 /**
115 * LRU list of history of current users. Most recently current is at the end.
116 */
117 private final ArrayList<Integer> mUserLru = new ArrayList<>();
118
119 /**
120 * Constant array of the users that are currently started.
121 */
122 private int[] mStartedUserArray = new int[] { 0 };
123
124 // If there are multiple profiles for the current user, their ids are here
125 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700126 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700127
128 /**
129 * Mapping from each known user ID to the profile group ID it is associated with.
130 */
131 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
132
133 /**
134 * Registered observers of the user switching mechanics.
135 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700136 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700137 = new RemoteCallbackList<>();
138
139 /**
140 * Currently active user switch.
141 */
142 Object mCurUserSwitchCallback;
143
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700144 private volatile UserManagerService mUserManager;
145
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700146 UserController(ActivityManagerService service) {
147 mService = service;
148 mHandler = mService.mHandler;
149 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800150 final UserState uss = new UserState(UserHandle.SYSTEM);
151 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700152 mUserLru.add(UserHandle.USER_SYSTEM);
153 updateStartedUserArrayLocked();
154 }
155
156 void finishUserSwitch(UserState uss) {
157 synchronized (mService) {
158 finishUserBoot(uss);
159
160 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700161 stopRunningUsersLocked(MAX_RUNNING_USERS);
162 }
163 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700164
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700165 void stopRunningUsersLocked(int maxRunningUsers) {
166 int num = mUserLru.size();
167 int i = 0;
168 while (num > maxRunningUsers && i < mUserLru.size()) {
169 Integer oldUserId = mUserLru.get(i);
170 UserState oldUss = mStartedUsers.get(oldUserId);
171 if (oldUss == null) {
172 // Shouldn't happen, but be sane if it does.
173 mUserLru.remove(i);
174 num--;
175 continue;
176 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700177 if (oldUss.state == UserState.STATE_STOPPING
178 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700179 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700180 num--;
181 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700182 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700183 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700184 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
185 // Owner/System user and current user can't be stopped. We count it as running
186 // when it is not a pure system user.
187 if (UserInfo.isSystemOnly(oldUserId)) {
188 num--;
189 }
190 i++;
191 continue;
192 }
193 // This is a user to be stopped.
194 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
195 num--;
196 }
197 num--;
198 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700199 }
200 }
201
202 void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700203 finishUserBoot(uss, null);
204 }
205
206 void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
207 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700208 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700209 // Bail if we ended up with a stale user
210 if (mStartedUsers.get(userId) != uss) return;
211
212 // We always walk through all the user lifecycle states to send
213 // consistent developer events. We step into RUNNING_LOCKED here,
214 // but we might immediately step into RUNNING below if the user
215 // storage is already unlocked.
216 if (uss.state == UserState.STATE_BOOTING) {
217 uss.setState(UserState.STATE_RUNNING_LOCKED);
218
219 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700220 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeya242f822015-12-17 15:38:20 -0700221 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
222 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700223 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
224 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
225 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
226 }
227
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700228 maybeUnlockUser(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700229 }
230 }
231
232 /**
233 * Consider stepping from {@link UserState#STATE_RUNNING_LOCKED} into
234 * {@link UserState#STATE_RUNNING}, which only occurs if the user storage is
235 * actually unlocked.
236 */
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700237 void finishUserUnlock(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700238 final int userId = uss.mHandle.getIdentifier();
239 synchronized (mService) {
240 // Bail if we ended up with a stale user
241 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
242
243 // Only keep marching forward if user is actually unlocked
244 if (!isUserKeyUnlocked(userId)) return;
245
246 if (uss.state == UserState.STATE_RUNNING_LOCKED) {
247 uss.setState(UserState.STATE_RUNNING);
248
249 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
250
251 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700252 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700253 unlockedIntent.addFlags(
254 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
255 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
256 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
257 userId);
258
259 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
260 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -0800261 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
262 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700263 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
264 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700265 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700266 }
267 }
268 }
269
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700270 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700271 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
272 != PackageManager.PERMISSION_GRANTED) {
273 String msg = "Permission Denial: switchUser() from pid="
274 + Binder.getCallingPid()
275 + ", uid=" + Binder.getCallingUid()
276 + " requires " + INTERACT_ACROSS_USERS_FULL;
277 Slog.w(TAG, msg);
278 throw new SecurityException(msg);
279 }
280 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
281 throw new IllegalArgumentException("Can't stop system user " + userId);
282 }
283 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
284 userId);
285 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700286 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700287 }
288 }
289
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700290 /**
291 * Stops the user along with its related users. The method calls
292 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
293 */
294 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
295 if (userId == UserHandle.USER_SYSTEM) {
296 return USER_OP_ERROR_IS_SYSTEM;
297 }
298 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700299 return USER_OP_IS_CURRENT;
300 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700301 int[] usersToStop = getUsersToStopLocked(userId);
302 // If one of related users is system or current, no related users should be stopped
303 for (int i = 0; i < usersToStop.length; i++) {
304 int relatedUserId = usersToStop[i];
305 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
306 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
307 + relatedUserId);
308 // We still need to stop the requested user if it's a force stop.
309 if (force) {
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800310 Slog.i(TAG,
311 "Force stop user " + userId + ". Related users will not be stopped");
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700312 stopSingleUserLocked(userId, callback);
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800313 return USER_OP_SUCCESS;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700314 }
315 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
316 }
317 }
318 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
319 for (int userIdToStop : usersToStop) {
320 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
321 }
322 return USER_OP_SUCCESS;
323 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700324
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700325 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
326 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700327 final UserState uss = mStartedUsers.get(userId);
328 if (uss == null) {
329 // User is not started, nothing to do... but we do need to
330 // callback if requested.
331 if (callback != null) {
332 mHandler.post(new Runnable() {
333 @Override
334 public void run() {
335 try {
336 callback.userStopped(userId);
337 } catch (RemoteException e) {
338 }
339 }
340 });
341 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700342 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700343 }
344
345 if (callback != null) {
346 uss.mStopCallbacks.add(callback);
347 }
348
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700349 if (uss.state != UserState.STATE_STOPPING
350 && uss.state != UserState.STATE_SHUTDOWN) {
351 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700352 updateStartedUserArrayLocked();
353
354 long ident = Binder.clearCallingIdentity();
355 try {
356 // We are going to broadcast ACTION_USER_STOPPING and then
357 // once that is done send a final ACTION_SHUTDOWN and then
358 // stop the user.
359 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
360 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
361 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
362 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
363 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
364 // This is the result receiver for the final shutdown broadcast.
365 final IIntentReceiver shutdownReceiver = 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 finishUserStop(uss);
370 }
371 };
372 // This is the result receiver for the initial stopping broadcast.
373 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
374 @Override
375 public void performReceive(Intent intent, int resultCode, String data,
376 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
377 // On to the next.
378 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700379 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700380 // Whoops, we are being started back up. Abort, abort!
381 return;
382 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700383 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700384 }
385 mService.mBatteryStatsService.noteEvent(
386 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
387 Integer.toString(userId), userId);
388 mService.mSystemServiceManager.stopUser(userId);
389 mService.broadcastIntentLocked(null, null, shutdownIntent,
390 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700391 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700392 }
393 };
394 // Kick things off.
395 mService.broadcastIntentLocked(null, null, stoppingIntent,
396 null, stoppingReceiver, 0, null, null,
397 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700398 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700399 } finally {
400 Binder.restoreCallingIdentity(ident);
401 }
402 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700403 }
404
405 void finishUserStop(UserState uss) {
406 final int userId = uss.mHandle.getIdentifier();
407 boolean stopped;
408 ArrayList<IStopUserCallback> callbacks;
409 synchronized (mService) {
410 callbacks = new ArrayList<>(uss.mStopCallbacks);
411 if (mStartedUsers.get(userId) != uss) {
412 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700413 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700414 stopped = false;
415 } else {
416 stopped = true;
417 // User can no longer run.
418 mStartedUsers.remove(userId);
419 mUserLru.remove(Integer.valueOf(userId));
420 updateStartedUserArrayLocked();
421
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800422 mService.onUserStoppedLocked(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700423 // Clean up all state and processes associated with the user.
424 // Kill all the processes for the user.
425 forceStopUserLocked(userId, "finish user");
426 }
427 }
428
429 for (int i = 0; i < callbacks.size(); i++) {
430 try {
431 if (stopped) callbacks.get(i).userStopped(userId);
432 else callbacks.get(i).userStopAborted(userId);
433 } catch (RemoteException e) {
434 }
435 }
436
437 if (stopped) {
438 mService.mSystemServiceManager.cleanupUser(userId);
439 synchronized (mService) {
440 mService.mStackSupervisor.removeUserLocked(userId);
441 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100442 // Remove the user if it is ephemeral.
443 if (getUserInfo(userId).isEphemeral()) {
444 mUserManager.removeUser(userId);
445 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700446 }
447 }
448
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700449 /**
450 * Determines the list of users that should be stopped together with the specified
451 * {@code userId}. The returned list includes {@code userId}.
452 */
453 private @NonNull int[] getUsersToStopLocked(int userId) {
454 int startedUsersSize = mStartedUsers.size();
455 IntArray userIds = new IntArray();
456 userIds.add(userId);
457 synchronized (mUserProfileGroupIdsSelfLocked) {
458 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
459 UserInfo.NO_PROFILE_GROUP_ID);
460 for (int i = 0; i < startedUsersSize; i++) {
461 UserState uss = mStartedUsers.valueAt(i);
462 int startedUserId = uss.mHandle.getIdentifier();
463 // Skip unrelated users (profileGroupId mismatch)
464 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
465 UserInfo.NO_PROFILE_GROUP_ID);
466 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
467 && (userGroupId == startedUserGroupId);
468 // userId has already been added
469 boolean sameUserId = startedUserId == userId;
470 if (!sameGroup || sameUserId) {
471 continue;
472 }
473 userIds.add(startedUserId);
474 }
475 }
476 return userIds.toArray();
477 }
478
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700479 private void forceStopUserLocked(int userId, String reason) {
480 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
481 userId, reason);
482 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
483 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
484 | Intent.FLAG_RECEIVER_FOREGROUND);
485 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
486 mService.broadcastIntentLocked(null, null, intent,
487 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700488 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700489 }
490
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700491 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100492 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700493 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100494 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700495 synchronized (mService) {
496 final int num = mUserLru.size();
497 for (int i = 0; i < num; i++) {
498 Integer oldUserId = mUserLru.get(i);
499 UserState oldUss = mStartedUsers.get(oldUserId);
500 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700501 || oldUss.state == UserState.STATE_STOPPING
502 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700503 continue;
504 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700505 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100506 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700507 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700508 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700509 break;
510 }
511 }
512 }
513 }
514
515 void startProfilesLocked() {
516 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700517 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700518 mCurrentUserId, false /* enabledOnly */);
519 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
520 for (UserInfo user : profiles) {
521 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
522 && user.id != mCurrentUserId) {
523 profilesToStart.add(user);
524 }
525 }
526 final int profilesToStartSize = profilesToStart.size();
527 int i = 0;
528 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
529 startUser(profilesToStart.get(i).id, /* foreground= */ false);
530 }
531 if (i < profilesToStartSize) {
532 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
533 }
534 }
535
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700536 private UserManagerService getUserManager() {
537 UserManagerService userManager = mUserManager;
538 if (userManager == null) {
539 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
540 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
541 }
542 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700543 }
544
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700545 private IMountService getMountService() {
546 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
547 }
548
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700549 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700550 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800551 if (mountService != null) {
552 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700553 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800554 } catch (RemoteException e) {
555 throw e.rethrowAsRuntimeException();
556 }
557 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700558 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
559 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800560 }
561 }
562
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700563 boolean startUser(final int userId, final boolean foreground) {
564 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
565 != PackageManager.PERMISSION_GRANTED) {
566 String msg = "Permission Denial: switchUser() from pid="
567 + Binder.getCallingPid()
568 + ", uid=" + Binder.getCallingUid()
569 + " requires " + INTERACT_ACROSS_USERS_FULL;
570 Slog.w(TAG, msg);
571 throw new SecurityException(msg);
572 }
573
574 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
575
576 final long ident = Binder.clearCallingIdentity();
577 try {
578 synchronized (mService) {
579 final int oldUserId = mCurrentUserId;
580 if (oldUserId == userId) {
581 return true;
582 }
583
584 mService.mStackSupervisor.setLockTaskModeLocked(null,
585 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
586
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700587 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700588 if (userInfo == null) {
589 Slog.w(TAG, "No user info for user #" + userId);
590 return false;
591 }
592 if (foreground && userInfo.isManagedProfile()) {
593 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
594 return false;
595 }
596
597 if (foreground) {
598 mService.mWindowManager.startFreezingScreen(
599 R.anim.screen_user_exit, R.anim.screen_user_enter);
600 }
601
602 boolean needStart = false;
603
604 // If the user we are switching to is not currently started, then
605 // we need to start it now.
606 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700607 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700608 updateStartedUserArrayLocked();
609 needStart = true;
610 }
611
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800612 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700613 final Integer userIdInt = userId;
614 mUserLru.remove(userIdInt);
615 mUserLru.add(userIdInt);
616
617 if (foreground) {
618 mCurrentUserId = userId;
619 mService.updateUserConfigurationLocked();
620 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
621 updateCurrentProfileIdsLocked();
622 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
623 // Once the internal notion of the active user has switched, we lock the device
624 // with the option to show the user switcher on the keyguard.
625 mService.mWindowManager.lockNow(null);
626 } else {
627 final Integer currentUserIdInt = mCurrentUserId;
628 updateCurrentProfileIdsLocked();
629 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
630 mUserLru.remove(currentUserIdInt);
631 mUserLru.add(currentUserIdInt);
632 }
633
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700634 // Make sure user is in the started state. If it is currently
635 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700636 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700637 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
638 // so we can just fairly silently bring the user back from
639 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700640 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700641 updateStartedUserArrayLocked();
642 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700643 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700644 // This means ACTION_SHUTDOWN has been sent, so we will
645 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700646 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700647 updateStartedUserArrayLocked();
648 needStart = true;
649 }
650
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700651 if (uss.state == UserState.STATE_BOOTING) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800652 // Let user manager propagate user restrictions to other services.
653 getUserManager().onBeforeStartUser(userId);
654
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700655 // Booting up a new user, need to tell system services about it.
656 // Note that this is on the same handler as scheduling of broadcasts,
657 // which is important because it needs to go first.
658 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
659 }
660
661 if (foreground) {
662 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
663 oldUserId));
664 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
665 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
666 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
667 oldUserId, userId, uss));
668 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
669 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
670 }
671
672 if (needStart) {
673 // Send USER_STARTED broadcast
674 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
675 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
676 | Intent.FLAG_RECEIVER_FOREGROUND);
677 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
678 mService.broadcastIntentLocked(null, null, intent,
679 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700680 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700681 }
682
683 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
684 if (userId != UserHandle.USER_SYSTEM) {
685 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
686 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
687 mService.broadcastIntentLocked(null, null, intent, null,
688 new IIntentReceiver.Stub() {
689 public void performReceive(Intent intent, int resultCode,
690 String data, Bundle extras, boolean ordered,
691 boolean sticky, int sendingUser) {
692 onUserInitialized(uss, foreground, oldUserId, userId);
693 }
694 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700695 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700696 uss.initializing = true;
697 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700698 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700699 }
700 }
701
702 if (foreground) {
703 if (!uss.initializing) {
704 moveUserToForegroundLocked(uss, oldUserId, userId);
705 }
706 } else {
707 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
708 }
709
710 if (needStart) {
711 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
712 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
713 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
714 mService.broadcastIntentLocked(null, null, intent,
715 null, new IIntentReceiver.Stub() {
716 @Override
717 public void performReceive(Intent intent, int resultCode,
718 String data, Bundle extras, boolean ordered, boolean sticky,
719 int sendingUser) throws RemoteException {
720 }
721 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700722 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
723 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700724 }
725 }
726 } finally {
727 Binder.restoreCallingIdentity(ident);
728 }
729
730 return true;
731 }
732
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700733 /**
734 * Start user, if its not already running, and bring it to foreground.
735 */
736 boolean startUserInForeground(final int userId, Dialog dlg) {
737 boolean result = startUser(userId, /* foreground */ true);
738 dlg.dismiss();
739 return result;
740 }
741
Jeff Sharkeyba512352015-11-12 20:17:45 -0800742 boolean unlockUser(final int userId, byte[] token) {
743 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
744 != PackageManager.PERMISSION_GRANTED) {
745 String msg = "Permission Denial: unlockUser() from pid="
746 + Binder.getCallingPid()
747 + ", uid=" + Binder.getCallingUid()
748 + " requires " + INTERACT_ACROSS_USERS_FULL;
749 Slog.w(TAG, msg);
750 throw new SecurityException(msg);
751 }
752
Jeff Sharkey8924e872015-11-30 12:52:10 -0700753 final long binderToken = Binder.clearCallingIdentity();
754 try {
755 return unlockUserCleared(userId, token);
756 } finally {
757 Binder.restoreCallingIdentity(binderToken);
758 }
759 }
760
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700761 /**
762 * Attempt to unlock user without a credential token. This typically
763 * succeeds when the device doesn't have credential-encrypted storage, or
764 * when the the credential-encrypted storage isn't tied to a user-provided
765 * PIN or pattern.
766 */
767 boolean maybeUnlockUser(final int userId) {
768 // Try unlocking storage using empty token
769 return unlockUserCleared(userId, null);
770 }
771
Jeff Sharkey8924e872015-11-30 12:52:10 -0700772 boolean unlockUserCleared(final int userId, byte[] token) {
773 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700774 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700775 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700776 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700777 }
778
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700779 if (!isUserKeyUnlocked(userId)) {
780 final UserInfo userInfo = getUserInfo(userId);
781 final IMountService mountService = getMountService();
782 try {
783 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
784 } catch (RemoteException | RuntimeException e) {
785 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
786 return false;
787 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800788 }
789
790 synchronized (mService) {
791 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700792 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800793 }
794
795 return true;
796 }
797
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800798 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700799 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800800 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
801 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700802 d.show();
803 }
804
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700805 void dispatchForegroundProfileChanged(int userId) {
806 final int observerCount = mUserSwitchObservers.beginBroadcast();
807 for (int i = 0; i < observerCount; i++) {
808 try {
809 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
810 } catch (RemoteException e) {
811 // Ignore
812 }
813 }
814 mUserSwitchObservers.finishBroadcast();
815 }
816
817 /** Called on handler thread */
818 void dispatchUserSwitchComplete(int userId) {
819 final int observerCount = mUserSwitchObservers.beginBroadcast();
820 for (int i = 0; i < observerCount; i++) {
821 try {
822 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
823 } catch (RemoteException e) {
824 }
825 }
826 mUserSwitchObservers.finishBroadcast();
827 }
828
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700829 private void stopBackgroundUsersIfEnforced(int oldUserId) {
830 // Never stop system user
831 if (oldUserId == UserHandle.USER_SYSTEM) {
832 return;
833 }
834 // For now, only check for user restriction. Additional checks can be added here
835 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
836 oldUserId);
837 if (!disallowRunInBg) {
838 return;
839 }
840 synchronized (mService) {
841 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
842 + " and related users");
843 stopUsersLocked(oldUserId, false, null);
844 }
845 }
846
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700847 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
848 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800849 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700850 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
851 }
852 }
853
854 void dispatchUserSwitch(final UserState uss, final int oldUserId,
855 final int newUserId) {
856 final int observerCount = mUserSwitchObservers.beginBroadcast();
857 if (observerCount > 0) {
858 final IRemoteCallback callback = new IRemoteCallback.Stub() {
859 int mCount = 0;
860 @Override
861 public void sendResult(Bundle data) throws RemoteException {
862 synchronized (mService) {
863 if (mCurUserSwitchCallback == this) {
864 mCount++;
865 if (mCount == observerCount) {
866 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
867 }
868 }
869 }
870 }
871 };
872 synchronized (mService) {
873 uss.switching = true;
874 mCurUserSwitchCallback = callback;
875 }
876 for (int i = 0; i < observerCount; i++) {
877 try {
878 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
879 newUserId, callback);
880 } catch (RemoteException e) {
881 }
882 }
883 } else {
884 synchronized (mService) {
885 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
886 }
887 }
888 mUserSwitchObservers.finishBroadcast();
889 }
890
891 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
892 mCurUserSwitchCallback = null;
893 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
894 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
895 oldUserId, newUserId, uss));
896 }
897
898 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700899 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700900 }
901
902 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
903 synchronized (mService) {
904 if (foreground) {
905 moveUserToForegroundLocked(uss, oldUserId, newUserId);
906 }
907 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700908 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700909 }
910
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700911 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700912 boolean clearInitializing, boolean clearSwitching) {
913 boolean unfrozen = false;
914 synchronized (mService) {
915 if (clearInitializing) {
916 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700917 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700918 }
919 if (clearSwitching) {
920 uss.switching = false;
921 }
922 if (!uss.switching && !uss.initializing) {
923 mService.mWindowManager.stopFreezingScreen();
924 unfrozen = true;
925 }
926 }
927 if (unfrozen) {
928 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
929 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
930 newUserId, 0));
931 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100932 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700933 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700934 }
935
936 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
937 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
938 if (homeInFront) {
939 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
940 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800941 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700942 }
943 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700944 getUserManager().onUserForeground(newUserId);
945 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
946 }
947
948 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
949 long ident = Binder.clearCallingIdentity();
950 try {
951 Intent intent;
952 if (oldUserId >= 0) {
953 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
954 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
955 int count = profiles.size();
956 for (int i = 0; i < count; i++) {
957 int profileUserId = profiles.get(i).id;
958 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
959 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
960 | Intent.FLAG_RECEIVER_FOREGROUND);
961 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
962 mService.broadcastIntentLocked(null, null, intent,
963 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
964 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
965 }
966 }
967 if (newUserId >= 0) {
968 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
969 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
970 int count = profiles.size();
971 for (int i = 0; i < count; i++) {
972 int profileUserId = profiles.get(i).id;
973 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
974 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
975 | Intent.FLAG_RECEIVER_FOREGROUND);
976 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
977 mService.broadcastIntentLocked(null, null, intent,
978 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
979 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
980 }
981 intent = new Intent(Intent.ACTION_USER_SWITCHED);
982 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
983 | Intent.FLAG_RECEIVER_FOREGROUND);
984 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
985 mService.broadcastIntentLocked(null, null, intent,
986 null, null, 0, null, null,
987 new String[] {android.Manifest.permission.MANAGE_USERS},
988 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
989 UserHandle.USER_ALL);
990 }
991 } finally {
992 Binder.restoreCallingIdentity(ident);
993 }
994 }
995
996
997 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
998 int allowMode, String name, String callerPackage) {
999 final int callingUserId = UserHandle.getUserId(callingUid);
1000 if (callingUserId == userId) {
1001 return userId;
1002 }
1003
1004 // Note that we may be accessing mCurrentUserId outside of a lock...
1005 // shouldn't be a big deal, if this is being called outside
1006 // of a locked context there is intrinsically a race with
1007 // the value the caller will receive and someone else changing it.
1008 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1009 // we will switch to the calling user if access to the current user fails.
1010 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1011
1012 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1013 final boolean allow;
1014 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1015 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1016 // If the caller has this permission, they always pass go. And collect $200.
1017 allow = true;
1018 } else if (allowMode == ALLOW_FULL_ONLY) {
1019 // We require full access, sucks to be you.
1020 allow = false;
1021 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1022 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1023 // If the caller does not have either permission, they are always doomed.
1024 allow = false;
1025 } else if (allowMode == ALLOW_NON_FULL) {
1026 // We are blanket allowing non-full access, you lucky caller!
1027 allow = true;
1028 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1029 // We may or may not allow this depending on whether the two users are
1030 // in the same profile.
1031 allow = isSameProfileGroup(callingUserId, targetUserId);
1032 } else {
1033 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1034 }
1035 if (!allow) {
1036 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1037 // In this case, they would like to just execute as their
1038 // owner user instead of failing.
1039 targetUserId = callingUserId;
1040 } else {
1041 StringBuilder builder = new StringBuilder(128);
1042 builder.append("Permission Denial: ");
1043 builder.append(name);
1044 if (callerPackage != null) {
1045 builder.append(" from ");
1046 builder.append(callerPackage);
1047 }
1048 builder.append(" asks to run as user ");
1049 builder.append(userId);
1050 builder.append(" but is calling from user ");
1051 builder.append(UserHandle.getUserId(callingUid));
1052 builder.append("; this requires ");
1053 builder.append(INTERACT_ACROSS_USERS_FULL);
1054 if (allowMode != ALLOW_FULL_ONLY) {
1055 builder.append(" or ");
1056 builder.append(INTERACT_ACROSS_USERS);
1057 }
1058 String msg = builder.toString();
1059 Slog.w(TAG, msg);
1060 throw new SecurityException(msg);
1061 }
1062 }
1063 }
1064 if (!allowAll && targetUserId < 0) {
1065 throw new IllegalArgumentException(
1066 "Call does not support special user #" + targetUserId);
1067 }
1068 // Check shell permission
1069 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1070 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1071 throw new SecurityException("Shell does not have permission to access user "
1072 + targetUserId + "\n " + Debug.getCallers(3));
1073 }
1074 }
1075 return targetUserId;
1076 }
1077
1078 int unsafeConvertIncomingUserLocked(int userId) {
1079 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1080 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001081 }
1082
1083 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1084 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1085 != PackageManager.PERMISSION_GRANTED) {
1086 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1087 + Binder.getCallingPid()
1088 + ", uid=" + Binder.getCallingUid()
1089 + " requires " + INTERACT_ACROSS_USERS_FULL;
1090 Slog.w(TAG, msg);
1091 throw new SecurityException(msg);
1092 }
1093
1094 mUserSwitchObservers.register(observer);
1095 }
1096
1097 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1098 mUserSwitchObservers.unregister(observer);
1099 }
1100
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001101 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001102 return mStartedUsers.get(userId);
1103 }
1104
1105 boolean hasStartedUserState(int userId) {
1106 return mStartedUsers.get(userId) != null;
1107 }
1108
1109 private void updateStartedUserArrayLocked() {
1110 int num = 0;
1111 for (int i = 0; i < mStartedUsers.size(); i++) {
1112 UserState uss = mStartedUsers.valueAt(i);
1113 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001114 if (uss.state != UserState.STATE_STOPPING
1115 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001116 num++;
1117 }
1118 }
1119 mStartedUserArray = new int[num];
1120 num = 0;
1121 for (int i = 0; i < mStartedUsers.size(); i++) {
1122 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001123 if (uss.state != UserState.STATE_STOPPING
1124 && uss.state != UserState.STATE_SHUTDOWN) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -08001125 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001126 }
1127 }
1128 }
1129
1130 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1131 for (int i = 0; i < mStartedUsers.size(); i++) {
1132 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001133 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001134 }
1135 }
1136
1137 /**
1138 * Refreshes the list of users related to the current user when either a
1139 * user switch happens or when a new related user is started in the
1140 * background.
1141 */
1142 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001143 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001144 false /* enabledOnly */);
1145 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1146 for (int i = 0; i < currentProfileIds.length; i++) {
1147 currentProfileIds[i] = profiles.get(i).id;
1148 }
1149 mCurrentProfileIds = currentProfileIds;
1150
1151 synchronized (mUserProfileGroupIdsSelfLocked) {
1152 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001153 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001154 for (int i = 0; i < users.size(); i++) {
1155 UserInfo user = users.get(i);
1156 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1157 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1158 }
1159 }
1160 }
1161 }
1162
1163 int[] getStartedUserArrayLocked() {
1164 return mStartedUserArray;
1165 }
1166
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001167 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001168 UserState state = getStartedUserStateLocked(userId);
1169 if (state == null) {
1170 return false;
1171 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001172 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001173 return true;
1174 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001175
1176 final boolean unlocked;
1177 switch (state.state) {
1178 case UserState.STATE_STOPPING:
1179 case UserState.STATE_SHUTDOWN:
1180 default:
1181 return false;
1182
1183 case UserState.STATE_BOOTING:
1184 case UserState.STATE_RUNNING_LOCKED:
1185 unlocked = false;
1186 break;
1187
1188 case UserState.STATE_RUNNING:
1189 unlocked = true;
1190 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001191 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001192
1193 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1194 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001195 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001196 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1197 return unlocked;
1198 }
1199
1200 // One way or another, we're running!
1201 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001202 }
1203
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001204 UserInfo getCurrentUser() {
1205 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1206 != PackageManager.PERMISSION_GRANTED) && (
1207 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1208 != PackageManager.PERMISSION_GRANTED)) {
1209 String msg = "Permission Denial: getCurrentUser() from pid="
1210 + Binder.getCallingPid()
1211 + ", uid=" + Binder.getCallingUid()
1212 + " requires " + INTERACT_ACROSS_USERS;
1213 Slog.w(TAG, msg);
1214 throw new SecurityException(msg);
1215 }
1216 synchronized (mService) {
1217 return getCurrentUserLocked();
1218 }
1219 }
1220
1221 UserInfo getCurrentUserLocked() {
1222 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001223 return getUserInfo(userId);
1224 }
1225
1226 int getCurrentOrTargetUserIdLocked() {
1227 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001228 }
1229
1230 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001231 return mCurrentUserId;
1232 }
1233
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001234 private boolean isCurrentUserLocked(int userId) {
Amith Yamasani458ac462015-12-18 11:21:31 -08001235 return userId == getCurrentOrTargetUserIdLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001236 }
1237
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001238 int setTargetUserIdLocked(int targetUserId) {
1239 return mTargetUserId = targetUserId;
1240 }
1241
1242 int[] getUsers() {
1243 UserManagerService ums = getUserManager();
1244 return ums != null ? ums.getUserIds() : new int[] { 0 };
1245 }
1246
1247 UserInfo getUserInfo(int userId) {
1248 return getUserManager().getUserInfo(userId);
1249 }
1250
1251 int[] getUserIds() {
1252 return getUserManager().getUserIds();
1253 }
1254
1255 boolean exists(int userId) {
1256 return getUserManager().exists(userId);
1257 }
1258
1259 boolean hasUserRestriction(String restriction, int userId) {
1260 return getUserManager().hasUserRestriction(restriction, userId);
1261 }
1262
1263 Set<Integer> getProfileIds(int userId) {
1264 Set<Integer> userIds = new HashSet<>();
1265 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1266 false /* enabledOnly */);
1267 for (UserInfo user : profiles) {
1268 userIds.add(user.id);
1269 }
1270 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001271 }
1272
1273 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1274 synchronized (mUserProfileGroupIdsSelfLocked) {
1275 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1276 UserInfo.NO_PROFILE_GROUP_ID);
1277 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1278 UserInfo.NO_PROFILE_GROUP_ID);
1279 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1280 && callingProfile == targetProfile;
1281 }
1282 }
1283
1284 boolean isCurrentProfileLocked(int userId) {
1285 return ArrayUtils.contains(mCurrentProfileIds, userId);
1286 }
1287
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001288 int[] getCurrentProfileIdsLocked() {
1289 return mCurrentProfileIds;
1290 }
1291
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001292 /**
1293 * Returns whether the given user requires credential entry at this time. This is used to
1294 * intercept activity launches for work apps when the Work Challenge is present.
1295 */
1296 boolean shouldConfirmCredentials(int userId) {
1297 final UserInfo user = getUserInfo(userId);
1298 if (!user.isManagedProfile() || !LockPatternUtils.isSeparateWorkChallengeEnabled()) {
1299 return false;
1300 }
1301 final KeyguardManager km = (KeyguardManager) mService.mContext
1302 .getSystemService(KEYGUARD_SERVICE);
1303 return km.isDeviceLocked(user.id);
1304 }
1305
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001306 void dump(PrintWriter pw, boolean dumpAll) {
1307 pw.println(" mStartedUsers:");
1308 for (int i = 0; i < mStartedUsers.size(); i++) {
1309 UserState uss = mStartedUsers.valueAt(i);
1310 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1311 pw.print(": "); uss.dump("", pw);
1312 }
1313 pw.print(" mStartedUserArray: [");
1314 for (int i = 0; i < mStartedUserArray.length; i++) {
1315 if (i > 0) pw.print(", ");
1316 pw.print(mStartedUserArray[i]);
1317 }
1318 pw.println("]");
1319 pw.print(" mUserLru: [");
1320 for (int i = 0; i < mUserLru.size(); i++) {
1321 if (i > 0) pw.print(", ");
1322 pw.print(mUserLru.get(i));
1323 }
1324 pw.println("]");
1325 if (dumpAll) {
1326 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1327 }
1328 synchronized (mUserProfileGroupIdsSelfLocked) {
1329 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1330 pw.println(" mUserProfileGroupIds:");
1331 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1332 pw.print(" User #");
1333 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1334 pw.print(" -> profile #");
1335 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1336 }
1337 }
1338 }
1339 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001340}