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