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