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