blob: a0e084b7f36f6f0a407e00f5fc610aef9d99f540 [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
428 // Clean up all state and processes associated with the user.
429 // Kill all the processes for the user.
430 forceStopUserLocked(userId, "finish user");
431 }
432 }
433
434 for (int i = 0; i < callbacks.size(); i++) {
435 try {
436 if (stopped) callbacks.get(i).userStopped(userId);
437 else callbacks.get(i).userStopAborted(userId);
438 } catch (RemoteException e) {
439 }
440 }
441
442 if (stopped) {
443 mService.mSystemServiceManager.cleanupUser(userId);
444 synchronized (mService) {
445 mService.mStackSupervisor.removeUserLocked(userId);
446 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100447 // Remove the user if it is ephemeral.
448 if (getUserInfo(userId).isEphemeral()) {
449 mUserManager.removeUser(userId);
450 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700451 }
452 }
453
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700454 /**
455 * Determines the list of users that should be stopped together with the specified
456 * {@code userId}. The returned list includes {@code userId}.
457 */
458 private @NonNull int[] getUsersToStopLocked(int userId) {
459 int startedUsersSize = mStartedUsers.size();
460 IntArray userIds = new IntArray();
461 userIds.add(userId);
462 synchronized (mUserProfileGroupIdsSelfLocked) {
463 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
464 UserInfo.NO_PROFILE_GROUP_ID);
465 for (int i = 0; i < startedUsersSize; i++) {
466 UserState uss = mStartedUsers.valueAt(i);
467 int startedUserId = uss.mHandle.getIdentifier();
468 // Skip unrelated users (profileGroupId mismatch)
469 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
470 UserInfo.NO_PROFILE_GROUP_ID);
471 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
472 && (userGroupId == startedUserGroupId);
473 // userId has already been added
474 boolean sameUserId = startedUserId == userId;
475 if (!sameGroup || sameUserId) {
476 continue;
477 }
478 userIds.add(startedUserId);
479 }
480 }
481 return userIds.toArray();
482 }
483
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700484 private void forceStopUserLocked(int userId, String reason) {
485 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
486 userId, reason);
487 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
488 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
489 | Intent.FLAG_RECEIVER_FOREGROUND);
490 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
491 mService.broadcastIntentLocked(null, null, intent,
492 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700493 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700494 }
495
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700496 /**
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100497 * Stops the guest or ephemeral user if it has gone to the background.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700498 */
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100499 private void stopGuestOrEphemeralUserIfBackground() {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700500 synchronized (mService) {
501 final int num = mUserLru.size();
502 for (int i = 0; i < num; i++) {
503 Integer oldUserId = mUserLru.get(i);
504 UserState oldUss = mStartedUsers.get(oldUserId);
505 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700506 || oldUss.state == UserState.STATE_STOPPING
507 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700508 continue;
509 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700510 UserInfo userInfo = getUserInfo(oldUserId);
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100511 if (userInfo.isGuest() || userInfo.isEphemeral()) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700512 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700513 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700514 break;
515 }
516 }
517 }
518 }
519
520 void startProfilesLocked() {
521 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700522 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700523 mCurrentUserId, false /* enabledOnly */);
524 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
525 for (UserInfo user : profiles) {
526 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
527 && user.id != mCurrentUserId) {
528 profilesToStart.add(user);
529 }
530 }
531 final int profilesToStartSize = profilesToStart.size();
532 int i = 0;
533 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
534 startUser(profilesToStart.get(i).id, /* foreground= */ false);
535 }
536 if (i < profilesToStartSize) {
537 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
538 }
539 }
540
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700541 private UserManagerService getUserManager() {
542 UserManagerService userManager = mUserManager;
543 if (userManager == null) {
544 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
545 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
546 }
547 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700548 }
549
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700550 private IMountService getMountService() {
551 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
552 }
553
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700554 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700555 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800556 if (mountService != null) {
557 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700558 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800559 } catch (RemoteException e) {
560 throw e.rethrowAsRuntimeException();
561 }
562 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700563 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
564 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800565 }
566 }
567
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700568 boolean startUser(final int userId, final boolean foreground) {
569 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
570 != PackageManager.PERMISSION_GRANTED) {
571 String msg = "Permission Denial: switchUser() from pid="
572 + Binder.getCallingPid()
573 + ", uid=" + Binder.getCallingUid()
574 + " requires " + INTERACT_ACROSS_USERS_FULL;
575 Slog.w(TAG, msg);
576 throw new SecurityException(msg);
577 }
578
579 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
580
581 final long ident = Binder.clearCallingIdentity();
582 try {
583 synchronized (mService) {
584 final int oldUserId = mCurrentUserId;
585 if (oldUserId == userId) {
586 return true;
587 }
588
589 mService.mStackSupervisor.setLockTaskModeLocked(null,
590 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
591
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700592 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700593 if (userInfo == null) {
594 Slog.w(TAG, "No user info for user #" + userId);
595 return false;
596 }
597 if (foreground && userInfo.isManagedProfile()) {
598 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
599 return false;
600 }
601
602 if (foreground) {
603 mService.mWindowManager.startFreezingScreen(
604 R.anim.screen_user_exit, R.anim.screen_user_enter);
605 }
606
607 boolean needStart = false;
608
609 // If the user we are switching to is not currently started, then
610 // we need to start it now.
611 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700612 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700613 updateStartedUserArrayLocked();
614 needStart = true;
615 }
616
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800617 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700618 final Integer userIdInt = userId;
619 mUserLru.remove(userIdInt);
620 mUserLru.add(userIdInt);
621
622 if (foreground) {
623 mCurrentUserId = userId;
624 mService.updateUserConfigurationLocked();
625 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
626 updateCurrentProfileIdsLocked();
627 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
628 // Once the internal notion of the active user has switched, we lock the device
629 // with the option to show the user switcher on the keyguard.
630 mService.mWindowManager.lockNow(null);
631 } else {
632 final Integer currentUserIdInt = mCurrentUserId;
633 updateCurrentProfileIdsLocked();
634 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
635 mUserLru.remove(currentUserIdInt);
636 mUserLru.add(currentUserIdInt);
637 }
638
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700639 // Make sure user is in the started state. If it is currently
640 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700641 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700642 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
643 // so we can just fairly silently bring the user back from
644 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700645 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700646 updateStartedUserArrayLocked();
647 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700648 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700649 // This means ACTION_SHUTDOWN has been sent, so we will
650 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700651 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700652 updateStartedUserArrayLocked();
653 needStart = true;
654 }
655
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700656 if (uss.state == UserState.STATE_BOOTING) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -0700657 // Give user manager a chance to propagate user restrictions
658 // to other services and prepare app storage
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800659 getUserManager().onBeforeStartUser(userId);
660
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700661 // Booting up a new user, need to tell system services about it.
662 // Note that this is on the same handler as scheduling of broadcasts,
663 // which is important because it needs to go first.
664 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
665 }
666
667 if (foreground) {
668 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
669 oldUserId));
670 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
671 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
672 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
673 oldUserId, userId, uss));
674 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
675 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
676 }
677
678 if (needStart) {
679 // Send USER_STARTED broadcast
680 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
681 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
682 | Intent.FLAG_RECEIVER_FOREGROUND);
683 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
684 mService.broadcastIntentLocked(null, null, intent,
685 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700686 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700687 }
688
689 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
690 if (userId != UserHandle.USER_SYSTEM) {
691 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
692 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
693 mService.broadcastIntentLocked(null, null, intent, null,
694 new IIntentReceiver.Stub() {
695 public void performReceive(Intent intent, int resultCode,
696 String data, Bundle extras, boolean ordered,
697 boolean sticky, int sendingUser) {
698 onUserInitialized(uss, foreground, oldUserId, userId);
699 }
700 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700701 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700702 uss.initializing = true;
703 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700704 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700705 }
706 }
707
708 if (foreground) {
709 if (!uss.initializing) {
710 moveUserToForegroundLocked(uss, oldUserId, userId);
711 }
712 } else {
713 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
714 }
715
716 if (needStart) {
717 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
718 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
719 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
720 mService.broadcastIntentLocked(null, null, intent,
721 null, new IIntentReceiver.Stub() {
722 @Override
723 public void performReceive(Intent intent, int resultCode,
724 String data, Bundle extras, boolean ordered, boolean sticky,
725 int sendingUser) throws RemoteException {
726 }
727 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700728 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
729 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700730 }
731 }
732 } finally {
733 Binder.restoreCallingIdentity(ident);
734 }
735
736 return true;
737 }
738
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700739 /**
740 * Start user, if its not already running, and bring it to foreground.
741 */
742 boolean startUserInForeground(final int userId, Dialog dlg) {
743 boolean result = startUser(userId, /* foreground */ true);
744 dlg.dismiss();
745 return result;
746 }
747
Jeff Sharkeyba512352015-11-12 20:17:45 -0800748 boolean unlockUser(final int userId, byte[] token) {
749 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
750 != PackageManager.PERMISSION_GRANTED) {
751 String msg = "Permission Denial: unlockUser() from pid="
752 + Binder.getCallingPid()
753 + ", uid=" + Binder.getCallingUid()
754 + " requires " + INTERACT_ACROSS_USERS_FULL;
755 Slog.w(TAG, msg);
756 throw new SecurityException(msg);
757 }
758
Jeff Sharkey8924e872015-11-30 12:52:10 -0700759 final long binderToken = Binder.clearCallingIdentity();
760 try {
761 return unlockUserCleared(userId, token);
762 } finally {
763 Binder.restoreCallingIdentity(binderToken);
764 }
765 }
766
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700767 /**
768 * Attempt to unlock user without a credential token. This typically
769 * succeeds when the device doesn't have credential-encrypted storage, or
770 * when the the credential-encrypted storage isn't tied to a user-provided
771 * PIN or pattern.
772 */
773 boolean maybeUnlockUser(final int userId) {
774 // Try unlocking storage using empty token
775 return unlockUserCleared(userId, null);
776 }
777
Jeff Sharkey8924e872015-11-30 12:52:10 -0700778 boolean unlockUserCleared(final int userId, byte[] token) {
779 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700780 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700781 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700782 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700783 }
784
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700785 if (!isUserKeyUnlocked(userId)) {
786 final UserInfo userInfo = getUserInfo(userId);
787 final IMountService mountService = getMountService();
788 try {
789 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
790 } catch (RemoteException | RuntimeException e) {
791 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
792 return false;
793 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800794 }
795
796 synchronized (mService) {
797 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700798 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800799 }
800
801 return true;
802 }
803
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800804 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700805 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800806 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
807 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700808 d.show();
809 }
810
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700811 void dispatchForegroundProfileChanged(int userId) {
812 final int observerCount = mUserSwitchObservers.beginBroadcast();
813 for (int i = 0; i < observerCount; i++) {
814 try {
815 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
816 } catch (RemoteException e) {
817 // Ignore
818 }
819 }
820 mUserSwitchObservers.finishBroadcast();
821 }
822
823 /** Called on handler thread */
824 void dispatchUserSwitchComplete(int userId) {
825 final int observerCount = mUserSwitchObservers.beginBroadcast();
826 for (int i = 0; i < observerCount; i++) {
827 try {
828 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
829 } catch (RemoteException e) {
830 }
831 }
832 mUserSwitchObservers.finishBroadcast();
833 }
834
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700835 private void stopBackgroundUsersIfEnforced(int oldUserId) {
836 // Never stop system user
837 if (oldUserId == UserHandle.USER_SYSTEM) {
838 return;
839 }
840 // For now, only check for user restriction. Additional checks can be added here
841 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
842 oldUserId);
843 if (!disallowRunInBg) {
844 return;
845 }
846 synchronized (mService) {
847 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
848 + " and related users");
849 stopUsersLocked(oldUserId, false, null);
850 }
851 }
852
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700853 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
854 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800855 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700856 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
857 }
858 }
859
860 void dispatchUserSwitch(final UserState uss, final int oldUserId,
861 final int newUserId) {
862 final int observerCount = mUserSwitchObservers.beginBroadcast();
863 if (observerCount > 0) {
864 final IRemoteCallback callback = new IRemoteCallback.Stub() {
865 int mCount = 0;
866 @Override
867 public void sendResult(Bundle data) throws RemoteException {
868 synchronized (mService) {
869 if (mCurUserSwitchCallback == this) {
870 mCount++;
871 if (mCount == observerCount) {
872 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
873 }
874 }
875 }
876 }
877 };
878 synchronized (mService) {
879 uss.switching = true;
880 mCurUserSwitchCallback = callback;
881 }
882 for (int i = 0; i < observerCount; i++) {
883 try {
884 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
885 newUserId, callback);
886 } catch (RemoteException e) {
887 }
888 }
889 } else {
890 synchronized (mService) {
891 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
892 }
893 }
894 mUserSwitchObservers.finishBroadcast();
895 }
896
897 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
898 mCurUserSwitchCallback = null;
899 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
900 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
901 oldUserId, newUserId, uss));
902 }
903
904 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700905 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700906 }
907
908 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
909 synchronized (mService) {
910 if (foreground) {
911 moveUserToForegroundLocked(uss, oldUserId, newUserId);
912 }
913 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700914 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700915 }
916
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700917 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700918 boolean clearInitializing, boolean clearSwitching) {
919 boolean unfrozen = false;
920 synchronized (mService) {
921 if (clearInitializing) {
922 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700923 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700924 }
925 if (clearSwitching) {
926 uss.switching = false;
927 }
928 if (!uss.switching && !uss.initializing) {
929 mService.mWindowManager.stopFreezingScreen();
930 unfrozen = true;
931 }
932 }
933 if (unfrozen) {
934 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
935 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
936 newUserId, 0));
937 }
Lenka Trochtovab4484ba2015-12-16 12:32:31 +0100938 stopGuestOrEphemeralUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700939 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700940 }
941
942 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
943 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
944 if (homeInFront) {
945 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
946 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800947 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700948 }
949 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700950 getUserManager().onUserForeground(newUserId);
951 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
952 }
953
954 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
955 long ident = Binder.clearCallingIdentity();
956 try {
957 Intent intent;
958 if (oldUserId >= 0) {
959 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
960 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
961 int count = profiles.size();
962 for (int i = 0; i < count; i++) {
963 int profileUserId = profiles.get(i).id;
964 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
965 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
966 | Intent.FLAG_RECEIVER_FOREGROUND);
967 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
968 mService.broadcastIntentLocked(null, null, intent,
969 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
970 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
971 }
972 }
973 if (newUserId >= 0) {
974 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
975 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
976 int count = profiles.size();
977 for (int i = 0; i < count; i++) {
978 int profileUserId = profiles.get(i).id;
979 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
980 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
981 | Intent.FLAG_RECEIVER_FOREGROUND);
982 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
983 mService.broadcastIntentLocked(null, null, intent,
984 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
985 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
986 }
987 intent = new Intent(Intent.ACTION_USER_SWITCHED);
988 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
989 | Intent.FLAG_RECEIVER_FOREGROUND);
990 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
991 mService.broadcastIntentLocked(null, null, intent,
992 null, null, 0, null, null,
993 new String[] {android.Manifest.permission.MANAGE_USERS},
994 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
995 UserHandle.USER_ALL);
996 }
997 } finally {
998 Binder.restoreCallingIdentity(ident);
999 }
1000 }
1001
1002
1003 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1004 int allowMode, String name, String callerPackage) {
1005 final int callingUserId = UserHandle.getUserId(callingUid);
1006 if (callingUserId == userId) {
1007 return userId;
1008 }
1009
1010 // Note that we may be accessing mCurrentUserId outside of a lock...
1011 // shouldn't be a big deal, if this is being called outside
1012 // of a locked context there is intrinsically a race with
1013 // the value the caller will receive and someone else changing it.
1014 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1015 // we will switch to the calling user if access to the current user fails.
1016 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1017
1018 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1019 final boolean allow;
1020 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1021 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1022 // If the caller has this permission, they always pass go. And collect $200.
1023 allow = true;
1024 } else if (allowMode == ALLOW_FULL_ONLY) {
1025 // We require full access, sucks to be you.
1026 allow = false;
1027 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1028 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1029 // If the caller does not have either permission, they are always doomed.
1030 allow = false;
1031 } else if (allowMode == ALLOW_NON_FULL) {
1032 // We are blanket allowing non-full access, you lucky caller!
1033 allow = true;
1034 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1035 // We may or may not allow this depending on whether the two users are
1036 // in the same profile.
1037 allow = isSameProfileGroup(callingUserId, targetUserId);
1038 } else {
1039 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1040 }
1041 if (!allow) {
1042 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1043 // In this case, they would like to just execute as their
1044 // owner user instead of failing.
1045 targetUserId = callingUserId;
1046 } else {
1047 StringBuilder builder = new StringBuilder(128);
1048 builder.append("Permission Denial: ");
1049 builder.append(name);
1050 if (callerPackage != null) {
1051 builder.append(" from ");
1052 builder.append(callerPackage);
1053 }
1054 builder.append(" asks to run as user ");
1055 builder.append(userId);
1056 builder.append(" but is calling from user ");
1057 builder.append(UserHandle.getUserId(callingUid));
1058 builder.append("; this requires ");
1059 builder.append(INTERACT_ACROSS_USERS_FULL);
1060 if (allowMode != ALLOW_FULL_ONLY) {
1061 builder.append(" or ");
1062 builder.append(INTERACT_ACROSS_USERS);
1063 }
1064 String msg = builder.toString();
1065 Slog.w(TAG, msg);
1066 throw new SecurityException(msg);
1067 }
1068 }
1069 }
1070 if (!allowAll && targetUserId < 0) {
1071 throw new IllegalArgumentException(
1072 "Call does not support special user #" + targetUserId);
1073 }
1074 // Check shell permission
1075 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1076 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1077 throw new SecurityException("Shell does not have permission to access user "
1078 + targetUserId + "\n " + Debug.getCallers(3));
1079 }
1080 }
1081 return targetUserId;
1082 }
1083
1084 int unsafeConvertIncomingUserLocked(int userId) {
1085 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1086 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001087 }
1088
1089 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1090 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1091 != PackageManager.PERMISSION_GRANTED) {
1092 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1093 + Binder.getCallingPid()
1094 + ", uid=" + Binder.getCallingUid()
1095 + " requires " + INTERACT_ACROSS_USERS_FULL;
1096 Slog.w(TAG, msg);
1097 throw new SecurityException(msg);
1098 }
1099
1100 mUserSwitchObservers.register(observer);
1101 }
1102
1103 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1104 mUserSwitchObservers.unregister(observer);
1105 }
1106
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001107 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001108 return mStartedUsers.get(userId);
1109 }
1110
1111 boolean hasStartedUserState(int userId) {
1112 return mStartedUsers.get(userId) != null;
1113 }
1114
1115 private void updateStartedUserArrayLocked() {
1116 int num = 0;
1117 for (int i = 0; i < mStartedUsers.size(); i++) {
1118 UserState uss = mStartedUsers.valueAt(i);
1119 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001120 if (uss.state != UserState.STATE_STOPPING
1121 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001122 num++;
1123 }
1124 }
1125 mStartedUserArray = new int[num];
1126 num = 0;
1127 for (int i = 0; i < mStartedUsers.size(); i++) {
1128 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001129 if (uss.state != UserState.STATE_STOPPING
1130 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001131 mStartedUserArray[num] = mStartedUsers.keyAt(i);
1132 num++;
1133 }
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}