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