blob: dc82dd8c938d2e6e4b994410d9389c1fbb690373 [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
627 final UserInfo userInfo = getUserInfo(userId);
628 final IMountService mountService = IMountService.Stub
629 .asInterface(ServiceManager.getService("mount"));
630 try {
631 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
632 } catch (RemoteException e) {
633 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
634 throw e.rethrowAsRuntimeException();
635 }
636
637 synchronized (mService) {
638 final UserState uss = mStartedUsers.get(userId);
639 updateUserUnlockedState(uss);
640 }
641
642 return true;
643 }
644
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800645 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700646 // The dialog will show and then initiate the user switch by calling startUserInForeground
Suprabh Shukla4fe508b2015-11-20 18:22:57 -0800647 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
648 fromToUserPair.second, true /* above system */);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700649 d.show();
650 }
651
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700652 void dispatchForegroundProfileChanged(int userId) {
653 final int observerCount = mUserSwitchObservers.beginBroadcast();
654 for (int i = 0; i < observerCount; i++) {
655 try {
656 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
657 } catch (RemoteException e) {
658 // Ignore
659 }
660 }
661 mUserSwitchObservers.finishBroadcast();
662 }
663
664 /** Called on handler thread */
665 void dispatchUserSwitchComplete(int userId) {
666 final int observerCount = mUserSwitchObservers.beginBroadcast();
667 for (int i = 0; i < observerCount; i++) {
668 try {
669 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
670 } catch (RemoteException e) {
671 }
672 }
673 mUserSwitchObservers.finishBroadcast();
674 }
675
676 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
677 synchronized (mService) {
678 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
679 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
680 }
681 }
682
683 void dispatchUserSwitch(final UserState uss, final int oldUserId,
684 final int newUserId) {
685 final int observerCount = mUserSwitchObservers.beginBroadcast();
686 if (observerCount > 0) {
687 final IRemoteCallback callback = new IRemoteCallback.Stub() {
688 int mCount = 0;
689 @Override
690 public void sendResult(Bundle data) throws RemoteException {
691 synchronized (mService) {
692 if (mCurUserSwitchCallback == this) {
693 mCount++;
694 if (mCount == observerCount) {
695 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
696 }
697 }
698 }
699 }
700 };
701 synchronized (mService) {
702 uss.switching = true;
703 mCurUserSwitchCallback = callback;
704 }
705 for (int i = 0; i < observerCount; i++) {
706 try {
707 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
708 newUserId, callback);
709 } catch (RemoteException e) {
710 }
711 }
712 } else {
713 synchronized (mService) {
714 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
715 }
716 }
717 mUserSwitchObservers.finishBroadcast();
718 }
719
720 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
721 mCurUserSwitchCallback = null;
722 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
723 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
724 oldUserId, newUserId, uss));
725 }
726
727 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
728 completeSwitchAndInitialize(uss, newUserId, false, true);
729 }
730
731 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
732 synchronized (mService) {
733 if (foreground) {
734 moveUserToForegroundLocked(uss, oldUserId, newUserId);
735 }
736 }
737 completeSwitchAndInitialize(uss, newUserId, true, false);
738 }
739
740 void completeSwitchAndInitialize(UserState uss, int newUserId,
741 boolean clearInitializing, boolean clearSwitching) {
742 boolean unfrozen = false;
743 synchronized (mService) {
744 if (clearInitializing) {
745 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700746 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700747 }
748 if (clearSwitching) {
749 uss.switching = false;
750 }
751 if (!uss.switching && !uss.initializing) {
752 mService.mWindowManager.stopFreezingScreen();
753 unfrozen = true;
754 }
755 }
756 if (unfrozen) {
757 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
758 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
759 newUserId, 0));
760 }
761 stopGuestUserIfBackground();
762 }
763
764 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
765 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
766 if (homeInFront) {
767 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
768 } else {
769 mService.mStackSupervisor.resumeTopActivitiesLocked();
770 }
771 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700772 getUserManager().onUserForeground(newUserId);
773 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
774 }
775
776 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
777 long ident = Binder.clearCallingIdentity();
778 try {
779 Intent intent;
780 if (oldUserId >= 0) {
781 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
782 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
783 int count = profiles.size();
784 for (int i = 0; i < count; i++) {
785 int profileUserId = profiles.get(i).id;
786 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
787 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
788 | Intent.FLAG_RECEIVER_FOREGROUND);
789 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
790 mService.broadcastIntentLocked(null, null, intent,
791 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
792 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
793 }
794 }
795 if (newUserId >= 0) {
796 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
797 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
798 int count = profiles.size();
799 for (int i = 0; i < count; i++) {
800 int profileUserId = profiles.get(i).id;
801 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
802 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
803 | Intent.FLAG_RECEIVER_FOREGROUND);
804 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
805 mService.broadcastIntentLocked(null, null, intent,
806 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
807 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
808 }
809 intent = new Intent(Intent.ACTION_USER_SWITCHED);
810 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
811 | Intent.FLAG_RECEIVER_FOREGROUND);
812 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
813 mService.broadcastIntentLocked(null, null, intent,
814 null, null, 0, null, null,
815 new String[] {android.Manifest.permission.MANAGE_USERS},
816 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
817 UserHandle.USER_ALL);
818 }
819 } finally {
820 Binder.restoreCallingIdentity(ident);
821 }
822 }
823
824
825 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
826 int allowMode, String name, String callerPackage) {
827 final int callingUserId = UserHandle.getUserId(callingUid);
828 if (callingUserId == userId) {
829 return userId;
830 }
831
832 // Note that we may be accessing mCurrentUserId outside of a lock...
833 // shouldn't be a big deal, if this is being called outside
834 // of a locked context there is intrinsically a race with
835 // the value the caller will receive and someone else changing it.
836 // We assume that USER_CURRENT_OR_SELF will use the current user; later
837 // we will switch to the calling user if access to the current user fails.
838 int targetUserId = unsafeConvertIncomingUserLocked(userId);
839
840 if (callingUid != 0 && callingUid != SYSTEM_UID) {
841 final boolean allow;
842 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
843 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
844 // If the caller has this permission, they always pass go. And collect $200.
845 allow = true;
846 } else if (allowMode == ALLOW_FULL_ONLY) {
847 // We require full access, sucks to be you.
848 allow = false;
849 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
850 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
851 // If the caller does not have either permission, they are always doomed.
852 allow = false;
853 } else if (allowMode == ALLOW_NON_FULL) {
854 // We are blanket allowing non-full access, you lucky caller!
855 allow = true;
856 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
857 // We may or may not allow this depending on whether the two users are
858 // in the same profile.
859 allow = isSameProfileGroup(callingUserId, targetUserId);
860 } else {
861 throw new IllegalArgumentException("Unknown mode: " + allowMode);
862 }
863 if (!allow) {
864 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
865 // In this case, they would like to just execute as their
866 // owner user instead of failing.
867 targetUserId = callingUserId;
868 } else {
869 StringBuilder builder = new StringBuilder(128);
870 builder.append("Permission Denial: ");
871 builder.append(name);
872 if (callerPackage != null) {
873 builder.append(" from ");
874 builder.append(callerPackage);
875 }
876 builder.append(" asks to run as user ");
877 builder.append(userId);
878 builder.append(" but is calling from user ");
879 builder.append(UserHandle.getUserId(callingUid));
880 builder.append("; this requires ");
881 builder.append(INTERACT_ACROSS_USERS_FULL);
882 if (allowMode != ALLOW_FULL_ONLY) {
883 builder.append(" or ");
884 builder.append(INTERACT_ACROSS_USERS);
885 }
886 String msg = builder.toString();
887 Slog.w(TAG, msg);
888 throw new SecurityException(msg);
889 }
890 }
891 }
892 if (!allowAll && targetUserId < 0) {
893 throw new IllegalArgumentException(
894 "Call does not support special user #" + targetUserId);
895 }
896 // Check shell permission
897 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
898 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
899 throw new SecurityException("Shell does not have permission to access user "
900 + targetUserId + "\n " + Debug.getCallers(3));
901 }
902 }
903 return targetUserId;
904 }
905
906 int unsafeConvertIncomingUserLocked(int userId) {
907 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
908 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700909 }
910
911 void registerUserSwitchObserver(IUserSwitchObserver observer) {
912 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
913 != PackageManager.PERMISSION_GRANTED) {
914 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
915 + Binder.getCallingPid()
916 + ", uid=" + Binder.getCallingUid()
917 + " requires " + INTERACT_ACROSS_USERS_FULL;
918 Slog.w(TAG, msg);
919 throw new SecurityException(msg);
920 }
921
922 mUserSwitchObservers.register(observer);
923 }
924
925 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
926 mUserSwitchObservers.unregister(observer);
927 }
928
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700929 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700930 return mStartedUsers.get(userId);
931 }
932
933 boolean hasStartedUserState(int userId) {
934 return mStartedUsers.get(userId) != null;
935 }
936
937 private void updateStartedUserArrayLocked() {
938 int num = 0;
939 for (int i = 0; i < mStartedUsers.size(); i++) {
940 UserState uss = mStartedUsers.valueAt(i);
941 // This list does not include stopping users.
942 if (uss.mState != UserState.STATE_STOPPING
943 && uss.mState != UserState.STATE_SHUTDOWN) {
944 num++;
945 }
946 }
947 mStartedUserArray = new int[num];
948 num = 0;
949 for (int i = 0; i < mStartedUsers.size(); i++) {
950 UserState uss = mStartedUsers.valueAt(i);
951 if (uss.mState != UserState.STATE_STOPPING
952 && uss.mState != UserState.STATE_SHUTDOWN) {
953 mStartedUserArray[num] = mStartedUsers.keyAt(i);
954 num++;
955 }
956 }
957 }
958
959 void sendBootCompletedLocked(IIntentReceiver resultTo) {
960 for (int i = 0; i < mStartedUsers.size(); i++) {
961 UserState uss = mStartedUsers.valueAt(i);
962 if (uss.mState == UserState.STATE_BOOTING) {
963 uss.mState = UserState.STATE_RUNNING;
964 final int userId = mStartedUsers.keyAt(i);
965 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
966 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
967 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
968 mService.broadcastIntentLocked(null, null, intent, null,
969 resultTo, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700970 new String[] {android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
971 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700972 }
973 }
974 }
975
976 /**
977 * Refreshes the list of users related to the current user when either a
978 * user switch happens or when a new related user is started in the
979 * background.
980 */
981 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700982 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700983 false /* enabledOnly */);
984 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
985 for (int i = 0; i < currentProfileIds.length; i++) {
986 currentProfileIds[i] = profiles.get(i).id;
987 }
988 mCurrentProfileIds = currentProfileIds;
989
990 synchronized (mUserProfileGroupIdsSelfLocked) {
991 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700992 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700993 for (int i = 0; i < users.size(); i++) {
994 UserInfo user = users.get(i);
995 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
996 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
997 }
998 }
999 }
1000 }
1001
1002 int[] getStartedUserArrayLocked() {
1003 return mStartedUserArray;
1004 }
1005
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001006 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001007 UserState state = getStartedUserStateLocked(userId);
1008 if (state == null) {
1009 return false;
1010 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001011 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001012 return true;
1013 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001014 if ((flags & ActivityManager.FLAG_WITH_AMNESIA) != 0) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001015 // If user is currently locked, we fall through to default "running"
1016 // behavior below
1017 if (state.unlocked) {
1018 return false;
1019 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001020 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001021 return state.mState != UserState.STATE_STOPPING
1022 && state.mState != UserState.STATE_SHUTDOWN;
1023 }
1024
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001025 UserInfo getCurrentUser() {
1026 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1027 != PackageManager.PERMISSION_GRANTED) && (
1028 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1029 != PackageManager.PERMISSION_GRANTED)) {
1030 String msg = "Permission Denial: getCurrentUser() from pid="
1031 + Binder.getCallingPid()
1032 + ", uid=" + Binder.getCallingUid()
1033 + " requires " + INTERACT_ACROSS_USERS;
1034 Slog.w(TAG, msg);
1035 throw new SecurityException(msg);
1036 }
1037 synchronized (mService) {
1038 return getCurrentUserLocked();
1039 }
1040 }
1041
1042 UserInfo getCurrentUserLocked() {
1043 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001044 return getUserInfo(userId);
1045 }
1046
1047 int getCurrentOrTargetUserIdLocked() {
1048 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001049 }
1050
1051 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001052 return mCurrentUserId;
1053 }
1054
1055 int setTargetUserIdLocked(int targetUserId) {
1056 return mTargetUserId = targetUserId;
1057 }
1058
1059 int[] getUsers() {
1060 UserManagerService ums = getUserManager();
1061 return ums != null ? ums.getUserIds() : new int[] { 0 };
1062 }
1063
1064 UserInfo getUserInfo(int userId) {
1065 return getUserManager().getUserInfo(userId);
1066 }
1067
1068 int[] getUserIds() {
1069 return getUserManager().getUserIds();
1070 }
1071
1072 boolean exists(int userId) {
1073 return getUserManager().exists(userId);
1074 }
1075
1076 boolean hasUserRestriction(String restriction, int userId) {
1077 return getUserManager().hasUserRestriction(restriction, userId);
1078 }
1079
1080 Set<Integer> getProfileIds(int userId) {
1081 Set<Integer> userIds = new HashSet<>();
1082 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1083 false /* enabledOnly */);
1084 for (UserInfo user : profiles) {
1085 userIds.add(user.id);
1086 }
1087 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001088 }
1089
1090 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1091 synchronized (mUserProfileGroupIdsSelfLocked) {
1092 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1093 UserInfo.NO_PROFILE_GROUP_ID);
1094 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1095 UserInfo.NO_PROFILE_GROUP_ID);
1096 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1097 && callingProfile == targetProfile;
1098 }
1099 }
1100
1101 boolean isCurrentProfileLocked(int userId) {
1102 return ArrayUtils.contains(mCurrentProfileIds, userId);
1103 }
1104
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001105 int[] getCurrentProfileIdsLocked() {
1106 return mCurrentProfileIds;
1107 }
1108
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001109 void dump(PrintWriter pw, boolean dumpAll) {
1110 pw.println(" mStartedUsers:");
1111 for (int i = 0; i < mStartedUsers.size(); i++) {
1112 UserState uss = mStartedUsers.valueAt(i);
1113 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1114 pw.print(": "); uss.dump("", pw);
1115 }
1116 pw.print(" mStartedUserArray: [");
1117 for (int i = 0; i < mStartedUserArray.length; i++) {
1118 if (i > 0) pw.print(", ");
1119 pw.print(mStartedUserArray[i]);
1120 }
1121 pw.println("]");
1122 pw.print(" mUserLru: [");
1123 for (int i = 0; i < mUserLru.size(); i++) {
1124 if (i > 0) pw.print(", ");
1125 pw.print(mUserLru.get(i));
1126 }
1127 pw.println("]");
1128 if (dumpAll) {
1129 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1130 }
1131 synchronized (mUserProfileGroupIdsSelfLocked) {
1132 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1133 pw.println(" mUserProfileGroupIds:");
1134 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1135 pw.print(" User #");
1136 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1137 pw.print(" -> profile #");
1138 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1139 }
1140 }
1141 }
1142 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001143}