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