UserController.java revision cca1c654f8d0d2ec4671e3b1342a2db5a5256eab
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 // Clear broadcast queue for the user to avoid delivering stale broadcasts 504 mService.clearBroadcastQueueForUserLocked(userId); 505 // Kick things off. 506 mService.broadcastIntentLocked(null, null, stoppingIntent, 507 null, stoppingReceiver, 0, null, null, 508 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, 509 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL); 510 } finally { 511 Binder.restoreCallingIdentity(ident); 512 } 513 } 514 } 515 516 void finishUserStopping(final int userId, final UserState uss) { 517 // On to the next. 518 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN); 519 // This is the result receiver for the final shutdown broadcast. 520 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() { 521 @Override 522 public void performReceive(Intent intent, int resultCode, String data, 523 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 524 mHandler.post(new Runnable() { 525 @Override 526 public void run() { 527 finishUserStopped(uss); 528 } 529 }); 530 } 531 }; 532 533 synchronized (mService) { 534 if (uss.state != UserState.STATE_STOPPING) { 535 // Whoops, we are being started back up. Abort, abort! 536 return; 537 } 538 uss.setState(UserState.STATE_SHUTDOWN); 539 } 540 541 mService.mBatteryStatsService.noteEvent( 542 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH, 543 Integer.toString(userId), userId); 544 mService.mSystemServiceManager.stopUser(userId); 545 546 synchronized (mService) { 547 mService.broadcastIntentLocked(null, null, shutdownIntent, 548 null, shutdownReceiver, 0, null, null, null, 549 AppOpsManager.OP_NONE, 550 null, true, false, MY_PID, SYSTEM_UID, userId); 551 } 552 } 553 554 void finishUserStopped(UserState uss) { 555 final int userId = uss.mHandle.getIdentifier(); 556 boolean stopped; 557 ArrayList<IStopUserCallback> callbacks; 558 synchronized (mService) { 559 callbacks = new ArrayList<>(uss.mStopCallbacks); 560 if (mStartedUsers.get(userId) != uss) { 561 stopped = false; 562 } else if (uss.state != UserState.STATE_SHUTDOWN) { 563 stopped = false; 564 } else { 565 stopped = true; 566 // User can no longer run. 567 mStartedUsers.remove(userId); 568 mUserLru.remove(Integer.valueOf(userId)); 569 updateStartedUserArrayLocked(); 570 571 mService.onUserStoppedLocked(userId); 572 // Clean up all state and processes associated with the user. 573 // Kill all the processes for the user. 574 forceStopUserLocked(userId, "finish user"); 575 } 576 } 577 578 for (int i = 0; i < callbacks.size(); i++) { 579 try { 580 if (stopped) callbacks.get(i).userStopped(userId); 581 else callbacks.get(i).userStopAborted(userId); 582 } catch (RemoteException e) { 583 } 584 } 585 586 if (stopped) { 587 mService.mSystemServiceManager.cleanupUser(userId); 588 synchronized (mService) { 589 mService.mStackSupervisor.removeUserLocked(userId); 590 } 591 // Remove the user if it is ephemeral. 592 if (getUserInfo(userId).isEphemeral()) { 593 mUserManager.removeUser(userId); 594 } 595 } 596 } 597 598 /** 599 * Determines the list of users that should be stopped together with the specified 600 * {@code userId}. The returned list includes {@code userId}. 601 */ 602 private @NonNull int[] getUsersToStopLocked(int userId) { 603 int startedUsersSize = mStartedUsers.size(); 604 IntArray userIds = new IntArray(); 605 userIds.add(userId); 606 synchronized (mUserProfileGroupIdsSelfLocked) { 607 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId, 608 UserInfo.NO_PROFILE_GROUP_ID); 609 for (int i = 0; i < startedUsersSize; i++) { 610 UserState uss = mStartedUsers.valueAt(i); 611 int startedUserId = uss.mHandle.getIdentifier(); 612 // Skip unrelated users (profileGroupId mismatch) 613 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId, 614 UserInfo.NO_PROFILE_GROUP_ID); 615 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID) 616 && (userGroupId == startedUserGroupId); 617 // userId has already been added 618 boolean sameUserId = startedUserId == userId; 619 if (!sameGroup || sameUserId) { 620 continue; 621 } 622 userIds.add(startedUserId); 623 } 624 } 625 return userIds.toArray(); 626 } 627 628 private void forceStopUserLocked(int userId, String reason) { 629 mService.forceStopPackageLocked(null, -1, false, false, true, false, false, 630 userId, reason); 631 Intent intent = new Intent(Intent.ACTION_USER_STOPPED); 632 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 633 | Intent.FLAG_RECEIVER_FOREGROUND); 634 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 635 mService.broadcastIntentLocked(null, null, intent, 636 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 637 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL); 638 } 639 640 /** 641 * Stops the guest or ephemeral user if it has gone to the background. 642 */ 643 private void stopGuestOrEphemeralUserIfBackground() { 644 synchronized (mService) { 645 final int num = mUserLru.size(); 646 for (int i = 0; i < num; i++) { 647 Integer oldUserId = mUserLru.get(i); 648 UserState oldUss = mStartedUsers.get(oldUserId); 649 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId 650 || oldUss.state == UserState.STATE_STOPPING 651 || oldUss.state == UserState.STATE_SHUTDOWN) { 652 continue; 653 } 654 UserInfo userInfo = getUserInfo(oldUserId); 655 if (userInfo.isEphemeral()) { 656 LocalServices.getService(UserManagerInternal.class) 657 .onEphemeralUserStop(oldUserId); 658 } 659 if (userInfo.isGuest() || userInfo.isEphemeral()) { 660 // This is a user to be stopped. 661 stopUsersLocked(oldUserId, true, null); 662 break; 663 } 664 } 665 } 666 } 667 668 void startProfilesLocked() { 669 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked"); 670 List<UserInfo> profiles = getUserManager().getProfiles( 671 mCurrentUserId, false /* enabledOnly */); 672 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size()); 673 for (UserInfo user : profiles) { 674 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED 675 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) { 676 profilesToStart.add(user); 677 } 678 } 679 final int profilesToStartSize = profilesToStart.size(); 680 int i = 0; 681 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) { 682 startUser(profilesToStart.get(i).id, /* foreground= */ false); 683 } 684 if (i < profilesToStartSize) { 685 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS"); 686 } 687 } 688 689 private UserManagerService getUserManager() { 690 UserManagerService userManager = mUserManager; 691 if (userManager == null) { 692 IBinder b = ServiceManager.getService(Context.USER_SERVICE); 693 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b); 694 } 695 return userManager; 696 } 697 698 private IMountService getMountService() { 699 return IMountService.Stub.asInterface(ServiceManager.getService("mount")); 700 } 701 702 /** 703 * Start user, if its not already running. 704 * <p>The user will be brought to the foreground, if {@code foreground} parameter is set. 705 * When starting the user, multiple intents will be broadcast in the following order:</p> 706 * <ul> 707 * <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user 708 * <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing 709 * user and all profiles of this user. Sent only if {@code foreground} parameter is true 710 * <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new 711 * user and all profiles of this user. Sent only if {@code foreground} parameter is true 712 * <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user. 713 * Sent only if {@code foreground} parameter is true 714 * <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers 715 * of the new fg user 716 * <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of 717 * the new user 718 * <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user 719 * <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the 720 * new user. Sent only when the user is booting after a system update. 721 * <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the 722 * new user. Sent only the first time a user is starting. 723 * <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new 724 * user. Indicates that the user has finished booting. 725 * </ul> 726 * 727 * @param userId ID of the user to start 728 * @param foreground true if user should be brought to the foreground 729 * @return true if the user has been successfully started 730 */ 731 boolean startUser(final int userId, final boolean foreground) { 732 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 733 != PackageManager.PERMISSION_GRANTED) { 734 String msg = "Permission Denial: switchUser() from pid=" 735 + Binder.getCallingPid() 736 + ", uid=" + Binder.getCallingUid() 737 + " requires " + INTERACT_ACROSS_USERS_FULL; 738 Slog.w(TAG, msg); 739 throw new SecurityException(msg); 740 } 741 742 Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground); 743 744 final long ident = Binder.clearCallingIdentity(); 745 try { 746 synchronized (mService) { 747 final int oldUserId = mCurrentUserId; 748 if (oldUserId == userId) { 749 return true; 750 } 751 752 mService.mStackSupervisor.setLockTaskModeLocked(null, 753 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false); 754 755 final UserInfo userInfo = getUserInfo(userId); 756 if (userInfo == null) { 757 Slog.w(TAG, "No user info for user #" + userId); 758 return false; 759 } 760 if (foreground && userInfo.isManagedProfile()) { 761 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user"); 762 return false; 763 } 764 765 if (foreground) { 766 mService.mWindowManager.startFreezingScreen( 767 R.anim.screen_user_exit, R.anim.screen_user_enter); 768 } 769 770 boolean needStart = false; 771 772 // If the user we are switching to is not currently started, then 773 // we need to start it now. 774 if (mStartedUsers.get(userId) == null) { 775 mStartedUsers.put(userId, new UserState(UserHandle.of(userId))); 776 updateStartedUserArrayLocked(); 777 needStart = true; 778 } 779 780 final UserState uss = mStartedUsers.get(userId); 781 final Integer userIdInt = userId; 782 mUserLru.remove(userIdInt); 783 mUserLru.add(userIdInt); 784 785 if (foreground) { 786 mCurrentUserId = userId; 787 mService.updateUserConfigurationLocked(); 788 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up 789 updateCurrentProfileIdsLocked(); 790 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds); 791 // Once the internal notion of the active user has switched, we lock the device 792 // with the option to show the user switcher on the keyguard. 793 mService.mWindowManager.lockNow(null); 794 } else { 795 final Integer currentUserIdInt = mCurrentUserId; 796 updateCurrentProfileIdsLocked(); 797 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds); 798 mUserLru.remove(currentUserIdInt); 799 mUserLru.add(currentUserIdInt); 800 } 801 802 // Make sure user is in the started state. If it is currently 803 // stopping, we need to knock that off. 804 if (uss.state == UserState.STATE_STOPPING) { 805 // If we are stopping, we haven't sent ACTION_SHUTDOWN, 806 // so we can just fairly silently bring the user back from 807 // the almost-dead. 808 uss.setState(uss.lastState); 809 updateStartedUserArrayLocked(); 810 needStart = true; 811 } else if (uss.state == UserState.STATE_SHUTDOWN) { 812 // This means ACTION_SHUTDOWN has been sent, so we will 813 // need to treat this as a new boot of the user. 814 uss.setState(UserState.STATE_BOOTING); 815 updateStartedUserArrayLocked(); 816 needStart = true; 817 } 818 819 if (uss.state == UserState.STATE_BOOTING) { 820 // Give user manager a chance to propagate user restrictions 821 // to other services and prepare app storage 822 getUserManager().onBeforeStartUser(userId); 823 824 // Booting up a new user, need to tell system services about it. 825 // Note that this is on the same handler as scheduling of broadcasts, 826 // which is important because it needs to go first. 827 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0)); 828 } 829 830 if (foreground) { 831 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId, 832 oldUserId)); 833 mHandler.removeMessages(REPORT_USER_SWITCH_MSG); 834 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 835 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG, 836 oldUserId, userId, uss)); 837 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG, 838 oldUserId, userId, uss), USER_SWITCH_TIMEOUT); 839 } 840 841 if (needStart) { 842 // Send USER_STARTED broadcast 843 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 844 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 845 | Intent.FLAG_RECEIVER_FOREGROUND); 846 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 847 mService.broadcastIntentLocked(null, null, intent, 848 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 849 null, false, false, MY_PID, SYSTEM_UID, userId); 850 } 851 852 if (foreground) { 853 moveUserToForegroundLocked(uss, oldUserId, userId); 854 } else { 855 mService.mUserController.finishUserBoot(uss); 856 } 857 858 if (needStart) { 859 Intent intent = new Intent(Intent.ACTION_USER_STARTING); 860 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 861 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 862 mService.broadcastIntentLocked(null, null, intent, 863 null, new IIntentReceiver.Stub() { 864 @Override 865 public void performReceive(Intent intent, int resultCode, 866 String data, Bundle extras, boolean ordered, boolean sticky, 867 int sendingUser) throws RemoteException { 868 } 869 }, 0, null, null, 870 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, 871 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL); 872 } 873 } 874 } finally { 875 Binder.restoreCallingIdentity(ident); 876 } 877 878 return true; 879 } 880 881 /** 882 * Start user, if its not already running, and bring it to foreground. 883 */ 884 boolean startUserInForeground(final int userId, Dialog dlg) { 885 boolean result = startUser(userId, /* foreground */ true); 886 dlg.dismiss(); 887 return result; 888 } 889 890 boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) { 891 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 892 != PackageManager.PERMISSION_GRANTED) { 893 String msg = "Permission Denial: unlockUser() from pid=" 894 + Binder.getCallingPid() 895 + ", uid=" + Binder.getCallingUid() 896 + " requires " + INTERACT_ACROSS_USERS_FULL; 897 Slog.w(TAG, msg); 898 throw new SecurityException(msg); 899 } 900 901 final long binderToken = Binder.clearCallingIdentity(); 902 try { 903 return unlockUserCleared(userId, token, secret, listener); 904 } finally { 905 Binder.restoreCallingIdentity(binderToken); 906 } 907 } 908 909 /** 910 * Attempt to unlock user without a credential token. This typically 911 * succeeds when the device doesn't have credential-encrypted storage, or 912 * when the the credential-encrypted storage isn't tied to a user-provided 913 * PIN or pattern. 914 */ 915 boolean maybeUnlockUser(final int userId) { 916 // Try unlocking storage using empty token 917 return unlockUserCleared(userId, null, null, null); 918 } 919 920 private static void notifyFinished(int userId, IProgressListener listener) { 921 if (listener == null) return; 922 try { 923 listener.onFinished(userId, null); 924 } catch (RemoteException ignored) { 925 } 926 } 927 928 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret, 929 IProgressListener listener) { 930 synchronized (mService) { 931 // Bail if user isn't actually running, otherwise register the given 932 // listener to watch for unlock progress 933 final UserState uss = mStartedUsers.get(userId); 934 if (uss == null) { 935 notifyFinished(userId, listener); 936 return false; 937 } else { 938 uss.mUnlockProgress.addListener(listener); 939 } 940 941 // TODO Move this block outside of synchronized if it causes lock contention 942 if (!StorageManager.isUserKeyUnlocked(userId)) { 943 final UserInfo userInfo = getUserInfo(userId); 944 final IMountService mountService = getMountService(); 945 try { 946 mountService.unlockUserKey(userId, userInfo.serialNumber, token, secret); 947 } catch (RemoteException | RuntimeException e) { 948 Slog.w(TAG, "Failed to unlock: " + e.getMessage()); 949 notifyFinished(userId, listener); 950 return false; 951 } 952 } 953 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