blob: 588a80b25d30cceacc63a14452bfaa09437a38d9 [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;
21import static android.app.ActivityManager.USER_OP_IS_CURRENT;
22import static android.app.ActivityManager.USER_OP_SUCCESS;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070023import static android.os.Process.SYSTEM_UID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070024import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
25import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
26import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070027import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
28import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
29import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
30import static com.android.server.am.ActivityManagerService.MY_PID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070031import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
32import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
33import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
34import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
35import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
36
37import android.app.ActivityManager;
38import android.app.AppOpsManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070039import android.app.Dialog;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070040import android.app.IStopUserCallback;
41import android.app.IUserSwitchObserver;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070042import android.content.Context;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070043import android.content.IIntentReceiver;
44import android.content.Intent;
45import android.content.pm.PackageManager;
46import android.content.pm.UserInfo;
47import android.os.BatteryStats;
48import android.os.Binder;
49import android.os.Bundle;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070050import android.os.Debug;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070051import android.os.Handler;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070052import android.os.IBinder;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070053import android.os.IRemoteCallback;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070054import android.os.IUserManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070055import android.os.Process;
56import android.os.RemoteCallbackList;
57import android.os.RemoteException;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070058import android.os.ServiceManager;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080059import android.os.SystemProperties;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070060import android.os.UserHandle;
61import android.os.UserManager;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080062import android.os.storage.IMountService;
63import android.os.storage.StorageManager;
Suprabh Shukla4fe508b2015-11-20 18:22:57 -080064import android.util.Pair;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070065import android.util.Slog;
66import android.util.SparseArray;
67import android.util.SparseIntArray;
68
69import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080070import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070071import com.android.internal.util.ArrayUtils;
72import com.android.server.pm.UserManagerService;
73
74import java.io.PrintWriter;
75import java.util.ArrayList;
76import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070077import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070078import java.util.List;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070079import java.util.Set;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070080
81/**
82 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
83 */
84final class UserController {
85 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
86 // Maximum number of users we allow to be running at a time.
87 static final int MAX_RUNNING_USERS = 3;
88
89 // Amount of time we wait for observers to handle a user switch before
90 // giving up on them and unfreezing the screen.
91 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
92
93 private final ActivityManagerService mService;
94 private final Handler mHandler;
95
96 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070097 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070098 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070099 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700100
101 /**
102 * Which users have been started, so are allowed to run code.
103 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800104 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700105 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800106
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700107 /**
108 * LRU list of history of current users. Most recently current is at the end.
109 */
110 private final ArrayList<Integer> mUserLru = new ArrayList<>();
111
112 /**
113 * Constant array of the users that are currently started.
114 */
115 private int[] mStartedUserArray = new int[] { 0 };
116
117 // If there are multiple profiles for the current user, their ids are here
118 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700119 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700120
121 /**
122 * Mapping from each known user ID to the profile group ID it is associated with.
123 */
124 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
125
126 /**
127 * Registered observers of the user switching mechanics.
128 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700129 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700130 = new RemoteCallbackList<>();
131
132 /**
133 * Currently active user switch.
134 */
135 Object mCurUserSwitchCallback;
136
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700137 private volatile UserManagerService mUserManager;
138
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700139 UserController(ActivityManagerService service) {
140 mService = service;
141 mHandler = mService.mHandler;
142 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800143 final UserState uss = new UserState(UserHandle.SYSTEM);
144 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
145 updateUserUnlockedState(uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700146 mUserLru.add(UserHandle.USER_SYSTEM);
147 updateStartedUserArrayLocked();
148 }
149
150 void finishUserSwitch(UserState uss) {
151 synchronized (mService) {
152 finishUserBoot(uss);
153
154 startProfilesLocked();
155
156 int num = mUserLru.size();
157 int i = 0;
158 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
159 Integer oldUserId = mUserLru.get(i);
160 UserState oldUss = mStartedUsers.get(oldUserId);
161 if (oldUss == null) {
162 // Shouldn't happen, but be sane if it does.
163 mUserLru.remove(i);
164 num--;
165 continue;
166 }
167 if (oldUss.mState == UserState.STATE_STOPPING
168 || oldUss.mState == UserState.STATE_SHUTDOWN) {
169 // This user is already stopping, doesn't count.
170 num--;
171 i++;
172 continue;
173 }
174 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
175 // Owner/System user and current user can't be stopped. We count it as running
176 // when it is not a pure system user.
177 if (UserInfo.isSystemOnly(oldUserId)) {
178 num--;
179 }
180 i++;
181 continue;
182 }
183 // This is a user to be stopped.
184 stopUserLocked(oldUserId, null);
185 num--;
186 i++;
187 }
188 }
189 }
190
191 void finishUserBoot(UserState uss) {
192 synchronized (mService) {
193 if (uss.mState == UserState.STATE_BOOTING
194 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
195 uss.mState = UserState.STATE_RUNNING;
196 final int userId = uss.mHandle.getIdentifier();
197 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
198 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
199 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
200 mService.broadcastIntentLocked(null, null, intent,
201 null, null, 0, null, null,
202 new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700203 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700204 }
205 }
206 }
207
208 int stopUser(final int userId, final IStopUserCallback callback) {
209 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
210 != PackageManager.PERMISSION_GRANTED) {
211 String msg = "Permission Denial: switchUser() from pid="
212 + Binder.getCallingPid()
213 + ", uid=" + Binder.getCallingUid()
214 + " requires " + INTERACT_ACROSS_USERS_FULL;
215 Slog.w(TAG, msg);
216 throw new SecurityException(msg);
217 }
218 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
219 throw new IllegalArgumentException("Can't stop system user " + userId);
220 }
221 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
222 userId);
223 synchronized (mService) {
224 return stopUserLocked(userId, callback);
225 }
226 }
227
228 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
229 if (DEBUG_MU) Slog.i(TAG, "stopUserLocked userId=" + userId);
230 if (mCurrentUserId == userId && mTargetUserId == UserHandle.USER_NULL) {
231 return USER_OP_IS_CURRENT;
232 }
233
234 final UserState uss = mStartedUsers.get(userId);
235 if (uss == null) {
236 // User is not started, nothing to do... but we do need to
237 // callback if requested.
238 if (callback != null) {
239 mHandler.post(new Runnable() {
240 @Override
241 public void run() {
242 try {
243 callback.userStopped(userId);
244 } catch (RemoteException e) {
245 }
246 }
247 });
248 }
249 return USER_OP_SUCCESS;
250 }
251
252 if (callback != null) {
253 uss.mStopCallbacks.add(callback);
254 }
255
256 if (uss.mState != UserState.STATE_STOPPING
257 && uss.mState != UserState.STATE_SHUTDOWN) {
258 uss.mState = UserState.STATE_STOPPING;
259 updateStartedUserArrayLocked();
260
261 long ident = Binder.clearCallingIdentity();
262 try {
263 // We are going to broadcast ACTION_USER_STOPPING and then
264 // once that is done send a final ACTION_SHUTDOWN and then
265 // stop the user.
266 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
267 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
268 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
269 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
270 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
271 // This is the result receiver for the final shutdown broadcast.
272 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
273 @Override
274 public void performReceive(Intent intent, int resultCode, String data,
275 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
276 finishUserStop(uss);
277 }
278 };
279 // This is the result receiver for the initial stopping broadcast.
280 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
281 @Override
282 public void performReceive(Intent intent, int resultCode, String data,
283 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
284 // On to the next.
285 synchronized (mService) {
286 if (uss.mState != UserState.STATE_STOPPING) {
287 // Whoops, we are being started back up. Abort, abort!
288 return;
289 }
290 uss.mState = UserState.STATE_SHUTDOWN;
291 }
292 mService.mBatteryStatsService.noteEvent(
293 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
294 Integer.toString(userId), userId);
295 mService.mSystemServiceManager.stopUser(userId);
296 mService.broadcastIntentLocked(null, null, shutdownIntent,
297 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700298 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700299 }
300 };
301 // Kick things off.
302 mService.broadcastIntentLocked(null, null, stoppingIntent,
303 null, stoppingReceiver, 0, null, null,
304 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700305 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700306 } finally {
307 Binder.restoreCallingIdentity(ident);
308 }
309 }
310
311 return USER_OP_SUCCESS;
312 }
313
314 void finishUserStop(UserState uss) {
315 final int userId = uss.mHandle.getIdentifier();
316 boolean stopped;
317 ArrayList<IStopUserCallback> callbacks;
318 synchronized (mService) {
319 callbacks = new ArrayList<>(uss.mStopCallbacks);
320 if (mStartedUsers.get(userId) != uss) {
321 stopped = false;
322 } else if (uss.mState != UserState.STATE_SHUTDOWN) {
323 stopped = false;
324 } else {
325 stopped = true;
326 // User can no longer run.
327 mStartedUsers.remove(userId);
328 mUserLru.remove(Integer.valueOf(userId));
329 updateStartedUserArrayLocked();
330
331 // Clean up all state and processes associated with the user.
332 // Kill all the processes for the user.
333 forceStopUserLocked(userId, "finish user");
334 }
335 }
336
337 for (int i = 0; i < callbacks.size(); i++) {
338 try {
339 if (stopped) callbacks.get(i).userStopped(userId);
340 else callbacks.get(i).userStopAborted(userId);
341 } catch (RemoteException e) {
342 }
343 }
344
345 if (stopped) {
346 mService.mSystemServiceManager.cleanupUser(userId);
347 synchronized (mService) {
348 mService.mStackSupervisor.removeUserLocked(userId);
349 }
350 }
351 }
352
353 private void forceStopUserLocked(int userId, String reason) {
354 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
355 userId, reason);
356 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
357 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
358 | Intent.FLAG_RECEIVER_FOREGROUND);
359 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
360 mService.broadcastIntentLocked(null, null, intent,
361 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700362 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700363 }
364
365
366 /**
367 * Stops the guest user if it has gone to the background.
368 */
369 private void stopGuestUserIfBackground() {
370 synchronized (mService) {
371 final int num = mUserLru.size();
372 for (int i = 0; i < num; i++) {
373 Integer oldUserId = mUserLru.get(i);
374 UserState oldUss = mStartedUsers.get(oldUserId);
375 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
376 || oldUss.mState == UserState.STATE_STOPPING
377 || oldUss.mState == UserState.STATE_SHUTDOWN) {
378 continue;
379 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700380 UserInfo userInfo = getUserInfo(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700381 if (userInfo.isGuest()) {
382 // This is a user to be stopped.
383 stopUserLocked(oldUserId, null);
384 break;
385 }
386 }
387 }
388 }
389
390 void startProfilesLocked() {
391 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700392 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700393 mCurrentUserId, false /* enabledOnly */);
394 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
395 for (UserInfo user : profiles) {
396 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
397 && user.id != mCurrentUserId) {
398 profilesToStart.add(user);
399 }
400 }
401 final int profilesToStartSize = profilesToStart.size();
402 int i = 0;
403 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
404 startUser(profilesToStart.get(i).id, /* foreground= */ false);
405 }
406 if (i < profilesToStartSize) {
407 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
408 }
409 }
410
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700411 private UserManagerService getUserManager() {
412 UserManagerService userManager = mUserManager;
413 if (userManager == null) {
414 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
415 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
416 }
417 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700418 }
419
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800420 private void updateUserUnlockedState(UserState uss) {
421 final IMountService mountService = IMountService.Stub
Jeff Sharkeyba512352015-11-12 20:17:45 -0800422 .asInterface(ServiceManager.getService("mount"));
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800423 if (mountService != null) {
424 try {
425 uss.unlocked = mountService.isUserKeyUnlocked(uss.mHandle.getIdentifier());
426 } catch (RemoteException e) {
427 throw e.rethrowAsRuntimeException();
428 }
429 } else {
430 // System isn't fully booted yet, so guess based on property
Jeff Sharkeyba512352015-11-12 20:17:45 -0800431 uss.unlocked = !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800432 }
433 }
434
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700435 boolean startUser(final int userId, final boolean foreground) {
436 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
437 != PackageManager.PERMISSION_GRANTED) {
438 String msg = "Permission Denial: switchUser() from pid="
439 + Binder.getCallingPid()
440 + ", uid=" + Binder.getCallingUid()
441 + " requires " + INTERACT_ACROSS_USERS_FULL;
442 Slog.w(TAG, msg);
443 throw new SecurityException(msg);
444 }
445
446 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
447
448 final long ident = Binder.clearCallingIdentity();
449 try {
450 synchronized (mService) {
451 final int oldUserId = mCurrentUserId;
452 if (oldUserId == userId) {
453 return true;
454 }
455
456 mService.mStackSupervisor.setLockTaskModeLocked(null,
457 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
458
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700459 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700460 if (userInfo == null) {
461 Slog.w(TAG, "No user info for user #" + userId);
462 return false;
463 }
464 if (foreground && userInfo.isManagedProfile()) {
465 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
466 return false;
467 }
468
469 if (foreground) {
470 mService.mWindowManager.startFreezingScreen(
471 R.anim.screen_user_exit, R.anim.screen_user_enter);
472 }
473
474 boolean needStart = false;
475
476 // If the user we are switching to is not currently started, then
477 // we need to start it now.
478 if (mStartedUsers.get(userId) == null) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800479 mStartedUsers.put(userId, new UserState(new UserHandle(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700480 updateStartedUserArrayLocked();
481 needStart = true;
482 }
483
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800484 final UserState uss = mStartedUsers.get(userId);
485 updateUserUnlockedState(uss);
486
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700487 final Integer userIdInt = userId;
488 mUserLru.remove(userIdInt);
489 mUserLru.add(userIdInt);
490
491 if (foreground) {
492 mCurrentUserId = userId;
493 mService.updateUserConfigurationLocked();
494 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
495 updateCurrentProfileIdsLocked();
496 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
497 // Once the internal notion of the active user has switched, we lock the device
498 // with the option to show the user switcher on the keyguard.
499 mService.mWindowManager.lockNow(null);
500 } else {
501 final Integer currentUserIdInt = mCurrentUserId;
502 updateCurrentProfileIdsLocked();
503 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
504 mUserLru.remove(currentUserIdInt);
505 mUserLru.add(currentUserIdInt);
506 }
507
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700508 // Make sure user is in the started state. If it is currently
509 // stopping, we need to knock that off.
510 if (uss.mState == UserState.STATE_STOPPING) {
511 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
512 // so we can just fairly silently bring the user back from
513 // the almost-dead.
514 uss.mState = UserState.STATE_RUNNING;
515 updateStartedUserArrayLocked();
516 needStart = true;
517 } else if (uss.mState == UserState.STATE_SHUTDOWN) {
518 // This means ACTION_SHUTDOWN has been sent, so we will
519 // need to treat this as a new boot of the user.
520 uss.mState = UserState.STATE_BOOTING;
521 updateStartedUserArrayLocked();
522 needStart = true;
523 }
524
525 if (uss.mState == UserState.STATE_BOOTING) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800526 // Let user manager propagate user restrictions to other services.
527 getUserManager().onBeforeStartUser(userId);
528
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700529 // Booting up a new user, need to tell system services about it.
530 // Note that this is on the same handler as scheduling of broadcasts,
531 // which is important because it needs to go first.
532 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
533 }
534
535 if (foreground) {
536 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
537 oldUserId));
538 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
539 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
540 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
541 oldUserId, userId, uss));
542 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
543 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
544 }
545
546 if (needStart) {
547 // Send USER_STARTED broadcast
548 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
549 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
550 | Intent.FLAG_RECEIVER_FOREGROUND);
551 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
552 mService.broadcastIntentLocked(null, null, intent,
553 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700554 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700555 }
556
557 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
558 if (userId != UserHandle.USER_SYSTEM) {
559 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
560 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
561 mService.broadcastIntentLocked(null, null, intent, null,
562 new IIntentReceiver.Stub() {
563 public void performReceive(Intent intent, int resultCode,
564 String data, Bundle extras, boolean ordered,
565 boolean sticky, int sendingUser) {
566 onUserInitialized(uss, foreground, oldUserId, userId);
567 }
568 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700569 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700570 uss.initializing = true;
571 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700572 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700573 }
574 }
575
576 if (foreground) {
577 if (!uss.initializing) {
578 moveUserToForegroundLocked(uss, oldUserId, userId);
579 }
580 } else {
581 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
582 }
583
584 if (needStart) {
585 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
586 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
587 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
588 mService.broadcastIntentLocked(null, null, intent,
589 null, new IIntentReceiver.Stub() {
590 @Override
591 public void performReceive(Intent intent, int resultCode,
592 String data, Bundle extras, boolean ordered, boolean sticky,
593 int sendingUser) throws RemoteException {
594 }
595 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700596 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
597 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700598 }
599 }
600 } finally {
601 Binder.restoreCallingIdentity(ident);
602 }
603
604 return true;
605 }
606
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700607 /**
608 * Start user, if its not already running, and bring it to foreground.
609 */
610 boolean startUserInForeground(final int userId, Dialog dlg) {
611 boolean result = startUser(userId, /* foreground */ true);
612 dlg.dismiss();
613 return result;
614 }
615
Jeff Sharkeyba512352015-11-12 20:17:45 -0800616 boolean unlockUser(final int userId, byte[] token) {
617 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
618 != PackageManager.PERMISSION_GRANTED) {
619 String msg = "Permission Denial: unlockUser() from pid="
620 + Binder.getCallingPid()
621 + ", uid=" + Binder.getCallingUid()
622 + " requires " + INTERACT_ACROSS_USERS_FULL;
623 Slog.w(TAG, msg);
624 throw new SecurityException(msg);
625 }
626
Jeff Sharkey8924e872015-11-30 12:52:10 -0700627 final long binderToken = Binder.clearCallingIdentity();
628 try {
629 return unlockUserCleared(userId, token);
630 } finally {
631 Binder.restoreCallingIdentity(binderToken);
632 }
633 }
634
635 boolean unlockUserCleared(final int userId, byte[] token) {
636 synchronized (mService) {
637 final UserState uss = mStartedUsers.get(userId);
638 if (uss.unlocked) {
639 // Bail early when already unlocked
640 return true;
641 }
642 }
643
Jeff Sharkeyba512352015-11-12 20:17:45 -0800644 final UserInfo userInfo = getUserInfo(userId);
645 final IMountService mountService = IMountService.Stub
646 .asInterface(ServiceManager.getService("mount"));
647 try {
648 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
649 } catch (RemoteException e) {
650 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
Jeff Sharkey8924e872015-11-30 12:52:10 -0700651 return false;
Jeff Sharkeyba512352015-11-12 20:17:45 -0800652 }
653
654 synchronized (mService) {
655 final UserState uss = mStartedUsers.get(userId);
656 updateUserUnlockedState(uss);
657 }
658
Jeff Sharkey8924e872015-11-30 12:52:10 -0700659 final Intent intent = new Intent(Intent.ACTION_USER_UNLOCKED);
660 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
661 mService.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
662 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID, userId);
663
Jeff Sharkeyba512352015-11-12 20:17:45 -0800664 return true;
665 }
666
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800667 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700668 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800669 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
670 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700671 d.show();
672 }
673
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700674 void dispatchForegroundProfileChanged(int userId) {
675 final int observerCount = mUserSwitchObservers.beginBroadcast();
676 for (int i = 0; i < observerCount; i++) {
677 try {
678 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
679 } catch (RemoteException e) {
680 // Ignore
681 }
682 }
683 mUserSwitchObservers.finishBroadcast();
684 }
685
686 /** Called on handler thread */
687 void dispatchUserSwitchComplete(int userId) {
688 final int observerCount = mUserSwitchObservers.beginBroadcast();
689 for (int i = 0; i < observerCount; i++) {
690 try {
691 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
692 } catch (RemoteException e) {
693 }
694 }
695 mUserSwitchObservers.finishBroadcast();
696 }
697
698 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
699 synchronized (mService) {
Amith Yamasanica0ac5c2015-11-20 09:44:08 -0800700 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700701 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
702 }
703 }
704
705 void dispatchUserSwitch(final UserState uss, final int oldUserId,
706 final int newUserId) {
707 final int observerCount = mUserSwitchObservers.beginBroadcast();
708 if (observerCount > 0) {
709 final IRemoteCallback callback = new IRemoteCallback.Stub() {
710 int mCount = 0;
711 @Override
712 public void sendResult(Bundle data) throws RemoteException {
713 synchronized (mService) {
714 if (mCurUserSwitchCallback == this) {
715 mCount++;
716 if (mCount == observerCount) {
717 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
718 }
719 }
720 }
721 }
722 };
723 synchronized (mService) {
724 uss.switching = true;
725 mCurUserSwitchCallback = callback;
726 }
727 for (int i = 0; i < observerCount; i++) {
728 try {
729 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
730 newUserId, callback);
731 } catch (RemoteException e) {
732 }
733 }
734 } else {
735 synchronized (mService) {
736 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
737 }
738 }
739 mUserSwitchObservers.finishBroadcast();
740 }
741
742 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
743 mCurUserSwitchCallback = null;
744 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
745 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
746 oldUserId, newUserId, uss));
747 }
748
749 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
750 completeSwitchAndInitialize(uss, newUserId, false, true);
751 }
752
753 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
754 synchronized (mService) {
755 if (foreground) {
756 moveUserToForegroundLocked(uss, oldUserId, newUserId);
757 }
758 }
759 completeSwitchAndInitialize(uss, newUserId, true, false);
760 }
761
762 void completeSwitchAndInitialize(UserState uss, int newUserId,
763 boolean clearInitializing, boolean clearSwitching) {
764 boolean unfrozen = false;
765 synchronized (mService) {
766 if (clearInitializing) {
767 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700768 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700769 }
770 if (clearSwitching) {
771 uss.switching = false;
772 }
773 if (!uss.switching && !uss.initializing) {
774 mService.mWindowManager.stopFreezingScreen();
775 unfrozen = true;
776 }
777 }
778 if (unfrozen) {
779 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
780 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
781 newUserId, 0));
782 }
783 stopGuestUserIfBackground();
784 }
785
786 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
787 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
788 if (homeInFront) {
789 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
790 } else {
791 mService.mStackSupervisor.resumeTopActivitiesLocked();
792 }
793 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700794 getUserManager().onUserForeground(newUserId);
795 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
796 }
797
798 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
799 long ident = Binder.clearCallingIdentity();
800 try {
801 Intent intent;
802 if (oldUserId >= 0) {
803 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
804 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
805 int count = profiles.size();
806 for (int i = 0; i < count; i++) {
807 int profileUserId = profiles.get(i).id;
808 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
809 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
810 | Intent.FLAG_RECEIVER_FOREGROUND);
811 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
812 mService.broadcastIntentLocked(null, null, intent,
813 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
814 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
815 }
816 }
817 if (newUserId >= 0) {
818 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
819 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
820 int count = profiles.size();
821 for (int i = 0; i < count; i++) {
822 int profileUserId = profiles.get(i).id;
823 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
824 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
825 | Intent.FLAG_RECEIVER_FOREGROUND);
826 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
827 mService.broadcastIntentLocked(null, null, intent,
828 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
829 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
830 }
831 intent = new Intent(Intent.ACTION_USER_SWITCHED);
832 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
833 | Intent.FLAG_RECEIVER_FOREGROUND);
834 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
835 mService.broadcastIntentLocked(null, null, intent,
836 null, null, 0, null, null,
837 new String[] {android.Manifest.permission.MANAGE_USERS},
838 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
839 UserHandle.USER_ALL);
840 }
841 } finally {
842 Binder.restoreCallingIdentity(ident);
843 }
844 }
845
846
847 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
848 int allowMode, String name, String callerPackage) {
849 final int callingUserId = UserHandle.getUserId(callingUid);
850 if (callingUserId == userId) {
851 return userId;
852 }
853
854 // Note that we may be accessing mCurrentUserId outside of a lock...
855 // shouldn't be a big deal, if this is being called outside
856 // of a locked context there is intrinsically a race with
857 // the value the caller will receive and someone else changing it.
858 // We assume that USER_CURRENT_OR_SELF will use the current user; later
859 // we will switch to the calling user if access to the current user fails.
860 int targetUserId = unsafeConvertIncomingUserLocked(userId);
861
862 if (callingUid != 0 && callingUid != SYSTEM_UID) {
863 final boolean allow;
864 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
865 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
866 // If the caller has this permission, they always pass go. And collect $200.
867 allow = true;
868 } else if (allowMode == ALLOW_FULL_ONLY) {
869 // We require full access, sucks to be you.
870 allow = false;
871 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
872 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
873 // If the caller does not have either permission, they are always doomed.
874 allow = false;
875 } else if (allowMode == ALLOW_NON_FULL) {
876 // We are blanket allowing non-full access, you lucky caller!
877 allow = true;
878 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
879 // We may or may not allow this depending on whether the two users are
880 // in the same profile.
881 allow = isSameProfileGroup(callingUserId, targetUserId);
882 } else {
883 throw new IllegalArgumentException("Unknown mode: " + allowMode);
884 }
885 if (!allow) {
886 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
887 // In this case, they would like to just execute as their
888 // owner user instead of failing.
889 targetUserId = callingUserId;
890 } else {
891 StringBuilder builder = new StringBuilder(128);
892 builder.append("Permission Denial: ");
893 builder.append(name);
894 if (callerPackage != null) {
895 builder.append(" from ");
896 builder.append(callerPackage);
897 }
898 builder.append(" asks to run as user ");
899 builder.append(userId);
900 builder.append(" but is calling from user ");
901 builder.append(UserHandle.getUserId(callingUid));
902 builder.append("; this requires ");
903 builder.append(INTERACT_ACROSS_USERS_FULL);
904 if (allowMode != ALLOW_FULL_ONLY) {
905 builder.append(" or ");
906 builder.append(INTERACT_ACROSS_USERS);
907 }
908 String msg = builder.toString();
909 Slog.w(TAG, msg);
910 throw new SecurityException(msg);
911 }
912 }
913 }
914 if (!allowAll && targetUserId < 0) {
915 throw new IllegalArgumentException(
916 "Call does not support special user #" + targetUserId);
917 }
918 // Check shell permission
919 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
920 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
921 throw new SecurityException("Shell does not have permission to access user "
922 + targetUserId + "\n " + Debug.getCallers(3));
923 }
924 }
925 return targetUserId;
926 }
927
928 int unsafeConvertIncomingUserLocked(int userId) {
929 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
930 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700931 }
932
933 void registerUserSwitchObserver(IUserSwitchObserver observer) {
934 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
935 != PackageManager.PERMISSION_GRANTED) {
936 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
937 + Binder.getCallingPid()
938 + ", uid=" + Binder.getCallingUid()
939 + " requires " + INTERACT_ACROSS_USERS_FULL;
940 Slog.w(TAG, msg);
941 throw new SecurityException(msg);
942 }
943
944 mUserSwitchObservers.register(observer);
945 }
946
947 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
948 mUserSwitchObservers.unregister(observer);
949 }
950
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700951 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700952 return mStartedUsers.get(userId);
953 }
954
955 boolean hasStartedUserState(int userId) {
956 return mStartedUsers.get(userId) != null;
957 }
958
959 private void updateStartedUserArrayLocked() {
960 int num = 0;
961 for (int i = 0; i < mStartedUsers.size(); i++) {
962 UserState uss = mStartedUsers.valueAt(i);
963 // This list does not include stopping users.
964 if (uss.mState != UserState.STATE_STOPPING
965 && uss.mState != UserState.STATE_SHUTDOWN) {
966 num++;
967 }
968 }
969 mStartedUserArray = new int[num];
970 num = 0;
971 for (int i = 0; i < mStartedUsers.size(); i++) {
972 UserState uss = mStartedUsers.valueAt(i);
973 if (uss.mState != UserState.STATE_STOPPING
974 && uss.mState != UserState.STATE_SHUTDOWN) {
975 mStartedUserArray[num] = mStartedUsers.keyAt(i);
976 num++;
977 }
978 }
979 }
980
981 void sendBootCompletedLocked(IIntentReceiver resultTo) {
982 for (int i = 0; i < mStartedUsers.size(); i++) {
983 UserState uss = mStartedUsers.valueAt(i);
984 if (uss.mState == UserState.STATE_BOOTING) {
985 uss.mState = UserState.STATE_RUNNING;
986 final int userId = mStartedUsers.keyAt(i);
987 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
988 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
989 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
990 mService.broadcastIntentLocked(null, null, intent, null,
991 resultTo, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700992 new String[] {android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
993 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700994 }
995 }
996 }
997
998 /**
999 * Refreshes the list of users related to the current user when either a
1000 * user switch happens or when a new related user is started in the
1001 * background.
1002 */
1003 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001004 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001005 false /* enabledOnly */);
1006 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1007 for (int i = 0; i < currentProfileIds.length; i++) {
1008 currentProfileIds[i] = profiles.get(i).id;
1009 }
1010 mCurrentProfileIds = currentProfileIds;
1011
1012 synchronized (mUserProfileGroupIdsSelfLocked) {
1013 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001014 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001015 for (int i = 0; i < users.size(); i++) {
1016 UserInfo user = users.get(i);
1017 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1018 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1019 }
1020 }
1021 }
1022 }
1023
1024 int[] getStartedUserArrayLocked() {
1025 return mStartedUserArray;
1026 }
1027
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001028 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001029 UserState state = getStartedUserStateLocked(userId);
1030 if (state == null) {
1031 return false;
1032 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001033 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001034 return true;
1035 }
Jeff Sharkey0825ab22015-12-02 13:04:49 -07001036 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0 && state.unlocked) {
1037 return false;
1038 }
1039 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0 && !state.unlocked) {
1040 return false;
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001041 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001042 return state.mState != UserState.STATE_STOPPING
1043 && state.mState != UserState.STATE_SHUTDOWN;
1044 }
1045
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001046 UserInfo getCurrentUser() {
1047 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1048 != PackageManager.PERMISSION_GRANTED) && (
1049 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1050 != PackageManager.PERMISSION_GRANTED)) {
1051 String msg = "Permission Denial: getCurrentUser() from pid="
1052 + Binder.getCallingPid()
1053 + ", uid=" + Binder.getCallingUid()
1054 + " requires " + INTERACT_ACROSS_USERS;
1055 Slog.w(TAG, msg);
1056 throw new SecurityException(msg);
1057 }
1058 synchronized (mService) {
1059 return getCurrentUserLocked();
1060 }
1061 }
1062
1063 UserInfo getCurrentUserLocked() {
1064 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001065 return getUserInfo(userId);
1066 }
1067
1068 int getCurrentOrTargetUserIdLocked() {
1069 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001070 }
1071
1072 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001073 return mCurrentUserId;
1074 }
1075
1076 int setTargetUserIdLocked(int targetUserId) {
1077 return mTargetUserId = targetUserId;
1078 }
1079
1080 int[] getUsers() {
1081 UserManagerService ums = getUserManager();
1082 return ums != null ? ums.getUserIds() : new int[] { 0 };
1083 }
1084
1085 UserInfo getUserInfo(int userId) {
1086 return getUserManager().getUserInfo(userId);
1087 }
1088
1089 int[] getUserIds() {
1090 return getUserManager().getUserIds();
1091 }
1092
1093 boolean exists(int userId) {
1094 return getUserManager().exists(userId);
1095 }
1096
1097 boolean hasUserRestriction(String restriction, int userId) {
1098 return getUserManager().hasUserRestriction(restriction, userId);
1099 }
1100
1101 Set<Integer> getProfileIds(int userId) {
1102 Set<Integer> userIds = new HashSet<>();
1103 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1104 false /* enabledOnly */);
1105 for (UserInfo user : profiles) {
1106 userIds.add(user.id);
1107 }
1108 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001109 }
1110
1111 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1112 synchronized (mUserProfileGroupIdsSelfLocked) {
1113 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1114 UserInfo.NO_PROFILE_GROUP_ID);
1115 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1116 UserInfo.NO_PROFILE_GROUP_ID);
1117 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1118 && callingProfile == targetProfile;
1119 }
1120 }
1121
1122 boolean isCurrentProfileLocked(int userId) {
1123 return ArrayUtils.contains(mCurrentProfileIds, userId);
1124 }
1125
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001126 int[] getCurrentProfileIdsLocked() {
1127 return mCurrentProfileIds;
1128 }
1129
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001130 void dump(PrintWriter pw, boolean dumpAll) {
1131 pw.println(" mStartedUsers:");
1132 for (int i = 0; i < mStartedUsers.size(); i++) {
1133 UserState uss = mStartedUsers.valueAt(i);
1134 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1135 pw.print(": "); uss.dump("", pw);
1136 }
1137 pw.print(" mStartedUserArray: [");
1138 for (int i = 0; i < mStartedUserArray.length; i++) {
1139 if (i > 0) pw.print(", ");
1140 pw.print(mStartedUserArray[i]);
1141 }
1142 pw.println("]");
1143 pw.print(" mUserLru: [");
1144 for (int i = 0; i < mUserLru.size(); i++) {
1145 if (i > 0) pw.print(", ");
1146 pw.print(mUserLru.get(i));
1147 }
1148 pw.println("]");
1149 if (dumpAll) {
1150 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1151 }
1152 synchronized (mUserProfileGroupIdsSelfLocked) {
1153 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1154 pw.println(" mUserProfileGroupIds:");
1155 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1156 pw.print(" User #");
1157 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1158 pw.print(" -> profile #");
1159 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1160 }
1161 }
1162 }
1163 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001164}