UserManagerService.java revision a68a28640fc700624369e07582033b0f5a71572c
1/* 2 * Copyright (C) 2011 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.pm; 18 19import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS; 20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; 21 22import android.Manifest; 23import android.annotation.NonNull; 24import android.annotation.Nullable; 25import android.annotation.UserIdInt; 26import android.app.Activity; 27import android.app.ActivityManager; 28import android.app.ActivityManagerInternal; 29import android.app.ActivityManagerNative; 30import android.app.IActivityManager; 31import android.app.IStopUserCallback; 32import android.app.KeyguardManager; 33import android.app.PendingIntent; 34import android.content.BroadcastReceiver; 35import android.content.Context; 36import android.content.Intent; 37import android.content.IntentFilter; 38import android.content.IntentSender; 39import android.content.pm.PackageManager; 40import android.content.pm.PackageManager.NameNotFoundException; 41import android.content.pm.ShortcutServiceInternal; 42import android.content.pm.UserInfo; 43import android.content.res.Resources; 44import android.graphics.Bitmap; 45import android.os.Binder; 46import android.os.Build; 47import android.os.Bundle; 48import android.os.Debug; 49import android.os.Environment; 50import android.os.FileUtils; 51import android.os.Handler; 52import android.os.IBinder; 53import android.os.IProgressListener; 54import android.os.IUserManager; 55import android.os.Message; 56import android.os.ParcelFileDescriptor; 57import android.os.Parcelable; 58import android.os.PersistableBundle; 59import android.os.Process; 60import android.os.RemoteException; 61import android.os.ResultReceiver; 62import android.os.SELinux; 63import android.os.ServiceManager; 64import android.os.ShellCallback; 65import android.os.ShellCommand; 66import android.os.SystemClock; 67import android.os.SystemProperties; 68import android.os.UserHandle; 69import android.os.UserManager; 70import android.os.UserManager.EnforcingUser; 71import android.os.UserManagerInternal; 72import android.os.UserManagerInternal.UserRestrictionsListener; 73import android.os.storage.StorageManager; 74import android.security.GateKeeper; 75import android.service.gatekeeper.IGateKeeperService; 76import android.util.AtomicFile; 77import android.util.IntArray; 78import android.util.Log; 79import android.util.Slog; 80import android.util.SparseArray; 81import android.util.SparseBooleanArray; 82import android.util.SparseIntArray; 83import android.util.SparseLongArray; 84import android.util.TimeUtils; 85import android.util.Xml; 86 87import com.android.internal.annotations.GuardedBy; 88import com.android.internal.annotations.VisibleForTesting; 89import com.android.internal.app.IAppOpsService; 90import com.android.internal.logging.MetricsLogger; 91import com.android.internal.os.BackgroundThread; 92import com.android.internal.util.DumpUtils; 93import com.android.internal.util.FastXmlSerializer; 94import com.android.internal.util.Preconditions; 95import com.android.internal.util.XmlUtils; 96import com.android.internal.widget.LockPatternUtils; 97import com.android.server.LocalServices; 98import com.android.server.LockGuard; 99import com.android.server.SystemService; 100import com.android.server.am.UserState; 101import com.android.server.storage.DeviceStorageMonitorInternal; 102 103import libcore.io.IoUtils; 104import libcore.util.Objects; 105 106import org.xmlpull.v1.XmlPullParser; 107import org.xmlpull.v1.XmlPullParserException; 108import org.xmlpull.v1.XmlSerializer; 109 110import java.io.BufferedOutputStream; 111import java.io.File; 112import java.io.FileDescriptor; 113import java.io.FileInputStream; 114import java.io.FileNotFoundException; 115import java.io.FileOutputStream; 116import java.io.IOException; 117import java.io.InputStream; 118import java.io.OutputStream; 119import java.io.PrintWriter; 120import java.nio.charset.StandardCharsets; 121import java.util.ArrayList; 122import java.util.Collections; 123import java.util.LinkedList; 124import java.util.List; 125 126/** 127 * Service for {@link UserManager}. 128 * 129 * Method naming convention: 130 * <ul> 131 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock. 132 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock. 133 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock. 134 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock. 135 * </ul> 136 */ 137public class UserManagerService extends IUserManager.Stub { 138 139 private static final String LOG_TAG = "UserManagerService"; 140 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE 141 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE 142 // Can be used for manual testing of id recycling 143 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE 144 145 private static final String TAG_NAME = "name"; 146 private static final String TAG_ACCOUNT = "account"; 147 private static final String ATTR_FLAGS = "flags"; 148 private static final String ATTR_ICON_PATH = "icon"; 149 private static final String ATTR_ID = "id"; 150 private static final String ATTR_CREATION_TIME = "created"; 151 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn"; 152 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint"; 153 private static final String ATTR_SERIAL_NO = "serialNumber"; 154 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber"; 155 private static final String ATTR_PARTIAL = "partial"; 156 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove"; 157 private static final String ATTR_USER_VERSION = "version"; 158 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId"; 159 private static final String ATTR_PROFILE_BADGE = "profileBadge"; 160 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId"; 161 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName"; 162 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType"; 163 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions"; 164 private static final String TAG_USERS = "users"; 165 private static final String TAG_USER = "user"; 166 private static final String TAG_RESTRICTIONS = "restrictions"; 167 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions"; 168 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS = 169 "device_policy_global_restrictions"; 170 /** Legacy name for device owner id tag. */ 171 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId"; 172 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId"; 173 private static final String TAG_ENTRY = "entry"; 174 private static final String TAG_VALUE = "value"; 175 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions"; 176 private static final String ATTR_KEY = "key"; 177 private static final String ATTR_VALUE_TYPE = "type"; 178 private static final String ATTR_MULTIPLE = "m"; 179 180 private static final String ATTR_TYPE_STRING_ARRAY = "sa"; 181 private static final String ATTR_TYPE_STRING = "s"; 182 private static final String ATTR_TYPE_BOOLEAN = "b"; 183 private static final String ATTR_TYPE_INTEGER = "i"; 184 private static final String ATTR_TYPE_BUNDLE = "B"; 185 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA"; 186 187 private static final String USER_INFO_DIR = "system" + File.separator + "users"; 188 private static final String USER_LIST_FILENAME = "userlist.xml"; 189 private static final String USER_PHOTO_FILENAME = "photo.png"; 190 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp"; 191 192 private static final String RESTRICTIONS_FILE_PREFIX = "res_"; 193 private static final String XML_SUFFIX = ".xml"; 194 195 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION = 196 UserInfo.FLAG_MANAGED_PROFILE 197 | UserInfo.FLAG_EPHEMERAL 198 | UserInfo.FLAG_RESTRICTED 199 | UserInfo.FLAG_GUEST 200 | UserInfo.FLAG_DEMO; 201 202 @VisibleForTesting 203 static final int MIN_USER_ID = 10; 204 // We need to keep process uid within Integer.MAX_VALUE. 205 @VisibleForTesting 206 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE; 207 208 // Max size of the queue of recently removed users 209 @VisibleForTesting 210 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100; 211 212 private static final int USER_VERSION = 7; 213 214 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms 215 216 // Maximum number of managed profiles permitted per user is 1. This cannot be increased 217 // without first making sure that the rest of the framework is prepared for it. 218 @VisibleForTesting 219 static final int MAX_MANAGED_PROFILES = 1; 220 221 static final int WRITE_USER_MSG = 1; 222 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds 223 224 // Tron counters 225 private static final String TRON_GUEST_CREATED = "users_guest_created"; 226 private static final String TRON_USER_CREATED = "users_user_created"; 227 private static final String TRON_DEMO_CREATED = "users_demo_created"; 228 229 private final Context mContext; 230 private final PackageManagerService mPm; 231 private final Object mPackagesLock; 232 private final UserDataPreparer mUserDataPreparer; 233 // Short-term lock for internal state, when interaction/sync with PM is not required 234 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER); 235 private final Object mRestrictionsLock = new Object(); 236 // Used for serializing access to app restriction files 237 private final Object mAppRestrictionsLock = new Object(); 238 239 private final Handler mHandler; 240 241 private final File mUsersDir; 242 private final File mUserListFile; 243 244 private static final IBinder mUserRestriconToken = new Binder(); 245 246 /** 247 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps. 248 */ 249 @VisibleForTesting 250 static class UserData { 251 // Basic user information and properties 252 UserInfo info; 253 // Account name used when there is a strong association between a user and an account 254 String account; 255 // Account information for seeding into a newly created user. This could also be 256 // used for login validation for an existing user, for updating their credentials. 257 // In the latter case, data may not need to be persisted as it is only valid for the 258 // current login session. 259 String seedAccountName; 260 String seedAccountType; 261 PersistableBundle seedAccountOptions; 262 // Whether to perist the seed account information to be available after a boot 263 boolean persistSeedData; 264 265 /** Elapsed realtime since boot when the user started. */ 266 long startRealtime; 267 268 /** Elapsed realtime since boot when the user was unlocked. */ 269 long unlockRealtime; 270 271 void clearSeedAccountData() { 272 seedAccountName = null; 273 seedAccountType = null; 274 seedAccountOptions = null; 275 persistSeedData = false; 276 } 277 } 278 279 @GuardedBy("mUsersLock") 280 private final SparseArray<UserData> mUsers = new SparseArray<>(); 281 282 /** 283 * User restrictions set via UserManager. This doesn't include restrictions set by 284 * device owner / profile owners. Only non-empty restriction bundles are stored. 285 * 286 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user, 287 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle} 288 * maybe shared between {@link #mBaseUserRestrictions} and 289 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately. 290 * (Otherwise we won't be able to detect what restrictions have changed in 291 * {@link #updateUserRestrictionsInternalLR}. 292 */ 293 @GuardedBy("mRestrictionsLock") 294 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>(); 295 296 /** 297 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined 298 * with device / profile owner restrictions. We'll initialize it lazily; use 299 * {@link #getEffectiveUserRestrictions} to access it. 300 * 301 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user, 302 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle} 303 * maybe shared between {@link #mBaseUserRestrictions} and 304 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately. 305 * (Otherwise we won't be able to detect what restrictions have changed in 306 * {@link #updateUserRestrictionsInternalLR}. 307 */ 308 @GuardedBy("mRestrictionsLock") 309 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>(); 310 311 /** 312 * User restrictions that have already been applied in 313 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions 314 * that have changed since the last 315 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call. 316 */ 317 @GuardedBy("mRestrictionsLock") 318 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>(); 319 320 /** 321 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService} 322 * that should be applied to all users, including guests. Only non-empty restriction bundles are 323 * stored. 324 */ 325 @GuardedBy("mRestrictionsLock") 326 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>(); 327 328 /** 329 * Id of the user that set global restrictions. 330 */ 331 @GuardedBy("mRestrictionsLock") 332 private int mDeviceOwnerUserId = UserHandle.USER_NULL; 333 334 /** 335 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService} 336 * for each user. Only non-empty restriction bundles are stored. 337 */ 338 @GuardedBy("mRestrictionsLock") 339 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>(); 340 341 @GuardedBy("mGuestRestrictions") 342 private final Bundle mGuestRestrictions = new Bundle(); 343 344 /** 345 * Set of user IDs being actively removed. Removed IDs linger in this set 346 * for several seconds to work around a VFS caching issue. 347 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array 348 */ 349 @GuardedBy("mUsersLock") 350 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray(); 351 352 /** 353 * Queue of recently removed userIds. Used for recycling of userIds 354 */ 355 @GuardedBy("mUsersLock") 356 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>(); 357 358 @GuardedBy("mUsersLock") 359 private int[] mUserIds; 360 @GuardedBy("mPackagesLock") 361 private int mNextSerialNumber; 362 private int mUserVersion = 0; 363 364 private IAppOpsService mAppOpsService; 365 366 private final LocalService mLocalService; 367 368 @GuardedBy("mUsersLock") 369 private boolean mIsDeviceManaged; 370 371 @GuardedBy("mUsersLock") 372 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray(); 373 374 @GuardedBy("mUserRestrictionsListeners") 375 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners = 376 new ArrayList<>(); 377 378 private final LockPatternUtils mLockPatternUtils; 379 380 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK = 381 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK"; 382 383 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() { 384 @Override 385 public void onReceive(Context context, Intent intent) { 386 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) { 387 return; 388 } 389 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT); 390 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL); 391 // Call setQuietModeEnabled on bg thread to avoid ANR 392 BackgroundThread.getHandler() 393 .post(() -> setQuietModeEnabled(userHandle, false, target)); 394 } 395 }; 396 397 /** 398 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode. 399 * 400 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)} 401 */ 402 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub { 403 private final IntentSender mTarget; 404 405 public DisableQuietModeUserUnlockedCallback(IntentSender target) { 406 Preconditions.checkNotNull(target); 407 mTarget = target; 408 } 409 410 @Override 411 public void onStarted(int id, Bundle extras) {} 412 413 @Override 414 public void onProgress(int id, int progress, Bundle extras) {} 415 416 @Override 417 public void onFinished(int id, Bundle extras) { 418 try { 419 mContext.startIntentSender(mTarget, null, 0, 0, 0); 420 } catch (IntentSender.SendIntentException e) { 421 Slog.e(LOG_TAG, "Failed to start the target in the callback", e); 422 } 423 } 424 } 425 426 /** 427 * Whether all users should be created ephemeral. 428 */ 429 @GuardedBy("mUsersLock") 430 private boolean mForceEphemeralUsers; 431 432 @GuardedBy("mUserStates") 433 private final SparseIntArray mUserStates = new SparseIntArray(); 434 435 private static UserManagerService sInstance; 436 437 public static UserManagerService getInstance() { 438 synchronized (UserManagerService.class) { 439 return sInstance; 440 } 441 } 442 443 public static class LifeCycle extends SystemService { 444 445 private UserManagerService mUms; 446 447 /** 448 * @param context 449 */ 450 public LifeCycle(Context context) { 451 super(context); 452 } 453 454 @Override 455 public void onStart() { 456 mUms = UserManagerService.getInstance(); 457 publishBinderService(Context.USER_SERVICE, mUms); 458 } 459 460 @Override 461 public void onBootPhase(int phase) { 462 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) { 463 mUms.cleanupPartialUsers(); 464 } 465 } 466 467 @Override 468 public void onStartUser(int userHandle) { 469 synchronized (mUms.mUsersLock) { 470 final UserData user = mUms.getUserDataLU(userHandle); 471 if (user != null) { 472 user.startRealtime = SystemClock.elapsedRealtime(); 473 } 474 } 475 } 476 477 @Override 478 public void onUnlockUser(int userHandle) { 479 synchronized (mUms.mUsersLock) { 480 final UserData user = mUms.getUserDataLU(userHandle); 481 if (user != null) { 482 user.unlockRealtime = SystemClock.elapsedRealtime(); 483 } 484 } 485 } 486 487 @Override 488 public void onStopUser(int userHandle) { 489 synchronized (mUms.mUsersLock) { 490 final UserData user = mUms.getUserDataLU(userHandle); 491 if (user != null) { 492 user.startRealtime = 0; 493 user.unlockRealtime = 0; 494 } 495 } 496 } 497 } 498 499 // TODO b/28848102 Add support for test dependencies injection 500 @VisibleForTesting 501 UserManagerService(Context context) { 502 this(context, null, null, new Object(), context.getCacheDir()); 503 } 504 505 /** 506 * Called by package manager to create the service. This is closely 507 * associated with the package manager, and the given lock is the 508 * package manager's own lock. 509 */ 510 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer, 511 Object packagesLock) { 512 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory()); 513 } 514 515 private UserManagerService(Context context, PackageManagerService pm, 516 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) { 517 mContext = context; 518 mPm = pm; 519 mPackagesLock = packagesLock; 520 mHandler = new MainHandler(); 521 mUserDataPreparer = userDataPreparer; 522 synchronized (mPackagesLock) { 523 mUsersDir = new File(dataDir, USER_INFO_DIR); 524 mUsersDir.mkdirs(); 525 // Make zeroth user directory, for services to migrate their files to that location 526 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM)); 527 userZeroDir.mkdirs(); 528 FileUtils.setPermissions(mUsersDir.toString(), 529 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH, 530 -1, -1); 531 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME); 532 initDefaultGuestRestrictions(); 533 readUserListLP(); 534 sInstance = this; 535 } 536 mLocalService = new LocalService(); 537 LocalServices.addService(UserManagerInternal.class, mLocalService); 538 mLockPatternUtils = new LockPatternUtils(mContext); 539 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING); 540 } 541 542 void systemReady() { 543 mAppOpsService = IAppOpsService.Stub.asInterface( 544 ServiceManager.getService(Context.APP_OPS_SERVICE)); 545 546 synchronized (mRestrictionsLock) { 547 applyUserRestrictionsLR(UserHandle.USER_SYSTEM); 548 } 549 550 UserInfo currentGuestUser = findCurrentGuestUser(); 551 if (currentGuestUser != null && !hasUserRestriction( 552 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) { 553 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option 554 // to it, in case this guest was created in a previous version where this 555 // user restriction was not a default guest restriction. 556 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id); 557 } 558 559 mContext.registerReceiver(mDisableQuietModeCallback, 560 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK), 561 null, mHandler); 562 } 563 564 void cleanupPartialUsers() { 565 // Prune out any partially created, partially removed and ephemeral users. 566 ArrayList<UserInfo> partials = new ArrayList<>(); 567 synchronized (mUsersLock) { 568 final int userSize = mUsers.size(); 569 for (int i = 0; i < userSize; i++) { 570 UserInfo ui = mUsers.valueAt(i).info; 571 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) { 572 partials.add(ui); 573 addRemovingUserIdLocked(ui.id); 574 ui.partial = true; 575 } 576 } 577 } 578 final int partialsSize = partials.size(); 579 for (int i = 0; i < partialsSize; i++) { 580 UserInfo ui = partials.get(i); 581 Slog.w(LOG_TAG, "Removing partially created user " + ui.id 582 + " (name=" + ui.name + ")"); 583 removeUserState(ui.id); 584 } 585 } 586 587 @Override 588 public String getUserAccount(int userId) { 589 checkManageUserAndAcrossUsersFullPermission("get user account"); 590 synchronized (mUsersLock) { 591 return mUsers.get(userId).account; 592 } 593 } 594 595 @Override 596 public void setUserAccount(int userId, String accountName) { 597 checkManageUserAndAcrossUsersFullPermission("set user account"); 598 UserData userToUpdate = null; 599 synchronized (mPackagesLock) { 600 synchronized (mUsersLock) { 601 final UserData userData = mUsers.get(userId); 602 if (userData == null) { 603 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId); 604 return; 605 } 606 String currentAccount = userData.account; 607 if (!Objects.equal(currentAccount, accountName)) { 608 userData.account = accountName; 609 userToUpdate = userData; 610 } 611 } 612 613 if (userToUpdate != null) { 614 writeUserLP(userToUpdate); 615 } 616 } 617 } 618 619 @Override 620 public UserInfo getPrimaryUser() { 621 checkManageUsersPermission("query users"); 622 synchronized (mUsersLock) { 623 final int userSize = mUsers.size(); 624 for (int i = 0; i < userSize; i++) { 625 UserInfo ui = mUsers.valueAt(i).info; 626 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) { 627 return ui; 628 } 629 } 630 } 631 return null; 632 } 633 634 @Override 635 public @NonNull List<UserInfo> getUsers(boolean excludeDying) { 636 checkManageOrCreateUsersPermission("query users"); 637 synchronized (mUsersLock) { 638 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size()); 639 final int userSize = mUsers.size(); 640 for (int i = 0; i < userSize; i++) { 641 UserInfo ui = mUsers.valueAt(i).info; 642 if (ui.partial) { 643 continue; 644 } 645 if (!excludeDying || !mRemovingUserIds.get(ui.id)) { 646 users.add(userWithName(ui)); 647 } 648 } 649 return users; 650 } 651 } 652 653 @Override 654 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) { 655 boolean returnFullInfo = true; 656 if (userId != UserHandle.getCallingUserId()) { 657 checkManageOrCreateUsersPermission("getting profiles related to user " + userId); 658 } else { 659 returnFullInfo = hasManageUsersPermission(); 660 } 661 final long ident = Binder.clearCallingIdentity(); 662 try { 663 synchronized (mUsersLock) { 664 return getProfilesLU(userId, enabledOnly, returnFullInfo); 665 } 666 } finally { 667 Binder.restoreCallingIdentity(ident); 668 } 669 } 670 671 @Override 672 public int[] getProfileIds(int userId, boolean enabledOnly) { 673 if (userId != UserHandle.getCallingUserId()) { 674 checkManageOrCreateUsersPermission("getting profiles related to user " + userId); 675 } 676 final long ident = Binder.clearCallingIdentity(); 677 try { 678 synchronized (mUsersLock) { 679 return getProfileIdsLU(userId, enabledOnly).toArray(); 680 } 681 } finally { 682 Binder.restoreCallingIdentity(ident); 683 } 684 } 685 686 /** Assume permissions already checked and caller's identity cleared */ 687 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) { 688 IntArray profileIds = getProfileIdsLU(userId, enabledOnly); 689 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size()); 690 for (int i = 0; i < profileIds.size(); i++) { 691 int profileId = profileIds.get(i); 692 UserInfo userInfo = mUsers.get(profileId).info; 693 // If full info is not required - clear PII data to prevent 3P apps from reading it 694 if (!fullInfo) { 695 userInfo = new UserInfo(userInfo); 696 userInfo.name = null; 697 userInfo.iconPath = null; 698 } else { 699 userInfo = userWithName(userInfo); 700 } 701 users.add(userInfo); 702 } 703 return users; 704 } 705 706 /** 707 * Assume permissions already checked and caller's identity cleared 708 */ 709 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) { 710 UserInfo user = getUserInfoLU(userId); 711 IntArray result = new IntArray(mUsers.size()); 712 if (user == null) { 713 // Probably a dying user 714 return result; 715 } 716 final int userSize = mUsers.size(); 717 for (int i = 0; i < userSize; i++) { 718 UserInfo profile = mUsers.valueAt(i).info; 719 if (!isProfileOf(user, profile)) { 720 continue; 721 } 722 if (enabledOnly && !profile.isEnabled()) { 723 continue; 724 } 725 if (mRemovingUserIds.get(profile.id)) { 726 continue; 727 } 728 if (profile.partial) { 729 continue; 730 } 731 result.add(profile.id); 732 } 733 return result; 734 } 735 736 @Override 737 public int getCredentialOwnerProfile(int userHandle) { 738 checkManageUsersPermission("get the credential owner"); 739 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) { 740 synchronized (mUsersLock) { 741 UserInfo profileParent = getProfileParentLU(userHandle); 742 if (profileParent != null) { 743 return profileParent.id; 744 } 745 } 746 } 747 748 return userHandle; 749 } 750 751 @Override 752 public boolean isSameProfileGroup(int userId, int otherUserId) { 753 if (userId == otherUserId) return true; 754 checkManageUsersPermission("check if in the same profile group"); 755 return isSameProfileGroupNoChecks(userId, otherUserId); 756 } 757 758 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) { 759 synchronized (mUsersLock) { 760 UserInfo userInfo = getUserInfoLU(userId); 761 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) { 762 return false; 763 } 764 UserInfo otherUserInfo = getUserInfoLU(otherUserId); 765 if (otherUserInfo == null 766 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) { 767 return false; 768 } 769 return userInfo.profileGroupId == otherUserInfo.profileGroupId; 770 } 771 } 772 773 @Override 774 public UserInfo getProfileParent(int userHandle) { 775 checkManageUsersPermission("get the profile parent"); 776 synchronized (mUsersLock) { 777 return getProfileParentLU(userHandle); 778 } 779 } 780 781 @Override 782 public int getProfileParentId(int userHandle) { 783 checkManageUsersPermission("get the profile parent"); 784 synchronized (mUsersLock) { 785 UserInfo profileParent = getProfileParentLU(userHandle); 786 if (profileParent == null) { 787 return userHandle; 788 } 789 790 return profileParent.id; 791 } 792 } 793 794 private UserInfo getProfileParentLU(int userHandle) { 795 UserInfo profile = getUserInfoLU(userHandle); 796 if (profile == null) { 797 return null; 798 } 799 int parentUserId = profile.profileGroupId; 800 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) { 801 return null; 802 } else { 803 return getUserInfoLU(parentUserId); 804 } 805 } 806 807 private static boolean isProfileOf(UserInfo user, UserInfo profile) { 808 return user.id == profile.id || 809 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID 810 && user.profileGroupId == profile.profileGroupId); 811 } 812 813 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle, 814 UserHandle parentHandle, boolean inQuietMode) { 815 Intent intent = new Intent(); 816 if (inQuietMode) { 817 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE); 818 } else { 819 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE); 820 } 821 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode); 822 intent.putExtra(Intent.EXTRA_USER, profileHandle); 823 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier()); 824 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 825 mContext.sendBroadcastAsUser(intent, parentHandle); 826 } 827 828 @Override 829 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode, 830 int userHandle, @Nullable IntentSender target) { 831 Preconditions.checkNotNull(callingPackage); 832 833 if (enableQuietMode && target != null) { 834 throw new IllegalArgumentException( 835 "target should only be specified when we are disabling quiet mode."); 836 } 837 838 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null); 839 final long identity = Binder.clearCallingIdentity(); 840 try { 841 if (enableQuietMode) { 842 setQuietModeEnabled(userHandle, true /* enableQuietMode */, target); 843 return true; 844 } else { 845 boolean needToShowConfirmCredential = 846 mLockPatternUtils.isSecure(userHandle) 847 && !StorageManager.isUserKeyUnlocked(userHandle); 848 if (needToShowConfirmCredential) { 849 showConfirmCredentialToDisableQuietMode(userHandle, target); 850 return false; 851 } else { 852 setQuietModeEnabled(userHandle, false /* enableQuietMode */, target); 853 return true; 854 } 855 } 856 } finally { 857 Binder.restoreCallingIdentity(identity); 858 } 859 } 860 861 /** 862 * The caller can modify quiet mode if it meets one of these conditions: 863 * <ul> 864 * <li>Has system UID or root UID</li> 865 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li> 866 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li> 867 * </ul> 868 * <p> 869 * If caller wants to start an intent after disabling the quiet mode, it must has 870 * {@link Manifest.permission#MANAGE_USERS}. 871 */ 872 private void ensureCanModifyQuietMode(String callingPackage, int callingUid, 873 boolean startIntent) { 874 if (hasManageUsersPermission()) { 875 return; 876 } 877 if (startIntent) { 878 throw new SecurityException("MANAGE_USERS permission is required to start intent " 879 + "after disabling quiet mode."); 880 } 881 final boolean hasModifyQuietModePermission = ActivityManager.checkComponentPermission( 882 Manifest.permission.MODIFY_QUIET_MODE, 883 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED; 884 if (hasModifyQuietModePermission) { 885 return; 886 } 887 888 verifyCallingPackage(callingPackage, callingUid); 889 final ShortcutServiceInternal shortcutInternal = 890 LocalServices.getService(ShortcutServiceInternal.class); 891 if (shortcutInternal != null) { 892 boolean isForegroundLauncher = 893 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid); 894 if (isForegroundLauncher) { 895 return; 896 } 897 } 898 throw new SecurityException("Can't modify quiet mode, caller is neither foreground " 899 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission"); 900 } 901 902 private void setQuietModeEnabled( 903 int userHandle, boolean enableQuietMode, IntentSender target) { 904 final UserInfo profile, parent; 905 final UserData profileUserData; 906 synchronized (mUsersLock) { 907 profile = getUserInfoLU(userHandle); 908 parent = getProfileParentLU(userHandle); 909 910 if (profile == null || !profile.isManagedProfile()) { 911 throw new IllegalArgumentException("User " + userHandle + " is not a profile"); 912 } 913 if (profile.isQuietModeEnabled() == enableQuietMode) { 914 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode); 915 return; 916 } 917 profile.flags ^= UserInfo.FLAG_QUIET_MODE; 918 profileUserData = getUserDataLU(profile.id); 919 } 920 synchronized (mPackagesLock) { 921 writeUserLP(profileUserData); 922 } 923 try { 924 if (enableQuietMode) { 925 ActivityManager.getService().stopUser(userHandle, /* force */true, null); 926 LocalServices.getService(ActivityManagerInternal.class) 927 .killForegroundAppsForUser(userHandle); 928 } else { 929 IProgressListener callback = target != null 930 ? new DisableQuietModeUserUnlockedCallback(target) 931 : null; 932 ActivityManager.getService().startUserInBackgroundWithListener( 933 userHandle, callback); 934 } 935 } catch (RemoteException e) { 936 // Should not happen, same process. 937 e.rethrowAsRuntimeException(); 938 } 939 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(), 940 enableQuietMode); 941 } 942 943 @Override 944 public boolean isQuietModeEnabled(int userHandle) { 945 synchronized (mPackagesLock) { 946 UserInfo info; 947 synchronized (mUsersLock) { 948 info = getUserInfoLU(userHandle); 949 } 950 if (info == null || !info.isManagedProfile()) { 951 return false; 952 } 953 return info.isQuietModeEnabled(); 954 } 955 } 956 957 /** 958 * Show confirm credential screen to unlock user in order to turn off quiet mode. 959 */ 960 private void showConfirmCredentialToDisableQuietMode( 961 @UserIdInt int userHandle, @Nullable IntentSender target) { 962 // otherwise, we show a profile challenge to trigger decryption of the user 963 final KeyguardManager km = (KeyguardManager) mContext.getSystemService( 964 Context.KEYGUARD_SERVICE); 965 // We should use userHandle not credentialOwnerUserId here, as even if it is unified 966 // lock, confirm screenlock page will know and show personal challenge, and unlock 967 // work profile when personal challenge is correct 968 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, 969 userHandle); 970 if (unlockIntent == null) { 971 return; 972 } 973 final Intent callBackIntent = new Intent( 974 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK); 975 if (target != null) { 976 callBackIntent.putExtra(Intent.EXTRA_INTENT, target); 977 } 978 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle); 979 callBackIntent.setPackage(mContext.getPackageName()); 980 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 981 final PendingIntent pendingIntent = PendingIntent.getBroadcast( 982 mContext, 983 0, 984 callBackIntent, 985 PendingIntent.FLAG_CANCEL_CURRENT | 986 PendingIntent.FLAG_ONE_SHOT | 987 PendingIntent.FLAG_IMMUTABLE); 988 // After unlocking the challenge, it will disable quiet mode and run the original 989 // intentSender 990 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender()); 991 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 992 mContext.startActivity(unlockIntent); 993 } 994 995 @Override 996 public void setUserEnabled(int userId) { 997 checkManageUsersPermission("enable user"); 998 synchronized (mPackagesLock) { 999 UserInfo info; 1000 synchronized (mUsersLock) { 1001 info = getUserInfoLU(userId); 1002 } 1003 if (info != null && !info.isEnabled()) { 1004 info.flags ^= UserInfo.FLAG_DISABLED; 1005 writeUserLP(getUserDataLU(info.id)); 1006 } 1007 } 1008 } 1009 1010 /** 1011 * Evicts a user's CE key by stopping and restarting the user. 1012 * 1013 * The key is evicted automatically by the user controller when the user has stopped. 1014 */ 1015 @Override 1016 public void evictCredentialEncryptionKey(@UserIdInt int userId) { 1017 checkManageUsersPermission("evict CE key"); 1018 final IActivityManager am = ActivityManagerNative.getDefault(); 1019 final long identity = Binder.clearCallingIdentity(); 1020 try { 1021 am.restartUserInBackground(userId); 1022 } catch (RemoteException re) { 1023 throw re.rethrowAsRuntimeException(); 1024 } finally { 1025 Binder.restoreCallingIdentity(identity); 1026 } 1027 } 1028 1029 @Override 1030 public UserInfo getUserInfo(int userId) { 1031 checkManageOrCreateUsersPermission("query user"); 1032 synchronized (mUsersLock) { 1033 return userWithName(getUserInfoLU(userId)); 1034 } 1035 } 1036 1037 /** 1038 * Returns a UserInfo object with the name filled in, for Owner, or the original 1039 * if the name is already set. 1040 */ 1041 private UserInfo userWithName(UserInfo orig) { 1042 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) { 1043 UserInfo withName = new UserInfo(orig); 1044 withName.name = getOwnerName(); 1045 return withName; 1046 } else { 1047 return orig; 1048 } 1049 } 1050 1051 @Override 1052 public int getManagedProfileBadge(@UserIdInt int userId) { 1053 int callingUserId = UserHandle.getCallingUserId(); 1054 if (callingUserId != userId && !hasManageUsersPermission()) { 1055 if (!isSameProfileGroupNoChecks(callingUserId, userId)) { 1056 throw new SecurityException( 1057 "You need MANAGE_USERS permission to: check if specified user a " + 1058 "managed profile outside your profile group"); 1059 } 1060 } 1061 synchronized (mUsersLock) { 1062 UserInfo userInfo = getUserInfoLU(userId); 1063 return userInfo != null ? userInfo.profileBadge : 0; 1064 } 1065 } 1066 1067 @Override 1068 public boolean isManagedProfile(int userId) { 1069 int callingUserId = UserHandle.getCallingUserId(); 1070 if (callingUserId != userId && !hasManageUsersPermission()) { 1071 if (!isSameProfileGroupNoChecks(callingUserId, userId)) { 1072 throw new SecurityException( 1073 "You need MANAGE_USERS permission to: check if specified user a " + 1074 "managed profile outside your profile group"); 1075 } 1076 } 1077 synchronized (mUsersLock) { 1078 UserInfo userInfo = getUserInfoLU(userId); 1079 return userInfo != null && userInfo.isManagedProfile(); 1080 } 1081 } 1082 1083 @Override 1084 public boolean isUserUnlockingOrUnlocked(int userId) { 1085 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked"); 1086 return mLocalService.isUserUnlockingOrUnlocked(userId); 1087 } 1088 1089 @Override 1090 public boolean isUserUnlocked(int userId) { 1091 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked"); 1092 return mLocalService.isUserUnlocked(userId); 1093 } 1094 1095 @Override 1096 public boolean isUserRunning(int userId) { 1097 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning"); 1098 return mLocalService.isUserRunning(userId); 1099 } 1100 1101 @Override 1102 public long getUserStartRealtime() { 1103 final int userId = UserHandle.getUserId(Binder.getCallingUid()); 1104 synchronized (mUsersLock) { 1105 final UserData user = getUserDataLU(userId); 1106 if (user != null) { 1107 return user.startRealtime; 1108 } 1109 return 0; 1110 } 1111 } 1112 1113 @Override 1114 public long getUserUnlockRealtime() { 1115 synchronized (mUsersLock) { 1116 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid())); 1117 if (user != null) { 1118 return user.unlockRealtime; 1119 } 1120 return 0; 1121 } 1122 } 1123 1124 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) { 1125 int callingUserId = UserHandle.getCallingUserId(); 1126 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) || 1127 hasManageUsersPermission()) { 1128 return; 1129 } 1130 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS, 1131 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) { 1132 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission " 1133 + "to: check " + name); 1134 } 1135 } 1136 1137 @Override 1138 public boolean isDemoUser(int userId) { 1139 int callingUserId = UserHandle.getCallingUserId(); 1140 if (callingUserId != userId && !hasManageUsersPermission()) { 1141 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId 1142 + " is a demo user"); 1143 } 1144 synchronized (mUsersLock) { 1145 UserInfo userInfo = getUserInfoLU(userId); 1146 return userInfo != null && userInfo.isDemo(); 1147 } 1148 } 1149 1150 @Override 1151 public boolean isRestricted() { 1152 synchronized (mUsersLock) { 1153 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted(); 1154 } 1155 } 1156 1157 @Override 1158 public boolean canHaveRestrictedProfile(int userId) { 1159 checkManageUsersPermission("canHaveRestrictedProfile"); 1160 synchronized (mUsersLock) { 1161 final UserInfo userInfo = getUserInfoLU(userId); 1162 if (userInfo == null || !userInfo.canHaveProfile()) { 1163 return false; 1164 } 1165 if (!userInfo.isAdmin()) { 1166 return false; 1167 } 1168 // restricted profile can be created if there is no DO set and the admin user has no PO; 1169 return !mIsDeviceManaged && !mIsUserManaged.get(userId); 1170 } 1171 } 1172 1173 @Override 1174 public boolean hasRestrictedProfiles() { 1175 checkManageUsersPermission("hasRestrictedProfiles"); 1176 final int callingUserId = UserHandle.getCallingUserId(); 1177 synchronized (mUsersLock) { 1178 final int userSize = mUsers.size(); 1179 for (int i = 0; i < userSize; i++) { 1180 UserInfo profile = mUsers.valueAt(i).info; 1181 if (callingUserId != profile.id 1182 && profile.restrictedProfileParentId == callingUserId) { 1183 return true; 1184 } 1185 } 1186 return false; 1187 } 1188 } 1189 1190 /* 1191 * Should be locked on mUsers before calling this. 1192 */ 1193 private UserInfo getUserInfoLU(int userId) { 1194 final UserData userData = mUsers.get(userId); 1195 // If it is partial and not in the process of being removed, return as unknown user. 1196 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) { 1197 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId); 1198 return null; 1199 } 1200 return userData != null ? userData.info : null; 1201 } 1202 1203 private UserData getUserDataLU(int userId) { 1204 final UserData userData = mUsers.get(userId); 1205 // If it is partial and not in the process of being removed, return as unknown user. 1206 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) { 1207 return null; 1208 } 1209 return userData; 1210 } 1211 1212 /** 1213 * Obtains {@link #mUsersLock} and return UserInfo from mUsers. 1214 * <p>No permissions checking or any addition checks are made</p> 1215 */ 1216 private UserInfo getUserInfoNoChecks(int userId) { 1217 synchronized (mUsersLock) { 1218 final UserData userData = mUsers.get(userId); 1219 return userData != null ? userData.info : null; 1220 } 1221 } 1222 1223 /** 1224 * Obtains {@link #mUsersLock} and return UserData from mUsers. 1225 * <p>No permissions checking or any addition checks are made</p> 1226 */ 1227 private UserData getUserDataNoChecks(int userId) { 1228 synchronized (mUsersLock) { 1229 return mUsers.get(userId); 1230 } 1231 } 1232 1233 /** Called by PackageManagerService */ 1234 public boolean exists(int userId) { 1235 return mLocalService.exists(userId); 1236 } 1237 1238 @Override 1239 public void setUserName(int userId, String name) { 1240 checkManageUsersPermission("rename users"); 1241 boolean changed = false; 1242 synchronized (mPackagesLock) { 1243 UserData userData = getUserDataNoChecks(userId); 1244 if (userData == null || userData.info.partial) { 1245 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId); 1246 return; 1247 } 1248 if (name != null && !name.equals(userData.info.name)) { 1249 userData.info.name = name; 1250 writeUserLP(userData); 1251 changed = true; 1252 } 1253 } 1254 if (changed) { 1255 sendUserInfoChangedBroadcast(userId); 1256 } 1257 } 1258 1259 @Override 1260 public void setUserIcon(int userId, Bitmap bitmap) { 1261 checkManageUsersPermission("update users"); 1262 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) { 1263 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled."); 1264 return; 1265 } 1266 mLocalService.setUserIcon(userId, bitmap); 1267 } 1268 1269 1270 1271 private void sendUserInfoChangedBroadcast(int userId) { 1272 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED); 1273 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 1274 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 1275 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL); 1276 } 1277 1278 @Override 1279 public ParcelFileDescriptor getUserIcon(int targetUserId) { 1280 String iconPath; 1281 synchronized (mPackagesLock) { 1282 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId); 1283 if (targetUserInfo == null || targetUserInfo.partial) { 1284 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId); 1285 return null; 1286 } 1287 1288 final int callingUserId = UserHandle.getCallingUserId(); 1289 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId; 1290 final int targetGroupId = targetUserInfo.profileGroupId; 1291 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID 1292 && callingGroupId == targetGroupId); 1293 if ((callingUserId != targetUserId) && !sameGroup) { 1294 checkManageUsersPermission("get the icon of a user who is not related"); 1295 } 1296 1297 if (targetUserInfo.iconPath == null) { 1298 return null; 1299 } 1300 iconPath = targetUserInfo.iconPath; 1301 } 1302 1303 try { 1304 return ParcelFileDescriptor.open( 1305 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY); 1306 } catch (FileNotFoundException e) { 1307 Log.e(LOG_TAG, "Couldn't find icon file", e); 1308 } 1309 return null; 1310 } 1311 1312 public void makeInitialized(int userId) { 1313 checkManageUsersPermission("makeInitialized"); 1314 boolean scheduleWriteUser = false; 1315 UserData userData; 1316 synchronized (mUsersLock) { 1317 userData = mUsers.get(userId); 1318 if (userData == null || userData.info.partial) { 1319 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId); 1320 return; 1321 } 1322 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) { 1323 userData.info.flags |= UserInfo.FLAG_INITIALIZED; 1324 scheduleWriteUser = true; 1325 } 1326 } 1327 if (scheduleWriteUser) { 1328 scheduleWriteUser(userData); 1329 } 1330 } 1331 1332 /** 1333 * If default guest restrictions haven't been initialized yet, add the basic 1334 * restrictions. 1335 */ 1336 private void initDefaultGuestRestrictions() { 1337 synchronized (mGuestRestrictions) { 1338 if (mGuestRestrictions.isEmpty()) { 1339 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true); 1340 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true); 1341 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true); 1342 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true); 1343 } 1344 } 1345 } 1346 1347 @Override 1348 public Bundle getDefaultGuestRestrictions() { 1349 checkManageUsersPermission("getDefaultGuestRestrictions"); 1350 synchronized (mGuestRestrictions) { 1351 return new Bundle(mGuestRestrictions); 1352 } 1353 } 1354 1355 @Override 1356 public void setDefaultGuestRestrictions(Bundle restrictions) { 1357 checkManageUsersPermission("setDefaultGuestRestrictions"); 1358 synchronized (mGuestRestrictions) { 1359 mGuestRestrictions.clear(); 1360 mGuestRestrictions.putAll(restrictions); 1361 } 1362 synchronized (mPackagesLock) { 1363 writeUserListLP(); 1364 } 1365 } 1366 1367 /** 1368 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions} 1369 */ 1370 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions, 1371 boolean isDeviceOwner, int cameraRestrictionScope) { 1372 final Bundle global = new Bundle(); 1373 final Bundle local = new Bundle(); 1374 1375 // Sort restrictions into local and global ensuring they don't overlap. 1376 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner, 1377 cameraRestrictionScope, global, local); 1378 1379 boolean globalChanged, localChanged; 1380 synchronized (mRestrictionsLock) { 1381 // Update global and local restrictions if they were changed. 1382 globalChanged = updateRestrictionsIfNeededLR( 1383 userId, global, mDevicePolicyGlobalUserRestrictions); 1384 localChanged = updateRestrictionsIfNeededLR( 1385 userId, local, mDevicePolicyLocalUserRestrictions); 1386 1387 if (isDeviceOwner) { 1388 // Remember the global restriction owner userId to be able to make a distinction 1389 // in getUserRestrictionSource on who set local policies. 1390 mDeviceOwnerUserId = userId; 1391 } else { 1392 if (mDeviceOwnerUserId == userId) { 1393 // When profile owner sets restrictions it passes null global bundle and we 1394 // reset global restriction owner userId. 1395 // This means this user used to have DO, but now the DO is gone and the user 1396 // instead has PO. 1397 mDeviceOwnerUserId = UserHandle.USER_NULL; 1398 } 1399 } 1400 } 1401 if (DBG) { 1402 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId 1403 + " global=" + global + (globalChanged ? " (changed)" : "") 1404 + " local=" + local + (localChanged ? " (changed)" : "") 1405 ); 1406 } 1407 // Don't call them within the mRestrictionsLock. 1408 synchronized (mPackagesLock) { 1409 if (localChanged || globalChanged) { 1410 writeUserLP(getUserDataNoChecks(userId)); 1411 } 1412 } 1413 1414 synchronized (mRestrictionsLock) { 1415 if (globalChanged) { 1416 applyUserRestrictionsForAllUsersLR(); 1417 } else if (localChanged) { 1418 applyUserRestrictionsLR(userId); 1419 } 1420 } 1421 } 1422 1423 /** 1424 * Updates restriction bundle for a given user in a given restriction array. If new bundle is 1425 * empty, record is removed from the array. 1426 * @return whether restrictions bundle is different from the old one. 1427 */ 1428 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions, 1429 SparseArray<Bundle> restrictionsArray) { 1430 final boolean changed = 1431 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions); 1432 if (changed) { 1433 if (!UserRestrictionsUtils.isEmpty(restrictions)) { 1434 restrictionsArray.put(userId, restrictions); 1435 } else { 1436 restrictionsArray.delete(userId); 1437 } 1438 } 1439 return changed; 1440 } 1441 1442 @GuardedBy("mRestrictionsLock") 1443 private Bundle computeEffectiveUserRestrictionsLR(int userId) { 1444 final Bundle baseRestrictions = 1445 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId)); 1446 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions); 1447 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId); 1448 1449 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) { 1450 // Common case first. 1451 return baseRestrictions; 1452 } 1453 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions); 1454 UserRestrictionsUtils.merge(effective, global); 1455 UserRestrictionsUtils.merge(effective, local); 1456 1457 return effective; 1458 } 1459 1460 @GuardedBy("mRestrictionsLock") 1461 private void invalidateEffectiveUserRestrictionsLR(int userId) { 1462 if (DBG) { 1463 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId); 1464 } 1465 mCachedEffectiveUserRestrictions.remove(userId); 1466 } 1467 1468 private Bundle getEffectiveUserRestrictions(int userId) { 1469 synchronized (mRestrictionsLock) { 1470 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId); 1471 if (restrictions == null) { 1472 restrictions = computeEffectiveUserRestrictionsLR(userId); 1473 mCachedEffectiveUserRestrictions.put(userId, restrictions); 1474 } 1475 return restrictions; 1476 } 1477 } 1478 1479 /** @return a specific user restriction that's in effect currently. */ 1480 @Override 1481 public boolean hasUserRestriction(String restrictionKey, int userId) { 1482 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) { 1483 return false; 1484 } 1485 Bundle restrictions = getEffectiveUserRestrictions(userId); 1486 return restrictions != null && restrictions.getBoolean(restrictionKey); 1487 } 1488 1489 /** 1490 * @hide 1491 * 1492 * Returns who set a user restriction on a user. 1493 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission. 1494 * @param restrictionKey the string key representing the restriction 1495 * @param userId the id of the user for whom to retrieve the restrictions. 1496 * @return The source of user restriction. Any combination of 1497 * {@link UserManager#RESTRICTION_NOT_SET}, 1498 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM}, 1499 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER} 1500 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER} 1501 */ 1502 @Override 1503 public int getUserRestrictionSource(String restrictionKey, int userId) { 1504 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId); 1505 // Get "bitwise or" of restriction sources for all enforcing users. 1506 int result = UserManager.RESTRICTION_NOT_SET; 1507 for (int i = enforcingUsers.size() - 1; i >= 0; i--) { 1508 result |= enforcingUsers.get(i).getUserRestrictionSource(); 1509 } 1510 return result; 1511 } 1512 1513 @Override 1514 public List<EnforcingUser> getUserRestrictionSources( 1515 String restrictionKey, @UserIdInt int userId) { 1516 checkManageUsersPermission("getUserRestrictionSource"); 1517 1518 // Shortcut for the most common case 1519 if (!hasUserRestriction(restrictionKey, userId)) { 1520 return Collections.emptyList(); 1521 } 1522 1523 final List<EnforcingUser> result = new ArrayList<>(); 1524 1525 // Check if it is base restriction. 1526 if (hasBaseUserRestriction(restrictionKey, userId)) { 1527 result.add(new EnforcingUser( 1528 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM)); 1529 } 1530 1531 synchronized (mRestrictionsLock) { 1532 // Check if it is set by profile owner. 1533 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId); 1534 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) { 1535 result.add(getEnforcingUserLocked(userId)); 1536 } 1537 1538 // Iterate over all users who enforce global restrictions. 1539 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) { 1540 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i); 1541 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i); 1542 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) { 1543 result.add(getEnforcingUserLocked(profileUserId)); 1544 } 1545 } 1546 } 1547 return result; 1548 } 1549 1550 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) { 1551 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER 1552 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER; 1553 return new EnforcingUser(userId, source); 1554 } 1555 1556 /** 1557 * @return UserRestrictions that are in effect currently. This always returns a new 1558 * {@link Bundle}. 1559 */ 1560 @Override 1561 public Bundle getUserRestrictions(int userId) { 1562 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId)); 1563 } 1564 1565 @Override 1566 public boolean hasBaseUserRestriction(String restrictionKey, int userId) { 1567 checkManageUsersPermission("hasBaseUserRestriction"); 1568 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) { 1569 return false; 1570 } 1571 synchronized (mRestrictionsLock) { 1572 Bundle bundle = mBaseUserRestrictions.get(userId); 1573 return (bundle != null && bundle.getBoolean(restrictionKey, false)); 1574 } 1575 } 1576 1577 @Override 1578 public void setUserRestriction(String key, boolean value, int userId) { 1579 checkManageUsersPermission("setUserRestriction"); 1580 if (!UserRestrictionsUtils.isValidRestriction(key)) { 1581 return; 1582 } 1583 synchronized (mRestrictionsLock) { 1584 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create 1585 // a copy. 1586 final Bundle newRestrictions = UserRestrictionsUtils.clone( 1587 mBaseUserRestrictions.get(userId)); 1588 newRestrictions.putBoolean(key, value); 1589 1590 updateUserRestrictionsInternalLR(newRestrictions, userId); 1591 } 1592 } 1593 1594 /** 1595 * Optionally updating user restrictions, calculate the effective user restrictions and also 1596 * propagate to other services and system settings. 1597 * 1598 * @param newBaseRestrictions User restrictions to set. 1599 * If null, will not update user restrictions and only does the propagation. 1600 * @param userId target user ID. 1601 */ 1602 @GuardedBy("mRestrictionsLock") 1603 private void updateUserRestrictionsInternalLR( 1604 @Nullable Bundle newBaseRestrictions, int userId) { 1605 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull( 1606 mAppliedUserRestrictions.get(userId)); 1607 1608 // Update base restrictions. 1609 if (newBaseRestrictions != null) { 1610 // If newBaseRestrictions == the current one, it's probably a bug. 1611 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId); 1612 1613 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions); 1614 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId) 1615 != newBaseRestrictions); 1616 1617 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) { 1618 scheduleWriteUser(getUserDataNoChecks(userId)); 1619 } 1620 } 1621 1622 final Bundle effective = computeEffectiveUserRestrictionsLR(userId); 1623 1624 mCachedEffectiveUserRestrictions.put(userId, effective); 1625 1626 // Apply the new restrictions. 1627 if (DBG) { 1628 debug("Applying user restrictions: userId=" + userId 1629 + " new=" + effective + " prev=" + prevAppliedRestrictions); 1630 } 1631 1632 if (mAppOpsService != null) { // We skip it until system-ready. 1633 mHandler.post(new Runnable() { 1634 @Override 1635 public void run() { 1636 try { 1637 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId); 1638 } catch (RemoteException e) { 1639 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions"); 1640 } 1641 } 1642 }); 1643 } 1644 1645 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions); 1646 1647 mAppliedUserRestrictions.put(userId, new Bundle(effective)); 1648 } 1649 1650 private void propagateUserRestrictionsLR(final int userId, 1651 Bundle newRestrictions, Bundle prevRestrictions) { 1652 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock 1653 // actually, but we still need some kind of synchronization otherwise we might end up 1654 // calling listeners out-of-order, thus "LR". 1655 1656 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) { 1657 return; 1658 } 1659 1660 final Bundle newRestrictionsFinal = new Bundle(newRestrictions); 1661 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions); 1662 1663 mHandler.post(new Runnable() { 1664 @Override 1665 public void run() { 1666 UserRestrictionsUtils.applyUserRestrictions( 1667 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal); 1668 1669 final UserRestrictionsListener[] listeners; 1670 synchronized (mUserRestrictionsListeners) { 1671 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()]; 1672 mUserRestrictionsListeners.toArray(listeners); 1673 } 1674 for (int i = 0; i < listeners.length; i++) { 1675 listeners[i].onUserRestrictionsChanged(userId, 1676 newRestrictionsFinal, prevRestrictionsFinal); 1677 } 1678 1679 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED) 1680 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 1681 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId)); 1682 } 1683 }); 1684 } 1685 1686 // Package private for the inner class. 1687 void applyUserRestrictionsLR(int userId) { 1688 updateUserRestrictionsInternalLR(null, userId); 1689 } 1690 1691 @GuardedBy("mRestrictionsLock") 1692 // Package private for the inner class. 1693 void applyUserRestrictionsForAllUsersLR() { 1694 if (DBG) { 1695 debug("applyUserRestrictionsForAllUsersLR"); 1696 } 1697 // First, invalidate all cached values. 1698 mCachedEffectiveUserRestrictions.clear(); 1699 1700 // We don't want to call into ActivityManagerService while taking a lock, so we'll call 1701 // it on a handler. 1702 final Runnable r = new Runnable() { 1703 @Override 1704 public void run() { 1705 // Then get the list of running users. 1706 final int[] runningUsers; 1707 try { 1708 runningUsers = ActivityManager.getService().getRunningUserIds(); 1709 } catch (RemoteException e) { 1710 Log.w(LOG_TAG, "Unable to access ActivityManagerService"); 1711 return; 1712 } 1713 // Then re-calculate the effective restrictions and apply, only for running users. 1714 // It's okay if a new user has started after the getRunningUserIds() call, 1715 // because we'll do the same thing (re-calculate the restrictions and apply) 1716 // when we start a user. 1717 synchronized (mRestrictionsLock) { 1718 for (int i = 0; i < runningUsers.length; i++) { 1719 applyUserRestrictionsLR(runningUsers[i]); 1720 } 1721 } 1722 } 1723 }; 1724 mHandler.post(r); 1725 } 1726 1727 /** 1728 * Check if we've hit the limit of how many users can be created. 1729 */ 1730 private boolean isUserLimitReached() { 1731 int count; 1732 synchronized (mUsersLock) { 1733 count = getAliveUsersExcludingGuestsCountLU(); 1734 } 1735 return count >= UserManager.getMaxSupportedUsers(); 1736 } 1737 1738 @Override 1739 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) { 1740 checkManageUsersPermission("check if more managed profiles can be added."); 1741 if (ActivityManager.isLowRamDeviceStatic()) { 1742 return false; 1743 } 1744 if (!mContext.getPackageManager().hasSystemFeature( 1745 PackageManager.FEATURE_MANAGED_USERS)) { 1746 return false; 1747 } 1748 // Limit number of managed profiles that can be created 1749 final int managedProfilesCount = getProfiles(userId, false).size() - 1; 1750 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0; 1751 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) { 1752 return false; 1753 } 1754 synchronized(mUsersLock) { 1755 UserInfo userInfo = getUserInfoLU(userId); 1756 if (userInfo == null || !userInfo.canHaveProfile()) { 1757 return false; 1758 } 1759 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU() 1760 - profilesRemovedCount; 1761 // We allow creating a managed profile in the special case where there is only one user. 1762 return usersCountAfterRemoving == 1 1763 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers(); 1764 } 1765 } 1766 1767 private int getAliveUsersExcludingGuestsCountLU() { 1768 int aliveUserCount = 0; 1769 final int totalUserCount = mUsers.size(); 1770 // Skip over users being removed 1771 for (int i = 0; i < totalUserCount; i++) { 1772 UserInfo user = mUsers.valueAt(i).info; 1773 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) { 1774 aliveUserCount++; 1775 } 1776 } 1777 return aliveUserCount; 1778 } 1779 1780 /** 1781 * Enforces that only the system UID or root's UID or apps that have the 1782 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and 1783 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL} 1784 * permissions can make certain calls to the UserManager. 1785 * 1786 * @param message used as message if SecurityException is thrown 1787 * @throws SecurityException if the caller does not have enough privilege. 1788 */ 1789 private static final void checkManageUserAndAcrossUsersFullPermission(String message) { 1790 final int uid = Binder.getCallingUid(); 1791 if (uid != Process.SYSTEM_UID && uid != 0 1792 && ActivityManager.checkComponentPermission( 1793 Manifest.permission.MANAGE_USERS, 1794 uid, -1, true) != PackageManager.PERMISSION_GRANTED 1795 && ActivityManager.checkComponentPermission( 1796 Manifest.permission.INTERACT_ACROSS_USERS_FULL, 1797 uid, -1, true) != PackageManager.PERMISSION_GRANTED) { 1798 throw new SecurityException( 1799 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " 1800 + message); 1801 } 1802 } 1803 1804 /** 1805 * Enforces that only the system UID or root's UID or apps that have the 1806 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} 1807 * permission can make certain calls to the UserManager. 1808 * 1809 * @param message used as message if SecurityException is thrown 1810 * @throws SecurityException if the caller is not system or root 1811 * @see #hasManageUsersPermission() 1812 */ 1813 private static final void checkManageUsersPermission(String message) { 1814 if (!hasManageUsersPermission()) { 1815 throw new SecurityException("You need MANAGE_USERS permission to: " + message); 1816 } 1817 } 1818 1819 /** 1820 * Enforces that only the system UID or root's UID or apps that have the 1821 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 1822 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} 1823 * can make certain calls to the UserManager. 1824 * 1825 * @param message used as message if SecurityException is thrown 1826 * @throws SecurityException if the caller is not system or root 1827 * @see #hasManageOrCreateUsersPermission() 1828 */ 1829 private static final void checkManageOrCreateUsersPermission(String message) { 1830 if (!hasManageOrCreateUsersPermission()) { 1831 throw new SecurityException( 1832 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message); 1833 } 1834 } 1835 1836 /** 1837 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries 1838 * to create user/profiles other than what is allowed for 1839 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only 1840 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission. 1841 */ 1842 private static final void checkManageOrCreateUsersPermission(int creationFlags) { 1843 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) { 1844 if (!hasManageOrCreateUsersPermission()) { 1845 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS " 1846 + "permission to create an user with flags: " + creationFlags); 1847 } 1848 } else if (!hasManageUsersPermission()) { 1849 throw new SecurityException("You need MANAGE_USERS permission to create an user " 1850 + " with flags: " + creationFlags); 1851 } 1852 } 1853 1854 /** 1855 * @return whether the calling UID is system UID or root's UID or the calling app has the 1856 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}. 1857 */ 1858 private static final boolean hasManageUsersPermission() { 1859 final int callingUid = Binder.getCallingUid(); 1860 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) 1861 || callingUid == Process.ROOT_UID 1862 || ActivityManager.checkComponentPermission( 1863 android.Manifest.permission.MANAGE_USERS, 1864 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED; 1865 } 1866 1867 /** 1868 * @return whether the calling UID is system UID or root's UID or the calling app has the 1869 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 1870 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}. 1871 */ 1872 private static final boolean hasManageOrCreateUsersPermission() { 1873 final int callingUid = Binder.getCallingUid(); 1874 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) 1875 || callingUid == Process.ROOT_UID 1876 || ActivityManager.checkComponentPermission( 1877 android.Manifest.permission.MANAGE_USERS, 1878 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED 1879 || ActivityManager.checkComponentPermission( 1880 android.Manifest.permission.CREATE_USERS, 1881 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED; 1882 } 1883 1884 /** 1885 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the 1886 * UserManager. 1887 * 1888 * @param message used as message if SecurityException is thrown 1889 * @throws SecurityException if the caller is not system or root 1890 */ 1891 private static void checkSystemOrRoot(String message) { 1892 final int uid = Binder.getCallingUid(); 1893 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) { 1894 throw new SecurityException("Only system may: " + message); 1895 } 1896 } 1897 1898 private void writeBitmapLP(UserInfo info, Bitmap bitmap) { 1899 try { 1900 File dir = new File(mUsersDir, Integer.toString(info.id)); 1901 File file = new File(dir, USER_PHOTO_FILENAME); 1902 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP); 1903 if (!dir.exists()) { 1904 dir.mkdir(); 1905 FileUtils.setPermissions( 1906 dir.getPath(), 1907 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 1908 -1, -1); 1909 } 1910 FileOutputStream os; 1911 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp)) 1912 && tmp.renameTo(file) && SELinux.restorecon(file)) { 1913 info.iconPath = file.getAbsolutePath(); 1914 } 1915 try { 1916 os.close(); 1917 } catch (IOException ioe) { 1918 // What the ... ! 1919 } 1920 tmp.delete(); 1921 } catch (FileNotFoundException e) { 1922 Slog.w(LOG_TAG, "Error setting photo for user ", e); 1923 } 1924 } 1925 1926 /** 1927 * Returns an array of user ids. This array is cached here for quick access, so do not modify or 1928 * cache it elsewhere. 1929 * @return the array of user ids. 1930 */ 1931 public int[] getUserIds() { 1932 synchronized (mUsersLock) { 1933 return mUserIds; 1934 } 1935 } 1936 1937 private void readUserListLP() { 1938 if (!mUserListFile.exists()) { 1939 fallbackToSingleUserLP(); 1940 return; 1941 } 1942 FileInputStream fis = null; 1943 AtomicFile userListFile = new AtomicFile(mUserListFile); 1944 try { 1945 fis = userListFile.openRead(); 1946 XmlPullParser parser = Xml.newPullParser(); 1947 parser.setInput(fis, StandardCharsets.UTF_8.name()); 1948 int type; 1949 while ((type = parser.next()) != XmlPullParser.START_TAG 1950 && type != XmlPullParser.END_DOCUMENT) { 1951 // Skip 1952 } 1953 1954 if (type != XmlPullParser.START_TAG) { 1955 Slog.e(LOG_TAG, "Unable to read user list"); 1956 fallbackToSingleUserLP(); 1957 return; 1958 } 1959 1960 mNextSerialNumber = -1; 1961 if (parser.getName().equals(TAG_USERS)) { 1962 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO); 1963 if (lastSerialNumber != null) { 1964 mNextSerialNumber = Integer.parseInt(lastSerialNumber); 1965 } 1966 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION); 1967 if (versionNumber != null) { 1968 mUserVersion = Integer.parseInt(versionNumber); 1969 } 1970 } 1971 1972 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user 1973 // currently), take care of it in case of upgrade. 1974 Bundle oldDevicePolicyGlobalUserRestrictions = null; 1975 1976 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 1977 if (type == XmlPullParser.START_TAG) { 1978 final String name = parser.getName(); 1979 if (name.equals(TAG_USER)) { 1980 String id = parser.getAttributeValue(null, ATTR_ID); 1981 1982 UserData userData = readUserLP(Integer.parseInt(id)); 1983 1984 if (userData != null) { 1985 synchronized (mUsersLock) { 1986 mUsers.put(userData.info.id, userData); 1987 if (mNextSerialNumber < 0 1988 || mNextSerialNumber <= userData.info.id) { 1989 mNextSerialNumber = userData.info.id + 1; 1990 } 1991 } 1992 } 1993 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) { 1994 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 1995 && type != XmlPullParser.END_TAG) { 1996 if (type == XmlPullParser.START_TAG) { 1997 if (parser.getName().equals(TAG_RESTRICTIONS)) { 1998 synchronized (mGuestRestrictions) { 1999 UserRestrictionsUtils 2000 .readRestrictions(parser, mGuestRestrictions); 2001 } 2002 } 2003 break; 2004 } 2005 } 2006 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID) 2007 // Legacy name, should only be encountered when upgrading from pre-O. 2008 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) { 2009 String ownerUserId = parser.getAttributeValue(null, ATTR_ID); 2010 if (ownerUserId != null) { 2011 mDeviceOwnerUserId = Integer.parseInt(ownerUserId); 2012 } 2013 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) { 2014 // Should only happen when upgrading from pre-O (version < 7). 2015 oldDevicePolicyGlobalUserRestrictions = 2016 UserRestrictionsUtils.readRestrictions(parser); 2017 } 2018 } 2019 } 2020 2021 updateUserIds(); 2022 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions); 2023 } catch (IOException | XmlPullParserException e) { 2024 fallbackToSingleUserLP(); 2025 } finally { 2026 IoUtils.closeQuietly(fis); 2027 } 2028 } 2029 2030 /** 2031 * Upgrade steps between versions, either for fixing bugs or changing the data format. 2032 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions. 2033 */ 2034 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) { 2035 final int originalVersion = mUserVersion; 2036 int userVersion = mUserVersion; 2037 if (userVersion < 1) { 2038 // Assign a proper name for the owner, if not initialized correctly before 2039 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM); 2040 if ("Primary".equals(userData.info.name)) { 2041 userData.info.name = 2042 mContext.getResources().getString(com.android.internal.R.string.owner_name); 2043 scheduleWriteUser(userData); 2044 } 2045 userVersion = 1; 2046 } 2047 2048 if (userVersion < 2) { 2049 // Owner should be marked as initialized 2050 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM); 2051 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) { 2052 userData.info.flags |= UserInfo.FLAG_INITIALIZED; 2053 scheduleWriteUser(userData); 2054 } 2055 userVersion = 2; 2056 } 2057 2058 2059 if (userVersion < 4) { 2060 userVersion = 4; 2061 } 2062 2063 if (userVersion < 5) { 2064 initDefaultGuestRestrictions(); 2065 userVersion = 5; 2066 } 2067 2068 if (userVersion < 6) { 2069 final boolean splitSystemUser = UserManager.isSplitSystemUser(); 2070 synchronized (mUsersLock) { 2071 for (int i = 0; i < mUsers.size(); i++) { 2072 UserData userData = mUsers.valueAt(i); 2073 // In non-split mode, only user 0 can have restricted profiles 2074 if (!splitSystemUser && userData.info.isRestricted() 2075 && (userData.info.restrictedProfileParentId 2076 == UserInfo.NO_PROFILE_GROUP_ID)) { 2077 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM; 2078 scheduleWriteUser(userData); 2079 } 2080 } 2081 } 2082 userVersion = 6; 2083 } 2084 2085 if (userVersion < 7) { 2086 // Previously only one user could enforce global restrictions, now it is per-user. 2087 synchronized (mRestrictionsLock) { 2088 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions) 2089 && mDeviceOwnerUserId != UserHandle.USER_NULL) { 2090 mDevicePolicyGlobalUserRestrictions.put( 2091 mDeviceOwnerUserId, oldGlobalUserRestrictions); 2092 } 2093 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move 2094 // it from local to global bundle for all users who set it. 2095 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS, 2096 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions 2097 ); 2098 } 2099 userVersion = 7; 2100 } 2101 2102 if (userVersion < USER_VERSION) { 2103 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to " 2104 + USER_VERSION); 2105 } else { 2106 mUserVersion = userVersion; 2107 2108 if (originalVersion < mUserVersion) { 2109 writeUserListLP(); 2110 } 2111 } 2112 } 2113 2114 private void fallbackToSingleUserLP() { 2115 int flags = UserInfo.FLAG_INITIALIZED; 2116 // In split system user mode, the admin and primary flags are assigned to the first human 2117 // user. 2118 if (!UserManager.isSplitSystemUser()) { 2119 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY; 2120 } 2121 // Create the system user 2122 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags); 2123 UserData userData = putUserInfo(system); 2124 mNextSerialNumber = MIN_USER_ID; 2125 mUserVersion = USER_VERSION; 2126 2127 Bundle restrictions = new Bundle(); 2128 try { 2129 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray( 2130 com.android.internal.R.array.config_defaultFirstUserRestrictions); 2131 for (String userRestriction : defaultFirstUserRestrictions) { 2132 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) { 2133 restrictions.putBoolean(userRestriction, true); 2134 } 2135 } 2136 } catch (Resources.NotFoundException e) { 2137 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e); 2138 } 2139 2140 if (!restrictions.isEmpty()) { 2141 synchronized (mRestrictionsLock) { 2142 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions); 2143 } 2144 } 2145 2146 updateUserIds(); 2147 initDefaultGuestRestrictions(); 2148 2149 writeUserLP(userData); 2150 writeUserListLP(); 2151 } 2152 2153 private String getOwnerName() { 2154 return mContext.getResources().getString(com.android.internal.R.string.owner_name); 2155 } 2156 2157 private void scheduleWriteUser(UserData UserData) { 2158 if (DBG) { 2159 debug("scheduleWriteUser"); 2160 } 2161 // No need to wrap it within a lock -- worst case, we'll just post the same message 2162 // twice. 2163 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) { 2164 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData); 2165 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY); 2166 } 2167 } 2168 2169 private void writeUserLP(UserData userData) { 2170 if (DBG) { 2171 debug("writeUserLP " + userData); 2172 } 2173 FileOutputStream fos = null; 2174 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX)); 2175 try { 2176 fos = userFile.startWrite(); 2177 final BufferedOutputStream bos = new BufferedOutputStream(fos); 2178 writeUserLP(userData, bos); 2179 userFile.finishWrite(fos); 2180 } catch (Exception ioe) { 2181 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe); 2182 userFile.failWrite(fos); 2183 } 2184 } 2185 2186 /* 2187 * Writes the user file in this format: 2188 * 2189 * <user flags="20039023" id="0"> 2190 * <name>Primary</name> 2191 * </user> 2192 */ 2193 @VisibleForTesting 2194 void writeUserLP(UserData userData, OutputStream os) 2195 throws IOException, XmlPullParserException { 2196 // XmlSerializer serializer = XmlUtils.serializerInstance(); 2197 final XmlSerializer serializer = new FastXmlSerializer(); 2198 serializer.setOutput(os, StandardCharsets.UTF_8.name()); 2199 serializer.startDocument(null, true); 2200 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 2201 2202 final UserInfo userInfo = userData.info; 2203 serializer.startTag(null, TAG_USER); 2204 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id)); 2205 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber)); 2206 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags)); 2207 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime)); 2208 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME, 2209 Long.toString(userInfo.lastLoggedInTime)); 2210 if (userInfo.lastLoggedInFingerprint != null) { 2211 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT, 2212 userInfo.lastLoggedInFingerprint); 2213 } 2214 if (userInfo.iconPath != null) { 2215 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath); 2216 } 2217 if (userInfo.partial) { 2218 serializer.attribute(null, ATTR_PARTIAL, "true"); 2219 } 2220 if (userInfo.guestToRemove) { 2221 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true"); 2222 } 2223 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 2224 serializer.attribute(null, ATTR_PROFILE_GROUP_ID, 2225 Integer.toString(userInfo.profileGroupId)); 2226 } 2227 serializer.attribute(null, ATTR_PROFILE_BADGE, 2228 Integer.toString(userInfo.profileBadge)); 2229 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) { 2230 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID, 2231 Integer.toString(userInfo.restrictedProfileParentId)); 2232 } 2233 // Write seed data 2234 if (userData.persistSeedData) { 2235 if (userData.seedAccountName != null) { 2236 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName); 2237 } 2238 if (userData.seedAccountType != null) { 2239 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType); 2240 } 2241 } 2242 if (userInfo.name != null) { 2243 serializer.startTag(null, TAG_NAME); 2244 serializer.text(userInfo.name); 2245 serializer.endTag(null, TAG_NAME); 2246 } 2247 synchronized (mRestrictionsLock) { 2248 UserRestrictionsUtils.writeRestrictions(serializer, 2249 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS); 2250 UserRestrictionsUtils.writeRestrictions(serializer, 2251 mDevicePolicyLocalUserRestrictions.get(userInfo.id), 2252 TAG_DEVICE_POLICY_RESTRICTIONS); 2253 UserRestrictionsUtils.writeRestrictions(serializer, 2254 mDevicePolicyGlobalUserRestrictions.get(userInfo.id), 2255 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS); 2256 } 2257 2258 if (userData.account != null) { 2259 serializer.startTag(null, TAG_ACCOUNT); 2260 serializer.text(userData.account); 2261 serializer.endTag(null, TAG_ACCOUNT); 2262 } 2263 2264 if (userData.persistSeedData && userData.seedAccountOptions != null) { 2265 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS); 2266 userData.seedAccountOptions.saveToXml(serializer); 2267 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS); 2268 } 2269 2270 serializer.endTag(null, TAG_USER); 2271 2272 serializer.endDocument(); 2273 } 2274 2275 /* 2276 * Writes the user list file in this format: 2277 * 2278 * <users nextSerialNumber="3"> 2279 * <user id="0"></user> 2280 * <user id="2"></user> 2281 * </users> 2282 */ 2283 private void writeUserListLP() { 2284 if (DBG) { 2285 debug("writeUserList"); 2286 } 2287 FileOutputStream fos = null; 2288 AtomicFile userListFile = new AtomicFile(mUserListFile); 2289 try { 2290 fos = userListFile.startWrite(); 2291 final BufferedOutputStream bos = new BufferedOutputStream(fos); 2292 2293 // XmlSerializer serializer = XmlUtils.serializerInstance(); 2294 final XmlSerializer serializer = new FastXmlSerializer(); 2295 serializer.setOutput(bos, StandardCharsets.UTF_8.name()); 2296 serializer.startDocument(null, true); 2297 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 2298 2299 serializer.startTag(null, TAG_USERS); 2300 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber)); 2301 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion)); 2302 2303 serializer.startTag(null, TAG_GUEST_RESTRICTIONS); 2304 synchronized (mGuestRestrictions) { 2305 UserRestrictionsUtils 2306 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS); 2307 } 2308 serializer.endTag(null, TAG_GUEST_RESTRICTIONS); 2309 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID); 2310 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId)); 2311 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID); 2312 int[] userIdsToWrite; 2313 synchronized (mUsersLock) { 2314 userIdsToWrite = new int[mUsers.size()]; 2315 for (int i = 0; i < userIdsToWrite.length; i++) { 2316 UserInfo user = mUsers.valueAt(i).info; 2317 userIdsToWrite[i] = user.id; 2318 } 2319 } 2320 for (int id : userIdsToWrite) { 2321 serializer.startTag(null, TAG_USER); 2322 serializer.attribute(null, ATTR_ID, Integer.toString(id)); 2323 serializer.endTag(null, TAG_USER); 2324 } 2325 2326 serializer.endTag(null, TAG_USERS); 2327 2328 serializer.endDocument(); 2329 userListFile.finishWrite(fos); 2330 } catch (Exception e) { 2331 userListFile.failWrite(fos); 2332 Slog.e(LOG_TAG, "Error writing user list"); 2333 } 2334 } 2335 2336 private UserData readUserLP(int id) { 2337 FileInputStream fis = null; 2338 try { 2339 AtomicFile userFile = 2340 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX)); 2341 fis = userFile.openRead(); 2342 return readUserLP(id, fis); 2343 } catch (IOException ioe) { 2344 Slog.e(LOG_TAG, "Error reading user list"); 2345 } catch (XmlPullParserException pe) { 2346 Slog.e(LOG_TAG, "Error reading user list"); 2347 } finally { 2348 IoUtils.closeQuietly(fis); 2349 } 2350 return null; 2351 } 2352 2353 @VisibleForTesting 2354 UserData readUserLP(int id, InputStream is) throws IOException, 2355 XmlPullParserException { 2356 int flags = 0; 2357 int serialNumber = id; 2358 String name = null; 2359 String account = null; 2360 String iconPath = null; 2361 long creationTime = 0L; 2362 long lastLoggedInTime = 0L; 2363 String lastLoggedInFingerprint = null; 2364 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID; 2365 int profileBadge = 0; 2366 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID; 2367 boolean partial = false; 2368 boolean guestToRemove = false; 2369 boolean persistSeedData = false; 2370 String seedAccountName = null; 2371 String seedAccountType = null; 2372 PersistableBundle seedAccountOptions = null; 2373 Bundle baseRestrictions = null; 2374 Bundle localRestrictions = null; 2375 Bundle globalRestrictions = null; 2376 2377 XmlPullParser parser = Xml.newPullParser(); 2378 parser.setInput(is, StandardCharsets.UTF_8.name()); 2379 int type; 2380 while ((type = parser.next()) != XmlPullParser.START_TAG 2381 && type != XmlPullParser.END_DOCUMENT) { 2382 // Skip 2383 } 2384 2385 if (type != XmlPullParser.START_TAG) { 2386 Slog.e(LOG_TAG, "Unable to read user " + id); 2387 return null; 2388 } 2389 2390 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) { 2391 int storedId = readIntAttribute(parser, ATTR_ID, -1); 2392 if (storedId != id) { 2393 Slog.e(LOG_TAG, "User id does not match the file name"); 2394 return null; 2395 } 2396 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id); 2397 flags = readIntAttribute(parser, ATTR_FLAGS, 0); 2398 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH); 2399 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0); 2400 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0); 2401 lastLoggedInFingerprint = parser.getAttributeValue(null, 2402 ATTR_LAST_LOGGED_IN_FINGERPRINT); 2403 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID, 2404 UserInfo.NO_PROFILE_GROUP_ID); 2405 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0); 2406 restrictedProfileParentId = readIntAttribute(parser, 2407 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID); 2408 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL); 2409 if ("true".equals(valueString)) { 2410 partial = true; 2411 } 2412 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE); 2413 if ("true".equals(valueString)) { 2414 guestToRemove = true; 2415 } 2416 2417 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME); 2418 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE); 2419 if (seedAccountName != null || seedAccountType != null) { 2420 persistSeedData = true; 2421 } 2422 2423 int outerDepth = parser.getDepth(); 2424 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 2425 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2426 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 2427 continue; 2428 } 2429 String tag = parser.getName(); 2430 if (TAG_NAME.equals(tag)) { 2431 type = parser.next(); 2432 if (type == XmlPullParser.TEXT) { 2433 name = parser.getText(); 2434 } 2435 } else if (TAG_RESTRICTIONS.equals(tag)) { 2436 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser); 2437 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) { 2438 localRestrictions = UserRestrictionsUtils.readRestrictions(parser); 2439 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) { 2440 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser); 2441 } else if (TAG_ACCOUNT.equals(tag)) { 2442 type = parser.next(); 2443 if (type == XmlPullParser.TEXT) { 2444 account = parser.getText(); 2445 } 2446 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) { 2447 seedAccountOptions = PersistableBundle.restoreFromXml(parser); 2448 persistSeedData = true; 2449 } 2450 } 2451 } 2452 2453 // Create the UserInfo object that gets passed around 2454 UserInfo userInfo = new UserInfo(id, name, iconPath, flags); 2455 userInfo.serialNumber = serialNumber; 2456 userInfo.creationTime = creationTime; 2457 userInfo.lastLoggedInTime = lastLoggedInTime; 2458 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint; 2459 userInfo.partial = partial; 2460 userInfo.guestToRemove = guestToRemove; 2461 userInfo.profileGroupId = profileGroupId; 2462 userInfo.profileBadge = profileBadge; 2463 userInfo.restrictedProfileParentId = restrictedProfileParentId; 2464 2465 // Create the UserData object that's internal to this class 2466 UserData userData = new UserData(); 2467 userData.info = userInfo; 2468 userData.account = account; 2469 userData.seedAccountName = seedAccountName; 2470 userData.seedAccountType = seedAccountType; 2471 userData.persistSeedData = persistSeedData; 2472 userData.seedAccountOptions = seedAccountOptions; 2473 2474 synchronized (mRestrictionsLock) { 2475 if (baseRestrictions != null) { 2476 mBaseUserRestrictions.put(id, baseRestrictions); 2477 } 2478 if (localRestrictions != null) { 2479 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions); 2480 } 2481 if (globalRestrictions != null) { 2482 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions); 2483 } 2484 } 2485 return userData; 2486 } 2487 2488 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) { 2489 String valueString = parser.getAttributeValue(null, attr); 2490 if (valueString == null) return defaultValue; 2491 try { 2492 return Integer.parseInt(valueString); 2493 } catch (NumberFormatException nfe) { 2494 return defaultValue; 2495 } 2496 } 2497 2498 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) { 2499 String valueString = parser.getAttributeValue(null, attr); 2500 if (valueString == null) return defaultValue; 2501 try { 2502 return Long.parseLong(valueString); 2503 } catch (NumberFormatException nfe) { 2504 return defaultValue; 2505 } 2506 } 2507 2508 /** 2509 * Removes the app restrictions file for a specific package and user id, if it exists. 2510 */ 2511 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) { 2512 File dir = Environment.getUserSystemDirectory(userId); 2513 File resFile = new File(dir, packageToRestrictionsFileName(pkg)); 2514 if (resFile.exists()) { 2515 resFile.delete(); 2516 } 2517 } 2518 2519 @Override 2520 public UserInfo createProfileForUser(String name, int flags, int userId, 2521 String[] disallowedPackages) { 2522 checkManageOrCreateUsersPermission(flags); 2523 return createUserInternal(name, flags, userId, disallowedPackages); 2524 } 2525 2526 @Override 2527 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId, 2528 String[] disallowedPackages) { 2529 checkManageOrCreateUsersPermission(flags); 2530 return createUserInternalUnchecked(name, flags, userId, disallowedPackages); 2531 } 2532 2533 @Override 2534 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) { 2535 checkManageOrCreateUsersPermission("Only the system can remove users"); 2536 return removeUserUnchecked(userHandle); 2537 } 2538 2539 @Override 2540 public UserInfo createUser(String name, int flags) { 2541 checkManageOrCreateUsersPermission(flags); 2542 return createUserInternal(name, flags, UserHandle.USER_NULL); 2543 } 2544 2545 private UserInfo createUserInternal(String name, int flags, int parentId) { 2546 return createUserInternal(name, flags, parentId, null); 2547 } 2548 2549 private UserInfo createUserInternal(String name, int flags, int parentId, 2550 String[] disallowedPackages) { 2551 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0) 2552 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE 2553 : UserManager.DISALLOW_ADD_USER; 2554 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) { 2555 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled."); 2556 return null; 2557 } 2558 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages); 2559 } 2560 2561 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId, 2562 String[] disallowedPackages) { 2563 DeviceStorageMonitorInternal dsm = LocalServices 2564 .getService(DeviceStorageMonitorInternal.class); 2565 if (dsm.isMemoryLow()) { 2566 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk."); 2567 return null; 2568 } 2569 if (ActivityManager.isLowRamDeviceStatic()) { 2570 return null; 2571 } 2572 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0; 2573 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0; 2574 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0; 2575 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0; 2576 final long ident = Binder.clearCallingIdentity(); 2577 UserInfo userInfo; 2578 UserData userData; 2579 final int userId; 2580 try { 2581 synchronized (mPackagesLock) { 2582 UserData parent = null; 2583 if (parentId != UserHandle.USER_NULL) { 2584 synchronized (mUsersLock) { 2585 parent = getUserDataLU(parentId); 2586 } 2587 if (parent == null) return null; 2588 } 2589 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) { 2590 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId); 2591 return null; 2592 } 2593 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) { 2594 // If we're not adding a guest/demo user or a managed profile and the limit has 2595 // been reached, cannot add a user. 2596 return null; 2597 } 2598 // If we're adding a guest and there already exists one, bail. 2599 if (isGuest && findCurrentGuestUser() != null) { 2600 return null; 2601 } 2602 // In legacy mode, restricted profile's parent can only be the owner user 2603 if (isRestricted && !UserManager.isSplitSystemUser() 2604 && (parentId != UserHandle.USER_SYSTEM)) { 2605 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner"); 2606 return null; 2607 } 2608 if (isRestricted && UserManager.isSplitSystemUser()) { 2609 if (parent == null) { 2610 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be " 2611 + "specified"); 2612 return null; 2613 } 2614 if (!parent.info.canHaveProfile()) { 2615 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be " 2616 + "created for the specified parent user id " + parentId); 2617 return null; 2618 } 2619 } 2620 // In split system user mode, we assign the first human user the primary flag. 2621 // And if there is no device owner, we also assign the admin flag to primary user. 2622 if (UserManager.isSplitSystemUser() 2623 && !isGuest && !isManagedProfile && getPrimaryUser() == null) { 2624 flags |= UserInfo.FLAG_PRIMARY; 2625 synchronized (mUsersLock) { 2626 if (!mIsDeviceManaged) { 2627 flags |= UserInfo.FLAG_ADMIN; 2628 } 2629 } 2630 } 2631 2632 userId = getNextAvailableId(); 2633 Environment.getUserSystemDirectory(userId).mkdirs(); 2634 boolean ephemeralGuests = Resources.getSystem() 2635 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral); 2636 2637 synchronized (mUsersLock) { 2638 // Add ephemeral flag to guests/users if required. Also inherit it from parent. 2639 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers 2640 || (parent != null && parent.info.isEphemeral())) { 2641 flags |= UserInfo.FLAG_EPHEMERAL; 2642 } 2643 2644 userInfo = new UserInfo(userId, name, null, flags); 2645 userInfo.serialNumber = mNextSerialNumber++; 2646 long now = System.currentTimeMillis(); 2647 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0; 2648 userInfo.partial = true; 2649 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT; 2650 if (isManagedProfile && parentId != UserHandle.USER_NULL) { 2651 userInfo.profileBadge = getFreeProfileBadgeLU(parentId); 2652 } 2653 userData = new UserData(); 2654 userData.info = userInfo; 2655 mUsers.put(userId, userData); 2656 } 2657 writeUserLP(userData); 2658 writeUserListLP(); 2659 if (parent != null) { 2660 if (isManagedProfile) { 2661 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) { 2662 parent.info.profileGroupId = parent.info.id; 2663 writeUserLP(parent); 2664 } 2665 userInfo.profileGroupId = parent.info.profileGroupId; 2666 } else if (isRestricted) { 2667 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) { 2668 parent.info.restrictedProfileParentId = parent.info.id; 2669 writeUserLP(parent); 2670 } 2671 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId; 2672 } 2673 } 2674 } 2675 final StorageManager storage = mContext.getSystemService(StorageManager.class); 2676 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral()); 2677 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber, 2678 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2679 mPm.createNewUser(userId, disallowedPackages); 2680 userInfo.partial = false; 2681 synchronized (mPackagesLock) { 2682 writeUserLP(userData); 2683 } 2684 updateUserIds(); 2685 Bundle restrictions = new Bundle(); 2686 if (isGuest) { 2687 synchronized (mGuestRestrictions) { 2688 restrictions.putAll(mGuestRestrictions); 2689 } 2690 } 2691 synchronized (mRestrictionsLock) { 2692 mBaseUserRestrictions.append(userId, restrictions); 2693 } 2694 mPm.onNewUserCreated(userId); 2695 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED); 2696 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 2697 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL, 2698 android.Manifest.permission.MANAGE_USERS); 2699 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED 2700 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1); 2701 } finally { 2702 Binder.restoreCallingIdentity(ident); 2703 } 2704 return userInfo; 2705 } 2706 2707 @VisibleForTesting 2708 UserData putUserInfo(UserInfo userInfo) { 2709 final UserData userData = new UserData(); 2710 userData.info = userInfo; 2711 synchronized (mUsers) { 2712 mUsers.put(userInfo.id, userData); 2713 } 2714 return userData; 2715 } 2716 2717 @VisibleForTesting 2718 void removeUserInfo(int userId) { 2719 synchronized (mUsers) { 2720 mUsers.remove(userId); 2721 } 2722 } 2723 2724 /** 2725 * @hide 2726 */ 2727 @Override 2728 public UserInfo createRestrictedProfile(String name, int parentUserId) { 2729 checkManageOrCreateUsersPermission("setupRestrictedProfile"); 2730 final UserInfo user = createProfileForUser( 2731 name, UserInfo.FLAG_RESTRICTED, parentUserId, null); 2732 if (user == null) { 2733 return null; 2734 } 2735 long identity = Binder.clearCallingIdentity(); 2736 try { 2737 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id); 2738 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise 2739 // the putIntForUser() will fail. 2740 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(), 2741 android.provider.Settings.Secure.LOCATION_MODE, 2742 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id); 2743 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id); 2744 } finally { 2745 Binder.restoreCallingIdentity(identity); 2746 } 2747 return user; 2748 } 2749 2750 /** 2751 * Find the current guest user. If the Guest user is partial, 2752 * then do not include it in the results as it is about to die. 2753 */ 2754 private UserInfo findCurrentGuestUser() { 2755 synchronized (mUsersLock) { 2756 final int size = mUsers.size(); 2757 for (int i = 0; i < size; i++) { 2758 final UserInfo user = mUsers.valueAt(i).info; 2759 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) { 2760 return user; 2761 } 2762 } 2763 } 2764 return null; 2765 } 2766 2767 /** 2768 * Mark this guest user for deletion to allow us to create another guest 2769 * and switch to that user before actually removing this guest. 2770 * @param userHandle the userid of the current guest 2771 * @return whether the user could be marked for deletion 2772 */ 2773 @Override 2774 public boolean markGuestForDeletion(int userHandle) { 2775 checkManageUsersPermission("Only the system can remove users"); 2776 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean( 2777 UserManager.DISALLOW_REMOVE_USER, false)) { 2778 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled."); 2779 return false; 2780 } 2781 2782 long ident = Binder.clearCallingIdentity(); 2783 try { 2784 final UserData userData; 2785 synchronized (mPackagesLock) { 2786 synchronized (mUsersLock) { 2787 userData = mUsers.get(userHandle); 2788 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) { 2789 return false; 2790 } 2791 } 2792 if (!userData.info.isGuest()) { 2793 return false; 2794 } 2795 // We set this to a guest user that is to be removed. This is a temporary state 2796 // where we are allowed to add new Guest users, even if this one is still not 2797 // removed. This user will still show up in getUserInfo() calls. 2798 // If we don't get around to removing this Guest user, it will be purged on next 2799 // startup. 2800 userData.info.guestToRemove = true; 2801 // Mark it as disabled, so that it isn't returned any more when 2802 // profiles are queried. 2803 userData.info.flags |= UserInfo.FLAG_DISABLED; 2804 writeUserLP(userData); 2805 } 2806 } finally { 2807 Binder.restoreCallingIdentity(ident); 2808 } 2809 return true; 2810 } 2811 2812 /** 2813 * Removes a user and all data directories created for that user. This method should be called 2814 * after the user's processes have been terminated. 2815 * @param userHandle the user's id 2816 */ 2817 @Override 2818 public boolean removeUser(int userHandle) { 2819 Slog.i(LOG_TAG, "removeUser u" + userHandle); 2820 checkManageOrCreateUsersPermission("Only the system can remove users"); 2821 2822 final boolean isManagedProfile; 2823 synchronized (mUsersLock) { 2824 UserInfo userInfo = getUserInfoLU(userHandle); 2825 isManagedProfile = userInfo != null && userInfo.isManagedProfile(); 2826 } 2827 String restriction = isManagedProfile 2828 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER; 2829 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) { 2830 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled."); 2831 return false; 2832 } 2833 return removeUserUnchecked(userHandle); 2834 } 2835 2836 private boolean removeUserUnchecked(int userHandle) { 2837 long ident = Binder.clearCallingIdentity(); 2838 try { 2839 final UserData userData; 2840 int currentUser = ActivityManager.getCurrentUser(); 2841 if (currentUser == userHandle) { 2842 Log.w(LOG_TAG, "Current user cannot be removed"); 2843 return false; 2844 } 2845 synchronized (mPackagesLock) { 2846 synchronized (mUsersLock) { 2847 userData = mUsers.get(userHandle); 2848 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) { 2849 return false; 2850 } 2851 2852 addRemovingUserIdLocked(userHandle); 2853 } 2854 2855 // Set this to a partially created user, so that the user will be purged 2856 // on next startup, in case the runtime stops now before stopping and 2857 // removing the user completely. 2858 userData.info.partial = true; 2859 // Mark it as disabled, so that it isn't returned any more when 2860 // profiles are queried. 2861 userData.info.flags |= UserInfo.FLAG_DISABLED; 2862 writeUserLP(userData); 2863 } 2864 try { 2865 mAppOpsService.removeUser(userHandle); 2866 } catch (RemoteException e) { 2867 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e); 2868 } 2869 2870 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID 2871 && userData.info.isManagedProfile()) { 2872 // Send broadcast to notify system that the user removed was a 2873 // managed user. 2874 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id); 2875 } 2876 2877 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle); 2878 int res; 2879 try { 2880 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true, 2881 new IStopUserCallback.Stub() { 2882 @Override 2883 public void userStopped(int userId) { 2884 finishRemoveUser(userId); 2885 } 2886 @Override 2887 public void userStopAborted(int userId) { 2888 } 2889 }); 2890 } catch (RemoteException e) { 2891 return false; 2892 } 2893 return res == ActivityManager.USER_OP_SUCCESS; 2894 } finally { 2895 Binder.restoreCallingIdentity(ident); 2896 } 2897 } 2898 2899 @VisibleForTesting 2900 void addRemovingUserIdLocked(int userId) { 2901 // We remember deleted user IDs to prevent them from being 2902 // reused during the current boot; they can still be reused 2903 // after a reboot or recycling of userIds. 2904 mRemovingUserIds.put(userId, true); 2905 mRecentlyRemovedIds.add(userId); 2906 // Keep LRU queue of recently removed IDs for recycling 2907 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) { 2908 mRecentlyRemovedIds.removeFirst(); 2909 } 2910 } 2911 2912 void finishRemoveUser(final int userHandle) { 2913 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle); 2914 // Let other services shutdown any activity and clean up their state before completely 2915 // wiping the user's system directory and removing from the user list 2916 long ident = Binder.clearCallingIdentity(); 2917 try { 2918 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED); 2919 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle); 2920 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL, 2921 android.Manifest.permission.MANAGE_USERS, 2922 2923 new BroadcastReceiver() { 2924 @Override 2925 public void onReceive(Context context, Intent intent) { 2926 if (DBG) { 2927 Slog.i(LOG_TAG, 2928 "USER_REMOVED broadcast sent, cleaning up user data " 2929 + userHandle); 2930 } 2931 new Thread() { 2932 @Override 2933 public void run() { 2934 // Clean up any ActivityManager state 2935 LocalServices.getService(ActivityManagerInternal.class) 2936 .onUserRemoved(userHandle); 2937 removeUserState(userHandle); 2938 } 2939 }.start(); 2940 } 2941 }, 2942 2943 null, Activity.RESULT_OK, null, null); 2944 } finally { 2945 Binder.restoreCallingIdentity(ident); 2946 } 2947 } 2948 2949 private void removeUserState(final int userHandle) { 2950 try { 2951 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle); 2952 } catch (IllegalStateException e) { 2953 // This may be simply because the user was partially created. 2954 Slog.i(LOG_TAG, 2955 "Destroying key for user " + userHandle + " failed, continuing anyway", e); 2956 } 2957 2958 // Cleanup gatekeeper secure user id 2959 try { 2960 final IGateKeeperService gk = GateKeeper.getService(); 2961 if (gk != null) { 2962 gk.clearSecureUserId(userHandle); 2963 } 2964 } catch (Exception ex) { 2965 Slog.w(LOG_TAG, "unable to clear GK secure user id"); 2966 } 2967 2968 // Cleanup package manager settings 2969 mPm.cleanUpUser(this, userHandle); 2970 2971 // Clean up all data before removing metadata 2972 mUserDataPreparer.destroyUserData(userHandle, 2973 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2974 2975 // Remove this user from the list 2976 synchronized (mUsersLock) { 2977 mUsers.remove(userHandle); 2978 mIsUserManaged.delete(userHandle); 2979 } 2980 synchronized (mUserStates) { 2981 mUserStates.delete(userHandle); 2982 } 2983 synchronized (mRestrictionsLock) { 2984 mBaseUserRestrictions.remove(userHandle); 2985 mAppliedUserRestrictions.remove(userHandle); 2986 mCachedEffectiveUserRestrictions.remove(userHandle); 2987 mDevicePolicyLocalUserRestrictions.remove(userHandle); 2988 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) { 2989 mDevicePolicyGlobalUserRestrictions.remove(userHandle); 2990 applyUserRestrictionsForAllUsersLR(); 2991 } 2992 } 2993 // Update the user list 2994 synchronized (mPackagesLock) { 2995 writeUserListLP(); 2996 } 2997 // Remove user file 2998 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX)); 2999 userFile.delete(); 3000 updateUserIds(); 3001 if (RELEASE_DELETED_USER_ID) { 3002 synchronized (mUsers) { 3003 mRemovingUserIds.delete(userHandle); 3004 } 3005 } 3006 } 3007 3008 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) { 3009 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED); 3010 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 3011 Intent.FLAG_RECEIVER_FOREGROUND); 3012 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId)); 3013 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId); 3014 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null); 3015 } 3016 3017 @Override 3018 public Bundle getApplicationRestrictions(String packageName) { 3019 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId()); 3020 } 3021 3022 @Override 3023 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) { 3024 if (UserHandle.getCallingUserId() != userId 3025 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) { 3026 checkSystemOrRoot("get application restrictions for other user/app " + packageName); 3027 } 3028 synchronized (mAppRestrictionsLock) { 3029 // Read the restrictions from XML 3030 return readApplicationRestrictionsLAr(packageName, userId); 3031 } 3032 } 3033 3034 @Override 3035 public void setApplicationRestrictions(String packageName, Bundle restrictions, 3036 int userId) { 3037 checkSystemOrRoot("set application restrictions"); 3038 if (restrictions != null) { 3039 restrictions.setDefusable(true); 3040 } 3041 synchronized (mAppRestrictionsLock) { 3042 if (restrictions == null || restrictions.isEmpty()) { 3043 cleanAppRestrictionsForPackageLAr(packageName, userId); 3044 } else { 3045 // Write the restrictions to XML 3046 writeApplicationRestrictionsLAr(packageName, restrictions, userId); 3047 } 3048 } 3049 3050 // Notify package of changes via an intent - only sent to explicitly registered receivers. 3051 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED); 3052 changeIntent.setPackage(packageName); 3053 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 3054 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId)); 3055 } 3056 3057 private int getUidForPackage(String packageName) { 3058 long ident = Binder.clearCallingIdentity(); 3059 try { 3060 return mContext.getPackageManager().getApplicationInfo(packageName, 3061 PackageManager.MATCH_ANY_USER).uid; 3062 } catch (NameNotFoundException nnfe) { 3063 return -1; 3064 } finally { 3065 Binder.restoreCallingIdentity(ident); 3066 } 3067 } 3068 3069 @GuardedBy("mAppRestrictionsLock") 3070 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) { 3071 AtomicFile restrictionsFile = 3072 new AtomicFile(new File(Environment.getUserSystemDirectory(userId), 3073 packageToRestrictionsFileName(packageName))); 3074 return readApplicationRestrictionsLAr(restrictionsFile); 3075 } 3076 3077 @VisibleForTesting 3078 @GuardedBy("mAppRestrictionsLock") 3079 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) { 3080 final Bundle restrictions = new Bundle(); 3081 final ArrayList<String> values = new ArrayList<>(); 3082 if (!restrictionsFile.getBaseFile().exists()) { 3083 return restrictions; 3084 } 3085 3086 FileInputStream fis = null; 3087 try { 3088 fis = restrictionsFile.openRead(); 3089 XmlPullParser parser = Xml.newPullParser(); 3090 parser.setInput(fis, StandardCharsets.UTF_8.name()); 3091 XmlUtils.nextElement(parser); 3092 if (parser.getEventType() != XmlPullParser.START_TAG) { 3093 Slog.e(LOG_TAG, "Unable to read restrictions file " 3094 + restrictionsFile.getBaseFile()); 3095 return restrictions; 3096 } 3097 while (parser.next() != XmlPullParser.END_DOCUMENT) { 3098 readEntry(restrictions, values, parser); 3099 } 3100 } catch (IOException|XmlPullParserException e) { 3101 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e); 3102 } finally { 3103 IoUtils.closeQuietly(fis); 3104 } 3105 return restrictions; 3106 } 3107 3108 private static void readEntry(Bundle restrictions, ArrayList<String> values, 3109 XmlPullParser parser) throws XmlPullParserException, IOException { 3110 int type = parser.getEventType(); 3111 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) { 3112 String key = parser.getAttributeValue(null, ATTR_KEY); 3113 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE); 3114 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE); 3115 if (multiple != null) { 3116 values.clear(); 3117 int count = Integer.parseInt(multiple); 3118 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) { 3119 if (type == XmlPullParser.START_TAG 3120 && parser.getName().equals(TAG_VALUE)) { 3121 values.add(parser.nextText().trim()); 3122 count--; 3123 } 3124 } 3125 String [] valueStrings = new String[values.size()]; 3126 values.toArray(valueStrings); 3127 restrictions.putStringArray(key, valueStrings); 3128 } else if (ATTR_TYPE_BUNDLE.equals(valType)) { 3129 restrictions.putBundle(key, readBundleEntry(parser, values)); 3130 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) { 3131 final int outerDepth = parser.getDepth(); 3132 ArrayList<Bundle> bundleList = new ArrayList<>(); 3133 while (XmlUtils.nextElementWithin(parser, outerDepth)) { 3134 Bundle childBundle = readBundleEntry(parser, values); 3135 bundleList.add(childBundle); 3136 } 3137 restrictions.putParcelableArray(key, 3138 bundleList.toArray(new Bundle[bundleList.size()])); 3139 } else { 3140 String value = parser.nextText().trim(); 3141 if (ATTR_TYPE_BOOLEAN.equals(valType)) { 3142 restrictions.putBoolean(key, Boolean.parseBoolean(value)); 3143 } else if (ATTR_TYPE_INTEGER.equals(valType)) { 3144 restrictions.putInt(key, Integer.parseInt(value)); 3145 } else { 3146 restrictions.putString(key, value); 3147 } 3148 } 3149 } 3150 } 3151 3152 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values) 3153 throws IOException, XmlPullParserException { 3154 Bundle childBundle = new Bundle(); 3155 final int outerDepth = parser.getDepth(); 3156 while (XmlUtils.nextElementWithin(parser, outerDepth)) { 3157 readEntry(childBundle, values, parser); 3158 } 3159 return childBundle; 3160 } 3161 3162 @GuardedBy("mAppRestrictionsLock") 3163 private static void writeApplicationRestrictionsLAr(String packageName, 3164 Bundle restrictions, int userId) { 3165 AtomicFile restrictionsFile = new AtomicFile( 3166 new File(Environment.getUserSystemDirectory(userId), 3167 packageToRestrictionsFileName(packageName))); 3168 writeApplicationRestrictionsLAr(restrictions, restrictionsFile); 3169 } 3170 3171 @VisibleForTesting 3172 @GuardedBy("mAppRestrictionsLock") 3173 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) { 3174 FileOutputStream fos = null; 3175 try { 3176 fos = restrictionsFile.startWrite(); 3177 final BufferedOutputStream bos = new BufferedOutputStream(fos); 3178 3179 final XmlSerializer serializer = new FastXmlSerializer(); 3180 serializer.setOutput(bos, StandardCharsets.UTF_8.name()); 3181 serializer.startDocument(null, true); 3182 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 3183 3184 serializer.startTag(null, TAG_RESTRICTIONS); 3185 writeBundle(restrictions, serializer); 3186 serializer.endTag(null, TAG_RESTRICTIONS); 3187 3188 serializer.endDocument(); 3189 restrictionsFile.finishWrite(fos); 3190 } catch (Exception e) { 3191 restrictionsFile.failWrite(fos); 3192 Slog.e(LOG_TAG, "Error writing application restrictions list", e); 3193 } 3194 } 3195 3196 private static void writeBundle(Bundle restrictions, XmlSerializer serializer) 3197 throws IOException { 3198 for (String key : restrictions.keySet()) { 3199 Object value = restrictions.get(key); 3200 serializer.startTag(null, TAG_ENTRY); 3201 serializer.attribute(null, ATTR_KEY, key); 3202 3203 if (value instanceof Boolean) { 3204 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN); 3205 serializer.text(value.toString()); 3206 } else if (value instanceof Integer) { 3207 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER); 3208 serializer.text(value.toString()); 3209 } else if (value == null || value instanceof String) { 3210 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING); 3211 serializer.text(value != null ? (String) value : ""); 3212 } else if (value instanceof Bundle) { 3213 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE); 3214 writeBundle((Bundle) value, serializer); 3215 } else if (value instanceof Parcelable[]) { 3216 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY); 3217 Parcelable[] array = (Parcelable[]) value; 3218 for (Parcelable parcelable : array) { 3219 if (!(parcelable instanceof Bundle)) { 3220 throw new IllegalArgumentException("bundle-array can only hold Bundles"); 3221 } 3222 serializer.startTag(null, TAG_ENTRY); 3223 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE); 3224 writeBundle((Bundle) parcelable, serializer); 3225 serializer.endTag(null, TAG_ENTRY); 3226 } 3227 } else { 3228 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY); 3229 String[] values = (String[]) value; 3230 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length)); 3231 for (String choice : values) { 3232 serializer.startTag(null, TAG_VALUE); 3233 serializer.text(choice != null ? choice : ""); 3234 serializer.endTag(null, TAG_VALUE); 3235 } 3236 } 3237 serializer.endTag(null, TAG_ENTRY); 3238 } 3239 } 3240 3241 @Override 3242 public int getUserSerialNumber(int userHandle) { 3243 synchronized (mUsersLock) { 3244 if (!exists(userHandle)) return -1; 3245 return getUserInfoLU(userHandle).serialNumber; 3246 } 3247 } 3248 3249 @Override 3250 public boolean isUserNameSet(int userHandle) { 3251 synchronized (mUsersLock) { 3252 UserInfo userInfo = getUserInfoLU(userHandle); 3253 return userInfo != null && userInfo.name != null; 3254 } 3255 } 3256 3257 @Override 3258 public int getUserHandle(int userSerialNumber) { 3259 synchronized (mUsersLock) { 3260 for (int userId : mUserIds) { 3261 UserInfo info = getUserInfoLU(userId); 3262 if (info != null && info.serialNumber == userSerialNumber) return userId; 3263 } 3264 // Not found 3265 return -1; 3266 } 3267 } 3268 3269 @Override 3270 public long getUserCreationTime(int userHandle) { 3271 int callingUserId = UserHandle.getCallingUserId(); 3272 UserInfo userInfo = null; 3273 synchronized (mUsersLock) { 3274 if (callingUserId == userHandle) { 3275 userInfo = getUserInfoLU(userHandle); 3276 } else { 3277 UserInfo parent = getProfileParentLU(userHandle); 3278 if (parent != null && parent.id == callingUserId) { 3279 userInfo = getUserInfoLU(userHandle); 3280 } 3281 } 3282 } 3283 if (userInfo == null) { 3284 throw new SecurityException("userHandle can only be the calling user or a managed " 3285 + "profile associated with this user"); 3286 } 3287 return userInfo.creationTime; 3288 } 3289 3290 /** 3291 * Caches the list of user ids in an array, adjusting the array size when necessary. 3292 */ 3293 private void updateUserIds() { 3294 int num = 0; 3295 synchronized (mUsersLock) { 3296 final int userSize = mUsers.size(); 3297 for (int i = 0; i < userSize; i++) { 3298 if (!mUsers.valueAt(i).info.partial) { 3299 num++; 3300 } 3301 } 3302 final int[] newUsers = new int[num]; 3303 int n = 0; 3304 for (int i = 0; i < userSize; i++) { 3305 if (!mUsers.valueAt(i).info.partial) { 3306 newUsers[n++] = mUsers.keyAt(i); 3307 } 3308 } 3309 mUserIds = newUsers; 3310 } 3311 } 3312 3313 /** 3314 * Called right before a user is started. This gives us a chance to prepare 3315 * app storage and apply any user restrictions. 3316 */ 3317 public void onBeforeStartUser(int userId) { 3318 UserInfo userInfo = getUserInfo(userId); 3319 if (userInfo == null) { 3320 return; 3321 } 3322 final int userSerial = userInfo.serialNumber; 3323 // Migrate only if build fingerprints mismatch 3324 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint); 3325 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE); 3326 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData); 3327 3328 if (userId != UserHandle.USER_SYSTEM) { 3329 synchronized (mRestrictionsLock) { 3330 applyUserRestrictionsLR(userId); 3331 } 3332 } 3333 } 3334 3335 /** 3336 * Called right before a user is unlocked. This gives us a chance to prepare 3337 * app storage. 3338 */ 3339 public void onBeforeUnlockUser(@UserIdInt int userId) { 3340 UserInfo userInfo = getUserInfo(userId); 3341 if (userInfo == null) { 3342 return; 3343 } 3344 final int userSerial = userInfo.serialNumber; 3345 // Migrate only if build fingerprints mismatch 3346 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint); 3347 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE); 3348 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData); 3349 } 3350 3351 /** 3352 * Examine all users present on given mounted volume, and destroy data 3353 * belonging to users that are no longer valid, or whose user ID has been 3354 * recycled. 3355 */ 3356 void reconcileUsers(String volumeUuid) { 3357 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */)); 3358 } 3359 3360 /** 3361 * Make a note of the last started time of a user and do some cleanup. 3362 * This is called with ActivityManagerService lock held. 3363 * @param userId the user that was just foregrounded 3364 */ 3365 public void onUserLoggedIn(@UserIdInt int userId) { 3366 UserData userData = getUserDataNoChecks(userId); 3367 if (userData == null || userData.info.partial) { 3368 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId); 3369 return; 3370 } 3371 3372 final long now = System.currentTimeMillis(); 3373 if (now > EPOCH_PLUS_30_YEARS) { 3374 userData.info.lastLoggedInTime = now; 3375 } 3376 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT; 3377 scheduleWriteUser(userData); 3378 } 3379 3380 /** 3381 * Returns the next available user id, filling in any holes in the ids. 3382 */ 3383 @VisibleForTesting 3384 int getNextAvailableId() { 3385 int nextId; 3386 synchronized (mUsersLock) { 3387 nextId = scanNextAvailableIdLocked(); 3388 if (nextId >= 0) { 3389 return nextId; 3390 } 3391 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds, 3392 // except most recently removed 3393 if (mRemovingUserIds.size() > 0) { 3394 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids."); 3395 mRemovingUserIds.clear(); 3396 for (Integer recentlyRemovedId : mRecentlyRemovedIds) { 3397 mRemovingUserIds.put(recentlyRemovedId, true); 3398 } 3399 nextId = scanNextAvailableIdLocked(); 3400 } 3401 } 3402 if (nextId < 0) { 3403 throw new IllegalStateException("No user id available!"); 3404 } 3405 return nextId; 3406 } 3407 3408 private int scanNextAvailableIdLocked() { 3409 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) { 3410 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) { 3411 return i; 3412 } 3413 } 3414 return -1; 3415 } 3416 3417 private static String packageToRestrictionsFileName(String packageName) { 3418 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX; 3419 } 3420 3421 @Override 3422 public void setSeedAccountData(int userId, String accountName, String accountType, 3423 PersistableBundle accountOptions, boolean persist) { 3424 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data"); 3425 synchronized (mPackagesLock) { 3426 final UserData userData; 3427 synchronized (mUsersLock) { 3428 userData = getUserDataLU(userId); 3429 if (userData == null) { 3430 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId); 3431 return; 3432 } 3433 userData.seedAccountName = accountName; 3434 userData.seedAccountType = accountType; 3435 userData.seedAccountOptions = accountOptions; 3436 userData.persistSeedData = persist; 3437 } 3438 if (persist) { 3439 writeUserLP(userData); 3440 } 3441 } 3442 } 3443 3444 @Override 3445 public String getSeedAccountName() throws RemoteException { 3446 checkManageUsersPermission("Cannot get seed account information"); 3447 synchronized (mUsersLock) { 3448 UserData userData = getUserDataLU(UserHandle.getCallingUserId()); 3449 return userData.seedAccountName; 3450 } 3451 } 3452 3453 @Override 3454 public String getSeedAccountType() throws RemoteException { 3455 checkManageUsersPermission("Cannot get seed account information"); 3456 synchronized (mUsersLock) { 3457 UserData userData = getUserDataLU(UserHandle.getCallingUserId()); 3458 return userData.seedAccountType; 3459 } 3460 } 3461 3462 @Override 3463 public PersistableBundle getSeedAccountOptions() throws RemoteException { 3464 checkManageUsersPermission("Cannot get seed account information"); 3465 synchronized (mUsersLock) { 3466 UserData userData = getUserDataLU(UserHandle.getCallingUserId()); 3467 return userData.seedAccountOptions; 3468 } 3469 } 3470 3471 @Override 3472 public void clearSeedAccountData() throws RemoteException { 3473 checkManageUsersPermission("Cannot clear seed account information"); 3474 synchronized (mPackagesLock) { 3475 UserData userData; 3476 synchronized (mUsersLock) { 3477 userData = getUserDataLU(UserHandle.getCallingUserId()); 3478 if (userData == null) return; 3479 userData.clearSeedAccountData(); 3480 } 3481 writeUserLP(userData); 3482 } 3483 } 3484 3485 @Override 3486 public boolean someUserHasSeedAccount(String accountName, String accountType) 3487 throws RemoteException { 3488 checkManageUsersPermission("Cannot check seed account information"); 3489 synchronized (mUsersLock) { 3490 final int userSize = mUsers.size(); 3491 for (int i = 0; i < userSize; i++) { 3492 final UserData data = mUsers.valueAt(i); 3493 if (data.info.isInitialized()) continue; 3494 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) { 3495 continue; 3496 } 3497 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) { 3498 continue; 3499 } 3500 return true; 3501 } 3502 } 3503 return false; 3504 } 3505 3506 @Override 3507 public void onShellCommand(FileDescriptor in, FileDescriptor out, 3508 FileDescriptor err, String[] args, ShellCallback callback, 3509 ResultReceiver resultReceiver) { 3510 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver); 3511 } 3512 3513 int onShellCommand(Shell shell, String cmd) { 3514 if (cmd == null) { 3515 return shell.handleDefaultCommands(cmd); 3516 } 3517 3518 final PrintWriter pw = shell.getOutPrintWriter(); 3519 try { 3520 switch(cmd) { 3521 case "list": 3522 return runList(pw); 3523 } 3524 } catch (RemoteException e) { 3525 pw.println("Remote exception: " + e); 3526 } 3527 return -1; 3528 } 3529 3530 private int runList(PrintWriter pw) throws RemoteException { 3531 final IActivityManager am = ActivityManager.getService(); 3532 final List<UserInfo> users = getUsers(false); 3533 if (users == null) { 3534 pw.println("Error: couldn't get users"); 3535 return 1; 3536 } else { 3537 pw.println("Users:"); 3538 for (int i = 0; i < users.size(); i++) { 3539 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : ""; 3540 pw.println("\t" + users.get(i).toString() + running); 3541 } 3542 return 0; 3543 } 3544 } 3545 3546 @Override 3547 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3548 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return; 3549 3550 long now = System.currentTimeMillis(); 3551 final long nowRealtime = SystemClock.elapsedRealtime(); 3552 StringBuilder sb = new StringBuilder(); 3553 synchronized (mPackagesLock) { 3554 synchronized (mUsersLock) { 3555 pw.println("Users:"); 3556 for (int i = 0; i < mUsers.size(); i++) { 3557 UserData userData = mUsers.valueAt(i); 3558 if (userData == null) { 3559 continue; 3560 } 3561 UserInfo userInfo = userData.info; 3562 final int userId = userInfo.id; 3563 pw.print(" "); pw.print(userInfo); 3564 pw.print(" serialNo="); pw.print(userInfo.serialNumber); 3565 if (mRemovingUserIds.get(userId)) { 3566 pw.print(" <removing> "); 3567 } 3568 if (userInfo.partial) { 3569 pw.print(" <partial>"); 3570 } 3571 pw.println(); 3572 pw.print(" State: "); 3573 final int state; 3574 synchronized (mUserStates) { 3575 state = mUserStates.get(userId, -1); 3576 } 3577 pw.println(UserState.stateToString(state)); 3578 pw.print(" Created: "); 3579 dumpTimeAgo(pw, sb, now, userInfo.creationTime); 3580 3581 pw.print(" Last logged in: "); 3582 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime); 3583 3584 pw.print(" Last logged in fingerprint: "); 3585 pw.println(userInfo.lastLoggedInFingerprint); 3586 3587 pw.print(" Start time: "); 3588 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime); 3589 3590 pw.print(" Unlock time: "); 3591 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime); 3592 3593 pw.print(" Has profile owner: "); 3594 pw.println(mIsUserManaged.get(userId)); 3595 pw.println(" Restrictions:"); 3596 synchronized (mRestrictionsLock) { 3597 UserRestrictionsUtils.dumpRestrictions( 3598 pw, " ", mBaseUserRestrictions.get(userInfo.id)); 3599 pw.println(" Device policy global restrictions:"); 3600 UserRestrictionsUtils.dumpRestrictions( 3601 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id)); 3602 pw.println(" Device policy local restrictions:"); 3603 UserRestrictionsUtils.dumpRestrictions( 3604 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id)); 3605 pw.println(" Effective restrictions:"); 3606 UserRestrictionsUtils.dumpRestrictions( 3607 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id)); 3608 } 3609 3610 if (userData.account != null) { 3611 pw.print(" Account name: " + userData.account); 3612 pw.println(); 3613 } 3614 3615 if (userData.seedAccountName != null) { 3616 pw.print(" Seed account name: " + userData.seedAccountName); 3617 pw.println(); 3618 if (userData.seedAccountType != null) { 3619 pw.print(" account type: " + userData.seedAccountType); 3620 pw.println(); 3621 } 3622 if (userData.seedAccountOptions != null) { 3623 pw.print(" account options exist"); 3624 pw.println(); 3625 } 3626 } 3627 } 3628 } 3629 pw.println(); 3630 pw.println(" Device owner id:" + mDeviceOwnerUserId); 3631 pw.println(); 3632 pw.println(" Guest restrictions:"); 3633 synchronized (mGuestRestrictions) { 3634 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions); 3635 } 3636 synchronized (mUsersLock) { 3637 pw.println(); 3638 pw.println(" Device managed: " + mIsDeviceManaged); 3639 if (mRemovingUserIds.size() > 0) { 3640 pw.println(); 3641 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds); 3642 } 3643 } 3644 synchronized (mUserStates) { 3645 pw.println(" Started users state: " + mUserStates); 3646 } 3647 // Dump some capabilities 3648 pw.println(); 3649 pw.println(" Max users: " + UserManager.getMaxSupportedUsers()); 3650 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers()); 3651 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean( 3652 com.android.internal.R.bool.config_guestUserEphemeral)); 3653 } 3654 } 3655 3656 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) { 3657 if (time == 0) { 3658 pw.println("<unknown>"); 3659 } else { 3660 sb.setLength(0); 3661 TimeUtils.formatDuration(nowTime - time, sb); 3662 sb.append(" ago"); 3663 pw.println(sb); 3664 } 3665 } 3666 3667 final class MainHandler extends Handler { 3668 3669 @Override 3670 public void handleMessage(Message msg) { 3671 switch (msg.what) { 3672 case WRITE_USER_MSG: 3673 removeMessages(WRITE_USER_MSG, msg.obj); 3674 synchronized (mPackagesLock) { 3675 int userId = ((UserData) msg.obj).info.id; 3676 UserData userData = getUserDataNoChecks(userId); 3677 if (userData != null) { 3678 writeUserLP(userData); 3679 } 3680 } 3681 } 3682 } 3683 } 3684 3685 /** 3686 * @param userId 3687 * @return whether the user has been initialized yet 3688 */ 3689 boolean isUserInitialized(int userId) { 3690 return mLocalService.isUserInitialized(userId); 3691 } 3692 3693 private class LocalService extends UserManagerInternal { 3694 @Override 3695 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions, 3696 boolean isDeviceOwner, int cameraRestrictionScope) { 3697 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions, 3698 isDeviceOwner, cameraRestrictionScope); 3699 } 3700 3701 @Override 3702 public Bundle getBaseUserRestrictions(int userId) { 3703 synchronized (mRestrictionsLock) { 3704 return mBaseUserRestrictions.get(userId); 3705 } 3706 } 3707 3708 @Override 3709 public void setBaseUserRestrictionsByDpmsForMigration( 3710 int userId, Bundle baseRestrictions) { 3711 synchronized (mRestrictionsLock) { 3712 if (updateRestrictionsIfNeededLR( 3713 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) { 3714 invalidateEffectiveUserRestrictionsLR(userId); 3715 } 3716 } 3717 3718 final UserData userData = getUserDataNoChecks(userId); 3719 synchronized (mPackagesLock) { 3720 if (userData != null) { 3721 writeUserLP(userData); 3722 } else { 3723 Slog.w(LOG_TAG, "UserInfo not found for " + userId); 3724 } 3725 } 3726 } 3727 3728 @Override 3729 public boolean getUserRestriction(int userId, String key) { 3730 return getUserRestrictions(userId).getBoolean(key); 3731 } 3732 3733 @Override 3734 public void addUserRestrictionsListener(UserRestrictionsListener listener) { 3735 synchronized (mUserRestrictionsListeners) { 3736 mUserRestrictionsListeners.add(listener); 3737 } 3738 } 3739 3740 @Override 3741 public void removeUserRestrictionsListener(UserRestrictionsListener listener) { 3742 synchronized (mUserRestrictionsListeners) { 3743 mUserRestrictionsListeners.remove(listener); 3744 } 3745 } 3746 3747 @Override 3748 public void setDeviceManaged(boolean isManaged) { 3749 synchronized (mUsersLock) { 3750 mIsDeviceManaged = isManaged; 3751 } 3752 } 3753 3754 @Override 3755 public void setUserManaged(int userId, boolean isManaged) { 3756 synchronized (mUsersLock) { 3757 mIsUserManaged.put(userId, isManaged); 3758 } 3759 } 3760 3761 @Override 3762 public void setUserIcon(int userId, Bitmap bitmap) { 3763 long ident = Binder.clearCallingIdentity(); 3764 try { 3765 synchronized (mPackagesLock) { 3766 UserData userData = getUserDataNoChecks(userId); 3767 if (userData == null || userData.info.partial) { 3768 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId); 3769 return; 3770 } 3771 writeBitmapLP(userData.info, bitmap); 3772 writeUserLP(userData); 3773 } 3774 sendUserInfoChangedBroadcast(userId); 3775 } finally { 3776 Binder.restoreCallingIdentity(ident); 3777 } 3778 } 3779 3780 @Override 3781 public void setForceEphemeralUsers(boolean forceEphemeralUsers) { 3782 synchronized (mUsersLock) { 3783 mForceEphemeralUsers = forceEphemeralUsers; 3784 } 3785 } 3786 3787 @Override 3788 public void removeAllUsers() { 3789 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) { 3790 // Remove the non-system users straight away. 3791 removeNonSystemUsers(); 3792 } else { 3793 // Switch to the system user first and then remove the other users. 3794 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() { 3795 @Override 3796 public void onReceive(Context context, Intent intent) { 3797 int userId = 3798 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 3799 if (userId != UserHandle.USER_SYSTEM) { 3800 return; 3801 } 3802 mContext.unregisterReceiver(this); 3803 removeNonSystemUsers(); 3804 } 3805 }; 3806 IntentFilter userSwitchedFilter = new IntentFilter(); 3807 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED); 3808 mContext.registerReceiver( 3809 userSwitchedReceiver, userSwitchedFilter, null, mHandler); 3810 3811 // Switch to the system user. 3812 ActivityManager am = 3813 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); 3814 am.switchUser(UserHandle.USER_SYSTEM); 3815 } 3816 } 3817 3818 @Override 3819 public void onEphemeralUserStop(int userId) { 3820 synchronized (mUsersLock) { 3821 UserInfo userInfo = getUserInfoLU(userId); 3822 if (userInfo != null && userInfo.isEphemeral()) { 3823 // Do not allow switching back to the ephemeral user again as the user is going 3824 // to be deleted. 3825 userInfo.flags |= UserInfo.FLAG_DISABLED; 3826 if (userInfo.isGuest()) { 3827 // Indicate that the guest will be deleted after it stops. 3828 userInfo.guestToRemove = true; 3829 } 3830 } 3831 } 3832 } 3833 3834 @Override 3835 public UserInfo createUserEvenWhenDisallowed(String name, int flags, 3836 String[] disallowedPackages) { 3837 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, 3838 disallowedPackages); 3839 // Keep this in sync with UserManager.createUser 3840 if (user != null && !user.isAdmin() && !user.isDemo()) { 3841 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id); 3842 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id); 3843 } 3844 return user; 3845 } 3846 3847 @Override 3848 public boolean removeUserEvenWhenDisallowed(int userId) { 3849 return removeUserUnchecked(userId); 3850 } 3851 3852 @Override 3853 public boolean isUserRunning(int userId) { 3854 synchronized (mUserStates) { 3855 return mUserStates.get(userId, -1) >= 0; 3856 } 3857 } 3858 3859 @Override 3860 public void setUserState(int userId, int userState) { 3861 synchronized (mUserStates) { 3862 mUserStates.put(userId, userState); 3863 } 3864 } 3865 3866 @Override 3867 public void removeUserState(int userId) { 3868 synchronized (mUserStates) { 3869 mUserStates.delete(userId); 3870 } 3871 } 3872 3873 @Override 3874 public int[] getUserIds() { 3875 return UserManagerService.this.getUserIds(); 3876 } 3877 3878 @Override 3879 public boolean isUserUnlockingOrUnlocked(int userId) { 3880 int state; 3881 synchronized (mUserStates) { 3882 state = mUserStates.get(userId, -1); 3883 } 3884 // Special case, in the stopping/shutdown state user key can still be unlocked 3885 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) { 3886 return StorageManager.isUserKeyUnlocked(userId); 3887 } 3888 return (state == UserState.STATE_RUNNING_UNLOCKING) 3889 || (state == UserState.STATE_RUNNING_UNLOCKED); 3890 } 3891 3892 @Override 3893 public boolean isUserUnlocked(int userId) { 3894 int state; 3895 synchronized (mUserStates) { 3896 state = mUserStates.get(userId, -1); 3897 } 3898 // Special case, in the stopping/shutdown state user key can still be unlocked 3899 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) { 3900 return StorageManager.isUserKeyUnlocked(userId); 3901 } 3902 return state == UserState.STATE_RUNNING_UNLOCKED; 3903 } 3904 3905 @Override 3906 public boolean isUserInitialized(int userId) { 3907 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0; 3908 } 3909 3910 @Override 3911 public boolean exists(int userId) { 3912 return getUserInfoNoChecks(userId) != null; 3913 } 3914 } 3915 3916 /* Remove all the users except of the system one. */ 3917 private void removeNonSystemUsers() { 3918 ArrayList<UserInfo> usersToRemove = new ArrayList<>(); 3919 synchronized (mUsersLock) { 3920 final int userSize = mUsers.size(); 3921 for (int i = 0; i < userSize; i++) { 3922 UserInfo ui = mUsers.valueAt(i).info; 3923 if (ui.id != UserHandle.USER_SYSTEM) { 3924 usersToRemove.add(ui); 3925 } 3926 } 3927 } 3928 for (UserInfo ui: usersToRemove) { 3929 removeUser(ui.id); 3930 } 3931 } 3932 3933 private class Shell extends ShellCommand { 3934 @Override 3935 public int onCommand(String cmd) { 3936 return onShellCommand(this, cmd); 3937 } 3938 3939 @Override 3940 public void onHelp() { 3941 final PrintWriter pw = getOutPrintWriter(); 3942 pw.println("User manager (user) commands:"); 3943 pw.println(" help"); 3944 pw.println(" Print this help text."); 3945 pw.println(""); 3946 pw.println(" list"); 3947 pw.println(" Prints all users on the system."); 3948 } 3949 } 3950 3951 private static void debug(String message) { 3952 Log.d(LOG_TAG, message + 3953 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : "")); 3954 } 3955 3956 @VisibleForTesting 3957 static int getMaxManagedProfiles() { 3958 // Allow overriding max managed profiles on debuggable builds for testing 3959 // of multiple profiles. 3960 if (!Build.IS_DEBUGGABLE) { 3961 return MAX_MANAGED_PROFILES; 3962 } else { 3963 return SystemProperties.getInt("persist.sys.max_profiles", 3964 MAX_MANAGED_PROFILES); 3965 } 3966 } 3967 3968 @VisibleForTesting 3969 int getFreeProfileBadgeLU(int parentUserId) { 3970 int maxManagedProfiles = getMaxManagedProfiles(); 3971 boolean[] usedBadges = new boolean[maxManagedProfiles]; 3972 final int userSize = mUsers.size(); 3973 for (int i = 0; i < userSize; i++) { 3974 UserInfo ui = mUsers.valueAt(i).info; 3975 // Check which badge indexes are already used by this profile group. 3976 if (ui.isManagedProfile() 3977 && ui.profileGroupId == parentUserId 3978 && !mRemovingUserIds.get(ui.id) 3979 && ui.profileBadge < maxManagedProfiles) { 3980 usedBadges[ui.profileBadge] = true; 3981 } 3982 } 3983 for (int i = 0; i < maxManagedProfiles; i++) { 3984 if (!usedBadges[i]) { 3985 return i; 3986 } 3987 } 3988 return 0; 3989 } 3990 3991 /** 3992 * Checks if the given user has a managed profile associated with it. 3993 * @param userId The parent user 3994 * @return 3995 */ 3996 boolean hasManagedProfile(int userId) { 3997 synchronized (mUsersLock) { 3998 UserInfo userInfo = getUserInfoLU(userId); 3999 final int userSize = mUsers.size(); 4000 for (int i = 0; i < userSize; i++) { 4001 UserInfo profile = mUsers.valueAt(i).info; 4002 if (userId != profile.id && isProfileOf(userInfo, profile)) { 4003 return true; 4004 } 4005 } 4006 return false; 4007 } 4008 } 4009 4010 /** 4011 * Check if the calling package name matches with the calling UID, throw 4012 * {@link SecurityException} if not. 4013 */ 4014 private void verifyCallingPackage(String callingPackage, int callingUid) { 4015 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid)); 4016 if (packageUid != callingUid) { 4017 throw new SecurityException("Specified package " + callingPackage 4018 + " does not match the calling uid " + callingUid); 4019 } 4020 } 4021} 4022