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