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