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