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