blob: e49bc3c6c3c36aeaf01c74587fdceea14147b733 [file] [log] [blame]
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.am;
18
19import static android.Manifest.permission.INTERACT_ACROSS_USERS;
20import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070021import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
22import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070023import static android.app.ActivityManager.USER_OP_IS_CURRENT;
24import static android.app.ActivityManager.USER_OP_SUCCESS;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070025import static android.os.Process.SYSTEM_UID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070026import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
27import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
28import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070029import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
30import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
31import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
32import static com.android.server.am.ActivityManagerService.MY_PID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070033import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
34import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
35import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
36import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -070037import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070038import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
39
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070040import android.annotation.NonNull;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070041import android.app.ActivityManager;
42import android.app.AppOpsManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070043import android.app.Dialog;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070044import android.app.IStopUserCallback;
45import android.app.IUserSwitchObserver;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070046import android.content.Context;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070047import android.content.IIntentReceiver;
48import android.content.Intent;
49import android.content.pm.PackageManager;
50import android.content.pm.UserInfo;
51import android.os.BatteryStats;
52import android.os.Binder;
53import android.os.Bundle;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070054import android.os.Debug;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070055import android.os.Handler;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070056import android.os.IBinder;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070057import android.os.IRemoteCallback;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070058import android.os.IUserManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070059import android.os.Process;
60import android.os.RemoteCallbackList;
61import android.os.RemoteException;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070062import android.os.ServiceManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070063import android.os.UserHandle;
64import android.os.UserManager;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080065import android.os.storage.IMountService;
66import android.os.storage.StorageManager;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -070067import android.util.IntArray;
Suprabh Shukla4fe508b2015-11-20 18:22:57 -080068import android.util.Pair;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070069import android.util.Slog;
70import android.util.SparseArray;
71import android.util.SparseIntArray;
72
73import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080074import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070075import com.android.internal.util.ArrayUtils;
76import com.android.server.pm.UserManagerService;
77
78import java.io.PrintWriter;
79import java.util.ArrayList;
80import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070081import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070082import java.util.List;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070083import java.util.Set;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070084
85/**
86 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
87 */
88final class UserController {
89 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
90 // Maximum number of users we allow to be running at a time.
91 static final int MAX_RUNNING_USERS = 3;
92
93 // Amount of time we wait for observers to handle a user switch before
94 // giving up on them and unfreezing the screen.
95 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
96
97 private final ActivityManagerService mService;
98 private final Handler mHandler;
99
100 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700101 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700102 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700103 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700104
105 /**
106 * Which users have been started, so are allowed to run code.
107 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800108 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700109 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800110
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700111 /**
112 * LRU list of history of current users. Most recently current is at the end.
113 */
114 private final ArrayList<Integer> mUserLru = new ArrayList<>();
115
116 /**
117 * Constant array of the users that are currently started.
118 */
119 private int[] mStartedUserArray = new int[] { 0 };
120
121 // If there are multiple profiles for the current user, their ids are here
122 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700123 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700124
125 /**
126 * Mapping from each known user ID to the profile group ID it is associated with.
127 */
128 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
129
130 /**
131 * Registered observers of the user switching mechanics.
132 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700133 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700134 = new RemoteCallbackList<>();
135
136 /**
137 * Currently active user switch.
138 */
139 Object mCurUserSwitchCallback;
140
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700141 private volatile UserManagerService mUserManager;
142
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700143 UserController(ActivityManagerService service) {
144 mService = service;
145 mHandler = mService.mHandler;
146 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800147 final UserState uss = new UserState(UserHandle.SYSTEM);
148 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700149 mUserLru.add(UserHandle.USER_SYSTEM);
150 updateStartedUserArrayLocked();
151 }
152
153 void finishUserSwitch(UserState uss) {
154 synchronized (mService) {
155 finishUserBoot(uss);
156
157 startProfilesLocked();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700158 stopRunningUsersLocked(MAX_RUNNING_USERS);
159 }
160 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700161
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700162 void stopRunningUsersLocked(int maxRunningUsers) {
163 int num = mUserLru.size();
164 int i = 0;
165 while (num > maxRunningUsers && i < mUserLru.size()) {
166 Integer oldUserId = mUserLru.get(i);
167 UserState oldUss = mStartedUsers.get(oldUserId);
168 if (oldUss == null) {
169 // Shouldn't happen, but be sane if it does.
170 mUserLru.remove(i);
171 num--;
172 continue;
173 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700174 if (oldUss.state == UserState.STATE_STOPPING
175 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700176 // This user is already stopping, doesn't count.
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700177 num--;
178 i++;
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700179 continue;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700180 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700181 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
182 // Owner/System user and current user can't be stopped. We count it as running
183 // when it is not a pure system user.
184 if (UserInfo.isSystemOnly(oldUserId)) {
185 num--;
186 }
187 i++;
188 continue;
189 }
190 // This is a user to be stopped.
191 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
192 num--;
193 }
194 num--;
195 i++;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700196 }
197 }
198
199 void finishUserBoot(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700200 finishUserBoot(uss, null);
201 }
202
203 void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
204 final int userId = uss.mHandle.getIdentifier();
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700205 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700206 // Bail if we ended up with a stale user
207 if (mStartedUsers.get(userId) != uss) return;
208
209 // We always walk through all the user lifecycle states to send
210 // consistent developer events. We step into RUNNING_LOCKED here,
211 // but we might immediately step into RUNNING below if the user
212 // storage is already unlocked.
213 if (uss.state == UserState.STATE_BOOTING) {
214 uss.setState(UserState.STATE_RUNNING_LOCKED);
215
216 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700217 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
218 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700219 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
220 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
221 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
222 }
223
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700224 maybeUnlockUser(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700225 }
226 }
227
228 /**
229 * Consider stepping from {@link UserState#STATE_RUNNING_LOCKED} into
230 * {@link UserState#STATE_RUNNING}, which only occurs if the user storage is
231 * actually unlocked.
232 */
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700233 void finishUserUnlock(UserState uss) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700234 final int userId = uss.mHandle.getIdentifier();
235 synchronized (mService) {
236 // Bail if we ended up with a stale user
237 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
238
239 // Only keep marching forward if user is actually unlocked
240 if (!isUserKeyUnlocked(userId)) return;
241
242 if (uss.state == UserState.STATE_RUNNING_LOCKED) {
243 uss.setState(UserState.STATE_RUNNING);
244
245 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0));
246
247 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -0700248 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700249 unlockedIntent.addFlags(
250 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
251 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
252 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
253 userId);
254
255 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
256 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -0800257 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
258 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700259 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
260 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700261 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700262 }
263 }
264 }
265
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700266 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700267 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
268 != PackageManager.PERMISSION_GRANTED) {
269 String msg = "Permission Denial: switchUser() from pid="
270 + Binder.getCallingPid()
271 + ", uid=" + Binder.getCallingUid()
272 + " requires " + INTERACT_ACROSS_USERS_FULL;
273 Slog.w(TAG, msg);
274 throw new SecurityException(msg);
275 }
276 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
277 throw new IllegalArgumentException("Can't stop system user " + userId);
278 }
279 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
280 userId);
281 synchronized (mService) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700282 return stopUsersLocked(userId, force, callback);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700283 }
284 }
285
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700286 /**
287 * Stops the user along with its related users. The method calls
288 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
289 */
290 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
291 if (userId == UserHandle.USER_SYSTEM) {
292 return USER_OP_ERROR_IS_SYSTEM;
293 }
294 if (isCurrentUserLocked(userId)) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700295 return USER_OP_IS_CURRENT;
296 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700297 int[] usersToStop = getUsersToStopLocked(userId);
298 // If one of related users is system or current, no related users should be stopped
299 for (int i = 0; i < usersToStop.length; i++) {
300 int relatedUserId = usersToStop[i];
301 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
302 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
303 + relatedUserId);
304 // We still need to stop the requested user if it's a force stop.
305 if (force) {
306 stopSingleUserLocked(userId, callback);
307 }
308 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
309 }
310 }
311 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
312 for (int userIdToStop : usersToStop) {
313 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
314 }
315 return USER_OP_SUCCESS;
316 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700317
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700318 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
319 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700320 final UserState uss = mStartedUsers.get(userId);
321 if (uss == null) {
322 // User is not started, nothing to do... but we do need to
323 // callback if requested.
324 if (callback != null) {
325 mHandler.post(new Runnable() {
326 @Override
327 public void run() {
328 try {
329 callback.userStopped(userId);
330 } catch (RemoteException e) {
331 }
332 }
333 });
334 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700335 return;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700336 }
337
338 if (callback != null) {
339 uss.mStopCallbacks.add(callback);
340 }
341
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700342 if (uss.state != UserState.STATE_STOPPING
343 && uss.state != UserState.STATE_SHUTDOWN) {
344 uss.setState(UserState.STATE_STOPPING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700345 updateStartedUserArrayLocked();
346
347 long ident = Binder.clearCallingIdentity();
348 try {
349 // We are going to broadcast ACTION_USER_STOPPING and then
350 // once that is done send a final ACTION_SHUTDOWN and then
351 // stop the user.
352 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
353 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
354 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
355 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
356 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
357 // This is the result receiver for the final shutdown broadcast.
358 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
359 @Override
360 public void performReceive(Intent intent, int resultCode, String data,
361 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
362 finishUserStop(uss);
363 }
364 };
365 // This is the result receiver for the initial stopping broadcast.
366 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
367 @Override
368 public void performReceive(Intent intent, int resultCode, String data,
369 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
370 // On to the next.
371 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700372 if (uss.state != UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700373 // Whoops, we are being started back up. Abort, abort!
374 return;
375 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700376 uss.setState(UserState.STATE_SHUTDOWN);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700377 }
378 mService.mBatteryStatsService.noteEvent(
379 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
380 Integer.toString(userId), userId);
381 mService.mSystemServiceManager.stopUser(userId);
382 mService.broadcastIntentLocked(null, null, shutdownIntent,
383 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700384 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700385 }
386 };
387 // Kick things off.
388 mService.broadcastIntentLocked(null, null, stoppingIntent,
389 null, stoppingReceiver, 0, null, null,
390 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700391 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700392 } finally {
393 Binder.restoreCallingIdentity(ident);
394 }
395 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700396 }
397
398 void finishUserStop(UserState uss) {
399 final int userId = uss.mHandle.getIdentifier();
400 boolean stopped;
401 ArrayList<IStopUserCallback> callbacks;
402 synchronized (mService) {
403 callbacks = new ArrayList<>(uss.mStopCallbacks);
404 if (mStartedUsers.get(userId) != uss) {
405 stopped = false;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700406 } else if (uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700407 stopped = false;
408 } else {
409 stopped = true;
410 // User can no longer run.
411 mStartedUsers.remove(userId);
412 mUserLru.remove(Integer.valueOf(userId));
413 updateStartedUserArrayLocked();
414
415 // Clean up all state and processes associated with the user.
416 // Kill all the processes for the user.
417 forceStopUserLocked(userId, "finish user");
418 }
419 }
420
421 for (int i = 0; i < callbacks.size(); i++) {
422 try {
423 if (stopped) callbacks.get(i).userStopped(userId);
424 else callbacks.get(i).userStopAborted(userId);
425 } catch (RemoteException e) {
426 }
427 }
428
429 if (stopped) {
430 mService.mSystemServiceManager.cleanupUser(userId);
431 synchronized (mService) {
432 mService.mStackSupervisor.removeUserLocked(userId);
433 }
434 }
435 }
436
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700437 /**
438 * Determines the list of users that should be stopped together with the specified
439 * {@code userId}. The returned list includes {@code userId}.
440 */
441 private @NonNull int[] getUsersToStopLocked(int userId) {
442 int startedUsersSize = mStartedUsers.size();
443 IntArray userIds = new IntArray();
444 userIds.add(userId);
445 synchronized (mUserProfileGroupIdsSelfLocked) {
446 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
447 UserInfo.NO_PROFILE_GROUP_ID);
448 for (int i = 0; i < startedUsersSize; i++) {
449 UserState uss = mStartedUsers.valueAt(i);
450 int startedUserId = uss.mHandle.getIdentifier();
451 // Skip unrelated users (profileGroupId mismatch)
452 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
453 UserInfo.NO_PROFILE_GROUP_ID);
454 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
455 && (userGroupId == startedUserGroupId);
456 // userId has already been added
457 boolean sameUserId = startedUserId == userId;
458 if (!sameGroup || sameUserId) {
459 continue;
460 }
461 userIds.add(startedUserId);
462 }
463 }
464 return userIds.toArray();
465 }
466
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700467 private void forceStopUserLocked(int userId, String reason) {
468 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
469 userId, reason);
470 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
471 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
472 | Intent.FLAG_RECEIVER_FOREGROUND);
473 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
474 mService.broadcastIntentLocked(null, null, intent,
475 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700476 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700477 }
478
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700479 /**
480 * Stops the guest user if it has gone to the background.
481 */
482 private void stopGuestUserIfBackground() {
483 synchronized (mService) {
484 final int num = mUserLru.size();
485 for (int i = 0; i < num; i++) {
486 Integer oldUserId = mUserLru.get(i);
487 UserState oldUss = mStartedUsers.get(oldUserId);
488 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700489 || oldUss.state == UserState.STATE_STOPPING
490 || oldUss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700491 continue;
492 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700493 UserInfo userInfo = getUserInfo(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700494 if (userInfo.isGuest()) {
495 // This is a user to be stopped.
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700496 stopUsersLocked(oldUserId, true, null);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700497 break;
498 }
499 }
500 }
501 }
502
503 void startProfilesLocked() {
504 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700505 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700506 mCurrentUserId, false /* enabledOnly */);
507 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
508 for (UserInfo user : profiles) {
509 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
510 && user.id != mCurrentUserId) {
511 profilesToStart.add(user);
512 }
513 }
514 final int profilesToStartSize = profilesToStart.size();
515 int i = 0;
516 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
517 startUser(profilesToStart.get(i).id, /* foreground= */ false);
518 }
519 if (i < profilesToStartSize) {
520 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
521 }
522 }
523
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700524 private UserManagerService getUserManager() {
525 UserManagerService userManager = mUserManager;
526 if (userManager == null) {
527 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
528 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
529 }
530 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700531 }
532
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700533 private IMountService getMountService() {
534 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
535 }
536
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700537 private boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700538 final IMountService mountService = getMountService();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800539 if (mountService != null) {
540 try {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700541 return mountService.isUserKeyUnlocked(userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800542 } catch (RemoteException e) {
543 throw e.rethrowAsRuntimeException();
544 }
545 } else {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700546 Slog.w(TAG, "Mount service not published; guessing locked state based on property");
547 return !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800548 }
549 }
550
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700551 boolean startUser(final int userId, final boolean foreground) {
552 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
553 != PackageManager.PERMISSION_GRANTED) {
554 String msg = "Permission Denial: switchUser() from pid="
555 + Binder.getCallingPid()
556 + ", uid=" + Binder.getCallingUid()
557 + " requires " + INTERACT_ACROSS_USERS_FULL;
558 Slog.w(TAG, msg);
559 throw new SecurityException(msg);
560 }
561
562 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
563
564 final long ident = Binder.clearCallingIdentity();
565 try {
566 synchronized (mService) {
567 final int oldUserId = mCurrentUserId;
568 if (oldUserId == userId) {
569 return true;
570 }
571
572 mService.mStackSupervisor.setLockTaskModeLocked(null,
573 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
574
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700575 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700576 if (userInfo == null) {
577 Slog.w(TAG, "No user info for user #" + userId);
578 return false;
579 }
580 if (foreground && userInfo.isManagedProfile()) {
581 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
582 return false;
583 }
584
585 if (foreground) {
586 mService.mWindowManager.startFreezingScreen(
587 R.anim.screen_user_exit, R.anim.screen_user_enter);
588 }
589
590 boolean needStart = false;
591
592 // If the user we are switching to is not currently started, then
593 // we need to start it now.
594 if (mStartedUsers.get(userId) == null) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700595 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700596 updateStartedUserArrayLocked();
597 needStart = true;
598 }
599
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800600 final UserState uss = mStartedUsers.get(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700601 final Integer userIdInt = userId;
602 mUserLru.remove(userIdInt);
603 mUserLru.add(userIdInt);
604
605 if (foreground) {
606 mCurrentUserId = userId;
607 mService.updateUserConfigurationLocked();
608 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
609 updateCurrentProfileIdsLocked();
610 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
611 // Once the internal notion of the active user has switched, we lock the device
612 // with the option to show the user switcher on the keyguard.
613 mService.mWindowManager.lockNow(null);
614 } else {
615 final Integer currentUserIdInt = mCurrentUserId;
616 updateCurrentProfileIdsLocked();
617 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
618 mUserLru.remove(currentUserIdInt);
619 mUserLru.add(currentUserIdInt);
620 }
621
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700622 // Make sure user is in the started state. If it is currently
623 // stopping, we need to knock that off.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700624 if (uss.state == UserState.STATE_STOPPING) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700625 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
626 // so we can just fairly silently bring the user back from
627 // the almost-dead.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700628 uss.setState(uss.lastState);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700629 updateStartedUserArrayLocked();
630 needStart = true;
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700631 } else if (uss.state == UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700632 // This means ACTION_SHUTDOWN has been sent, so we will
633 // need to treat this as a new boot of the user.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700634 uss.setState(UserState.STATE_BOOTING);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700635 updateStartedUserArrayLocked();
636 needStart = true;
637 }
638
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700639 if (uss.state == UserState.STATE_BOOTING) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800640 // Let user manager propagate user restrictions to other services.
641 getUserManager().onBeforeStartUser(userId);
642
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700643 // Booting up a new user, need to tell system services about it.
644 // Note that this is on the same handler as scheduling of broadcasts,
645 // which is important because it needs to go first.
646 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
647 }
648
649 if (foreground) {
650 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
651 oldUserId));
652 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
653 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
654 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
655 oldUserId, userId, uss));
656 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
657 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
658 }
659
660 if (needStart) {
661 // Send USER_STARTED broadcast
662 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
663 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
664 | Intent.FLAG_RECEIVER_FOREGROUND);
665 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
666 mService.broadcastIntentLocked(null, null, intent,
667 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700668 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700669 }
670
671 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
672 if (userId != UserHandle.USER_SYSTEM) {
673 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
674 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
675 mService.broadcastIntentLocked(null, null, intent, null,
676 new IIntentReceiver.Stub() {
677 public void performReceive(Intent intent, int resultCode,
678 String data, Bundle extras, boolean ordered,
679 boolean sticky, int sendingUser) {
680 onUserInitialized(uss, foreground, oldUserId, userId);
681 }
682 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700683 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700684 uss.initializing = true;
685 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700686 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700687 }
688 }
689
690 if (foreground) {
691 if (!uss.initializing) {
692 moveUserToForegroundLocked(uss, oldUserId, userId);
693 }
694 } else {
695 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
696 }
697
698 if (needStart) {
699 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
700 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
701 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
702 mService.broadcastIntentLocked(null, null, intent,
703 null, new IIntentReceiver.Stub() {
704 @Override
705 public void performReceive(Intent intent, int resultCode,
706 String data, Bundle extras, boolean ordered, boolean sticky,
707 int sendingUser) throws RemoteException {
708 }
709 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700710 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
711 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700712 }
713 }
714 } finally {
715 Binder.restoreCallingIdentity(ident);
716 }
717
718 return true;
719 }
720
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700721 /**
722 * Start user, if its not already running, and bring it to foreground.
723 */
724 boolean startUserInForeground(final int userId, Dialog dlg) {
725 boolean result = startUser(userId, /* foreground */ true);
726 dlg.dismiss();
727 return result;
728 }
729
Jeff Sharkeyba512352015-11-12 20:17:45 -0800730 boolean unlockUser(final int userId, byte[] token) {
731 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
732 != PackageManager.PERMISSION_GRANTED) {
733 String msg = "Permission Denial: unlockUser() from pid="
734 + Binder.getCallingPid()
735 + ", uid=" + Binder.getCallingUid()
736 + " requires " + INTERACT_ACROSS_USERS_FULL;
737 Slog.w(TAG, msg);
738 throw new SecurityException(msg);
739 }
740
Jeff Sharkey8924e872015-11-30 12:52:10 -0700741 final long binderToken = Binder.clearCallingIdentity();
742 try {
743 return unlockUserCleared(userId, token);
744 } finally {
745 Binder.restoreCallingIdentity(binderToken);
746 }
747 }
748
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700749 /**
750 * Attempt to unlock user without a credential token. This typically
751 * succeeds when the device doesn't have credential-encrypted storage, or
752 * when the the credential-encrypted storage isn't tied to a user-provided
753 * PIN or pattern.
754 */
755 boolean maybeUnlockUser(final int userId) {
756 // Try unlocking storage using empty token
757 return unlockUserCleared(userId, null);
758 }
759
Jeff Sharkey8924e872015-11-30 12:52:10 -0700760 boolean unlockUserCleared(final int userId, byte[] token) {
761 synchronized (mService) {
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700762 // Bail if already running unlocked
Jeff Sharkey8924e872015-11-30 12:52:10 -0700763 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -0700764 if (uss.state == UserState.STATE_RUNNING) return true;
Jeff Sharkey8924e872015-11-30 12:52:10 -0700765 }
766
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700767 if (!isUserKeyUnlocked(userId)) {
768 final UserInfo userInfo = getUserInfo(userId);
769 final IMountService mountService = getMountService();
770 try {
771 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
772 } catch (RemoteException | RuntimeException e) {
773 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
774 return false;
775 }
Jeff Sharkeyba512352015-11-12 20:17:45 -0800776 }
777
778 synchronized (mService) {
779 final UserState uss = mStartedUsers.get(userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700780 finishUserUnlock(uss);
Jeff Sharkeyba512352015-11-12 20:17:45 -0800781 }
782
783 return true;
784 }
785
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800786 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700787 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800788 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
789 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700790 d.show();
791 }
792
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700793 void dispatchForegroundProfileChanged(int userId) {
794 final int observerCount = mUserSwitchObservers.beginBroadcast();
795 for (int i = 0; i < observerCount; i++) {
796 try {
797 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
798 } catch (RemoteException e) {
799 // Ignore
800 }
801 }
802 mUserSwitchObservers.finishBroadcast();
803 }
804
805 /** Called on handler thread */
806 void dispatchUserSwitchComplete(int userId) {
807 final int observerCount = mUserSwitchObservers.beginBroadcast();
808 for (int i = 0; i < observerCount; i++) {
809 try {
810 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
811 } catch (RemoteException e) {
812 }
813 }
814 mUserSwitchObservers.finishBroadcast();
815 }
816
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700817 private void stopBackgroundUsersIfEnforced(int oldUserId) {
818 // Never stop system user
819 if (oldUserId == UserHandle.USER_SYSTEM) {
820 return;
821 }
822 // For now, only check for user restriction. Additional checks can be added here
823 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
824 oldUserId);
825 if (!disallowRunInBg) {
826 return;
827 }
828 synchronized (mService) {
829 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
830 + " and related users");
831 stopUsersLocked(oldUserId, false, null);
832 }
833 }
834
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700835 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
836 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800837 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700838 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
839 }
840 }
841
842 void dispatchUserSwitch(final UserState uss, final int oldUserId,
843 final int newUserId) {
844 final int observerCount = mUserSwitchObservers.beginBroadcast();
845 if (observerCount > 0) {
846 final IRemoteCallback callback = new IRemoteCallback.Stub() {
847 int mCount = 0;
848 @Override
849 public void sendResult(Bundle data) throws RemoteException {
850 synchronized (mService) {
851 if (mCurUserSwitchCallback == this) {
852 mCount++;
853 if (mCount == observerCount) {
854 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
855 }
856 }
857 }
858 }
859 };
860 synchronized (mService) {
861 uss.switching = true;
862 mCurUserSwitchCallback = callback;
863 }
864 for (int i = 0; i < observerCount; i++) {
865 try {
866 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
867 newUserId, callback);
868 } catch (RemoteException e) {
869 }
870 }
871 } else {
872 synchronized (mService) {
873 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
874 }
875 }
876 mUserSwitchObservers.finishBroadcast();
877 }
878
879 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
880 mCurUserSwitchCallback = null;
881 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
882 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
883 oldUserId, newUserId, uss));
884 }
885
886 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700887 completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700888 }
889
890 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
891 synchronized (mService) {
892 if (foreground) {
893 moveUserToForegroundLocked(uss, oldUserId, newUserId);
894 }
895 }
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700896 completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700897 }
898
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700899 void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700900 boolean clearInitializing, boolean clearSwitching) {
901 boolean unfrozen = false;
902 synchronized (mService) {
903 if (clearInitializing) {
904 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700905 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700906 }
907 if (clearSwitching) {
908 uss.switching = false;
909 }
910 if (!uss.switching && !uss.initializing) {
911 mService.mWindowManager.stopFreezingScreen();
912 unfrozen = true;
913 }
914 }
915 if (unfrozen) {
916 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
917 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
918 newUserId, 0));
919 }
920 stopGuestUserIfBackground();
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700921 stopBackgroundUsersIfEnforced(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700922 }
923
924 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
925 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
926 if (homeInFront) {
927 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
928 } else {
929 mService.mStackSupervisor.resumeTopActivitiesLocked();
930 }
931 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700932 getUserManager().onUserForeground(newUserId);
933 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
934 }
935
936 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
937 long ident = Binder.clearCallingIdentity();
938 try {
939 Intent intent;
940 if (oldUserId >= 0) {
941 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
942 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
943 int count = profiles.size();
944 for (int i = 0; i < count; i++) {
945 int profileUserId = profiles.get(i).id;
946 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
947 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
948 | Intent.FLAG_RECEIVER_FOREGROUND);
949 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
950 mService.broadcastIntentLocked(null, null, intent,
951 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
952 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
953 }
954 }
955 if (newUserId >= 0) {
956 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
957 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
958 int count = profiles.size();
959 for (int i = 0; i < count; i++) {
960 int profileUserId = profiles.get(i).id;
961 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
962 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
963 | Intent.FLAG_RECEIVER_FOREGROUND);
964 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
965 mService.broadcastIntentLocked(null, null, intent,
966 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
967 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
968 }
969 intent = new Intent(Intent.ACTION_USER_SWITCHED);
970 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
971 | Intent.FLAG_RECEIVER_FOREGROUND);
972 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
973 mService.broadcastIntentLocked(null, null, intent,
974 null, null, 0, null, null,
975 new String[] {android.Manifest.permission.MANAGE_USERS},
976 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
977 UserHandle.USER_ALL);
978 }
979 } finally {
980 Binder.restoreCallingIdentity(ident);
981 }
982 }
983
984
985 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
986 int allowMode, String name, String callerPackage) {
987 final int callingUserId = UserHandle.getUserId(callingUid);
988 if (callingUserId == userId) {
989 return userId;
990 }
991
992 // Note that we may be accessing mCurrentUserId outside of a lock...
993 // shouldn't be a big deal, if this is being called outside
994 // of a locked context there is intrinsically a race with
995 // the value the caller will receive and someone else changing it.
996 // We assume that USER_CURRENT_OR_SELF will use the current user; later
997 // we will switch to the calling user if access to the current user fails.
998 int targetUserId = unsafeConvertIncomingUserLocked(userId);
999
1000 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1001 final boolean allow;
1002 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1003 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1004 // If the caller has this permission, they always pass go. And collect $200.
1005 allow = true;
1006 } else if (allowMode == ALLOW_FULL_ONLY) {
1007 // We require full access, sucks to be you.
1008 allow = false;
1009 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1010 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1011 // If the caller does not have either permission, they are always doomed.
1012 allow = false;
1013 } else if (allowMode == ALLOW_NON_FULL) {
1014 // We are blanket allowing non-full access, you lucky caller!
1015 allow = true;
1016 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1017 // We may or may not allow this depending on whether the two users are
1018 // in the same profile.
1019 allow = isSameProfileGroup(callingUserId, targetUserId);
1020 } else {
1021 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1022 }
1023 if (!allow) {
1024 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1025 // In this case, they would like to just execute as their
1026 // owner user instead of failing.
1027 targetUserId = callingUserId;
1028 } else {
1029 StringBuilder builder = new StringBuilder(128);
1030 builder.append("Permission Denial: ");
1031 builder.append(name);
1032 if (callerPackage != null) {
1033 builder.append(" from ");
1034 builder.append(callerPackage);
1035 }
1036 builder.append(" asks to run as user ");
1037 builder.append(userId);
1038 builder.append(" but is calling from user ");
1039 builder.append(UserHandle.getUserId(callingUid));
1040 builder.append("; this requires ");
1041 builder.append(INTERACT_ACROSS_USERS_FULL);
1042 if (allowMode != ALLOW_FULL_ONLY) {
1043 builder.append(" or ");
1044 builder.append(INTERACT_ACROSS_USERS);
1045 }
1046 String msg = builder.toString();
1047 Slog.w(TAG, msg);
1048 throw new SecurityException(msg);
1049 }
1050 }
1051 }
1052 if (!allowAll && targetUserId < 0) {
1053 throw new IllegalArgumentException(
1054 "Call does not support special user #" + targetUserId);
1055 }
1056 // Check shell permission
1057 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1058 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1059 throw new SecurityException("Shell does not have permission to access user "
1060 + targetUserId + "\n " + Debug.getCallers(3));
1061 }
1062 }
1063 return targetUserId;
1064 }
1065
1066 int unsafeConvertIncomingUserLocked(int userId) {
1067 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1068 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001069 }
1070
1071 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1072 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1073 != PackageManager.PERMISSION_GRANTED) {
1074 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1075 + Binder.getCallingPid()
1076 + ", uid=" + Binder.getCallingUid()
1077 + " requires " + INTERACT_ACROSS_USERS_FULL;
1078 Slog.w(TAG, msg);
1079 throw new SecurityException(msg);
1080 }
1081
1082 mUserSwitchObservers.register(observer);
1083 }
1084
1085 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1086 mUserSwitchObservers.unregister(observer);
1087 }
1088
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001089 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001090 return mStartedUsers.get(userId);
1091 }
1092
1093 boolean hasStartedUserState(int userId) {
1094 return mStartedUsers.get(userId) != null;
1095 }
1096
1097 private void updateStartedUserArrayLocked() {
1098 int num = 0;
1099 for (int i = 0; i < mStartedUsers.size(); i++) {
1100 UserState uss = mStartedUsers.valueAt(i);
1101 // This list does not include stopping users.
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001102 if (uss.state != UserState.STATE_STOPPING
1103 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001104 num++;
1105 }
1106 }
1107 mStartedUserArray = new int[num];
1108 num = 0;
1109 for (int i = 0; i < mStartedUsers.size(); i++) {
1110 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001111 if (uss.state != UserState.STATE_STOPPING
1112 && uss.state != UserState.STATE_SHUTDOWN) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001113 mStartedUserArray[num] = mStartedUsers.keyAt(i);
1114 num++;
1115 }
1116 }
1117 }
1118
1119 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1120 for (int i = 0; i < mStartedUsers.size(); i++) {
1121 UserState uss = mStartedUsers.valueAt(i);
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001122 finishUserBoot(uss, resultTo);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001123 }
1124 }
1125
1126 /**
1127 * Refreshes the list of users related to the current user when either a
1128 * user switch happens or when a new related user is started in the
1129 * background.
1130 */
1131 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001132 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001133 false /* enabledOnly */);
1134 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1135 for (int i = 0; i < currentProfileIds.length; i++) {
1136 currentProfileIds[i] = profiles.get(i).id;
1137 }
1138 mCurrentProfileIds = currentProfileIds;
1139
1140 synchronized (mUserProfileGroupIdsSelfLocked) {
1141 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001142 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001143 for (int i = 0; i < users.size(); i++) {
1144 UserInfo user = users.get(i);
1145 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1146 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1147 }
1148 }
1149 }
1150 }
1151
1152 int[] getStartedUserArrayLocked() {
1153 return mStartedUserArray;
1154 }
1155
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001156 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001157 UserState state = getStartedUserStateLocked(userId);
1158 if (state == null) {
1159 return false;
1160 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001161 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001162 return true;
1163 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001164
1165 final boolean unlocked;
1166 switch (state.state) {
1167 case UserState.STATE_STOPPING:
1168 case UserState.STATE_SHUTDOWN:
1169 default:
1170 return false;
1171
1172 case UserState.STATE_BOOTING:
1173 case UserState.STATE_RUNNING_LOCKED:
1174 unlocked = false;
1175 break;
1176
1177 case UserState.STATE_RUNNING:
1178 unlocked = true;
1179 break;
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001180 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001181
1182 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1183 return !unlocked;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001184 }
Jeff Sharkeybedbaa92015-12-02 16:42:25 -07001185 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1186 return unlocked;
1187 }
1188
1189 // One way or another, we're running!
1190 return true;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001191 }
1192
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001193 UserInfo getCurrentUser() {
1194 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1195 != PackageManager.PERMISSION_GRANTED) && (
1196 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1197 != PackageManager.PERMISSION_GRANTED)) {
1198 String msg = "Permission Denial: getCurrentUser() from pid="
1199 + Binder.getCallingPid()
1200 + ", uid=" + Binder.getCallingUid()
1201 + " requires " + INTERACT_ACROSS_USERS;
1202 Slog.w(TAG, msg);
1203 throw new SecurityException(msg);
1204 }
1205 synchronized (mService) {
1206 return getCurrentUserLocked();
1207 }
1208 }
1209
1210 UserInfo getCurrentUserLocked() {
1211 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001212 return getUserInfo(userId);
1213 }
1214
1215 int getCurrentOrTargetUserIdLocked() {
1216 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001217 }
1218
1219 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001220 return mCurrentUserId;
1221 }
1222
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001223 private boolean isCurrentUserLocked(int userId) {
1224 return mCurrentUserId == userId || mTargetUserId == userId;
1225 }
1226
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001227 int setTargetUserIdLocked(int targetUserId) {
1228 return mTargetUserId = targetUserId;
1229 }
1230
1231 int[] getUsers() {
1232 UserManagerService ums = getUserManager();
1233 return ums != null ? ums.getUserIds() : new int[] { 0 };
1234 }
1235
1236 UserInfo getUserInfo(int userId) {
1237 return getUserManager().getUserInfo(userId);
1238 }
1239
1240 int[] getUserIds() {
1241 return getUserManager().getUserIds();
1242 }
1243
1244 boolean exists(int userId) {
1245 return getUserManager().exists(userId);
1246 }
1247
1248 boolean hasUserRestriction(String restriction, int userId) {
1249 return getUserManager().hasUserRestriction(restriction, userId);
1250 }
1251
1252 Set<Integer> getProfileIds(int userId) {
1253 Set<Integer> userIds = new HashSet<>();
1254 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1255 false /* enabledOnly */);
1256 for (UserInfo user : profiles) {
1257 userIds.add(user.id);
1258 }
1259 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001260 }
1261
1262 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1263 synchronized (mUserProfileGroupIdsSelfLocked) {
1264 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1265 UserInfo.NO_PROFILE_GROUP_ID);
1266 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1267 UserInfo.NO_PROFILE_GROUP_ID);
1268 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1269 && callingProfile == targetProfile;
1270 }
1271 }
1272
1273 boolean isCurrentProfileLocked(int userId) {
1274 return ArrayUtils.contains(mCurrentProfileIds, userId);
1275 }
1276
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001277 int[] getCurrentProfileIdsLocked() {
1278 return mCurrentProfileIds;
1279 }
1280
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001281 void dump(PrintWriter pw, boolean dumpAll) {
1282 pw.println(" mStartedUsers:");
1283 for (int i = 0; i < mStartedUsers.size(); i++) {
1284 UserState uss = mStartedUsers.valueAt(i);
1285 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1286 pw.print(": "); uss.dump("", pw);
1287 }
1288 pw.print(" mStartedUserArray: [");
1289 for (int i = 0; i < mStartedUserArray.length; i++) {
1290 if (i > 0) pw.print(", ");
1291 pw.print(mStartedUserArray[i]);
1292 }
1293 pw.println("]");
1294 pw.print(" mUserLru: [");
1295 for (int i = 0; i < mUserLru.size(); i++) {
1296 if (i > 0) pw.print(", ");
1297 pw.print(mUserLru.get(i));
1298 }
1299 pw.println("]");
1300 if (dumpAll) {
1301 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1302 }
1303 synchronized (mUserProfileGroupIdsSelfLocked) {
1304 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1305 pw.println(" mUserProfileGroupIds:");
1306 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1307 pw.print(" User #");
1308 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1309 pw.print(" -> profile #");
1310 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1311 }
1312 }
1313 }
1314 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001315}