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