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