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