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