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