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