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