UserController.java revision ce18c8167766f92856f94a8e88e19de4698960e6
1/* 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_ERROR_IS_SYSTEM; 22import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP; 23import static android.app.ActivityManager.USER_OP_IS_CURRENT; 24import static android.app.ActivityManager.USER_OP_SUCCESS; 25import static android.content.Context.KEYGUARD_SERVICE; 26import static android.os.Process.SYSTEM_UID; 27 28import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; 29import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 30import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 31import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY; 32import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL; 33import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE; 34import static com.android.server.am.ActivityManagerService.MY_PID; 35import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG; 36import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG; 37import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG; 38import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG; 39import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG; 40import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG; 41import static com.android.server.am.UserState.STATE_BOOTING; 42import static com.android.server.am.UserState.STATE_RUNNING_LOCKED; 43import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED; 44import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING; 45 46import android.annotation.NonNull; 47import android.annotation.UserIdInt; 48import android.app.ActivityManager; 49import android.app.AppOpsManager; 50import android.app.Dialog; 51import android.app.IStopUserCallback; 52import android.app.IUserSwitchObserver; 53import android.app.KeyguardManager; 54import android.content.Context; 55import android.content.IIntentReceiver; 56import android.content.Intent; 57import android.content.pm.PackageManager; 58import android.content.pm.UserInfo; 59import android.os.BatteryStats; 60import android.os.Binder; 61import android.os.Build; 62import android.os.Bundle; 63import android.os.Debug; 64import android.os.Handler; 65import android.os.IBinder; 66import android.os.IProgressListener; 67import android.os.IRemoteCallback; 68import android.os.IUserManager; 69import android.os.Process; 70import android.os.RemoteCallbackList; 71import android.os.RemoteException; 72import android.os.ServiceManager; 73import android.os.UserHandle; 74import android.os.UserManager; 75import android.os.UserManagerInternal; 76import android.os.storage.IMountService; 77import android.os.storage.StorageManager; 78import android.util.IntArray; 79import android.util.Pair; 80import android.util.Slog; 81import android.util.SparseArray; 82import android.util.SparseIntArray; 83 84import com.android.internal.R; 85import com.android.internal.annotations.GuardedBy; 86import com.android.internal.util.ArrayUtils; 87import com.android.internal.widget.LockPatternUtils; 88import com.android.server.LocalServices; 89import com.android.server.pm.UserManagerService; 90 91import java.io.PrintWriter; 92import java.util.ArrayList; 93import java.util.Arrays; 94import java.util.HashSet; 95import java.util.List; 96import java.util.Objects; 97import java.util.Set; 98 99/** 100 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality. 101 */ 102final class UserController { 103 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM; 104 105 // Maximum number of users we allow to be running at a time. 106 static final int MAX_RUNNING_USERS = 3; 107 108 // Amount of time we wait for observers to handle a user switch before 109 // giving up on them and unfreezing the screen. 110 static final int USER_SWITCH_TIMEOUT = 2 * 1000; 111 112 private final ActivityManagerService mService; 113 private final Handler mHandler; 114 115 // Holds the current foreground user's id 116 private int mCurrentUserId = UserHandle.USER_SYSTEM; 117 // Holds the target user's id during a user switch 118 private int mTargetUserId = UserHandle.USER_NULL; 119 120 /** 121 * Which users have been started, so are allowed to run code. 122 */ 123 @GuardedBy("mService") 124 private final SparseArray<UserState> mStartedUsers = new SparseArray<>(); 125 126 /** 127 * LRU list of history of current users. Most recently current is at the end. 128 */ 129 private final ArrayList<Integer> mUserLru = new ArrayList<>(); 130 131 /** 132 * Constant array of the users that are currently started. 133 */ 134 private int[] mStartedUserArray = new int[] { 0 }; 135 136 // If there are multiple profiles for the current user, their ids are here 137 // Currently only the primary user can have managed profiles 138 private int[] mCurrentProfileIds = new int[] {}; 139 140 /** 141 * Mapping from each known user ID to the profile group ID it is associated with. 142 */ 143 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray(); 144 145 /** 146 * Registered observers of the user switching mechanics. 147 */ 148 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers 149 = new RemoteCallbackList<>(); 150 151 /** 152 * Currently active user switch. 153 */ 154 Object mCurUserSwitchCallback; 155 156 private volatile UserManagerService mUserManager; 157 158 private final LockPatternUtils mLockPatternUtils; 159 160 UserController(ActivityManagerService service) { 161 mService = service; 162 mHandler = mService.mHandler; 163 // User 0 is the first and only user that runs at boot. 164 final UserState uss = new UserState(UserHandle.SYSTEM); 165 mStartedUsers.put(UserHandle.USER_SYSTEM, uss); 166 mUserLru.add(UserHandle.USER_SYSTEM); 167 mLockPatternUtils = new LockPatternUtils(mService.mContext); 168 updateStartedUserArrayLocked(); 169 } 170 171 void finishUserSwitch(UserState uss) { 172 synchronized (mService) { 173 finishUserBoot(uss); 174 175 startProfilesLocked(); 176 stopRunningUsersLocked(MAX_RUNNING_USERS); 177 } 178 } 179 180 void stopRunningUsersLocked(int maxRunningUsers) { 181 int num = mUserLru.size(); 182 int i = 0; 183 while (num > maxRunningUsers && i < mUserLru.size()) { 184 Integer oldUserId = mUserLru.get(i); 185 UserState oldUss = mStartedUsers.get(oldUserId); 186 if (oldUss == null) { 187 // Shouldn't happen, but be sane if it does. 188 mUserLru.remove(i); 189 num--; 190 continue; 191 } 192 if (oldUss.state == UserState.STATE_STOPPING 193 || oldUss.state == UserState.STATE_SHUTDOWN) { 194 // This user is already stopping, doesn't count. 195 num--; 196 i++; 197 continue; 198 } 199 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) { 200 // Owner/System user and current user can't be stopped. We count it as running 201 // when it is not a pure system user. 202 if (UserInfo.isSystemOnly(oldUserId)) { 203 num--; 204 } 205 i++; 206 continue; 207 } 208 // This is a user to be stopped. 209 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) { 210 num--; 211 } 212 num--; 213 i++; 214 } 215 } 216 217 private void finishUserBoot(UserState uss) { 218 finishUserBoot(uss, null); 219 } 220 221 private void finishUserBoot(UserState uss, IIntentReceiver resultTo) { 222 final int userId = uss.mHandle.getIdentifier(); 223 Slog.d(TAG, "Finishing user boot " + userId); 224 synchronized (mService) { 225 // Bail if we ended up with a stale user 226 if (mStartedUsers.get(userId) != uss) return; 227 228 // We always walk through all the user lifecycle states to send 229 // consistent developer events. We step into RUNNING_LOCKED here, 230 // but we might immediately step into RUNNING below if the user 231 // storage is already unlocked. 232 if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) { 233 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null); 234 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 235 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT 236 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 237 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null, 238 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED }, 239 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId); 240 } 241 242 // We need to delay unlocking managed profiles until the parent user 243 // is also unlocked. 244 if (getUserManager().isManagedProfile(userId)) { 245 final UserInfo parent = getUserManager().getProfileParent(userId); 246 if (parent != null 247 && isUserRunningLocked(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) { 248 Slog.d(TAG, "User " + userId + " (parent " + parent.id 249 + "): attempting unlock because parent is unlocked"); 250 maybeUnlockUser(userId); 251 } else { 252 String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id); 253 Slog.d(TAG, "User " + userId + " (parent " + parentId 254 + "): delaying unlock because parent is locked"); 255 } 256 } else { 257 maybeUnlockUser(userId); 258 } 259 } 260 } 261 262 /** 263 * Step from {@link UserState#STATE_RUNNING_LOCKED} to 264 * {@link UserState#STATE_RUNNING_UNLOCKING}. 265 */ 266 private void finishUserUnlocking(final UserState uss) { 267 final int userId = uss.mHandle.getIdentifier(); 268 synchronized (mService) { 269 // Bail if we ended up with a stale user 270 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return; 271 272 // Only keep marching forward if user is actually unlocked 273 if (!StorageManager.isUserKeyUnlocked(userId)) return; 274 275 if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) { 276 uss.mUnlockProgress.start(); 277 278 // Prepare app storage before we go any further 279 uss.mUnlockProgress.setProgress(5, 280 mService.mContext.getString(R.string.android_start_title)); 281 mUserManager.onBeforeUnlockUser(userId); 282 uss.mUnlockProgress.setProgress(20); 283 284 // Dispatch unlocked to system services; when fully dispatched, 285 // that calls through to the next "unlocked" phase 286 mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss) 287 .sendToTarget(); 288 } 289 } 290 } 291 292 /** 293 * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to 294 * {@link UserState#STATE_RUNNING_UNLOCKED}. 295 */ 296 void finishUserUnlocked(final UserState uss) { 297 final int userId = uss.mHandle.getIdentifier(); 298 synchronized (mService) { 299 // Bail if we ended up with a stale user 300 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return; 301 302 // Only keep marching forward if user is actually unlocked 303 if (!StorageManager.isUserKeyUnlocked(userId)) return; 304 305 if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) { 306 uss.mUnlockProgress.finish(); 307 308 // Dispatch unlocked to external apps 309 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED); 310 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 311 unlockedIntent.addFlags( 312 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND); 313 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null, 314 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID, 315 userId); 316 317 if (getUserInfo(userId).isManagedProfile()) { 318 UserInfo parent = getUserManager().getProfileParent(userId); 319 if (parent != null) { 320 final Intent profileUnlockedIntent = new Intent( 321 Intent.ACTION_MANAGED_PROFILE_UNLOCKED); 322 profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId)); 323 profileUnlockedIntent.addFlags( 324 Intent.FLAG_RECEIVER_REGISTERED_ONLY 325 | Intent.FLAG_RECEIVER_FOREGROUND); 326 mService.broadcastIntentLocked(null, null, profileUnlockedIntent, 327 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 328 null, false, false, MY_PID, SYSTEM_UID, 329 parent.id); 330 } 331 } 332 333 // Send PRE_BOOT broadcasts if user fingerprint changed; we 334 // purposefully block sending BOOT_COMPLETED until after all 335 // PRE_BOOT receivers are finished to avoid ANR'ing apps 336 final UserInfo info = getUserInfo(userId); 337 if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) { 338 new PreBootBroadcaster(mService, userId, null) { 339 @Override 340 public void onFinished() { 341 finishUserUnlockedCompleted(uss); 342 } 343 }.sendNext(); 344 } else { 345 finishUserUnlockedCompleted(uss); 346 } 347 } 348 } 349 } 350 351 private void finishUserUnlockedCompleted(UserState uss) { 352 final int userId = uss.mHandle.getIdentifier(); 353 synchronized (mService) { 354 // Bail if we ended up with a stale user 355 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return; 356 final UserInfo userInfo = getUserInfo(userId); 357 if (userInfo == null) { 358 return; 359 } 360 361 // Only keep marching forward if user is actually unlocked 362 if (!StorageManager.isUserKeyUnlocked(userId)) return; 363 364 // Remember that we logged in 365 mUserManager.onUserLoggedIn(userId); 366 367 if (!userInfo.isInitialized()) { 368 if (userId != UserHandle.USER_SYSTEM) { 369 Slog.d(TAG, "Initializing user #" + userId); 370 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE); 371 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 372 mService.broadcastIntentLocked(null, null, intent, null, 373 new IIntentReceiver.Stub() { 374 @Override 375 public void performReceive(Intent intent, int resultCode, 376 String data, Bundle extras, boolean ordered, 377 boolean sticky, int sendingUser) { 378 // Note: performReceive is called with mService lock held 379 getUserManager().makeInitialized(userInfo.id); 380 } 381 }, 0, null, null, null, AppOpsManager.OP_NONE, 382 null, true, false, MY_PID, SYSTEM_UID, userId); 383 } 384 } 385 386 Slog.d(TAG, "Sending BOOT_COMPLETE user #" + userId); 387 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 388 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 389 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT 390 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 391 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null, 392 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED }, 393 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId); 394 } 395 } 396 397 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) { 398 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 399 != PackageManager.PERMISSION_GRANTED) { 400 String msg = "Permission Denial: switchUser() from pid=" 401 + Binder.getCallingPid() 402 + ", uid=" + Binder.getCallingUid() 403 + " requires " + INTERACT_ACROSS_USERS_FULL; 404 Slog.w(TAG, msg); 405 throw new SecurityException(msg); 406 } 407 if (userId < 0 || userId == UserHandle.USER_SYSTEM) { 408 throw new IllegalArgumentException("Can't stop system user " + userId); 409 } 410 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, 411 userId); 412 synchronized (mService) { 413 return stopUsersLocked(userId, force, callback); 414 } 415 } 416 417 /** 418 * Stops the user along with its related users. The method calls 419 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped. 420 */ 421 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) { 422 if (userId == UserHandle.USER_SYSTEM) { 423 return USER_OP_ERROR_IS_SYSTEM; 424 } 425 if (isCurrentUserLocked(userId)) { 426 return USER_OP_IS_CURRENT; 427 } 428 int[] usersToStop = getUsersToStopLocked(userId); 429 // If one of related users is system or current, no related users should be stopped 430 for (int i = 0; i < usersToStop.length; i++) { 431 int relatedUserId = usersToStop[i]; 432 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) { 433 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user " 434 + relatedUserId); 435 // We still need to stop the requested user if it's a force stop. 436 if (force) { 437 Slog.i(TAG, 438 "Force stop user " + userId + ". Related users will not be stopped"); 439 stopSingleUserLocked(userId, callback); 440 return USER_OP_SUCCESS; 441 } 442 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP; 443 } 444 } 445 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop)); 446 for (int userIdToStop : usersToStop) { 447 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null); 448 } 449 return USER_OP_SUCCESS; 450 } 451 452 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) { 453 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId); 454 final UserState uss = mStartedUsers.get(userId); 455 if (uss == null) { 456 // User is not started, nothing to do... but we do need to 457 // callback if requested. 458 if (callback != null) { 459 mHandler.post(new Runnable() { 460 @Override 461 public void run() { 462 try { 463 callback.userStopped(userId); 464 } catch (RemoteException e) { 465 } 466 } 467 }); 468 } 469 return; 470 } 471 472 if (callback != null) { 473 uss.mStopCallbacks.add(callback); 474 } 475 476 if (uss.state != UserState.STATE_STOPPING 477 && uss.state != UserState.STATE_SHUTDOWN) { 478 uss.setState(UserState.STATE_STOPPING); 479 updateStartedUserArrayLocked(); 480 481 long ident = Binder.clearCallingIdentity(); 482 try { 483 // We are going to broadcast ACTION_USER_STOPPING and then 484 // once that is done send a final ACTION_SHUTDOWN and then 485 // stop the user. 486 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING); 487 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 488 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 489 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 490 // This is the result receiver for the initial stopping broadcast. 491 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() { 492 @Override 493 public void performReceive(Intent intent, int resultCode, String data, 494 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 495 mHandler.post(new Runnable() { 496 @Override 497 public void run() { 498 finishUserStopping(userId, uss); 499 } 500 }); 501 } 502 }; 503 // Kick things off. 504 mService.broadcastIntentLocked(null, null, stoppingIntent, 505 null, stoppingReceiver, 0, null, null, 506 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, 507 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL); 508 } finally { 509 Binder.restoreCallingIdentity(ident); 510 } 511 } 512 } 513 514 void finishUserStopping(final int userId, final UserState uss) { 515 // On to the next. 516 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN); 517 // This is the result receiver for the final shutdown broadcast. 518 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() { 519 @Override 520 public void performReceive(Intent intent, int resultCode, String data, 521 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 522 mHandler.post(new Runnable() { 523 @Override 524 public void run() { 525 finishUserStopped(uss); 526 } 527 }); 528 } 529 }; 530 531 synchronized (mService) { 532 if (uss.state != UserState.STATE_STOPPING) { 533 // Whoops, we are being started back up. Abort, abort! 534 return; 535 } 536 uss.setState(UserState.STATE_SHUTDOWN); 537 } 538 539 mService.mBatteryStatsService.noteEvent( 540 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH, 541 Integer.toString(userId), userId); 542 mService.mSystemServiceManager.stopUser(userId); 543 544 synchronized (mService) { 545 mService.broadcastIntentLocked(null, null, shutdownIntent, 546 null, shutdownReceiver, 0, null, null, null, 547 AppOpsManager.OP_NONE, 548 null, true, false, MY_PID, SYSTEM_UID, userId); 549 } 550 } 551 552 void finishUserStopped(UserState uss) { 553 final int userId = uss.mHandle.getIdentifier(); 554 boolean stopped; 555 ArrayList<IStopUserCallback> callbacks; 556 synchronized (mService) { 557 callbacks = new ArrayList<>(uss.mStopCallbacks); 558 if (mStartedUsers.get(userId) != uss) { 559 stopped = false; 560 } else if (uss.state != UserState.STATE_SHUTDOWN) { 561 stopped = false; 562 } else { 563 stopped = true; 564 // User can no longer run. 565 mStartedUsers.remove(userId); 566 mUserLru.remove(Integer.valueOf(userId)); 567 updateStartedUserArrayLocked(); 568 569 mService.onUserStoppedLocked(userId); 570 // Clean up all state and processes associated with the user. 571 // Kill all the processes for the user. 572 forceStopUserLocked(userId, "finish user"); 573 } 574 } 575 576 for (int i = 0; i < callbacks.size(); i++) { 577 try { 578 if (stopped) callbacks.get(i).userStopped(userId); 579 else callbacks.get(i).userStopAborted(userId); 580 } catch (RemoteException e) { 581 } 582 } 583 584 if (stopped) { 585 mService.mSystemServiceManager.cleanupUser(userId); 586 synchronized (mService) { 587 mService.mStackSupervisor.removeUserLocked(userId); 588 } 589 // Remove the user if it is ephemeral. 590 if (getUserInfo(userId).isEphemeral()) { 591 mUserManager.removeUser(userId); 592 } 593 } 594 } 595 596 /** 597 * Determines the list of users that should be stopped together with the specified 598 * {@code userId}. The returned list includes {@code userId}. 599 */ 600 private @NonNull int[] getUsersToStopLocked(int userId) { 601 int startedUsersSize = mStartedUsers.size(); 602 IntArray userIds = new IntArray(); 603 userIds.add(userId); 604 synchronized (mUserProfileGroupIdsSelfLocked) { 605 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId, 606 UserInfo.NO_PROFILE_GROUP_ID); 607 for (int i = 0; i < startedUsersSize; i++) { 608 UserState uss = mStartedUsers.valueAt(i); 609 int startedUserId = uss.mHandle.getIdentifier(); 610 // Skip unrelated users (profileGroupId mismatch) 611 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId, 612 UserInfo.NO_PROFILE_GROUP_ID); 613 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID) 614 && (userGroupId == startedUserGroupId); 615 // userId has already been added 616 boolean sameUserId = startedUserId == userId; 617 if (!sameGroup || sameUserId) { 618 continue; 619 } 620 userIds.add(startedUserId); 621 } 622 } 623 return userIds.toArray(); 624 } 625 626 private void forceStopUserLocked(int userId, String reason) { 627 mService.forceStopPackageLocked(null, -1, false, false, true, false, false, 628 userId, reason); 629 Intent intent = new Intent(Intent.ACTION_USER_STOPPED); 630 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 631 | Intent.FLAG_RECEIVER_FOREGROUND); 632 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 633 mService.broadcastIntentLocked(null, null, intent, 634 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 635 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL); 636 } 637 638 /** 639 * Stops the guest or ephemeral user if it has gone to the background. 640 */ 641 private void stopGuestOrEphemeralUserIfBackground() { 642 synchronized (mService) { 643 final int num = mUserLru.size(); 644 for (int i = 0; i < num; i++) { 645 Integer oldUserId = mUserLru.get(i); 646 UserState oldUss = mStartedUsers.get(oldUserId); 647 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId 648 || oldUss.state == UserState.STATE_STOPPING 649 || oldUss.state == UserState.STATE_SHUTDOWN) { 650 continue; 651 } 652 UserInfo userInfo = getUserInfo(oldUserId); 653 if (userInfo.isEphemeral()) { 654 LocalServices.getService(UserManagerInternal.class) 655 .onEphemeralUserStop(oldUserId); 656 } 657 if (userInfo.isGuest() || userInfo.isEphemeral()) { 658 // This is a user to be stopped. 659 stopUsersLocked(oldUserId, true, null); 660 break; 661 } 662 } 663 } 664 } 665 666 void startProfilesLocked() { 667 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked"); 668 List<UserInfo> profiles = getUserManager().getProfiles( 669 mCurrentUserId, false /* enabledOnly */); 670 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size()); 671 for (UserInfo user : profiles) { 672 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED 673 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) { 674 profilesToStart.add(user); 675 } 676 } 677 final int profilesToStartSize = profilesToStart.size(); 678 int i = 0; 679 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) { 680 startUser(profilesToStart.get(i).id, /* foreground= */ false); 681 } 682 if (i < profilesToStartSize) { 683 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS"); 684 } 685 } 686 687 private UserManagerService getUserManager() { 688 UserManagerService userManager = mUserManager; 689 if (userManager == null) { 690 IBinder b = ServiceManager.getService(Context.USER_SERVICE); 691 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b); 692 } 693 return userManager; 694 } 695 696 private IMountService getMountService() { 697 return IMountService.Stub.asInterface(ServiceManager.getService("mount")); 698 } 699 700 /** 701 * Start user, if its not already running. 702 * <p>The user will be brought to the foreground, if {@code foreground} parameter is set. 703 * When starting the user, multiple intents will be broadcast in the following order:</p> 704 * <ul> 705 * <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user 706 * <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing 707 * user and all profiles of this user. Sent only if {@code foreground} parameter is true 708 * <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new 709 * user and all profiles of this user. Sent only if {@code foreground} parameter is true 710 * <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user. 711 * Sent only if {@code foreground} parameter is true 712 * <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers 713 * of the new fg user 714 * <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of 715 * the new user 716 * <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user 717 * <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the 718 * new user. Sent only when the user is booting after a system update. 719 * <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the 720 * new user. Sent only the first time a user is starting. 721 * <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new 722 * user. Indicates that the user has finished booting. 723 * </ul> 724 * 725 * @param userId ID of the user to start 726 * @param foreground true if user should be brought to the foreground 727 * @return true if the user has been successfully started 728 */ 729 boolean startUser(final int userId, final boolean foreground) { 730 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 731 != PackageManager.PERMISSION_GRANTED) { 732 String msg = "Permission Denial: switchUser() from pid=" 733 + Binder.getCallingPid() 734 + ", uid=" + Binder.getCallingUid() 735 + " requires " + INTERACT_ACROSS_USERS_FULL; 736 Slog.w(TAG, msg); 737 throw new SecurityException(msg); 738 } 739 740 Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground); 741 742 final long ident = Binder.clearCallingIdentity(); 743 try { 744 synchronized (mService) { 745 final int oldUserId = mCurrentUserId; 746 if (oldUserId == userId) { 747 return true; 748 } 749 750 mService.mStackSupervisor.setLockTaskModeLocked(null, 751 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false); 752 753 final UserInfo userInfo = getUserInfo(userId); 754 if (userInfo == null) { 755 Slog.w(TAG, "No user info for user #" + userId); 756 return false; 757 } 758 if (foreground && userInfo.isManagedProfile()) { 759 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user"); 760 return false; 761 } 762 763 if (foreground) { 764 mService.mWindowManager.startFreezingScreen( 765 R.anim.screen_user_exit, R.anim.screen_user_enter); 766 } 767 768 boolean needStart = false; 769 770 // If the user we are switching to is not currently started, then 771 // we need to start it now. 772 if (mStartedUsers.get(userId) == null) { 773 mStartedUsers.put(userId, new UserState(UserHandle.of(userId))); 774 updateStartedUserArrayLocked(); 775 needStart = true; 776 } 777 778 final UserState uss = mStartedUsers.get(userId); 779 final Integer userIdInt = userId; 780 mUserLru.remove(userIdInt); 781 mUserLru.add(userIdInt); 782 783 if (foreground) { 784 mCurrentUserId = userId; 785 mService.updateUserConfigurationLocked(); 786 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up 787 updateCurrentProfileIdsLocked(); 788 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds); 789 // Once the internal notion of the active user has switched, we lock the device 790 // with the option to show the user switcher on the keyguard. 791 mService.mWindowManager.lockNow(null); 792 } else { 793 final Integer currentUserIdInt = mCurrentUserId; 794 updateCurrentProfileIdsLocked(); 795 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds); 796 mUserLru.remove(currentUserIdInt); 797 mUserLru.add(currentUserIdInt); 798 } 799 800 // Make sure user is in the started state. If it is currently 801 // stopping, we need to knock that off. 802 if (uss.state == UserState.STATE_STOPPING) { 803 // If we are stopping, we haven't sent ACTION_SHUTDOWN, 804 // so we can just fairly silently bring the user back from 805 // the almost-dead. 806 uss.setState(uss.lastState); 807 updateStartedUserArrayLocked(); 808 needStart = true; 809 } else if (uss.state == UserState.STATE_SHUTDOWN) { 810 // This means ACTION_SHUTDOWN has been sent, so we will 811 // need to treat this as a new boot of the user. 812 uss.setState(UserState.STATE_BOOTING); 813 updateStartedUserArrayLocked(); 814 needStart = true; 815 } 816 817 if (uss.state == UserState.STATE_BOOTING) { 818 // Give user manager a chance to propagate user restrictions 819 // to other services and prepare app storage 820 getUserManager().onBeforeStartUser(userId); 821 822 // Booting up a new user, need to tell system services about it. 823 // Note that this is on the same handler as scheduling of broadcasts, 824 // which is important because it needs to go first. 825 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0)); 826 } 827 828 if (foreground) { 829 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId, 830 oldUserId)); 831 mHandler.removeMessages(REPORT_USER_SWITCH_MSG); 832 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 833 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG, 834 oldUserId, userId, uss)); 835 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG, 836 oldUserId, userId, uss), USER_SWITCH_TIMEOUT); 837 } 838 839 if (needStart) { 840 // Send USER_STARTED broadcast 841 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 842 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 843 | Intent.FLAG_RECEIVER_FOREGROUND); 844 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 845 mService.broadcastIntentLocked(null, null, intent, 846 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 847 null, false, false, MY_PID, SYSTEM_UID, userId); 848 } 849 850 if (foreground) { 851 moveUserToForegroundLocked(uss, oldUserId, userId); 852 } else { 853 mService.mUserController.finishUserBoot(uss); 854 } 855 856 if (needStart) { 857 Intent intent = new Intent(Intent.ACTION_USER_STARTING); 858 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 859 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 860 mService.broadcastIntentLocked(null, null, intent, 861 null, new IIntentReceiver.Stub() { 862 @Override 863 public void performReceive(Intent intent, int resultCode, 864 String data, Bundle extras, boolean ordered, boolean sticky, 865 int sendingUser) throws RemoteException { 866 } 867 }, 0, null, null, 868 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, 869 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL); 870 } 871 } 872 } finally { 873 Binder.restoreCallingIdentity(ident); 874 } 875 876 return true; 877 } 878 879 /** 880 * Start user, if its not already running, and bring it to foreground. 881 */ 882 boolean startUserInForeground(final int userId, Dialog dlg) { 883 boolean result = startUser(userId, /* foreground */ true); 884 dlg.dismiss(); 885 return result; 886 } 887 888 boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) { 889 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 890 != PackageManager.PERMISSION_GRANTED) { 891 String msg = "Permission Denial: unlockUser() from pid=" 892 + Binder.getCallingPid() 893 + ", uid=" + Binder.getCallingUid() 894 + " requires " + INTERACT_ACROSS_USERS_FULL; 895 Slog.w(TAG, msg); 896 throw new SecurityException(msg); 897 } 898 899 final long binderToken = Binder.clearCallingIdentity(); 900 try { 901 return unlockUserCleared(userId, token, secret, listener); 902 } finally { 903 Binder.restoreCallingIdentity(binderToken); 904 } 905 } 906 907 /** 908 * Attempt to unlock user without a credential token. This typically 909 * succeeds when the device doesn't have credential-encrypted storage, or 910 * when the the credential-encrypted storage isn't tied to a user-provided 911 * PIN or pattern. 912 */ 913 boolean maybeUnlockUser(final int userId) { 914 // Try unlocking storage using empty token 915 return unlockUserCleared(userId, null, null, null); 916 } 917 918 private static void notifyFinished(int userId, IProgressListener listener) { 919 if (listener == null) return; 920 try { 921 listener.onFinished(userId, null); 922 } catch (RemoteException ignored) { 923 } 924 } 925 926 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret, 927 IProgressListener listener) { 928 final UserState uss; 929 synchronized (mService) { 930 // Bail if user isn't actually running, otherwise register the given 931 // listener to watch for unlock progress 932 uss = mStartedUsers.get(userId); 933 if (uss == null) { 934 notifyFinished(userId, listener); 935 return false; 936 } else { 937 uss.mUnlockProgress.addListener(listener); 938 } 939 } 940 941 if (!StorageManager.isUserKeyUnlocked(userId)) { 942 final UserInfo userInfo = getUserInfo(userId); 943 final IMountService mountService = getMountService(); 944 try { 945 mountService.unlockUserKey(userId, userInfo.serialNumber, token, secret); 946 } catch (RemoteException | RuntimeException e) { 947 Slog.w(TAG, "Failed to unlock: " + e.getMessage()); 948 notifyFinished(userId, listener); 949 return false; 950 } 951 } 952 953 synchronized (mService) { 954 finishUserUnlocking(uss); 955 956 // We just unlocked a user, so let's now attempt to unlock any 957 // managed profiles under that user. 958 for (int i = 0; i < mStartedUsers.size(); i++) { 959 final int testUserId = mStartedUsers.keyAt(i); 960 final UserInfo parent = getUserManager().getProfileParent(testUserId); 961 if (parent != null && parent.id == userId && testUserId != userId) { 962 Slog.d(TAG, "User " + testUserId + " (parent " + parent.id 963 + "): attempting unlock because parent was just unlocked"); 964 maybeUnlockUser(testUserId); 965 } 966 } 967 } 968 969 return true; 970 } 971 972 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) { 973 // The dialog will show and then initiate the user switch by calling startUserInForeground 974 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first, 975 fromToUserPair.second, true /* above system */); 976 d.show(); 977 } 978 979 void dispatchForegroundProfileChanged(int userId) { 980 final int observerCount = mUserSwitchObservers.beginBroadcast(); 981 for (int i = 0; i < observerCount; i++) { 982 try { 983 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId); 984 } catch (RemoteException e) { 985 // Ignore 986 } 987 } 988 mUserSwitchObservers.finishBroadcast(); 989 } 990 991 /** Called on handler thread */ 992 void dispatchUserSwitchComplete(int userId) { 993 final int observerCount = mUserSwitchObservers.beginBroadcast(); 994 for (int i = 0; i < observerCount; i++) { 995 try { 996 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId); 997 } catch (RemoteException e) { 998 } 999 } 1000 mUserSwitchObservers.finishBroadcast(); 1001 } 1002 1003 private void stopBackgroundUsersIfEnforced(int oldUserId) { 1004 // Never stop system user 1005 if (oldUserId == UserHandle.USER_SYSTEM) { 1006 return; 1007 } 1008 // For now, only check for user restriction. Additional checks can be added here 1009 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND, 1010 oldUserId); 1011 if (!disallowRunInBg) { 1012 return; 1013 } 1014 synchronized (mService) { 1015 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId 1016 + " and related users"); 1017 stopUsersLocked(oldUserId, false, null); 1018 } 1019 } 1020 1021 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) { 1022 synchronized (mService) { 1023 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId); 1024 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 1025 } 1026 } 1027 1028 void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) { 1029 Slog.d(TAG, "Dispatch onUserSwitching oldUser #" + oldUserId + " newUser #" + newUserId); 1030 final int observerCount = mUserSwitchObservers.beginBroadcast(); 1031 if (observerCount > 0) { 1032 final IRemoteCallback callback = new IRemoteCallback.Stub() { 1033 int mCount = 0; 1034 @Override 1035 public void sendResult(Bundle data) throws RemoteException { 1036 synchronized (mService) { 1037 if (mCurUserSwitchCallback == this) { 1038 mCount++; 1039 if (mCount == observerCount) { 1040 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 1041 } 1042 } 1043 } 1044 } 1045 }; 1046 synchronized (mService) { 1047 uss.switching = true; 1048 mCurUserSwitchCallback = callback; 1049 } 1050 for (int i = 0; i < observerCount; i++) { 1051 try { 1052 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching( 1053 newUserId, callback); 1054 } catch (RemoteException e) { 1055 } 1056 } 1057 } else { 1058 synchronized (mService) { 1059 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 1060 } 1061 } 1062 mUserSwitchObservers.finishBroadcast(); 1063 } 1064 1065 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) { 1066 mCurUserSwitchCallback = null; 1067 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 1068 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG, 1069 oldUserId, newUserId, uss)); 1070 } 1071 1072 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) { 1073 Slog.d(TAG, "Continue user switch oldUser #" + oldUserId + ", newUser #" + newUserId); 1074 synchronized (mService) { 1075 mService.mWindowManager.stopFreezingScreen(); 1076 } 1077 uss.switching = false; 1078 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG); 1079 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG, 1080 newUserId, 0)); 1081 stopGuestOrEphemeralUserIfBackground(); 1082 stopBackgroundUsersIfEnforced(oldUserId); 1083 } 1084 1085 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) { 1086 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss); 1087 if (homeInFront) { 1088 mService.startHomeActivityLocked(newUserId, "moveUserToForeground"); 1089 } else { 1090 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked(); 1091 } 1092 EventLogTags.writeAmSwitchUser(newUserId); 1093 sendUserSwitchBroadcastsLocked(oldUserId, newUserId); 1094 } 1095 1096 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) { 1097 long ident = Binder.clearCallingIdentity(); 1098 try { 1099 Intent intent; 1100 if (oldUserId >= 0) { 1101 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user 1102 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false); 1103 int count = profiles.size(); 1104 for (int i = 0; i < count; i++) { 1105 int profileUserId = profiles.get(i).id; 1106 intent = new Intent(Intent.ACTION_USER_BACKGROUND); 1107 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 1108 | Intent.FLAG_RECEIVER_FOREGROUND); 1109 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 1110 mService.broadcastIntentLocked(null, null, intent, 1111 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 1112 null, false, false, MY_PID, SYSTEM_UID, profileUserId); 1113 } 1114 } 1115 if (newUserId >= 0) { 1116 // Send USER_FOREGROUND broadcast to all profiles of the incoming user 1117 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false); 1118 int count = profiles.size(); 1119 for (int i = 0; i < count; i++) { 1120 int profileUserId = profiles.get(i).id; 1121 intent = new Intent(Intent.ACTION_USER_FOREGROUND); 1122 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 1123 | Intent.FLAG_RECEIVER_FOREGROUND); 1124 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 1125 mService.broadcastIntentLocked(null, null, intent, 1126 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 1127 null, false, false, MY_PID, SYSTEM_UID, profileUserId); 1128 } 1129 intent = new Intent(Intent.ACTION_USER_SWITCHED); 1130 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 1131 | Intent.FLAG_RECEIVER_FOREGROUND); 1132 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId); 1133 mService.broadcastIntentLocked(null, null, intent, 1134 null, null, 0, null, null, 1135 new String[] {android.Manifest.permission.MANAGE_USERS}, 1136 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID, 1137 UserHandle.USER_ALL); 1138 } 1139 } finally { 1140 Binder.restoreCallingIdentity(ident); 1141 } 1142 } 1143 1144 1145 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 1146 int allowMode, String name, String callerPackage) { 1147 final int callingUserId = UserHandle.getUserId(callingUid); 1148 if (callingUserId == userId) { 1149 return userId; 1150 } 1151 1152 // Note that we may be accessing mCurrentUserId outside of a lock... 1153 // shouldn't be a big deal, if this is being called outside 1154 // of a locked context there is intrinsically a race with 1155 // the value the caller will receive and someone else changing it. 1156 // We assume that USER_CURRENT_OR_SELF will use the current user; later 1157 // we will switch to the calling user if access to the current user fails. 1158 int targetUserId = unsafeConvertIncomingUserLocked(userId); 1159 1160 if (callingUid != 0 && callingUid != SYSTEM_UID) { 1161 final boolean allow; 1162 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 1163 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 1164 // If the caller has this permission, they always pass go. And collect $200. 1165 allow = true; 1166 } else if (allowMode == ALLOW_FULL_ONLY) { 1167 // We require full access, sucks to be you. 1168 allow = false; 1169 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 1170 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) { 1171 // If the caller does not have either permission, they are always doomed. 1172 allow = false; 1173 } else if (allowMode == ALLOW_NON_FULL) { 1174 // We are blanket allowing non-full access, you lucky caller! 1175 allow = true; 1176 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) { 1177 // We may or may not allow this depending on whether the two users are 1178 // in the same profile. 1179 allow = isSameProfileGroup(callingUserId, targetUserId); 1180 } else { 1181 throw new IllegalArgumentException("Unknown mode: " + allowMode); 1182 } 1183 if (!allow) { 1184 if (userId == UserHandle.USER_CURRENT_OR_SELF) { 1185 // In this case, they would like to just execute as their 1186 // owner user instead of failing. 1187 targetUserId = callingUserId; 1188 } else { 1189 StringBuilder builder = new StringBuilder(128); 1190 builder.append("Permission Denial: "); 1191 builder.append(name); 1192 if (callerPackage != null) { 1193 builder.append(" from "); 1194 builder.append(callerPackage); 1195 } 1196 builder.append(" asks to run as user "); 1197 builder.append(userId); 1198 builder.append(" but is calling from user "); 1199 builder.append(UserHandle.getUserId(callingUid)); 1200 builder.append("; this requires "); 1201 builder.append(INTERACT_ACROSS_USERS_FULL); 1202 if (allowMode != ALLOW_FULL_ONLY) { 1203 builder.append(" or "); 1204 builder.append(INTERACT_ACROSS_USERS); 1205 } 1206 String msg = builder.toString(); 1207 Slog.w(TAG, msg); 1208 throw new SecurityException(msg); 1209 } 1210 } 1211 } 1212 if (!allowAll && targetUserId < 0) { 1213 throw new IllegalArgumentException( 1214 "Call does not support special user #" + targetUserId); 1215 } 1216 // Check shell permission 1217 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) { 1218 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) { 1219 throw new SecurityException("Shell does not have permission to access user " 1220 + targetUserId + "\n " + Debug.getCallers(3)); 1221 } 1222 } 1223 return targetUserId; 1224 } 1225 1226 int unsafeConvertIncomingUserLocked(int userId) { 1227 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF) 1228 ? getCurrentUserIdLocked(): userId; 1229 } 1230 1231 void registerUserSwitchObserver(IUserSwitchObserver observer) { 1232 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 1233 != PackageManager.PERMISSION_GRANTED) { 1234 final String msg = "Permission Denial: registerUserSwitchObserver() from pid=" 1235 + Binder.getCallingPid() 1236 + ", uid=" + Binder.getCallingUid() 1237 + " requires " + INTERACT_ACROSS_USERS_FULL; 1238 Slog.w(TAG, msg); 1239 throw new SecurityException(msg); 1240 } 1241 1242 mUserSwitchObservers.register(observer); 1243 } 1244 1245 void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 1246 mUserSwitchObservers.unregister(observer); 1247 } 1248 1249 UserState getStartedUserStateLocked(int userId) { 1250 return mStartedUsers.get(userId); 1251 } 1252 1253 boolean hasStartedUserState(int userId) { 1254 return mStartedUsers.get(userId) != null; 1255 } 1256 1257 private void updateStartedUserArrayLocked() { 1258 int num = 0; 1259 for (int i = 0; i < mStartedUsers.size(); i++) { 1260 UserState uss = mStartedUsers.valueAt(i); 1261 // This list does not include stopping users. 1262 if (uss.state != UserState.STATE_STOPPING 1263 && uss.state != UserState.STATE_SHUTDOWN) { 1264 num++; 1265 } 1266 } 1267 mStartedUserArray = new int[num]; 1268 num = 0; 1269 for (int i = 0; i < mStartedUsers.size(); i++) { 1270 UserState uss = mStartedUsers.valueAt(i); 1271 if (uss.state != UserState.STATE_STOPPING 1272 && uss.state != UserState.STATE_SHUTDOWN) { 1273 mStartedUserArray[num++] = mStartedUsers.keyAt(i); 1274 } 1275 } 1276 } 1277 1278 void sendBootCompletedLocked(IIntentReceiver resultTo) { 1279 for (int i = 0; i < mStartedUsers.size(); i++) { 1280 UserState uss = mStartedUsers.valueAt(i); 1281 finishUserBoot(uss, resultTo); 1282 } 1283 } 1284 1285 void onSystemReady() { 1286 updateCurrentProfileIdsLocked(); 1287 } 1288 1289 /** 1290 * Refreshes the list of users related to the current user when either a 1291 * user switch happens or when a new related user is started in the 1292 * background. 1293 */ 1294 private void updateCurrentProfileIdsLocked() { 1295 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId, 1296 false /* enabledOnly */); 1297 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null 1298 for (int i = 0; i < currentProfileIds.length; i++) { 1299 currentProfileIds[i] = profiles.get(i).id; 1300 } 1301 mCurrentProfileIds = currentProfileIds; 1302 1303 synchronized (mUserProfileGroupIdsSelfLocked) { 1304 mUserProfileGroupIdsSelfLocked.clear(); 1305 final List<UserInfo> users = getUserManager().getUsers(false); 1306 for (int i = 0; i < users.size(); i++) { 1307 UserInfo user = users.get(i); 1308 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 1309 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId); 1310 } 1311 } 1312 } 1313 } 1314 1315 int[] getStartedUserArrayLocked() { 1316 return mStartedUserArray; 1317 } 1318 1319 boolean isUserRunningLocked(int userId, int flags) { 1320 UserState state = getStartedUserStateLocked(userId); 1321 if (state == null) { 1322 return false; 1323 } 1324 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) { 1325 return true; 1326 } 1327 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) { 1328 switch (state.state) { 1329 case UserState.STATE_BOOTING: 1330 case UserState.STATE_RUNNING_LOCKED: 1331 return true; 1332 default: 1333 return false; 1334 } 1335 } 1336 if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) { 1337 switch (state.state) { 1338 case UserState.STATE_RUNNING_UNLOCKING: 1339 case UserState.STATE_RUNNING_UNLOCKED: 1340 return true; 1341 default: 1342 return false; 1343 } 1344 } 1345 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) { 1346 switch (state.state) { 1347 case UserState.STATE_RUNNING_UNLOCKED: 1348 return true; 1349 default: 1350 return false; 1351 } 1352 } 1353 1354 // One way or another, we're running! 1355 return true; 1356 } 1357 1358 UserInfo getCurrentUser() { 1359 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS) 1360 != PackageManager.PERMISSION_GRANTED) && ( 1361 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 1362 != PackageManager.PERMISSION_GRANTED)) { 1363 String msg = "Permission Denial: getCurrentUser() from pid=" 1364 + Binder.getCallingPid() 1365 + ", uid=" + Binder.getCallingUid() 1366 + " requires " + INTERACT_ACROSS_USERS; 1367 Slog.w(TAG, msg); 1368 throw new SecurityException(msg); 1369 } 1370 synchronized (mService) { 1371 return getCurrentUserLocked(); 1372 } 1373 } 1374 1375 UserInfo getCurrentUserLocked() { 1376 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId; 1377 return getUserInfo(userId); 1378 } 1379 1380 int getCurrentOrTargetUserIdLocked() { 1381 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId; 1382 } 1383 1384 int getCurrentUserIdLocked() { 1385 return mCurrentUserId; 1386 } 1387 1388 private boolean isCurrentUserLocked(int userId) { 1389 return userId == getCurrentOrTargetUserIdLocked(); 1390 } 1391 1392 int setTargetUserIdLocked(int targetUserId) { 1393 return mTargetUserId = targetUserId; 1394 } 1395 1396 int[] getUsers() { 1397 UserManagerService ums = getUserManager(); 1398 return ums != null ? ums.getUserIds() : new int[] { 0 }; 1399 } 1400 1401 UserInfo getUserInfo(int userId) { 1402 return getUserManager().getUserInfo(userId); 1403 } 1404 1405 int[] getUserIds() { 1406 return getUserManager().getUserIds(); 1407 } 1408 1409 boolean exists(int userId) { 1410 return getUserManager().exists(userId); 1411 } 1412 1413 boolean hasUserRestriction(String restriction, int userId) { 1414 return getUserManager().hasUserRestriction(restriction, userId); 1415 } 1416 1417 Set<Integer> getProfileIds(int userId) { 1418 Set<Integer> userIds = new HashSet<>(); 1419 final List<UserInfo> profiles = getUserManager().getProfiles(userId, 1420 false /* enabledOnly */); 1421 for (UserInfo user : profiles) { 1422 userIds.add(user.id); 1423 } 1424 return userIds; 1425 } 1426 1427 boolean isSameProfileGroup(int callingUserId, int targetUserId) { 1428 synchronized (mUserProfileGroupIdsSelfLocked) { 1429 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId, 1430 UserInfo.NO_PROFILE_GROUP_ID); 1431 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId, 1432 UserInfo.NO_PROFILE_GROUP_ID); 1433 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID 1434 && callingProfile == targetProfile; 1435 } 1436 } 1437 1438 boolean isCurrentProfileLocked(int userId) { 1439 return ArrayUtils.contains(mCurrentProfileIds, userId); 1440 } 1441 1442 int[] getCurrentProfileIdsLocked() { 1443 return mCurrentProfileIds; 1444 } 1445 1446 /** 1447 * Returns whether the given user requires credential entry at this time. This is used to 1448 * intercept activity launches for work apps when the Work Challenge is present. 1449 */ 1450 boolean shouldConfirmCredentials(int userId) { 1451 synchronized (mService) { 1452 if (mStartedUsers.get(userId) == null) { 1453 return false; 1454 } 1455 } 1456 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) { 1457 return false; 1458 } 1459 final KeyguardManager km = (KeyguardManager) mService.mContext 1460 .getSystemService(KEYGUARD_SERVICE); 1461 return km.isDeviceLocked(userId); 1462 } 1463 1464 boolean isLockScreenDisabled(@UserIdInt int userId) { 1465 return mLockPatternUtils.isLockScreenDisabled(userId); 1466 } 1467 1468 void dump(PrintWriter pw, boolean dumpAll) { 1469 pw.println(" mStartedUsers:"); 1470 for (int i = 0; i < mStartedUsers.size(); i++) { 1471 UserState uss = mStartedUsers.valueAt(i); 1472 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier()); 1473 pw.print(": "); uss.dump("", pw); 1474 } 1475 pw.print(" mStartedUserArray: ["); 1476 for (int i = 0; i < mStartedUserArray.length; i++) { 1477 if (i > 0) pw.print(", "); 1478 pw.print(mStartedUserArray[i]); 1479 } 1480 pw.println("]"); 1481 pw.print(" mUserLru: ["); 1482 for (int i = 0; i < mUserLru.size(); i++) { 1483 if (i > 0) pw.print(", "); 1484 pw.print(mUserLru.get(i)); 1485 } 1486 pw.println("]"); 1487 if (dumpAll) { 1488 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray)); 1489 } 1490 synchronized (mUserProfileGroupIdsSelfLocked) { 1491 if (mUserProfileGroupIdsSelfLocked.size() > 0) { 1492 pw.println(" mUserProfileGroupIds:"); 1493 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) { 1494 pw.print(" User #"); 1495 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i)); 1496 pw.print(" -> profile #"); 1497 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i)); 1498 } 1499 } 1500 } 1501 } 1502} 1503