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