blob: a21570cef476b65560c618d194fa028b5423b3c8 [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
Clara Bayarria1771112015-12-18 16:29:18 +0000146 private final LockPatternUtils mLockPatternUtils;
147
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700148 UserController(ActivityManagerService service) {
149 mService = service;
150 mHandler = mService.mHandler;
151 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800152 final UserState uss = new UserState(UserHandle.SYSTEM);
153 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700154 mUserLru.add(UserHandle.USER_SYSTEM);
Clara Bayarria1771112015-12-18 16:29:18 +0000155 mLockPatternUtils = new LockPatternUtils(mService.mContext);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700156 updateStartedUserArrayLocked();
157 }
158
159 void finishUserSwitch(UserState uss) {
160 synchronized (mService) {
161 finishUserBoot(uss);
162
163 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700164 stopRunningUsersLocked(MAX_RUNNING_USERS);
165 }
166 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700167
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700168 void stopRunningUsersLocked(int maxRunningUsers) {
169 int num = mUserLru.size();
170 int i = 0;
171 while (num > maxRunningUsers && i < mUserLru.size()) {
172 Integer oldUserId = mUserLru.get(i);
173 UserState oldUss = mStartedUsers.get(oldUserId);
174 if (oldUss == null) {
175 // Shouldn't happen, but be sane if it does.
176 mUserLru.remove(i);
177 num--;
178 continue;
179 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700180 if (oldUss.state == UserState.STATE_STOPPING
181 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700182 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700183 num--;
184 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700185 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700186 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700187 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
188 // Owner/System user and current user can't be stopped. We count it as running
189 // when it is not a pure system user.
190 if (UserInfo.isSystemOnly(oldUserId)) {
191 num--;
192 }
193 i++;
194 continue;
195 }
196 // This is a user to be stopped.
197 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
198 num--;
199 }
200 num--;
201 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700202 }
203 }
204
205 void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700206 finishUserBoot(uss, null);
207 }
208
209 void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
210 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700211 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700212 // Bail if we ended up with a stale user
213 if (mStartedUsers.get(userId) != uss) return;
214
215 // We always walk through all the user lifecycle states to send
216 // consistent developer events. We step into RUNNING_LOCKED here,
217 // but we might immediately step into RUNNING below if the user
218 // storage is already unlocked.
219 if (uss.state == UserState.STATE_BOOTING) {
220 uss.setState(UserState.STATE_RUNNING_LOCKED);
221
222 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700223 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeya242f822015-12-17 15:38:20 -0700224 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
225 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700226 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
227 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
228 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
229 }
230
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700231 maybeUnlockUser(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700232 }
233 }
234
235 /**
236 * Consider stepping from {@link UserState#STATE_RUNNING_LOCKED} into
237 * {@link UserState#STATE_RUNNING}, which only occurs if the user storage is
238 * actually unlocked.
239 */
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700240 void finishUserUnlock(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700241 final int userId = uss.mHandle.getIdentifier();
242 synchronized (mService) {
243 // Bail if we ended up with a stale user
244 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
245
246 // Only keep marching forward if user is actually unlocked
247 if (!isUserKeyUnlocked(userId)) return;
248
249 if (uss.state == UserState.STATE_RUNNING_LOCKED) {
250 uss.setState(UserState.STATE_RUNNING);
251
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700252 // Give user manager a chance to prepare app storage
253 mUserManager.onBeforeUnlockUser(userId);
254
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700255 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
256
257 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700258 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700259 unlockedIntent.addFlags(
260 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
261 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
262 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
263 userId);
264
265 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
266 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -0800267 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
268 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700269 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
270 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700271 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700272 }
273 }
274 }
275
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700276 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700277 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
278 != PackageManager.PERMISSION_GRANTED) {
279 String msg = "Permission Denial: switchUser() from pid="
280 + Binder.getCallingPid()
281 + ", uid=" + Binder.getCallingUid()
282 + " requires " + INTERACT_ACROSS_USERS_FULL;
283 Slog.w(TAG, msg);
284 throw new SecurityException(msg);
285 }
286 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
287 throw new IllegalArgumentException("Can't stop system user " + userId);
288 }
289 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
290 userId);
291 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700292 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700293 }
294 }
295
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700296 /**
297 * Stops the user along with its related users. The method calls
298 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
299 */
300 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
301 if (userId == UserHandle.USER_SYSTEM) {
302 return USER_OP_ERROR_IS_SYSTEM;
303 }
304 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700305 return USER_OP_IS_CURRENT;
306 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700307 int[] usersToStop = getUsersToStopLocked(userId);
308 // If one of related users is system or current, no related users should be stopped
309 for (int i = 0; i < usersToStop.length; i++) {
310 int relatedUserId = usersToStop[i];
311 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
312 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
313 + relatedUserId);
314 // We still need to stop the requested user if it's a force stop.
315 if (force) {
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800316 Slog.i(TAG,
317 "Force stop user " + userId + ". Related users will not be stopped");
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700318 stopSingleUserLocked(userId, callback);
Fyodor Kupolov7b4a8a42016-01-04 12:47:22 -0800319 return USER_OP_SUCCESS;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700320 }
321 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
322 }
323 }
324 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
325 for (int userIdToStop : usersToStop) {
326 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
327 }
328 return USER_OP_SUCCESS;
329 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700330
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700331 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
332 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700333 final UserState uss = mStartedUsers.get(userId);
334 if (uss == null) {
335 // User is not started, nothing to do... but we do need to
336 // callback if requested.
337 if (callback != null) {
338 mHandler.post(new Runnable() {
339 @Override
340 public void run() {
341 try {
342 callback.userStopped(userId);
343 } catch (RemoteException e) {
344 }
345 }
346 });
347 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700348 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700349 }
350
351 if (callback != null) {
352 uss.mStopCallbacks.add(callback);
353 }
354
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700355 if (uss.state != UserState.STATE_STOPPING
356 && uss.state != UserState.STATE_SHUTDOWN) {
357 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700358 updateStartedUserArrayLocked();
359
360 long ident = Binder.clearCallingIdentity();
361 try {
362 // We are going to broadcast ACTION_USER_STOPPING and then
363 // once that is done send a final ACTION_SHUTDOWN and then
364 // stop the user.
365 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
366 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
367 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
368 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
369 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
370 // This is the result receiver for the final shutdown broadcast.
371 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
372 @Override
373 public void performReceive(Intent intent, int resultCode, String data,
374 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
375 finishUserStop(uss);
376 }
377 };
378 // This is the result receiver for the initial stopping broadcast.
379 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
380 @Override
381 public void performReceive(Intent intent, int resultCode, String data,
382 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
383 // On to the next.
384 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700385 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700386 // Whoops, we are being started back up. Abort, abort!
387 return;
388 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700389 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700390 }
391 mService.mBatteryStatsService.noteEvent(
392 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
393 Integer.toString(userId), userId);
394 mService.mSystemServiceManager.stopUser(userId);
395 mService.broadcastIntentLocked(null, null, shutdownIntent,
396 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700397 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700398 }
399 };
400 // Kick things off.
401 mService.broadcastIntentLocked(null, null, stoppingIntent,
402 null, stoppingReceiver, 0, null, null,
403 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700404 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700405 } finally {
406 Binder.restoreCallingIdentity(ident);
407 }
408 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700409 }
410
411 void finishUserStop(UserState uss) {
412 final int userId = uss.mHandle.getIdentifier();
413 boolean stopped;
414 ArrayList<IStopUserCallback> callbacks;
415 synchronized (mService) {
416 callbacks = new ArrayList<>(uss.mStopCallbacks);
417 if (mStartedUsers.get(userId) != uss) {
418 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700419 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700420 stopped = false;
421 } else {
422 stopped = true;
423 // User can no longer run.
424 mStartedUsers.remove(userId);
425 mUserLru.remove(Integer.valueOf(userId));
426 updateStartedUserArrayLocked();
427
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800428 mService.onUserStoppedLocked(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700429 // Clean up all state and processes associated with the user.
430 // Kill all the processes for the user.
431 forceStopUserLocked(userId, "finish user");
432 }
433 }
434
435 for (int i = 0; i < callbacks.size(); i++) {
436 try {
437 if (stopped) callbacks.get(i).userStopped(userId);
438 else callbacks.get(i).userStopAborted(userId);
439 } catch (RemoteException e) {
440 }
441 }
442
443 if (stopped) {
444 mService.mSystemServiceManager.cleanupUser(userId);
445 synchronized (mService) {
446 mService.mStackSupervisor.removeUserLocked(userId);
447 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100448 // Remove the user if it is ephemeral.
449 if (getUserInfo(userId).isEphemeral()) {
450 mUserManager.removeUser(userId);
451 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700452 }
453 }
454
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700455 /**
456 * Determines the list of users that should be stopped together with the specified
457 * {@code userId}. The returned list includes {@code userId}.
458 */
459 private @NonNull int[] getUsersToStopLocked(int userId) {
460 int startedUsersSize = mStartedUsers.size();
461 IntArray userIds = new IntArray();
462 userIds.add(userId);
463 synchronized (mUserProfileGroupIdsSelfLocked) {
464 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
465 UserInfo.NO_PROFILE_GROUP_ID);
466 for (int i = 0; i < startedUsersSize; i++) {
467 UserState uss = mStartedUsers.valueAt(i);
468 int startedUserId = uss.mHandle.getIdentifier();
469 // Skip unrelated users (profileGroupId mismatch)
470 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
471 UserInfo.NO_PROFILE_GROUP_ID);
472 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
473 && (userGroupId == startedUserGroupId);
474 // userId has already been added
475 boolean sameUserId = startedUserId == userId;
476 if (!sameGroup || sameUserId) {
477 continue;
478 }
479 userIds.add(startedUserId);
480 }
481 }
482 return userIds.toArray();
483 }
484
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700485 private void forceStopUserLocked(int userId, String reason) {
486 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
487 userId, reason);
488 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
489 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
490 | Intent.FLAG_RECEIVER_FOREGROUND);
491 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
492 mService.broadcastIntentLocked(null, null, intent,
493 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700494 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700495 }
496
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700497 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100498 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700499 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100500 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700501 synchronized (mService) {
502 final int num = mUserLru.size();
503 for (int i = 0; i < num; i++) {
504 Integer oldUserId = mUserLru.get(i);
505 UserState oldUss = mStartedUsers.get(oldUserId);
506 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700507 || oldUss.state == UserState.STATE_STOPPING
508 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700509 continue;
510 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700511 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100512 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700513 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700514 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700515 break;
516 }
517 }
518 }
519 }
520
521 void startProfilesLocked() {
522 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700523 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700524 mCurrentUserId, false /* enabledOnly */);
525 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
526 for (UserInfo user : profiles) {
527 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
Rubin Xuf13c9802016-01-21 18:06:00 +0000528 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700529 profilesToStart.add(user);
530 }
531 }
532 final int profilesToStartSize = profilesToStart.size();
533 int i = 0;
534 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
535 startUser(profilesToStart.get(i).id, /* foreground= */ false);
536 }
537 if (i < profilesToStartSize) {
538 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
539 }
540 }
541
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700542 private UserManagerService getUserManager() {
543 UserManagerService userManager = mUserManager;
544 if (userManager == null) {
545 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
546 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
547 }
548 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700549 }
550
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700551 private IMountService getMountService() {
552 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
553 }
554
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700555 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700556 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800557 if (mountService != null) {
558 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700559 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800560 } catch (RemoteException e) {
561 throw e.rethrowAsRuntimeException();
562 }
563 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700564 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
565 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800566 }
567 }
568
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700569 boolean startUser(final int userId, final boolean foreground) {
570 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
571 != PackageManager.PERMISSION_GRANTED) {
572 String msg = "Permission Denial: switchUser() from pid="
573 + Binder.getCallingPid()
574 + ", uid=" + Binder.getCallingUid()
575 + " requires " + INTERACT_ACROSS_USERS_FULL;
576 Slog.w(TAG, msg);
577 throw new SecurityException(msg);
578 }
579
580 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
581
582 final long ident = Binder.clearCallingIdentity();
583 try {
584 synchronized (mService) {
585 final int oldUserId = mCurrentUserId;
586 if (oldUserId == userId) {
587 return true;
588 }
589
590 mService.mStackSupervisor.setLockTaskModeLocked(null,
591 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
592
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700593 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700594 if (userInfo == null) {
595 Slog.w(TAG, "No user info for user #" + userId);
596 return false;
597 }
598 if (foreground && userInfo.isManagedProfile()) {
599 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
600 return false;
601 }
602
603 if (foreground) {
604 mService.mWindowManager.startFreezingScreen(
605 R.anim.screen_user_exit, R.anim.screen_user_enter);
606 }
607
608 boolean needStart = false;
609
610 // If the user we are switching to is not currently started, then
611 // we need to start it now.
612 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700613 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700614 updateStartedUserArrayLocked();
615 needStart = true;
616 }
617
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800618 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700619 final Integer userIdInt = userId;
620 mUserLru.remove(userIdInt);
621 mUserLru.add(userIdInt);
622
623 if (foreground) {
624 mCurrentUserId = userId;
625 mService.updateUserConfigurationLocked();
626 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
627 updateCurrentProfileIdsLocked();
628 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
629 // Once the internal notion of the active user has switched, we lock the device
630 // with the option to show the user switcher on the keyguard.
631 mService.mWindowManager.lockNow(null);
632 } else {
633 final Integer currentUserIdInt = mCurrentUserId;
634 updateCurrentProfileIdsLocked();
635 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
636 mUserLru.remove(currentUserIdInt);
637 mUserLru.add(currentUserIdInt);
638 }
639
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700640 // Make sure user is in the started state. If it is currently
641 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700642 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700643 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
644 // so we can just fairly silently bring the user back from
645 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700646 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700647 updateStartedUserArrayLocked();
648 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700649 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700650 // This means ACTION_SHUTDOWN has been sent, so we will
651 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700652 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700653 updateStartedUserArrayLocked();
654 needStart = true;
655 }
656
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700657 if (uss.state == UserState.STATE_BOOTING) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700658 // Give user manager a chance to propagate user restrictions
659 // to other services and prepare app storage
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800660 getUserManager().onBeforeStartUser(userId);
661
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700662 // Booting up a new user, need to tell system services about it.
663 // Note that this is on the same handler as scheduling of broadcasts,
664 // which is important because it needs to go first.
665 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
666 }
667
668 if (foreground) {
669 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
670 oldUserId));
671 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
672 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
673 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
674 oldUserId, userId, uss));
675 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
676 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
677 }
678
679 if (needStart) {
680 // Send USER_STARTED broadcast
681 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
682 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
683 | Intent.FLAG_RECEIVER_FOREGROUND);
684 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
685 mService.broadcastIntentLocked(null, null, intent,
686 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700687 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700688 }
689
690 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
691 if (userId != UserHandle.USER_SYSTEM) {
692 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
693 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
694 mService.broadcastIntentLocked(null, null, intent, null,
695 new IIntentReceiver.Stub() {
696 public void performReceive(Intent intent, int resultCode,
697 String data, Bundle extras, boolean ordered,
698 boolean sticky, int sendingUser) {
699 onUserInitialized(uss, foreground, oldUserId, userId);
700 }
701 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700702 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700703 uss.initializing = true;
704 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700705 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700706 }
707 }
708
709 if (foreground) {
710 if (!uss.initializing) {
711 moveUserToForegroundLocked(uss, oldUserId, userId);
712 }
713 } else {
714 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
715 }
716
717 if (needStart) {
718 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
719 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
720 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
721 mService.broadcastIntentLocked(null, null, intent,
722 null, new IIntentReceiver.Stub() {
723 @Override
724 public void performReceive(Intent intent, int resultCode,
725 String data, Bundle extras, boolean ordered, boolean sticky,
726 int sendingUser) throws RemoteException {
727 }
728 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700729 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
730 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700731 }
732 }
733 } finally {
734 Binder.restoreCallingIdentity(ident);
735 }
736
737 return true;
738 }
739
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700740 /**
741 * Start user, if its not already running, and bring it to foreground.
742 */
743 boolean startUserInForeground(final int userId, Dialog dlg) {
744 boolean result = startUser(userId, /* foreground */ true);
745 dlg.dismiss();
746 return result;
747 }
748
Jeff Sharkeyba512352015-11-12 20:17:45 -0800749 boolean unlockUser(final int userId, byte[] token) {
750 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
751 != PackageManager.PERMISSION_GRANTED) {
752 String msg = "Permission Denial: unlockUser() from pid="
753 + Binder.getCallingPid()
754 + ", uid=" + Binder.getCallingUid()
755 + " requires " + INTERACT_ACROSS_USERS_FULL;
756 Slog.w(TAG, msg);
757 throw new SecurityException(msg);
758 }
759
Jeff Sharkey8924e872015-11-30 12:52:10 -0700760 final long binderToken = Binder.clearCallingIdentity();
761 try {
762 return unlockUserCleared(userId, token);
763 } finally {
764 Binder.restoreCallingIdentity(binderToken);
765 }
766 }
767
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700768 /**
769 * Attempt to unlock user without a credential token. This typically
770 * succeeds when the device doesn't have credential-encrypted storage, or
771 * when the the credential-encrypted storage isn't tied to a user-provided
772 * PIN or pattern.
773 */
774 boolean maybeUnlockUser(final int userId) {
775 // Try unlocking storage using empty token
776 return unlockUserCleared(userId, null);
777 }
778
Jeff Sharkey8924e872015-11-30 12:52:10 -0700779 boolean unlockUserCleared(final int userId, byte[] token) {
780 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700781 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700782 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700783 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700784 }
785
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700786 if (!isUserKeyUnlocked(userId)) {
787 final UserInfo userInfo = getUserInfo(userId);
788 final IMountService mountService = getMountService();
789 try {
790 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
791 } catch (RemoteException | RuntimeException e) {
792 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
793 return false;
794 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800795 }
796
797 synchronized (mService) {
798 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700799 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800800 }
801
802 return true;
803 }
804
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800805 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700806 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800807 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
808 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700809 d.show();
810 }
811
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700812 void dispatchForegroundProfileChanged(int userId) {
813 final int observerCount = mUserSwitchObservers.beginBroadcast();
814 for (int i = 0; i < observerCount; i++) {
815 try {
816 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
817 } catch (RemoteException e) {
818 // Ignore
819 }
820 }
821 mUserSwitchObservers.finishBroadcast();
822 }
823
824 /** Called on handler thread */
825 void dispatchUserSwitchComplete(int userId) {
826 final int observerCount = mUserSwitchObservers.beginBroadcast();
827 for (int i = 0; i < observerCount; i++) {
828 try {
829 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
830 } catch (RemoteException e) {
831 }
832 }
833 mUserSwitchObservers.finishBroadcast();
834 }
835
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700836 private void stopBackgroundUsersIfEnforced(int oldUserId) {
837 // Never stop system user
838 if (oldUserId == UserHandle.USER_SYSTEM) {
839 return;
840 }
841 // For now, only check for user restriction. Additional checks can be added here
842 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
843 oldUserId);
844 if (!disallowRunInBg) {
845 return;
846 }
847 synchronized (mService) {
848 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
849 + " and related users");
850 stopUsersLocked(oldUserId, false, null);
851 }
852 }
853
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700854 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
855 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800856 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700857 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
858 }
859 }
860
861 void dispatchUserSwitch(final UserState uss, final int oldUserId,
862 final int newUserId) {
863 final int observerCount = mUserSwitchObservers.beginBroadcast();
864 if (observerCount > 0) {
865 final IRemoteCallback callback = new IRemoteCallback.Stub() {
866 int mCount = 0;
867 @Override
868 public void sendResult(Bundle data) throws RemoteException {
869 synchronized (mService) {
870 if (mCurUserSwitchCallback == this) {
871 mCount++;
872 if (mCount == observerCount) {
873 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
874 }
875 }
876 }
877 }
878 };
879 synchronized (mService) {
880 uss.switching = true;
881 mCurUserSwitchCallback = callback;
882 }
883 for (int i = 0; i < observerCount; i++) {
884 try {
885 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
886 newUserId, callback);
887 } catch (RemoteException e) {
888 }
889 }
890 } else {
891 synchronized (mService) {
892 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
893 }
894 }
895 mUserSwitchObservers.finishBroadcast();
896 }
897
898 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
899 mCurUserSwitchCallback = null;
900 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
901 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
902 oldUserId, newUserId, uss));
903 }
904
905 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700906 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700907 }
908
909 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
910 synchronized (mService) {
911 if (foreground) {
912 moveUserToForegroundLocked(uss, oldUserId, newUserId);
913 }
914 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700915 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700916 }
917
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700918 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700919 boolean clearInitializing, boolean clearSwitching) {
920 boolean unfrozen = false;
921 synchronized (mService) {
922 if (clearInitializing) {
923 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700924 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700925 }
926 if (clearSwitching) {
927 uss.switching = false;
928 }
929 if (!uss.switching && !uss.initializing) {
930 mService.mWindowManager.stopFreezingScreen();
931 unfrozen = true;
932 }
933 }
934 if (unfrozen) {
935 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
936 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
937 newUserId, 0));
938 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100939 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700940 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700941 }
942
943 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
944 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
945 if (homeInFront) {
946 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
947 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800948 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700949 }
950 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700951 getUserManager().onUserForeground(newUserId);
952 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
953 }
954
955 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
956 long ident = Binder.clearCallingIdentity();
957 try {
958 Intent intent;
959 if (oldUserId >= 0) {
960 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
961 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
962 int count = profiles.size();
963 for (int i = 0; i < count; i++) {
964 int profileUserId = profiles.get(i).id;
965 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
966 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
967 | Intent.FLAG_RECEIVER_FOREGROUND);
968 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
969 mService.broadcastIntentLocked(null, null, intent,
970 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
971 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
972 }
973 }
974 if (newUserId >= 0) {
975 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
976 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
977 int count = profiles.size();
978 for (int i = 0; i < count; i++) {
979 int profileUserId = profiles.get(i).id;
980 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
981 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
982 | Intent.FLAG_RECEIVER_FOREGROUND);
983 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
984 mService.broadcastIntentLocked(null, null, intent,
985 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
986 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
987 }
988 intent = new Intent(Intent.ACTION_USER_SWITCHED);
989 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
990 | Intent.FLAG_RECEIVER_FOREGROUND);
991 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
992 mService.broadcastIntentLocked(null, null, intent,
993 null, null, 0, null, null,
994 new String[] {android.Manifest.permission.MANAGE_USERS},
995 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
996 UserHandle.USER_ALL);
997 }
998 } finally {
999 Binder.restoreCallingIdentity(ident);
1000 }
1001 }
1002
1003
1004 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1005 int allowMode, String name, String callerPackage) {
1006 final int callingUserId = UserHandle.getUserId(callingUid);
1007 if (callingUserId == userId) {
1008 return userId;
1009 }
1010
1011 // Note that we may be accessing mCurrentUserId outside of a lock...
1012 // shouldn't be a big deal, if this is being called outside
1013 // of a locked context there is intrinsically a race with
1014 // the value the caller will receive and someone else changing it.
1015 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1016 // we will switch to the calling user if access to the current user fails.
1017 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1018
1019 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1020 final boolean allow;
1021 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1022 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1023 // If the caller has this permission, they always pass go. And collect $200.
1024 allow = true;
1025 } else if (allowMode == ALLOW_FULL_ONLY) {
1026 // We require full access, sucks to be you.
1027 allow = false;
1028 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1029 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1030 // If the caller does not have either permission, they are always doomed.
1031 allow = false;
1032 } else if (allowMode == ALLOW_NON_FULL) {
1033 // We are blanket allowing non-full access, you lucky caller!
1034 allow = true;
1035 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1036 // We may or may not allow this depending on whether the two users are
1037 // in the same profile.
1038 allow = isSameProfileGroup(callingUserId, targetUserId);
1039 } else {
1040 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1041 }
1042 if (!allow) {
1043 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1044 // In this case, they would like to just execute as their
1045 // owner user instead of failing.
1046 targetUserId = callingUserId;
1047 } else {
1048 StringBuilder builder = new StringBuilder(128);
1049 builder.append("Permission Denial: ");
1050 builder.append(name);
1051 if (callerPackage != null) {
1052 builder.append(" from ");
1053 builder.append(callerPackage);
1054 }
1055 builder.append(" asks to run as user ");
1056 builder.append(userId);
1057 builder.append(" but is calling from user ");
1058 builder.append(UserHandle.getUserId(callingUid));
1059 builder.append("; this requires ");
1060 builder.append(INTERACT_ACROSS_USERS_FULL);
1061 if (allowMode != ALLOW_FULL_ONLY) {
1062 builder.append(" or ");
1063 builder.append(INTERACT_ACROSS_USERS);
1064 }
1065 String msg = builder.toString();
1066 Slog.w(TAG, msg);
1067 throw new SecurityException(msg);
1068 }
1069 }
1070 }
1071 if (!allowAll && targetUserId < 0) {
1072 throw new IllegalArgumentException(
1073 "Call does not support special user #" + targetUserId);
1074 }
1075 // Check shell permission
1076 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1077 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1078 throw new SecurityException("Shell does not have permission to access user "
1079 + targetUserId + "\n " + Debug.getCallers(3));
1080 }
1081 }
1082 return targetUserId;
1083 }
1084
1085 int unsafeConvertIncomingUserLocked(int userId) {
1086 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1087 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001088 }
1089
1090 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1091 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1092 != PackageManager.PERMISSION_GRANTED) {
1093 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1094 + Binder.getCallingPid()
1095 + ", uid=" + Binder.getCallingUid()
1096 + " requires " + INTERACT_ACROSS_USERS_FULL;
1097 Slog.w(TAG, msg);
1098 throw new SecurityException(msg);
1099 }
1100
1101 mUserSwitchObservers.register(observer);
1102 }
1103
1104 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1105 mUserSwitchObservers.unregister(observer);
1106 }
1107
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001108 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001109 return mStartedUsers.get(userId);
1110 }
1111
1112 boolean hasStartedUserState(int userId) {
1113 return mStartedUsers.get(userId) != null;
1114 }
1115
1116 private void updateStartedUserArrayLocked() {
1117 int num = 0;
1118 for (int i = 0; i < mStartedUsers.size(); i++) {
1119 UserState uss = mStartedUsers.valueAt(i);
1120 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001121 if (uss.state != UserState.STATE_STOPPING
1122 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001123 num++;
1124 }
1125 }
1126 mStartedUserArray = new int[num];
1127 num = 0;
1128 for (int i = 0; i < mStartedUsers.size(); i++) {
1129 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001130 if (uss.state != UserState.STATE_STOPPING
1131 && uss.state != UserState.STATE_SHUTDOWN) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -08001132 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001133 }
1134 }
1135 }
1136
1137 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1138 for (int i = 0; i < mStartedUsers.size(); i++) {
1139 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001140 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001141 }
1142 }
1143
1144 /**
1145 * Refreshes the list of users related to the current user when either a
1146 * user switch happens or when a new related user is started in the
1147 * background.
1148 */
1149 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001150 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001151 false /* enabledOnly */);
1152 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1153 for (int i = 0; i < currentProfileIds.length; i++) {
1154 currentProfileIds[i] = profiles.get(i).id;
1155 }
1156 mCurrentProfileIds = currentProfileIds;
1157
1158 synchronized (mUserProfileGroupIdsSelfLocked) {
1159 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001160 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001161 for (int i = 0; i < users.size(); i++) {
1162 UserInfo user = users.get(i);
1163 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1164 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1165 }
1166 }
1167 }
1168 }
1169
1170 int[] getStartedUserArrayLocked() {
1171 return mStartedUserArray;
1172 }
1173
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001174 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001175 UserState state = getStartedUserStateLocked(userId);
1176 if (state == null) {
1177 return false;
1178 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001179 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001180 return true;
1181 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001182
1183 final boolean unlocked;
1184 switch (state.state) {
1185 case UserState.STATE_STOPPING:
1186 case UserState.STATE_SHUTDOWN:
1187 default:
1188 return false;
1189
1190 case UserState.STATE_BOOTING:
1191 case UserState.STATE_RUNNING_LOCKED:
1192 unlocked = false;
1193 break;
1194
1195 case UserState.STATE_RUNNING:
1196 unlocked = true;
1197 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001198 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001199
1200 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1201 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001202 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001203 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1204 return unlocked;
1205 }
1206
1207 // One way or another, we're running!
1208 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001209 }
1210
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001211 UserInfo getCurrentUser() {
1212 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1213 != PackageManager.PERMISSION_GRANTED) && (
1214 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1215 != PackageManager.PERMISSION_GRANTED)) {
1216 String msg = "Permission Denial: getCurrentUser() from pid="
1217 + Binder.getCallingPid()
1218 + ", uid=" + Binder.getCallingUid()
1219 + " requires " + INTERACT_ACROSS_USERS;
1220 Slog.w(TAG, msg);
1221 throw new SecurityException(msg);
1222 }
1223 synchronized (mService) {
1224 return getCurrentUserLocked();
1225 }
1226 }
1227
1228 UserInfo getCurrentUserLocked() {
1229 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001230 return getUserInfo(userId);
1231 }
1232
1233 int getCurrentOrTargetUserIdLocked() {
1234 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001235 }
1236
1237 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001238 return mCurrentUserId;
1239 }
1240
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001241 private boolean isCurrentUserLocked(int userId) {
Amith Yamasani458ac462015-12-18 11:21:31 -08001242 return userId == getCurrentOrTargetUserIdLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001243 }
1244
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001245 int setTargetUserIdLocked(int targetUserId) {
1246 return mTargetUserId = targetUserId;
1247 }
1248
1249 int[] getUsers() {
1250 UserManagerService ums = getUserManager();
1251 return ums != null ? ums.getUserIds() : new int[] { 0 };
1252 }
1253
1254 UserInfo getUserInfo(int userId) {
1255 return getUserManager().getUserInfo(userId);
1256 }
1257
1258 int[] getUserIds() {
1259 return getUserManager().getUserIds();
1260 }
1261
1262 boolean exists(int userId) {
1263 return getUserManager().exists(userId);
1264 }
1265
1266 boolean hasUserRestriction(String restriction, int userId) {
1267 return getUserManager().hasUserRestriction(restriction, userId);
1268 }
1269
1270 Set<Integer> getProfileIds(int userId) {
1271 Set<Integer> userIds = new HashSet<>();
1272 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1273 false /* enabledOnly */);
1274 for (UserInfo user : profiles) {
1275 userIds.add(user.id);
1276 }
1277 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001278 }
1279
1280 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1281 synchronized (mUserProfileGroupIdsSelfLocked) {
1282 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1283 UserInfo.NO_PROFILE_GROUP_ID);
1284 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1285 UserInfo.NO_PROFILE_GROUP_ID);
1286 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1287 && callingProfile == targetProfile;
1288 }
1289 }
1290
1291 boolean isCurrentProfileLocked(int userId) {
1292 return ArrayUtils.contains(mCurrentProfileIds, userId);
1293 }
1294
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001295 int[] getCurrentProfileIdsLocked() {
1296 return mCurrentProfileIds;
1297 }
1298
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001299 /**
1300 * Returns whether the given user requires credential entry at this time. This is used to
1301 * intercept activity launches for work apps when the Work Challenge is present.
1302 */
1303 boolean shouldConfirmCredentials(int userId) {
Clara Bayarria1771112015-12-18 16:29:18 +00001304 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001305 return false;
1306 }
1307 final KeyguardManager km = (KeyguardManager) mService.mContext
1308 .getSystemService(KEYGUARD_SERVICE);
Clara Bayarria1771112015-12-18 16:29:18 +00001309 return km.isDeviceLocked(userId);
Clara Bayarriea9b10e2015-12-04 15:36:26 +00001310 }
1311
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001312 void dump(PrintWriter pw, boolean dumpAll) {
1313 pw.println(" mStartedUsers:");
1314 for (int i = 0; i < mStartedUsers.size(); i++) {
1315 UserState uss = mStartedUsers.valueAt(i);
1316 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1317 pw.print(": "); uss.dump("", pw);
1318 }
1319 pw.print(" mStartedUserArray: [");
1320 for (int i = 0; i < mStartedUserArray.length; i++) {
1321 if (i > 0) pw.print(", ");
1322 pw.print(mStartedUserArray[i]);
1323 }
1324 pw.println("]");
1325 pw.print(" mUserLru: [");
1326 for (int i = 0; i < mUserLru.size(); i++) {
1327 if (i > 0) pw.print(", ");
1328 pw.print(mUserLru.get(i));
1329 }
1330 pw.println("]");
1331 if (dumpAll) {
1332 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1333 }
1334 synchronized (mUserProfileGroupIdsSelfLocked) {
1335 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1336 pw.println(" mUserProfileGroupIds:");
1337 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1338 pw.print(" User #");
1339 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1340 pw.print(" -> profile #");
1341 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1342 }
1343 }
1344 }
1345 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001346}