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