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