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