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