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