UserManagerService.java revision 4593e425a88c1fab1b6526617a21d5c0105bf18f
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) 1491 && !user.isGuest() && !user.partial) { 1492 aliveUserCount++; 1493 } 1494 } 1495 return aliveUserCount; 1496 } 1497 1498 /** 1499 * Enforces that only the system UID or root's UID or apps that have the 1500 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and 1501 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL} 1502 * permissions can make certain calls to the UserManager. 1503 * 1504 * @param message used as message if SecurityException is thrown 1505 * @throws SecurityException if the caller does not have enough privilege. 1506 */ 1507 private static final void checkManageUserAndAcrossUsersFullPermission(String message) { 1508 final int uid = Binder.getCallingUid(); 1509 if (uid != Process.SYSTEM_UID && uid != 0 1510 && ActivityManager.checkComponentPermission( 1511 Manifest.permission.MANAGE_USERS, 1512 uid, -1, true) != PackageManager.PERMISSION_GRANTED 1513 && ActivityManager.checkComponentPermission( 1514 Manifest.permission.INTERACT_ACROSS_USERS_FULL, 1515 uid, -1, true) != PackageManager.PERMISSION_GRANTED) { 1516 throw new SecurityException( 1517 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " 1518 + message); 1519 } 1520 } 1521 1522 /** 1523 * Enforces that only the system UID or root's UID or apps that have the 1524 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} 1525 * permission can make certain calls to the UserManager. 1526 * 1527 * @param message used as message if SecurityException is thrown 1528 * @throws SecurityException if the caller is not system or root 1529 * @see #hasManageUsersPermission() 1530 */ 1531 private static final void checkManageUsersPermission(String message) { 1532 if (!hasManageUsersPermission()) { 1533 throw new SecurityException("You need MANAGE_USERS permission to: " + message); 1534 } 1535 } 1536 1537 /** 1538 * Enforces that only the system UID or root's UID or apps that have the 1539 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 1540 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} 1541 * can make certain calls to the UserManager. 1542 * 1543 * @param message used as message if SecurityException is thrown 1544 * @throws SecurityException if the caller is not system or root 1545 * @see #hasManageOrCreateUsersPermission() 1546 */ 1547 private static final void checkManageOrCreateUsersPermission(String message) { 1548 if (!hasManageOrCreateUsersPermission()) { 1549 throw new SecurityException( 1550 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message); 1551 } 1552 } 1553 1554 /** 1555 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries 1556 * to create user/profiles other than what is allowed for 1557 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only 1558 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission. 1559 */ 1560 private static final void checkManageOrCreateUsersPermission(int creationFlags) { 1561 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) { 1562 if (!hasManageOrCreateUsersPermission()) { 1563 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS " 1564 + "permission to create an user with flags: " + creationFlags); 1565 } 1566 } else if (!hasManageUsersPermission()) { 1567 throw new SecurityException("You need MANAGE_USERS permission to create an user " 1568 + " with flags: " + creationFlags); 1569 } 1570 } 1571 1572 /** 1573 * @return whether the calling UID is system UID or root's UID or the calling app has the 1574 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}. 1575 */ 1576 private static final boolean hasManageUsersPermission() { 1577 final int callingUid = Binder.getCallingUid(); 1578 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) 1579 || callingUid == Process.ROOT_UID 1580 || ActivityManager.checkComponentPermission( 1581 android.Manifest.permission.MANAGE_USERS, 1582 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED; 1583 } 1584 1585 /** 1586 * @return whether the calling UID is system UID or root's UID or the calling app has the 1587 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 1588 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}. 1589 */ 1590 private static final boolean hasManageOrCreateUsersPermission() { 1591 final int callingUid = Binder.getCallingUid(); 1592 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) 1593 || callingUid == Process.ROOT_UID 1594 || ActivityManager.checkComponentPermission( 1595 android.Manifest.permission.MANAGE_USERS, 1596 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED 1597 || ActivityManager.checkComponentPermission( 1598 android.Manifest.permission.CREATE_USERS, 1599 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED; 1600 } 1601 1602 /** 1603 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the 1604 * UserManager. 1605 * 1606 * @param message used as message if SecurityException is thrown 1607 * @throws SecurityException if the caller is not system or root 1608 */ 1609 private static void checkSystemOrRoot(String message) { 1610 final int uid = Binder.getCallingUid(); 1611 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) { 1612 throw new SecurityException("Only system may: " + message); 1613 } 1614 } 1615 1616 private void writeBitmapLP(UserInfo info, Bitmap bitmap) { 1617 try { 1618 File dir = new File(mUsersDir, Integer.toString(info.id)); 1619 File file = new File(dir, USER_PHOTO_FILENAME); 1620 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP); 1621 if (!dir.exists()) { 1622 dir.mkdir(); 1623 FileUtils.setPermissions( 1624 dir.getPath(), 1625 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 1626 -1, -1); 1627 } 1628 FileOutputStream os; 1629 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp)) 1630 && tmp.renameTo(file) && SELinux.restorecon(file)) { 1631 info.iconPath = file.getAbsolutePath(); 1632 } 1633 try { 1634 os.close(); 1635 } catch (IOException ioe) { 1636 // What the ... ! 1637 } 1638 tmp.delete(); 1639 } catch (FileNotFoundException e) { 1640 Slog.w(LOG_TAG, "Error setting photo for user ", e); 1641 } 1642 } 1643 1644 /** 1645 * Returns an array of user ids. This array is cached here for quick access, so do not modify or 1646 * cache it elsewhere. 1647 * @return the array of user ids. 1648 */ 1649 public int[] getUserIds() { 1650 synchronized (mUsersLock) { 1651 return mUserIds; 1652 } 1653 } 1654 1655 private void readUserListLP() { 1656 if (!mUserListFile.exists()) { 1657 fallbackToSingleUserLP(); 1658 return; 1659 } 1660 FileInputStream fis = null; 1661 AtomicFile userListFile = new AtomicFile(mUserListFile); 1662 try { 1663 fis = userListFile.openRead(); 1664 XmlPullParser parser = Xml.newPullParser(); 1665 parser.setInput(fis, StandardCharsets.UTF_8.name()); 1666 int type; 1667 while ((type = parser.next()) != XmlPullParser.START_TAG 1668 && type != XmlPullParser.END_DOCUMENT) { 1669 // Skip 1670 } 1671 1672 if (type != XmlPullParser.START_TAG) { 1673 Slog.e(LOG_TAG, "Unable to read user list"); 1674 fallbackToSingleUserLP(); 1675 return; 1676 } 1677 1678 mNextSerialNumber = -1; 1679 if (parser.getName().equals(TAG_USERS)) { 1680 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO); 1681 if (lastSerialNumber != null) { 1682 mNextSerialNumber = Integer.parseInt(lastSerialNumber); 1683 } 1684 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION); 1685 if (versionNumber != null) { 1686 mUserVersion = Integer.parseInt(versionNumber); 1687 } 1688 } 1689 1690 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle(); 1691 1692 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 1693 if (type == XmlPullParser.START_TAG) { 1694 final String name = parser.getName(); 1695 if (name.equals(TAG_USER)) { 1696 String id = parser.getAttributeValue(null, ATTR_ID); 1697 1698 UserData userData = readUserLP(Integer.parseInt(id)); 1699 1700 if (userData != null) { 1701 synchronized (mUsersLock) { 1702 mUsers.put(userData.info.id, userData); 1703 if (mNextSerialNumber < 0 1704 || mNextSerialNumber <= userData.info.id) { 1705 mNextSerialNumber = userData.info.id + 1; 1706 } 1707 } 1708 } 1709 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) { 1710 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 1711 && type != XmlPullParser.END_TAG) { 1712 if (type == XmlPullParser.START_TAG) { 1713 if (parser.getName().equals(TAG_RESTRICTIONS)) { 1714 synchronized (mGuestRestrictions) { 1715 UserRestrictionsUtils 1716 .readRestrictions(parser, mGuestRestrictions); 1717 } 1718 } 1719 break; 1720 } 1721 } 1722 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) { 1723 UserRestrictionsUtils.readRestrictions(parser, 1724 newDevicePolicyGlobalUserRestrictions); 1725 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) { 1726 String ownerUserId = parser.getAttributeValue(null, ATTR_ID); 1727 if (ownerUserId != null) { 1728 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId); 1729 } 1730 } 1731 } 1732 } 1733 synchronized (mRestrictionsLock) { 1734 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions; 1735 } 1736 updateUserIds(); 1737 upgradeIfNecessaryLP(); 1738 } catch (IOException | XmlPullParserException e) { 1739 fallbackToSingleUserLP(); 1740 } finally { 1741 IoUtils.closeQuietly(fis); 1742 } 1743 } 1744 1745 /** 1746 * Upgrade steps between versions, either for fixing bugs or changing the data format. 1747 */ 1748 private void upgradeIfNecessaryLP() { 1749 final int originalVersion = mUserVersion; 1750 int userVersion = mUserVersion; 1751 if (userVersion < 1) { 1752 // Assign a proper name for the owner, if not initialized correctly before 1753 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM); 1754 if ("Primary".equals(userData.info.name)) { 1755 userData.info.name = 1756 mContext.getResources().getString(com.android.internal.R.string.owner_name); 1757 scheduleWriteUser(userData); 1758 } 1759 userVersion = 1; 1760 } 1761 1762 if (userVersion < 2) { 1763 // Owner should be marked as initialized 1764 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM); 1765 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) { 1766 userData.info.flags |= UserInfo.FLAG_INITIALIZED; 1767 scheduleWriteUser(userData); 1768 } 1769 userVersion = 2; 1770 } 1771 1772 1773 if (userVersion < 4) { 1774 userVersion = 4; 1775 } 1776 1777 if (userVersion < 5) { 1778 initDefaultGuestRestrictions(); 1779 userVersion = 5; 1780 } 1781 1782 if (userVersion < 6) { 1783 final boolean splitSystemUser = UserManager.isSplitSystemUser(); 1784 synchronized (mUsersLock) { 1785 for (int i = 0; i < mUsers.size(); i++) { 1786 UserData userData = mUsers.valueAt(i); 1787 // In non-split mode, only user 0 can have restricted profiles 1788 if (!splitSystemUser && userData.info.isRestricted() 1789 && (userData.info.restrictedProfileParentId 1790 == UserInfo.NO_PROFILE_GROUP_ID)) { 1791 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM; 1792 scheduleWriteUser(userData); 1793 } 1794 } 1795 } 1796 userVersion = 6; 1797 } 1798 1799 if (userVersion < USER_VERSION) { 1800 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to " 1801 + USER_VERSION); 1802 } else { 1803 mUserVersion = userVersion; 1804 1805 if (originalVersion < mUserVersion) { 1806 writeUserListLP(); 1807 } 1808 } 1809 } 1810 1811 private void fallbackToSingleUserLP() { 1812 int flags = UserInfo.FLAG_INITIALIZED; 1813 // In split system user mode, the admin and primary flags are assigned to the first human 1814 // user. 1815 if (!UserManager.isSplitSystemUser()) { 1816 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY; 1817 } 1818 // Create the system user 1819 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags); 1820 UserData userData = putUserInfo(system); 1821 mNextSerialNumber = MIN_USER_ID; 1822 mUserVersion = USER_VERSION; 1823 1824 Bundle restrictions = new Bundle(); 1825 try { 1826 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray( 1827 com.android.internal.R.array.config_defaultFirstUserRestrictions); 1828 for (String userRestriction : defaultFirstUserRestrictions) { 1829 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) { 1830 restrictions.putBoolean(userRestriction, true); 1831 } 1832 } 1833 } catch (Resources.NotFoundException e) { 1834 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e); 1835 } 1836 1837 synchronized (mRestrictionsLock) { 1838 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions); 1839 } 1840 1841 updateUserIds(); 1842 initDefaultGuestRestrictions(); 1843 1844 writeUserLP(userData); 1845 writeUserListLP(); 1846 } 1847 1848 private String getOwnerName() { 1849 return mContext.getResources().getString(com.android.internal.R.string.owner_name); 1850 } 1851 1852 private void scheduleWriteUser(UserData UserData) { 1853 if (DBG) { 1854 debug("scheduleWriteUser"); 1855 } 1856 // No need to wrap it within a lock -- worst case, we'll just post the same message 1857 // twice. 1858 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) { 1859 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData); 1860 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY); 1861 } 1862 } 1863 1864 /* 1865 * Writes the user file in this format: 1866 * 1867 * <user flags="20039023" id="0"> 1868 * <name>Primary</name> 1869 * </user> 1870 */ 1871 private void writeUserLP(UserData userData) { 1872 if (DBG) { 1873 debug("writeUserLP " + userData); 1874 } 1875 FileOutputStream fos = null; 1876 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX)); 1877 try { 1878 fos = userFile.startWrite(); 1879 final BufferedOutputStream bos = new BufferedOutputStream(fos); 1880 1881 // XmlSerializer serializer = XmlUtils.serializerInstance(); 1882 final XmlSerializer serializer = new FastXmlSerializer(); 1883 serializer.setOutput(bos, StandardCharsets.UTF_8.name()); 1884 serializer.startDocument(null, true); 1885 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 1886 1887 final UserInfo userInfo = userData.info; 1888 serializer.startTag(null, TAG_USER); 1889 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id)); 1890 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber)); 1891 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags)); 1892 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime)); 1893 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME, 1894 Long.toString(userInfo.lastLoggedInTime)); 1895 if (userInfo.lastLoggedInFingerprint != null) { 1896 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT, 1897 userInfo.lastLoggedInFingerprint); 1898 } 1899 if (userInfo.iconPath != null) { 1900 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath); 1901 } 1902 if (userInfo.partial) { 1903 serializer.attribute(null, ATTR_PARTIAL, "true"); 1904 } 1905 if (userInfo.guestToRemove) { 1906 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true"); 1907 } 1908 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 1909 serializer.attribute(null, ATTR_PROFILE_GROUP_ID, 1910 Integer.toString(userInfo.profileGroupId)); 1911 } 1912 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) { 1913 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID, 1914 Integer.toString(userInfo.restrictedProfileParentId)); 1915 } 1916 // Write seed data 1917 if (userData.persistSeedData) { 1918 if (userData.seedAccountName != null) { 1919 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName); 1920 } 1921 if (userData.seedAccountType != null) { 1922 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType); 1923 } 1924 } 1925 if (userInfo.name != null) { 1926 serializer.startTag(null, TAG_NAME); 1927 serializer.text(userInfo.name); 1928 serializer.endTag(null, TAG_NAME); 1929 } 1930 synchronized (mRestrictionsLock) { 1931 UserRestrictionsUtils.writeRestrictions(serializer, 1932 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS); 1933 UserRestrictionsUtils.writeRestrictions(serializer, 1934 mDevicePolicyLocalUserRestrictions.get(userInfo.id), 1935 TAG_DEVICE_POLICY_RESTRICTIONS); 1936 } 1937 1938 if (userData.account != null) { 1939 serializer.startTag(null, TAG_ACCOUNT); 1940 serializer.text(userData.account); 1941 serializer.endTag(null, TAG_ACCOUNT); 1942 } 1943 1944 if (userData.persistSeedData && userData.seedAccountOptions != null) { 1945 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS); 1946 userData.seedAccountOptions.saveToXml(serializer); 1947 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS); 1948 } 1949 serializer.endTag(null, TAG_USER); 1950 1951 serializer.endDocument(); 1952 userFile.finishWrite(fos); 1953 } catch (Exception ioe) { 1954 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe); 1955 userFile.failWrite(fos); 1956 } 1957 } 1958 1959 /* 1960 * Writes the user list file in this format: 1961 * 1962 * <users nextSerialNumber="3"> 1963 * <user id="0"></user> 1964 * <user id="2"></user> 1965 * </users> 1966 */ 1967 private void writeUserListLP() { 1968 if (DBG) { 1969 debug("writeUserList"); 1970 } 1971 FileOutputStream fos = null; 1972 AtomicFile userListFile = new AtomicFile(mUserListFile); 1973 try { 1974 fos = userListFile.startWrite(); 1975 final BufferedOutputStream bos = new BufferedOutputStream(fos); 1976 1977 // XmlSerializer serializer = XmlUtils.serializerInstance(); 1978 final XmlSerializer serializer = new FastXmlSerializer(); 1979 serializer.setOutput(bos, StandardCharsets.UTF_8.name()); 1980 serializer.startDocument(null, true); 1981 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 1982 1983 serializer.startTag(null, TAG_USERS); 1984 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber)); 1985 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion)); 1986 1987 serializer.startTag(null, TAG_GUEST_RESTRICTIONS); 1988 synchronized (mGuestRestrictions) { 1989 UserRestrictionsUtils 1990 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS); 1991 } 1992 serializer.endTag(null, TAG_GUEST_RESTRICTIONS); 1993 synchronized (mRestrictionsLock) { 1994 UserRestrictionsUtils.writeRestrictions(serializer, 1995 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS); 1996 } 1997 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID); 1998 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId)); 1999 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID); 2000 int[] userIdsToWrite; 2001 synchronized (mUsersLock) { 2002 userIdsToWrite = new int[mUsers.size()]; 2003 for (int i = 0; i < userIdsToWrite.length; i++) { 2004 UserInfo user = mUsers.valueAt(i).info; 2005 userIdsToWrite[i] = user.id; 2006 } 2007 } 2008 for (int id : userIdsToWrite) { 2009 serializer.startTag(null, TAG_USER); 2010 serializer.attribute(null, ATTR_ID, Integer.toString(id)); 2011 serializer.endTag(null, TAG_USER); 2012 } 2013 2014 serializer.endTag(null, TAG_USERS); 2015 2016 serializer.endDocument(); 2017 userListFile.finishWrite(fos); 2018 } catch (Exception e) { 2019 userListFile.failWrite(fos); 2020 Slog.e(LOG_TAG, "Error writing user list"); 2021 } 2022 } 2023 2024 private UserData readUserLP(int id) { 2025 int flags = 0; 2026 int serialNumber = id; 2027 String name = null; 2028 String account = null; 2029 String iconPath = null; 2030 long creationTime = 0L; 2031 long lastLoggedInTime = 0L; 2032 String lastLoggedInFingerprint = null; 2033 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID; 2034 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID; 2035 boolean partial = false; 2036 boolean guestToRemove = false; 2037 boolean persistSeedData = false; 2038 String seedAccountName = null; 2039 String seedAccountType = null; 2040 PersistableBundle seedAccountOptions = null; 2041 Bundle baseRestrictions = new Bundle(); 2042 Bundle localRestrictions = new Bundle(); 2043 2044 FileInputStream fis = null; 2045 try { 2046 AtomicFile userFile = 2047 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX)); 2048 fis = userFile.openRead(); 2049 XmlPullParser parser = Xml.newPullParser(); 2050 parser.setInput(fis, StandardCharsets.UTF_8.name()); 2051 int type; 2052 while ((type = parser.next()) != XmlPullParser.START_TAG 2053 && type != XmlPullParser.END_DOCUMENT) { 2054 // Skip 2055 } 2056 2057 if (type != XmlPullParser.START_TAG) { 2058 Slog.e(LOG_TAG, "Unable to read user " + id); 2059 return null; 2060 } 2061 2062 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) { 2063 int storedId = readIntAttribute(parser, ATTR_ID, -1); 2064 if (storedId != id) { 2065 Slog.e(LOG_TAG, "User id does not match the file name"); 2066 return null; 2067 } 2068 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id); 2069 flags = readIntAttribute(parser, ATTR_FLAGS, 0); 2070 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH); 2071 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0); 2072 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0); 2073 lastLoggedInFingerprint = parser.getAttributeValue(null, 2074 ATTR_LAST_LOGGED_IN_FINGERPRINT); 2075 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID, 2076 UserInfo.NO_PROFILE_GROUP_ID); 2077 restrictedProfileParentId = readIntAttribute(parser, 2078 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID); 2079 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL); 2080 if ("true".equals(valueString)) { 2081 partial = true; 2082 } 2083 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE); 2084 if ("true".equals(valueString)) { 2085 guestToRemove = true; 2086 } 2087 2088 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME); 2089 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE); 2090 if (seedAccountName != null || seedAccountType != null) { 2091 persistSeedData = true; 2092 } 2093 2094 int outerDepth = parser.getDepth(); 2095 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 2096 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2097 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 2098 continue; 2099 } 2100 String tag = parser.getName(); 2101 if (TAG_NAME.equals(tag)) { 2102 type = parser.next(); 2103 if (type == XmlPullParser.TEXT) { 2104 name = parser.getText(); 2105 } 2106 } else if (TAG_RESTRICTIONS.equals(tag)) { 2107 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions); 2108 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) { 2109 UserRestrictionsUtils.readRestrictions(parser, localRestrictions); 2110 } else if (TAG_ACCOUNT.equals(tag)) { 2111 type = parser.next(); 2112 if (type == XmlPullParser.TEXT) { 2113 account = parser.getText(); 2114 } 2115 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) { 2116 seedAccountOptions = PersistableBundle.restoreFromXml(parser); 2117 persistSeedData = true; 2118 } 2119 } 2120 } 2121 2122 // Create the UserInfo object that gets passed around 2123 UserInfo userInfo = new UserInfo(id, name, iconPath, flags); 2124 userInfo.serialNumber = serialNumber; 2125 userInfo.creationTime = creationTime; 2126 userInfo.lastLoggedInTime = lastLoggedInTime; 2127 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint; 2128 userInfo.partial = partial; 2129 userInfo.guestToRemove = guestToRemove; 2130 userInfo.profileGroupId = profileGroupId; 2131 userInfo.restrictedProfileParentId = restrictedProfileParentId; 2132 2133 // Create the UserData object that's internal to this class 2134 UserData userData = new UserData(); 2135 userData.info = userInfo; 2136 userData.account = account; 2137 userData.seedAccountName = seedAccountName; 2138 userData.seedAccountType = seedAccountType; 2139 userData.persistSeedData = persistSeedData; 2140 userData.seedAccountOptions = seedAccountOptions; 2141 2142 synchronized (mRestrictionsLock) { 2143 mBaseUserRestrictions.put(id, baseRestrictions); 2144 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions); 2145 } 2146 return userData; 2147 } catch (IOException ioe) { 2148 } catch (XmlPullParserException pe) { 2149 } finally { 2150 if (fis != null) { 2151 try { 2152 fis.close(); 2153 } catch (IOException e) { 2154 } 2155 } 2156 } 2157 return null; 2158 } 2159 2160 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) { 2161 String valueString = parser.getAttributeValue(null, attr); 2162 if (valueString == null) return defaultValue; 2163 try { 2164 return Integer.parseInt(valueString); 2165 } catch (NumberFormatException nfe) { 2166 return defaultValue; 2167 } 2168 } 2169 2170 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) { 2171 String valueString = parser.getAttributeValue(null, attr); 2172 if (valueString == null) return defaultValue; 2173 try { 2174 return Long.parseLong(valueString); 2175 } catch (NumberFormatException nfe) { 2176 return defaultValue; 2177 } 2178 } 2179 2180 /** 2181 * Removes the app restrictions file for a specific package and user id, if it exists. 2182 */ 2183 private void cleanAppRestrictionsForPackage(String pkg, int userId) { 2184 synchronized (mPackagesLock) { 2185 File dir = Environment.getUserSystemDirectory(userId); 2186 File resFile = new File(dir, packageToRestrictionsFileName(pkg)); 2187 if (resFile.exists()) { 2188 resFile.delete(); 2189 } 2190 } 2191 } 2192 2193 @Override 2194 public UserInfo createProfileForUser(String name, int flags, int userId, 2195 String[] disallowedPackages) { 2196 checkManageOrCreateUsersPermission(flags); 2197 return createUserInternal(name, flags, userId, disallowedPackages); 2198 } 2199 2200 @Override 2201 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId, 2202 String[] disallowedPackages) { 2203 checkManageOrCreateUsersPermission(flags); 2204 return createUserInternalUnchecked(name, flags, userId, disallowedPackages); 2205 } 2206 2207 @Override 2208 public UserInfo createUser(String name, int flags) { 2209 checkManageOrCreateUsersPermission(flags); 2210 return createUserInternal(name, flags, UserHandle.USER_NULL); 2211 } 2212 2213 private UserInfo createUserInternal(String name, int flags, int parentId) { 2214 return createUserInternal(name, flags, parentId, null); 2215 } 2216 2217 private UserInfo createUserInternal(String name, int flags, int parentId, 2218 String[] disallowedPackages) { 2219 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) { 2220 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled."); 2221 return null; 2222 } 2223 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages); 2224 } 2225 2226 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId, 2227 String[] disallowedPackages) { 2228 DeviceStorageMonitorInternal dsm = LocalServices 2229 .getService(DeviceStorageMonitorInternal.class); 2230 if (dsm.isMemoryLow()) { 2231 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk."); 2232 return null; 2233 } 2234 if (ActivityManager.isLowRamDeviceStatic()) { 2235 return null; 2236 } 2237 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0; 2238 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0; 2239 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0; 2240 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0; 2241 final long ident = Binder.clearCallingIdentity(); 2242 UserInfo userInfo; 2243 UserData userData; 2244 final int userId; 2245 try { 2246 synchronized (mPackagesLock) { 2247 UserData parent = null; 2248 if (parentId != UserHandle.USER_NULL) { 2249 synchronized (mUsersLock) { 2250 parent = getUserDataLU(parentId); 2251 } 2252 if (parent == null) return null; 2253 } 2254 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) { 2255 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId); 2256 return null; 2257 } 2258 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) { 2259 // If we're not adding a guest/demo user or a managed profile and the limit has 2260 // been reached, cannot add a user. 2261 return null; 2262 } 2263 // If we're adding a guest and there already exists one, bail. 2264 if (isGuest && findCurrentGuestUser() != null) { 2265 return null; 2266 } 2267 // In legacy mode, restricted profile's parent can only be the owner user 2268 if (isRestricted && !UserManager.isSplitSystemUser() 2269 && (parentId != UserHandle.USER_SYSTEM)) { 2270 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner"); 2271 return null; 2272 } 2273 if (isRestricted && UserManager.isSplitSystemUser()) { 2274 if (parent == null) { 2275 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be " 2276 + "specified"); 2277 return null; 2278 } 2279 if (!parent.info.canHaveProfile()) { 2280 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be " 2281 + "created for the specified parent user id " + parentId); 2282 return null; 2283 } 2284 } 2285 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0 2286 && (flags & UserInfo.FLAG_DEMO) == 0) { 2287 Log.e(LOG_TAG, 2288 "Ephemeral users are supported on split-system-user systems only."); 2289 return null; 2290 } 2291 // In split system user mode, we assign the first human user the primary flag. 2292 // And if there is no device owner, we also assign the admin flag to primary user. 2293 if (UserManager.isSplitSystemUser() 2294 && !isGuest && !isManagedProfile && getPrimaryUser() == null) { 2295 flags |= UserInfo.FLAG_PRIMARY; 2296 synchronized (mUsersLock) { 2297 if (!mIsDeviceManaged) { 2298 flags |= UserInfo.FLAG_ADMIN; 2299 } 2300 } 2301 } 2302 2303 userId = getNextAvailableId(); 2304 Environment.getUserSystemDirectory(userId).mkdirs(); 2305 boolean ephemeralGuests = Resources.getSystem() 2306 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral); 2307 2308 synchronized (mUsersLock) { 2309 // Add ephemeral flag to guests/users if required. Also inherit it from parent. 2310 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers 2311 || (parent != null && parent.info.isEphemeral())) { 2312 flags |= UserInfo.FLAG_EPHEMERAL; 2313 } 2314 2315 userInfo = new UserInfo(userId, name, null, flags); 2316 userInfo.serialNumber = mNextSerialNumber++; 2317 long now = System.currentTimeMillis(); 2318 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0; 2319 userInfo.partial = true; 2320 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT; 2321 userData = new UserData(); 2322 userData.info = userInfo; 2323 mUsers.put(userId, userData); 2324 } 2325 writeUserLP(userData); 2326 writeUserListLP(); 2327 if (parent != null) { 2328 if (isManagedProfile) { 2329 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) { 2330 parent.info.profileGroupId = parent.info.id; 2331 writeUserLP(parent); 2332 } 2333 userInfo.profileGroupId = parent.info.profileGroupId; 2334 } else if (isRestricted) { 2335 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) { 2336 parent.info.restrictedProfileParentId = parent.info.id; 2337 writeUserLP(parent); 2338 } 2339 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId; 2340 } 2341 } 2342 } 2343 final StorageManager storage = mContext.getSystemService(StorageManager.class); 2344 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral()); 2345 mPm.prepareUserData(userId, userInfo.serialNumber, 2346 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2347 mPm.createNewUser(userId, disallowedPackages); 2348 userInfo.partial = false; 2349 synchronized (mPackagesLock) { 2350 writeUserLP(userData); 2351 } 2352 updateUserIds(); 2353 Bundle restrictions = new Bundle(); 2354 if (isGuest) { 2355 synchronized (mGuestRestrictions) { 2356 restrictions.putAll(mGuestRestrictions); 2357 } 2358 } 2359 synchronized (mRestrictionsLock) { 2360 mBaseUserRestrictions.append(userId, restrictions); 2361 } 2362 mPm.onNewUserCreated(userId); 2363 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED); 2364 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 2365 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL, 2366 android.Manifest.permission.MANAGE_USERS); 2367 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1); 2368 } finally { 2369 Binder.restoreCallingIdentity(ident); 2370 } 2371 return userInfo; 2372 } 2373 2374 @VisibleForTesting 2375 UserData putUserInfo(UserInfo userInfo) { 2376 final UserData userData = new UserData(); 2377 userData.info = userInfo; 2378 synchronized (mUsers) { 2379 mUsers.put(userInfo.id, userData); 2380 } 2381 return userData; 2382 } 2383 2384 @VisibleForTesting 2385 void removeUserInfo(int userId) { 2386 synchronized (mUsers) { 2387 mUsers.remove(userId); 2388 } 2389 } 2390 2391 /** 2392 * @hide 2393 */ 2394 @Override 2395 public UserInfo createRestrictedProfile(String name, int parentUserId) { 2396 checkManageOrCreateUsersPermission("setupRestrictedProfile"); 2397 final UserInfo user = createProfileForUser( 2398 name, UserInfo.FLAG_RESTRICTED, parentUserId, null); 2399 if (user == null) { 2400 return null; 2401 } 2402 long identity = Binder.clearCallingIdentity(); 2403 try { 2404 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id); 2405 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise 2406 // the putIntForUser() will fail. 2407 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(), 2408 android.provider.Settings.Secure.LOCATION_MODE, 2409 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id); 2410 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id); 2411 } finally { 2412 Binder.restoreCallingIdentity(identity); 2413 } 2414 return user; 2415 } 2416 2417 /** 2418 * Find the current guest user. If the Guest user is partial, 2419 * then do not include it in the results as it is about to die. 2420 */ 2421 private UserInfo findCurrentGuestUser() { 2422 synchronized (mUsersLock) { 2423 final int size = mUsers.size(); 2424 for (int i = 0; i < size; i++) { 2425 final UserInfo user = mUsers.valueAt(i).info; 2426 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) { 2427 return user; 2428 } 2429 } 2430 } 2431 return null; 2432 } 2433 2434 /** 2435 * Mark this guest user for deletion to allow us to create another guest 2436 * and switch to that user before actually removing this guest. 2437 * @param userHandle the userid of the current guest 2438 * @return whether the user could be marked for deletion 2439 */ 2440 @Override 2441 public boolean markGuestForDeletion(int userHandle) { 2442 checkManageUsersPermission("Only the system can remove users"); 2443 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean( 2444 UserManager.DISALLOW_REMOVE_USER, false)) { 2445 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled."); 2446 return false; 2447 } 2448 2449 long ident = Binder.clearCallingIdentity(); 2450 try { 2451 final UserData userData; 2452 synchronized (mPackagesLock) { 2453 synchronized (mUsersLock) { 2454 userData = mUsers.get(userHandle); 2455 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) { 2456 return false; 2457 } 2458 } 2459 if (!userData.info.isGuest()) { 2460 return false; 2461 } 2462 // We set this to a guest user that is to be removed. This is a temporary state 2463 // where we are allowed to add new Guest users, even if this one is still not 2464 // removed. This user will still show up in getUserInfo() calls. 2465 // If we don't get around to removing this Guest user, it will be purged on next 2466 // startup. 2467 userData.info.guestToRemove = true; 2468 // Mark it as disabled, so that it isn't returned any more when 2469 // profiles are queried. 2470 userData.info.flags |= UserInfo.FLAG_DISABLED; 2471 writeUserLP(userData); 2472 } 2473 } finally { 2474 Binder.restoreCallingIdentity(ident); 2475 } 2476 return true; 2477 } 2478 2479 /** 2480 * Removes a user and all data directories created for that user. This method should be called 2481 * after the user's processes have been terminated. 2482 * @param userHandle the user's id 2483 */ 2484 @Override 2485 public boolean removeUser(int userHandle) { 2486 Slog.i(LOG_TAG, "removeUser u" + userHandle); 2487 checkManageOrCreateUsersPermission("Only the system can remove users"); 2488 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean( 2489 UserManager.DISALLOW_REMOVE_USER, false)) { 2490 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled."); 2491 return false; 2492 } 2493 2494 long ident = Binder.clearCallingIdentity(); 2495 try { 2496 final UserData userData; 2497 int currentUser = ActivityManager.getCurrentUser(); 2498 if (currentUser == userHandle) { 2499 Log.w(LOG_TAG, "Current user cannot be removed"); 2500 return false; 2501 } 2502 synchronized (mPackagesLock) { 2503 synchronized (mUsersLock) { 2504 userData = mUsers.get(userHandle); 2505 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) { 2506 return false; 2507 } 2508 2509 addRemovingUserIdLocked(userHandle); 2510 } 2511 2512 try { 2513 mAppOpsService.removeUser(userHandle); 2514 } catch (RemoteException e) { 2515 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e); 2516 } 2517 // Set this to a partially created user, so that the user will be purged 2518 // on next startup, in case the runtime stops now before stopping and 2519 // removing the user completely. 2520 userData.info.partial = true; 2521 // Mark it as disabled, so that it isn't returned any more when 2522 // profiles are queried. 2523 userData.info.flags |= UserInfo.FLAG_DISABLED; 2524 writeUserLP(userData); 2525 } 2526 2527 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID 2528 && userData.info.isManagedProfile()) { 2529 // Send broadcast to notify system that the user removed was a 2530 // managed user. 2531 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id); 2532 } 2533 2534 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle); 2535 int res; 2536 try { 2537 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true, 2538 new IStopUserCallback.Stub() { 2539 @Override 2540 public void userStopped(int userId) { 2541 finishRemoveUser(userId); 2542 } 2543 @Override 2544 public void userStopAborted(int userId) { 2545 } 2546 }); 2547 } catch (RemoteException e) { 2548 return false; 2549 } 2550 return res == ActivityManager.USER_OP_SUCCESS; 2551 } finally { 2552 Binder.restoreCallingIdentity(ident); 2553 } 2554 } 2555 2556 @VisibleForTesting 2557 void addRemovingUserIdLocked(int userId) { 2558 // We remember deleted user IDs to prevent them from being 2559 // reused during the current boot; they can still be reused 2560 // after a reboot or recycling of userIds. 2561 mRemovingUserIds.put(userId, true); 2562 mRecentlyRemovedIds.add(userId); 2563 // Keep LRU queue of recently removed IDs for recycling 2564 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) { 2565 mRecentlyRemovedIds.removeFirst(); 2566 } 2567 } 2568 2569 void finishRemoveUser(final int userHandle) { 2570 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle); 2571 // Let other services shutdown any activity and clean up their state before completely 2572 // wiping the user's system directory and removing from the user list 2573 long ident = Binder.clearCallingIdentity(); 2574 try { 2575 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED); 2576 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle); 2577 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL, 2578 android.Manifest.permission.MANAGE_USERS, 2579 2580 new BroadcastReceiver() { 2581 @Override 2582 public void onReceive(Context context, Intent intent) { 2583 if (DBG) { 2584 Slog.i(LOG_TAG, 2585 "USER_REMOVED broadcast sent, cleaning up user data " 2586 + userHandle); 2587 } 2588 new Thread() { 2589 @Override 2590 public void run() { 2591 // Clean up any ActivityManager state 2592 LocalServices.getService(ActivityManagerInternal.class) 2593 .onUserRemoved(userHandle); 2594 removeUserState(userHandle); 2595 } 2596 }.start(); 2597 } 2598 }, 2599 2600 null, Activity.RESULT_OK, null, null); 2601 } finally { 2602 Binder.restoreCallingIdentity(ident); 2603 } 2604 } 2605 2606 private void removeUserState(final int userHandle) { 2607 try { 2608 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle); 2609 } catch (IllegalStateException e) { 2610 // This may be simply because the user was partially created. 2611 Slog.i(LOG_TAG, 2612 "Destroying key for user " + userHandle + " failed, continuing anyway", e); 2613 } 2614 2615 // Cleanup gatekeeper secure user id 2616 try { 2617 final IGateKeeperService gk = GateKeeper.getService(); 2618 if (gk != null) { 2619 gk.clearSecureUserId(userHandle); 2620 } 2621 } catch (Exception ex) { 2622 Slog.w(LOG_TAG, "unable to clear GK secure user id"); 2623 } 2624 2625 // Cleanup package manager settings 2626 mPm.cleanUpUser(this, userHandle); 2627 2628 // Clean up all data before removing metadata 2629 mPm.destroyUserData(userHandle, 2630 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2631 2632 // Remove this user from the list 2633 synchronized (mUsersLock) { 2634 mUsers.remove(userHandle); 2635 mIsUserManaged.delete(userHandle); 2636 } 2637 synchronized (mUserStates) { 2638 mUserStates.delete(userHandle); 2639 } 2640 synchronized (mRestrictionsLock) { 2641 mBaseUserRestrictions.remove(userHandle); 2642 mAppliedUserRestrictions.remove(userHandle); 2643 mCachedEffectiveUserRestrictions.remove(userHandle); 2644 mDevicePolicyLocalUserRestrictions.remove(userHandle); 2645 } 2646 // Update the user list 2647 synchronized (mPackagesLock) { 2648 writeUserListLP(); 2649 } 2650 // Remove user file 2651 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX)); 2652 userFile.delete(); 2653 updateUserIds(); 2654 if (RELEASE_DELETED_USER_ID) { 2655 synchronized (mUsers) { 2656 mRemovingUserIds.delete(userHandle); 2657 } 2658 } 2659 } 2660 2661 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) { 2662 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED); 2663 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 2664 Intent.FLAG_RECEIVER_FOREGROUND); 2665 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId)); 2666 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId); 2667 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null); 2668 } 2669 2670 @Override 2671 public Bundle getApplicationRestrictions(String packageName) { 2672 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId()); 2673 } 2674 2675 @Override 2676 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) { 2677 if (UserHandle.getCallingUserId() != userId 2678 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) { 2679 checkSystemOrRoot("get application restrictions for other users/apps"); 2680 } 2681 synchronized (mPackagesLock) { 2682 // Read the restrictions from XML 2683 return readApplicationRestrictionsLP(packageName, userId); 2684 } 2685 } 2686 2687 @Override 2688 public void setApplicationRestrictions(String packageName, Bundle restrictions, 2689 int userId) { 2690 checkSystemOrRoot("set application restrictions"); 2691 if (restrictions != null) { 2692 restrictions.setDefusable(true); 2693 } 2694 synchronized (mPackagesLock) { 2695 if (restrictions == null || restrictions.isEmpty()) { 2696 cleanAppRestrictionsForPackage(packageName, userId); 2697 } else { 2698 // Write the restrictions to XML 2699 writeApplicationRestrictionsLP(packageName, restrictions, userId); 2700 } 2701 } 2702 2703 // Notify package of changes via an intent - only sent to explicitly registered receivers. 2704 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED); 2705 changeIntent.setPackage(packageName); 2706 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 2707 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId)); 2708 } 2709 2710 private int getUidForPackage(String packageName) { 2711 long ident = Binder.clearCallingIdentity(); 2712 try { 2713 return mContext.getPackageManager().getApplicationInfo(packageName, 2714 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid; 2715 } catch (NameNotFoundException nnfe) { 2716 return -1; 2717 } finally { 2718 Binder.restoreCallingIdentity(ident); 2719 } 2720 } 2721 2722 private Bundle readApplicationRestrictionsLP(String packageName, int userId) { 2723 AtomicFile restrictionsFile = 2724 new AtomicFile(new File(Environment.getUserSystemDirectory(userId), 2725 packageToRestrictionsFileName(packageName))); 2726 return readApplicationRestrictionsLP(restrictionsFile); 2727 } 2728 2729 @VisibleForTesting 2730 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) { 2731 final Bundle restrictions = new Bundle(); 2732 final ArrayList<String> values = new ArrayList<>(); 2733 if (!restrictionsFile.getBaseFile().exists()) { 2734 return restrictions; 2735 } 2736 2737 FileInputStream fis = null; 2738 try { 2739 fis = restrictionsFile.openRead(); 2740 XmlPullParser parser = Xml.newPullParser(); 2741 parser.setInput(fis, StandardCharsets.UTF_8.name()); 2742 XmlUtils.nextElement(parser); 2743 if (parser.getEventType() != XmlPullParser.START_TAG) { 2744 Slog.e(LOG_TAG, "Unable to read restrictions file " 2745 + restrictionsFile.getBaseFile()); 2746 return restrictions; 2747 } 2748 while (parser.next() != XmlPullParser.END_DOCUMENT) { 2749 readEntry(restrictions, values, parser); 2750 } 2751 } catch (IOException|XmlPullParserException e) { 2752 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e); 2753 } finally { 2754 IoUtils.closeQuietly(fis); 2755 } 2756 return restrictions; 2757 } 2758 2759 private static void readEntry(Bundle restrictions, ArrayList<String> values, 2760 XmlPullParser parser) throws XmlPullParserException, IOException { 2761 int type = parser.getEventType(); 2762 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) { 2763 String key = parser.getAttributeValue(null, ATTR_KEY); 2764 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE); 2765 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE); 2766 if (multiple != null) { 2767 values.clear(); 2768 int count = Integer.parseInt(multiple); 2769 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) { 2770 if (type == XmlPullParser.START_TAG 2771 && parser.getName().equals(TAG_VALUE)) { 2772 values.add(parser.nextText().trim()); 2773 count--; 2774 } 2775 } 2776 String [] valueStrings = new String[values.size()]; 2777 values.toArray(valueStrings); 2778 restrictions.putStringArray(key, valueStrings); 2779 } else if (ATTR_TYPE_BUNDLE.equals(valType)) { 2780 restrictions.putBundle(key, readBundleEntry(parser, values)); 2781 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) { 2782 final int outerDepth = parser.getDepth(); 2783 ArrayList<Bundle> bundleList = new ArrayList<>(); 2784 while (XmlUtils.nextElementWithin(parser, outerDepth)) { 2785 Bundle childBundle = readBundleEntry(parser, values); 2786 bundleList.add(childBundle); 2787 } 2788 restrictions.putParcelableArray(key, 2789 bundleList.toArray(new Bundle[bundleList.size()])); 2790 } else { 2791 String value = parser.nextText().trim(); 2792 if (ATTR_TYPE_BOOLEAN.equals(valType)) { 2793 restrictions.putBoolean(key, Boolean.parseBoolean(value)); 2794 } else if (ATTR_TYPE_INTEGER.equals(valType)) { 2795 restrictions.putInt(key, Integer.parseInt(value)); 2796 } else { 2797 restrictions.putString(key, value); 2798 } 2799 } 2800 } 2801 } 2802 2803 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values) 2804 throws IOException, XmlPullParserException { 2805 Bundle childBundle = new Bundle(); 2806 final int outerDepth = parser.getDepth(); 2807 while (XmlUtils.nextElementWithin(parser, outerDepth)) { 2808 readEntry(childBundle, values, parser); 2809 } 2810 return childBundle; 2811 } 2812 2813 private void writeApplicationRestrictionsLP(String packageName, 2814 Bundle restrictions, int userId) { 2815 AtomicFile restrictionsFile = new AtomicFile( 2816 new File(Environment.getUserSystemDirectory(userId), 2817 packageToRestrictionsFileName(packageName))); 2818 writeApplicationRestrictionsLP(restrictions, restrictionsFile); 2819 } 2820 2821 @VisibleForTesting 2822 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) { 2823 FileOutputStream fos = null; 2824 try { 2825 fos = restrictionsFile.startWrite(); 2826 final BufferedOutputStream bos = new BufferedOutputStream(fos); 2827 2828 final XmlSerializer serializer = new FastXmlSerializer(); 2829 serializer.setOutput(bos, StandardCharsets.UTF_8.name()); 2830 serializer.startDocument(null, true); 2831 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 2832 2833 serializer.startTag(null, TAG_RESTRICTIONS); 2834 writeBundle(restrictions, serializer); 2835 serializer.endTag(null, TAG_RESTRICTIONS); 2836 2837 serializer.endDocument(); 2838 restrictionsFile.finishWrite(fos); 2839 } catch (Exception e) { 2840 restrictionsFile.failWrite(fos); 2841 Slog.e(LOG_TAG, "Error writing application restrictions list", e); 2842 } 2843 } 2844 2845 private static void writeBundle(Bundle restrictions, XmlSerializer serializer) 2846 throws IOException { 2847 for (String key : restrictions.keySet()) { 2848 Object value = restrictions.get(key); 2849 serializer.startTag(null, TAG_ENTRY); 2850 serializer.attribute(null, ATTR_KEY, key); 2851 2852 if (value instanceof Boolean) { 2853 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN); 2854 serializer.text(value.toString()); 2855 } else if (value instanceof Integer) { 2856 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER); 2857 serializer.text(value.toString()); 2858 } else if (value == null || value instanceof String) { 2859 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING); 2860 serializer.text(value != null ? (String) value : ""); 2861 } else if (value instanceof Bundle) { 2862 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE); 2863 writeBundle((Bundle) value, serializer); 2864 } else if (value instanceof Parcelable[]) { 2865 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY); 2866 Parcelable[] array = (Parcelable[]) value; 2867 for (Parcelable parcelable : array) { 2868 if (!(parcelable instanceof Bundle)) { 2869 throw new IllegalArgumentException("bundle-array can only hold Bundles"); 2870 } 2871 serializer.startTag(null, TAG_ENTRY); 2872 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE); 2873 writeBundle((Bundle) parcelable, serializer); 2874 serializer.endTag(null, TAG_ENTRY); 2875 } 2876 } else { 2877 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY); 2878 String[] values = (String[]) value; 2879 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length)); 2880 for (String choice : values) { 2881 serializer.startTag(null, TAG_VALUE); 2882 serializer.text(choice != null ? choice : ""); 2883 serializer.endTag(null, TAG_VALUE); 2884 } 2885 } 2886 serializer.endTag(null, TAG_ENTRY); 2887 } 2888 } 2889 2890 @Override 2891 public int getUserSerialNumber(int userHandle) { 2892 synchronized (mUsersLock) { 2893 if (!exists(userHandle)) return -1; 2894 return getUserInfoLU(userHandle).serialNumber; 2895 } 2896 } 2897 2898 @Override 2899 public int getUserHandle(int userSerialNumber) { 2900 synchronized (mUsersLock) { 2901 for (int userId : mUserIds) { 2902 UserInfo info = getUserInfoLU(userId); 2903 if (info != null && info.serialNumber == userSerialNumber) return userId; 2904 } 2905 // Not found 2906 return -1; 2907 } 2908 } 2909 2910 @Override 2911 public long getUserCreationTime(int userHandle) { 2912 int callingUserId = UserHandle.getCallingUserId(); 2913 UserInfo userInfo = null; 2914 synchronized (mUsersLock) { 2915 if (callingUserId == userHandle) { 2916 userInfo = getUserInfoLU(userHandle); 2917 } else { 2918 UserInfo parent = getProfileParentLU(userHandle); 2919 if (parent != null && parent.id == callingUserId) { 2920 userInfo = getUserInfoLU(userHandle); 2921 } 2922 } 2923 } 2924 if (userInfo == null) { 2925 throw new SecurityException("userHandle can only be the calling user or a managed " 2926 + "profile associated with this user"); 2927 } 2928 return userInfo.creationTime; 2929 } 2930 2931 /** 2932 * Caches the list of user ids in an array, adjusting the array size when necessary. 2933 */ 2934 private void updateUserIds() { 2935 int num = 0; 2936 synchronized (mUsersLock) { 2937 final int userSize = mUsers.size(); 2938 for (int i = 0; i < userSize; i++) { 2939 if (!mUsers.valueAt(i).info.partial) { 2940 num++; 2941 } 2942 } 2943 final int[] newUsers = new int[num]; 2944 int n = 0; 2945 for (int i = 0; i < userSize; i++) { 2946 if (!mUsers.valueAt(i).info.partial) { 2947 newUsers[n++] = mUsers.keyAt(i); 2948 } 2949 } 2950 mUserIds = newUsers; 2951 } 2952 } 2953 2954 /** 2955 * Called right before a user is started. This gives us a chance to prepare 2956 * app storage and apply any user restrictions. 2957 */ 2958 public void onBeforeStartUser(int userId) { 2959 UserInfo userInfo = getUserInfo(userId); 2960 if (userInfo == null) { 2961 return; 2962 } 2963 final int userSerial = userInfo.serialNumber; 2964 // Migrate only if build fingerprints mismatch 2965 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint); 2966 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE); 2967 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData); 2968 2969 if (userId != UserHandle.USER_SYSTEM) { 2970 synchronized (mRestrictionsLock) { 2971 applyUserRestrictionsLR(userId); 2972 } 2973 } 2974 2975 maybeInitializeDemoMode(userId); 2976 } 2977 2978 /** 2979 * Called right before a user is unlocked. This gives us a chance to prepare 2980 * app storage. 2981 */ 2982 public void onBeforeUnlockUser(@UserIdInt int userId) { 2983 UserInfo userInfo = getUserInfo(userId); 2984 if (userInfo == null) { 2985 return; 2986 } 2987 final int userSerial = userInfo.serialNumber; 2988 // Migrate only if build fingerprints mismatch 2989 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint); 2990 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE); 2991 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData); 2992 } 2993 2994 /** 2995 * Make a note of the last started time of a user and do some cleanup. 2996 * This is called with ActivityManagerService lock held. 2997 * @param userId the user that was just foregrounded 2998 */ 2999 public void onUserLoggedIn(@UserIdInt int userId) { 3000 UserData userData = getUserDataNoChecks(userId); 3001 if (userData == null || userData.info.partial) { 3002 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId); 3003 return; 3004 } 3005 3006 final long now = System.currentTimeMillis(); 3007 if (now > EPOCH_PLUS_30_YEARS) { 3008 userData.info.lastLoggedInTime = now; 3009 } 3010 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT; 3011 scheduleWriteUser(userData); 3012 } 3013 3014 private void maybeInitializeDemoMode(int userId) { 3015 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) { 3016 String demoLauncher = 3017 mContext.getResources().getString( 3018 com.android.internal.R.string.config_demoModeLauncherComponent); 3019 if (!TextUtils.isEmpty(demoLauncher)) { 3020 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher); 3021 String demoLauncherPkg = componentToEnable.getPackageName(); 3022 try { 3023 final IPackageManager iPm = AppGlobals.getPackageManager(); 3024 iPm.setComponentEnabledSetting(componentToEnable, 3025 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0, 3026 /* userId= */ userId); 3027 iPm.setApplicationEnabledSetting(demoLauncherPkg, 3028 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0, 3029 /* userId= */ userId, null); 3030 } catch (RemoteException re) { 3031 // Internal, shouldn't happen 3032 } 3033 } 3034 } 3035 } 3036 3037 /** 3038 * Returns the next available user id, filling in any holes in the ids. 3039 */ 3040 @VisibleForTesting 3041 int getNextAvailableId() { 3042 int nextId; 3043 synchronized (mUsersLock) { 3044 nextId = scanNextAvailableIdLocked(); 3045 if (nextId >= 0) { 3046 return nextId; 3047 } 3048 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds, 3049 // except most recently removed 3050 if (mRemovingUserIds.size() > 0) { 3051 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids."); 3052 mRemovingUserIds.clear(); 3053 for (Integer recentlyRemovedId : mRecentlyRemovedIds) { 3054 mRemovingUserIds.put(recentlyRemovedId, true); 3055 } 3056 nextId = scanNextAvailableIdLocked(); 3057 } 3058 } 3059 if (nextId < 0) { 3060 throw new IllegalStateException("No user id available!"); 3061 } 3062 return nextId; 3063 } 3064 3065 private int scanNextAvailableIdLocked() { 3066 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) { 3067 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) { 3068 return i; 3069 } 3070 } 3071 return -1; 3072 } 3073 3074 private String packageToRestrictionsFileName(String packageName) { 3075 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX; 3076 } 3077 3078 /** 3079 * Enforce that serial number stored in user directory inode matches the 3080 * given expected value. Gracefully sets the serial number if currently 3081 * undefined. 3082 * 3083 * @throws IOException when problem extracting serial number, or serial 3084 * number is mismatched. 3085 */ 3086 public static void enforceSerialNumber(File file, int serialNumber) throws IOException { 3087 if (StorageManager.isFileEncryptedEmulatedOnly()) { 3088 // When we're emulating FBE, the directory may have been chmod 3089 // 000'ed, meaning we can't read the serial number to enforce it; 3090 // instead of destroying the user, just log a warning. 3091 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid"); 3092 return; 3093 } 3094 3095 final int foundSerial = getSerialNumber(file); 3096 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial); 3097 3098 if (foundSerial == -1) { 3099 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid"); 3100 try { 3101 setSerialNumber(file, serialNumber); 3102 } catch (IOException e) { 3103 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e); 3104 } 3105 3106 } else if (foundSerial != serialNumber) { 3107 throw new IOException("Found serial number " + foundSerial 3108 + " doesn't match expected " + serialNumber); 3109 } 3110 } 3111 3112 /** 3113 * Set serial number stored in user directory inode. 3114 * 3115 * @throws IOException if serial number was already set 3116 */ 3117 private static void setSerialNumber(File file, int serialNumber) 3118 throws IOException { 3119 try { 3120 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8); 3121 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE); 3122 } catch (ErrnoException e) { 3123 throw e.rethrowAsIOException(); 3124 } 3125 } 3126 3127 /** 3128 * Return serial number stored in user directory inode. 3129 * 3130 * @return parsed serial number, or -1 if not set 3131 */ 3132 private static int getSerialNumber(File file) throws IOException { 3133 try { 3134 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL); 3135 final String serial = new String(buf); 3136 try { 3137 return Integer.parseInt(serial); 3138 } catch (NumberFormatException e) { 3139 throw new IOException("Bad serial number: " + serial); 3140 } 3141 } catch (ErrnoException e) { 3142 if (e.errno == OsConstants.ENODATA) { 3143 return -1; 3144 } else { 3145 throw e.rethrowAsIOException(); 3146 } 3147 } 3148 } 3149 3150 @Override 3151 public void setSeedAccountData(int userId, String accountName, String accountType, 3152 PersistableBundle accountOptions, boolean persist) { 3153 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data"); 3154 synchronized (mPackagesLock) { 3155 final UserData userData; 3156 synchronized (mUsersLock) { 3157 userData = getUserDataLU(userId); 3158 if (userData == null) { 3159 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId); 3160 return; 3161 } 3162 userData.seedAccountName = accountName; 3163 userData.seedAccountType = accountType; 3164 userData.seedAccountOptions = accountOptions; 3165 userData.persistSeedData = persist; 3166 } 3167 if (persist) { 3168 writeUserLP(userData); 3169 } 3170 } 3171 } 3172 3173 @Override 3174 public String getSeedAccountName() throws RemoteException { 3175 checkManageUsersPermission("Cannot get seed account information"); 3176 synchronized (mUsersLock) { 3177 UserData userData = getUserDataLU(UserHandle.getCallingUserId()); 3178 return userData.seedAccountName; 3179 } 3180 } 3181 3182 @Override 3183 public String getSeedAccountType() throws RemoteException { 3184 checkManageUsersPermission("Cannot get seed account information"); 3185 synchronized (mUsersLock) { 3186 UserData userData = getUserDataLU(UserHandle.getCallingUserId()); 3187 return userData.seedAccountType; 3188 } 3189 } 3190 3191 @Override 3192 public PersistableBundle getSeedAccountOptions() throws RemoteException { 3193 checkManageUsersPermission("Cannot get seed account information"); 3194 synchronized (mUsersLock) { 3195 UserData userData = getUserDataLU(UserHandle.getCallingUserId()); 3196 return userData.seedAccountOptions; 3197 } 3198 } 3199 3200 @Override 3201 public void clearSeedAccountData() throws RemoteException { 3202 checkManageUsersPermission("Cannot clear seed account information"); 3203 synchronized (mPackagesLock) { 3204 UserData userData; 3205 synchronized (mUsersLock) { 3206 userData = getUserDataLU(UserHandle.getCallingUserId()); 3207 if (userData == null) return; 3208 userData.clearSeedAccountData(); 3209 } 3210 writeUserLP(userData); 3211 } 3212 } 3213 3214 @Override 3215 public boolean someUserHasSeedAccount(String accountName, String accountType) 3216 throws RemoteException { 3217 checkManageUsersPermission("Cannot check seed account information"); 3218 synchronized (mUsersLock) { 3219 final int userSize = mUsers.size(); 3220 for (int i = 0; i < userSize; i++) { 3221 final UserData data = mUsers.valueAt(i); 3222 if (data.info.isInitialized()) continue; 3223 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) { 3224 continue; 3225 } 3226 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) { 3227 continue; 3228 } 3229 return true; 3230 } 3231 } 3232 return false; 3233 } 3234 3235 @Override 3236 public void onShellCommand(FileDescriptor in, FileDescriptor out, 3237 FileDescriptor err, String[] args, ShellCallback callback, 3238 ResultReceiver resultReceiver) { 3239 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver); 3240 } 3241 3242 int onShellCommand(Shell shell, String cmd) { 3243 if (cmd == null) { 3244 return shell.handleDefaultCommands(cmd); 3245 } 3246 3247 final PrintWriter pw = shell.getOutPrintWriter(); 3248 try { 3249 switch(cmd) { 3250 case "list": 3251 return runList(pw); 3252 } 3253 } catch (RemoteException e) { 3254 pw.println("Remote exception: " + e); 3255 } 3256 return -1; 3257 } 3258 3259 private int runList(PrintWriter pw) throws RemoteException { 3260 final IActivityManager am = ActivityManagerNative.getDefault(); 3261 final List<UserInfo> users = getUsers(false); 3262 if (users == null) { 3263 pw.println("Error: couldn't get users"); 3264 return 1; 3265 } else { 3266 pw.println("Users:"); 3267 for (int i = 0; i < users.size(); i++) { 3268 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : ""; 3269 pw.println("\t" + users.get(i).toString() + running); 3270 } 3271 return 0; 3272 } 3273 } 3274 3275 @Override 3276 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3277 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 3278 != PackageManager.PERMISSION_GRANTED) { 3279 pw.println("Permission Denial: can't dump UserManager from from pid=" 3280 + Binder.getCallingPid() 3281 + ", uid=" + Binder.getCallingUid() 3282 + " without permission " 3283 + android.Manifest.permission.DUMP); 3284 return; 3285 } 3286 3287 long now = System.currentTimeMillis(); 3288 StringBuilder sb = new StringBuilder(); 3289 synchronized (mPackagesLock) { 3290 synchronized (mUsersLock) { 3291 pw.println("Users:"); 3292 for (int i = 0; i < mUsers.size(); i++) { 3293 UserData userData = mUsers.valueAt(i); 3294 if (userData == null) { 3295 continue; 3296 } 3297 UserInfo userInfo = userData.info; 3298 final int userId = userInfo.id; 3299 pw.print(" "); pw.print(userInfo); 3300 pw.print(" serialNo="); pw.print(userInfo.serialNumber); 3301 if (mRemovingUserIds.get(userId)) { 3302 pw.print(" <removing> "); 3303 } 3304 if (userInfo.partial) { 3305 pw.print(" <partial>"); 3306 } 3307 pw.println(); 3308 pw.print(" Created: "); 3309 if (userInfo.creationTime == 0) { 3310 pw.println("<unknown>"); 3311 } else { 3312 sb.setLength(0); 3313 TimeUtils.formatDuration(now - userInfo.creationTime, sb); 3314 sb.append(" ago"); 3315 pw.println(sb); 3316 } 3317 pw.print(" Last logged in: "); 3318 if (userInfo.lastLoggedInTime == 0) { 3319 pw.println("<unknown>"); 3320 } else { 3321 sb.setLength(0); 3322 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb); 3323 sb.append(" ago"); 3324 pw.println(sb); 3325 } 3326 pw.print(" Last logged in fingerprint: "); 3327 pw.println(userInfo.lastLoggedInFingerprint); 3328 pw.print(" Has profile owner: "); 3329 pw.println(mIsUserManaged.get(userId)); 3330 pw.println(" Restrictions:"); 3331 synchronized (mRestrictionsLock) { 3332 UserRestrictionsUtils.dumpRestrictions( 3333 pw, " ", mBaseUserRestrictions.get(userInfo.id)); 3334 pw.println(" Device policy local restrictions:"); 3335 UserRestrictionsUtils.dumpRestrictions( 3336 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id)); 3337 pw.println(" Effective restrictions:"); 3338 UserRestrictionsUtils.dumpRestrictions( 3339 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id)); 3340 } 3341 3342 if (userData.account != null) { 3343 pw.print(" Account name: " + userData.account); 3344 pw.println(); 3345 } 3346 3347 if (userData.seedAccountName != null) { 3348 pw.print(" Seed account name: " + userData.seedAccountName); 3349 pw.println(); 3350 if (userData.seedAccountType != null) { 3351 pw.print(" account type: " + userData.seedAccountType); 3352 pw.println(); 3353 } 3354 if (userData.seedAccountOptions != null) { 3355 pw.print(" account options exist"); 3356 pw.println(); 3357 } 3358 } 3359 } 3360 } 3361 pw.println(); 3362 pw.println(" Device policy global restrictions:"); 3363 synchronized (mRestrictionsLock) { 3364 UserRestrictionsUtils 3365 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions); 3366 } 3367 pw.println(); 3368 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId); 3369 pw.println(); 3370 pw.println(" Guest restrictions:"); 3371 synchronized (mGuestRestrictions) { 3372 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions); 3373 } 3374 synchronized (mUsersLock) { 3375 pw.println(); 3376 pw.println(" Device managed: " + mIsDeviceManaged); 3377 if (mRemovingUserIds.size() > 0) { 3378 pw.println(); 3379 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds); 3380 } 3381 } 3382 synchronized (mUserStates) { 3383 pw.println(" Started users state: " + mUserStates); 3384 } 3385 // Dump some capabilities 3386 pw.println(); 3387 pw.println(" Max users: " + UserManager.getMaxSupportedUsers()); 3388 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers()); 3389 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean( 3390 com.android.internal.R.bool.config_guestUserEphemeral)); 3391 } 3392 } 3393 3394 final class MainHandler extends Handler { 3395 3396 @Override 3397 public void handleMessage(Message msg) { 3398 switch (msg.what) { 3399 case WRITE_USER_MSG: 3400 removeMessages(WRITE_USER_MSG, msg.obj); 3401 synchronized (mPackagesLock) { 3402 int userId = ((UserData) msg.obj).info.id; 3403 UserData userData = getUserDataNoChecks(userId); 3404 if (userData != null) { 3405 writeUserLP(userData); 3406 } 3407 } 3408 } 3409 } 3410 } 3411 3412 /** 3413 * @param userId 3414 * @return whether the user has been initialized yet 3415 */ 3416 boolean isInitialized(int userId) { 3417 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0; 3418 } 3419 3420 private class LocalService extends UserManagerInternal { 3421 @Override 3422 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions, 3423 @Nullable Bundle globalRestrictions) { 3424 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions, 3425 globalRestrictions); 3426 } 3427 3428 @Override 3429 public Bundle getBaseUserRestrictions(int userId) { 3430 synchronized (mRestrictionsLock) { 3431 return mBaseUserRestrictions.get(userId); 3432 } 3433 } 3434 3435 @Override 3436 public void setBaseUserRestrictionsByDpmsForMigration( 3437 int userId, Bundle baseRestrictions) { 3438 synchronized (mRestrictionsLock) { 3439 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions)); 3440 invalidateEffectiveUserRestrictionsLR(userId); 3441 } 3442 3443 final UserData userData = getUserDataNoChecks(userId); 3444 synchronized (mPackagesLock) { 3445 if (userData != null) { 3446 writeUserLP(userData); 3447 } else { 3448 Slog.w(LOG_TAG, "UserInfo not found for " + userId); 3449 } 3450 } 3451 } 3452 3453 @Override 3454 public boolean getUserRestriction(int userId, String key) { 3455 return getUserRestrictions(userId).getBoolean(key); 3456 } 3457 3458 @Override 3459 public void addUserRestrictionsListener(UserRestrictionsListener listener) { 3460 synchronized (mUserRestrictionsListeners) { 3461 mUserRestrictionsListeners.add(listener); 3462 } 3463 } 3464 3465 @Override 3466 public void removeUserRestrictionsListener(UserRestrictionsListener listener) { 3467 synchronized (mUserRestrictionsListeners) { 3468 mUserRestrictionsListeners.remove(listener); 3469 } 3470 } 3471 3472 @Override 3473 public void setDeviceManaged(boolean isManaged) { 3474 synchronized (mUsersLock) { 3475 mIsDeviceManaged = isManaged; 3476 } 3477 } 3478 3479 @Override 3480 public void setUserManaged(int userId, boolean isManaged) { 3481 synchronized (mUsersLock) { 3482 mIsUserManaged.put(userId, isManaged); 3483 } 3484 } 3485 3486 @Override 3487 public void setUserIcon(int userId, Bitmap bitmap) { 3488 long ident = Binder.clearCallingIdentity(); 3489 try { 3490 synchronized (mPackagesLock) { 3491 UserData userData = getUserDataNoChecks(userId); 3492 if (userData == null || userData.info.partial) { 3493 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId); 3494 return; 3495 } 3496 writeBitmapLP(userData.info, bitmap); 3497 writeUserLP(userData); 3498 } 3499 sendUserInfoChangedBroadcast(userId); 3500 } finally { 3501 Binder.restoreCallingIdentity(ident); 3502 } 3503 } 3504 3505 @Override 3506 public void setForceEphemeralUsers(boolean forceEphemeralUsers) { 3507 synchronized (mUsersLock) { 3508 mForceEphemeralUsers = forceEphemeralUsers; 3509 } 3510 } 3511 3512 @Override 3513 public void removeAllUsers() { 3514 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) { 3515 // Remove the non-system users straight away. 3516 removeNonSystemUsers(); 3517 } else { 3518 // Switch to the system user first and then remove the other users. 3519 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() { 3520 @Override 3521 public void onReceive(Context context, Intent intent) { 3522 int userId = 3523 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 3524 if (userId != UserHandle.USER_SYSTEM) { 3525 return; 3526 } 3527 mContext.unregisterReceiver(this); 3528 removeNonSystemUsers(); 3529 } 3530 }; 3531 IntentFilter userSwitchedFilter = new IntentFilter(); 3532 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED); 3533 mContext.registerReceiver( 3534 userSwitchedReceiver, userSwitchedFilter, null, mHandler); 3535 3536 // Switch to the system user. 3537 ActivityManager am = 3538 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); 3539 am.switchUser(UserHandle.USER_SYSTEM); 3540 } 3541 } 3542 3543 @Override 3544 public void onEphemeralUserStop(int userId) { 3545 synchronized (mUsersLock) { 3546 UserInfo userInfo = getUserInfoLU(userId); 3547 if (userInfo != null && userInfo.isEphemeral()) { 3548 // Do not allow switching back to the ephemeral user again as the user is going 3549 // to be deleted. 3550 userInfo.flags |= UserInfo.FLAG_DISABLED; 3551 if (userInfo.isGuest()) { 3552 // Indicate that the guest will be deleted after it stops. 3553 userInfo.guestToRemove = true; 3554 } 3555 } 3556 } 3557 } 3558 3559 @Override 3560 public UserInfo createUserEvenWhenDisallowed(String name, int flags) { 3561 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null); 3562 // Keep this in sync with UserManager.createUser 3563 if (user != null && !user.isAdmin()) { 3564 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id); 3565 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id); 3566 } 3567 return user; 3568 } 3569 3570 @Override 3571 public boolean isUserRunning(int userId) { 3572 synchronized (mUserStates) { 3573 return mUserStates.get(userId, -1) >= 0; 3574 } 3575 } 3576 3577 @Override 3578 public void setUserState(int userId, int userState) { 3579 synchronized (mUserStates) { 3580 mUserStates.put(userId, userState); 3581 } 3582 } 3583 3584 @Override 3585 public void removeUserState(int userId) { 3586 synchronized (mUserStates) { 3587 mUserStates.delete(userId); 3588 } 3589 } 3590 3591 @Override 3592 public boolean isUserUnlockingOrUnlocked(int userId) { 3593 synchronized (mUserStates) { 3594 int state = mUserStates.get(userId, -1); 3595 return (state == UserState.STATE_RUNNING_UNLOCKING) 3596 || (state == UserState.STATE_RUNNING_UNLOCKED); 3597 } 3598 } 3599 } 3600 3601 /* Remove all the users except of the system one. */ 3602 private void removeNonSystemUsers() { 3603 ArrayList<UserInfo> usersToRemove = new ArrayList<>(); 3604 synchronized (mUsersLock) { 3605 final int userSize = mUsers.size(); 3606 for (int i = 0; i < userSize; i++) { 3607 UserInfo ui = mUsers.valueAt(i).info; 3608 if (ui.id != UserHandle.USER_SYSTEM) { 3609 usersToRemove.add(ui); 3610 } 3611 } 3612 } 3613 for (UserInfo ui: usersToRemove) { 3614 removeUser(ui.id); 3615 } 3616 } 3617 3618 private class Shell extends ShellCommand { 3619 @Override 3620 public int onCommand(String cmd) { 3621 return onShellCommand(this, cmd); 3622 } 3623 3624 @Override 3625 public void onHelp() { 3626 final PrintWriter pw = getOutPrintWriter(); 3627 pw.println("User manager (user) commands:"); 3628 pw.println(" help"); 3629 pw.println(" Print this help text."); 3630 pw.println(""); 3631 pw.println(" list"); 3632 pw.println(" Prints all users on the system."); 3633 } 3634 } 3635 3636 private static void debug(String message) { 3637 Log.d(LOG_TAG, message + 3638 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : "")); 3639 } 3640} 3641