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