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