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