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