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