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 17 package com.android.server.pm; 18 19 import static android.content.Intent.ACTION_SCREEN_OFF; 20 import static android.content.Intent.ACTION_SCREEN_ON; 21 import static android.content.Intent.EXTRA_USER_ID; 22 import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS; 23 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; 24 import static android.content.pm.LauncherUserInfo.PRIVATE_SPACE_ENTRYPOINT_HIDDEN; 25 import static android.content.pm.PackageManager.FEATURE_AUTOMOTIVE; 26 import static android.content.pm.PackageManager.FEATURE_EMBEDDED; 27 import static android.content.pm.PackageManager.FEATURE_LEANBACK; 28 import static android.content.pm.PackageManager.FEATURE_WATCH; 29 import static android.os.UserHandle.USER_SYSTEM; 30 import static android.os.UserManager.DEV_CREATE_OVERRIDE_PROPERTY; 31 import static android.os.UserManager.DISALLOW_USER_SWITCH; 32 import static android.os.UserManager.SYSTEM_USER_MODE_EMULATION_PROPERTY; 33 import static android.os.UserManager.USER_OPERATION_ERROR_UNKNOWN; 34 import static android.os.UserManager.USER_OPERATION_ERROR_USER_RESTRICTED; 35 import static android.os.UserManager.USER_TYPE_PROFILE_PRIVATE; 36 import static android.provider.Settings.Secure.HIDE_PRIVATESPACE_ENTRY_POINT; 37 38 import static com.android.internal.app.SetScreenLockDialogActivity.EXTRA_ORIGIN_USER_ID; 39 import static com.android.internal.app.SetScreenLockDialogActivity.LAUNCH_REASON_DISABLE_QUIET_MODE; 40 import static com.android.internal.util.ConcurrentUtils.DIRECT_EXECUTOR; 41 import static com.android.server.pm.UserJourneyLogger.ERROR_CODE_ABORTED; 42 import static com.android.server.pm.UserJourneyLogger.ERROR_CODE_UNSPECIFIED; 43 import static com.android.server.pm.UserJourneyLogger.ERROR_CODE_USER_ALREADY_AN_ADMIN; 44 import static com.android.server.pm.UserJourneyLogger.ERROR_CODE_USER_IS_NOT_AN_ADMIN; 45 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_GRANT_ADMIN; 46 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_REVOKE_ADMIN; 47 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_CREATE; 48 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_LIFECYCLE; 49 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_REMOVE; 50 51 import android.Manifest; 52 import android.accounts.Account; 53 import android.accounts.AccountManager; 54 import android.annotation.ColorRes; 55 import android.annotation.DrawableRes; 56 import android.annotation.NonNull; 57 import android.annotation.Nullable; 58 import android.annotation.RequiresPermission; 59 import android.annotation.SpecialUsers.CanBeALL; 60 import android.annotation.SpecialUsers.CanBeCURRENT; 61 import android.annotation.SpecialUsers.CanBeNULL; 62 import android.annotation.StringRes; 63 import android.annotation.UserIdInt; 64 import android.app.ActivityManager; 65 import android.app.ActivityManagerInternal; 66 import android.app.ActivityManagerNative; 67 import android.app.ActivityOptions; 68 import android.app.AlarmManager; 69 import android.app.BroadcastOptions; 70 import android.app.IActivityManager; 71 import android.app.IStopUserCallback; 72 import android.app.KeyguardManager; 73 import android.app.Notification; 74 import android.app.NotificationManager; 75 import android.app.PendingIntent; 76 import android.app.StatsManager; 77 import android.app.admin.DevicePolicyEventLogger; 78 import android.app.admin.DevicePolicyManagerInternal; 79 import android.content.BroadcastReceiver; 80 import android.content.Context; 81 import android.content.IIntentReceiver; 82 import android.content.Intent; 83 import android.content.IntentFilter; 84 import android.content.IntentSender; 85 import android.content.pm.LauncherUserInfo; 86 import android.content.pm.PackageManager; 87 import android.content.pm.PackageManager.NameNotFoundException; 88 import android.content.pm.PackageManagerInternal; 89 import android.content.pm.PackagePartitions; 90 import android.content.pm.ShortcutServiceInternal; 91 import android.content.pm.UserInfo; 92 import android.content.pm.UserInfo.UserInfoFlag; 93 import android.content.pm.UserPackage; 94 import android.content.pm.UserProperties; 95 import android.content.pm.parsing.FrameworkParsingPackageUtils; 96 import android.content.res.Configuration; 97 import android.content.res.Resources; 98 import android.database.ContentObserver; 99 import android.graphics.Bitmap; 100 import android.multiuser.Flags; 101 import android.net.Uri; 102 import android.os.Binder; 103 import android.os.Build; 104 import android.os.Bundle; 105 import android.os.Debug; 106 import android.os.Environment; 107 import android.os.FileUtils; 108 import android.os.Handler; 109 import android.os.HandlerExecutor; 110 import android.os.IBinder; 111 import android.os.IProgressListener; 112 import android.os.IUserManager; 113 import android.os.IUserRestrictionsListener; 114 import android.os.Message; 115 import android.os.ParcelFileDescriptor; 116 import android.os.Parcelable; 117 import android.os.PersistableBundle; 118 import android.os.PowerManager; 119 import android.os.Process; 120 import android.os.RemoteException; 121 import android.os.ResultReceiver; 122 import android.os.SELinux; 123 import android.os.ServiceManager; 124 import android.os.ServiceSpecificException; 125 import android.os.ShellCallback; 126 import android.os.SystemClock; 127 import android.os.SystemProperties; 128 import android.os.UserHandle; 129 import android.os.UserManager; 130 import android.os.UserManager.EnforcingUser; 131 import android.os.UserManager.QuietModeFlag; 132 import android.os.UserManager.UserLogoutability; 133 import android.os.storage.StorageManager; 134 import android.os.storage.StorageManagerInternal; 135 import android.provider.Settings; 136 import android.service.voice.VoiceInteractionManagerInternal; 137 import android.stats.devicepolicy.DevicePolicyEnums; 138 import android.telecom.TelecomManager; 139 import android.text.TextUtils; 140 import android.util.ArrayMap; 141 import android.util.ArraySet; 142 import android.util.AtomicFile; 143 import android.util.IndentingPrintWriter; 144 import android.util.IntArray; 145 import android.util.Pair; 146 import android.util.Slog; 147 import android.util.SparseArray; 148 import android.util.SparseBooleanArray; 149 import android.util.SparseIntArray; 150 import android.util.StatsEvent; 151 import android.util.TimeUtils; 152 import android.util.TypedValue; 153 import android.util.Xml; 154 155 import com.android.internal.R; 156 import com.android.internal.annotations.GuardedBy; 157 import com.android.internal.annotations.VisibleForTesting; 158 import com.android.internal.app.IAppOpsService; 159 import com.android.internal.app.SetScreenLockDialogActivity; 160 import com.android.internal.logging.MetricsLogger; 161 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 162 import com.android.internal.notification.SystemNotificationChannels; 163 import com.android.internal.os.BackgroundThread; 164 import com.android.internal.os.RoSystemProperties; 165 import com.android.internal.util.DumpUtils; 166 import com.android.internal.util.FrameworkStatsLog; 167 import com.android.internal.util.Preconditions; 168 import com.android.internal.util.XmlUtils; 169 import com.android.internal.widget.LockPatternUtils; 170 import com.android.modules.utils.TypedXmlPullParser; 171 import com.android.modules.utils.TypedXmlSerializer; 172 import com.android.server.BundleUtils; 173 import com.android.server.LocalServices; 174 import com.android.server.LockGuard; 175 import com.android.server.SystemService; 176 import com.android.server.am.UserState; 177 import com.android.server.pm.UserManagerInternal.UserLifecycleListener; 178 import com.android.server.pm.UserManagerInternal.UserRestrictionsListener; 179 import com.android.server.storage.DeviceStorageMonitorInternal; 180 import com.android.server.utils.Slogf; 181 import com.android.server.utils.TimingsTraceAndSlog; 182 import com.android.server.wm.ActivityTaskManagerInternal; 183 184 import libcore.io.IoUtils; 185 186 import org.xmlpull.v1.XmlPullParser; 187 import org.xmlpull.v1.XmlPullParserException; 188 189 import java.io.File; 190 import java.io.FileDescriptor; 191 import java.io.FileInputStream; 192 import java.io.FileNotFoundException; 193 import java.io.FileOutputStream; 194 import java.io.IOException; 195 import java.io.InputStream; 196 import java.io.OutputStream; 197 import java.io.PrintWriter; 198 import java.util.ArrayList; 199 import java.util.Arrays; 200 import java.util.Collections; 201 import java.util.LinkedList; 202 import java.util.List; 203 import java.util.Objects; 204 import java.util.Optional; 205 import java.util.Set; 206 import java.util.concurrent.CountDownLatch; 207 import java.util.concurrent.LinkedBlockingQueue; 208 import java.util.concurrent.ThreadPoolExecutor; 209 import java.util.concurrent.TimeUnit; 210 import java.util.concurrent.atomic.AtomicInteger; 211 import java.util.concurrent.atomic.AtomicReference; 212 213 /** 214 * Service for {@link UserManager}. 215 * 216 * Method naming convention: 217 * <ul> 218 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock. 219 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock. 220 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock. 221 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock. 222 * </ul> 223 */ 224 public class UserManagerService extends IUserManager.Stub { 225 226 private static final String LOG_TAG = "UserManagerService"; 227 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE 228 // For Multiple Users on Multiple Displays 229 static final boolean DBG_MUMD = false; // DO NOT SUBMIT WITH TRUE 230 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE 231 // Can be used for manual testing of id recycling 232 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE 233 234 private static final String TAG_NAME = "name"; 235 private static final String TAG_ACCOUNT = "account"; 236 private static final String ATTR_FLAGS = "flags"; 237 private static final String ATTR_TYPE = "type"; // userType 238 private static final String ATTR_ICON_PATH = "icon"; 239 private static final String ATTR_ID = "id"; 240 private static final String ATTR_CREATION_TIME = "created"; 241 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn"; 242 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint"; 243 private static final String ATTR_LAST_ENTERED_FOREGROUND_TIME = "lastEnteredForeground"; 244 private static final String ATTR_SERIAL_NO = "serialNumber"; 245 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber"; 246 private static final String ATTR_PARTIAL = "partial"; 247 private static final String ATTR_PRE_CREATED = "preCreated"; 248 private static final String ATTR_CONVERTED_FROM_PRE_CREATED = "convertedFromPreCreated"; 249 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove"; 250 private static final String ATTR_USER_VERSION = "version"; 251 private static final String ATTR_USER_TYPE_VERSION = "userTypeConfigVersion"; 252 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId"; 253 private static final String ATTR_PROFILE_BADGE = "profileBadge"; 254 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId"; 255 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName"; 256 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType"; 257 258 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions"; 259 private static final String TAG_USERS = "users"; 260 private static final String TAG_USER = "user"; 261 private static final String TAG_RESTRICTIONS = "restrictions"; 262 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions"; 263 private static final String TAG_DEVICE_POLICY_LOCAL_RESTRICTIONS = 264 "device_policy_local_restrictions"; 265 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS = 266 "device_policy_global_restrictions"; 267 /** Legacy name for device owner id tag. */ 268 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId"; 269 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId"; 270 private static final String TAG_ENTRY = "entry"; 271 private static final String TAG_VALUE = "value"; 272 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions"; 273 private static final String TAG_USER_PROPERTIES = "userProperties"; 274 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL = 275 "lastRequestQuietModeEnabledCall"; 276 private static final String TAG_IGNORE_PREPARE_STORAGE_ERRORS = 277 "ignorePrepareStorageErrors"; 278 279 private static final String ATTR_KEY = "key"; 280 private static final String ATTR_VALUE_TYPE = "type"; 281 private static final String ATTR_MULTIPLE = "m"; 282 283 private static final String ATTR_TYPE_STRING_ARRAY = "sa"; 284 private static final String ATTR_TYPE_STRING = "s"; 285 private static final String ATTR_TYPE_BOOLEAN = "b"; 286 private static final String ATTR_TYPE_INTEGER = "i"; 287 private static final String ATTR_TYPE_BUNDLE = "B"; 288 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA"; 289 290 private static final String USER_INFO_DIR = "system" + File.separator + "users"; 291 private static final String USER_LIST_FILENAME = "userlist.xml"; 292 private static final String USER_PHOTO_FILENAME = "photo.png"; 293 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp"; 294 295 private static final String RESTRICTIONS_FILE_PREFIX = "res_"; 296 private static final String XML_SUFFIX = ".xml"; 297 298 private static final String CUSTOM_BIOMETRIC_PROMPT_LOGO_RES_ID_KEY = "custom_logo_res_id"; 299 private static final String CUSTOM_BIOMETRIC_PROMPT_LOGO_DESCRIPTION_KEY = 300 "custom_logo_description"; 301 302 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION = 303 UserInfo.FLAG_MANAGED_PROFILE 304 | UserInfo.FLAG_PROFILE 305 | UserInfo.FLAG_EPHEMERAL 306 | UserInfo.FLAG_RESTRICTED 307 | UserInfo.FLAG_GUEST 308 | UserInfo.FLAG_DEMO 309 | UserInfo.FLAG_FULL 310 | UserInfo.FLAG_FOR_TESTING; 311 312 @VisibleForTesting 313 static final int MIN_USER_ID = UserHandle.MIN_SECONDARY_USER_ID; 314 315 // We need to keep process uid within Integer.MAX_VALUE. 316 @VisibleForTesting 317 static final int MAX_USER_ID = UserHandle.MAX_SECONDARY_USER_ID; 318 319 // Max size of the queue of recently removed users 320 @VisibleForTesting 321 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100; 322 323 private static final int USER_VERSION = 11; 324 325 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms 326 327 static final int WRITE_USER_MSG = 1; 328 static final int WRITE_USER_LIST_MSG = 2; 329 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds 330 331 private static final long BOOT_USER_SET_TIMEOUT_MS = 300_000; 332 333 /** 334 * The time duration (in milliseconds) post device inactivity after which the private space 335 * should be auto-locked if the corresponding settings option is selected by the user. 336 */ 337 private static final long PRIVATE_SPACE_AUTO_LOCK_INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000; 338 339 /** 340 * The time duration (in milliseconds) of the window length for the auto-lock message alarm 341 */ 342 private static final long PRIVATE_SPACE_AUTO_LOCK_INACTIVITY_ALARM_WINDOW_MS = 343 TimeUnit.SECONDS.toMillis(55); 344 345 // Tron counters 346 private static final String TRON_GUEST_CREATED = "users_guest_created"; 347 private static final String TRON_USER_CREATED = "users_user_created"; 348 private static final String TRON_DEMO_CREATED = "users_demo_created"; 349 350 // The boot user strategy for HSUM. 351 private static final int BOOT_TO_PREVIOUS_OR_FIRST_SWITCHABLE_USER = 0; 352 private static final int BOOT_TO_HSU_FOR_PROVISIONED_DEVICE = 1; 353 354 private final Context mContext; 355 private final PackageManagerService mPm; 356 357 358 /** 359 * Lock for packages. If using with {@link #mUsersLock}, {@link #mPackagesLock} should be 360 * acquired first. 361 */ 362 private final Object mPackagesLock; 363 private final UserDataPreparer mUserDataPreparer; 364 /** 365 * Short-term lock for internal state, when interaction/sync with PM is not required. If using 366 * with {@link #mPackagesLock}, {@link #mPackagesLock} should be acquired first. 367 */ 368 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER); 369 private final Object mRestrictionsLock = new Object(); 370 // Used for serializing access to app restriction files 371 private final Object mAppRestrictionsLock = new Object(); 372 373 private final Handler mHandler; 374 375 private final ThreadPoolExecutor mInternalExecutor; 376 377 private final File mUsersDir; 378 private final File mUserListFile; 379 380 private final IBinder mUserRestrictionToken = new Binder(); 381 382 /** Installs system packages based on user-type. */ 383 private final UserSystemPackageInstaller mSystemPackageInstaller; 384 385 private PackageManagerInternal mPmInternal; 386 private DevicePolicyManagerInternal mDevicePolicyManagerInternal; 387 private ActivityManagerInternal mAmInternal; 388 389 /** Indicates that this is the 1st boot after the system user mode was changed by emulation. */ 390 private boolean mUpdatingSystemUserMode; 391 392 /** Count down latch to wait while boot user is not set.*/ 393 private final CountDownLatch mBootUserLatch = new CountDownLatch(1); 394 395 /** Current boot phase. */ 396 private @SystemService.BootPhase int mCurrentBootPhase; 397 398 /** 399 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps. 400 */ 401 @VisibleForTesting 402 static class UserData { 403 // Basic user information and properties 404 @NonNull UserInfo info; 405 // Account name used when there is a strong association between a user and an account 406 String account; 407 // Account information for seeding into a newly created user. This could also be 408 // used for login validation for an existing user, for updating their credentials. 409 // In the latter case, data may not need to be persisted as it is only valid for the 410 // current login session. 411 String seedAccountName; 412 String seedAccountType; 413 PersistableBundle seedAccountOptions; 414 // Whether to perist the seed account information to be available after a boot 415 boolean persistSeedData; 416 417 /** Properties of the user whose default values originate from its user type. */ 418 UserProperties userProperties; 419 420 /** Elapsed realtime since boot when the user started. */ 421 long startRealtime; 422 423 /** Elapsed realtime since boot when the user was unlocked. */ 424 long unlockRealtime; 425 426 /** Wall clock time in millis when the user last entered the foreground. */ 427 long mLastEnteredForegroundTimeMillis; 428 429 private long mLastRequestQuietModeEnabledMillis; 430 431 /** 432 * {@code true} if the system should ignore errors when preparing the 433 * storage directories for this user. This is {@code false} for all new 434 * users; it will only be {@code true} for users that already existed 435 * on-disk from an older version of Android. 436 */ 437 private boolean mIgnorePrepareStorageErrors; 438 setLastRequestQuietModeEnabledMillis(long millis)439 void setLastRequestQuietModeEnabledMillis(long millis) { 440 mLastRequestQuietModeEnabledMillis = millis; 441 } 442 getLastRequestQuietModeEnabledMillis()443 long getLastRequestQuietModeEnabledMillis() { 444 return mLastRequestQuietModeEnabledMillis; 445 } 446 getIgnorePrepareStorageErrors()447 boolean getIgnorePrepareStorageErrors() { 448 return mIgnorePrepareStorageErrors; 449 } 450 451 @SuppressWarnings("AndroidFrameworkCompatChange") // This is not an app-visible API. setIgnorePrepareStorageErrors()452 void setIgnorePrepareStorageErrors() { 453 // This method won't be called for new users. But to fully rule out 454 // the possibility of mIgnorePrepareStorageErrors ever being true 455 // for any user on any device that launched with T or later, we also 456 // explicitly check that DEVICE_INITIAL_SDK_INT is below T before 457 // honoring the request to set mIgnorePrepareStorageErrors to true. 458 if (Build.VERSION.DEVICE_INITIAL_SDK_INT < Build.VERSION_CODES.TIRAMISU) { 459 mIgnorePrepareStorageErrors = true; 460 return; 461 } 462 Slog.w(LOG_TAG, "Not setting mIgnorePrepareStorageErrors to true" 463 + " since this is a new device"); 464 } 465 clearSeedAccountData()466 void clearSeedAccountData() { 467 seedAccountName = null; 468 seedAccountType = null; 469 seedAccountOptions = null; 470 persistSeedData = false; 471 } 472 } 473 474 @GuardedBy("mUsersLock") 475 private final SparseArray<UserData> mUsers; 476 477 /** 478 * Map of user type names to their corresponding {@link UserTypeDetails}. 479 * Should not be modified after UserManagerService constructor finishes. 480 */ 481 private final ArrayMap<String, UserTypeDetails> mUserTypes; 482 483 /** 484 * User restrictions set via UserManager. This doesn't include restrictions set by 485 * device owner / profile owners. Only non-empty restriction bundles are stored. 486 * 487 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user, 488 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle} 489 * maybe shared between {@link #mBaseUserRestrictions} and 490 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately. 491 * (Otherwise we won't be able to detect what restrictions have changed in 492 * {@link #updateUserRestrictionsInternalLR}. 493 */ 494 @GuardedBy("mRestrictionsLock") 495 private final RestrictionsSet mBaseUserRestrictions = new RestrictionsSet(); 496 497 /** 498 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined 499 * with device / profile owner restrictions. We'll initialize it lazily; use 500 * {@link #getEffectiveUserRestrictions} to access it. 501 * 502 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user, 503 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle} 504 * maybe shared between {@link #mBaseUserRestrictions} and 505 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately. 506 * (Otherwise we won't be able to detect what restrictions have changed in 507 * {@link #updateUserRestrictionsInternalLR}. 508 */ 509 @GuardedBy("mRestrictionsLock") 510 private final RestrictionsSet mCachedEffectiveUserRestrictions = new RestrictionsSet(); 511 512 /** 513 * User restrictions that have already been applied in 514 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions 515 * that have changed since the last 516 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call. 517 */ 518 @GuardedBy("mRestrictionsLock") 519 private final RestrictionsSet mAppliedUserRestrictions = new RestrictionsSet(); 520 521 /** 522 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService} 523 * for each user. Restrictions that apply to all users (global) are represented by 524 * {@link com.android.os.UserHandle.USER_ALL}. 525 * The key is the user id of the user whom the restrictions are targeting. 526 */ 527 @GuardedBy("mRestrictionsLock") 528 private final RestrictionsSet mDevicePolicyUserRestrictions = new RestrictionsSet(); 529 530 @GuardedBy("mGuestRestrictions") 531 private final Bundle mGuestRestrictions = new Bundle(); 532 533 /** 534 * Set of user IDs that are being removed or were removed during the current boot. User IDs in 535 * this set aren't reused until the device is rebooted, unless MAX_USER_ID is reached. Some 536 * services don't fully clear out in-memory user state upon user removal; this behavior is 537 * intended to mitigate such issues by limiting user ID reuse. This array applies to any type 538 * of user (including pre-created users) when they are removed. Use {@link 539 * #addRemovingUserIdLocked(int)} to add elements to this array. 540 */ 541 @GuardedBy("mUsersLock") 542 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray(); 543 544 /** 545 * Queue of recently removed userIds. Used for recycling of userIds 546 */ 547 @GuardedBy("mUsersLock") 548 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>(); 549 550 @GuardedBy("mUsersLock") 551 private int[] mUserIds; 552 553 @GuardedBy("mUsersLock") 554 private int[] mUserIdsIncludingPreCreated; 555 556 @GuardedBy("mPackagesLock") 557 private int mNextSerialNumber; 558 private int mUserVersion = 0; 559 private int mUserTypeVersion = 0; 560 561 private IAppOpsService mAppOpsService; 562 563 private final LocalService mLocalService; 564 565 @GuardedBy("mUsersLock") 566 private boolean mIsDeviceManaged; 567 568 @GuardedBy("mUsersLock") 569 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray(); 570 571 @GuardedBy("mUserRestrictionsListeners") 572 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners = 573 new ArrayList<>(); 574 575 @GuardedBy("mUserLifecycleListeners") 576 private final ArrayList<UserLifecycleListener> mUserLifecycleListeners = new ArrayList<>(); 577 578 private final UserJourneyLogger mUserJourneyLogger = new UserJourneyLogger(); 579 580 private final LockPatternUtils mLockPatternUtils; 581 582 private KeyguardManager.KeyguardLockedStateListener mKeyguardLockedStateListener; 583 584 /** 585 * {@link android.app.AlarmManager.OnAlarmListener} to schedule an alarm to enable 586 * auto-locking private space after screen timeout 587 */ 588 private PrivateSpaceAutoLockTimer mPrivateSpaceAutoLockTimer; 589 590 /** Tag representing the alarm manager timer for auto-locking private space */ 591 private static final String PRIVATE_SPACE_AUTO_LOCK_TIMER_TAG = "PrivateSpaceAutoLockTimer"; 592 593 594 /** Content observer to get callbacks for privte space autolock settings changes */ 595 private final SettingsObserver mPrivateSpaceAutoLockSettingsObserver; 596 597 private final class SettingsObserver extends ContentObserver { SettingsObserver(Handler handler)598 SettingsObserver(Handler handler) { 599 super(handler); 600 } 601 602 @Override onChange(boolean selfChange, Uri uri)603 public void onChange(boolean selfChange, Uri uri) { 604 if (isAutoLockForPrivateSpaceEnabled()) { 605 final String path = uri.getLastPathSegment(); 606 if (TextUtils.equals(path, Settings.Secure.PRIVATE_SPACE_AUTO_LOCK)) { 607 int autoLockPreference = 608 Settings.Secure.getIntForUser(mContext.getContentResolver(), 609 Settings.Secure.PRIVATE_SPACE_AUTO_LOCK, 610 Settings.Secure.PRIVATE_SPACE_AUTO_LOCK_AFTER_DEVICE_RESTART, 611 getMainUserIdUnchecked()); 612 Slog.i(LOG_TAG, "Auto-lock settings changed to " + autoLockPreference); 613 setOrUpdateAutoLockPreferenceForPrivateProfile(autoLockPreference); 614 } 615 } 616 } 617 } 618 619 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK = 620 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK"; 621 622 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() { 623 @Override 624 public void onReceive(Context context, Intent intent) { 625 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) { 626 return; 627 } 628 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT, android.content.IntentSender.class); 629 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL); 630 final String callingPackage = intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME); 631 setQuietModeEnabledAsync(userId, false, target, callingPackage); 632 } 633 }; 634 635 /** Checks if the device inactivity broadcast receiver is already registered*/ 636 private boolean mIsDeviceInactivityBroadcastReceiverRegistered = false; 637 638 private final BroadcastReceiver mDeviceInactivityBroadcastReceiver = new BroadcastReceiver() { 639 @Override 640 public void onReceive(Context context, Intent intent) { 641 if (isAutoLockForPrivateSpaceEnabled()) { 642 if (ACTION_SCREEN_OFF.equals(intent.getAction())) { 643 maybeScheduleAlarmToAutoLockPrivateSpace(); 644 } else if (ACTION_SCREEN_ON.equals(intent.getAction())) { 645 Slog.d(LOG_TAG, "SCREEN_ON broadcast received, " 646 + "removing pending alarms to auto-lock private space"); 647 // Remove any pending alarm since the device is interactive again 648 cancelPendingAutoLockAlarms(); 649 } 650 } 651 } 652 }; 653 cancelPendingAutoLockAlarms()654 private void cancelPendingAutoLockAlarms() { 655 final AlarmManager alarmManager = mContext.getSystemService(AlarmManager.class); 656 if (alarmManager != null && mPrivateSpaceAutoLockTimer != null) { 657 alarmManager.cancel(mPrivateSpaceAutoLockTimer); 658 } 659 } 660 661 @VisibleForTesting maybeScheduleAlarmToAutoLockPrivateSpace()662 void maybeScheduleAlarmToAutoLockPrivateSpace() { 663 // No action needed if auto-lock on inactivity not selected 664 final int privateSpaceAutoLockPreference = 665 Settings.Secure.getIntForUser(mContext.getContentResolver(), 666 Settings.Secure.PRIVATE_SPACE_AUTO_LOCK, 667 Settings.Secure.PRIVATE_SPACE_AUTO_LOCK_AFTER_DEVICE_RESTART, 668 getMainUserIdUnchecked()); 669 if (privateSpaceAutoLockPreference 670 != Settings.Secure.PRIVATE_SPACE_AUTO_LOCK_AFTER_INACTIVITY) { 671 Slogf.d(LOG_TAG, "Not scheduling auto-lock on inactivity," 672 + "preference is set to %d", privateSpaceAutoLockPreference); 673 return; 674 } 675 int privateProfileUserId = getPrivateProfileUserId(); 676 if (privateProfileUserId != UserHandle.USER_NULL) { 677 if (isQuietModeEnabled(privateProfileUserId)) { 678 Slogf.d(LOG_TAG, "Not scheduling auto-lock alarm for %d, " 679 + "quiet mode already enabled", privateProfileUserId); 680 return; 681 } 682 scheduleAlarmToAutoLockPrivateSpace(privateProfileUserId, 683 PRIVATE_SPACE_AUTO_LOCK_INACTIVITY_TIMEOUT_MS); 684 } 685 } 686 687 @VisibleForTesting scheduleAlarmToAutoLockPrivateSpace(int userId, long delayInMillis)688 void scheduleAlarmToAutoLockPrivateSpace(int userId, long delayInMillis) { 689 final AlarmManager alarmManager = mContext.getSystemService(AlarmManager.class); 690 if (alarmManager == null) { 691 Slog.e(LOG_TAG, "AlarmManager not available, cannot schedule auto-lock alarm"); 692 return; 693 } 694 initPrivateSpaceAutoLockTimer(userId); 695 final long alarmWindowStartTime = SystemClock.elapsedRealtime() + delayInMillis; 696 alarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP, 697 alarmWindowStartTime, 698 PRIVATE_SPACE_AUTO_LOCK_INACTIVITY_ALARM_WINDOW_MS, 699 PRIVATE_SPACE_AUTO_LOCK_TIMER_TAG, 700 new HandlerExecutor(mHandler), 701 mPrivateSpaceAutoLockTimer); 702 } 703 initPrivateSpaceAutoLockTimer(int userId)704 private void initPrivateSpaceAutoLockTimer(int userId) { 705 cancelPendingAutoLockAlarms(); 706 if (mPrivateSpaceAutoLockTimer == null 707 || mPrivateSpaceAutoLockTimer.getUserId() != userId) { 708 mPrivateSpaceAutoLockTimer = new PrivateSpaceAutoLockTimer(userId); 709 } 710 } 711 712 private class PrivateSpaceAutoLockTimer implements AlarmManager.OnAlarmListener { 713 714 private final int mUserId; 715 PrivateSpaceAutoLockTimer(int userId)716 PrivateSpaceAutoLockTimer(int userId) { 717 mUserId = userId; 718 } 719 getUserId()720 int getUserId() { 721 return mUserId; 722 } 723 724 @Override onAlarm()725 public void onAlarm() { 726 final PowerManager powerManager = mContext.getSystemService(PowerManager.class); 727 if (powerManager != null && !powerManager.isInteractive()) { 728 Slog.i(LOG_TAG, "Auto-locking private space with user-id " + mUserId); 729 setQuietModeEnabledAsync(mUserId, true, 730 /* target */ null, mContext.getPackageName()); 731 } else { 732 Slog.i(LOG_TAG, "Device is interactive, skipping auto-lock for profile user " 733 + mUserId); 734 } 735 } 736 } 737 738 @RequiresPermission(Manifest.permission.SUBSCRIBE_TO_KEYGUARD_LOCKED_STATE) initializeAndRegisterKeyguardLockedStateListener()739 private void initializeAndRegisterKeyguardLockedStateListener() { 740 mKeyguardLockedStateListener = this::tryAutoLockingPrivateSpaceOnKeyguardChanged; 741 // Register with keyguard to send locked state events to the listener initialized above 742 try { 743 final KeyguardManager keyguardManager = 744 mContext.getSystemService(KeyguardManager.class); 745 Slog.i(LOG_TAG, "Adding keyguard locked state listener"); 746 keyguardManager.addKeyguardLockedStateListener(new HandlerExecutor(mHandler), 747 mKeyguardLockedStateListener); 748 } catch (Exception e) { 749 Slog.e(LOG_TAG, "Error adding keyguard locked listener ", e); 750 } 751 } 752 753 @VisibleForTesting 754 @RequiresPermission(Manifest.permission.SUBSCRIBE_TO_KEYGUARD_LOCKED_STATE) setOrUpdateAutoLockPreferenceForPrivateProfile( @ettings.Secure.PrivateSpaceAutoLockOption int autoLockPreference)755 void setOrUpdateAutoLockPreferenceForPrivateProfile( 756 @Settings.Secure.PrivateSpaceAutoLockOption int autoLockPreference) { 757 int privateProfileUserId = getPrivateProfileUserId(); 758 if (privateProfileUserId == UserHandle.USER_NULL) { 759 Slog.e(LOG_TAG, "Auto-lock preference updated but private space user not found"); 760 return; 761 } 762 763 if (autoLockPreference == Settings.Secure.PRIVATE_SPACE_AUTO_LOCK_AFTER_INACTIVITY) { 764 // Register inactivity broadcast 765 if (!mIsDeviceInactivityBroadcastReceiverRegistered) { 766 Slog.i(LOG_TAG, "Registering device inactivity broadcast receivers"); 767 mContext.registerReceiver(mDeviceInactivityBroadcastReceiver, 768 new IntentFilter(ACTION_SCREEN_OFF), 769 null, mHandler); 770 771 mContext.registerReceiver(mDeviceInactivityBroadcastReceiver, 772 new IntentFilter(ACTION_SCREEN_ON), 773 null, mHandler); 774 775 mIsDeviceInactivityBroadcastReceiverRegistered = true; 776 } 777 } else { 778 // Unregister device inactivity broadcasts 779 if (mIsDeviceInactivityBroadcastReceiverRegistered) { 780 Slog.i(LOG_TAG, "Removing device inactivity broadcast receivers"); 781 cancelPendingAutoLockAlarms(); 782 mContext.unregisterReceiver(mDeviceInactivityBroadcastReceiver); 783 mIsDeviceInactivityBroadcastReceiverRegistered = false; 784 } 785 } 786 787 if (autoLockPreference == Settings.Secure.PRIVATE_SPACE_AUTO_LOCK_ON_DEVICE_LOCK) { 788 // Initialize and add keyguard state listener 789 initializeAndRegisterKeyguardLockedStateListener(); 790 } else { 791 // Remove keyguard state listener 792 try { 793 final KeyguardManager keyguardManager = 794 mContext.getSystemService(KeyguardManager.class); 795 Slog.i(LOG_TAG, "Removing keyguard locked state listener"); 796 keyguardManager.removeKeyguardLockedStateListener(mKeyguardLockedStateListener); 797 } catch (Exception e) { 798 Slog.e(LOG_TAG, "Error adding keyguard locked state listener ", e); 799 } 800 } 801 } 802 803 @VisibleForTesting tryAutoLockingPrivateSpaceOnKeyguardChanged(boolean isKeyguardLocked)804 void tryAutoLockingPrivateSpaceOnKeyguardChanged(boolean isKeyguardLocked) { 805 if (isAutoLockForPrivateSpaceEnabled()) { 806 int autoLockPreference = Settings.Secure.getIntForUser(mContext.getContentResolver(), 807 Settings.Secure.PRIVATE_SPACE_AUTO_LOCK, 808 Settings.Secure.PRIVATE_SPACE_AUTO_LOCK_AFTER_DEVICE_RESTART, 809 getMainUserIdUnchecked()); 810 boolean isAutoLockOnDeviceLockSelected = 811 autoLockPreference == Settings.Secure.PRIVATE_SPACE_AUTO_LOCK_ON_DEVICE_LOCK; 812 if (isKeyguardLocked && isAutoLockOnDeviceLockSelected) { 813 autoLockPrivateSpace(); 814 } 815 } 816 } 817 818 @VisibleForTesting autoLockPrivateSpace()819 void autoLockPrivateSpace() { 820 int privateProfileUserId = getPrivateProfileUserId(); 821 if (privateProfileUserId != UserHandle.USER_NULL) { 822 Slog.i(LOG_TAG, "Auto-locking private space with user-id " 823 + privateProfileUserId); 824 setQuietModeEnabledAsync(privateProfileUserId, 825 /* enableQuietMode */true, /* target */ null, 826 mContext.getPackageName()); 827 } 828 } 829 830 @VisibleForTesting setQuietModeEnabledAsync(@serIdInt int userId, boolean enableQuietMode, IntentSender target, @Nullable String callingPackage)831 void setQuietModeEnabledAsync(@UserIdInt int userId, boolean enableQuietMode, 832 IntentSender target, @Nullable String callingPackage) { 833 if (android.multiuser.Flags.moveQuietModeOperationsToSeparateThread()) { 834 // Call setQuietModeEnabled on a separate thread. Calling this operation on the main 835 // thread can cause ANRs, posting on a BackgroundThread can result in delays 836 Slog.d(LOG_TAG, "Calling setQuietModeEnabled for user " + userId 837 + " on a separate thread"); 838 mInternalExecutor.execute(() -> setQuietModeEnabled(userId, enableQuietMode, target, 839 callingPackage)); 840 } else { 841 // Call setQuietModeEnabled on bg thread to avoid ANR 842 BackgroundThread.getHandler().post( 843 () -> setQuietModeEnabled(userId, enableQuietMode, target, 844 callingPackage) 845 ); 846 } 847 } 848 849 /** 850 * Cache the owner name string, since it could be read repeatedly on a critical code path 851 * but hit by slow IO. This could be eliminated once we have the cached UserInfo in place. 852 */ 853 private final AtomicReference<String> mOwnerName = new AtomicReference<>(); 854 855 private final TypedValue mOwnerNameTypedValue = new TypedValue(); 856 857 private final Configuration mLastConfiguration = new Configuration(); 858 859 private final BroadcastReceiver mConfigurationChangeReceiver = new BroadcastReceiver() { 860 @Override 861 public void onReceive(Context context, Intent intent) { 862 if (!Intent.ACTION_CONFIGURATION_CHANGED.equals(intent.getAction())) { 863 return; 864 } 865 invalidateOwnerNameIfNecessary(context.getResources(), false /* forceUpdate */); 866 } 867 }; 868 869 // TODO(b/161915546): remove once userWithName() is fixed / removed 870 // Use to debug / dump when user 0 is allocated at userWithName() 871 public static final boolean DBG_ALLOCATION = false; // DO NOT SUBMIT WITH TRUE 872 public final AtomicInteger mUser0Allocations; 873 874 /** 875 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode. 876 * 877 * @see #requestQuietModeEnabled(String, boolean, int, IntentSender, int) 878 */ 879 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub { 880 private final IntentSender mTarget; 881 DisableQuietModeUserUnlockedCallback(IntentSender target)882 public DisableQuietModeUserUnlockedCallback(IntentSender target) { 883 Objects.requireNonNull(target); 884 mTarget = target; 885 } 886 887 @Override onStarted(int id, Bundle extras)888 public void onStarted(int id, Bundle extras) {} 889 890 @Override onProgress(int id, int progress, Bundle extras)891 public void onProgress(int id, int progress, Bundle extras) {} 892 893 @Override onFinished(int id, Bundle extras)894 public void onFinished(int id, Bundle extras) { 895 mHandler.post(() -> { 896 try { 897 ActivityOptions activityOptions = 898 ActivityOptions.makeBasic().setPendingIntentBackgroundActivityStartMode( 899 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED); 900 mContext.startIntentSender(mTarget, null, 0, 0, 0, activityOptions.toBundle()); 901 } catch (IntentSender.SendIntentException e) { 902 Slog.e(LOG_TAG, "Failed to start the target in the callback", e); 903 } 904 }); 905 } 906 } 907 908 /** 909 * Whether all users should be created ephemeral. 910 */ 911 @GuardedBy("mUsersLock") 912 private boolean mForceEphemeralUsers; 913 914 /** 915 * The member mUserStates affects the return value of isUserUnlocked. 916 * If any value in mUserStates changes, then the binder cache for 917 * isUserUnlocked must be invalidated. When adding mutating methods to 918 * WatchedUserStates, be sure to invalidate the cache in the new 919 * methods. 920 */ 921 private class WatchedUserStates { 922 final SparseIntArray states; WatchedUserStates()923 public WatchedUserStates() { 924 states = new SparseIntArray(); 925 invalidateIsUserUnlockedCache(); 926 } get(@serIdInt int userId)927 public int get(@UserIdInt int userId) { 928 return states.get(userId); 929 } get(@serIdInt int userId, int fallback)930 public int get(@UserIdInt int userId, int fallback) { 931 return states.indexOfKey(userId) >= 0 ? states.get(userId) : fallback; 932 } put(@serIdInt int userId, int state)933 public void put(@UserIdInt int userId, int state) { 934 states.put(userId, state); 935 invalidateIsUserUnlockedCache(); 936 } delete(@serIdInt int userId)937 public void delete(@UserIdInt int userId) { 938 states.delete(userId); 939 invalidateIsUserUnlockedCache(); 940 } has(@serIdInt int userId)941 public boolean has(@UserIdInt int userId) { 942 return states.get(userId, UserHandle.USER_NULL) != UserHandle.USER_NULL; 943 } 944 @Override toString()945 public String toString() { 946 return states.toString(); 947 } invalidateIsUserUnlockedCache()948 private void invalidateIsUserUnlockedCache() { 949 UserManager.invalidateIsUserUnlockedCache(); 950 } 951 } 952 @GuardedBy("mUserStates") 953 private final WatchedUserStates mUserStates = new WatchedUserStates(); 954 955 private final UserVisibilityMediator mUserVisibilityMediator; 956 957 @GuardedBy("mUsersLock") 958 private @CanBeNULL @UserIdInt int mBootUser = UserHandle.USER_NULL; 959 960 private static UserManagerService sInstance; 961 getInstance()962 public static UserManagerService getInstance() { 963 synchronized (UserManagerService.class) { 964 return sInstance; 965 } 966 } 967 968 public static class LifeCycle extends SystemService { 969 970 private UserManagerService mUms; 971 972 /** 973 * @param context 974 */ LifeCycle(Context context)975 public LifeCycle(Context context) { 976 super(context); 977 } 978 979 @Override onStart()980 public void onStart() { 981 mUms = UserManagerService.getInstance(); 982 publishBinderService(Context.USER_SERVICE, mUms); 983 } 984 985 @Override onBootPhase(int phase)986 public void onBootPhase(int phase) { 987 mUms.mCurrentBootPhase = phase; 988 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) { 989 mUms.cleanupPartialUsers(); 990 991 if (mUms.mPm.isDeviceUpgrading()) { 992 mUms.cleanupPreCreatedUsers(); 993 } 994 995 mUms.registerStatsCallbacks(); 996 } 997 } 998 999 @Override onUserStarting(@onNull TargetUser targetUser)1000 public void onUserStarting(@NonNull TargetUser targetUser) { 1001 synchronized (mUms.mUsersLock) { 1002 final UserData user = mUms.getUserDataLU(targetUser.getUserIdentifier()); 1003 if (user != null) { 1004 user.startRealtime = SystemClock.elapsedRealtime(); 1005 if (targetUser.getUserIdentifier() == UserHandle.USER_SYSTEM 1006 && targetUser.isFull()) { 1007 mUms.setLastEnteredForegroundTimeToNow(user); 1008 } 1009 } 1010 } 1011 } 1012 1013 @Override onUserUnlocking(@onNull TargetUser targetUser)1014 public void onUserUnlocking(@NonNull TargetUser targetUser) { 1015 synchronized (mUms.mUsersLock) { 1016 final UserData user = mUms.getUserDataLU(targetUser.getUserIdentifier()); 1017 if (user != null) { 1018 user.unlockRealtime = SystemClock.elapsedRealtime(); 1019 } 1020 } 1021 if (targetUser.getUserIdentifier() == UserHandle.USER_SYSTEM 1022 && UserManager.isCommunalProfileEnabled()) { 1023 mUms.startCommunalProfile(); 1024 } 1025 } 1026 1027 @Override onUserSwitching(@onNull TargetUser from, @NonNull TargetUser to)1028 public void onUserSwitching(@NonNull TargetUser from, @NonNull TargetUser to) { 1029 synchronized (mUms.mUsersLock) { 1030 final UserData user = mUms.getUserDataLU(to.getUserIdentifier()); 1031 if (user != null) { 1032 mUms.setLastEnteredForegroundTimeToNow(user); 1033 } 1034 } 1035 } 1036 1037 @Override onUserStopping(@onNull TargetUser targetUser)1038 public void onUserStopping(@NonNull TargetUser targetUser) { 1039 synchronized (mUms.mUsersLock) { 1040 final UserData user = mUms.getUserDataLU(targetUser.getUserIdentifier()); 1041 if (user != null) { 1042 user.startRealtime = 0; 1043 user.unlockRealtime = 0; 1044 } 1045 } 1046 } 1047 } 1048 1049 // TODO(b/28848102) Add support for test dependencies injection 1050 @VisibleForTesting UserManagerService(Context context)1051 UserManagerService(Context context) { 1052 this(context, /* pm= */ null, /* userDataPreparer= */ null, 1053 /* packagesLock= */ new Object(), context.getCacheDir(), /* users= */ null); 1054 } 1055 1056 /** 1057 * Called by package manager to create the service. This is closely 1058 * associated with the package manager, and the given lock is the 1059 * package manager's own lock. 1060 */ UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer, Object packagesLock)1061 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer, 1062 Object packagesLock) { 1063 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory(), 1064 /* users= */ null); 1065 } 1066 1067 @VisibleForTesting UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer, Object packagesLock, File dataDir, SparseArray<UserData> users)1068 UserManagerService(Context context, PackageManagerService pm, 1069 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir, 1070 SparseArray<UserData> users) { 1071 mContext = context; 1072 mPm = pm; 1073 mPackagesLock = packagesLock; 1074 mUsers = users != null ? users : new SparseArray<>(); 1075 mHandler = new MainHandler(); 1076 mInternalExecutor = new ThreadPoolExecutor(/* corePoolSize */ 0, /* maximumPoolSize */ 1, 1077 /* keepAliveTime */ 24, TimeUnit.HOURS, new LinkedBlockingQueue<>()); 1078 mUserVisibilityMediator = new UserVisibilityMediator(mHandler); 1079 mUserDataPreparer = userDataPreparer; 1080 mUserTypes = UserTypeFactory.getUserTypes(); 1081 invalidateOwnerNameIfNecessary(getContextResources(), true /* forceUpdate */); 1082 synchronized (mPackagesLock) { 1083 mUsersDir = new File(dataDir, USER_INFO_DIR); 1084 mUsersDir.mkdirs(); 1085 // Make zeroth user directory, for services to migrate their files to that location 1086 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM)); 1087 userZeroDir.mkdirs(); 1088 FileUtils.setPermissions(mUsersDir.toString(), 1089 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH, 1090 -1, -1); 1091 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME); 1092 initDefaultGuestRestrictions(); 1093 readUserListLP(); 1094 sInstance = this; 1095 } 1096 mSystemPackageInstaller = new UserSystemPackageInstaller(this, mUserTypes); 1097 mLocalService = new LocalService(); 1098 LocalServices.addService(UserManagerInternal.class, mLocalService); 1099 mLockPatternUtils = new LockPatternUtils(mContext); 1100 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING); 1101 mUser0Allocations = DBG_ALLOCATION ? new AtomicInteger() : null; 1102 mPrivateSpaceAutoLockSettingsObserver = new SettingsObserver(mHandler); 1103 emulateSystemUserModeIfNeeded(); 1104 initPropertyInvalidatedCaches(); 1105 } 1106 1107 /** 1108 * This method is used to invalidate the caches at server statup, 1109 * so that caches can start working. 1110 */ initPropertyInvalidatedCaches()1111 private static final void initPropertyInvalidatedCaches() { 1112 if (android.multiuser.Flags.cachesNotInvalidatedAtStartReadOnly()) { 1113 UserManager.invalidateIsUserUnlockedCache(); 1114 UserManager.invalidateQuietModeEnabledCache(); 1115 if (android.multiuser.Flags.cacheUserPropertiesCorrectlyReadOnly()) { 1116 UserManager.invalidateStaticUserProperties(); 1117 UserManager.invalidateUserPropertiesCache(); 1118 } 1119 UserManager.invalidateCacheOnUserListChange(); 1120 UserManager.invalidateUserRestriction(); 1121 } 1122 } 1123 systemReady()1124 void systemReady() { 1125 mAppOpsService = IAppOpsService.Stub.asInterface( 1126 ServiceManager.getService(Context.APP_OPS_SERVICE)); 1127 1128 synchronized (mRestrictionsLock) { 1129 applyUserRestrictionsLR(UserHandle.USER_SYSTEM); 1130 } 1131 1132 mContext.registerReceiver(mDisableQuietModeCallback, 1133 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK), 1134 null, mHandler); 1135 1136 mContext.registerReceiver(mConfigurationChangeReceiver, 1137 new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED), 1138 null, mHandler); 1139 1140 if (isAutoLockForPrivateSpaceEnabled()) { 1141 1142 int mainUserId = getMainUserIdUnchecked(); 1143 if (mainUserId != UserHandle.USER_NULL) { 1144 mContext.getContentResolver().registerContentObserverAsUser( 1145 Settings.Secure.getUriFor( 1146 Settings.Secure.PRIVATE_SPACE_AUTO_LOCK), false, 1147 mPrivateSpaceAutoLockSettingsObserver, UserHandle.of(mainUserId)); 1148 1149 setOrUpdateAutoLockPreferenceForPrivateProfile( 1150 Settings.Secure.getIntForUser(mContext.getContentResolver(), 1151 Settings.Secure.PRIVATE_SPACE_AUTO_LOCK, 1152 Settings.Secure.PRIVATE_SPACE_AUTO_LOCK_AFTER_DEVICE_RESTART, 1153 mainUserId)); 1154 } 1155 } 1156 1157 if (isAutoLockingPrivateSpaceOnRestartsEnabled()) { 1158 autoLockPrivateSpace(); 1159 } 1160 1161 showHsumNotificationIfNeeded(); 1162 1163 if (UserManagerInternal.shouldShowNotificationForBackgroundUserSounds()) { 1164 new BackgroundUserSoundNotifier(mContext); 1165 } 1166 } 1167 doesDeviceHardwareSupportPrivateSpace()1168 private boolean doesDeviceHardwareSupportPrivateSpace() { 1169 return !mPm.hasSystemFeature(FEATURE_EMBEDDED, 0) 1170 && !mPm.hasSystemFeature(FEATURE_WATCH, 0) 1171 && !mPm.hasSystemFeature(FEATURE_LEANBACK, 0) 1172 && !mPm.hasSystemFeature(FEATURE_AUTOMOTIVE, 0); 1173 } 1174 isAutoLockForPrivateSpaceEnabled()1175 private static boolean isAutoLockForPrivateSpaceEnabled() { 1176 return android.os.Flags.allowPrivateProfile() 1177 && Flags.supportAutolockForPrivateSpace() 1178 && android.multiuser.Flags.enablePrivateSpaceFeatures(); 1179 } 1180 isAutoLockingPrivateSpaceOnRestartsEnabled()1181 private boolean isAutoLockingPrivateSpaceOnRestartsEnabled() { 1182 return android.os.Flags.allowPrivateProfile() 1183 && android.multiuser.Flags.enablePrivateSpaceAutolockOnRestarts() 1184 && android.multiuser.Flags.enablePrivateSpaceFeatures(); 1185 } 1186 getSystemResources()1187 private Resources getSystemResources() { 1188 return android.multiuser.Flags.useUnifiedResources() 1189 ? getContextResources() : Resources.getSystem(); 1190 } 1191 getContextResources()1192 private Resources getContextResources() { 1193 return mContext.getResources(); 1194 } 1195 1196 /** 1197 * This method retrieves the {@link UserManagerInternal} only for the purpose of 1198 * PackageManagerService construction. 1199 */ getInternalForInjectorOnly()1200 UserManagerInternal getInternalForInjectorOnly() { 1201 return mLocalService; 1202 } 1203 startCommunalProfile()1204 private void startCommunalProfile() { 1205 final int communalProfileId = getCommunalProfileIdUnchecked(); 1206 if (communalProfileId != UserHandle.USER_NULL) { 1207 Slogf.d(LOG_TAG, "Starting the Communal Profile"); 1208 boolean started = false; 1209 try { 1210 started = ActivityManager.getService().startProfile(communalProfileId); 1211 } catch (RemoteException e) { 1212 // Should not happen - same process 1213 e.rethrowAsRuntimeException(); 1214 } 1215 if (!started) { 1216 Slogf.wtf(LOG_TAG, 1217 "Failed to start communal profile userId=%d", communalProfileId); 1218 } 1219 } else { 1220 Slogf.w(LOG_TAG, "Cannot start Communal Profile because there isn't one"); 1221 } 1222 } 1223 1224 /** Marks the user as slated for deletion during boot if necessary. **/ 1225 @GuardedBy("mUsersLock") markUserForRemovalIfNecessaryLU(UserInfo ui)1226 private void markUserForRemovalIfNecessaryLU(UserInfo ui) { 1227 if (!ui.isEphemeral()) { 1228 // User should be ephemeral to be marked for removal. 1229 return; 1230 } 1231 if (ui.preCreated) { 1232 // Avoid marking pre-created users for removal. 1233 return; 1234 } 1235 if (ui.lastLoggedInTime == 0 && ui.isGuest() && getSystemResources().getBoolean( 1236 com.android.internal.R.bool.config_guestUserAutoCreated)) { 1237 // Avoid marking auto-created but not-yet-logged-in guest user for removal. Because a 1238 // new one will be created anyway, and this one doesn't have any personal data in it yet 1239 // due to not being logged in. 1240 return; 1241 } 1242 // Mark the user for removal. 1243 addRemovingUserIdLocked(ui.id); 1244 ui.partial = true; 1245 addUserInfoFlags(ui, UserInfo.FLAG_DISABLED); 1246 } 1247 1248 /* Prunes out any partially created or partially removed users. */ cleanupPartialUsers()1249 private void cleanupPartialUsers() { 1250 ArrayList<UserInfo> partials = new ArrayList<>(); 1251 synchronized (mUsersLock) { 1252 final int userSize = mUsers.size(); 1253 for (int i = 0; i < userSize; i++) { 1254 UserInfo ui = mUsers.valueAt(i).info; 1255 if ((ui.partial || ui.guestToRemove) && ui.id != UserHandle.USER_SYSTEM) { 1256 partials.add(ui); 1257 if (!mRemovingUserIds.get(ui.id)) { 1258 addRemovingUserIdLocked(ui.id); 1259 } 1260 ui.partial = true; 1261 } 1262 } 1263 } 1264 final int partialsSize = partials.size(); 1265 for (int i = 0; i < partialsSize; i++) { 1266 UserInfo ui = partials.get(i); 1267 Slog.w(LOG_TAG, "Removing partially created user " + ui.id 1268 + " (name=" + ui.name + ")"); 1269 removeUserState(ui.id); 1270 } 1271 } 1272 1273 /** 1274 * Removes any pre-created users from the system. Should be invoked after OTAs, to ensure 1275 * pre-created users are not stale. New pre-created pool can be re-created after the update. 1276 */ cleanupPreCreatedUsers()1277 private void cleanupPreCreatedUsers() { 1278 final ArrayList<UserInfo> preCreatedUsers; 1279 synchronized (mUsersLock) { 1280 final int userSize = mUsers.size(); 1281 preCreatedUsers = new ArrayList<>(userSize); 1282 for (int i = 0; i < userSize; i++) { 1283 UserInfo ui = mUsers.valueAt(i).info; 1284 if (ui.preCreated) { 1285 preCreatedUsers.add(ui); 1286 addRemovingUserIdLocked(ui.id); 1287 addUserInfoFlags(ui, UserInfo.FLAG_DISABLED); 1288 ui.partial = true; 1289 } 1290 } 1291 } 1292 final int preCreatedSize = preCreatedUsers.size(); 1293 for (int i = 0; i < preCreatedSize; i++) { 1294 UserInfo ui = preCreatedUsers.get(i); 1295 Slog.i(LOG_TAG, "Removing pre-created user " + ui.id); 1296 removeUserState(ui.id); 1297 } 1298 } 1299 1300 @Override getUserAccount(@serIdInt int userId)1301 public String getUserAccount(@UserIdInt int userId) { 1302 checkManageUserAndAcrossUsersFullPermission("get user account"); 1303 synchronized (mUsersLock) { 1304 return mUsers.get(userId).account; 1305 } 1306 } 1307 1308 @Override setUserAccount(@serIdInt int userId, String accountName)1309 public void setUserAccount(@UserIdInt int userId, String accountName) { 1310 checkManageUserAndAcrossUsersFullPermission("set user account"); 1311 UserData userToUpdate = null; 1312 synchronized (mPackagesLock) { 1313 synchronized (mUsersLock) { 1314 final UserData userData = mUsers.get(userId); 1315 if (userData == null) { 1316 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId); 1317 return; 1318 } 1319 String currentAccount = userData.account; 1320 if (!Objects.equals(currentAccount, accountName)) { 1321 userData.account = accountName; 1322 userToUpdate = userData; 1323 } 1324 } 1325 1326 if (userToUpdate != null) { 1327 writeUserLP(userToUpdate); 1328 } 1329 } 1330 } 1331 1332 @Override getPrimaryUser()1333 public UserInfo getPrimaryUser() { 1334 checkManageUsersPermission("query users"); 1335 synchronized (mUsersLock) { 1336 final int userSize = mUsers.size(); 1337 for (int i = 0; i < userSize; i++) { 1338 UserInfo ui = mUsers.valueAt(i).info; 1339 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) { 1340 return ui; 1341 } 1342 } 1343 } 1344 return null; 1345 } 1346 1347 @Override getMainUserId()1348 public @CanBeNULL @UserIdInt int getMainUserId() { 1349 checkQueryOrCreateUsersPermission("get main user id"); 1350 return getMainUserIdUnchecked(); 1351 } 1352 getMainUserIdUnchecked()1353 private @CanBeNULL @UserIdInt int getMainUserIdUnchecked() { 1354 synchronized (mUsersLock) { 1355 final int userSize = mUsers.size(); 1356 for (int i = 0; i < userSize; i++) { 1357 final UserInfo user = mUsers.valueAt(i).info; 1358 if (user.isMain() && !mRemovingUserIds.get(user.id)) { 1359 return user.id; 1360 } 1361 } 1362 } 1363 return UserHandle.USER_NULL; 1364 } 1365 getPrivateProfileUserId()1366 private @CanBeNULL @UserIdInt int getPrivateProfileUserId() { 1367 synchronized (mUsersLock) { 1368 for (int userId : getUserIds()) { 1369 UserInfo userInfo = getUserInfoLU(userId); 1370 if (userInfo != null && userInfo.isPrivateProfile()) { 1371 return userInfo.id; 1372 } 1373 } 1374 } 1375 return UserHandle.USER_NULL; 1376 } 1377 1378 @Override setBootUser(@serIdInt int userId)1379 public void setBootUser(@UserIdInt int userId) { 1380 checkCreateUsersPermission("Set boot user"); 1381 synchronized (mUsersLock) { 1382 // TODO(b/263381643): Change to EventLog. 1383 Slogf.i(LOG_TAG, "setBootUser %d", userId); 1384 mBootUser = userId; 1385 } 1386 mBootUserLatch.countDown(); 1387 } 1388 1389 @Override getBootUser()1390 public @UserIdInt int getBootUser() { 1391 checkCreateUsersPermission("Get boot user"); 1392 try { 1393 return getBootUserUnchecked(); 1394 } catch (UserManager.CheckedUserOperationException e) { 1395 throw e.toServiceSpecificException(); 1396 } 1397 } 1398 getBootUserUnchecked()1399 private @UserIdInt int getBootUserUnchecked() throws UserManager.CheckedUserOperationException { 1400 synchronized (mUsersLock) { 1401 if (mBootUser != UserHandle.USER_NULL) { 1402 final UserData userData = mUsers.get(mBootUser); 1403 if (userData != null && userData.info.supportsSwitchToByUser()) { 1404 Slogf.i(LOG_TAG, "Using provided boot user: %d", mBootUser); 1405 return mBootUser; 1406 } else { 1407 Slogf.w(LOG_TAG, 1408 "Provided boot user cannot be switched to: %d", mBootUser); 1409 } 1410 } 1411 } 1412 1413 if (isHeadlessSystemUserMode()) { 1414 final int bootStrategy = getContextResources() 1415 .getInteger(com.android.internal.R.integer.config_hsumBootStrategy); 1416 switch (bootStrategy) { 1417 case BOOT_TO_PREVIOUS_OR_FIRST_SWITCHABLE_USER: 1418 return getPreviousOrFirstSwitchableUser(); 1419 case BOOT_TO_HSU_FOR_PROVISIONED_DEVICE: 1420 return getBootUserBasedOnProvisioning(); 1421 default: 1422 Slogf.w(LOG_TAG, "Unknown HSUM boot strategy: %d", bootStrategy); 1423 return getPreviousOrFirstSwitchableUser(); 1424 } 1425 } 1426 // Not HSUM, return system user. 1427 return UserHandle.USER_SYSTEM; 1428 } 1429 getBootUserBasedOnProvisioning()1430 private @UserIdInt int getBootUserBasedOnProvisioning() 1431 throws UserManager.CheckedUserOperationException { 1432 final boolean provisioned = Settings.Global.getInt(mContext.getContentResolver(), 1433 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 1434 if (provisioned) { 1435 return UserHandle.USER_SYSTEM; 1436 } else { 1437 final int firstSwitchableFullUser = getFirstSwitchableUser(true); 1438 if (firstSwitchableFullUser != UserHandle.USER_NULL) { 1439 Slogf.i(LOG_TAG, 1440 "Boot user is first switchable full user %d", 1441 firstSwitchableFullUser); 1442 return firstSwitchableFullUser; 1443 } 1444 // No switchable full user found. Uh oh! 1445 throw new UserManager.CheckedUserOperationException( 1446 "No switchable full user found", USER_OPERATION_ERROR_UNKNOWN); 1447 } 1448 } 1449 getPreviousOrFirstSwitchableUser()1450 private @UserIdInt int getPreviousOrFirstSwitchableUser() 1451 throws UserManager.CheckedUserOperationException { 1452 // Return the previous foreground user, if there is one. 1453 final int previousUser = getPreviousFullUserToEnterForeground(); 1454 if (previousUser != UserHandle.USER_NULL) { 1455 Slogf.i(LOG_TAG, "Boot user is previous user %d", previousUser); 1456 return previousUser; 1457 } 1458 // No previous user. Return the first switchable user if there is one. 1459 final int firstSwitchableUser = getFirstSwitchableUser(false); 1460 if (firstSwitchableUser != UserHandle.USER_NULL) { 1461 Slogf.i(LOG_TAG, 1462 "Boot user is first switchable user %d", firstSwitchableUser); 1463 return firstSwitchableUser; 1464 } 1465 // No switchable users found. Uh oh! 1466 throw new UserManager.CheckedUserOperationException( 1467 "No switchable users found", USER_OPERATION_ERROR_UNKNOWN); 1468 } 1469 getFirstSwitchableUser(boolean fullUserOnly)1470 private @CanBeNULL @UserIdInt int getFirstSwitchableUser(boolean fullUserOnly) { 1471 synchronized (mUsersLock) { 1472 final int userSize = mUsers.size(); 1473 for (int i = 0; i < userSize; i++) { 1474 final UserData userData = mUsers.valueAt(i); 1475 if (userData.info.supportsSwitchToByUser() && 1476 (!fullUserOnly || userData.info.isFull())) { 1477 int firstSwitchable = userData.info.id; 1478 return firstSwitchable; 1479 } 1480 } 1481 } 1482 return UserHandle.USER_NULL; 1483 } 1484 1485 @Override getPreviousFullUserToEnterForeground()1486 public @CanBeNULL @UserIdInt int getPreviousFullUserToEnterForeground() { 1487 checkQueryOrCreateUsersPermission("get previous user"); 1488 return getPreviousFullUserToEnterForegroundUnchecked(); 1489 } 1490 getPreviousFullUserToEnterForegroundUnchecked()1491 private int getPreviousFullUserToEnterForegroundUnchecked() { 1492 int previousUser = UserHandle.USER_NULL; 1493 long latestEnteredTime = 0; 1494 final int currentUser = getCurrentUserId(); 1495 synchronized (mUsersLock) { 1496 final int userSize = mUsers.size(); 1497 for (int i = 0; i < userSize; i++) { 1498 final UserData userData = mUsers.valueAt(i); 1499 final int userId = userData.info.id; 1500 if (userId != currentUser && userData.info.isFull() && !userData.info.partial 1501 && userData.info.isEnabled() && !mRemovingUserIds.get(userId)) { 1502 final long userEnteredTime = userData.mLastEnteredForegroundTimeMillis; 1503 if (userEnteredTime > latestEnteredTime) { 1504 latestEnteredTime = userEnteredTime; 1505 previousUser = userId; 1506 } 1507 } 1508 } 1509 } 1510 return previousUser; 1511 } 1512 1513 @Override getCommunalProfileId()1514 public @CanBeNULL @UserIdInt int getCommunalProfileId() { 1515 checkQueryOrCreateUsersPermission("get communal profile user id"); 1516 return getCommunalProfileIdUnchecked(); 1517 } 1518 1519 /** Returns the currently-designated communal profile, or USER_NULL if not present. */ getCommunalProfileIdUnchecked()1520 private @CanBeNULL @UserIdInt int getCommunalProfileIdUnchecked() { 1521 synchronized (mUsersLock) { 1522 final int userSize = mUsers.size(); 1523 for (int i = 0; i < userSize; i++) { 1524 final UserInfo user = mUsers.valueAt(i).info; 1525 if (user.isCommunalProfile() && !mRemovingUserIds.get(user.id)) { 1526 return user.id; 1527 } 1528 } 1529 } 1530 return UserHandle.USER_NULL; 1531 } 1532 1533 /** Returns the currently-designated supervising profile, or USER_NULL if not present. */ getSupervisingProfileId()1534 private @CanBeNULL @UserIdInt int getSupervisingProfileId() { 1535 synchronized (mUsersLock) { 1536 final int userSize = mUsers.size(); 1537 for (int i = 0; i < userSize; i++) { 1538 final UserInfo user = mUsers.valueAt(i).info; 1539 if (user.isSupervisingProfile() && !mRemovingUserIds.get(user.id)) { 1540 return user.id; 1541 } 1542 } 1543 } 1544 return UserHandle.USER_NULL; 1545 } 1546 getUsers(boolean excludeDying)1547 public @NonNull List<UserInfo> getUsers(boolean excludeDying) { 1548 return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */ 1549 true); 1550 } 1551 1552 @Override getUsers(boolean excludePartial, boolean excludeDying, boolean excludePreCreated)1553 public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying, 1554 boolean excludePreCreated) { 1555 checkCreateUsersPermission("query users"); 1556 return getUsersInternal(excludePartial, excludeDying, excludePreCreated); 1557 } 1558 getUsersInternal(boolean excludePartial, boolean excludeDying, boolean excludePreCreated)1559 private @NonNull List<UserInfo> getUsersInternal(boolean excludePartial, boolean excludeDying, 1560 boolean excludePreCreated) { 1561 synchronized (mUsersLock) { 1562 ArrayList<UserInfo> users = new ArrayList<>(mUsers.size()); 1563 final int userSize = mUsers.size(); 1564 for (int i = 0; i < userSize; i++) { 1565 UserInfo ui = mUsers.valueAt(i).info; 1566 if ((excludePartial && ui.partial) 1567 || (excludeDying && mRemovingUserIds.get(ui.id)) 1568 || (excludePreCreated && ui.preCreated)) { 1569 continue; 1570 } 1571 users.add(userWithName(ui)); 1572 } 1573 return users; 1574 } 1575 } 1576 1577 @Override getProfiles(@serIdInt int userId, boolean enabledOnly)1578 public List<UserInfo> getProfiles(@UserIdInt int userId, boolean enabledOnly) { 1579 boolean returnFullInfo; 1580 if (userId != UserHandle.getCallingUserId()) { 1581 checkQueryOrCreateUsersPermission("getting profiles related to user " + userId); 1582 returnFullInfo = true; 1583 } else { 1584 returnFullInfo = hasCreateUsersPermission(); 1585 } 1586 final long ident = Binder.clearCallingIdentity(); 1587 try { 1588 synchronized (mUsersLock) { 1589 return getProfilesLU(userId, /* userType */ null, enabledOnly, returnFullInfo); 1590 } 1591 } finally { 1592 Binder.restoreCallingIdentity(ident); 1593 } 1594 } 1595 1596 // TODO(b/142482943): Will probably need a getProfiles(userType). But permissions may vary. 1597 1598 @Override getProfileIds(@serIdInt int userId, boolean enabledOnly)1599 public int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) { 1600 return getProfileIds(userId, null, enabledOnly, /* excludeHidden */ false); 1601 } 1602 1603 // TODO(b/142482943): Probably @Override and make this accessible in UserManager. 1604 /** 1605 * Returns all the users of type userType that are in the same profile group as userId 1606 * (including userId itself, if it is of the appropriate user type). 1607 * 1608 * <p>If userType is non-{@code null}, only returns users that are of type userType. 1609 * If enabledOnly, only returns users that are not {@link UserInfo#FLAG_DISABLED}. 1610 */ getProfileIds(@serIdInt int userId, @Nullable String userType, boolean enabledOnly, boolean excludeHidden)1611 public int[] getProfileIds(@UserIdInt int userId, @Nullable String userType, 1612 boolean enabledOnly, boolean excludeHidden) { 1613 if (userId != UserHandle.getCallingUserId()) { 1614 checkQueryOrCreateUsersPermission("getting profiles related to user " + userId); 1615 } 1616 final long ident = Binder.clearCallingIdentity(); 1617 try { 1618 synchronized (mUsersLock) { 1619 return getProfileIdsLU(userId, userType, enabledOnly, excludeHidden).toArray(); 1620 } 1621 } finally { 1622 Binder.restoreCallingIdentity(ident); 1623 } 1624 } 1625 1626 /** Assume permissions already checked and caller's identity cleared */ 1627 @GuardedBy("mUsersLock") getProfilesLU(@serIdInt int userId, @Nullable String userType, boolean enabledOnly, boolean fullInfo)1628 private List<UserInfo> getProfilesLU(@UserIdInt int userId, @Nullable String userType, 1629 boolean enabledOnly, boolean fullInfo) { 1630 IntArray profileIds = getProfileIdsLU(userId, userType, enabledOnly, /* excludeHidden */ 1631 false); 1632 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size()); 1633 for (int i = 0; i < profileIds.size(); i++) { 1634 int profileId = profileIds.get(i); 1635 UserInfo userInfo = mUsers.get(profileId).info; 1636 // If full info is not required - clear PII data to prevent 3P apps from reading it 1637 if (!fullInfo) { 1638 userInfo = new UserInfo(userInfo); 1639 userInfo.name = null; 1640 userInfo.iconPath = null; 1641 } else { 1642 userInfo = userWithName(userInfo); 1643 } 1644 users.add(userInfo); 1645 } 1646 return users; 1647 } 1648 1649 /** 1650 * Assume permissions already checked and caller's identity cleared 1651 * <p>If userType is {@code null}, returns all profiles for user; else, only returns 1652 * profiles of that type. 1653 */ 1654 @GuardedBy("mUsersLock") getProfileIdsLU(@serIdInt int userId, @Nullable String userType, boolean enabledOnly, boolean excludeHidden)1655 private IntArray getProfileIdsLU(@UserIdInt int userId, @Nullable String userType, 1656 boolean enabledOnly, boolean excludeHidden) { 1657 UserInfo user = getUserInfoLU(userId); 1658 IntArray result = new IntArray(mUsers.size()); 1659 if (user == null) { 1660 // Probably a dying user 1661 return result; 1662 } 1663 final int userSize = mUsers.size(); 1664 for (int i = 0; i < userSize; i++) { 1665 UserInfo profile = mUsers.valueAt(i).info; 1666 if (!isSameProfileGroup(user, profile)) { 1667 continue; 1668 } 1669 if (enabledOnly && !profile.isEnabled()) { 1670 continue; 1671 } 1672 if (mRemovingUserIds.get(profile.id)) { 1673 continue; 1674 } 1675 if (profile.partial) { 1676 continue; 1677 } 1678 if (userType != null && !userType.equals(profile.userType)) { 1679 continue; 1680 } 1681 if (excludeHidden && isProfileHidden(profile.id)) { 1682 continue; 1683 } 1684 result.add(profile.id); 1685 } 1686 return result; 1687 } 1688 1689 /* 1690 * Returns all the users that are in the same profile group as userId excluding those with 1691 * {@link UserProperties#getProfileApiVisibility()} set to hidden. The returned list includes 1692 * the user itself. 1693 */ 1694 // TODO (b/323011770): Add a permission check to make an exception for App stores if we end 1695 // up supporting Private Space on COPE devices 1696 @Override getProfileIdsExcludingHidden(@serIdInt int userId, boolean enabledOnly)1697 public int[] getProfileIdsExcludingHidden(@UserIdInt int userId, boolean enabledOnly) { 1698 return getProfileIds(userId, null, enabledOnly, /* excludeHidden */ true); 1699 } 1700 isProfileHidden(int userId)1701 private boolean isProfileHidden(int userId) { 1702 UserProperties userProperties = getUserPropertiesCopy(userId); 1703 if (android.os.Flags.allowPrivateProfile() 1704 && android.multiuser.Flags.enableHidingProfiles() 1705 && android.multiuser.Flags.enablePrivateSpaceFeatures()) { 1706 return userProperties.getProfileApiVisibility() 1707 == UserProperties.PROFILE_API_VISIBILITY_HIDDEN; 1708 } 1709 return false; 1710 } 1711 1712 @Override getCredentialOwnerProfile(@serIdInt int userId)1713 public int getCredentialOwnerProfile(@UserIdInt int userId) { 1714 checkManageUsersPermission("get the credential owner"); 1715 final long identity = Binder.clearCallingIdentity(); 1716 try { 1717 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) { 1718 synchronized (mUsersLock) { 1719 UserInfo profileParent = getProfileParentLU(userId); 1720 if (profileParent != null) { 1721 return profileParent.id; 1722 } 1723 } 1724 } 1725 } finally { 1726 Binder.restoreCallingIdentity(identity); 1727 } 1728 return userId; 1729 } 1730 1731 @Override isSameProfileGroup(@serIdInt int userId, int otherUserId)1732 public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) { 1733 if (userId == otherUserId) return true; 1734 checkQueryUsersPermission("check if in the same profile group"); 1735 return isSameProfileGroupNoChecks(userId, otherUserId); 1736 } 1737 1738 /** Returns whether users are in the same profile group. */ isSameProfileGroupNoChecks(@serIdInt int userId, int otherUserId)1739 private boolean isSameProfileGroupNoChecks(@UserIdInt int userId, int otherUserId) { 1740 synchronized (mUsersLock) { 1741 UserInfo userInfo = getUserInfoLU(userId); 1742 if (userInfo == null) { 1743 return false; 1744 } 1745 UserInfo otherUserInfo = getUserInfoLU(otherUserId); 1746 if (otherUserInfo == null) { 1747 return false; 1748 } 1749 return isSameProfileGroup(userInfo, otherUserInfo); 1750 } 1751 } 1752 1753 /** 1754 * Returns whether users are in the same profile group, or if the target is a communal profile. 1755 */ isSameUserOrProfileGroupOrTargetIsCommunal(UserInfo asker, UserInfo target)1756 private boolean isSameUserOrProfileGroupOrTargetIsCommunal(UserInfo asker, UserInfo target) { 1757 if (asker.id == target.id) return true; 1758 if (android.multiuser.Flags.supportCommunalProfile()) { 1759 if (target.isCommunalProfile()) return true; 1760 } 1761 return (asker.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID 1762 && asker.profileGroupId == target.profileGroupId); 1763 } 1764 1765 @Override getProfileParent(@serIdInt int userId)1766 public UserInfo getProfileParent(@UserIdInt int userId) { 1767 if (!hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) { 1768 throw new SecurityException( 1769 "You need MANAGE_USERS or INTERACT_ACROSS_USERS permission to get the " 1770 + "profile parent"); 1771 } 1772 synchronized (mUsersLock) { 1773 return getProfileParentLU(userId); 1774 } 1775 } 1776 1777 @Override getProfileParentId(@serIdInt int userId)1778 public int getProfileParentId(@UserIdInt int userId) { 1779 checkManageUsersPermission("get the profile parent"); 1780 return getProfileParentIdUnchecked(userId); 1781 } 1782 getProfileParentIdUnchecked(@serIdInt int userId)1783 private @UserIdInt int getProfileParentIdUnchecked(@UserIdInt int userId) { 1784 synchronized (mUsersLock) { 1785 UserInfo profileParent = getProfileParentLU(userId); 1786 if (profileParent == null) { 1787 return userId; 1788 } 1789 return profileParent.id; 1790 } 1791 } 1792 1793 1794 @GuardedBy("mUsersLock") getProfileParentLU(@serIdInt int userId)1795 private UserInfo getProfileParentLU(@UserIdInt int userId) { 1796 UserInfo profile = getUserInfoLU(userId); 1797 if (profile == null) { 1798 return null; 1799 } 1800 int parentUserId = profile.profileGroupId; 1801 if (parentUserId == userId || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) { 1802 return null; 1803 } else { 1804 return getUserInfoLU(parentUserId); 1805 } 1806 } 1807 isSameProfileGroup(@onNull UserInfo user1, @NonNull UserInfo user2)1808 private static boolean isSameProfileGroup(@NonNull UserInfo user1, @NonNull UserInfo user2) { 1809 return user1.id == user2.id || 1810 (user1.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID 1811 && user1.profileGroupId == user2.profileGroupId); 1812 } 1813 getAvailabilityIntentAction(boolean enableQuietMode, boolean useManagedActions)1814 private String getAvailabilityIntentAction(boolean enableQuietMode, boolean useManagedActions) { 1815 return useManagedActions ? 1816 enableQuietMode ? 1817 Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE 1818 : Intent.ACTION_MANAGED_PROFILE_AVAILABLE 1819 : enableQuietMode ? 1820 Intent.ACTION_PROFILE_UNAVAILABLE 1821 : Intent.ACTION_PROFILE_AVAILABLE; 1822 } 1823 broadcastProfileAvailabilityChanges(UserInfo profileInfo, UserHandle parentHandle, boolean enableQuietMode, boolean useManagedActions)1824 private void broadcastProfileAvailabilityChanges(UserInfo profileInfo, 1825 UserHandle parentHandle, boolean enableQuietMode, boolean useManagedActions) { 1826 Intent availabilityIntent = new Intent(); 1827 availabilityIntent.setAction( 1828 getAvailabilityIntentAction(enableQuietMode, useManagedActions)); 1829 availabilityIntent.putExtra(Intent.EXTRA_QUIET_MODE, enableQuietMode); 1830 availabilityIntent.putExtra(Intent.EXTRA_USER, profileInfo.getUserHandle()); 1831 availabilityIntent.putExtra(Intent.EXTRA_USER_HANDLE, 1832 profileInfo.getUserHandle().getIdentifier()); 1833 if (profileInfo.isManagedProfile()) { 1834 getDevicePolicyManagerInternal().broadcastIntentToManifestReceivers( 1835 availabilityIntent, parentHandle, /* requiresPermission= */ true); 1836 } 1837 availabilityIntent.addFlags( 1838 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND); 1839 1840 // TODO(b/302708423): Restrict the apps that can receive these intents in case of a private 1841 // profile. 1842 final Bundle options = new BroadcastOptions() 1843 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE) 1844 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT) 1845 // Both actions use single namespace because only the final state matters. 1846 .setDeliveryGroupMatchingKey( 1847 useManagedActions ? Intent.ACTION_MANAGED_PROFILE_AVAILABLE 1848 : Intent.ACTION_PROFILE_AVAILABLE, 1849 String.valueOf(profileInfo.getUserHandle().getIdentifier()) /* key */) 1850 .toBundle(); 1851 mContext.sendBroadcastAsUser(availabilityIntent, parentHandle, /* receiverPermission= */ 1852 null, options); 1853 } 1854 1855 @Override requestQuietModeEnabled(@onNull String callingPackage, boolean enableQuietMode, @UserIdInt int userId, @Nullable IntentSender target, @QuietModeFlag int flags)1856 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode, 1857 @UserIdInt int userId, @Nullable IntentSender target, @QuietModeFlag int flags) { 1858 Objects.requireNonNull(callingPackage); 1859 1860 if (enableQuietMode && target != null) { 1861 throw new IllegalArgumentException( 1862 "target should only be specified when we are disabling quiet mode."); 1863 } 1864 1865 final boolean dontAskCredential = 1866 (flags & UserManager.QUIET_MODE_DISABLE_DONT_ASK_CREDENTIAL) != 0; 1867 final boolean onlyIfCredentialNotRequired = 1868 (flags & UserManager.QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED) != 0; 1869 if (dontAskCredential && onlyIfCredentialNotRequired) { 1870 throw new IllegalArgumentException("invalid flags: " + flags); 1871 } 1872 1873 ensureCanModifyQuietMode( 1874 callingPackage, Binder.getCallingUid(), userId, target != null, dontAskCredential); 1875 1876 if (onlyIfCredentialNotRequired && callingPackage.equals( 1877 getPackageManagerInternal().getSystemUiServiceComponent().getPackageName())) { 1878 // This is to prevent SysUI from accidentally allowing the profile to turned on 1879 // without password when keyguard is still locked. 1880 throw new SecurityException("SystemUI is not allowed to set " 1881 + "QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED"); 1882 } 1883 1884 final long identity = Binder.clearCallingIdentity(); 1885 try { 1886 // QUIET_MODE_DISABLE_DONT_ASK_CREDENTIAL is only allowed for managed-profiles 1887 if (dontAskCredential) { 1888 UserInfo userInfo; 1889 synchronized (mUsersLock) { 1890 userInfo = getUserInfo(userId); 1891 } 1892 if (userInfo == null) { 1893 throw new IllegalArgumentException("Invalid user. Can't find user details " 1894 + "for userId " + userId); 1895 } 1896 if (!userInfo.isManagedProfile()) { 1897 throw new IllegalArgumentException("Invalid flags: " + flags 1898 + ". Can't skip credential check for the user"); 1899 } 1900 } 1901 if (enableQuietMode) { 1902 setQuietModeEnabled(userId, true /* enableQuietMode */, target, callingPackage); 1903 return true; 1904 } 1905 if (android.os.Flags.allowPrivateProfile() 1906 && android.multiuser.Flags.enablePrivateSpaceFeatures()) { 1907 final UserProperties userProperties = getUserPropertiesInternal(userId); 1908 if (userProperties != null 1909 && userProperties.isAuthAlwaysRequiredToDisableQuietMode()) { 1910 if (onlyIfCredentialNotRequired) { 1911 return false; 1912 } 1913 1914 final KeyguardManager km = mContext.getSystemService(KeyguardManager.class); 1915 int parentUserId = getProfileParentId(userId); 1916 if (km != null && km.isDeviceSecure(parentUserId)) { 1917 showConfirmCredentialToDisableQuietMode(userId, target, callingPackage); 1918 return false; 1919 } else if (km != null && !km.isDeviceSecure(parentUserId) 1920 && android.multiuser.Flags.showSetScreenLockDialog() 1921 // TODO(b/330720545): Add a better way to accomplish this, also use it 1922 // to block profile creation w/o device credentials present. 1923 && Settings.Secure.getIntForUser(mContext.getContentResolver(), 1924 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) == 1) { 1925 Intent setScreenLockPromptIntent = 1926 SetScreenLockDialogActivity 1927 .createBaseIntent(LAUNCH_REASON_DISABLE_QUIET_MODE); 1928 setScreenLockPromptIntent.putExtra(EXTRA_ORIGIN_USER_ID, userId); 1929 mContext.startActivityAsUser(setScreenLockPromptIntent, 1930 UserHandle.of(parentUserId)); 1931 return false; 1932 } else { 1933 Slog.w(LOG_TAG, "Allowing profile unlock even when device credentials " 1934 + "are not set for user " + userId); 1935 } 1936 } 1937 } 1938 final boolean hasUnifiedChallenge = 1939 mLockPatternUtils.isManagedProfileWithUnifiedChallenge(userId); 1940 if (hasUnifiedChallenge) { 1941 KeyguardManager km = mContext.getSystemService(KeyguardManager.class); 1942 // Normally only attempt to auto-unlock unified challenge if keyguard is not showing 1943 // (to stop turning profile on automatically via the QS tile), except when we 1944 // are called with QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED, in which 1945 // case always attempt to auto-unlock. 1946 if (!km.isDeviceLocked(mLocalService.getProfileParentId(userId)) 1947 || onlyIfCredentialNotRequired) { 1948 mLockPatternUtils.tryUnlockWithCachedUnifiedChallenge(userId); 1949 } 1950 } 1951 final boolean needToShowConfirmCredential = !dontAskCredential 1952 && mLockPatternUtils.isSecure(userId) 1953 && (!hasUnifiedChallenge || !StorageManager.isCeStorageUnlocked(userId)); 1954 if (needToShowConfirmCredential) { 1955 if (onlyIfCredentialNotRequired) { 1956 return false; 1957 } 1958 showConfirmCredentialToDisableQuietMode(userId, target, callingPackage); 1959 return false; 1960 } 1961 setQuietModeEnabled(userId, false /* enableQuietMode */, target, callingPackage); 1962 return true; 1963 } finally { 1964 Binder.restoreCallingIdentity(identity); 1965 } 1966 } 1967 1968 /** 1969 * The caller can modify quiet mode if it meets one of these conditions: 1970 * <ul> 1971 * <li>Has system UID or root UID</li> 1972 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li> 1973 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li> 1974 * <li>Is the foreground default launcher app</li> 1975 * </ul> 1976 * <p> 1977 * If caller wants to start an intent after disabling the quiet mode, or if it is targeting a 1978 * user in a different profile group from the caller, it must have 1979 * {@link Manifest.permission#MANAGE_USERS}. 1980 */ ensureCanModifyQuietMode(String callingPackage, int callingUid, @UserIdInt int targetUserId, boolean startIntent, boolean dontAskCredential)1981 private void ensureCanModifyQuietMode(String callingPackage, int callingUid, 1982 @UserIdInt int targetUserId, boolean startIntent, boolean dontAskCredential) { 1983 verifyCallingPackage(callingPackage, callingUid); 1984 1985 if (hasManageUsersPermission()) { 1986 return; 1987 } 1988 if (startIntent) { 1989 throw new SecurityException("MANAGE_USERS permission is required to start intent " 1990 + "after disabling quiet mode."); 1991 } 1992 if (dontAskCredential) { 1993 throw new SecurityException("MANAGE_USERS permission is required to disable quiet " 1994 + "mode without credentials."); 1995 } 1996 if (!isSameProfileGroupNoChecks(UserHandle.getUserId(callingUid), targetUserId)) { 1997 throw new SecurityException("MANAGE_USERS permission is required to modify quiet mode " 1998 + "for a different profile group."); 1999 } 2000 final boolean hasModifyQuietModePermission = hasPermissionGranted( 2001 Manifest.permission.MODIFY_QUIET_MODE, callingUid); 2002 if (hasModifyQuietModePermission) { 2003 return; 2004 } 2005 2006 final ShortcutServiceInternal shortcutInternal = 2007 LocalServices.getService(ShortcutServiceInternal.class); 2008 if (shortcutInternal != null) { 2009 boolean isForegroundLauncher = 2010 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid); 2011 if (isForegroundLauncher) { 2012 return; 2013 } 2014 } 2015 throw new SecurityException("Can't modify quiet mode, caller is neither foreground " 2016 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission"); 2017 } 2018 setQuietModeEnabled(@serIdInt int userId, boolean enableQuietMode, IntentSender target, @Nullable String callingPackage)2019 private void setQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode, 2020 IntentSender target, @Nullable String callingPackage) { 2021 final UserInfo profile, parent; 2022 final UserData profileUserData; 2023 synchronized (mUsersLock) { 2024 profile = getUserInfoLU(userId); 2025 parent = getProfileParentLU(userId); 2026 2027 if (profile == null || !profile.isProfile()) { 2028 throw new IllegalArgumentException("User " + userId + " is not a profile"); 2029 } 2030 if (profile.isQuietModeEnabled() == enableQuietMode) { 2031 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode); 2032 return; 2033 } 2034 UserManager.invalidateQuietModeEnabledCache(); 2035 profile.flags ^= UserInfo.FLAG_QUIET_MODE; 2036 profileUserData = getUserDataLU(profile.id); 2037 } 2038 synchronized (mPackagesLock) { 2039 writeUserLP(profileUserData); 2040 } 2041 2042 try { 2043 if (enableQuietMode) { 2044 stopUserForQuietMode(userId); 2045 LocalServices.getService(ActivityManagerInternal.class) 2046 .killForegroundAppsForUser(userId); 2047 } else { 2048 IProgressListener callback = target != null 2049 ? new DisableQuietModeUserUnlockedCallback(target) 2050 : null; 2051 ActivityManager.getService().startProfileWithListener(userId, callback); 2052 } 2053 } catch (RemoteException e) { 2054 // Should not happen, same process. 2055 e.rethrowAsRuntimeException(); 2056 } 2057 2058 logQuietModeEnabled(userId, enableQuietMode, callingPackage); 2059 2060 // Broadcast generic intents for all profiles 2061 if (android.os.Flags.allowPrivateProfile() 2062 && android.multiuser.Flags.enablePrivateSpaceFeatures()) { 2063 broadcastProfileAvailabilityChanges(profile, parent.getUserHandle(), 2064 enableQuietMode, false); 2065 } 2066 // Broadcast Managed profile availability intents too for managed profiles. 2067 if (profile.isManagedProfile()){ 2068 broadcastProfileAvailabilityChanges(profile, parent.getUserHandle(), 2069 enableQuietMode, true); 2070 } 2071 } 2072 stopUserForQuietMode(int userId)2073 private void stopUserForQuietMode(int userId) throws RemoteException { 2074 if (android.os.Flags.allowPrivateProfile() 2075 && android.multiuser.Flags.enableBiometricsToUnlockPrivateSpace() 2076 && android.multiuser.Flags.enablePrivateSpaceFeatures()) { 2077 // Allow delayed locking since some profile types want to be able to unlock again via 2078 // biometrics. 2079 ActivityManager.getService().stopUserWithDelayedLocking(userId, null); 2080 return; 2081 } 2082 ActivityManager.getService().stopUserWithCallback(userId, null); 2083 } 2084 logQuietModeEnabled(@serIdInt int userId, boolean enableQuietMode, @Nullable String callingPackage)2085 private void logQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode, 2086 @Nullable String callingPackage) { 2087 Slogf.i(LOG_TAG, 2088 "requestQuietModeEnabled called by package %s, with enableQuietMode %b.", 2089 callingPackage, 2090 enableQuietMode); 2091 UserData userData; 2092 synchronized (mUsersLock) { 2093 userData = getUserDataLU(userId); 2094 } 2095 if (userData == null) { 2096 return; 2097 } 2098 final long now = System.currentTimeMillis(); 2099 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L 2100 ? now - userData.getLastRequestQuietModeEnabledMillis() 2101 : now - userData.info.creationTime); 2102 DevicePolicyEventLogger 2103 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED) 2104 .setInt(UserJourneyLogger.getUserTypeForStatsd(userData.info.userType)) 2105 .setStrings(callingPackage) 2106 .setBoolean(enableQuietMode) 2107 .setTimePeriod(period) 2108 .write(); 2109 userData.setLastRequestQuietModeEnabledMillis(now); 2110 } 2111 2112 @Override isQuietModeEnabled(@serIdInt int userId)2113 public boolean isQuietModeEnabled(@UserIdInt int userId) { 2114 synchronized (mPackagesLock) { 2115 UserInfo info; 2116 synchronized (mUsersLock) { 2117 info = getUserInfoLU(userId); 2118 } 2119 if (info == null || !info.isProfile()) { 2120 return false; 2121 } 2122 return info.isQuietModeEnabled(); 2123 } 2124 } 2125 2126 /** 2127 * Show confirm credential screen to unlock user in order to turn off quiet mode. 2128 */ showConfirmCredentialToDisableQuietMode( @serIdInt int userId, @Nullable IntentSender target, @Nullable String callingPackage)2129 private void showConfirmCredentialToDisableQuietMode( 2130 @UserIdInt int userId, @Nullable IntentSender target, @Nullable String callingPackage) { 2131 if (android.app.admin.flags.Flags.quietModeCredentialBugFix()) { 2132 if (!android.multiuser.Flags.restrictQuietModeCredentialBugFixToManagedProfiles() 2133 || getUserInfo(userId).isManagedProfile()) { 2134 // TODO (b/308121702) It may be brittle to rely on user states to check managed 2135 // profile state 2136 int state; 2137 synchronized (mUserStates) { 2138 state = mUserStates.get(userId, UserState.STATE_NONE); 2139 } 2140 if (state != UserState.STATE_NONE) { 2141 Slog.i(LOG_TAG, 2142 "showConfirmCredentialToDisableQuietMode() called too early, managed " 2143 + "user " + userId + " is still alive."); 2144 return; 2145 } 2146 } 2147 } 2148 // otherwise, we show a profile challenge to trigger decryption of the user 2149 final KeyguardManager km = (KeyguardManager) mContext.getSystemService( 2150 Context.KEYGUARD_SERVICE); 2151 // We should use userId not credentialOwnerUserId here, as even if it is unified 2152 // lock, confirm screenlock page will know and show personal challenge, and unlock 2153 // work profile when personal challenge is correct 2154 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId); 2155 if (unlockIntent == null) { 2156 return; 2157 } 2158 final Intent callBackIntent = new Intent( 2159 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK); 2160 if (target != null) { 2161 callBackIntent.putExtra(Intent.EXTRA_INTENT, target); 2162 } 2163 callBackIntent.putExtra(EXTRA_USER_ID, userId); 2164 callBackIntent.setPackage(mContext.getPackageName()); 2165 callBackIntent.putExtra(Intent.EXTRA_PACKAGE_NAME, callingPackage); 2166 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 2167 final PendingIntent pendingIntent = PendingIntent.getBroadcast( 2168 mContext, 2169 0, 2170 callBackIntent, 2171 PendingIntent.FLAG_CANCEL_CURRENT | 2172 PendingIntent.FLAG_ONE_SHOT | 2173 PendingIntent.FLAG_IMMUTABLE); 2174 // After unlocking the challenge, it will disable quiet mode and run the original 2175 // intentSender 2176 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender()); 2177 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 2178 2179 if (Flags.enablePrivateSpaceFeatures() && Flags.usePrivateSpaceIconInBiometricPrompt() 2180 && getUserInfo(userId).isPrivateProfile()) { 2181 unlockIntent.putExtra(CUSTOM_BIOMETRIC_PROMPT_LOGO_RES_ID_KEY, 2182 com.android.internal.R.drawable.stat_sys_private_profile_status); 2183 unlockIntent.putExtra(CUSTOM_BIOMETRIC_PROMPT_LOGO_DESCRIPTION_KEY, 2184 mContext.getString(R.string.private_space_biometric_prompt_title)); 2185 } 2186 mContext.startActivityAsUser( 2187 unlockIntent, UserHandle.of(getProfileParentIdUnchecked(userId))); 2188 } 2189 2190 @Override setUserEnabled(@serIdInt int userId)2191 public void setUserEnabled(@UserIdInt int userId) { 2192 checkManageUsersPermission("enable user"); 2193 UserInfo info; 2194 boolean wasUserDisabled = false; 2195 synchronized (mPackagesLock) { 2196 synchronized (mUsersLock) { 2197 info = getUserInfoLU(userId); 2198 if (info != null && !info.isEnabled()) { 2199 wasUserDisabled = true; 2200 removeUserInfoFlags(info, UserInfo.FLAG_DISABLED); 2201 writeUserLP(getUserDataLU(info.id)); 2202 } 2203 } 2204 } 2205 if (wasUserDisabled && info != null && info.isProfile()) { 2206 sendProfileAddedBroadcast(info.profileGroupId, info.id); 2207 } 2208 } 2209 2210 /** 2211 * This method is for monitoring flag changes on users flags and invalidate cache relevant to 2212 * the change. The method add flags and invalidateOnUserInfoFlagChange for the flags which 2213 * has changed. 2214 * @param userInfo of existing user in mUsers list 2215 * @param flags to be added to userInfo 2216 */ addUserInfoFlags(UserInfo userInfo, @UserInfoFlag int flags)2217 private void addUserInfoFlags(UserInfo userInfo, @UserInfoFlag int flags) { 2218 int diff = ~userInfo.flags & flags; 2219 if (diff > 0) { 2220 userInfo.flags |= diff; 2221 UserManager.invalidateOnUserInfoFlagChange(diff); 2222 } 2223 } 2224 2225 /** 2226 * This method is for monitoring flag changes on users flags and invalidate cache relevant to 2227 * the change. The method remove flags and invalidateOnUserInfoFlagChange for the flags which 2228 * has changed. 2229 * @param userInfo of existing user in mUsers list 2230 * @param flags to be removed from userInfo 2231 */ removeUserInfoFlags(UserInfo userInfo, @UserInfoFlag int flags)2232 private void removeUserInfoFlags(UserInfo userInfo, @UserInfoFlag int flags) { 2233 int diff = userInfo.flags & flags; 2234 if (diff > 0) { 2235 userInfo.flags ^= diff; 2236 UserManager.invalidateOnUserInfoFlagChange(diff); 2237 } 2238 } 2239 2240 @Override setUserAdmin(@serIdInt int userId)2241 public void setUserAdmin(@UserIdInt int userId) { 2242 checkManageUserAndAcrossUsersFullPermission("set user admin"); 2243 if (Flags.unicornModeRefactoringForHsumReadOnly()) { 2244 checkAdminStatusChangeAllowed(userId); 2245 } 2246 2247 mUserJourneyLogger.logUserJourneyBegin(userId, USER_JOURNEY_GRANT_ADMIN); 2248 UserData user; 2249 synchronized (mPackagesLock) { 2250 synchronized (mUsersLock) { 2251 user = getUserDataLU(userId); 2252 if (user == null) { 2253 // Exit if no user found with that id, 2254 mUserJourneyLogger.logNullUserJourneyError(USER_JOURNEY_GRANT_ADMIN, 2255 getCurrentUserId(), userId, /* userType */ "", /* userFlags */ -1); 2256 return; 2257 } else if (user.info.isAdmin()) { 2258 // Exit if the user is already an Admin. 2259 mUserJourneyLogger.logUserJourneyFinishWithError(getCurrentUserId(), 2260 user.info, USER_JOURNEY_GRANT_ADMIN, 2261 ERROR_CODE_USER_ALREADY_AN_ADMIN); 2262 return; 2263 } 2264 user.info.flags ^= UserInfo.FLAG_ADMIN; 2265 writeUserLP(user); 2266 } 2267 } 2268 mUserJourneyLogger.logUserJourneyFinishWithError(getCurrentUserId(), user.info, 2269 USER_JOURNEY_GRANT_ADMIN, ERROR_CODE_UNSPECIFIED); 2270 } 2271 2272 @Override revokeUserAdmin(@serIdInt int userId)2273 public void revokeUserAdmin(@UserIdInt int userId) { 2274 checkManageUserAndAcrossUsersFullPermission("revoke admin privileges"); 2275 if (Flags.unicornModeRefactoringForHsumReadOnly()) { 2276 checkAdminStatusChangeAllowed(userId); 2277 } 2278 2279 mUserJourneyLogger.logUserJourneyBegin(userId, USER_JOURNEY_REVOKE_ADMIN); 2280 UserData user; 2281 synchronized (mPackagesLock) { 2282 synchronized (mUsersLock) { 2283 user = getUserDataLU(userId); 2284 if (user == null) { 2285 // Exit if no user found with that id 2286 mUserJourneyLogger.logNullUserJourneyError( 2287 USER_JOURNEY_REVOKE_ADMIN, 2288 getCurrentUserId(), userId, "", -1); 2289 return; 2290 } else if (!user.info.isAdmin()) { 2291 // Exit if no user is not an Admin. 2292 mUserJourneyLogger.logUserJourneyFinishWithError(getCurrentUserId(), user.info, 2293 USER_JOURNEY_REVOKE_ADMIN, ERROR_CODE_USER_IS_NOT_AN_ADMIN); 2294 return; 2295 } 2296 user.info.flags ^= UserInfo.FLAG_ADMIN; 2297 writeUserLP(user); 2298 } 2299 } 2300 mUserJourneyLogger.logUserJourneyFinishWithError(getCurrentUserId(), user.info, 2301 USER_JOURNEY_REVOKE_ADMIN, ERROR_CODE_UNSPECIFIED); 2302 } 2303 2304 /** 2305 * Evicts a user's CE key by stopping and restarting the user. 2306 * 2307 * The key is evicted automatically by the user controller when the user has stopped. 2308 */ 2309 @Override evictCredentialEncryptionKey(@serIdInt int userId)2310 public void evictCredentialEncryptionKey(@UserIdInt int userId) { 2311 checkManageUsersPermission("evict CE key"); 2312 final IActivityManager am = ActivityManagerNative.getDefault(); 2313 final long identity = Binder.clearCallingIdentity(); 2314 // TODO(b/280054081): save userStartMode when user started and re-use it here instead 2315 final int userStartMode = isProfileUnchecked(userId) 2316 ? UserManagerInternal.USER_START_MODE_BACKGROUND_VISIBLE 2317 : UserManagerInternal.USER_START_MODE_BACKGROUND; 2318 try { 2319 am.restartUserInBackground(userId, userStartMode); 2320 } catch (RemoteException re) { 2321 throw re.rethrowAsRuntimeException(); 2322 } finally { 2323 Binder.restoreCallingIdentity(identity); 2324 } 2325 } 2326 2327 /** 2328 * Returns whether the given user (specified by userId) is of the given user type, such as 2329 * {@link UserManager#USER_TYPE_FULL_GUEST}. 2330 */ 2331 @Override isUserOfType(@serIdInt int userId, String userType)2332 public boolean isUserOfType(@UserIdInt int userId, String userType) { 2333 checkQueryOrCreateUsersPermission("check user type"); 2334 return userType != null && userType.equals(getUserTypeNoChecks(userId)); 2335 } 2336 2337 /** 2338 * Returns the user type of the given userId, or null if the user doesn't exist. 2339 * <p>No permissions checks are made (but userId checks may be made). 2340 */ getUserTypeNoChecks(@serIdInt int userId)2341 private @Nullable String getUserTypeNoChecks(@UserIdInt int userId) { 2342 synchronized (mUsersLock) { 2343 final UserInfo userInfo = getUserInfoLU(userId); 2344 return userInfo != null ? userInfo.userType : null; 2345 } 2346 } 2347 2348 /** 2349 * Returns the UserTypeDetails of the given userId's user type, or null if the no such user. 2350 * <p>No permissions checks are made (but userId checks may be made). 2351 */ getUserTypeDetailsNoChecks(@serIdInt int userId)2352 private @Nullable UserTypeDetails getUserTypeDetailsNoChecks(@UserIdInt int userId) { 2353 final String typeStr = getUserTypeNoChecks(userId); 2354 return typeStr != null ? mUserTypes.get(typeStr) : null; 2355 } 2356 2357 /** 2358 * Returns the UserTypeDetails of the given userInfo's user type (or null for a null userInfo). 2359 */ getUserTypeDetails(@ullable UserInfo userInfo)2360 private @Nullable UserTypeDetails getUserTypeDetails(@Nullable UserInfo userInfo) { 2361 final String typeStr = userInfo != null ? userInfo.userType : null; 2362 return typeStr != null ? mUserTypes.get(typeStr) : null; 2363 } 2364 2365 @Override getUserInfo(@serIdInt int userId)2366 public UserInfo getUserInfo(@UserIdInt int userId) { 2367 checkQueryOrCreateUsersPermission("query user"); 2368 synchronized (mUsersLock) { 2369 return userWithName(getUserInfoLU(userId)); 2370 } 2371 } 2372 2373 /** 2374 * Returns a UserInfo object with the name filled in, for Owner and Guest, or the original 2375 * if the name is already set. 2376 * 2377 * Note: Currently, the resulting name can be null if a user was truly created with a null name. 2378 */ userWithName(UserInfo orig)2379 private UserInfo userWithName(UserInfo orig) { 2380 if (orig != null && orig.name == null) { 2381 String name = null; 2382 if (orig.id == UserHandle.USER_SYSTEM) { 2383 if (DBG_ALLOCATION) { 2384 final int number = mUser0Allocations.incrementAndGet(); 2385 Slog.w(LOG_TAG, "System user instantiated at least " + number + " times"); 2386 } 2387 name = getOwnerName(); 2388 } else if (orig.isMain()) { 2389 name = getOwnerName(); 2390 } else if (orig.isGuest()) { 2391 name = getGuestName(); 2392 } 2393 if (name != null) { 2394 final UserInfo withName = new UserInfo(orig); 2395 withName.name = name; 2396 return withName; 2397 } 2398 } 2399 return orig; 2400 } 2401 2402 /** Returns whether the given user type is one of the FULL user types. */ isUserTypeSubtypeOfFull(String userType)2403 boolean isUserTypeSubtypeOfFull(String userType) { 2404 UserTypeDetails userTypeDetails = mUserTypes.get(userType); 2405 return userTypeDetails != null && userTypeDetails.isFull(); 2406 } 2407 2408 /** Returns whether the given user type is one of the PROFILE user types. */ isUserTypeSubtypeOfProfile(String userType)2409 boolean isUserTypeSubtypeOfProfile(String userType) { 2410 UserTypeDetails userTypeDetails = mUserTypes.get(userType); 2411 return userTypeDetails != null && userTypeDetails.isProfile(); 2412 } 2413 2414 /** Returns whether the given user type is one of the SYSTEM user types. */ isUserTypeSubtypeOfSystem(String userType)2415 boolean isUserTypeSubtypeOfSystem(String userType) { 2416 UserTypeDetails userTypeDetails = mUserTypes.get(userType); 2417 return userTypeDetails != null && userTypeDetails.isSystem(); 2418 } 2419 2420 /** 2421 * Returns a *copy* of the given user's UserProperties, stripping out any information for which 2422 * the caller lacks permission. 2423 */ 2424 @Override getUserPropertiesCopy(@serIdInt int userId)2425 public @NonNull UserProperties getUserPropertiesCopy(@UserIdInt int userId) { 2426 checkQueryOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserProperties"); 2427 final UserProperties origProperties = getUserPropertiesInternal(userId); 2428 if (origProperties != null) { 2429 boolean exposeAllFields = Binder.getCallingUid() == Process.SYSTEM_UID; 2430 boolean hasManage = hasManageUsersPermission(); 2431 boolean hasQuery = hasQueryUsersPermission(); 2432 return new UserProperties(origProperties, exposeAllFields, hasManage, hasQuery); 2433 } 2434 // A non-existent or partial user will reach here. 2435 throw new IllegalArgumentException("Cannot access properties for user " + userId); 2436 } 2437 2438 /** Returns the user's actual, canonical UserProperties object. Do not edit it externally. */ getUserPropertiesInternal(@serIdInt int userId)2439 private @Nullable UserProperties getUserPropertiesInternal(@UserIdInt int userId) { 2440 synchronized (mUsersLock) { 2441 final UserData userData = getUserDataLU(userId); 2442 if (userData != null) { 2443 return userData.userProperties; 2444 } 2445 } 2446 return null; 2447 } 2448 2449 @Override hasBadge(@serIdInt int userId)2450 public boolean hasBadge(@UserIdInt int userId) { 2451 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "hasBadge"); 2452 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId); 2453 return userTypeDetails != null && userTypeDetails.hasBadge(); 2454 } 2455 2456 @Override getUserBadgeLabelResId(@serIdInt int userId)2457 public @StringRes int getUserBadgeLabelResId(@UserIdInt int userId) { 2458 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, 2459 "getUserBadgeLabelResId"); 2460 final UserInfo userInfo = getUserInfoNoChecks(userId); 2461 final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo); 2462 if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) { 2463 Slog.e(LOG_TAG, "Requested badge label for non-badged user " + userId); 2464 return Resources.ID_NULL; 2465 } 2466 final int badgeIndex = userInfo.profileBadge; 2467 return userTypeDetails.getBadgeLabel(badgeIndex); 2468 } 2469 2470 /** 2471 * @return the color (not the resource ID) to be used for the user's badge in light theme 2472 */ 2473 @Override getUserBadgeColorResId(@serIdInt int userId)2474 public @ColorRes int getUserBadgeColorResId(@UserIdInt int userId) { 2475 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, 2476 "getUserBadgeColorResId"); 2477 final UserInfo userInfo = getUserInfoNoChecks(userId); 2478 final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo); 2479 if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) { 2480 Slog.e(LOG_TAG, "Requested badge dark color for non-badged user " + userId); 2481 return Resources.ID_NULL; 2482 } 2483 return userTypeDetails.getBadgeColor(userInfo.profileBadge); 2484 } 2485 2486 /** 2487 * @return the color (not the resource ID) to be used for the user's badge in dark theme 2488 */ 2489 @Override getUserBadgeDarkColorResId(@serIdInt int userId)2490 public @ColorRes int getUserBadgeDarkColorResId(@UserIdInt int userId) { 2491 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, 2492 "getUserBadgeDarkColorResId"); 2493 final UserInfo userInfo = getUserInfoNoChecks(userId); 2494 final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo); 2495 if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) { 2496 Slog.e(LOG_TAG, "Requested badge color for non-badged user " + userId); 2497 return Resources.ID_NULL; 2498 } 2499 return userTypeDetails.getDarkThemeBadgeColor(userInfo.profileBadge); 2500 } 2501 2502 @Override getUserIconBadgeResId(@serIdInt int userId)2503 public @DrawableRes int getUserIconBadgeResId(@UserIdInt int userId) { 2504 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserIconBadgeResId"); 2505 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId); 2506 if (userTypeDetails == null || !userTypeDetails.hasBadge()) { 2507 Slog.e(LOG_TAG, "Requested icon badge for non-badged user " + userId); 2508 return Resources.ID_NULL; 2509 } 2510 return userTypeDetails.getIconBadge(); 2511 } 2512 2513 @Override getUserBadgeResId(@serIdInt int userId)2514 public @DrawableRes int getUserBadgeResId(@UserIdInt int userId) { 2515 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserBadgeResId"); 2516 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId); 2517 if (userTypeDetails == null || !userTypeDetails.hasBadge()) { 2518 Slog.e(LOG_TAG, "Requested badge for non-badged user " + userId); 2519 return Resources.ID_NULL; 2520 } 2521 return userTypeDetails.getBadgePlain(); 2522 } 2523 2524 @Override getUserBadgeNoBackgroundResId(@serIdInt int userId)2525 public @DrawableRes int getUserBadgeNoBackgroundResId(@UserIdInt int userId) { 2526 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, 2527 "getUserBadgeNoBackgroundResId"); 2528 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId); 2529 if (userTypeDetails == null || !userTypeDetails.hasBadge()) { 2530 Slog.e(LOG_TAG, "Requested badge (no background) for non-badged user " + userId); 2531 return Resources.ID_NULL; 2532 } 2533 return userTypeDetails.getBadgeNoBackground(); 2534 } 2535 2536 @Override getUserStatusBarIconResId(@serIdInt int userId)2537 public @DrawableRes int getUserStatusBarIconResId(@UserIdInt int userId) { 2538 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, 2539 "getUserStatusBarIconResId"); 2540 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId); 2541 if (userTypeDetails == null || !userTypeDetails.hasBadge()) { 2542 Slog.w(LOG_TAG, "Requested status bar icon for non-badged user " + userId); 2543 return Resources.ID_NULL; 2544 } 2545 return userTypeDetails.getStatusBarIcon(); 2546 } 2547 2548 @Override getProfileLabelResId(@serIdInt int userId)2549 public @StringRes int getProfileLabelResId(@UserIdInt int userId) { 2550 checkQueryOrInteractPermissionIfCallerInOtherProfileGroup(userId, 2551 "getProfileLabelResId"); 2552 final UserInfo userInfo = getUserInfoNoChecks(userId); 2553 final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo); 2554 if (userInfo == null || userTypeDetails == null) { 2555 return Resources.ID_NULL; 2556 } 2557 final int userIndex = userInfo.profileBadge; 2558 return userTypeDetails.getLabel(userIndex); 2559 } 2560 2561 @Override getProfileAccessibilityLabelResId(@serIdInt int userId)2562 public @StringRes int getProfileAccessibilityLabelResId(@UserIdInt int userId) { 2563 checkQueryOrInteractPermissionIfCallerInOtherProfileGroup(userId, 2564 "getProfileAccessibilityLabelResId"); 2565 final UserInfo userInfo = getUserInfoNoChecks(userId); 2566 final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo); 2567 if (userInfo == null || userTypeDetails == null) { 2568 return Resources.ID_NULL; 2569 } 2570 return userTypeDetails.getAccessibilityString(); 2571 } 2572 isProfile(@serIdInt int userId)2573 public boolean isProfile(@UserIdInt int userId) { 2574 checkQueryOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isProfile"); 2575 return isProfileUnchecked(userId); 2576 } 2577 isProfileUnchecked(@serIdInt int userId)2578 private boolean isProfileUnchecked(@UserIdInt int userId) { 2579 synchronized (mUsersLock) { 2580 UserInfo userInfo = getUserInfoLU(userId); 2581 return userInfo != null && userInfo.isProfile(); 2582 } 2583 } 2584 2585 /** 2586 * Returns the user type (if it is a profile), empty string (if it isn't a profile), 2587 * or null (if the user doesn't exist). 2588 */ 2589 @Override getProfileType(@serIdInt int userId)2590 public @Nullable String getProfileType(@UserIdInt int userId) { 2591 checkQueryOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getProfileType"); 2592 synchronized (mUsersLock) { 2593 UserInfo userInfo = getUserInfoLU(userId); 2594 if (userInfo != null) { 2595 return userInfo.isProfile() ? userInfo.userType : ""; 2596 } 2597 return null; 2598 } 2599 } 2600 2601 @Override isUserUnlockingOrUnlocked(@serIdInt int userId)2602 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) { 2603 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, 2604 "isUserUnlockingOrUnlocked"); 2605 return mLocalService.isUserUnlockingOrUnlocked(userId); 2606 } 2607 2608 @Override isUserUnlocked(@serIdInt int userId)2609 public boolean isUserUnlocked(@UserIdInt int userId) { 2610 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isUserUnlocked"); 2611 return mLocalService.isUserUnlocked(userId); 2612 } 2613 2614 @Override isUserRunning(@serIdInt int userId)2615 public boolean isUserRunning(@UserIdInt int userId) { 2616 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isUserRunning"); 2617 return mLocalService.isUserRunning(userId); 2618 } 2619 2620 @Override isUserForeground(@serIdInt int userId)2621 public boolean isUserForeground(@UserIdInt int userId) { 2622 final int callingUserId = UserHandle.getCallingUserId(); 2623 if (callingUserId != userId 2624 && !hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) { 2625 throw new SecurityException("Caller from user " + callingUserId + " needs MANAGE_USERS " 2626 + "or INTERACT_ACROSS_USERS permission to check if another user (" + userId 2627 + ") is running in the foreground"); 2628 } 2629 2630 return userId == getCurrentUserId(); 2631 } 2632 2633 @Override isUserVisible(@serIdInt int userId)2634 public boolean isUserVisible(@UserIdInt int userId) { 2635 int callingUserId = UserHandle.getCallingUserId(); 2636 if (callingUserId != userId 2637 && !hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) { 2638 throw new SecurityException("Caller from user " + callingUserId + " needs MANAGE_USERS " 2639 + "or INTERACT_ACROSS_USERS permission to check if another user (" + userId 2640 + ") is visible"); 2641 } 2642 2643 return mUserVisibilityMediator.isUserVisible(userId); 2644 } 2645 2646 /** 2647 * This method validates whether calling user is valid in visible background users feature. 2648 * Valid user is the current user or the system or in the same profile group as the current 2649 * user. Visible background users are not valid calling users. 2650 */ enforceCurrentUserIfVisibleBackgroundEnabled()2651 public static void enforceCurrentUserIfVisibleBackgroundEnabled() { 2652 if (!UserManager.isVisibleBackgroundUsersEnabled()) { 2653 return; 2654 } 2655 final int callingUserId = UserHandle.getCallingUserId(); 2656 final long ident = Binder.clearCallingIdentity(); 2657 try { 2658 final int currentUserId = ActivityManager.getCurrentUser(); 2659 if (DBG) { 2660 Slog.d(LOG_TAG, "enforceCurrentUserIfVisibleBackgroundEnabled:" 2661 + " callingUserId=" + callingUserId 2662 + " isSystemUser=" + (callingUserId == USER_SYSTEM) 2663 + " currentUserId=" + currentUserId 2664 + " callingPid=" + Binder.getCallingPid() 2665 + " callingUid=" + Binder.getCallingUid()); 2666 } 2667 if (callingUserId != USER_SYSTEM && callingUserId != currentUserId 2668 && !UserManagerService.getInstance() 2669 .isSameProfileGroup(callingUserId, currentUserId)) { 2670 throw new SecurityException( 2671 "Invalid calling user on devices that enable visible background users. " 2672 + "callingUserId=" + callingUserId + " currentUserId=" 2673 + currentUserId); 2674 } 2675 } finally { 2676 Binder.restoreCallingIdentity(ident); 2677 } 2678 } 2679 2680 /** 2681 * Gets the current and target user ids as a {@link Pair}, calling 2682 * {@link ActivityManagerInternal} directly (and without performing any permission check). 2683 * 2684 * @return ids of current foreground user and the target user. Target user will be 2685 * {@link UserHandle#USER_NULL} if there is not an ongoing user switch. And if 2686 * {@link ActivityManagerInternal} is not available yet, they will both be 2687 * {@link UserHandle#USER_NULL}. 2688 */ 2689 @VisibleForTesting 2690 @NonNull getCurrentAndTargetUserIds()2691 Pair<Integer, Integer> getCurrentAndTargetUserIds() { 2692 ActivityManagerInternal activityManagerInternal = getActivityManagerInternal(); 2693 if (activityManagerInternal == null) { 2694 Slog.w(LOG_TAG, "getCurrentAndTargetUserId() called too early, " 2695 + "ActivityManagerInternal is not set yet"); 2696 return new Pair<>(UserHandle.USER_NULL, UserHandle.USER_NULL); 2697 } 2698 return activityManagerInternal.getCurrentAndTargetUserIds(); 2699 } 2700 2701 /** 2702 * Gets the current user id, calling {@link ActivityManagerInternal} directly (and without 2703 * performing any permission check). 2704 * 2705 * @return id of current foreground user, or {@link UserHandle#USER_NULL} if 2706 * {@link ActivityManagerInternal} is not available yet. 2707 */ 2708 @VisibleForTesting getCurrentUserId()2709 @CanBeNULL @UserIdInt int getCurrentUserId() { 2710 ActivityManagerInternal activityManagerInternal = getActivityManagerInternal(); 2711 if (activityManagerInternal == null) { 2712 Slog.w(LOG_TAG, "getCurrentUserId() called too early, ActivityManagerInternal" 2713 + " is not set yet"); 2714 return UserHandle.USER_NULL; 2715 } 2716 return activityManagerInternal.getCurrentUserId(); 2717 } 2718 2719 /** 2720 * Gets whether the user is the current foreground user or a started profile of that user. 2721 * 2722 * <p>Doesn't perform any permission check. 2723 */ 2724 @VisibleForTesting isCurrentUserOrRunningProfileOfCurrentUser(@serIdInt int userId)2725 boolean isCurrentUserOrRunningProfileOfCurrentUser(@UserIdInt int userId) { 2726 int currentUserId = getCurrentUserId(); 2727 2728 if (currentUserId == userId) { 2729 return true; 2730 } 2731 2732 if (isProfileUnchecked(userId)) { 2733 int parentId = getProfileParentIdUnchecked(userId); 2734 if (parentId == currentUserId) { 2735 return isUserRunning(userId); 2736 } 2737 } 2738 2739 return false; 2740 } 2741 2742 // Called by UserManagerServiceShellCommand isUserVisibleOnDisplay(@serIdInt int userId, int displayId)2743 boolean isUserVisibleOnDisplay(@UserIdInt int userId, int displayId) { 2744 return mUserVisibilityMediator.isUserVisible(userId, displayId); 2745 } 2746 2747 @Override getVisibleUsers()2748 public int[] getVisibleUsers() { 2749 if (!hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) { 2750 throw new SecurityException("Caller needs MANAGE_USERS or INTERACT_ACROSS_USERS " 2751 + "permission to get list of visible users"); 2752 } 2753 final long ident = Binder.clearCallingIdentity(); 2754 try { 2755 return mUserVisibilityMediator.getVisibleUsers().toArray(); 2756 } finally { 2757 Binder.restoreCallingIdentity(ident); 2758 } 2759 } 2760 2761 @Override getMainDisplayIdAssignedToUser(int userId)2762 public int getMainDisplayIdAssignedToUser(int userId) { 2763 final int callingUserId = UserHandle.getCallingUserId(); 2764 if (callingUserId != userId 2765 && !hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) { 2766 throw new SecurityException("Caller from user " + callingUserId + " needs MANAGE_USERS " 2767 + "or INTERACT_ACROSS_USERS permission to get the main display for (" + userId 2768 + ")"); 2769 } 2770 return mUserVisibilityMediator.getMainDisplayAssignedToUser(userId); 2771 } 2772 2773 @Override isForegroundUserAdmin()2774 public boolean isForegroundUserAdmin() { 2775 // No permission requirements for this API. 2776 synchronized (mUsersLock) { 2777 final int currentUserId = getCurrentUserId(); 2778 if (currentUserId != UserHandle.USER_NULL) { 2779 final UserInfo userInfo = getUserInfoLU(currentUserId); 2780 return userInfo != null && userInfo.isAdmin(); 2781 } 2782 } 2783 return false; 2784 } 2785 2786 @Override getUserName()2787 public @NonNull String getUserName() { 2788 final int callingUid = Binder.getCallingUid(); 2789 if (!hasQueryOrCreateUsersPermission() 2790 && !hasPermissionGranted( 2791 android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED, callingUid)) { 2792 throw new SecurityException("You need MANAGE_USERS, CREATE_USERS, QUERY_USERS, or " 2793 + "GET_ACCOUNTS_PRIVILEGED permissions to: get user name"); 2794 } 2795 final int userId = UserHandle.getUserId(callingUid); 2796 synchronized (mUsersLock) { 2797 UserInfo userInfo = userWithName(getUserInfoLU(userId)); 2798 if (userInfo != null && userInfo.name != null) { 2799 return userInfo.name; 2800 } 2801 return ""; 2802 } 2803 } 2804 2805 @Override getUserStartRealtime()2806 public long getUserStartRealtime() { 2807 final int userId = UserHandle.getUserId(Binder.getCallingUid()); 2808 synchronized (mUsersLock) { 2809 final UserData user = getUserDataLU(userId); 2810 if (user != null) { 2811 return user.startRealtime; 2812 } 2813 return 0; 2814 } 2815 } 2816 2817 @Override getUserUnlockRealtime()2818 public long getUserUnlockRealtime() { 2819 synchronized (mUsersLock) { 2820 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid())); 2821 if (user != null) { 2822 return user.unlockRealtime; 2823 } 2824 return 0; 2825 } 2826 } 2827 2828 /** 2829 * Enforces that the calling user is in the same profile group as {@code userId} or that only 2830 * the system UID or root's UID or apps that have the 2831 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS INTERACT_ACROSS_USERS} 2832 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} 2833 * can make certain calls to the UserManager. 2834 * 2835 * @param name used as message if SecurityException is thrown 2836 * @throws SecurityException if the caller lacks the required permissions. 2837 */ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(@serIdInt int userId, String name)2838 private void checkManageOrInteractPermissionIfCallerInOtherProfileGroup(@UserIdInt int userId, 2839 String name) { 2840 final int callingUserId = UserHandle.getCallingUserId(); 2841 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId)) { 2842 return; 2843 } 2844 if (hasManageUsersPermission()) { 2845 return; 2846 } 2847 if (hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS, 2848 Binder.getCallingUid())) { 2849 return; 2850 } 2851 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission " 2852 + "to: check " + name); 2853 } 2854 2855 /** 2856 * Enforces that the calling user is in the same profile group as {@code userId} or that only 2857 * the system UID or root's UID or apps that have the 2858 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS INTERACT_ACROSS_USERS} 2859 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 2860 * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS} 2861 * can make certain calls to the UserManager. 2862 * 2863 * @param name used as message if SecurityException is thrown 2864 * @throws SecurityException if the caller lacks the required permissions. 2865 */ checkQueryOrInteractPermissionIfCallerInOtherProfileGroup( @serIdInt int userId, String name)2866 private void checkQueryOrInteractPermissionIfCallerInOtherProfileGroup( 2867 @UserIdInt int userId, String name) { 2868 final int callingUserId = UserHandle.getCallingUserId(); 2869 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId)) { 2870 return; 2871 } 2872 if (hasQueryUsersPermission()) { 2873 return; 2874 } 2875 if (hasPermissionGranted( 2876 Manifest.permission.INTERACT_ACROSS_USERS, Binder.getCallingUid())) { 2877 return; 2878 } 2879 throw new SecurityException("You need INTERACT_ACROSS_USERS, MANAGE_USERS, or QUERY_USERS " 2880 + "permission to: check " + name); 2881 } 2882 2883 /** 2884 * Enforces that the calling user is in the same profile group as {@code userId} or that only 2885 * the system UID or root's UID or apps that have the 2886 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 2887 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} or 2888 * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS} 2889 * can make certain calls to the UserManager. 2890 * 2891 * @param userId the user's id 2892 * @param name used as message if SecurityException is thrown 2893 * @throws SecurityException if the caller lacks the required permissions. 2894 */ checkQueryOrCreateUsersPermissionIfCallerInOtherProfileGroup( @serIdInt int userId, String name)2895 private void checkQueryOrCreateUsersPermissionIfCallerInOtherProfileGroup( 2896 @UserIdInt int userId, String name) { 2897 final int callingUserId = UserHandle.getCallingUserId(); 2898 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId)) { 2899 return; 2900 } 2901 checkQueryOrCreateUsersPermission(name); 2902 } 2903 2904 @Override isDemoUser(@serIdInt int userId)2905 public boolean isDemoUser(@UserIdInt int userId) { 2906 final int callingUserId = UserHandle.getCallingUserId(); 2907 if (callingUserId != userId && !hasManageUsersPermission()) { 2908 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId 2909 + " is a demo user"); 2910 } 2911 2912 if (SystemProperties.getBoolean("ro.boot.arc_demo_mode", false)) { 2913 return true; 2914 } 2915 2916 synchronized (mUsersLock) { 2917 UserInfo userInfo = getUserInfoLU(userId); 2918 return userInfo != null && userInfo.isDemo(); 2919 } 2920 } 2921 2922 @Override isAdminUser(@serIdInt int userId)2923 public boolean isAdminUser(@UserIdInt int userId) { 2924 checkQueryOrCreateUsersPermissionIfCallerInOtherProfileGroup(userId, "isAdminUser"); 2925 synchronized (mUsersLock) { 2926 final UserInfo userInfo = getUserInfoLU(userId); 2927 return userInfo != null && userInfo.isAdmin(); 2928 } 2929 } 2930 2931 @Override isPreCreated(@serIdInt int userId)2932 public boolean isPreCreated(@UserIdInt int userId) { 2933 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isPreCreated"); 2934 synchronized (mUsersLock) { 2935 UserInfo userInfo = getUserInfoLU(userId); 2936 return userInfo != null && userInfo.preCreated; 2937 } 2938 } 2939 2940 /** 2941 * Returns whether switching users is currently allowed for the provided user. 2942 * <p> 2943 * Switching users is not allowed in the following cases: 2944 * <li>the user is in a phone call</li> 2945 * <li>{@link UserManager#DISALLOW_USER_SWITCH} is set</li> 2946 * <li>system user hasn't been unlocked yet</li> 2947 * 2948 * @return A {@link UserManager.UserSwitchabilityResult} flag indicating if the user is 2949 * switchable. 2950 */ 2951 @Override getUserSwitchability(@serIdInt int userId)2952 public @UserManager.UserSwitchabilityResult int getUserSwitchability(@UserIdInt int userId) { 2953 if (Flags.getUserSwitchabilityPermission()) { 2954 if (!hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) { 2955 throw new SecurityException( 2956 "You need MANAGE_USERS or INTERACT_ACROSS_USERS permission to " 2957 + "getUserSwitchability"); 2958 } 2959 } else { 2960 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, 2961 "getUserSwitchability"); 2962 } 2963 2964 final TimingsTraceAndSlog t = new TimingsTraceAndSlog(); 2965 t.traceBegin("getUserSwitchability-" + userId); 2966 2967 int flags = UserManager.SWITCHABILITY_STATUS_OK; 2968 2969 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELECOM)) { 2970 t.traceBegin("TM.isInCall"); 2971 final long identity = Binder.clearCallingIdentity(); 2972 try { 2973 final TelecomManager telecomManager = mContext.getSystemService( 2974 TelecomManager.class); 2975 if (telecomManager != null && telecomManager.isInCall()) { 2976 flags |= UserManager.SWITCHABILITY_STATUS_USER_IN_CALL; 2977 } 2978 } finally { 2979 Binder.restoreCallingIdentity(identity); 2980 } 2981 t.traceEnd(); 2982 } 2983 t.traceBegin("hasUserRestriction-DISALLOW_USER_SWITCH"); 2984 if (mLocalService.hasUserRestriction(DISALLOW_USER_SWITCH, userId)) { 2985 flags |= UserManager.SWITCHABILITY_STATUS_USER_SWITCH_DISALLOWED; 2986 } 2987 t.traceEnd(); 2988 2989 // System User is always unlocked in Headless System User Mode, so ignore this flag 2990 if (!isHeadlessSystemUserMode()) { 2991 t.traceBegin("getInt-ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED"); 2992 final boolean allowUserSwitchingWhenSystemUserLocked = Settings.Global.getInt( 2993 mContext.getContentResolver(), 2994 Settings.Global.ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED, 0) != 0; 2995 t.traceEnd(); 2996 t.traceBegin("isUserUnlocked-USER_SYSTEM"); 2997 final boolean systemUserUnlocked = mLocalService.isUserUnlocked(UserHandle.USER_SYSTEM); 2998 t.traceEnd(); 2999 3000 if (!allowUserSwitchingWhenSystemUserLocked && !systemUserUnlocked) { 3001 flags |= UserManager.SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED; 3002 } 3003 } 3004 t.traceEnd(); 3005 3006 return flags; 3007 } 3008 3009 @VisibleForTesting isUserSwitcherEnabled(@serIdInt int userId)3010 boolean isUserSwitcherEnabled(@UserIdInt int userId) { 3011 boolean multiUserSettingOn = Settings.Global.getInt(mContext.getContentResolver(), 3012 Settings.Global.USER_SWITCHER_ENABLED, 3013 getSystemResources().getBoolean(com.android.internal 3014 .R.bool.config_showUserSwitcherByDefault) ? 1 : 0) != 0; 3015 3016 return UserManager.supportsMultipleUsers() 3017 && !hasUserRestriction(DISALLOW_USER_SWITCH, userId) 3018 && !UserManager.isDeviceInDemoMode(mContext) 3019 && multiUserSettingOn; 3020 } 3021 3022 @Override getUserLogoutability(@serIdInt int userId)3023 public @UserLogoutability int getUserLogoutability(@UserIdInt int userId) { 3024 if (!android.multiuser.Flags.logoutUserApi()) { 3025 throw new UnsupportedOperationException( 3026 "aconfig flag android.multiuser.logout_user_api not enabled"); 3027 } 3028 3029 checkManageUsersPermission("getUserLogoutability"); 3030 3031 if (userId == UserHandle.USER_SYSTEM) { 3032 return UserManager.LOGOUTABILITY_STATUS_CANNOT_LOGOUT_SYSTEM_USER; 3033 } 3034 3035 if (userId != getCurrentUserId()) { 3036 // TODO(b/393656514): Decide what to do with non-current/background users. 3037 // As of now, we are not going to logout a background user. A background user should 3038 // simply be stopped instead. 3039 return UserManager.LOGOUTABILITY_STATUS_CANNOT_SWITCH; 3040 } 3041 3042 if (getUserSwitchability(userId) != UserManager.SWITCHABILITY_STATUS_OK) { 3043 return UserManager.LOGOUTABILITY_STATUS_CANNOT_SWITCH; 3044 } 3045 3046 if (getUserToLogoutCurrentUserTo() == UserHandle.USER_NULL) { 3047 return UserManager.LOGOUTABILITY_STATUS_NO_SUITABLE_USER_TO_LOGOUT_TO; 3048 } 3049 3050 return UserManager.LOGOUTABILITY_STATUS_OK; 3051 } 3052 3053 /** 3054 * Returns the user to switch to, when logging out current user. If in HSUM and has interactive 3055 * system user, then logout would switch to the system user. Otherwise, logout would switch to 3056 * the previous foreground user. 3057 */ getUserToLogoutCurrentUserTo()3058 private @UserIdInt int getUserToLogoutCurrentUserTo() { 3059 if (isHeadlessSystemUserMode() && canSwitchToHeadlessSystemUser()) { 3060 return USER_SYSTEM; 3061 } 3062 return getPreviousFullUserToEnterForegroundUnchecked(); 3063 } 3064 3065 @Override isUserSwitcherEnabled(boolean showEvenIfNotActionable, @UserIdInt int userId)3066 public boolean isUserSwitcherEnabled(boolean showEvenIfNotActionable, 3067 @UserIdInt int userId) { 3068 if (!isUserSwitcherEnabled(userId)) { 3069 return false; 3070 } 3071 // The feature is enabled. But is it worth showing? 3072 return showEvenIfNotActionable 3073 || !hasUserRestriction(UserManager.DISALLOW_ADD_USER, userId) // Can add new user 3074 || areThereMultipleSwitchableUsers(); // There are switchable users 3075 } 3076 3077 /** Returns true if there is more than one user that can be switched to. */ areThereMultipleSwitchableUsers()3078 private boolean areThereMultipleSwitchableUsers() { 3079 List<UserInfo> aliveUsers = getUsers(true, true, true); 3080 boolean isAnyAliveUser = false; 3081 for (UserInfo userInfo : aliveUsers) { 3082 if (userInfo.supportsSwitchToByUser()) { 3083 if (isAnyAliveUser) { 3084 return true; 3085 } 3086 isAnyAliveUser = true; 3087 } 3088 } 3089 return false; 3090 } 3091 3092 @Override isRestricted(@serIdInt int userId)3093 public boolean isRestricted(@UserIdInt int userId) { 3094 if (userId != UserHandle.getCallingUserId()) { 3095 checkQueryOrCreateUsersPermission("query isRestricted for user " + userId); 3096 } 3097 synchronized (mUsersLock) { 3098 final UserInfo userInfo = getUserInfoLU(userId); 3099 return userInfo == null ? false : userInfo.isRestricted(); 3100 } 3101 } 3102 3103 @Override canHaveRestrictedProfile(@serIdInt int userId)3104 public boolean canHaveRestrictedProfile(@UserIdInt int userId) { 3105 checkManageUsersPermission("canHaveRestrictedProfile"); 3106 synchronized (mUsersLock) { 3107 final UserInfo userInfo = getUserInfoLU(userId); 3108 if (userInfo == null || !userInfo.canHaveProfile()) { 3109 return false; 3110 } 3111 if (!userInfo.isAdmin()) { 3112 return false; 3113 } 3114 // restricted profile can be created if there is no DO set and the admin user has no PO; 3115 return !mIsDeviceManaged && !mIsUserManaged.get(userId); 3116 } 3117 } 3118 3119 @Override canAddPrivateProfile(@serIdInt int userId)3120 public boolean canAddPrivateProfile(@UserIdInt int userId) { 3121 checkCreateUsersPermission("canHaveRestrictedProfile"); 3122 UserInfo parentUserInfo = getUserInfo(userId); 3123 return isUserTypeEnabled(USER_TYPE_PROFILE_PRIVATE) 3124 && canAddMoreProfilesToUser(USER_TYPE_PROFILE_PRIVATE, 3125 userId, /* allowedToRemoveOne */ false) 3126 && (parentUserInfo != null && parentUserInfo.isMain()) 3127 && doesDeviceHardwareSupportPrivateSpace() 3128 && !hasUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE, userId); 3129 } 3130 3131 @Override hasRestrictedProfiles(@serIdInt int userId)3132 public boolean hasRestrictedProfiles(@UserIdInt int userId) { 3133 checkManageUsersPermission("hasRestrictedProfiles"); 3134 synchronized (mUsersLock) { 3135 final int userSize = mUsers.size(); 3136 for (int i = 0; i < userSize; i++) { 3137 UserInfo profile = mUsers.valueAt(i).info; 3138 if (userId != profile.id 3139 && profile.restrictedProfileParentId == userId) { 3140 return true; 3141 } 3142 } 3143 return false; 3144 } 3145 } 3146 3147 /* 3148 * Should be locked on mUsers before calling this. 3149 */ 3150 @GuardedBy("mUsersLock") getUserInfoLU(@serIdInt int userId)3151 private UserInfo getUserInfoLU(@UserIdInt int userId) { 3152 final UserData userData = mUsers.get(userId); 3153 // If it is partial and not in the process of being removed, return as unknown user. 3154 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) { 3155 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId); 3156 return null; 3157 } 3158 return userData != null ? userData.info : null; 3159 } 3160 3161 @GuardedBy("mUsersLock") getUserDataLU(@serIdInt int userId)3162 private UserData getUserDataLU(@UserIdInt int userId) { 3163 final UserData userData = mUsers.get(userId); 3164 // If it is partial and not in the process of being removed, return as unknown user. 3165 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) { 3166 return null; 3167 } 3168 return userData; 3169 } 3170 3171 /** 3172 * Obtains {@link #mUsersLock} and return UserInfo from mUsers. 3173 * <p>No permissions checking or any addition checks are made</p> 3174 */ getUserInfoNoChecks(@serIdInt int userId)3175 private UserInfo getUserInfoNoChecks(@UserIdInt int userId) { 3176 synchronized (mUsersLock) { 3177 final UserData userData = mUsers.get(userId); 3178 return userData != null ? userData.info : null; 3179 } 3180 } 3181 3182 /** 3183 * Obtains {@link #mUsersLock} and return UserData from mUsers. 3184 * <p>No permissions checking or any addition checks are made</p> 3185 */ getUserDataNoChecks(@serIdInt int userId)3186 private UserData getUserDataNoChecks(@UserIdInt int userId) { 3187 synchronized (mUsersLock) { 3188 return mUsers.get(userId); 3189 } 3190 } 3191 3192 /** Called by PackageManagerService */ exists(@serIdInt int userId)3193 public boolean exists(@UserIdInt int userId) { 3194 return mLocalService.exists(userId); 3195 } 3196 3197 /** 3198 * Returns user's {@link CrossProfileIntentFilter.AccessControlLevel}, which is derived from 3199 * {@link UserTypeDetails}. If user does not have defined their access control level, 3200 * returns default {@link CrossProfileIntentFilter#ACCESS_LEVEL_ALL} 3201 */ 3202 private @CrossProfileIntentFilter.AccessControlLevel int getCrossProfileIntentFilterAccessControl(@serIdInt int userId)3203 getCrossProfileIntentFilterAccessControl(@UserIdInt int userId) { 3204 final UserProperties userProperties = getUserPropertiesInternal(userId); 3205 return userProperties != null ? userProperties.getCrossProfileIntentFilterAccessControl() : 3206 CrossProfileIntentFilter.ACCESS_LEVEL_ALL; 3207 } 3208 3209 /** 3210 * Verifies if calling user is allowed to access {@link CrossProfileIntentFilter} between given 3211 * source and target user. 3212 * @param sourceUserId userId for which CrossProfileIntentFilter would be configured 3213 * @param targetUserId target user where we can resolve given intent filter 3214 * @param callingUid user accessing api 3215 * @param addCrossProfileIntentFilter if the operation is addition or not. 3216 * @throws SecurityException is calling user is not allowed to access. 3217 */ enforceCrossProfileIntentFilterAccess( int sourceUserId, int targetUserId, int callingUid, boolean addCrossProfileIntentFilter)3218 public void enforceCrossProfileIntentFilterAccess( 3219 int sourceUserId, int targetUserId, 3220 int callingUid, boolean addCrossProfileIntentFilter) { 3221 if (!isCrossProfileIntentFilterAccessible(sourceUserId, targetUserId, 3222 addCrossProfileIntentFilter)) { 3223 throw new SecurityException("CrossProfileIntentFilter cannot be accessed by user " 3224 + callingUid); 3225 } 3226 } 3227 3228 /** 3229 * Checks if {@link CrossProfileIntentFilter} can be accessed by calling user for given source 3230 * and target user. There are following rules of access 3231 * 1. For {@link CrossProfileIntentFilter#ACCESS_LEVEL_ALL}, 3232 * irrespective of user we would allow access(addition/modification/removal) 3233 * 2. For {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM}, 3234 * only system/root user would be able to access(addition/modification/removal) 3235 * 3. For {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM_ADD_ONLY}, 3236 * only system/root user would be able to add but not modify/remove. Once added, it cannot be 3237 * modified or removed 3238 * @param sourceUserId userId for which CrossProfileIntentFilter would be configured 3239 * @param targetUserId target user where we can resolve given intent filter 3240 * @param addCrossProfileIntentFilter if the operation is addition or not. 3241 * @return true if {@link CrossProfileIntentFilter} can be accessed by calling user 3242 */ isCrossProfileIntentFilterAccessible(int sourceUserId, int targetUserId, boolean addCrossProfileIntentFilter)3243 public boolean isCrossProfileIntentFilterAccessible(int sourceUserId, int targetUserId, 3244 boolean addCrossProfileIntentFilter) { 3245 int effectiveAccessControl = 3246 getCrossProfileIntentFilterAccessControl(sourceUserId, targetUserId); 3247 3248 /* 3249 For {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM}, if accessing user is not 3250 system or root disallowing access to {@link CrossProfileIntentFilter} 3251 */ 3252 if (CrossProfileIntentFilter.ACCESS_LEVEL_SYSTEM == effectiveAccessControl 3253 && !PackageManagerServiceUtils.isSystemOrRoot()) { 3254 return false; 3255 } 3256 3257 /* 3258 For {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM_ADD_ONLY}, allowing only 3259 system user to add {@link CrossProfileIntentFilter}. All users(including system) are 3260 disallowed to modify/remove. 3261 */ 3262 if (CrossProfileIntentFilter.ACCESS_LEVEL_SYSTEM_ADD_ONLY == effectiveAccessControl 3263 && (!addCrossProfileIntentFilter || !PackageManagerServiceUtils.isSystemOrRoot())) { 3264 return false; 3265 } 3266 return true; 3267 } 3268 3269 /** 3270 * Returns {@link CrossProfileIntentFilter.AccessControlLevel} 3271 * that should be assigned to {@link CrossProfileIntentFilter} 3272 * computed from source user's and target user's 3273 * {@link CrossProfileIntentFilter.AccessControlLevel}. 3274 * The Access Level is configured per {@link CrossProfileIntentFilter} and its property of edge 3275 * between source and target user e.g. for all {@link CrossProfileIntentFilter}s configured 3276 * between Primary user and Clone profile should have access level of 3277 * {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM} which is driven by highest 3278 * access value from source or target. The higher value means higher restrictions. 3279 * @param sourceUserId userId of source user for whom CrossProfileIntentFilter will be stored 3280 * @param targetUserId userId of target user for whom Cross Profile access would be allowed 3281 * @return least privileged {@link CrossProfileIntentFilter.AccessControlLevel} from source or 3282 * target user. 3283 */ 3284 public @CrossProfileIntentFilter.AccessControlLevel int getCrossProfileIntentFilterAccessControl(int sourceUserId, int targetUserId)3285 getCrossProfileIntentFilterAccessControl(int sourceUserId, int targetUserId) { 3286 int sourceAccessControlLevel, 3287 targetAccessControlLevel, effectiveAccessControl; 3288 sourceAccessControlLevel = getCrossProfileIntentFilterAccessControl(sourceUserId); 3289 targetAccessControlLevel = getCrossProfileIntentFilterAccessControl(targetUserId); 3290 effectiveAccessControl = Math.max(sourceAccessControlLevel, targetAccessControlLevel); 3291 return effectiveAccessControl; 3292 } 3293 3294 @Override setUserName(@serIdInt int userId, String name)3295 public void setUserName(@UserIdInt int userId, String name) { 3296 checkManageUsersPermission("rename users"); 3297 synchronized (mPackagesLock) { 3298 UserData userData = getUserDataNoChecks(userId); 3299 if (userData == null || userData.info.partial) { 3300 Slogf.w(LOG_TAG, "setUserName: unknown user #%d", userId); 3301 return; 3302 } 3303 if (Objects.equals(name, userData.info.name)) { 3304 Slogf.i(LOG_TAG, "setUserName: ignoring for user #%d as it didn't change (%s)", 3305 userId, getRedacted(name)); 3306 return; 3307 } 3308 if (name == null) { 3309 Slogf.i(LOG_TAG, "setUserName: resetting name of user #%d", userId); 3310 } else { 3311 Slogf.i(LOG_TAG, "setUserName: setting name of user #%d to %s", userId, 3312 getRedacted(name)); 3313 } 3314 userData.info.name = name; 3315 writeUserLP(userData); 3316 } 3317 final long ident = Binder.clearCallingIdentity(); 3318 try { 3319 sendUserInfoChangedBroadcast(userId); 3320 } finally { 3321 Binder.restoreCallingIdentity(ident); 3322 } 3323 } 3324 3325 @Override setUserEphemeral(@serIdInt int userId, boolean enableEphemeral)3326 public boolean setUserEphemeral(@UserIdInt int userId, boolean enableEphemeral) { 3327 checkCreateUsersPermission("update ephemeral user flag"); 3328 return enableEphemeral 3329 ? UserManager.isRemoveResultSuccessful(setUserEphemeralUnchecked(userId)) 3330 : setUserNonEphemeralUnchecked(userId); 3331 } 3332 setUserNonEphemeralUnchecked(@serIdInt int userId)3333 private boolean setUserNonEphemeralUnchecked(@UserIdInt int userId) { 3334 synchronized (mPackagesLock) { 3335 final UserData userData; 3336 synchronized (mUsersLock) { 3337 userData = mUsers.get(userId); 3338 if (userData == null) { 3339 Slog.e(LOG_TAG, TextUtils.formatSimple( 3340 "Cannot set user %d non-ephemeral, invalid user id provided.", userId)); 3341 return false; 3342 } 3343 if (!userData.info.isEphemeral()) { 3344 return true; 3345 } 3346 3347 if ((userData.info.flags & UserInfo.FLAG_EPHEMERAL_ON_CREATE) != 0) { 3348 // when user is created in ephemeral mode via FLAG_EPHEMERAL 3349 // its state cannot be changed to non-ephemeral. 3350 // FLAG_EPHEMERAL_ON_CREATE is used to keep track of this state 3351 Slog.e(LOG_TAG, TextUtils.formatSimple("User %d can not be changed to " 3352 + "non-ephemeral because it was set ephemeral on create.", userId)); 3353 return false; 3354 } 3355 } 3356 userData.info.flags &= ~UserInfo.FLAG_EPHEMERAL; 3357 writeUserLP(userData); 3358 } 3359 return true; 3360 } 3361 setUserEphemeralUnchecked(@serIdInt int userId)3362 private @UserManager.RemoveResult int setUserEphemeralUnchecked(@UserIdInt int userId) { 3363 synchronized (mPackagesLock) { 3364 final UserData userData; 3365 synchronized (mUsersLock) { 3366 final int userRemovability = getUserRemovabilityLocked(userId, "set as ephemeral"); 3367 if (userRemovability != UserManager.REMOVE_RESULT_USER_IS_REMOVABLE) { 3368 return userRemovability; 3369 } 3370 userData = mUsers.get(userId); 3371 } 3372 userData.info.flags |= UserInfo.FLAG_EPHEMERAL; 3373 writeUserLP(userData); 3374 } 3375 Slog.i(LOG_TAG, TextUtils.formatSimple( 3376 "User %d is set ephemeral and will be removed on user switch or reboot.", userId)); 3377 return UserManager.REMOVE_RESULT_DEFERRED; 3378 } 3379 3380 @Override setUserIcon(@serIdInt int userId, Bitmap bitmap)3381 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) { 3382 try { 3383 checkManageUsersPermission("update users"); 3384 enforceUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId, 3385 "Cannot set user icon"); 3386 mLocalService.setUserIcon(userId, bitmap); 3387 } catch (UserManager.CheckedUserOperationException e) { 3388 throw e.toServiceSpecificException(); 3389 } 3390 } 3391 sendUserInfoChangedBroadcast(@serIdInt int userId)3392 private void sendUserInfoChangedBroadcast(@UserIdInt int userId) { 3393 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED); 3394 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 3395 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 3396 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL); 3397 3398 // This intent allow system UI apps to refresh the content even if process was freezed. 3399 Intent bgIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED_BACKGROUND); 3400 bgIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 3401 bgIntent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 3402 mContext.sendBroadcastAsUser(bgIntent, UserHandle.ALL, 3403 Manifest.permission.MANAGE_USERS); 3404 } 3405 3406 @Override getUserIcon(int targetUserId)3407 public ParcelFileDescriptor getUserIcon(int targetUserId) { 3408 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) { 3409 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED " 3410 + "permissions to: get user icon"); 3411 } 3412 String iconPath; 3413 synchronized (mPackagesLock) { 3414 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId); 3415 if (targetUserInfo == null || targetUserInfo.partial) { 3416 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId); 3417 return null; 3418 } 3419 3420 final int callingUserId = UserHandle.getCallingUserId(); 3421 final UserInfo callingUserInfo = getUserInfoNoChecks(callingUserId); 3422 if (!isSameUserOrProfileGroupOrTargetIsCommunal(callingUserInfo, targetUserInfo)) { 3423 checkManageUsersPermission("get the icon of a user who is not related"); 3424 } 3425 3426 if (targetUserInfo.iconPath == null) { 3427 return null; 3428 } 3429 iconPath = targetUserInfo.iconPath; 3430 } 3431 3432 try { 3433 return ParcelFileDescriptor.open( 3434 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY); 3435 } catch (FileNotFoundException e) { 3436 Slog.e(LOG_TAG, "Couldn't find icon file", e); 3437 } 3438 return null; 3439 } 3440 makeInitialized(@serIdInt int userId)3441 public void makeInitialized(@UserIdInt int userId) { 3442 if (DBG) Slog.d(LOG_TAG, "makeInitialized(" + userId + ")"); 3443 checkManageUsersPermission("makeInitialized"); 3444 boolean scheduleWriteUser = false; 3445 UserData userData; 3446 synchronized (mUsersLock) { 3447 userData = mUsers.get(userId); 3448 if (userData == null || userData.info.partial) { 3449 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId); 3450 return; 3451 } 3452 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) { 3453 userData.info.flags |= UserInfo.FLAG_INITIALIZED; 3454 scheduleWriteUser = true; 3455 } 3456 } 3457 if (scheduleWriteUser) { 3458 scheduleWriteUser(userId); 3459 } 3460 } 3461 3462 /** 3463 * If default guest restrictions haven't been initialized yet, add the basic 3464 * restrictions. 3465 */ initDefaultGuestRestrictions()3466 private void initDefaultGuestRestrictions() { 3467 synchronized (mGuestRestrictions) { 3468 if (mGuestRestrictions.isEmpty()) { 3469 UserTypeDetails guestType = mUserTypes.get(UserManager.USER_TYPE_FULL_GUEST); 3470 if (guestType == null) { 3471 Slog.wtf(LOG_TAG, "Can't set default guest restrictions: type doesn't exist."); 3472 return; 3473 } 3474 guestType.addDefaultRestrictionsTo(mGuestRestrictions); 3475 } 3476 } 3477 } 3478 3479 @Override getDefaultGuestRestrictions()3480 public Bundle getDefaultGuestRestrictions() { 3481 checkManageUsersPermission("getDefaultGuestRestrictions"); 3482 synchronized (mGuestRestrictions) { 3483 return new Bundle(mGuestRestrictions); 3484 } 3485 } 3486 3487 @Override setDefaultGuestRestrictions(Bundle restrictions)3488 public void setDefaultGuestRestrictions(Bundle restrictions) { 3489 checkManageUsersPermission("setDefaultGuestRestrictions"); 3490 final List<UserInfo> guests = getGuestUsers(); 3491 synchronized (mRestrictionsLock) { 3492 for (int i = 0; i < guests.size(); i++) { 3493 updateUserRestrictionsInternalLR(restrictions, guests.get(i).id); 3494 } 3495 } 3496 synchronized (mGuestRestrictions) { 3497 mGuestRestrictions.clear(); 3498 mGuestRestrictions.putAll(restrictions); 3499 } 3500 synchronized (mPackagesLock) { 3501 writeUserListLP(); 3502 } 3503 } 3504 3505 @VisibleForTesting setUserRestrictionInner( @anBeALL @serIdInt int userId, @NonNull String key, boolean value)3506 void setUserRestrictionInner( 3507 @CanBeALL @UserIdInt int userId, @NonNull String key, boolean value) { 3508 if (!UserRestrictionsUtils.isValidRestriction(key)) { 3509 Slog.e(LOG_TAG, "Setting invalid restriction " + key); 3510 return; 3511 } 3512 synchronized (mRestrictionsLock) { 3513 final Bundle newRestrictions = BundleUtils.clone( 3514 mDevicePolicyUserRestrictions.getRestrictions(userId)); 3515 newRestrictions.putBoolean(key, value); 3516 3517 if (mDevicePolicyUserRestrictions.updateRestrictions(userId, newRestrictions)) { 3518 if (userId == UserHandle.USER_ALL) { 3519 applyUserRestrictionsForAllUsersLR(); 3520 } else { 3521 applyUserRestrictionsLR(userId); 3522 } 3523 } 3524 } 3525 } 3526 3527 /** 3528 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions} 3529 */ setDevicePolicyUserRestrictionsInner(@serIdInt int originatingUserId, @NonNull Bundle global, @NonNull RestrictionsSet local, boolean isDeviceOwner)3530 private void setDevicePolicyUserRestrictionsInner(@UserIdInt int originatingUserId, 3531 @NonNull Bundle global, @NonNull RestrictionsSet local, 3532 boolean isDeviceOwner) { 3533 synchronized (mRestrictionsLock) { 3534 final IntArray updatedUserIds = mDevicePolicyUserRestrictions.getUserIds(); 3535 3536 mCachedEffectiveUserRestrictions.removeAllRestrictions(); 3537 mDevicePolicyUserRestrictions.removeAllRestrictions(); 3538 3539 mDevicePolicyUserRestrictions.updateRestrictions(UserHandle.USER_ALL, global); 3540 3541 final IntArray localUserIds = local.getUserIds(); 3542 for (int i = 0; i < localUserIds.size(); i++) { 3543 final int userId = localUserIds.get(i); 3544 mDevicePolicyUserRestrictions.updateRestrictions(userId, 3545 local.getRestrictions(userId)); 3546 updatedUserIds.add(userId); 3547 } 3548 3549 applyUserRestrictionsForAllUsersLR(); 3550 for (int i = 0; i < updatedUserIds.size(); i++) { 3551 if (updatedUserIds.get(i) == UserHandle.USER_ALL) { 3552 continue; 3553 } 3554 applyUserRestrictionsLR(updatedUserIds.get(i)); 3555 } 3556 } 3557 } 3558 3559 @GuardedBy("mRestrictionsLock") computeEffectiveUserRestrictionsLR(@serIdInt int userId)3560 private Bundle computeEffectiveUserRestrictionsLR(@UserIdInt int userId) { 3561 final Bundle baseRestrictions = mBaseUserRestrictions.getRestrictionsNonNull(userId); 3562 3563 final Bundle global = mDevicePolicyUserRestrictions.getRestrictionsNonNull( 3564 UserHandle.USER_ALL); 3565 final Bundle local = mDevicePolicyUserRestrictions.getRestrictionsNonNull(userId); 3566 3567 if (global.isEmpty() && local.isEmpty()) { 3568 // Common case first. 3569 return baseRestrictions; 3570 } 3571 final Bundle effective = BundleUtils.clone(baseRestrictions); 3572 UserRestrictionsUtils.merge(effective, global); 3573 UserRestrictionsUtils.merge(effective, local); 3574 3575 return effective; 3576 } 3577 3578 @GuardedBy("mRestrictionsLock") invalidateEffectiveUserRestrictionsLR(@serIdInt int userId)3579 private void invalidateEffectiveUserRestrictionsLR(@UserIdInt int userId) { 3580 if (DBG) { 3581 Slog.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId); 3582 } 3583 mCachedEffectiveUserRestrictions.remove(userId); 3584 } 3585 getEffectiveUserRestrictions(@serIdInt int userId)3586 private Bundle getEffectiveUserRestrictions(@UserIdInt int userId) { 3587 synchronized (mRestrictionsLock) { 3588 Bundle restrictions = mCachedEffectiveUserRestrictions.getRestrictions(userId); 3589 if (restrictions == null) { 3590 restrictions = computeEffectiveUserRestrictionsLR(userId); 3591 mCachedEffectiveUserRestrictions.updateRestrictions(userId, restrictions); 3592 } 3593 return restrictions; 3594 } 3595 } 3596 3597 /** @return a specific user restriction that's in effect currently. */ 3598 @Override hasUserRestriction(String restrictionKey, @UserIdInt int userId)3599 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) { 3600 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "hasUserRestriction"); 3601 // TODO(b/390455855): Should this be (!userExists(userId) && userId != UserHandle.USER_ALL)? 3602 if (!userExists(userId)) { 3603 return false; 3604 } 3605 return mLocalService.hasUserRestriction(restrictionKey, userId); 3606 } 3607 3608 /** @return if any user has the given restriction. */ 3609 @Override hasUserRestrictionOnAnyUser(String restrictionKey)3610 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) { 3611 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) { 3612 return false; 3613 } 3614 final List<UserInfo> users = getUsers(/* excludeDying= */ true); 3615 for (int i = 0; i < users.size(); i++) { 3616 final int userId = users.get(i).id; 3617 Bundle restrictions = getEffectiveUserRestrictions(userId); 3618 if (restrictions != null && restrictions.getBoolean(restrictionKey)) { 3619 return true; 3620 } 3621 } 3622 return false; 3623 } 3624 3625 @Override isSettingRestrictedForUser(String setting, @UserIdInt int userId, String value, int callingUid)3626 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId, 3627 String value, int callingUid) { 3628 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3629 throw new SecurityException("Non-system caller"); 3630 } 3631 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId, 3632 value, callingUid); 3633 } 3634 3635 @Override addUserRestrictionsListener(final IUserRestrictionsListener listener)3636 public void addUserRestrictionsListener(final IUserRestrictionsListener listener) { 3637 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3638 throw new SecurityException("Non-system caller"); 3639 } 3640 3641 // NOTE: unregistering not supported; only client is the settings provider, 3642 // which installs a single static permanent listener. If that listener goes 3643 // bad it implies the whole system process is going to crash. 3644 mLocalService.addUserRestrictionsListener( 3645 (int userId, Bundle newRestrict, Bundle prevRestrict) -> { 3646 try { 3647 listener.onUserRestrictionsChanged(userId, newRestrict, prevRestrict); 3648 } catch (RemoteException re) { 3649 Slog.e("IUserRestrictionsListener", 3650 "Unable to invoke listener: " + re.getMessage()); 3651 } 3652 }); 3653 } 3654 3655 /** 3656 * Returns who set a user restriction on a user. 3657 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission. 3658 * @param restrictionKey the string key representing the restriction 3659 * @param userId the id of the user for whom to retrieve the restrictions. 3660 * @return The source of user restriction. Any combination of 3661 * {@link UserManager#RESTRICTION_NOT_SET}, 3662 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM}, 3663 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER} 3664 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER} 3665 */ 3666 @Override getUserRestrictionSource(String restrictionKey, @UserIdInt int userId)3667 public int getUserRestrictionSource(String restrictionKey, @UserIdInt int userId) { 3668 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId); 3669 // Get "bitwise or" of restriction sources for all enforcing users. 3670 int result = UserManager.RESTRICTION_NOT_SET; 3671 for (int i = enforcingUsers.size() - 1; i >= 0; i--) { 3672 result |= enforcingUsers.get(i).getUserRestrictionSource(); 3673 } 3674 return result; 3675 } 3676 3677 @Override getUserRestrictionSources( String restrictionKey, @UserIdInt int userId)3678 public List<EnforcingUser> getUserRestrictionSources( 3679 String restrictionKey, @UserIdInt int userId) { 3680 checkQueryUsersPermission("call getUserRestrictionSources."); 3681 3682 // Shortcut for the most common case 3683 if (!hasUserRestriction(restrictionKey, userId)) { 3684 return Collections.emptyList(); 3685 } 3686 3687 final List<EnforcingUser> result = new ArrayList<>(); 3688 3689 // Check if it is base restriction. 3690 if (hasBaseUserRestriction(restrictionKey, userId)) { 3691 result.add(new EnforcingUser( 3692 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM)); 3693 } 3694 3695 final DevicePolicyManagerInternal dpmi = getDevicePolicyManagerInternal(); 3696 if (dpmi != null) { 3697 result.addAll(dpmi.getUserRestrictionSources(restrictionKey, userId)); 3698 } 3699 return result; 3700 } 3701 3702 /** 3703 * @return UserRestrictions that are in effect currently. This always returns a new 3704 * {@link Bundle}. 3705 */ 3706 @Override getUserRestrictions(@serIdInt int userId)3707 public Bundle getUserRestrictions(@UserIdInt int userId) { 3708 checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserRestrictions"); 3709 return BundleUtils.clone(getEffectiveUserRestrictions(userId)); 3710 } 3711 3712 @Override hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId)3713 public boolean hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId) { 3714 checkCreateUsersPermission("hasBaseUserRestriction"); 3715 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) { 3716 return false; 3717 } 3718 synchronized (mRestrictionsLock) { 3719 Bundle bundle = mBaseUserRestrictions.getRestrictions(userId); 3720 return (bundle != null && bundle.getBoolean(restrictionKey, false)); 3721 } 3722 } 3723 3724 @Override setUserRestriction(String key, boolean value, @UserIdInt int userId)3725 public void setUserRestriction(String key, boolean value, @UserIdInt int userId) { 3726 checkManageUsersPermission("setUserRestriction"); 3727 if (!UserRestrictionsUtils.isValidRestriction(key)) { 3728 return; 3729 } 3730 3731 if (!userExists(userId)) { 3732 Slogf.w(LOG_TAG, "Cannot set user restriction %s. User with id %d does not exist", 3733 key, userId); 3734 return; 3735 } 3736 synchronized (mRestrictionsLock) { 3737 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create 3738 // a copy. 3739 final Bundle newRestrictions = BundleUtils.clone( 3740 mBaseUserRestrictions.getRestrictions(userId)); 3741 newRestrictions.putBoolean(key, value); 3742 3743 updateUserRestrictionsInternalLR(newRestrictions, userId); 3744 } 3745 } 3746 3747 /** 3748 * Optionally updating user restrictions, calculate the effective user restrictions and also 3749 * propagate to other services and system settings. 3750 * 3751 * @param newBaseRestrictions User restrictions to set. 3752 * If null, will not update user restrictions and only does the propagation. 3753 * @param userId target user ID. 3754 */ 3755 @GuardedBy("mRestrictionsLock") updateUserRestrictionsInternalLR( @ullable Bundle newBaseRestrictions, @UserIdInt int userId)3756 private void updateUserRestrictionsInternalLR( 3757 @Nullable Bundle newBaseRestrictions, @UserIdInt int userId) { 3758 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull( 3759 mAppliedUserRestrictions.getRestrictions(userId)); 3760 3761 // Update base restrictions. 3762 if (newBaseRestrictions != null) { 3763 // If newBaseRestrictions == the current one, it's probably a bug. 3764 final Bundle prevBaseRestrictions = mBaseUserRestrictions.getRestrictions(userId); 3765 3766 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions); 3767 Preconditions.checkState(mCachedEffectiveUserRestrictions.getRestrictions(userId) 3768 != newBaseRestrictions); 3769 3770 if (mBaseUserRestrictions.updateRestrictions(userId, new Bundle(newBaseRestrictions))) { 3771 scheduleWriteUser(userId); 3772 } 3773 } 3774 3775 final Bundle effective = computeEffectiveUserRestrictionsLR(userId); 3776 3777 mCachedEffectiveUserRestrictions.updateRestrictions(userId, new Bundle(effective)); 3778 3779 // Apply the new restrictions. 3780 if (DBG) { 3781 debug("Applying user restrictions: userId=" + userId 3782 + " new=" + effective + " prev=" + prevAppliedRestrictions); 3783 } 3784 3785 if (mAppOpsService != null) { // We skip it until system-ready. 3786 mHandler.post(() -> { 3787 try { 3788 mAppOpsService.setUserRestrictions(effective, mUserRestrictionToken, userId); 3789 } catch (RemoteException e) { 3790 Slog.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions"); 3791 } 3792 }); 3793 } 3794 3795 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions); 3796 3797 mAppliedUserRestrictions.updateRestrictions(userId, new Bundle(effective)); 3798 } 3799 3800 @GuardedBy("mRestrictionsLock") propagateUserRestrictionsLR(final int userId, Bundle newRestrictions, Bundle prevRestrictions)3801 private void propagateUserRestrictionsLR(final int userId, 3802 Bundle newRestrictions, Bundle prevRestrictions) { 3803 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock 3804 // actually, but we still need some kind of synchronization otherwise we might end up 3805 // calling listeners out-of-order, thus "LR". 3806 3807 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) { 3808 return; 3809 } 3810 3811 final Bundle newRestrictionsFinal = new Bundle(newRestrictions); 3812 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions); 3813 3814 mHandler.post(new Runnable() { 3815 @Override 3816 public void run() { 3817 UserRestrictionsUtils.applyUserRestrictions( 3818 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal); 3819 3820 final UserRestrictionsListener[] listeners; 3821 synchronized (mUserRestrictionsListeners) { 3822 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()]; 3823 mUserRestrictionsListeners.toArray(listeners); 3824 } 3825 for (int i = 0; i < listeners.length; i++) { 3826 listeners[i].onUserRestrictionsChanged(userId, 3827 newRestrictionsFinal, prevRestrictionsFinal); 3828 } 3829 3830 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED) 3831 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 3832 // Setting the MOST_RECENT policy allows us to discard older broadcasts 3833 // still waiting to be delivered. 3834 final Bundle options = BroadcastOptions.makeBasic() 3835 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT) 3836 .toBundle(); 3837 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId), 3838 null /* receiverPermission */, options); 3839 } 3840 }); 3841 } 3842 3843 // Package private for the inner class. 3844 @GuardedBy("mRestrictionsLock") applyUserRestrictionsLR(@serIdInt int userId)3845 private void applyUserRestrictionsLR(@UserIdInt int userId) { 3846 updateUserRestrictionsInternalLR(null, userId); 3847 scheduleWriteUser(userId); 3848 } 3849 3850 @GuardedBy("mRestrictionsLock") 3851 // Package private for the inner class. applyUserRestrictionsForAllUsersLR()3852 private void applyUserRestrictionsForAllUsersLR() { 3853 if (DBG) { 3854 debug("applyUserRestrictionsForAllUsersLR"); 3855 } 3856 // First, invalidate all cached values. 3857 mCachedEffectiveUserRestrictions.removeAllRestrictions(); 3858 3859 // We don't want to call into ActivityManagerService while taking a lock, so we'll call 3860 // it on a handler. 3861 final Runnable r = new Runnable() { 3862 @Override 3863 public void run() { 3864 // Then get the list of running users. 3865 final int[] runningUsers; 3866 try { 3867 runningUsers = ActivityManager.getService().getRunningUserIds(); 3868 } catch (RemoteException e) { 3869 Slog.w(LOG_TAG, "Unable to access ActivityManagerService"); 3870 return; 3871 } 3872 // Then re-calculate the effective restrictions and apply, only for running users. 3873 // It's okay if a new user has started after the getRunningUserIds() call, 3874 // because we'll do the same thing (re-calculate the restrictions and apply) 3875 // when we start a user. 3876 synchronized (mRestrictionsLock) { 3877 for (int i = 0; i < runningUsers.length; i++) { 3878 applyUserRestrictionsLR(runningUsers[i]); 3879 } 3880 } 3881 } 3882 }; 3883 mHandler.post(r); 3884 } 3885 3886 /** 3887 * Check if we've hit the limit of how many users can be created. 3888 */ isUserLimitReached()3889 private boolean isUserLimitReached() { 3890 int count; 3891 synchronized (mUsersLock) { 3892 count = getAliveUsersExcludingGuestsCountLU(); 3893 } 3894 return count >= UserManager.getMaxSupportedUsers() 3895 && !isCreationOverrideEnabled(); 3896 } 3897 3898 /** 3899 * Returns whether more users of the given type can be added (based on how many users of that 3900 * type already exist). 3901 * 3902 * <p>For checking whether more profiles can be added to a particular parent use 3903 * {@link #canAddMoreProfilesToUser}. 3904 */ canAddMoreUsersOfType(@onNull UserTypeDetails userTypeDetails)3905 private boolean canAddMoreUsersOfType(@NonNull UserTypeDetails userTypeDetails) { 3906 if (!isUserTypeEnabled(userTypeDetails)) { 3907 return false; 3908 } 3909 final int max = userTypeDetails.getMaxAllowed(); 3910 if (max == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) { 3911 return true; // Indicates that there is no max. 3912 } 3913 return getNumberOfUsersOfType(userTypeDetails.getName()) < max 3914 || isCreationOverrideEnabled(); 3915 } 3916 3917 /** 3918 * Returns the remaining number of users of the given type that can be created. (taking into 3919 * account the total number of users on the device as well as how many exist of that type) 3920 */ 3921 @Override getRemainingCreatableUserCount(String userType)3922 public int getRemainingCreatableUserCount(String userType) { 3923 checkQueryOrCreateUsersPermission("get the remaining number of users that can be added."); 3924 final UserTypeDetails type = mUserTypes.get(userType); 3925 if (type == null || !isUserTypeEnabled(type)) { 3926 return 0; 3927 } 3928 synchronized (mUsersLock) { 3929 final int userCount = getAliveUsersExcludingGuestsCountLU(); 3930 3931 // Limit total number of users that can be created (except for guest and demo) 3932 int result = 3933 UserManager.isUserTypeGuest(userType) || UserManager.isUserTypeDemo(userType) 3934 ? Integer.MAX_VALUE 3935 : (UserManager.getMaxSupportedUsers() - userCount); 3936 3937 // Managed profiles have their own specific rules. 3938 if (type.isManagedProfile()) { 3939 if (!mContext.getPackageManager().hasSystemFeature( 3940 PackageManager.FEATURE_MANAGED_USERS)) { 3941 return 0; 3942 } 3943 // Special case: Allow creating a managed profile anyway if there's only 1 user 3944 if (result <= 0 & userCount == 1) { 3945 result = 1; 3946 } 3947 } 3948 if (result <= 0) { 3949 return 0; 3950 } 3951 3952 // Limit against max allowed for type 3953 result = Math.min(result, 3954 type.getMaxAllowed() == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS 3955 ? Integer.MAX_VALUE 3956 : (type.getMaxAllowed() - getNumberOfUsersOfType(userType))); 3957 3958 return Math.max(0, result); 3959 } 3960 } 3961 3962 /** 3963 * Gets the number of users of the given user type. 3964 * Does not include users that are about to die. 3965 */ getNumberOfUsersOfType(String userType)3966 private int getNumberOfUsersOfType(String userType) { 3967 int count = 0; 3968 synchronized (mUsersLock) { 3969 final int size = mUsers.size(); 3970 for (int i = 0; i < size; i++) { 3971 final UserInfo user = mUsers.valueAt(i).info; 3972 if (user.userType.equals(userType) 3973 && !user.guestToRemove 3974 && !mRemovingUserIds.get(user.id) 3975 && !user.preCreated) { 3976 count++; 3977 } 3978 } 3979 } 3980 return count; 3981 } 3982 3983 /** 3984 * Returns whether more users of the given type can be added (based on how many users of that 3985 * type already exist). 3986 */ 3987 @Override canAddMoreUsersOfType(String userType)3988 public boolean canAddMoreUsersOfType(String userType) { 3989 checkCreateUsersPermission("check if more users can be added."); 3990 final UserTypeDetails userTypeDetails = mUserTypes.get(userType); 3991 return userTypeDetails != null && canAddMoreUsersOfType(userTypeDetails); 3992 } 3993 3994 /** Returns whether the creation of users of the given user type is enabled on this device. */ 3995 @Override isUserTypeEnabled(String userType)3996 public boolean isUserTypeEnabled(String userType) { 3997 checkCreateUsersPermission("check if user type is enabled."); 3998 final UserTypeDetails userTypeDetails = mUserTypes.get(userType); 3999 return userTypeDetails != null && isUserTypeEnabled(userTypeDetails); 4000 } 4001 4002 /** Returns whether the creation of users of the given user type is enabled on this device. */ isUserTypeEnabled(@onNull UserTypeDetails userTypeDetails)4003 private boolean isUserTypeEnabled(@NonNull UserTypeDetails userTypeDetails) { 4004 return userTypeDetails.isEnabled() || isCreationOverrideEnabled(); 4005 } 4006 4007 /** 4008 * Returns whether to almost-always allow creating users even beyond their limit or if disabled. 4009 * For Debug builds only. 4010 */ isCreationOverrideEnabled()4011 private boolean isCreationOverrideEnabled() { 4012 return Build.isDebuggable() 4013 && SystemProperties.getBoolean(DEV_CREATE_OVERRIDE_PROPERTY, false); 4014 } 4015 4016 @Override canAddMoreManagedProfiles(@serIdInt int userId, boolean allowedToRemoveOne)4017 public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) { 4018 return canAddMoreProfilesToUser(UserManager.USER_TYPE_PROFILE_MANAGED, userId, 4019 allowedToRemoveOne); 4020 } 4021 4022 /** Returns whether more profiles of the given type can be added to the given parent userId. */ 4023 @Override canAddMoreProfilesToUser(String userType, @UserIdInt int userId, boolean allowedToRemoveOne)4024 public boolean canAddMoreProfilesToUser(String userType, @UserIdInt int userId, 4025 boolean allowedToRemoveOne) { 4026 return 0 < getRemainingCreatableProfileCount(userType, userId, allowedToRemoveOne) 4027 || isCreationOverrideEnabled(); 4028 } 4029 4030 @Override getRemainingCreatableProfileCount(@onNull String userType, @UserIdInt int userId)4031 public int getRemainingCreatableProfileCount(@NonNull String userType, @UserIdInt int userId) { 4032 return getRemainingCreatableProfileCount(userType, userId, false); 4033 } 4034 4035 /** 4036 * Returns the remaining number of profiles of the given type that can be added to the given 4037 * user. (taking into account the total number of users on the device as well as how many 4038 * profiles exist of that type both in general and for the given user) 4039 */ getRemainingCreatableProfileCount(@onNull String userType, @UserIdInt int userId, boolean allowedToRemoveOne)4040 private int getRemainingCreatableProfileCount(@NonNull String userType, @UserIdInt int userId, 4041 boolean allowedToRemoveOne) { 4042 checkQueryOrCreateUsersPermission( 4043 "get the remaining number of profiles that can be added to the given user."); 4044 final UserTypeDetails type = mUserTypes.get(userType); 4045 if (type == null || !isUserTypeEnabled(type)) { 4046 return 0; 4047 } 4048 // Managed profiles have their own specific rules. 4049 final boolean isManagedProfile = type.isManagedProfile(); 4050 if (isManagedProfile) { 4051 if (!mContext.getPackageManager().hasSystemFeature( 4052 PackageManager.FEATURE_MANAGED_USERS)) { 4053 return 0; 4054 } 4055 } 4056 synchronized (mUsersLock) { 4057 // Check if the parent exists and its type is even allowed to have a profile. 4058 UserInfo userInfo = getUserInfoLU(userId); 4059 if (userInfo == null || !userInfo.canHaveProfile()) { 4060 return 0; 4061 } 4062 4063 final int userTypeCount = getProfileIds(userId, userType, false, /* excludeHidden */ 4064 false).length; 4065 final int profilesRemovedCount = userTypeCount > 0 && allowedToRemoveOne ? 1 : 0; 4066 final int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU() 4067 - profilesRemovedCount; 4068 4069 // Limit total number of users that can be created 4070 int result = UserManager.getMaxSupportedUsers() - usersCountAfterRemoving; 4071 4072 // Special case: Allow creating a managed profile anyway if there's only 1 user 4073 if (result <= 0 && isManagedProfile && usersCountAfterRemoving == 1) { 4074 result = 1; 4075 } 4076 4077 // Limit the number of profiles of this type that can be created. 4078 final int maxUsersOfType = getMaxUsersOfTypePerParent(type); 4079 if (maxUsersOfType != UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) { 4080 result = Math.min(result, maxUsersOfType - (userTypeCount - profilesRemovedCount)); 4081 } 4082 if (result <= 0) { 4083 return 0; 4084 } 4085 4086 // Limit against max allowed for type (beyond max allowed per parent) 4087 if (type.getMaxAllowed() != UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) { 4088 result = Math.min(result, type.getMaxAllowed() 4089 - (getNumberOfUsersOfType(userType) - profilesRemovedCount)); 4090 } 4091 4092 return Math.max(0, result); 4093 } 4094 } 4095 4096 @GuardedBy("mUsersLock") getAliveUsersExcludingGuestsCountLU()4097 private int getAliveUsersExcludingGuestsCountLU() { 4098 int aliveUserCount = 0; 4099 final int totalUserCount = mUsers.size(); 4100 // Skip over users being removed 4101 for (int i = 0; i < totalUserCount; i++) { 4102 UserInfo user = mUsers.valueAt(i).info; 4103 if (!mRemovingUserIds.get(user.id) && !user.isGuest() && !user.preCreated) { 4104 aliveUserCount++; 4105 } 4106 } 4107 return aliveUserCount; 4108 } 4109 4110 /** 4111 * Enforces that only the system UID or root's UID or apps that have the 4112 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and 4113 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL} 4114 * permissions can make certain calls to the UserManager. 4115 * 4116 * @param message used as message if SecurityException is thrown 4117 * @throws SecurityException if the caller does not have enough privilege. 4118 */ checkManageUserAndAcrossUsersFullPermission(String message)4119 private static final void checkManageUserAndAcrossUsersFullPermission(String message) { 4120 final int uid = Binder.getCallingUid(); 4121 4122 if (uid == Process.SYSTEM_UID || uid == 0) { 4123 // System UID or root's UID are granted privilege. 4124 return; 4125 } 4126 4127 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid) 4128 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) { 4129 // Apps with both permissions are granted privilege. 4130 return; 4131 } 4132 4133 throw new SecurityException( 4134 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message); 4135 } 4136 hasPermissionGranted(String permission, int uid)4137 private static boolean hasPermissionGranted(String permission, int uid) { 4138 return ActivityManager.checkComponentPermission( 4139 permission, uid, /* owningUid = */-1, /* exported = */ true) == 4140 PackageManager.PERMISSION_GRANTED; 4141 } 4142 4143 /** 4144 * Enforces that only the system UID or root's UID or apps that have the 4145 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} 4146 * permission can make certain calls to the UserManager. 4147 * 4148 * @param message used as message if SecurityException is thrown 4149 * @throws SecurityException if the caller is not system or root 4150 * @see #hasManageUsersPermission() 4151 */ checkManageUsersPermission(String message)4152 private static final void checkManageUsersPermission(String message) { 4153 if (!hasManageUsersPermission()) { 4154 throw new SecurityException("You need MANAGE_USERS permission to: " + message); 4155 } 4156 } 4157 4158 /** 4159 * Enforces that only the system UID or root's UID or apps that have the 4160 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 4161 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} 4162 * can make certain calls to the UserManager. 4163 * 4164 * @param message used as message if SecurityException is thrown 4165 * @throws SecurityException if the caller is not system or root 4166 * @see #hasCreateUsersPermission() 4167 */ checkCreateUsersPermission(String message)4168 private static final void checkCreateUsersPermission(String message) { 4169 if (!hasCreateUsersPermission()) { 4170 throw new SecurityException( 4171 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message); 4172 } 4173 } 4174 4175 /** 4176 * Enforces that only the system UID or root's UID or apps that have the 4177 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 4178 * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS} 4179 * can make certain calls to the UserManager. 4180 * 4181 * @param message used as message if SecurityException is thrown 4182 * @throws SecurityException if the caller lacks the required permissions. 4183 */ checkQueryUsersPermission(String message)4184 private static final void checkQueryUsersPermission(String message) { 4185 if (!hasQueryUsersPermission()) { 4186 throw new SecurityException( 4187 "You either need MANAGE_USERS or QUERY_USERS permission to: " + message); 4188 } 4189 } 4190 4191 /** 4192 * Enforces that only the system UID or root's UID or apps that have the 4193 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 4194 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} or 4195 * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS} 4196 * can make certain calls to the UserManager. 4197 * 4198 * @param message used as message if SecurityException is thrown 4199 * @throws SecurityException if the caller lacks the required permissions. 4200 */ checkQueryOrCreateUsersPermission(String message)4201 private static final void checkQueryOrCreateUsersPermission(String message) { 4202 if (!hasQueryOrCreateUsersPermission()) { 4203 throw new SecurityException( 4204 "You either need MANAGE_USERS, CREATE_USERS, or QUERY_USERS permission to: " 4205 + message); 4206 } 4207 } 4208 4209 /** 4210 * Similar to {@link #checkCreateUsersPermission(String)} but when the caller is tries 4211 * to create user/profiles other than what is allowed for 4212 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only 4213 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission. 4214 */ checkCreateUsersPermission(int creationFlags)4215 private static final void checkCreateUsersPermission(int creationFlags) { 4216 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) { 4217 if (!hasCreateUsersPermission()) { 4218 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS " 4219 + "permission to create an user with flags: " + creationFlags); 4220 } 4221 } else if (!hasManageUsersPermission()) { 4222 throw new SecurityException("You need MANAGE_USERS permission to create an user " 4223 + " with flags: " + creationFlags); 4224 } 4225 } 4226 4227 /** 4228 * @return whether the calling UID is system UID or root's UID or the calling app has the 4229 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}. 4230 */ hasManageUsersPermission()4231 private static final boolean hasManageUsersPermission() { 4232 final int callingUid = Binder.getCallingUid(); 4233 return hasManageUsersPermission(callingUid); 4234 } 4235 4236 /** 4237 * @return whether the given UID is system UID or root's UID or the has the permission 4238 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}. 4239 */ hasManageUsersPermission(int callingUid)4240 private static boolean hasManageUsersPermission(int callingUid) { 4241 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) 4242 || callingUid == Process.ROOT_UID 4243 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid); 4244 } 4245 4246 /** 4247 * @return whether the calling UID is system UID or root's UID or the calling app has the 4248 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission. 4249 */ hasManageUsersOrPermission(String alternativePermission)4250 private static final boolean hasManageUsersOrPermission(String alternativePermission) { 4251 final int callingUid = Binder.getCallingUid(); 4252 return hasManageUsersPermission(callingUid) 4253 || hasPermissionGranted(alternativePermission, callingUid); 4254 } 4255 4256 /** 4257 * @return whether the calling UID is system UID or root's UID or the calling app has the 4258 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 4259 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}. 4260 */ hasCreateUsersPermission()4261 private static final boolean hasCreateUsersPermission() { 4262 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS); 4263 } 4264 4265 /** 4266 * @return whether the calling UID is system UID or root's UID or the calling app has the 4267 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 4268 * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS}. 4269 */ hasQueryUsersPermission()4270 private static final boolean hasQueryUsersPermission() { 4271 return hasManageUsersOrPermission(android.Manifest.permission.QUERY_USERS); 4272 } 4273 4274 /** 4275 * @return whether the calling UID is system UID or root's UID or the calling app has 4276 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or 4277 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} or 4278 * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS}. 4279 */ hasQueryOrCreateUsersPermission()4280 private static final boolean hasQueryOrCreateUsersPermission() { 4281 return hasCreateUsersPermission() 4282 || hasPermissionGranted(Manifest.permission.QUERY_USERS, Binder.getCallingUid()); 4283 } 4284 4285 /** 4286 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the 4287 * UserManager. 4288 * 4289 * @param message used as message if SecurityException is thrown 4290 * @throws SecurityException if the caller is not system or root 4291 */ checkSystemOrRoot(String message)4292 private static void checkSystemOrRoot(String message) { 4293 final int uid = Binder.getCallingUid(); 4294 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) { 4295 throw new SecurityException("Only system may: " + message); 4296 } 4297 } 4298 4299 /** 4300 * Checks if changing the admin status of a target user is restricted 4301 * due to the DISALLOW_GRANT_ADMIN restriction. If either the calling 4302 * user or the target user has this restriction, a SecurityException 4303 * is thrown. 4304 * 4305 * @param targetUser The user ID of the user whose admin status is being 4306 * considered for change. 4307 * @throws SecurityException if the admin status change is restricted due 4308 * to the DISALLOW_GRANT_ADMIN restriction. 4309 */ checkAdminStatusChangeAllowed(int targetUser)4310 private void checkAdminStatusChangeAllowed(int targetUser) { 4311 if (hasUserRestriction(UserManager.DISALLOW_GRANT_ADMIN, UserHandle.getCallingUserId()) 4312 || hasUserRestriction(UserManager.DISALLOW_GRANT_ADMIN, targetUser)) { 4313 throw new SecurityException( 4314 "Admin status change is restricted. The DISALLOW_GRANT_ADMIN " 4315 + "restriction is applied either on the current or the target user."); 4316 } 4317 } 4318 4319 @GuardedBy({"mPackagesLock"}) writeBitmapLP(UserInfo info, Bitmap bitmap)4320 private void writeBitmapLP(UserInfo info, Bitmap bitmap) { 4321 try { 4322 File dir = new File(mUsersDir, Integer.toString(info.id)); 4323 File file = new File(dir, USER_PHOTO_FILENAME); 4324 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP); 4325 if (!dir.exists()) { 4326 dir.mkdir(); 4327 FileUtils.setPermissions( 4328 dir.getPath(), 4329 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 4330 -1, -1); 4331 } 4332 FileOutputStream os; 4333 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp)) 4334 && tmp.renameTo(file) && SELinux.restorecon(file)) { 4335 info.iconPath = file.getAbsolutePath(); 4336 } 4337 try { 4338 os.close(); 4339 } catch (IOException ioe) { 4340 // What the ... ! 4341 } 4342 tmp.delete(); 4343 } catch (FileNotFoundException e) { 4344 Slog.w(LOG_TAG, "Error setting photo for user ", e); 4345 } 4346 } 4347 4348 /** 4349 * Returns an array of user ids. 4350 * 4351 * <p>This array is cached here for quick access, so do not modify or cache it elsewhere. 4352 * 4353 * @return the array of user ids. 4354 */ getUserIds()4355 public @NonNull int[] getUserIds() { 4356 synchronized (mUsersLock) { 4357 return mUserIds; 4358 } 4359 } 4360 4361 /** 4362 * Checks whether user with a given ID exists. 4363 * @param id User id to be checked. 4364 */ 4365 @VisibleForTesting userExists(int id)4366 boolean userExists(int id) { 4367 synchronized (mUsersLock) { 4368 for (int userId : mUserIds) { 4369 if (userId == id) { 4370 return true; 4371 } 4372 } 4373 } 4374 return false; 4375 } 4376 4377 /** 4378 * Returns an array of user ids, including pre-created users. 4379 * 4380 * <p>This method should only used for the specific cases that need to handle pre-created users; 4381 * most callers should call {@link #getUserIds()} instead. 4382 * 4383 * <p>This array is cached here for quick access, so do not modify or 4384 * cache it elsewhere. 4385 * 4386 * @return the array of user ids. 4387 */ getUserIdsIncludingPreCreated()4388 public @NonNull int[] getUserIdsIncludingPreCreated() { 4389 synchronized (mUsersLock) { 4390 return mUserIdsIncludingPreCreated; 4391 } 4392 } 4393 4394 /** Checks whether the device is currently in headless system user mode (for any reason). */ 4395 @Override isHeadlessSystemUserMode()4396 public boolean isHeadlessSystemUserMode() { 4397 synchronized (mUsersLock) { 4398 final UserData systemUserData = mUsers.get(UserHandle.USER_SYSTEM); 4399 return !systemUserData.info.isFull(); 4400 } 4401 } 4402 4403 /** 4404 * Checks whether the default state of the device is headless system user mode, i.e. what the 4405 * mode would be if we did a fresh factory reset. 4406 * If the mode is being emulated (via SYSTEM_USER_MODE_EMULATION_PROPERTY) then that will be 4407 * returned instead. 4408 * Note that, even in the absence of emulation, a device might deviate from the current default 4409 * due to an OTA changing the default (which won't change the already-decided mode). 4410 */ isDefaultHeadlessSystemUserMode()4411 private boolean isDefaultHeadlessSystemUserMode() { 4412 if (!Build.isDebuggable()) { 4413 return RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER; 4414 } 4415 4416 final String emulatedValue = SystemProperties.get(SYSTEM_USER_MODE_EMULATION_PROPERTY); 4417 if (!TextUtils.isEmpty(emulatedValue)) { 4418 if (UserManager.SYSTEM_USER_MODE_EMULATION_HEADLESS.equals(emulatedValue)) return true; 4419 if (UserManager.SYSTEM_USER_MODE_EMULATION_FULL.equals(emulatedValue)) return false; 4420 if (!UserManager.SYSTEM_USER_MODE_EMULATION_DEFAULT.equals(emulatedValue)) { 4421 Slogf.e(LOG_TAG, "isDefaultHeadlessSystemUserMode(): ignoring invalid valued of " 4422 + "property %s: %s", 4423 SYSTEM_USER_MODE_EMULATION_PROPERTY, emulatedValue); 4424 } 4425 } 4426 4427 return RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER; 4428 } 4429 4430 /** 4431 * Called on boot to change the system user mode (for example, from headless to full or 4432 * vice versa) for development purposes. 4433 */ emulateSystemUserModeIfNeeded()4434 private void emulateSystemUserModeIfNeeded() { 4435 if (!Build.isDebuggable()) { 4436 return; 4437 } 4438 if (TextUtils.isEmpty(SystemProperties.get(SYSTEM_USER_MODE_EMULATION_PROPERTY))) { 4439 return; 4440 } 4441 4442 final boolean newHeadlessSystemUserMode = isDefaultHeadlessSystemUserMode(); 4443 4444 // Update system user type 4445 synchronized (mPackagesLock) { 4446 synchronized (mUsersLock) { 4447 final UserData systemUserData = mUsers.get(UserHandle.USER_SYSTEM); 4448 if (systemUserData == null) { 4449 Slogf.wtf(LOG_TAG, "emulateSystemUserModeIfNeeded(): no system user data"); 4450 return; 4451 } 4452 final int oldMainUserId = getMainUserIdUnchecked(); 4453 final int oldSysFlags = systemUserData.info.flags; 4454 final int newSysFlags; 4455 final String newUserType; 4456 if (newHeadlessSystemUserMode) { 4457 newUserType = UserManager.USER_TYPE_SYSTEM_HEADLESS; 4458 newSysFlags = oldSysFlags & ~UserInfo.FLAG_FULL & ~UserInfo.FLAG_MAIN; 4459 } else { 4460 newUserType = UserManager.USER_TYPE_FULL_SYSTEM; 4461 newSysFlags = oldSysFlags | UserInfo.FLAG_FULL | UserInfo.FLAG_MAIN; 4462 } 4463 4464 if (systemUserData.info.userType.equals(newUserType)) { 4465 Slogf.d(LOG_TAG, "emulateSystemUserModeIfNeeded(): system user type is already " 4466 + "%s, returning", newUserType); 4467 return; 4468 } 4469 Slogf.i(LOG_TAG, "Persisting emulated system user data: type changed from %s to " 4470 + "%s, flags changed from %s to %s", 4471 systemUserData.info.userType, newUserType, 4472 UserInfo.flagsToString(oldSysFlags), UserInfo.flagsToString(newSysFlags)); 4473 4474 systemUserData.info.userType = newUserType; 4475 systemUserData.info.flags = newSysFlags; 4476 writeUserLP(systemUserData); 4477 4478 // Designate the MainUser to a reasonable choice if needed. 4479 final UserData oldMain = getUserDataNoChecks(oldMainUserId); 4480 if (newHeadlessSystemUserMode) { 4481 final boolean mainIsAlreadyNonSystem = 4482 oldMain != null && (oldMain.info.flags & UserInfo.FLAG_SYSTEM) == 0; 4483 if (!mainIsAlreadyNonSystem && isMainUserPermanentAdmin()) { 4484 // We need a new choice for Main. Pick the oldest. 4485 // If no oldest, don't set any. Let the BootUserInitializer do that later. 4486 final UserInfo newMainUser = getEarliestCreatedFullUser(); 4487 if (newMainUser != null) { 4488 Slogf.i(LOG_TAG, "Designating user " + newMainUser.id + " to be Main"); 4489 newMainUser.flags |= UserInfo.FLAG_MAIN; 4490 writeUserLP(getUserDataNoChecks(newMainUser.id)); 4491 } 4492 } 4493 } else { 4494 // We already made user 0 Main above. Now strip it from the old Main user. 4495 // TODO(b/256624031): For now, we demand the Main user (if there is one) is 4496 // always the system in non-HSUM. In the future, when we relax this, change how 4497 // we handle MAIN. 4498 if (oldMain != null && (oldMain.info.flags & UserInfo.FLAG_SYSTEM) == 0) { 4499 Slogf.i(LOG_TAG, "Transferring Main to user 0 from " + oldMain.info.id); 4500 oldMain.info.flags &= ~UserInfo.FLAG_MAIN; 4501 writeUserLP(oldMain); 4502 } else { 4503 Slogf.i(LOG_TAG, "Designated user 0 to be Main"); 4504 } 4505 } 4506 } 4507 } 4508 4509 // Update emulated mode, which will used to trigger an update on user packages 4510 mUpdatingSystemUserMode = true; 4511 } 4512 4513 /** 4514 * If the device's actual HSUM status differs from that which is defined by its build 4515 * configuration, warn the user. Ignores HSUM emulated status, since that isn't relevant. 4516 * 4517 * The goal is to inform dogfooders that they need to factory reset the device to align their 4518 * device with its build configuration. 4519 */ showHsumNotificationIfNeeded()4520 private void showHsumNotificationIfNeeded() { 4521 if (RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER == isHeadlessSystemUserMode()) { 4522 // Actual state does match the configuration. Great! 4523 return; 4524 } 4525 if (Build.isDebuggable() 4526 && !TextUtils.isEmpty(SystemProperties.get(SYSTEM_USER_MODE_EMULATION_PROPERTY))) { 4527 // Ignore any device that has been playing around with HSUM emulation. 4528 return; 4529 } 4530 Slogf.w(LOG_TAG, "Posting warning that device's HSUM status doesn't match the build's."); 4531 4532 final String title = mContext 4533 .getString(R.string.wrong_hsum_configuration_notification_title); 4534 final String message = mContext 4535 .getString(R.string.wrong_hsum_configuration_notification_message); 4536 4537 final Notification notification = 4538 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 4539 .setSmallIcon(R.drawable.stat_sys_adb) 4540 .setWhen(0) 4541 .setOngoing(true) 4542 .setTicker(title) 4543 .setDefaults(0) 4544 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 4545 .setContentTitle(title) 4546 .setContentText(message) 4547 .setVisibility(Notification.VISIBILITY_PUBLIC) 4548 .build(); 4549 4550 final NotificationManager notificationManager = 4551 mContext.getSystemService(NotificationManager.class); 4552 notificationManager.notifyAsUser( 4553 null, SystemMessage.NOTE_WRONG_HSUM_STATUS, notification, UserHandle.ALL); 4554 } 4555 getUserListFile()4556 private ResilientAtomicFile getUserListFile() { 4557 File tempBackup = new File(mUserListFile.getParent(), mUserListFile.getName() + ".backup"); 4558 File reserveCopy = new File(mUserListFile.getParent(), 4559 mUserListFile.getName() + ".reservecopy"); 4560 int fileMode = FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IXOTH; 4561 return new ResilientAtomicFile(mUserListFile, tempBackup, reserveCopy, fileMode, 4562 "user list", (priority, msg) -> { 4563 Slog.e(LOG_TAG, msg); 4564 // Something went wrong, schedule full rewrite. 4565 scheduleWriteUserList(); 4566 }); 4567 } 4568 4569 @GuardedBy({"mPackagesLock"}) readUserListLP()4570 private void readUserListLP() { 4571 // Whether guest restrictions are present on userlist.xml 4572 boolean guestRestrictionsArePresentOnUserListXml = false; 4573 try (ResilientAtomicFile file = getUserListFile()) { 4574 FileInputStream fin = null; 4575 try { 4576 fin = file.openRead(); 4577 if (fin == null) { 4578 Slog.e(LOG_TAG, "userlist.xml not found, fallback to single user"); 4579 fallbackToSingleUserLP(); 4580 return; 4581 } 4582 4583 final TypedXmlPullParser parser = Xml.resolvePullParser(fin); 4584 int type; 4585 while ((type = parser.next()) != XmlPullParser.START_TAG 4586 && type != XmlPullParser.END_DOCUMENT) { 4587 // Skip 4588 } 4589 4590 if (type != XmlPullParser.START_TAG) { 4591 Slog.e(LOG_TAG, "Unable to read user list"); 4592 fallbackToSingleUserLP(); 4593 return; 4594 } 4595 4596 mNextSerialNumber = -1; 4597 if (parser.getName().equals(TAG_USERS)) { 4598 mNextSerialNumber = 4599 parser.getAttributeInt(null, ATTR_NEXT_SERIAL_NO, mNextSerialNumber); 4600 mUserVersion = 4601 parser.getAttributeInt(null, ATTR_USER_VERSION, mUserVersion); 4602 mUserTypeVersion = 4603 parser.getAttributeInt(null, ATTR_USER_TYPE_VERSION, mUserTypeVersion); 4604 } 4605 4606 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 4607 if (type == XmlPullParser.START_TAG) { 4608 final String name = parser.getName(); 4609 if (name.equals(TAG_USER)) { 4610 UserData userData = readUserLP(parser.getAttributeInt(null, ATTR_ID), 4611 mUserVersion); 4612 4613 if (userData != null) { 4614 synchronized (mUsersLock) { 4615 addUserDataLU(userData); 4616 if (mNextSerialNumber < 0 4617 || mNextSerialNumber <= userData.info.id) { 4618 mNextSerialNumber = userData.info.id + 1; 4619 } 4620 markUserForRemovalIfNecessaryLU(userData.info); 4621 } 4622 } 4623 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) { 4624 guestRestrictionsArePresentOnUserListXml = true; 4625 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 4626 && type != XmlPullParser.END_TAG) { 4627 if (type == XmlPullParser.START_TAG) { 4628 if (parser.getName().equals(TAG_RESTRICTIONS)) { 4629 synchronized (mGuestRestrictions) { 4630 UserRestrictionsUtils 4631 .readRestrictions(parser, mGuestRestrictions); 4632 } 4633 } 4634 break; 4635 } 4636 } 4637 } 4638 } 4639 } 4640 4641 updateUserIds(); 4642 upgradeIfNecessaryLP(); 4643 updateUsersWithFeatureFlags(guestRestrictionsArePresentOnUserListXml); 4644 } catch (Exception e) { 4645 // Remove corrupted file and retry. 4646 file.failRead(fin, e); 4647 readUserListLP(); 4648 return; 4649 } 4650 } 4651 4652 synchronized (mUsersLock) { 4653 if (mUsers.size() == 0) { 4654 Slog.e(LOG_TAG, "mUsers is empty, fallback to single user"); 4655 fallbackToSingleUserLP(); 4656 } 4657 } 4658 } 4659 4660 /** 4661 * Upgrade steps between versions, either for fixing bugs or changing the data format. 4662 */ 4663 @GuardedBy({"mPackagesLock"}) upgradeIfNecessaryLP()4664 private void upgradeIfNecessaryLP() { 4665 upgradeIfNecessaryLP(mUserVersion, mUserTypeVersion); 4666 } 4667 4668 /** 4669 * Update any user formats or Xml data that need to be updated based on the current user state 4670 * and the feature flag settings. 4671 */ 4672 @GuardedBy({"mPackagesLock"}) updateUsersWithFeatureFlags(boolean guestRestrictionsArePresentOnUserListXml)4673 private void updateUsersWithFeatureFlags(boolean guestRestrictionsArePresentOnUserListXml) { 4674 // User Xml re-writes are required when guest restrictions are saved on userlist.xml but 4675 // as per the feature flag it should be on the SYSTEM user's xml or guest restrictions 4676 // are saved on SYSTEM user's xml but as per the flags it should not be saved there. 4677 if (guestRestrictionsArePresentOnUserListXml 4678 == Flags.saveGlobalAndGuestRestrictionsOnSystemUserXmlReadOnly()) { 4679 for (int userId: getUserIds()) { 4680 writeUserLP(getUserDataNoChecks(userId)); 4681 } 4682 writeUserListLP(); 4683 } 4684 } 4685 4686 /** 4687 * Version of {@link #upgradeIfNecessaryLP()} that takes in the userVersion for testing 4688 * purposes. For non-tests, use {@link #upgradeIfNecessaryLP()}. 4689 */ 4690 @GuardedBy({"mPackagesLock"}) 4691 @VisibleForTesting upgradeIfNecessaryLP(int userVersion, int userTypeVersion)4692 void upgradeIfNecessaryLP(int userVersion, int userTypeVersion) { 4693 Slog.i(LOG_TAG, "Upgrading users from userVersion " + userVersion + " to " + USER_VERSION); 4694 Set<Integer> userIdsToWrite = new ArraySet<>(); 4695 final int originalVersion = mUserVersion; 4696 final int originalUserTypeVersion = mUserTypeVersion; 4697 if (userVersion < 1) { 4698 // Assign a proper name for the owner, if not initialized correctly before 4699 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM); 4700 if ("Primary".equals(userData.info.name)) { 4701 userData.info.name = 4702 getContextResources().getString(com.android.internal.R.string.owner_name); 4703 userIdsToWrite.add(userData.info.id); 4704 } 4705 userVersion = 1; 4706 } 4707 4708 if (userVersion < 2) { 4709 // Owner should be marked as initialized 4710 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM); 4711 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) { 4712 userData.info.flags |= UserInfo.FLAG_INITIALIZED; 4713 userIdsToWrite.add(userData.info.id); 4714 } 4715 userVersion = 2; 4716 } 4717 4718 4719 if (userVersion < 4) { 4720 userVersion = 4; 4721 } 4722 4723 if (userVersion < 5) { 4724 initDefaultGuestRestrictions(); 4725 userVersion = 5; 4726 } 4727 4728 if (userVersion < 6) { 4729 synchronized (mUsersLock) { 4730 for (int i = 0; i < mUsers.size(); i++) { 4731 UserData userData = mUsers.valueAt(i); 4732 // Only system user can have restricted profiles 4733 if (userData.info.isRestricted() && (userData.info.restrictedProfileParentId 4734 == UserInfo.NO_PROFILE_GROUP_ID)) { 4735 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM; 4736 userIdsToWrite.add(userData.info.id); 4737 } 4738 } 4739 } 4740 userVersion = 6; 4741 } 4742 4743 if (userVersion < 7) { 4744 // Previously only one user could enforce global restrictions, now it is per-user. 4745 synchronized (mRestrictionsLock) { 4746 if (mDevicePolicyUserRestrictions.removeRestrictionsForAllUsers( 4747 UserManager.ENSURE_VERIFY_APPS)) { 4748 mDevicePolicyUserRestrictions.getRestrictionsNonNull(UserHandle.USER_ALL) 4749 .putBoolean(UserManager.ENSURE_VERIFY_APPS, true); 4750 } 4751 } 4752 // DISALLOW_CONFIG_WIFI was made a default guest restriction some time during version 6. 4753 final List<UserInfo> guestUsers = getGuestUsers(); 4754 for (int i = 0; i < guestUsers.size(); i++) { 4755 final UserInfo guestUser = guestUsers.get(i); 4756 if (guestUser != null && !hasUserRestriction( 4757 UserManager.DISALLOW_CONFIG_WIFI, guestUser.id)) { 4758 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, guestUser.id); 4759 } 4760 } 4761 userVersion = 7; 4762 } 4763 4764 if (userVersion < 8) { 4765 // Added FLAG_FULL and FLAG_SYSTEM flags. 4766 synchronized (mUsersLock) { 4767 UserData userData = mUsers.get(UserHandle.USER_SYSTEM); 4768 userData.info.flags |= UserInfo.FLAG_SYSTEM; 4769 // We assume that isDefaultHeadlessSystemUserMode() does not change during the OTA 4770 // from userVersion < 8 since it is documented that pre-R devices do not support its 4771 // modification. Therefore, its current value should be the same as the pre-update 4772 // version. 4773 if (!isDefaultHeadlessSystemUserMode()) { 4774 userData.info.flags |= UserInfo.FLAG_FULL; 4775 } 4776 userIdsToWrite.add(userData.info.id); 4777 4778 // Mark FULL all non-profile users except USER_SYSTEM. 4779 // Start index at 1 since USER_SYSTEM is the smallest userId and we're skipping it. 4780 for (int i = 1; i < mUsers.size(); i++) { 4781 userData = mUsers.valueAt(i); 4782 if ((userData.info.flags & UserInfo.FLAG_MANAGED_PROFILE) == 0) { 4783 userData.info.flags |= UserInfo.FLAG_FULL; 4784 userIdsToWrite.add(userData.info.id); 4785 } 4786 } 4787 } 4788 userVersion = 8; 4789 } 4790 4791 if (userVersion < 9) { 4792 // Convert from UserInfo flags to UserTypes. Apply FLAG_PROFILE to FLAG_MANAGED_PROFILE. 4793 synchronized (mUsersLock) { 4794 for (int i = 0; i < mUsers.size(); i++) { 4795 UserData userData = mUsers.valueAt(i); 4796 final int flags = userData.info.flags; 4797 if ((flags & UserInfo.FLAG_SYSTEM) != 0) { 4798 if ((flags & UserInfo.FLAG_FULL) != 0) { 4799 userData.info.userType = UserManager.USER_TYPE_FULL_SYSTEM; 4800 } else { 4801 userData.info.userType = UserManager.USER_TYPE_SYSTEM_HEADLESS; 4802 } 4803 } else { 4804 try { 4805 userData.info.userType = UserInfo.getDefaultUserType(flags); 4806 } catch (IllegalArgumentException e) { 4807 // TODO(b/142482943): What should we do here? Delete user? Crashloop? 4808 throw new IllegalStateException("Cannot upgrade user with flags " 4809 + Integer.toHexString(flags) + " because it doesn't correspond " 4810 + "to a valid user type.", e); 4811 } 4812 } 4813 // OEMs are responsible for their own custom upgrade logic here. 4814 4815 final UserTypeDetails userTypeDetails = mUserTypes.get(userData.info.userType); 4816 if (userTypeDetails == null) { 4817 throw new IllegalStateException( 4818 "Cannot upgrade user with flags " + Integer.toHexString(flags) 4819 + " because " + userData.info.userType + " isn't defined" 4820 + " on this device!"); 4821 } 4822 userData.info.flags |= userTypeDetails.getDefaultUserInfoFlags(); 4823 userIdsToWrite.add(userData.info.id); 4824 } 4825 } 4826 userVersion = 9; 4827 } 4828 4829 if (userVersion < 10) { 4830 // Add UserProperties. 4831 synchronized (mUsersLock) { 4832 for (int i = 0; i < mUsers.size(); i++) { 4833 final UserData userData = mUsers.valueAt(i); 4834 final UserTypeDetails userTypeDetails = mUserTypes.get(userData.info.userType); 4835 if (userTypeDetails == null) { 4836 throw new IllegalStateException( 4837 "Cannot upgrade user because " + userData.info.userType 4838 + " isn't defined on this device!"); 4839 } 4840 userData.userProperties = new UserProperties( 4841 userTypeDetails.getDefaultUserPropertiesReference()); 4842 userIdsToWrite.add(userData.info.id); 4843 } 4844 } 4845 userVersion = 10; 4846 } 4847 4848 if (userVersion < 11) { 4849 // Add FLAG_MAIN 4850 if (isHeadlessSystemUserMode()) { 4851 if (isMainUserPermanentAdmin()) { 4852 final UserInfo earliestCreatedUser = getEarliestCreatedFullUser(); 4853 if (earliestCreatedUser != null) { 4854 earliestCreatedUser.flags |= UserInfo.FLAG_MAIN; 4855 userIdsToWrite.add(earliestCreatedUser.id); 4856 } 4857 } 4858 } else { // not isHeadlessSystemUserMode 4859 synchronized (mUsersLock) { 4860 final UserData userData = mUsers.get(UserHandle.USER_SYSTEM); 4861 userData.info.flags |= UserInfo.FLAG_MAIN; 4862 userIdsToWrite.add(userData.info.id); 4863 } 4864 } 4865 userVersion = 11; 4866 } 4867 4868 // Reminder: If you add another upgrade, make sure to increment USER_VERSION too. 4869 4870 // Done with userVersion changes, moving on to deal with userTypeVersion upgrades 4871 // Upgrade from previous user type to a new user type 4872 final int newUserTypeVersion = UserTypeFactory.getUserTypeVersion(); 4873 if (newUserTypeVersion > userTypeVersion) { 4874 synchronized (mUsersLock) { 4875 upgradeUserTypesLU(UserTypeFactory.getUserTypeUpgrades(), mUserTypes, 4876 userTypeVersion, userIdsToWrite); 4877 } 4878 } 4879 4880 if (userVersion < USER_VERSION) { 4881 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to " 4882 + USER_VERSION); 4883 } else { 4884 if (userVersion > USER_VERSION) { 4885 Slog.wtf(LOG_TAG, "Upgraded user version " + mUserVersion + " is higher the SDK's " 4886 + "one of " + USER_VERSION + ". Someone forgot to update USER_VERSION?"); 4887 } 4888 4889 mUserVersion = userVersion; 4890 mUserTypeVersion = newUserTypeVersion; 4891 4892 if (originalVersion < mUserVersion || originalUserTypeVersion < mUserTypeVersion) { 4893 for (int userId : userIdsToWrite) { 4894 UserData userData = getUserDataNoChecks(userId); 4895 if (userData != null) { 4896 writeUserLP(userData); 4897 } 4898 } 4899 writeUserListLP(); 4900 } 4901 } 4902 } 4903 4904 @GuardedBy("mUsersLock") upgradeUserTypesLU(@onNull List<UserTypeFactory.UserTypeUpgrade> upgradeOps, @NonNull ArrayMap<String, UserTypeDetails> userTypes, final int formerUserTypeVersion, @NonNull Set<Integer> userIdsToWrite)4905 private void upgradeUserTypesLU(@NonNull List<UserTypeFactory.UserTypeUpgrade> upgradeOps, 4906 @NonNull ArrayMap<String, UserTypeDetails> userTypes, 4907 final int formerUserTypeVersion, 4908 @NonNull Set<Integer> userIdsToWrite) { 4909 for (UserTypeFactory.UserTypeUpgrade userTypeUpgrade : upgradeOps) { 4910 if (DBG) { 4911 Slog.i(LOG_TAG, "Upgrade: " + userTypeUpgrade.getFromType() + " to: " 4912 + userTypeUpgrade.getToType() + " maxVersion: " 4913 + userTypeUpgrade.getUpToVersion()); 4914 } 4915 4916 // upgrade user type if version up to getUpToVersion() 4917 if (formerUserTypeVersion <= userTypeUpgrade.getUpToVersion()) { 4918 for (int i = 0; i < mUsers.size(); i++) { 4919 UserData userData = mUsers.valueAt(i); 4920 if (userTypeUpgrade.getFromType().equals(userData.info.userType)) { 4921 final UserTypeDetails newUserType = userTypes.get( 4922 userTypeUpgrade.getToType()); 4923 4924 if (newUserType == null) { 4925 throw new IllegalStateException( 4926 "Upgrade destination user type not defined: " 4927 + userTypeUpgrade.getToType()); 4928 } 4929 4930 upgradeProfileToTypeLU(userData.info, newUserType); 4931 userIdsToWrite.add(userData.info.id); 4932 } 4933 } 4934 } 4935 } 4936 } 4937 4938 /** 4939 * Changes the user type of a profile to a new user type. 4940 * @param userInfo The user to be updated. 4941 * @param newUserType The new user type. 4942 */ 4943 @GuardedBy("mUsersLock") 4944 @VisibleForTesting upgradeProfileToTypeLU(@onNull UserInfo userInfo, @NonNull UserTypeDetails newUserType)4945 void upgradeProfileToTypeLU(@NonNull UserInfo userInfo, @NonNull UserTypeDetails newUserType) { 4946 Slog.i(LOG_TAG, "Upgrading user " + userInfo.id 4947 + " from " + userInfo.userType 4948 + " to " + newUserType.getName()); 4949 4950 if (!userInfo.isProfile()) { 4951 throw new IllegalStateException( 4952 "Can only upgrade profile types. " + userInfo.userType 4953 + " is not a profile type."); 4954 } 4955 4956 // Exceeded maximum profiles for parent user: log error, but allow upgrade 4957 if (!canAddMoreProfilesToUser(newUserType.getName(), userInfo.profileGroupId, false)) { 4958 Slog.w(LOG_TAG, 4959 "Exceeded maximum profiles of type " + newUserType.getName() + " for user " 4960 + userInfo.id + ". Maximum allowed= " 4961 + newUserType.getMaxAllowedPerParent()); 4962 } 4963 4964 final UserTypeDetails oldUserType = mUserTypes.get(userInfo.userType); 4965 final int oldFlags; 4966 if (oldUserType != null) { 4967 oldFlags = oldUserType.getDefaultUserInfoFlags(); 4968 } else { 4969 // if oldUserType is missing from config_user_types.xml -> can only assume FLAG_PROFILE 4970 oldFlags = UserInfo.FLAG_PROFILE; 4971 } 4972 4973 //convert userData to newUserType 4974 userInfo.userType = newUserType.getName(); 4975 // remove old default flags and add newUserType's default flags 4976 userInfo.flags = newUserType.getDefaultUserInfoFlags() | (userInfo.flags ^ oldFlags); 4977 4978 // merge existing base restrictions with the new type's default restrictions 4979 synchronized (mRestrictionsLock) { 4980 if (!BundleUtils.isEmpty(newUserType.getDefaultRestrictions())) { 4981 final Bundle newRestrictions = BundleUtils.clone( 4982 mBaseUserRestrictions.getRestrictions(userInfo.id)); 4983 UserRestrictionsUtils.merge(newRestrictions, 4984 newUserType.getDefaultRestrictions()); 4985 updateUserRestrictionsInternalLR(newRestrictions, userInfo.id); 4986 if (DBG) { 4987 Slog.i(LOG_TAG, "Updated user " + userInfo.id 4988 + " restrictions to " + newRestrictions); 4989 } 4990 } 4991 } 4992 4993 // re-compute badge index 4994 userInfo.profileBadge = getFreeProfileBadgeLU(userInfo.profileGroupId, userInfo.userType); 4995 } 4996 4997 /** Returns the oldest Full Admin user, or null is if there none. */ getEarliestCreatedFullUser()4998 private @Nullable UserInfo getEarliestCreatedFullUser() { 4999 final List<UserInfo> users = getUsersInternal(true, true, true); 5000 UserInfo earliestUser = null; 5001 long earliestCreationTime = Long.MAX_VALUE; 5002 for (int i = 0; i < users.size(); i++) { 5003 final UserInfo info = users.get(i); 5004 if (info.isFull() && info.isAdmin() && info.creationTime >= 0 5005 && info.creationTime < earliestCreationTime) { 5006 earliestCreationTime = info.creationTime; 5007 earliestUser = info; 5008 } 5009 } 5010 return earliestUser; 5011 } 5012 5013 @GuardedBy({"mPackagesLock"}) fallbackToSingleUserLP()5014 private void fallbackToSingleUserLP() { 5015 // Create the system user 5016 final String systemUserType = isDefaultHeadlessSystemUserMode() 5017 ? UserManager.USER_TYPE_SYSTEM_HEADLESS 5018 : UserManager.USER_TYPE_FULL_SYSTEM; 5019 final int flags = mUserTypes.get(systemUserType).getDefaultUserInfoFlags() 5020 | UserInfo.FLAG_INITIALIZED; 5021 final UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, 5022 /* name= */ null, /* iconPath= */ null, flags, systemUserType); 5023 final UserData userData = putUserInfo(system); 5024 userData.userProperties = new UserProperties( 5025 mUserTypes.get(userData.info.userType).getDefaultUserPropertiesReference()); 5026 mNextSerialNumber = MIN_USER_ID; 5027 mUserVersion = USER_VERSION; 5028 mUserTypeVersion = UserTypeFactory.getUserTypeVersion(); 5029 5030 final Bundle restrictions = new Bundle(); 5031 try { 5032 final String[] defaultFirstUserRestrictions = getContextResources().getStringArray( 5033 com.android.internal.R.array.config_defaultFirstUserRestrictions); 5034 for (String userRestriction : defaultFirstUserRestrictions) { 5035 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) { 5036 restrictions.putBoolean(userRestriction, true); 5037 } 5038 } 5039 } catch (Resources.NotFoundException e) { 5040 Slog.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e); 5041 } 5042 5043 if (!restrictions.isEmpty()) { 5044 synchronized (mRestrictionsLock) { 5045 mBaseUserRestrictions.updateRestrictions(UserHandle.USER_SYSTEM, 5046 restrictions); 5047 } 5048 } 5049 5050 initDefaultGuestRestrictions(); 5051 5052 writeUserLP(userData); 5053 writeUserListLP(); 5054 } 5055 getOwnerName()5056 private String getOwnerName() { 5057 return mOwnerName.get(); 5058 } 5059 getGuestName()5060 private String getGuestName() { 5061 return mContext.getString(com.android.internal.R.string.guest_name); 5062 } 5063 invalidateOwnerNameIfNecessary(@onNull Resources res, boolean forceUpdate)5064 private void invalidateOwnerNameIfNecessary(@NonNull Resources res, boolean forceUpdate) { 5065 final int configChanges = mLastConfiguration.updateFrom(res.getConfiguration()); 5066 if (forceUpdate || (configChanges & mOwnerNameTypedValue.changingConfigurations) != 0) { 5067 res.getValue(com.android.internal.R.string.owner_name, mOwnerNameTypedValue, true); 5068 final CharSequence ownerName = mOwnerNameTypedValue.coerceToString(); 5069 mOwnerName.set(ownerName != null ? ownerName.toString() : null); 5070 // Invalidate when owners name changes due to config change. 5071 UserManager.invalidateCacheOnUserDataChanged(); 5072 } 5073 5074 } 5075 scheduleWriteUserList()5076 private void scheduleWriteUserList() { 5077 if (DBG) { 5078 debug("scheduleWriteUserList"); 5079 } 5080 // No need to wrap it within a lock -- worst case, we'll just post the same message 5081 // twice. 5082 if (!mHandler.hasMessages(WRITE_USER_LIST_MSG)) { 5083 Message msg = mHandler.obtainMessage(WRITE_USER_LIST_MSG); 5084 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY); 5085 } 5086 // Invalidate cache when {@link UserData} changed, but write was scheduled for later. 5087 UserManager.invalidateCacheOnUserDataChanged(); 5088 } 5089 scheduleWriteUser(@serIdInt int userId)5090 private void scheduleWriteUser(@UserIdInt int userId) { 5091 if (DBG) { 5092 debug("scheduleWriteUser"); 5093 } 5094 // No need to wrap it within a lock -- worst case, we'll just post the same message 5095 // twice. 5096 if (!mHandler.hasMessages(WRITE_USER_MSG, userId)) { 5097 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userId); 5098 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY); 5099 } 5100 // Invalidate cache when {@link Data} changed, but write was scheduled for later. 5101 UserManager.invalidateCacheOnUserDataChanged(); 5102 } 5103 getUserFile(int userId)5104 private ResilientAtomicFile getUserFile(int userId) { 5105 File file = new File(mUsersDir, userId + XML_SUFFIX); 5106 File tempBackup = new File(mUsersDir, userId + XML_SUFFIX + ".backup"); 5107 File reserveCopy = new File(mUsersDir, userId + XML_SUFFIX + ".reservecopy"); 5108 int fileMode = FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IXOTH; 5109 return new ResilientAtomicFile(file, tempBackup, reserveCopy, fileMode, 5110 "user info", (priority, msg) -> { 5111 Slog.e(LOG_TAG, msg); 5112 // Something went wrong, schedule full rewrite. 5113 UserData userData = getUserDataNoChecks(userId); 5114 if (userData != null) { 5115 scheduleWriteUser(userId); 5116 } 5117 }); 5118 } 5119 5120 @GuardedBy({"mPackagesLock"}) 5121 private void writeUserLP(UserData userData) { 5122 if (DBG) { 5123 debug("writeUserLP " + userData); 5124 } 5125 // invalidate caches related to any {@link UserData} change. 5126 UserManager.invalidateCacheOnUserDataChanged(); 5127 5128 try (ResilientAtomicFile userFile = getUserFile(userData.info.id)) { 5129 FileOutputStream fos = null; 5130 try { 5131 fos = userFile.startWrite(); 5132 writeUserLP(userData, fos); 5133 userFile.finishWrite(fos); 5134 } catch (Exception ioe) { 5135 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe); 5136 userFile.failWrite(fos); 5137 } 5138 } 5139 } 5140 5141 /* 5142 * Writes the user file in this format: 5143 * 5144 * <user flags="20039023" id="0"> 5145 * <name>Primary</name> 5146 * </user> 5147 */ 5148 @GuardedBy({"mPackagesLock"}) 5149 @VisibleForTesting 5150 void writeUserLP(UserData userData, OutputStream os) 5151 throws IOException, XmlPullParserException { 5152 final TypedXmlSerializer serializer = Xml.resolveSerializer(os); 5153 serializer.startDocument(null, true); 5154 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 5155 5156 final UserInfo userInfo = userData.info; 5157 serializer.startTag(null, TAG_USER); 5158 serializer.attributeInt(null, ATTR_ID, userInfo.id); 5159 serializer.attributeInt(null, ATTR_SERIAL_NO, userInfo.serialNumber); 5160 serializer.attributeInt(null, ATTR_FLAGS, userInfo.flags); 5161 serializer.attribute(null, ATTR_TYPE, userInfo.userType); 5162 serializer.attributeLong(null, ATTR_CREATION_TIME, userInfo.creationTime); 5163 serializer.attributeLong(null, ATTR_LAST_LOGGED_IN_TIME, userInfo.lastLoggedInTime); 5164 if (userInfo.lastLoggedInFingerprint != null) { 5165 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT, 5166 userInfo.lastLoggedInFingerprint); 5167 } 5168 serializer.attributeLong( 5169 null, ATTR_LAST_ENTERED_FOREGROUND_TIME, userData.mLastEnteredForegroundTimeMillis); 5170 if (userInfo.iconPath != null) { 5171 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath); 5172 } 5173 if (userInfo.partial) { 5174 serializer.attributeBoolean(null, ATTR_PARTIAL, true); 5175 } 5176 if (userInfo.preCreated) { 5177 serializer.attributeBoolean(null, ATTR_PRE_CREATED, true); 5178 } 5179 if (userInfo.convertedFromPreCreated) { 5180 serializer.attributeBoolean(null, ATTR_CONVERTED_FROM_PRE_CREATED, true); 5181 } 5182 if (userInfo.guestToRemove) { 5183 serializer.attributeBoolean(null, ATTR_GUEST_TO_REMOVE, true); 5184 } 5185 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 5186 serializer.attributeInt(null, ATTR_PROFILE_GROUP_ID, userInfo.profileGroupId); 5187 } 5188 serializer.attributeInt(null, ATTR_PROFILE_BADGE, userInfo.profileBadge); 5189 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) { 5190 serializer.attributeInt(null, ATTR_RESTRICTED_PROFILE_PARENT_ID, 5191 userInfo.restrictedProfileParentId); 5192 } 5193 // Write seed data 5194 if (userData.persistSeedData) { 5195 if (userData.seedAccountName != null) { 5196 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, 5197 truncateString(userData.seedAccountName, 5198 UserManager.MAX_ACCOUNT_STRING_LENGTH)); 5199 } 5200 if (userData.seedAccountType != null) { 5201 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, 5202 truncateString(userData.seedAccountType, 5203 UserManager.MAX_ACCOUNT_STRING_LENGTH)); 5204 } 5205 } 5206 if (userInfo.name != null) { 5207 serializer.startTag(null, TAG_NAME); 5208 serializer.text(truncateString(userInfo.name, UserManager.MAX_USER_NAME_LENGTH)); 5209 serializer.endTag(null, TAG_NAME); 5210 } 5211 synchronized (mRestrictionsLock) { 5212 UserRestrictionsUtils.writeRestrictions(serializer, 5213 mBaseUserRestrictions.getRestrictions(userInfo.id), TAG_RESTRICTIONS); 5214 5215 if (Flags.saveGlobalAndGuestRestrictionsOnSystemUserXmlReadOnly()) { 5216 if (userInfo.id == UserHandle.USER_SYSTEM) { 5217 UserRestrictionsUtils.writeRestrictions(serializer, 5218 mDevicePolicyUserRestrictions.getRestrictions(UserHandle.USER_ALL), 5219 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS); 5220 5221 serializer.startTag(null, TAG_GUEST_RESTRICTIONS); 5222 synchronized (mGuestRestrictions) { 5223 UserRestrictionsUtils.writeRestrictions(serializer, mGuestRestrictions, 5224 TAG_RESTRICTIONS); 5225 } 5226 serializer.endTag(null, TAG_GUEST_RESTRICTIONS); 5227 } 5228 } else { 5229 UserRestrictionsUtils.writeRestrictions(serializer, 5230 mDevicePolicyUserRestrictions.getRestrictions(UserHandle.USER_ALL), 5231 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS); 5232 } 5233 5234 UserRestrictionsUtils.writeRestrictions(serializer, 5235 mDevicePolicyUserRestrictions.getRestrictions(userInfo.id), 5236 TAG_DEVICE_POLICY_LOCAL_RESTRICTIONS); 5237 } 5238 5239 if (userData.account != null) { 5240 serializer.startTag(null, TAG_ACCOUNT); 5241 serializer.text(userData.account); 5242 serializer.endTag(null, TAG_ACCOUNT); 5243 } 5244 5245 if (userData.persistSeedData && userData.seedAccountOptions != null) { 5246 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS); 5247 userData.seedAccountOptions.saveToXml(serializer); 5248 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS); 5249 } 5250 5251 if (userData.userProperties != null) { 5252 serializer.startTag(null, TAG_USER_PROPERTIES); 5253 userData.userProperties.writeToXml(serializer); 5254 serializer.endTag(null, TAG_USER_PROPERTIES); 5255 } 5256 5257 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) { 5258 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL); 5259 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis())); 5260 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL); 5261 } 5262 5263 serializer.startTag(/* namespace */ null, TAG_IGNORE_PREPARE_STORAGE_ERRORS); 5264 serializer.text(String.valueOf(userData.getIgnorePrepareStorageErrors())); 5265 serializer.endTag(/* namespace */ null, TAG_IGNORE_PREPARE_STORAGE_ERRORS); 5266 5267 serializer.endTag(null, TAG_USER); 5268 5269 serializer.endDocument(); 5270 } 5271 5272 private String truncateString(String original, int limit) { 5273 if (original == null || original.length() <= limit) { 5274 return original; 5275 } 5276 return original.substring(0, limit); 5277 } 5278 5279 /* 5280 * Writes the user list file in this format: 5281 * 5282 * <users nextSerialNumber="3"> 5283 * <user id="0"></user> 5284 * <user id="2"></user> 5285 * </users> 5286 */ 5287 @GuardedBy({"mPackagesLock"}) 5288 private void writeUserListLP() { 5289 if (DBG) { 5290 debug("writeUserList"); 5291 } 5292 // invalidate caches related to any {@link UserData} change. 5293 UserManager.invalidateCacheOnUserDataChanged(); 5294 5295 try (ResilientAtomicFile file = getUserListFile()) { 5296 FileOutputStream fos = null; 5297 try { 5298 fos = file.startWrite(); 5299 5300 final TypedXmlSerializer serializer = Xml.resolveSerializer(fos); 5301 serializer.startDocument(null, true); 5302 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", 5303 true); 5304 5305 serializer.startTag(null, TAG_USERS); 5306 serializer.attributeInt(null, ATTR_NEXT_SERIAL_NO, mNextSerialNumber); 5307 serializer.attributeInt(null, ATTR_USER_VERSION, mUserVersion); 5308 serializer.attributeInt(null, ATTR_USER_TYPE_VERSION, mUserTypeVersion); 5309 5310 if (!Flags.saveGlobalAndGuestRestrictionsOnSystemUserXmlReadOnly()) { 5311 serializer.startTag(null, TAG_GUEST_RESTRICTIONS); 5312 synchronized (mGuestRestrictions) { 5313 UserRestrictionsUtils 5314 .writeRestrictions(serializer, mGuestRestrictions, 5315 TAG_RESTRICTIONS); 5316 } 5317 serializer.endTag(null, TAG_GUEST_RESTRICTIONS); 5318 } 5319 int[] userIdsToWrite; 5320 synchronized (mUsersLock) { 5321 userIdsToWrite = new int[mUsers.size()]; 5322 for (int i = 0; i < userIdsToWrite.length; i++) { 5323 UserInfo user = mUsers.valueAt(i).info; 5324 userIdsToWrite[i] = user.id; 5325 } 5326 } 5327 for (int id : userIdsToWrite) { 5328 serializer.startTag(null, TAG_USER); 5329 serializer.attributeInt(null, ATTR_ID, id); 5330 serializer.endTag(null, TAG_USER); 5331 } 5332 5333 serializer.endTag(null, TAG_USERS); 5334 5335 serializer.endDocument(); 5336 file.finishWrite(fos); 5337 } catch (Exception e) { 5338 Slog.e(LOG_TAG, "Error writing user list", e); 5339 file.failWrite(fos); 5340 } 5341 } 5342 } 5343 5344 @GuardedBy({"mPackagesLock"}) 5345 private UserData readUserLP(int id, int userVersion) { 5346 try (ResilientAtomicFile file = getUserFile(id)) { 5347 FileInputStream fis = null; 5348 try { 5349 fis = file.openRead(); 5350 if (fis == null) { 5351 Slog.e(LOG_TAG, "User info not found, returning null, user id: " + id); 5352 return null; 5353 } 5354 return readUserLP(id, fis, userVersion); 5355 } catch (Exception e) { 5356 // Remove corrupted file and retry. 5357 Slog.e(LOG_TAG, "Error reading user info, user id: " + id); 5358 file.failRead(fis, e); 5359 return readUserLP(id, userVersion); 5360 } 5361 } 5362 } 5363 5364 @GuardedBy({"mPackagesLock"}) 5365 @VisibleForTesting 5366 UserData readUserLP(int id, InputStream is, int userVersion) throws IOException, 5367 XmlPullParserException { 5368 int flags = 0; 5369 String userType = null; 5370 int serialNumber = id; 5371 String name = null; 5372 String account = null; 5373 String iconPath = null; 5374 long creationTime = 0L; 5375 long lastLoggedInTime = 0L; 5376 long lastRequestQuietModeEnabledTimestamp = 0L; 5377 String lastLoggedInFingerprint = null; 5378 long lastEnteredForegroundTime = 0L; 5379 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID; 5380 int profileBadge = 0; 5381 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID; 5382 boolean partial = false; 5383 boolean preCreated = false; 5384 boolean converted = false; 5385 boolean guestToRemove = false; 5386 boolean persistSeedData = false; 5387 String seedAccountName = null; 5388 String seedAccountType = null; 5389 PersistableBundle seedAccountOptions = null; 5390 UserProperties userProperties = null; 5391 Bundle baseRestrictions = null; 5392 Bundle legacyLocalRestrictions = null; 5393 Bundle localRestrictions = null; 5394 Bundle globalRestrictions = null; 5395 boolean ignorePrepareStorageErrors = true; // default is true for old users 5396 5397 final TypedXmlPullParser parser = Xml.resolvePullParser(is); 5398 int type; 5399 while ((type = parser.next()) != XmlPullParser.START_TAG 5400 && type != XmlPullParser.END_DOCUMENT) { 5401 // Skip 5402 } 5403 5404 if (type != XmlPullParser.START_TAG) { 5405 Slog.e(LOG_TAG, "Unable to read user " + id); 5406 return null; 5407 } 5408 5409 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) { 5410 int storedId = parser.getAttributeInt(null, ATTR_ID, -1); 5411 if (storedId != id) { 5412 Slog.e(LOG_TAG, "User id does not match the file name"); 5413 return null; 5414 } 5415 serialNumber = parser.getAttributeInt(null, ATTR_SERIAL_NO, id); 5416 flags = parser.getAttributeInt(null, ATTR_FLAGS, 0); 5417 userType = parser.getAttributeValue(null, ATTR_TYPE); 5418 userType = userType != null ? userType.intern() : null; 5419 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH); 5420 creationTime = parser.getAttributeLong(null, ATTR_CREATION_TIME, 0); 5421 lastLoggedInTime = parser.getAttributeLong(null, ATTR_LAST_LOGGED_IN_TIME, 0); 5422 lastLoggedInFingerprint = parser.getAttributeValue(null, 5423 ATTR_LAST_LOGGED_IN_FINGERPRINT); 5424 lastEnteredForegroundTime = 5425 parser.getAttributeLong(null, ATTR_LAST_ENTERED_FOREGROUND_TIME, 0L); 5426 profileGroupId = parser.getAttributeInt(null, ATTR_PROFILE_GROUP_ID, 5427 UserInfo.NO_PROFILE_GROUP_ID); 5428 profileBadge = parser.getAttributeInt(null, ATTR_PROFILE_BADGE, 0); 5429 restrictedProfileParentId = parser.getAttributeInt(null, 5430 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID); 5431 partial = parser.getAttributeBoolean(null, ATTR_PARTIAL, false); 5432 preCreated = parser.getAttributeBoolean(null, ATTR_PRE_CREATED, false); 5433 converted = parser.getAttributeBoolean(null, ATTR_CONVERTED_FROM_PRE_CREATED, false); 5434 guestToRemove = parser.getAttributeBoolean(null, ATTR_GUEST_TO_REMOVE, false); 5435 5436 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME); 5437 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE); 5438 if (seedAccountName != null || seedAccountType != null) { 5439 persistSeedData = true; 5440 } 5441 5442 int outerDepth = parser.getDepth(); 5443 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 5444 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 5445 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 5446 continue; 5447 } 5448 String tag = parser.getName(); 5449 if (TAG_NAME.equals(tag)) { 5450 type = parser.next(); 5451 if (type == XmlPullParser.TEXT) { 5452 name = parser.getText(); 5453 } 5454 } else if (TAG_RESTRICTIONS.equals(tag)) { 5455 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser); 5456 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) { 5457 legacyLocalRestrictions = UserRestrictionsUtils.readRestrictions(parser); 5458 } else if (TAG_DEVICE_POLICY_LOCAL_RESTRICTIONS.equals(tag)) { 5459 if (userVersion < 10) { 5460 // Prior to version 10, the local user restrictions were stored as sub tags 5461 // grouped by the user id of the source user. The source is no longer stored 5462 // on versions 10+ as this is now stored in the DevicePolicyEngine. 5463 RestrictionsSet oldLocalRestrictions = 5464 RestrictionsSet.readRestrictions( 5465 parser, TAG_DEVICE_POLICY_LOCAL_RESTRICTIONS); 5466 localRestrictions = oldLocalRestrictions.mergeAll(); 5467 } else { 5468 localRestrictions = UserRestrictionsUtils.readRestrictions(parser); 5469 } 5470 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) { 5471 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser); 5472 } else if (TAG_GUEST_RESTRICTIONS.equals(tag)) { 5473 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 5474 && type != XmlPullParser.END_TAG) { 5475 if (type == XmlPullParser.START_TAG) { 5476 if (parser.getName().equals(TAG_RESTRICTIONS)) { 5477 synchronized (mGuestRestrictions) { 5478 UserRestrictionsUtils 5479 .readRestrictions(parser, mGuestRestrictions); 5480 } 5481 } 5482 break; 5483 } 5484 } 5485 } else if (TAG_ACCOUNT.equals(tag)) { 5486 type = parser.next(); 5487 if (type == XmlPullParser.TEXT) { 5488 account = parser.getText(); 5489 } 5490 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) { 5491 seedAccountOptions = PersistableBundle.restoreFromXml(parser); 5492 persistSeedData = true; 5493 } else if (TAG_USER_PROPERTIES.equals(tag)) { 5494 // We already got the userType above (if it exists), so we can use it. 5495 // And it must exist, since ATTR_TYPE historically predates PROPERTIES. 5496 final UserTypeDetails userTypeDetails = mUserTypes.get(userType); 5497 if (userTypeDetails == null) { 5498 Slog.e(LOG_TAG, "User has properties but no user type!"); 5499 return null; 5500 } 5501 final UserProperties defaultProps 5502 = userTypeDetails.getDefaultUserPropertiesReference(); 5503 userProperties = new UserProperties(parser, defaultProps); 5504 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) { 5505 type = parser.next(); 5506 if (type == XmlPullParser.TEXT) { 5507 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText()); 5508 } 5509 } else if (TAG_IGNORE_PREPARE_STORAGE_ERRORS.equals(tag)) { 5510 type = parser.next(); 5511 if (type == XmlPullParser.TEXT) { 5512 ignorePrepareStorageErrors = Boolean.parseBoolean(parser.getText()); 5513 } 5514 } 5515 } 5516 } 5517 5518 // Create the UserInfo object that gets passed around 5519 UserInfo userInfo = new UserInfo(id, name, iconPath, flags, userType); 5520 userInfo.serialNumber = serialNumber; 5521 userInfo.creationTime = creationTime; 5522 userInfo.lastLoggedInTime = lastLoggedInTime; 5523 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint; 5524 userInfo.partial = partial; 5525 userInfo.preCreated = preCreated; 5526 userInfo.convertedFromPreCreated = converted; 5527 userInfo.guestToRemove = guestToRemove; 5528 userInfo.profileGroupId = profileGroupId; 5529 userInfo.profileBadge = profileBadge; 5530 userInfo.restrictedProfileParentId = restrictedProfileParentId; 5531 5532 // Create the UserData object that's internal to this class 5533 UserData userData = new UserData(); 5534 userData.info = userInfo; 5535 userData.account = account; 5536 userData.seedAccountName = seedAccountName; 5537 userData.seedAccountType = seedAccountType; 5538 userData.persistSeedData = persistSeedData; 5539 userData.seedAccountOptions = seedAccountOptions; 5540 userData.userProperties = userProperties; 5541 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp); 5542 userData.mLastEnteredForegroundTimeMillis = lastEnteredForegroundTime; 5543 if (ignorePrepareStorageErrors) { 5544 userData.setIgnorePrepareStorageErrors(); 5545 } 5546 5547 synchronized (mRestrictionsLock) { 5548 if (baseRestrictions != null) { 5549 mBaseUserRestrictions.updateRestrictions(id, baseRestrictions); 5550 } 5551 if (localRestrictions != null) { 5552 mDevicePolicyUserRestrictions.updateRestrictions(id, localRestrictions); 5553 if (legacyLocalRestrictions != null) { 5554 Slog.wtf(LOG_TAG, "Seeing both legacy and current local restrictions in xml"); 5555 } 5556 } else if (legacyLocalRestrictions != null) { 5557 mDevicePolicyUserRestrictions.updateRestrictions(id, legacyLocalRestrictions); 5558 } 5559 if (globalRestrictions != null) { 5560 mDevicePolicyUserRestrictions.updateRestrictions(UserHandle.USER_ALL, 5561 globalRestrictions); 5562 } 5563 } 5564 return userData; 5565 } 5566 5567 /** 5568 * Removes the app restrictions file for a specific package and user id, if it exists. 5569 * 5570 * @return whether there were any restrictions. 5571 */ 5572 @GuardedBy({"mAppRestrictionsLock"}) 5573 private static boolean cleanAppRestrictionsForPackageLAr(String pkg, @UserIdInt int userId) { 5574 final File dir = Environment.getUserSystemDirectory(userId); 5575 final File resFile = new File(dir, packageToRestrictionsFileName(pkg)); 5576 if (resFile.exists()) { 5577 resFile.delete(); 5578 return true; 5579 } 5580 return false; 5581 } 5582 5583 /** 5584 * Creates a profile user. Used for actual profiles, like 5585 * {@link UserManager#USER_TYPE_PROFILE_MANAGED}, 5586 * as well as for {@link UserManager#USER_TYPE_FULL_RESTRICTED}. 5587 */ 5588 @Override 5589 public @NonNull UserInfo createProfileForUserWithThrow( 5590 @Nullable String name, @NonNull String userType, @UserInfoFlag int flags, 5591 @UserIdInt int userId, @Nullable String[] disallowedPackages) 5592 throws ServiceSpecificException { 5593 5594 checkCreateUsersPermission(flags); 5595 try { 5596 return createUserInternal(name, userType, flags, userId, disallowedPackages); 5597 } catch (UserManager.CheckedUserOperationException e) { 5598 throw e.toServiceSpecificException(); 5599 } 5600 } 5601 5602 /** 5603 * @see #createProfileForUser 5604 */ 5605 @Override 5606 public @NonNull UserInfo createProfileForUserEvenWhenDisallowedWithThrow( 5607 @Nullable String name, @NonNull String userType, @UserInfoFlag int flags, 5608 @UserIdInt int userId, @Nullable String[] disallowedPackages) 5609 throws ServiceSpecificException { 5610 5611 checkCreateUsersPermission(flags); 5612 try { 5613 return createUserInternalUnchecked(name, userType, flags, userId, 5614 /* preCreate= */ false, disallowedPackages, /* token= */ null); 5615 } catch (UserManager.CheckedUserOperationException e) { 5616 throw e.toServiceSpecificException(); 5617 } 5618 } 5619 5620 @Override 5621 public @NonNull UserInfo createUserWithThrow( 5622 @Nullable String name, @NonNull String userType, @UserInfoFlag int flags) 5623 throws ServiceSpecificException { 5624 5625 checkCreateUsersPermission(flags); 5626 try { 5627 return createUserInternal(name, userType, flags, UserHandle.USER_NULL, 5628 /* disallowedPackages= */ null); 5629 } catch (UserManager.CheckedUserOperationException e) { 5630 throw e.toServiceSpecificException(); 5631 } 5632 } 5633 5634 @Override 5635 public @NonNull UserInfo preCreateUserWithThrow( 5636 @NonNull String userType) 5637 throws ServiceSpecificException { 5638 5639 final UserTypeDetails userTypeDetails = mUserTypes.get(userType); 5640 final int flags = userTypeDetails != null ? userTypeDetails.getDefaultUserInfoFlags() : 0; 5641 5642 checkCreateUsersPermission(flags); 5643 5644 Preconditions.checkArgument(isUserTypeEligibleForPreCreation(userTypeDetails), 5645 "cannot pre-create user of type " + userType); 5646 Slog.i(LOG_TAG, "Pre-creating user of type " + userType); 5647 5648 try { 5649 return createUserInternalUnchecked(/* name= */ null, userType, flags, 5650 /* parentId= */ UserHandle.USER_NULL, /* preCreate= */ true, 5651 /* disallowedPackages= */ null, /* token= */ null); 5652 } catch (UserManager.CheckedUserOperationException e) { 5653 throw e.toServiceSpecificException(); 5654 } 5655 } 5656 5657 @Override 5658 public @NonNull UserHandle createUserWithAttributes( 5659 @Nullable String userName, @NonNull String userType, @UserInfoFlag int flags, 5660 @Nullable Bitmap userIcon, @Nullable String accountName, @Nullable String accountType, 5661 @Nullable PersistableBundle accountOptions) 5662 throws ServiceSpecificException { 5663 5664 checkCreateUsersPermission(flags); 5665 5666 if (someUserHasAccountNoChecks(accountName, accountType)) { 5667 throw new ServiceSpecificException( 5668 UserManager.USER_OPERATION_ERROR_USER_ACCOUNT_ALREADY_EXISTS); 5669 } 5670 5671 UserInfo userInfo; 5672 try { 5673 userInfo = createUserInternal(userName, userType, flags, UserHandle.USER_NULL, null); 5674 } catch (UserManager.CheckedUserOperationException e) { 5675 throw e.toServiceSpecificException(); 5676 } 5677 5678 if (userIcon != null) { 5679 mLocalService.setUserIcon(userInfo.id, userIcon); 5680 } 5681 5682 setSeedAccountDataNoChecks(userInfo.id, accountName, accountType, accountOptions, true); 5683 5684 return userInfo.getUserHandle(); 5685 } 5686 5687 private @NonNull UserInfo createUserInternal( 5688 @Nullable String name, @NonNull String userType, 5689 @UserInfoFlag int flags, @CanBeNULL @UserIdInt int parentId, 5690 @Nullable String[] disallowedPackages) 5691 throws UserManager.CheckedUserOperationException { 5692 5693 // Checking user restriction before creating new user, 5694 // default check is for DISALLOW_ADD_USER 5695 // If new user is of type CLONE, check if creation of clone profile is allowed 5696 // If new user is of type MANAGED, check if creation of managed profile is allowed 5697 // If new user is of type PRIVATE, check if creation of private profile is allowed 5698 String restriction = UserManager.DISALLOW_ADD_USER; 5699 if (UserManager.isUserTypeCloneProfile(userType)) { 5700 restriction = UserManager.DISALLOW_ADD_CLONE_PROFILE; 5701 } else if (UserManager.isUserTypeManagedProfile(userType)) { 5702 restriction = UserManager.DISALLOW_ADD_MANAGED_PROFILE; 5703 } else if (UserManager.isUserTypePrivateProfile(userType)) { 5704 restriction = UserManager.DISALLOW_ADD_PRIVATE_PROFILE; 5705 } 5706 5707 enforceUserRestriction(restriction, UserHandle.getCallingUserId(), 5708 "Cannot add user"); 5709 if (Flags.unicornModeRefactoringForHsumReadOnly()) { 5710 if ((flags & UserInfo.FLAG_ADMIN) != 0) { 5711 enforceUserRestriction(UserManager.DISALLOW_GRANT_ADMIN, 5712 UserHandle.getCallingUserId(), "Cannot create ADMIN user"); 5713 } 5714 } 5715 5716 return createUserInternalUnchecked(name, userType, flags, parentId, 5717 /* preCreate= */ false, disallowedPackages, /* token= */ null); 5718 } 5719 5720 private @NonNull UserInfo createUserInternalUnchecked( 5721 @Nullable String name, @NonNull String userType, @UserInfoFlag int flags, 5722 @CanBeNULL @UserIdInt int parentId, boolean preCreate, 5723 @Nullable String[] disallowedPackages, @Nullable Object token) 5724 throws UserManager.CheckedUserOperationException { 5725 5726 final int noneUserId = -1; 5727 final TimingsTraceAndSlog t = new TimingsTraceAndSlog(); 5728 t.traceBegin("createUser-" + flags); 5729 mUserJourneyLogger.logUserJourneyBegin(noneUserId, USER_JOURNEY_USER_CREATE); 5730 UserInfo newUser = null; 5731 try { 5732 newUser = createUserInternalUncheckedNoTracing(name, userType, flags, parentId, 5733 preCreate, disallowedPackages, t, token); 5734 return newUser; 5735 } finally { 5736 if (newUser != null) { 5737 mUserJourneyLogger.logUserCreateJourneyFinish(getCurrentUserId(), newUser); 5738 } else { 5739 mUserJourneyLogger.logNullUserJourneyError( 5740 USER_JOURNEY_USER_CREATE, 5741 getCurrentUserId(), noneUserId, userType, flags); 5742 } 5743 t.traceEnd(); 5744 } 5745 } 5746 5747 private @NonNull UserInfo createUserInternalUncheckedNoTracing( 5748 @Nullable String name, @NonNull String userType, @UserInfoFlag int flags, 5749 @UserIdInt int parentId, boolean preCreate, @Nullable String[] disallowedPackages, 5750 @NonNull TimingsTraceAndSlog t, @Nullable Object token) 5751 throws UserManager.CheckedUserOperationException { 5752 String truncatedName = truncateString(name, UserManager.MAX_USER_NAME_LENGTH); 5753 final UserTypeDetails userTypeDetails = mUserTypes.get(userType); 5754 if (userTypeDetails == null) { 5755 throwCheckedUserOperationException( 5756 "Cannot create user of invalid user type: " + userType, 5757 USER_OPERATION_ERROR_UNKNOWN); 5758 } 5759 userType = userType.intern(); // Now that we know it's valid, we can intern it. 5760 flags |= userTypeDetails.getDefaultUserInfoFlags(); 5761 if (!checkUserTypeConsistency(flags)) { 5762 throwCheckedUserOperationException( 5763 "Cannot add user. Flags (" + Integer.toHexString(flags) 5764 + ") and userTypeDetails (" + userType + ") are inconsistent.", 5765 USER_OPERATION_ERROR_UNKNOWN); 5766 } 5767 if ((flags & UserInfo.FLAG_SYSTEM) != 0) { 5768 throwCheckedUserOperationException( 5769 "Cannot add user. Flags (" + Integer.toHexString(flags) 5770 + ") indicated SYSTEM user, which cannot be created.", 5771 USER_OPERATION_ERROR_UNKNOWN); 5772 } 5773 if (!isUserTypeEnabled(userTypeDetails)) { 5774 throwCheckedUserOperationException( 5775 "Cannot add a user of disabled type " + userType + ".", 5776 UserManager.USER_OPERATION_ERROR_DISABLED_USER); 5777 } 5778 5779 synchronized (mUsersLock) { 5780 if (mForceEphemeralUsers) { 5781 flags |= UserInfo.FLAG_EPHEMERAL; 5782 } 5783 } 5784 5785 // Try to use a pre-created user (if available). 5786 if (!preCreate && parentId < 0 && isUserTypeEligibleForPreCreation(userTypeDetails)) { 5787 final UserInfo preCreatedUser = convertPreCreatedUserIfPossible(userType, flags, 5788 truncatedName, token); 5789 if (preCreatedUser != null) { 5790 return preCreatedUser; 5791 } 5792 } 5793 5794 DeviceStorageMonitorInternal dsm = LocalServices 5795 .getService(DeviceStorageMonitorInternal.class); 5796 if (dsm.isMemoryLow()) { 5797 throwCheckedUserOperationException( 5798 "Cannot add user. Not enough space on disk.", 5799 UserManager.USER_OPERATION_ERROR_LOW_STORAGE); 5800 } 5801 5802 final boolean isMainUser = (flags & UserInfo.FLAG_MAIN) != 0; 5803 final boolean isProfile = userTypeDetails.isProfile(); 5804 final boolean isGuest = UserManager.isUserTypeGuest(userType); 5805 final boolean isRestricted = UserManager.isUserTypeRestricted(userType); 5806 final boolean isDemo = UserManager.isUserTypeDemo(userType); 5807 final boolean isManagedProfile = UserManager.isUserTypeManagedProfile(userType); 5808 final boolean isPrivateProfile = UserManager.isUserTypePrivateProfile(userType); 5809 final boolean requiresProfileParent = userTypeDetails.isProfileParentRequired(); 5810 5811 final long ident = Binder.clearCallingIdentity(); 5812 UserInfo userInfo; 5813 UserData userData; 5814 final int userId; 5815 try { 5816 synchronized (mPackagesLock) { 5817 UserData parent = null; 5818 if (parentId != UserHandle.USER_NULL) { 5819 synchronized (mUsersLock) { 5820 parent = getUserDataLU(parentId); 5821 } 5822 if (parent == null) { 5823 throwCheckedUserOperationException( 5824 "Cannot find user data for parent user " + parentId, 5825 USER_OPERATION_ERROR_UNKNOWN); 5826 } 5827 } 5828 if (isMainUser && getMainUserIdUnchecked() != UserHandle.USER_NULL) { 5829 throwCheckedUserOperationException( 5830 "Cannot add user with FLAG_MAIN as main user already exists.", 5831 UserManager.USER_OPERATION_ERROR_MAX_USERS); 5832 } 5833 if (!preCreate && !canAddMoreUsersOfType(userTypeDetails)) { 5834 throwCheckedUserOperationException( 5835 "Cannot add more users of type " + userType 5836 + ". Maximum number of that type already exists.", 5837 UserManager.USER_OPERATION_ERROR_MAX_USERS); 5838 } 5839 // Keep logic in sync with getRemainingCreatableUserCount() 5840 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) { 5841 // If the user limit has been reached, we cannot add a user (except guest/demo). 5842 // Note that managed profiles can bypass it in certain circumstances (taken 5843 // into account in the profile check below). 5844 throwCheckedUserOperationException( 5845 "Cannot add user. Maximum user limit is reached.", 5846 UserManager.USER_OPERATION_ERROR_MAX_USERS); 5847 } 5848 // TODO(b/142482943): Perhaps let the following code apply to restricted users too. 5849 if (requiresProfileParent && 5850 !canAddMoreProfilesToUser(userType, parentId, false)) { 5851 throwCheckedUserOperationException( 5852 "Cannot add more profiles of type " + userType 5853 + " for user " + parentId, 5854 UserManager.USER_OPERATION_ERROR_MAX_USERS); 5855 } 5856 if (android.multiuser.Flags.blockPrivateSpaceCreation() 5857 && isPrivateProfile && !canAddPrivateProfile(parentId)) { 5858 throwCheckedUserOperationException( 5859 "Cannot add profile of type " + userType + " for user " + parentId, 5860 UserManager.USER_OPERATION_ERROR_PRIVATE_PROFILE); 5861 } 5862 if (isRestricted && (parentId != UserHandle.USER_SYSTEM) 5863 && !isCreationOverrideEnabled()) { 5864 throwCheckedUserOperationException( 5865 "Cannot add restricted profile - parent user must be system", 5866 USER_OPERATION_ERROR_UNKNOWN); 5867 } 5868 5869 userId = getNextAvailableId(); 5870 Slog.i(LOG_TAG, "Creating user " + userId + " of type " + userType); 5871 Environment.getUserSystemDirectory(userId).mkdirs(); 5872 5873 synchronized (mUsersLock) { 5874 // Inherit ephemeral flag from parent. 5875 if (parent != null && parent.info.isEphemeral()) { 5876 flags |= UserInfo.FLAG_EPHEMERAL; 5877 } 5878 5879 // Always clear EPHEMERAL for pre-created users, otherwise the storage key 5880 // won't be persisted. The flag will be re-added (if needed) when the 5881 // pre-created user is "converted" to a normal user. 5882 if (preCreate) { 5883 flags &= ~UserInfo.FLAG_EPHEMERAL; 5884 } 5885 5886 if ((flags & UserInfo.FLAG_EPHEMERAL) != 0) { 5887 flags |= UserInfo.FLAG_EPHEMERAL_ON_CREATE; 5888 } 5889 5890 userInfo = new UserInfo(userId, truncatedName, null, flags, userType); 5891 userInfo.serialNumber = mNextSerialNumber++; 5892 userInfo.creationTime = getCreationTime(); 5893 userInfo.partial = true; 5894 userInfo.preCreated = preCreate; 5895 userInfo.lastLoggedInFingerprint = PackagePartitions.FINGERPRINT; 5896 if (userTypeDetails.hasBadge() && parentId != UserHandle.USER_NULL) { 5897 userInfo.profileBadge = getFreeProfileBadgeLU(parentId, userType); 5898 } 5899 userData = new UserData(); 5900 userData.info = userInfo; 5901 userData.userProperties = new UserProperties( 5902 userTypeDetails.getDefaultUserPropertiesReference()); 5903 addUserDataLU(userData); 5904 } 5905 writeUserLP(userData); 5906 writeUserListLP(); 5907 if (parent != null) { 5908 if (isProfile) { 5909 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) { 5910 parent.info.profileGroupId = parent.info.id; 5911 writeUserLP(parent); 5912 } 5913 userInfo.profileGroupId = parent.info.profileGroupId; 5914 } else if (isRestricted) { 5915 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) { 5916 parent.info.restrictedProfileParentId = parent.info.id; 5917 writeUserLP(parent); 5918 } 5919 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId; 5920 } 5921 } 5922 } 5923 5924 t.traceBegin("createUserStorageKeys"); 5925 final StorageManager storage = mContext.getSystemService(StorageManager.class); 5926 storage.createUserStorageKeys(userId, userInfo.isEphemeral()); 5927 t.traceEnd(); 5928 5929 // Only prepare DE storage here. CE storage will be prepared later, when the user is 5930 // unlocked. We do this to ensure that CE storage isn't prepared before the CE key is 5931 // saved to disk. This also matches what is done for user 0. 5932 t.traceBegin("prepareUserData"); 5933 mUserDataPreparer.prepareUserData(userInfo, StorageManager.FLAG_STORAGE_DE); 5934 t.traceEnd(); 5935 5936 t.traceBegin("LSS.createNewUser"); 5937 mLockPatternUtils.createNewUser(userId, userInfo.serialNumber); 5938 t.traceEnd(); 5939 5940 final Set<String> userTypeInstallablePackages = 5941 mSystemPackageInstaller.getInstallablePackagesForUserType(userType); 5942 t.traceBegin("PM.createNewUser"); 5943 mPm.createNewUser(userId, userTypeInstallablePackages, disallowedPackages); 5944 t.traceEnd(); 5945 5946 Bundle restrictions = new Bundle(); 5947 if (isGuest) { 5948 // Guest default restrictions can be modified via setDefaultGuestRestrictions. 5949 synchronized (mGuestRestrictions) { 5950 restrictions.putAll(mGuestRestrictions); 5951 } 5952 } else { 5953 userTypeDetails.addDefaultRestrictionsTo(restrictions); 5954 if (isMainUser) { 5955 restrictions.remove(UserManager.DISALLOW_OUTGOING_CALLS); 5956 restrictions.remove(UserManager.DISALLOW_SMS); 5957 } 5958 } 5959 synchronized (mRestrictionsLock) { 5960 mBaseUserRestrictions.updateRestrictions(userId, restrictions); 5961 } 5962 5963 userInfo.partial = false; 5964 if (android.multiuser.Flags.invalidateCacheOnUsersChangedReadOnly()) { 5965 UserManager.invalidateCacheOnUserListChange(); 5966 } 5967 synchronized (mPackagesLock) { 5968 writeUserLP(userData); 5969 } 5970 updateUserIds(); 5971 5972 t.traceBegin("PM.onNewUserCreated-" + userId); 5973 mPm.onNewUserCreated(userId, /* convertedFromPreCreated= */ false); 5974 t.traceEnd(); 5975 applyDefaultUserSettings(userTypeDetails, userId); 5976 setDefaultCrossProfileIntentFilters(userId, userTypeDetails, restrictions, parentId); 5977 5978 if (preCreate) { 5979 // Must start user (which will be stopped right away, through 5980 // UserController.finishUserUnlockedCompleted) so services can properly 5981 // intialize it. 5982 // NOTE: user will be stopped on UserController.finishUserUnlockedCompleted(). 5983 Slog.i(LOG_TAG, "starting pre-created user " + userInfo.toFullString()); 5984 final IActivityManager am = ActivityManager.getService(); 5985 try { 5986 am.startUserInBackground(userId); 5987 } catch (RemoteException e) { 5988 Slog.w(LOG_TAG, "could not start pre-created user " + userId, e); 5989 } 5990 } else { 5991 dispatchUserAdded(userInfo, token); 5992 } 5993 5994 } finally { 5995 Binder.restoreCallingIdentity(ident); 5996 } 5997 5998 // TODO(b/143092698): it's possible to reach "max users overflow" when the user is created 5999 // "from scratch" (i.e., not from a pre-created user) and reaches the maximum number of 6000 // users without counting the pre-created one. Then when the pre-created is converted, the 6001 // "effective" number of max users is exceeds. Example: 6002 // Max: 3 Current: 2 full (u0 and u10) + 1 pre-created (u11) 6003 // Step 1: create(/* flags doesn't match u11 */): u12 is created, "effective max" is now 3 6004 // (u0, u10, u12) but "real" max is 4 (u0, u10, u11, u12) 6005 // Step 2: create(/* flags match u11 */): u11 is converted, now "effective max" is also 4 6006 // (u0, u10, u11, u12) 6007 // One way to avoid this issue is by removing a pre-created user from the pool when the 6008 // "real" max exceeds the max here. 6009 6010 return userInfo; 6011 } 6012 6013 private void applyDefaultUserSettings(UserTypeDetails userTypeDetails, @UserIdInt int userId) { 6014 final Bundle systemSettings = userTypeDetails.getDefaultSystemSettings(); 6015 final Bundle secureSettings = userTypeDetails.getDefaultSecureSettings(); 6016 if (systemSettings.isEmpty() && secureSettings.isEmpty()) { 6017 return; 6018 } 6019 6020 final int systemSettingsSize = systemSettings.size(); 6021 final String[] systemSettingsArray = systemSettings.keySet().toArray( 6022 new String[systemSettingsSize]); 6023 for (int i = 0; i < systemSettingsSize; i++) { 6024 final String setting = systemSettingsArray[i]; 6025 if (!Settings.System.putStringForUser( 6026 mContext.getContentResolver(), setting, systemSettings.getString(setting), 6027 userId)) { 6028 Slog.e(LOG_TAG, "Failed to insert default system setting: " + setting); 6029 } 6030 } 6031 6032 final int secureSettingsSize = secureSettings.size(); 6033 final String[] secureSettingsArray = secureSettings.keySet().toArray( 6034 new String[secureSettingsSize]); 6035 for (int i = 0; i < secureSettingsSize; i++) { 6036 final String setting = secureSettingsArray[i]; 6037 if (!Settings.Secure.putStringForUser( 6038 mContext.getContentResolver(), setting, secureSettings.getString(setting), 6039 userId)) { 6040 Slog.e(LOG_TAG, "Failed to insert default secure setting: " + setting); 6041 } 6042 } 6043 } 6044 6045 /** 6046 * Sets all default cross profile intent filters between {@code parentUserId} and 6047 * {@code profileUserId}, does nothing if {@code userType} is not a profile. 6048 */ 6049 private void setDefaultCrossProfileIntentFilters( 6050 @UserIdInt int profileUserId, UserTypeDetails profileDetails, 6051 Bundle profileRestrictions, @UserIdInt int parentUserId) { 6052 if (profileDetails == null || !profileDetails.isProfile()) { 6053 return; 6054 } 6055 final List<DefaultCrossProfileIntentFilter> filters = 6056 profileDetails.getDefaultCrossProfileIntentFilters(); 6057 if (filters.isEmpty()) { 6058 return; 6059 } 6060 6061 // Skip filters that allow data to be shared into the profile, if admin has disabled it. 6062 final boolean disallowSharingIntoProfile = 6063 profileRestrictions.getBoolean( 6064 UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, 6065 /* defaultValue = */ false); 6066 final int size = profileDetails.getDefaultCrossProfileIntentFilters().size(); 6067 for (int i = 0; i < size; i++) { 6068 final DefaultCrossProfileIntentFilter filter = 6069 profileDetails.getDefaultCrossProfileIntentFilters().get(i); 6070 if (disallowSharingIntoProfile && filter.letsPersonalDataIntoProfile) { 6071 continue; 6072 } 6073 if (filter.direction == DefaultCrossProfileIntentFilter.Direction.TO_PARENT) { 6074 mPm.addCrossProfileIntentFilter(mPm.snapshotComputer(), 6075 filter.filter, mContext.getOpPackageName(), profileUserId, parentUserId, 6076 filter.flags); 6077 } else { 6078 mPm.addCrossProfileIntentFilter(mPm.snapshotComputer(), 6079 filter.filter, mContext.getOpPackageName(), parentUserId, profileUserId, 6080 filter.flags); 6081 } 6082 } 6083 } 6084 6085 /** 6086 * Finds and converts a previously pre-created user into a regular user, if possible. 6087 * 6088 * @return the converted user, or {@code null} if no pre-created user could be converted. 6089 */ 6090 private @Nullable UserInfo convertPreCreatedUserIfPossible(String userType, 6091 @UserInfoFlag int flags, @Nullable String name, @Nullable Object token) { 6092 final UserData preCreatedUserData; 6093 synchronized (mUsersLock) { 6094 preCreatedUserData = getPreCreatedUserLU(userType); 6095 } 6096 if (preCreatedUserData == null) { 6097 return null; 6098 } 6099 synchronized (mUserStates) { 6100 if (mUserStates.has(preCreatedUserData.info.id)) { 6101 Slog.w(LOG_TAG, "Cannot reuse pre-created user " 6102 + preCreatedUserData.info.id + " because it didn't stop yet"); 6103 return null; 6104 } 6105 } 6106 final UserInfo preCreatedUser = preCreatedUserData.info; 6107 final int newFlags = preCreatedUser.flags | flags; 6108 if (!checkUserTypeConsistency(newFlags)) { 6109 Slog.wtf(LOG_TAG, "Cannot reuse pre-created user " + preCreatedUser.id 6110 + " of type " + userType + " because flags are inconsistent. " 6111 + "Flags (" + Integer.toHexString(flags) + "); preCreatedUserFlags ( " 6112 + Integer.toHexString(preCreatedUser.flags) + ")."); 6113 return null; 6114 } 6115 Slog.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " of type " 6116 + userType + " and bestowing on it flags " + UserInfo.flagsToString(flags)); 6117 preCreatedUser.name = name; 6118 preCreatedUser.flags = newFlags; 6119 preCreatedUser.preCreated = false; 6120 preCreatedUser.convertedFromPreCreated = true; 6121 preCreatedUser.creationTime = getCreationTime(); 6122 6123 synchronized (mPackagesLock) { 6124 writeUserLP(preCreatedUserData); 6125 writeUserListLP(); 6126 } 6127 updateUserIds(); 6128 Binder.withCleanCallingIdentity(() -> { 6129 mPm.onNewUserCreated(preCreatedUser.id, /* convertedFromPreCreated= */ true); 6130 dispatchUserAdded(preCreatedUser, token); 6131 VoiceInteractionManagerInternal vimi = LocalServices 6132 .getService(VoiceInteractionManagerInternal.class); 6133 if (vimi != null) { 6134 vimi.onPreCreatedUserConversion(preCreatedUser.id); 6135 } 6136 }); 6137 return preCreatedUser; 6138 } 6139 6140 /** Checks that the flags do not contain mutually exclusive types/properties. */ 6141 @VisibleForTesting 6142 static boolean checkUserTypeConsistency(@UserInfoFlag int flags) { 6143 // Mask to check that flags don't refer to multiple user types. 6144 final int userTypeFlagMask = UserInfo.FLAG_GUEST | UserInfo.FLAG_DEMO 6145 | UserInfo.FLAG_RESTRICTED | UserInfo.FLAG_PROFILE; 6146 return isAtMostOneFlag(flags & userTypeFlagMask) 6147 && isAtMostOneFlag(flags & (UserInfo.FLAG_PROFILE | UserInfo.FLAG_FULL)) 6148 && isAtMostOneFlag(flags & (UserInfo.FLAG_PROFILE | UserInfo.FLAG_SYSTEM)); 6149 } 6150 6151 /** Returns whether the given flags contains at most one 1. */ 6152 private static boolean isAtMostOneFlag(int flags) { 6153 return (flags & (flags - 1)) == 0; 6154 // If !=0, this means that flags is not a power of 2, and therefore is multiple types. 6155 } 6156 6157 /** Install/uninstall system packages for all users based on their user-type, as applicable. */ 6158 boolean installWhitelistedSystemPackages(boolean isFirstBoot, boolean isUpgrade, 6159 @Nullable ArraySet<String> existingPackages) { 6160 return mSystemPackageInstaller.installWhitelistedSystemPackages( 6161 isFirstBoot || mUpdatingSystemUserMode, isUpgrade, existingPackages); 6162 } 6163 6164 @Override 6165 public String[] getPreInstallableSystemPackages(@NonNull String userType) { 6166 checkCreateUsersPermission("getPreInstallableSystemPackages"); 6167 final Set<String> installableSystemPackages = 6168 mSystemPackageInstaller.getInstallablePackagesForUserType(userType); 6169 if (installableSystemPackages == null) { 6170 return null; 6171 } 6172 return installableSystemPackages.toArray(new String[installableSystemPackages.size()]); 6173 } 6174 6175 private long getCreationTime() { 6176 final long now = System.currentTimeMillis(); 6177 return (now > EPOCH_PLUS_30_YEARS) ? now : 0; 6178 } 6179 6180 private void dispatchUserAdded(@NonNull UserInfo userInfo, @Nullable Object token) { 6181 // Notify internal listeners first... 6182 synchronized (mUserLifecycleListeners) { 6183 for (int i = 0; i < mUserLifecycleListeners.size(); i++) { 6184 mUserLifecycleListeners.get(i).onUserCreated(userInfo, token); 6185 } 6186 } 6187 6188 //...then external ones 6189 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED); 6190 addedIntent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 6191 // In HSUM, MainUser might be created before PHASE_ACTIVITY_MANAGER_READY has been sent. 6192 addedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6193 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id); 6194 // Also, add the UserHandle for mainline modules which can't use the @hide 6195 // EXTRA_USER_HANDLE. 6196 addedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userInfo.id)); 6197 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL, 6198 android.Manifest.permission.MANAGE_USERS); 6199 MetricsLogger.count(mContext, userInfo.isGuest() ? TRON_GUEST_CREATED 6200 : (userInfo.isDemo() ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1); 6201 6202 if (userInfo.isProfile()) { 6203 sendProfileAddedBroadcast(userInfo.profileGroupId, userInfo.id); 6204 } else { 6205 // If the user switch hasn't been explicitly toggled on or off by the user, turn it on. 6206 if (android.provider.Settings.Global.getString(mContext.getContentResolver(), 6207 android.provider.Settings.Global.USER_SWITCHER_ENABLED) == null) { 6208 if (getSystemResources().getBoolean( 6209 com.android.internal.R.bool.config_enableUserSwitcherUponUserCreation)) { 6210 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 6211 android.provider.Settings.Global.USER_SWITCHER_ENABLED, 1); 6212 } 6213 } 6214 } 6215 } 6216 6217 /** 6218 * Gets a pre-created user for the given user type. 6219 * 6220 * <p>Should be used only during user creation, so the pre-created user can be used (instead of 6221 * creating and initializing a new user from scratch). 6222 */ 6223 // TODO(b/143092698): add unit test 6224 @GuardedBy("mUsersLock") 6225 private @Nullable UserData getPreCreatedUserLU(String userType) { 6226 if (DBG) Slog.d(LOG_TAG, "getPreCreatedUser(): userType= " + userType); 6227 final int userSize = mUsers.size(); 6228 for (int i = 0; i < userSize; i++) { 6229 final UserData user = mUsers.valueAt(i); 6230 if (DBG) Slog.d(LOG_TAG, i + ":" + user.info.toFullString()); 6231 if (user.info.preCreated && !user.info.partial && user.info.userType.equals(userType)) { 6232 if (!user.info.isInitialized()) { 6233 Slog.w(LOG_TAG, "found pre-created user of type " + userType 6234 + ", but it's not initialized yet: " + user.info.toFullString()); 6235 continue; 6236 } 6237 return user; 6238 } 6239 } 6240 return null; 6241 } 6242 6243 /** 6244 * Returns whether a user with the given userTypeDetails is eligible to be 6245 * {@link UserInfo#preCreated}. 6246 */ 6247 private static boolean isUserTypeEligibleForPreCreation(UserTypeDetails userTypeDetails) { 6248 if (userTypeDetails == null) { 6249 return false; 6250 } 6251 return !userTypeDetails.isProfile() 6252 && !userTypeDetails.getName().equals(UserManager.USER_TYPE_FULL_RESTRICTED); 6253 } 6254 6255 /** Register callbacks for statsd pulled atoms. */ 6256 private void registerStatsCallbacks() { 6257 final StatsManager statsManager = mContext.getSystemService(StatsManager.class); 6258 statsManager.setPullAtomCallback( 6259 FrameworkStatsLog.USER_INFO, 6260 null, // use default PullAtomMetadata values 6261 DIRECT_EXECUTOR, 6262 this::onPullAtom); 6263 statsManager.setPullAtomCallback( 6264 FrameworkStatsLog.MULTI_USER_INFO, 6265 null, // use default PullAtomMetadata values 6266 DIRECT_EXECUTOR, 6267 this::onPullAtom); 6268 } 6269 6270 /** Writes a UserInfo pulled atom for each user on the device. */ 6271 private int onPullAtom(int atomTag, List<StatsEvent> data) { 6272 if (atomTag == FrameworkStatsLog.USER_INFO) { 6273 final List<UserInfo> users = getUsersInternal(true, true, true); 6274 final int size = users.size(); 6275 if (size > 1) { 6276 for (int idx = 0; idx < size; idx++) { 6277 final UserInfo user = users.get(idx); 6278 final int userTypeStandard = mUserJourneyLogger 6279 .getUserTypeForStatsd(user.userType); 6280 final String userTypeCustom = (userTypeStandard == FrameworkStatsLog 6281 .USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__TYPE_UNKNOWN) 6282 ? 6283 user.userType : null; 6284 6285 boolean isUserRunningUnlocked; 6286 synchronized (mUserStates) { 6287 isUserRunningUnlocked = 6288 mUserStates.get(user.id, -1) == UserState.STATE_RUNNING_UNLOCKED; 6289 } 6290 6291 data.add(FrameworkStatsLog.buildStatsEvent(FrameworkStatsLog.USER_INFO, 6292 user.id, 6293 userTypeStandard, 6294 userTypeCustom, 6295 user.flags, 6296 user.creationTime, 6297 user.lastLoggedInTime, 6298 isUserRunningUnlocked 6299 )); 6300 } 6301 } 6302 } else if (atomTag == FrameworkStatsLog.MULTI_USER_INFO) { 6303 if (UserManager.getMaxSupportedUsers() > 1) { 6304 data.add(FrameworkStatsLog.buildStatsEvent(FrameworkStatsLog.MULTI_USER_INFO, 6305 UserManager.getMaxSupportedUsers(), 6306 // TODO(b/390455855): is USER_ALL really allowed here? 6307 isUserSwitcherEnabled(UserHandle.USER_ALL), 6308 UserManager.supportsMultipleUsers() 6309 && !hasUserRestriction(UserManager.DISALLOW_ADD_USER, 6310 // TODO(b/390455855): is USER_ALL really allowed here? 6311 UserHandle.USER_ALL))); 6312 } 6313 } else { 6314 Slogf.e(LOG_TAG, "Unexpected atom tag: %d", atomTag); 6315 return android.app.StatsManager.PULL_SKIP; 6316 } 6317 return android.app.StatsManager.PULL_SUCCESS; 6318 } 6319 6320 @VisibleForTesting 6321 UserData putUserInfo(UserInfo userInfo) { 6322 final UserData userData = new UserData(); 6323 userData.info = userInfo; 6324 synchronized (mUsersLock) { 6325 addUserDataLU(userData); 6326 } 6327 updateUserIds(); 6328 return userData; 6329 } 6330 6331 /** For testing only! Directly, unnaturally removes userId from list of users. */ 6332 @VisibleForTesting 6333 void removeUserInfo(@UserIdInt int userId) { 6334 synchronized (mUsersLock) { 6335 removeUserDataLU(userId); 6336 } 6337 } 6338 6339 @Override 6340 public @NonNull UserInfo createRestrictedProfileWithThrow( 6341 @Nullable String name, @UserIdInt int parentUserId) 6342 throws ServiceSpecificException { 6343 6344 checkCreateUsersPermission("setupRestrictedProfile"); 6345 final UserInfo user = createProfileForUserWithThrow( 6346 name, UserManager.USER_TYPE_FULL_RESTRICTED, 0, parentUserId, null); 6347 final long identity = Binder.clearCallingIdentity(); 6348 try { 6349 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id); 6350 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise 6351 // the putIntForUser() will fail. 6352 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(), 6353 android.provider.Settings.Secure.LOCATION_MODE, 6354 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id); 6355 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id); 6356 } finally { 6357 Binder.restoreCallingIdentity(identity); 6358 } 6359 return user; 6360 } 6361 6362 /** 6363 * Gets the existing guest users. If a Guest user is partial, 6364 * then do not include it in the results as it is about to die. 6365 * 6366 * @return list of existing Guest users currently on the device. 6367 */ 6368 @Override 6369 public List<UserInfo> getGuestUsers() { 6370 checkManageUsersPermission("getGuestUsers"); 6371 final ArrayList<UserInfo> guestUsers = new ArrayList<>(); 6372 synchronized (mUsersLock) { 6373 final int size = mUsers.size(); 6374 for (int i = 0; i < size; i++) { 6375 final UserInfo user = mUsers.valueAt(i).info; 6376 if (user.isGuest() && !user.guestToRemove && !user.preCreated 6377 && !mRemovingUserIds.get(user.id)) { 6378 guestUsers.add(user); 6379 } 6380 } 6381 } 6382 return guestUsers; 6383 } 6384 6385 /** 6386 * Mark this guest user for deletion to allow us to create another guest 6387 * and switch to that user before actually removing this guest. 6388 * @param userId the userid of the current guest 6389 * @return whether the user could be marked for deletion 6390 */ 6391 @Override 6392 public boolean markGuestForDeletion(@UserIdInt int userId) { 6393 checkManageUsersPermission("Only the system can remove users"); 6394 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean( 6395 UserManager.DISALLOW_REMOVE_USER, false)) { 6396 Slog.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled."); 6397 return false; 6398 } 6399 6400 final long ident = Binder.clearCallingIdentity(); 6401 try { 6402 final UserData userData; 6403 synchronized (mPackagesLock) { 6404 synchronized (mUsersLock) { 6405 userData = mUsers.get(userId); 6406 if (userId == 0 || userData == null || mRemovingUserIds.get(userId)) { 6407 return false; 6408 } 6409 } 6410 if (!userData.info.isGuest()) { 6411 return false; 6412 } 6413 // We set this to a guest user that is to be removed. This is a temporary state 6414 // where we are allowed to add new Guest users, even if this one is still not 6415 // removed. This user will still show up in getUserInfo() calls. 6416 // If we don't get around to removing this Guest user, it will be purged on next 6417 // startup. 6418 userData.info.guestToRemove = true; 6419 // Mark it as disabled, so that it isn't returned any more when 6420 // profiles are queried. 6421 addUserInfoFlags(userData.info, UserInfo.FLAG_DISABLED); 6422 writeUserLP(userData); 6423 } 6424 } finally { 6425 Binder.restoreCallingIdentity(ident); 6426 } 6427 return true; 6428 } 6429 6430 /** 6431 * Removes a user and its profiles along with all data directories created for that user 6432 * and its profile. 6433 * This method should be called after the user's processes have been terminated. 6434 * @param userId the user's id 6435 */ 6436 @Override 6437 public boolean removeUser(@UserIdInt int userId) { 6438 Slog.i(LOG_TAG, "removeUser u" + userId); 6439 checkCreateUsersPermission("Only the system can remove users"); 6440 6441 final Optional<String> restrictionOptional = getUserRemovalRestrictionOptional(userId); 6442 if (!restrictionOptional.isEmpty() 6443 && getUserRestrictions(UserHandle.getCallingUserId()) 6444 .getBoolean(restrictionOptional.get(), false)) { 6445 Slog.w(LOG_TAG, "Cannot remove user. " + restrictionOptional.get() + " is enabled."); 6446 return false; 6447 } 6448 if (mCurrentBootPhase < SystemService.PHASE_ACTIVITY_MANAGER_READY) { 6449 Slog.w(LOG_TAG, "Cannot remove user, removeUser is called too early during boot. " 6450 + "ActivityManager is not ready yet."); 6451 return false; 6452 } 6453 return removeUserWithProfilesUnchecked(userId); 6454 } 6455 6456 private boolean removeUserWithProfilesUnchecked(@UserIdInt int userId) { 6457 final UserData userData; 6458 final boolean isProfile; 6459 final IntArray profileIds; 6460 synchronized (mUsersLock) { 6461 final int userRemovability = getUserRemovabilityLocked(userId, "removed"); 6462 if (userRemovability != UserManager.REMOVE_RESULT_USER_IS_REMOVABLE) { 6463 return UserManager.isRemoveResultSuccessful(userRemovability); 6464 } 6465 userData = mUsers.get(userId); 6466 isProfile = userData.info.isProfile(); 6467 profileIds = isProfile ? null : getProfileIdsLU(userId, null, false, /* excludeHidden */ 6468 false); 6469 } 6470 6471 if (!isProfile) { 6472 Pair<Integer, Integer> currentAndTargetUserIds = getCurrentAndTargetUserIds(); 6473 if (userId == currentAndTargetUserIds.first) { 6474 Slog.w(LOG_TAG, "Current user cannot be removed."); 6475 return false; 6476 } 6477 if (userId == currentAndTargetUserIds.second) { 6478 Slog.w(LOG_TAG, "Target user of an ongoing user switch cannot be removed."); 6479 return false; 6480 } 6481 for (int i = profileIds.size() - 1; i >= 0; i--) { 6482 int profileId = profileIds.get(i); 6483 if (profileId == userId) { 6484 //Remove the associated profiles first and then remove the user 6485 continue; 6486 } 6487 Slog.i(LOG_TAG, "removing profile:" + profileId 6488 + " associated with user:" + userId); 6489 if (!removeUserUnchecked(profileId)) { 6490 // If the profile was not immediately removed, make sure it is marked as 6491 // ephemeral. Don't mark as disabled since, per UserInfo.FLAG_DISABLED 6492 // documentation, an ephemeral user should only be marked as disabled 6493 // when its removal is in progress. 6494 Slog.i(LOG_TAG, "Unable to immediately remove profile " + profileId 6495 + "associated with user " + userId + ". User is set as ephemeral " 6496 + "and will be removed on user switch or reboot."); 6497 synchronized (mPackagesLock) { 6498 UserData profileData = getUserDataNoChecks(userId); 6499 profileData.info.flags |= UserInfo.FLAG_EPHEMERAL; 6500 6501 writeUserLP(profileData); 6502 } 6503 } 6504 } 6505 } 6506 6507 return removeUserUnchecked(userId); 6508 } 6509 6510 @Override 6511 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) { 6512 checkCreateUsersPermission("Only the system can remove users"); 6513 return removeUserWithProfilesUnchecked(userId); 6514 } 6515 6516 /** 6517 * Returns an optional string name of the restriction to check for user removal. The restriction 6518 * name varies depending on whether the user is a managed profile. 6519 * 6520 * <p>If the flag android.multiuser.ignore_restrictions_when_deleting_private_profile is enabled 6521 * and the user is a private profile (i.e. has no removal restrictions) the method will return 6522 * {@code Optional.empty()}. 6523 */ 6524 private Optional<String> getUserRemovalRestrictionOptional(@UserIdInt int userId) { 6525 final boolean isPrivateProfile; 6526 final boolean isManagedProfile; 6527 final UserInfo userInfo; 6528 synchronized (mUsersLock) { 6529 userInfo = getUserInfoLU(userId); 6530 } 6531 isPrivateProfile = userInfo != null && userInfo.isPrivateProfile(); 6532 isManagedProfile = userInfo != null && userInfo.isManagedProfile(); 6533 if (android.multiuser.Flags.ignoreRestrictionsWhenDeletingPrivateProfile() 6534 && isPrivateProfile) { 6535 return Optional.empty(); 6536 } 6537 return Optional.of( 6538 isManagedProfile 6539 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 6540 : UserManager.DISALLOW_REMOVE_USER); 6541 } 6542 6543 private boolean removeUserUnchecked(@UserIdInt int userId) { 6544 final long ident = Binder.clearCallingIdentity(); 6545 try { 6546 final UserData userData; 6547 synchronized (mPackagesLock) { 6548 synchronized (mUsersLock) { 6549 final int userRemovability = getUserRemovabilityLocked(userId, "removed"); 6550 if (userRemovability != UserManager.REMOVE_RESULT_USER_IS_REMOVABLE) { 6551 return UserManager.isRemoveResultSuccessful(userRemovability); 6552 } 6553 userData = mUsers.get(userId); 6554 Slog.i(LOG_TAG, "Removing user " + userId); 6555 addRemovingUserIdLocked(userId); 6556 } 6557 // Set this to a partially created user, so that the user will be purged 6558 // on next startup, in case the runtime stops now before stopping and 6559 // removing the user completely. 6560 userData.info.partial = true; 6561 if (android.multiuser.Flags.invalidateCacheOnUsersChangedReadOnly()) { 6562 UserManager.invalidateCacheOnUserListChange(); 6563 } 6564 // Mark it as disabled, so that it isn't returned any more when 6565 // profiles are queried. 6566 addUserInfoFlags(userData.info, UserInfo.FLAG_DISABLED); 6567 writeUserLP(userData); 6568 } 6569 6570 mUserJourneyLogger.logUserJourneyBegin(userId, USER_JOURNEY_USER_REMOVE); 6571 mUserJourneyLogger.startSessionForDelayedJourney(userId, 6572 USER_JOURNEY_USER_LIFECYCLE, userData.info.creationTime); 6573 6574 try { 6575 mAppOpsService.removeUser(userId); 6576 } catch (RemoteException e) { 6577 Slog.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e); 6578 } 6579 6580 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID 6581 && userData.info.isProfile()) { 6582 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id, 6583 userData.info.userType); 6584 } 6585 6586 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userId); 6587 int res; 6588 try { 6589 res = ActivityManager.getService().stopUserWithCallback(userId, 6590 new IStopUserCallback.Stub() { 6591 @Override 6592 public void userStopped(int userIdParam) { 6593 finishRemoveUser(userIdParam); 6594 int originUserId = UserManagerService.this.getCurrentUserId(); 6595 mUserJourneyLogger.logUserJourneyFinishWithError(originUserId, 6596 userData.info, USER_JOURNEY_USER_REMOVE, 6597 ERROR_CODE_UNSPECIFIED); 6598 mUserJourneyLogger 6599 .logDelayedUserJourneyFinishWithError(originUserId, 6600 userData.info, USER_JOURNEY_USER_LIFECYCLE, 6601 ERROR_CODE_UNSPECIFIED); 6602 } 6603 @Override 6604 public void userStopAborted(int userIdParam) { 6605 int originUserId = UserManagerService.this.getCurrentUserId(); 6606 mUserJourneyLogger.logUserJourneyFinishWithError(originUserId, 6607 userData.info, USER_JOURNEY_USER_REMOVE, 6608 ERROR_CODE_ABORTED); 6609 mUserJourneyLogger 6610 .logDelayedUserJourneyFinishWithError(originUserId, 6611 userData.info, USER_JOURNEY_USER_LIFECYCLE, 6612 ERROR_CODE_ABORTED); 6613 } 6614 }); 6615 } catch (RemoteException e) { 6616 Slog.w(LOG_TAG, "Failed to stop user during removal.", e); 6617 return false; 6618 } 6619 return res == ActivityManager.USER_OP_SUCCESS; 6620 } finally { 6621 Binder.restoreCallingIdentity(ident); 6622 } 6623 } 6624 6625 @VisibleForTesting 6626 void addRemovingUserId(@UserIdInt int userId) { 6627 synchronized (mUsersLock) { 6628 addRemovingUserIdLocked(userId); 6629 } 6630 } 6631 6632 @GuardedBy("mUsersLock") 6633 void addRemovingUserIdLocked(@UserIdInt int userId) { 6634 // We remember deleted user IDs to prevent them from being 6635 // reused during the current boot; they can still be reused 6636 // after a reboot or recycling of userIds. 6637 mRemovingUserIds.put(userId, true); 6638 mRecentlyRemovedIds.add(userId); 6639 // Keep LRU queue of recently removed IDs for recycling 6640 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) { 6641 mRecentlyRemovedIds.removeFirst(); 6642 } 6643 } 6644 6645 @Override 6646 public @UserManager.RemoveResult int removeUserWhenPossible(@UserIdInt int userId, 6647 boolean overrideDevicePolicy) { 6648 Slog.i(LOG_TAG, "removeUserWhenPossible u" + userId); 6649 checkCreateUsersPermission("Only the system can remove users"); 6650 6651 if (!overrideDevicePolicy) { 6652 final Optional<String> restrictionOptional = getUserRemovalRestrictionOptional(userId); 6653 if (!restrictionOptional.isEmpty() 6654 && getUserRestrictions(UserHandle.getCallingUserId()) 6655 .getBoolean(restrictionOptional.get(), false)) { 6656 Slog.w( 6657 LOG_TAG, 6658 "Cannot remove user. " + restrictionOptional.get() + " is enabled."); 6659 return UserManager.REMOVE_RESULT_ERROR_USER_RESTRICTION; 6660 } 6661 } 6662 Slog.i(LOG_TAG, "Attempting to immediately remove user " + userId); 6663 if (removeUserWithProfilesUnchecked(userId)) { 6664 return UserManager.REMOVE_RESULT_REMOVED; 6665 } 6666 Slog.i(LOG_TAG, TextUtils.formatSimple( 6667 "Unable to immediately remove user %d. Now trying to set it ephemeral.", userId)); 6668 return setUserEphemeralUnchecked(userId); 6669 } 6670 6671 /** 6672 * Returns the user's removability status. 6673 * User is removable if the return value is {@link UserManager#REMOVE_RESULT_USER_IS_REMOVABLE}. 6674 * If the user is not removable this method also prints the reason. 6675 * See also {@link UserManager#isRemoveResultSuccessful}. 6676 */ 6677 @GuardedBy("mUsersLock") 6678 private @UserManager.RemoveResult int getUserRemovabilityLocked(@UserIdInt int userId, 6679 String msg) { 6680 String prefix = TextUtils.formatSimple("User %d can not be %s, ", userId, msg); 6681 if (userId == UserHandle.USER_SYSTEM) { 6682 Slog.e(LOG_TAG, prefix + "system user cannot be removed."); 6683 return UserManager.REMOVE_RESULT_ERROR_SYSTEM_USER; 6684 } 6685 final UserData userData = mUsers.get(userId); 6686 if (userData == null) { 6687 Slog.e(LOG_TAG, prefix + "invalid user id provided."); 6688 return UserManager.REMOVE_RESULT_ERROR_USER_NOT_FOUND; 6689 } 6690 if (isNonRemovableMainUser(userData.info)) { 6691 Slog.e(LOG_TAG, prefix 6692 + "main user cannot be removed when it's a permanent admin user."); 6693 return UserManager.REMOVE_RESULT_ERROR_MAIN_USER_PERMANENT_ADMIN; 6694 } 6695 if (mRemovingUserIds.get(userId)) { 6696 Slog.w(LOG_TAG, prefix + "it is already scheduled for removal."); 6697 return UserManager.REMOVE_RESULT_ALREADY_BEING_REMOVED; 6698 } 6699 return UserManager.REMOVE_RESULT_USER_IS_REMOVABLE; 6700 } 6701 6702 6703 private void finishRemoveUser(final @UserIdInt int userId) { 6704 Slog.i(LOG_TAG, "finishRemoveUser " + userId); 6705 6706 UserInfo user; 6707 synchronized (mUsersLock) { 6708 user = getUserInfoLU(userId); 6709 } 6710 if (user != null && user.preCreated) { 6711 Slog.i(LOG_TAG, "Removing a pre-created user with user id: " + userId); 6712 // Don't want to fire ACTION_USER_REMOVED, so cleanup the state and exit early. 6713 LocalServices.getService(ActivityTaskManagerInternal.class).onUserStopped(userId); 6714 removeUserState(userId); 6715 return; 6716 } 6717 6718 synchronized (mUserLifecycleListeners) { 6719 for (int i = 0; i < mUserLifecycleListeners.size(); i++) { 6720 mUserLifecycleListeners.get(i).onUserRemoved(user); 6721 } 6722 } 6723 6724 // Let other services shutdown any activity and clean up their state before completely 6725 // wiping the user's system directory and removing from the user list 6726 final long ident = Binder.clearCallingIdentity(); 6727 try { 6728 Intent removedIntent = new Intent(Intent.ACTION_USER_REMOVED); 6729 removedIntent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 6730 removedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 6731 // Also, add the UserHandle for mainline modules which can't use the @hide 6732 // EXTRA_USER_HANDLE. 6733 removedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId)); 6734 getActivityManagerInternal().broadcastIntentWithCallback(removedIntent, 6735 new IIntentReceiver.Stub() { 6736 @Override 6737 public void performReceive(Intent intent, int resultCode, String data, 6738 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 6739 if (DBG) { 6740 Slog.i(LOG_TAG, 6741 "USER_REMOVED broadcast sent, cleaning up user data " 6742 + userId); 6743 } 6744 new Thread(() -> { 6745 getActivityManagerInternal().onUserRemoving(userId); 6746 removeUserState(userId); 6747 }).start(); 6748 } 6749 }, 6750 new String[] {android.Manifest.permission.MANAGE_USERS}, 6751 UserHandle.USER_ALL, null, null, null); 6752 } finally { 6753 Binder.restoreCallingIdentity(ident); 6754 } 6755 } 6756 6757 private void removeUserState(final @UserIdInt int userId) { 6758 Slog.i(LOG_TAG, "Removing user state of user " + userId); 6759 6760 // Cleanup lock settings. This requires that the user's DE storage still be accessible, so 6761 // this must happen before destroyUserStorageKeys(). 6762 mLockPatternUtils.removeUser(userId); 6763 6764 // Evict and destroy the user's CE and DE encryption keys. At this point, the user's CE and 6765 // DE storage is made inaccessible, except to delete its contents. 6766 try { 6767 mContext.getSystemService(StorageManager.class).destroyUserStorageKeys(userId); 6768 } catch (IllegalStateException e) { 6769 // This may be simply because the user was partially created. 6770 Slog.i(LOG_TAG, "Destroying storage keys for user " + userId 6771 + " failed, continuing anyway", e); 6772 } 6773 6774 // Cleanup package manager settings 6775 mPm.cleanUpUser(this, userId); 6776 6777 // Clean up all data before removing metadata 6778 mUserDataPreparer.destroyUserData(userId, 6779 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 6780 6781 // Remove this user from the list 6782 synchronized (mUsersLock) { 6783 removeUserDataLU(userId); 6784 mIsUserManaged.delete(userId); 6785 getActivityManagerInternal().onUserRemoved(userId); 6786 } 6787 synchronized (mUserStates) { 6788 mUserStates.delete(userId); 6789 } 6790 synchronized (mRestrictionsLock) { 6791 mBaseUserRestrictions.remove(userId); 6792 mAppliedUserRestrictions.remove(userId); 6793 mCachedEffectiveUserRestrictions.remove(userId); 6794 // Remove restrictions affecting the user 6795 if (mDevicePolicyUserRestrictions.remove(userId)) { 6796 applyUserRestrictionsForAllUsersLR(); 6797 } 6798 } 6799 // Update the user list 6800 synchronized (mPackagesLock) { 6801 writeUserListLP(); 6802 } 6803 // Remove user file(s) 6804 getUserFile(userId).delete(); 6805 updateUserIds(); 6806 if (RELEASE_DELETED_USER_ID) { 6807 synchronized (mUsersLock) { 6808 mRemovingUserIds.delete(userId); 6809 } 6810 } 6811 } 6812 6813 /** 6814 * Send {@link Intent#ACTION_PROFILE_ADDED} broadcast when a user of type 6815 * {@link UserInfo#isProfile()} is added. This broadcast is sent only to dynamic receivers 6816 * created with {@link Context#registerReceiver}. 6817 */ 6818 private void sendProfileAddedBroadcast(int parentUserId, int addedUserId) { 6819 sendProfileBroadcast( 6820 new Intent(Intent.ACTION_PROFILE_ADDED), 6821 parentUserId, addedUserId); 6822 } 6823 6824 /** 6825 * Send {@link Intent#ACTION_PROFILE_REMOVED} broadcast when a user of type 6826 * {@link UserInfo#isProfile()} is removed. Additionally sends 6827 * {@link Intent#ACTION_MANAGED_PROFILE_REMOVED} broadcast if the profile is of type 6828 * {@link UserManager#USER_TYPE_PROFILE_MANAGED} 6829 * 6830 * <p> {@link Intent#ACTION_PROFILE_REMOVED} is a generalized broadcast for all users of type 6831 * {@link UserInfo#isProfile()} and is sent only to dynamic receivers. 6832 * 6833 * <p> In contrast, the {@link Intent#ACTION_MANAGED_PROFILE_REMOVED} broadcast is specific to 6834 * {@link UserManager#USER_TYPE_PROFILE_MANAGED} and is sent to both manifest and dynamic 6835 * receivers thus it is still needed as manifest receivers will not be able to listen to 6836 * the aforementioned generalized broadcast. 6837 */ 6838 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId, String userType) { 6839 if (Objects.equals(userType, UserManager.USER_TYPE_PROFILE_MANAGED)) { 6840 sendManagedProfileRemovedBroadcast(parentUserId, removedUserId); 6841 } 6842 sendProfileBroadcast( 6843 new Intent(Intent.ACTION_PROFILE_REMOVED), 6844 parentUserId, removedUserId); 6845 } 6846 6847 private void sendProfileBroadcast(Intent intent, 6848 int parentUserId, int userId) { 6849 final UserHandle parentHandle = UserHandle.of(parentUserId); 6850 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId)); 6851 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 6852 | Intent.FLAG_RECEIVER_FOREGROUND); 6853 mContext.sendBroadcastAsUser(intent, parentHandle, /* receiverPermission= */null); 6854 } 6855 6856 private void sendManagedProfileRemovedBroadcast(int parentUserId, int removedUserId) { 6857 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED); 6858 managedProfileIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(removedUserId)); 6859 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId); 6860 final UserHandle parentHandle = UserHandle.of(parentUserId); 6861 getDevicePolicyManagerInternal().broadcastIntentToManifestReceivers( 6862 managedProfileIntent, parentHandle, /* requiresPermission= */ false); 6863 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 6864 | Intent.FLAG_RECEIVER_FOREGROUND); 6865 mContext.sendBroadcastAsUser(managedProfileIntent, parentHandle, 6866 /* receiverPermission= */null); 6867 } 6868 6869 /** 6870 * <p>Starting from Android version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, 6871 * it is possible for there to be multiple managing agents on the device with the ability to set 6872 * restrictions, e.g. an Enterprise DPC and a Supervision admin. This API will only to return 6873 * the restrictions set by the DPCs. To retrieve restrictions set by all agents, use 6874 * {@link android.content.RestrictionsManager#getApplicationRestrictionsPerAdmin} instead. 6875 */ 6876 @Override 6877 public Bundle getApplicationRestrictions(String packageName) { 6878 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId()); 6879 } 6880 6881 /** 6882 * <p>Starting from Android version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, 6883 * it is possible for there to be multiple managing agents on the device with the ability to set 6884 * restrictions, e.g. an Enterprise DPC and a Supervision admin. This API will only to return 6885 * the restrictions set by the DPCs. To retrieve restrictions set by all agents, use 6886 * {@link android.content.RestrictionsManager#getApplicationRestrictionsPerAdmin} instead. 6887 */ 6888 @Override 6889 public Bundle getApplicationRestrictionsForUser(String packageName, @UserIdInt int userId) { 6890 if (UserHandle.getCallingUserId() != userId 6891 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) { 6892 checkSystemOrRoot("get application restrictions for other user/app " + packageName); 6893 } 6894 synchronized (mAppRestrictionsLock) { 6895 // Read the restrictions from XML 6896 return readApplicationRestrictionsLAr(packageName, userId); 6897 } 6898 } 6899 6900 @Override 6901 public void setApplicationRestrictions(String packageName, Bundle restrictions, 6902 @UserIdInt int userId) { 6903 checkSystemOrRoot("set application restrictions"); 6904 String validationResult = 6905 FrameworkParsingPackageUtils.validateName(packageName, false, false); 6906 if (validationResult != null) { 6907 throw new IllegalArgumentException("Invalid package name: " + validationResult); 6908 } 6909 if (restrictions != null) { 6910 restrictions.setDefusable(true); 6911 } 6912 final boolean changed; 6913 synchronized (mAppRestrictionsLock) { 6914 if (restrictions == null || restrictions.isEmpty()) { 6915 changed = cleanAppRestrictionsForPackageLAr(packageName, userId); 6916 } else { 6917 // Write the restrictions to XML 6918 writeApplicationRestrictionsLAr(packageName, restrictions, userId); 6919 // TODO(b/154323615): avoid unnecessary broadcast when there is no change. 6920 changed = true; 6921 } 6922 } 6923 6924 if (!changed) { 6925 return; 6926 } 6927 6928 // Notify package of changes via an intent - only sent to explicitly registered receivers. 6929 final Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED); 6930 changeIntent.setPackage(packageName); 6931 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 6932 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId)); 6933 } 6934 6935 private int getUidForPackage(String packageName) { 6936 final long ident = Binder.clearCallingIdentity(); 6937 try { 6938 return mContext.getPackageManager().getApplicationInfo(packageName, 6939 PackageManager.MATCH_ANY_USER).uid; 6940 } catch (NameNotFoundException nnfe) { 6941 return -1; 6942 } finally { 6943 Binder.restoreCallingIdentity(ident); 6944 } 6945 } 6946 6947 @GuardedBy("mAppRestrictionsLock") 6948 private static Bundle readApplicationRestrictionsLAr(String packageName, 6949 @UserIdInt int userId) { 6950 AtomicFile restrictionsFile = 6951 new AtomicFile(new File(Environment.getUserSystemDirectory(userId), 6952 packageToRestrictionsFileName(packageName))); 6953 return readApplicationRestrictionsLAr(restrictionsFile); 6954 } 6955 6956 @VisibleForTesting 6957 @GuardedBy("mAppRestrictionsLock") 6958 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) { 6959 final Bundle restrictions = new Bundle(); 6960 final ArrayList<String> values = new ArrayList<>(); 6961 if (!restrictionsFile.getBaseFile().exists()) { 6962 return restrictions; 6963 } 6964 6965 FileInputStream fis = null; 6966 try { 6967 fis = restrictionsFile.openRead(); 6968 final TypedXmlPullParser parser = Xml.resolvePullParser(fis); 6969 XmlUtils.nextElement(parser); 6970 if (parser.getEventType() != XmlPullParser.START_TAG) { 6971 Slog.e(LOG_TAG, "Unable to read restrictions file " 6972 + restrictionsFile.getBaseFile()); 6973 return restrictions; 6974 } 6975 while (parser.next() != XmlPullParser.END_DOCUMENT) { 6976 readEntry(restrictions, values, parser); 6977 } 6978 } catch (IOException|XmlPullParserException e) { 6979 Slog.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e); 6980 } finally { 6981 IoUtils.closeQuietly(fis); 6982 } 6983 return restrictions; 6984 } 6985 6986 private static void readEntry(Bundle restrictions, ArrayList<String> values, 6987 TypedXmlPullParser parser) throws XmlPullParserException, IOException { 6988 int type = parser.getEventType(); 6989 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) { 6990 String key = parser.getAttributeValue(null, ATTR_KEY); 6991 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE); 6992 int count = parser.getAttributeInt(null, ATTR_MULTIPLE, -1); 6993 if (count != -1) { 6994 values.clear(); 6995 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) { 6996 if (type == XmlPullParser.START_TAG 6997 && parser.getName().equals(TAG_VALUE)) { 6998 values.add(parser.nextText().trim()); 6999 count--; 7000 } 7001 } 7002 String [] valueStrings = new String[values.size()]; 7003 values.toArray(valueStrings); 7004 restrictions.putStringArray(key, valueStrings); 7005 } else if (ATTR_TYPE_BUNDLE.equals(valType)) { 7006 restrictions.putBundle(key, readBundleEntry(parser, values)); 7007 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) { 7008 final int outerDepth = parser.getDepth(); 7009 ArrayList<Bundle> bundleList = new ArrayList<>(); 7010 while (XmlUtils.nextElementWithin(parser, outerDepth)) { 7011 Bundle childBundle = readBundleEntry(parser, values); 7012 bundleList.add(childBundle); 7013 } 7014 restrictions.putParcelableArray(key, 7015 bundleList.toArray(new Bundle[bundleList.size()])); 7016 } else { 7017 String value = parser.nextText().trim(); 7018 if (ATTR_TYPE_BOOLEAN.equals(valType)) { 7019 restrictions.putBoolean(key, Boolean.parseBoolean(value)); 7020 } else if (ATTR_TYPE_INTEGER.equals(valType)) { 7021 restrictions.putInt(key, Integer.parseInt(value)); 7022 } else { 7023 restrictions.putString(key, value); 7024 } 7025 } 7026 } 7027 } 7028 7029 private static Bundle readBundleEntry(TypedXmlPullParser parser, ArrayList<String> values) 7030 throws IOException, XmlPullParserException { 7031 Bundle childBundle = new Bundle(); 7032 final int outerDepth = parser.getDepth(); 7033 while (XmlUtils.nextElementWithin(parser, outerDepth)) { 7034 readEntry(childBundle, values, parser); 7035 } 7036 return childBundle; 7037 } 7038 7039 @GuardedBy("mAppRestrictionsLock") 7040 private static void writeApplicationRestrictionsLAr(String packageName, 7041 Bundle restrictions, @UserIdInt int userId) { 7042 AtomicFile restrictionsFile = new AtomicFile( 7043 new File(Environment.getUserSystemDirectory(userId), 7044 packageToRestrictionsFileName(packageName))); 7045 writeApplicationRestrictionsLAr(restrictions, restrictionsFile); 7046 } 7047 7048 @VisibleForTesting 7049 @GuardedBy("mAppRestrictionsLock") 7050 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) { 7051 FileOutputStream fos = null; 7052 try { 7053 fos = restrictionsFile.startWrite(); 7054 final TypedXmlSerializer serializer = Xml.resolveSerializer(fos); 7055 serializer.startDocument(null, true); 7056 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 7057 7058 serializer.startTag(null, TAG_RESTRICTIONS); 7059 writeBundle(restrictions, serializer); 7060 serializer.endTag(null, TAG_RESTRICTIONS); 7061 7062 serializer.endDocument(); 7063 restrictionsFile.finishWrite(fos); 7064 } catch (Exception e) { 7065 restrictionsFile.failWrite(fos); 7066 Slog.e(LOG_TAG, "Error writing application restrictions list", e); 7067 } 7068 } 7069 7070 private static void writeBundle(Bundle restrictions, TypedXmlSerializer serializer) 7071 throws IOException { 7072 for (String key : restrictions.keySet()) { 7073 Object value = restrictions.get(key); 7074 serializer.startTag(null, TAG_ENTRY); 7075 serializer.attribute(null, ATTR_KEY, key); 7076 7077 if (value instanceof Boolean) { 7078 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN); 7079 serializer.text(value.toString()); 7080 } else if (value instanceof Integer) { 7081 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER); 7082 serializer.text(value.toString()); 7083 } else if (value == null || value instanceof String) { 7084 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING); 7085 serializer.text(value != null ? (String) value : ""); 7086 } else if (value instanceof Bundle) { 7087 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE); 7088 writeBundle((Bundle) value, serializer); 7089 } else if (value instanceof Parcelable[]) { 7090 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY); 7091 Parcelable[] array = (Parcelable[]) value; 7092 for (Parcelable parcelable : array) { 7093 if (!(parcelable instanceof Bundle)) { 7094 throw new IllegalArgumentException("bundle-array can only hold Bundles"); 7095 } 7096 serializer.startTag(null, TAG_ENTRY); 7097 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE); 7098 writeBundle((Bundle) parcelable, serializer); 7099 serializer.endTag(null, TAG_ENTRY); 7100 } 7101 } else { 7102 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY); 7103 String[] values = (String[]) value; 7104 serializer.attributeInt(null, ATTR_MULTIPLE, values.length); 7105 for (String choice : values) { 7106 serializer.startTag(null, TAG_VALUE); 7107 serializer.text(choice != null ? choice : ""); 7108 serializer.endTag(null, TAG_VALUE); 7109 } 7110 } 7111 serializer.endTag(null, TAG_ENTRY); 7112 } 7113 } 7114 7115 @Override 7116 public int getUserSerialNumber(@UserIdInt int userId) { 7117 synchronized (mUsersLock) { 7118 final UserInfo userInfo = getUserInfoLU(userId); 7119 return userInfo != null ? userInfo.serialNumber : -1; 7120 } 7121 } 7122 7123 @Override 7124 public boolean isUserNameSet(@UserIdInt int userId) { 7125 final int callingUid = Binder.getCallingUid(); 7126 final int callingUserId = UserHandle.getUserId(callingUid); 7127 if (!hasQueryOrCreateUsersPermission() 7128 && !(callingUserId == userId && hasPermissionGranted( 7129 android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED, callingUid))) { 7130 throw new SecurityException("You need MANAGE_USERS, CREATE_USERS, QUERY_USERS, or " 7131 + "GET_ACCOUNTS_PRIVILEGED permissions to: get whether user name is set"); 7132 } 7133 synchronized (mUsersLock) { 7134 final UserInfo userInfo = getUserInfoLU(userId); 7135 return userInfo != null && userInfo.name != null; 7136 } 7137 } 7138 7139 @Override 7140 public int getUserHandle(int userSerialNumber) { 7141 synchronized (mUsersLock) { 7142 for (int userId : mUserIds) { 7143 UserInfo info = getUserInfoLU(userId); 7144 if (info != null && info.serialNumber == userSerialNumber) return userId; 7145 } 7146 // Not found 7147 return -1; 7148 } 7149 } 7150 7151 @Override 7152 public long getUserCreationTime(@UserIdInt int userId) { 7153 int callingUserId = UserHandle.getCallingUserId(); 7154 UserInfo userInfo = null; 7155 synchronized (mUsersLock) { 7156 if (callingUserId == userId) { 7157 userInfo = getUserInfoLU(userId); 7158 } else { 7159 UserInfo parent = getProfileParentLU(userId); 7160 if (parent != null && parent.id == callingUserId) { 7161 userInfo = getUserInfoLU(userId); 7162 } 7163 } 7164 } 7165 if (userInfo == null) { 7166 throw new SecurityException("userId can only be the calling user or a " 7167 + "profile associated with this user"); 7168 } 7169 return userInfo.creationTime; 7170 } 7171 7172 /** 7173 * Adding user data to mUsers list in one place to invalidate related caches. 7174 */ 7175 @GuardedBy("mUsersLock") 7176 private void addUserDataLU(UserData userData) { 7177 if (android.multiuser.Flags.invalidateCacheOnUsersChangedReadOnly()) { 7178 UserManager.invalidateCacheOnUserListChange(); 7179 } 7180 mUsers.put(userData.info.id, userData); 7181 } 7182 7183 /** 7184 * Removing user data to mUsers list in one place to invalidate related caches. 7185 */ 7186 @GuardedBy("mUsersLock") 7187 private void removeUserDataLU(@UserIdInt int userId) { 7188 UserManager.invalidateCacheOnUserListChange(); 7189 mUsers.remove(userId); 7190 } 7191 7192 /** 7193 * Caches the list of user ids in an array, adjusting the array size when necessary. 7194 */ 7195 private void updateUserIds() { 7196 int num = 0; 7197 int numIncludingPreCreated = 0; 7198 synchronized (mUsersLock) { 7199 final int userSize = mUsers.size(); 7200 for (int i = 0; i < userSize; i++) { 7201 final UserInfo userInfo = mUsers.valueAt(i).info; 7202 if (!userInfo.partial) { 7203 numIncludingPreCreated++; 7204 if (!userInfo.preCreated) { 7205 num++; 7206 } 7207 } 7208 } 7209 if (DBG) { 7210 Slog.d(LOG_TAG, "updateUserIds(): numberUsers= " + num 7211 + " includingPreCreated=" + numIncludingPreCreated); 7212 } 7213 final int[] newUsers = new int[num]; 7214 final int[] newUsersIncludingPreCreated = new int[numIncludingPreCreated]; 7215 7216 int n = 0; 7217 int nIncludingPreCreated = 0; 7218 for (int i = 0; i < userSize; i++) { 7219 final UserInfo userInfo = mUsers.valueAt(i).info; 7220 if (!userInfo.partial) { 7221 final int userId = mUsers.keyAt(i); 7222 newUsersIncludingPreCreated[nIncludingPreCreated++] = userId; 7223 if (!userInfo.preCreated) { 7224 newUsers[n++] = userId; 7225 } 7226 } 7227 } 7228 mUserIds = newUsers; 7229 mUserIdsIncludingPreCreated = newUsersIncludingPreCreated; 7230 if (DBG) { 7231 Slog.d(LOG_TAG, "updateUserIds(): userIds= " + Arrays.toString(mUserIds) 7232 + " includingPreCreated=" + Arrays.toString(mUserIdsIncludingPreCreated)); 7233 } 7234 UserPackage.setValidUserIds(mUserIds); 7235 } 7236 } 7237 7238 /** 7239 * Called right before a user is started. This gives us a chance to prepare 7240 * app storage and apply any user restrictions. 7241 */ 7242 public void onBeforeStartUser(@UserIdInt int userId) { 7243 UserInfo userInfo = getUserInfo(userId); 7244 if (userInfo == null) { 7245 return; 7246 } 7247 TimingsTraceAndSlog t = new TimingsTraceAndSlog(); 7248 t.traceBegin("onBeforeStartUser-" + userId); 7249 // Migrate only if build fingerprints mismatch 7250 boolean migrateAppsData = !PackagePartitions.FINGERPRINT.equals( 7251 userInfo.lastLoggedInFingerprint); 7252 t.traceBegin("prepareUserData"); 7253 mUserDataPreparer.prepareUserData(userInfo, StorageManager.FLAG_STORAGE_DE); 7254 t.traceEnd(); 7255 t.traceBegin("reconcileAppsData"); 7256 getPackageManagerInternal().reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, 7257 migrateAppsData); 7258 t.traceEnd(); 7259 7260 if (userId != UserHandle.USER_SYSTEM) { 7261 t.traceBegin("applyUserRestrictions"); 7262 synchronized (mRestrictionsLock) { 7263 applyUserRestrictionsLR(userId); 7264 } 7265 t.traceEnd(); 7266 } 7267 t.traceEnd(); // onBeforeStartUser 7268 } 7269 7270 /** 7271 * Called right before a user is unlocked. This gives us a chance to prepare 7272 * app storage. 7273 */ 7274 public void onBeforeUnlockUser(@UserIdInt int userId) { 7275 UserInfo userInfo = getUserInfo(userId); 7276 if (userInfo == null) { 7277 return; 7278 } 7279 // Migrate only if build fingerprints mismatch 7280 boolean migrateAppsData = !PackagePartitions.FINGERPRINT.equals( 7281 userInfo.lastLoggedInFingerprint); 7282 7283 final TimingsTraceAndSlog t = new TimingsTraceAndSlog(); 7284 t.traceBegin("prepareUserData-" + userId); 7285 mUserDataPreparer.prepareUserData(userInfo, StorageManager.FLAG_STORAGE_CE); 7286 t.traceEnd(); 7287 7288 StorageManagerInternal smInternal = LocalServices.getService(StorageManagerInternal.class); 7289 smInternal.markCeStoragePrepared(userId); 7290 7291 t.traceBegin("reconcileAppsData-" + userId); 7292 getPackageManagerInternal().reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, 7293 migrateAppsData); 7294 t.traceEnd(); 7295 } 7296 7297 /** 7298 * Examine all users present on given mounted volume, and destroy data 7299 * belonging to users that are no longer valid, or whose user ID has been 7300 * recycled. 7301 */ 7302 void reconcileUsers(String volumeUuid) { 7303 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers( 7304 /* excludePartial= */ true, 7305 /* excludeDying= */ true, 7306 /* excludePreCreated= */ false)); 7307 } 7308 7309 /** 7310 * Make a note of the last started time of a user and do some cleanup. 7311 * This is called with ActivityManagerService lock held. 7312 * @param userId the user that was just foregrounded 7313 */ 7314 public void onUserLoggedIn(@UserIdInt int userId) { 7315 UserData userData = getUserDataNoChecks(userId); 7316 if (userData == null || userData.info.partial) { 7317 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId); 7318 return; 7319 } 7320 7321 final long now = System.currentTimeMillis(); 7322 if (now > EPOCH_PLUS_30_YEARS) { 7323 userData.info.lastLoggedInTime = now; 7324 } 7325 userData.info.lastLoggedInFingerprint = PackagePartitions.FINGERPRINT; 7326 scheduleWriteUser(userId); 7327 } 7328 7329 /** 7330 * Returns the next available user id, filling in any holes in the ids. 7331 */ 7332 @VisibleForTesting 7333 int getNextAvailableId() { 7334 int nextId; 7335 synchronized (mUsersLock) { 7336 nextId = scanNextAvailableIdLocked(); 7337 if (nextId >= 0) { 7338 return nextId; 7339 } 7340 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds, 7341 // except most recently removed 7342 if (mRemovingUserIds.size() > 0) { 7343 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids."); 7344 mRemovingUserIds.clear(); 7345 for (Integer recentlyRemovedId : mRecentlyRemovedIds) { 7346 mRemovingUserIds.put(recentlyRemovedId, true); 7347 } 7348 nextId = scanNextAvailableIdLocked(); 7349 } 7350 } 7351 // If we got here, we probably recycled user ids, so invalidate any caches. 7352 UserManager.invalidateStaticUserProperties(); 7353 UserManager.invalidateUserPropertiesCache(); 7354 if (nextId < 0) { 7355 throw new IllegalStateException("No user id available!"); 7356 } 7357 return nextId; 7358 } 7359 7360 @GuardedBy("mUsersLock") 7361 private int scanNextAvailableIdLocked() { 7362 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) { 7363 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) { 7364 return i; 7365 } 7366 } 7367 return -1; 7368 } 7369 7370 private static String packageToRestrictionsFileName(String packageName) { 7371 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX; 7372 } 7373 7374 @Nullable 7375 private static String getRedacted(@Nullable String string) { 7376 return string == null ? null : string.length() + "_chars"; 7377 } 7378 7379 @Override 7380 public void setSeedAccountData(@UserIdInt int userId, String accountName, String accountType, 7381 PersistableBundle accountOptions, boolean persist) { 7382 checkManageUsersPermission("set user seed account data"); 7383 setSeedAccountDataNoChecks(userId, accountName, accountType, accountOptions, persist); 7384 } 7385 7386 private void setSeedAccountDataNoChecks(@UserIdInt int userId, @Nullable String accountName, 7387 @Nullable String accountType, @Nullable PersistableBundle accountOptions, 7388 boolean persist) { 7389 7390 synchronized (mPackagesLock) { 7391 final UserData userData; 7392 synchronized (mUsersLock) { 7393 userData = getUserDataLU(userId); 7394 if (userData == null) { 7395 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId); 7396 return; 7397 } 7398 userData.seedAccountName = truncateString(accountName, 7399 UserManager.MAX_ACCOUNT_STRING_LENGTH); 7400 userData.seedAccountType = truncateString(accountType, 7401 UserManager.MAX_ACCOUNT_STRING_LENGTH); 7402 if (accountOptions != null && accountOptions.isBundleContentsWithinLengthLimit( 7403 UserManager.MAX_ACCOUNT_OPTIONS_LENGTH)) { 7404 userData.seedAccountOptions = accountOptions; 7405 } 7406 userData.persistSeedData = persist; 7407 } 7408 if (persist) { 7409 writeUserLP(userData); 7410 } 7411 } 7412 } 7413 7414 @Override 7415 public String getSeedAccountName(@UserIdInt int userId) throws RemoteException { 7416 checkManageUsersPermission("Cannot get seed account information"); 7417 synchronized (mUsersLock) { 7418 final UserData userData = getUserDataLU(userId); 7419 return userData == null ? null : userData.seedAccountName; 7420 } 7421 } 7422 7423 @Override 7424 public String getSeedAccountType(@UserIdInt int userId) throws RemoteException { 7425 checkManageUsersPermission("Cannot get seed account information"); 7426 synchronized (mUsersLock) { 7427 final UserData userData = getUserDataLU(userId); 7428 return userData == null ? null : userData.seedAccountType; 7429 } 7430 } 7431 7432 @Override 7433 public PersistableBundle getSeedAccountOptions(@UserIdInt int userId) throws RemoteException { 7434 checkManageUsersPermission("Cannot get seed account information"); 7435 synchronized (mUsersLock) { 7436 final UserData userData = getUserDataLU(userId); 7437 return userData == null ? null : userData.seedAccountOptions; 7438 } 7439 } 7440 7441 @Override 7442 public void clearSeedAccountData(@UserIdInt int userId) throws RemoteException { 7443 checkManageUsersPermission("Cannot clear seed account information"); 7444 synchronized (mPackagesLock) { 7445 UserData userData; 7446 synchronized (mUsersLock) { 7447 userData = getUserDataLU(userId); 7448 if (userData == null) return; 7449 userData.clearSeedAccountData(); 7450 } 7451 writeUserLP(userData); 7452 } 7453 } 7454 7455 @Override 7456 public boolean someUserHasSeedAccount(String accountName, String accountType) { 7457 checkManageUsersPermission("check seed account information"); 7458 return someUserHasSeedAccountNoChecks(accountName, accountType); 7459 } 7460 7461 private boolean someUserHasSeedAccountNoChecks(String accountName, String accountType) { 7462 synchronized (mUsersLock) { 7463 final int userSize = mUsers.size(); 7464 for (int i = 0; i < userSize; i++) { 7465 final UserData data = mUsers.valueAt(i); 7466 if (data.info.isInitialized()) continue; 7467 if (mRemovingUserIds.get(data.info.id)) continue; 7468 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) { 7469 continue; 7470 } 7471 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) { 7472 continue; 7473 } 7474 return true; 7475 } 7476 } 7477 return false; 7478 } 7479 7480 @Override 7481 public boolean someUserHasAccount(String accountName, String accountType) { 7482 checkCreateUsersPermission("check seed account information"); 7483 return someUserHasAccountNoChecks(accountName, accountType); 7484 } 7485 7486 private boolean someUserHasAccountNoChecks( 7487 String accountName, String accountType) { 7488 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) { 7489 return false; 7490 } 7491 7492 final Account account = new Account(accountName, accountType); 7493 7494 return Binder.withCleanCallingIdentity(() -> 7495 AccountManager.get(mContext).someUserHasAccount(account) 7496 || someUserHasSeedAccountNoChecks(accountName, accountType)); 7497 } 7498 7499 private void setLastEnteredForegroundTimeToNow(@NonNull UserData userData) { 7500 userData.mLastEnteredForegroundTimeMillis = System.currentTimeMillis(); 7501 scheduleWriteUser(userData.info.id); 7502 } 7503 7504 @Override 7505 public void onShellCommand(FileDescriptor in, FileDescriptor out, 7506 FileDescriptor err, String[] args, ShellCallback callback, 7507 ResultReceiver resultReceiver) { 7508 (new UserManagerServiceShellCommand(this, mSystemPackageInstaller, 7509 mLockPatternUtils, mContext)) 7510 .exec(this, in, out, err, args, callback, resultReceiver); 7511 } 7512 7513 @Override 7514 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 7515 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return; 7516 7517 final long now = System.currentTimeMillis(); 7518 final long nowRealtime = SystemClock.elapsedRealtime(); 7519 final StringBuilder sb = new StringBuilder(); 7520 7521 if (args != null && args.length > 0) { 7522 switch (args[0]) { 7523 case "--user": 7524 dumpUser(pw, UserHandle.parseUserArg(args[1]), sb, now, nowRealtime); 7525 return; 7526 case "--visibility-mediator": 7527 mUserVisibilityMediator.dump(pw, args); 7528 return; 7529 } 7530 } 7531 7532 final int currentUserId = getCurrentUserId(); 7533 pw.print("Current user: "); 7534 if (currentUserId != UserHandle.USER_NULL) { 7535 pw.println(currentUserId); 7536 } else { 7537 pw.println("N/A"); 7538 } 7539 7540 pw.println(); 7541 synchronized (mPackagesLock) { 7542 synchronized (mUsersLock) { 7543 pw.println("Users:"); 7544 for (int i = 0; i < mUsers.size(); i++) { 7545 UserData userData = mUsers.valueAt(i); 7546 if (userData == null) { 7547 continue; 7548 } 7549 dumpUserLocked(pw, userData, sb, now, nowRealtime); 7550 } 7551 } 7552 7553 pw.println(); 7554 pw.println("Device properties:"); 7555 pw.println(" Device policy global restrictions:"); 7556 synchronized (mRestrictionsLock) { 7557 UserRestrictionsUtils.dumpRestrictions( 7558 pw, " ", 7559 mDevicePolicyUserRestrictions.getRestrictions(UserHandle.USER_ALL)); 7560 } 7561 pw.println(" Guest restrictions:"); 7562 synchronized (mGuestRestrictions) { 7563 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions); 7564 } 7565 synchronized (mUsersLock) { 7566 pw.println(); 7567 pw.println(" Device managed: " + mIsDeviceManaged); 7568 if (mRemovingUserIds.size() > 0) { 7569 pw.println(); 7570 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds); 7571 } 7572 } 7573 synchronized (mUserStates) { 7574 pw.print(" Started users state: ["); 7575 final int size = mUserStates.states.size(); 7576 for (int i = 0; i < size; i++) { 7577 final int userId = mUserStates.states.keyAt(i); 7578 final int state = mUserStates.states.valueAt(i); 7579 pw.print(userId); 7580 pw.print('='); 7581 pw.print(UserState.stateToString(state)); 7582 if (i != size - 1) pw.print(", "); 7583 } 7584 pw.println(']'); 7585 } 7586 synchronized (mUsersLock) { 7587 pw.print(" Cached user IDs: "); 7588 pw.println(Arrays.toString(mUserIds)); 7589 pw.print(" Cached user IDs (including pre-created): "); 7590 pw.println(Arrays.toString(mUserIdsIncludingPreCreated)); 7591 } 7592 } // synchronized (mPackagesLock) 7593 7594 pw.println(); 7595 mUserVisibilityMediator.dump(pw, args); 7596 pw.println(); 7597 7598 // Dump some capabilities 7599 pw.println(); 7600 int effectiveMaxSupportedUsers = UserManager.getMaxSupportedUsers(); 7601 pw.print(" Max users: " + effectiveMaxSupportedUsers); 7602 int defaultMaxSupportedUsers = getSystemResources() 7603 .getInteger(R.integer.config_multiuserMaximumUsers); 7604 if (effectiveMaxSupportedUsers != defaultMaxSupportedUsers) { 7605 pw.print(" (built-in value: " + defaultMaxSupportedUsers + ")"); 7606 } 7607 pw.println(" (limit reached: " + isUserLimitReached() + ")"); 7608 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers()); 7609 pw.println(" All guests ephemeral: " + getSystemResources().getBoolean( 7610 com.android.internal.R.bool.config_guestUserEphemeral)); 7611 pw.println(" Force ephemeral users: " + mForceEphemeralUsers); 7612 final boolean isHeadlessSystemUserMode = isHeadlessSystemUserMode(); 7613 pw.println(" Is headless-system mode: " + isHeadlessSystemUserMode); 7614 if (isHeadlessSystemUserMode != RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER) { 7615 pw.println(" (differs from the current default build value)"); 7616 } 7617 if (!TextUtils.isEmpty(SystemProperties.get(SYSTEM_USER_MODE_EMULATION_PROPERTY))) { 7618 pw.println(" (emulated by 'cmd user set-system-user-mode-emulation')"); 7619 if (mUpdatingSystemUserMode) { 7620 pw.println(" (and being updated after boot)"); 7621 } 7622 } 7623 if (isHeadlessSystemUserMode) { 7624 pw.println(" Can switch to headless system user: " + getSystemResources() 7625 .getBoolean(com.android.internal.R.bool.config_canSwitchToHeadlessSystemUser)); 7626 } 7627 pw.println(" User version: " + mUserVersion); 7628 pw.println(" Owner name: " + getOwnerName()); 7629 if (DBG_ALLOCATION) { 7630 pw.println(" System user allocations: " + mUser0Allocations.get()); 7631 } 7632 synchronized (mUsersLock) { 7633 pw.println(" Boot user: " + mBootUser); 7634 } 7635 pw.println("Can add private profile: "+ canAddPrivateProfile(currentUserId)); 7636 7637 pw.println(); 7638 pw.println("Number of listeners for"); 7639 synchronized (mUserRestrictionsListeners) { 7640 pw.println(" restrictions: " + mUserRestrictionsListeners.size()); 7641 } 7642 synchronized (mUserLifecycleListeners) { 7643 pw.println(" user lifecycle events: " + mUserLifecycleListeners.size()); 7644 } 7645 7646 // Dump UserTypes 7647 pw.println(); 7648 pw.println("User types version: " + mUserTypeVersion); 7649 pw.println("User types (" + mUserTypes.size() + " types):"); 7650 for (int i = 0; i < mUserTypes.size(); i++) { 7651 pw.println(" " + mUserTypes.keyAt(i) + ": "); 7652 mUserTypes.valueAt(i).dump(pw, " "); 7653 } 7654 7655 // TODO: create IndentingPrintWriter at the beginning of dump() and use the proper 7656 // indentation methods instead of explicit printing " " 7657 try (IndentingPrintWriter ipw = new IndentingPrintWriter(pw)) { 7658 7659 // Dump SystemPackageInstaller info 7660 ipw.println(); 7661 mSystemPackageInstaller.dump(ipw); 7662 7663 // NOTE: pw's not available after this point as it's auto-closed by ipw, so new dump 7664 // statements should use ipw below 7665 } 7666 } 7667 7668 private void dumpUser(PrintWriter pw, @CanBeCURRENT @UserIdInt int userId, StringBuilder sb, 7669 long now, long nowRealtime) { 7670 if (userId == UserHandle.USER_CURRENT) { 7671 final int currentUserId = getCurrentUserId(); 7672 pw.print("Current user: "); 7673 if (currentUserId == UserHandle.USER_NULL) { 7674 pw.println("Cannot determine current user"); 7675 return; 7676 } 7677 userId = currentUserId; 7678 } 7679 7680 synchronized (mUsersLock) { 7681 final UserData userData = mUsers.get(userId); 7682 if (userData == null) { 7683 pw.println("User " + userId + " not found"); 7684 return; 7685 } 7686 dumpUserLocked(pw, userData, sb, now, nowRealtime); 7687 } 7688 } 7689 7690 @GuardedBy("mUsersLock") 7691 private void dumpUserLocked(PrintWriter pw, UserData userData, StringBuilder tempStringBuilder, 7692 long now, long nowRealtime) { 7693 final UserInfo userInfo = userData.info; 7694 final int userId = userInfo.id; 7695 pw.print(" "); pw.print(userInfo); 7696 pw.print(" serialNo="); pw.print(userInfo.serialNumber); 7697 pw.print(" isPrimary="); pw.print(userInfo.isPrimary()); 7698 if (userInfo.profileGroupId != userInfo.id 7699 && userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 7700 pw.print(" parentId="); pw.print(userInfo.profileGroupId); 7701 } 7702 7703 if (mRemovingUserIds.get(userId)) { 7704 pw.print(" <removing> "); 7705 } 7706 if (userInfo.partial) { 7707 pw.print(" <partial>"); 7708 } 7709 if (userInfo.preCreated) { 7710 pw.print(" <pre-created>"); 7711 } 7712 if (userInfo.convertedFromPreCreated) { 7713 pw.print(" <converted>"); 7714 } 7715 pw.println(); 7716 pw.print(" Type: "); pw.println(userInfo.userType); 7717 pw.print(" Flags: "); pw.print(userInfo.flags); pw.print(" ("); 7718 pw.print(UserInfo.flagsToString(userInfo.flags)); pw.println(")"); 7719 pw.print(" State: "); 7720 final int state; 7721 synchronized (mUserStates) { 7722 state = mUserStates.get(userId, -1); 7723 } 7724 pw.println(UserState.stateToString(state)); 7725 pw.print(" Created: "); 7726 dumpTimeAgo(pw, tempStringBuilder, now, userInfo.creationTime); 7727 7728 pw.print(" Last logged in: "); 7729 dumpTimeAgo(pw, tempStringBuilder, now, userInfo.lastLoggedInTime); 7730 7731 pw.print(" Last logged in fingerprint: "); 7732 pw.println(userInfo.lastLoggedInFingerprint); 7733 7734 pw.print(" Start time: "); 7735 dumpTimeAgo(pw, tempStringBuilder, nowRealtime, userData.startRealtime); 7736 7737 pw.print(" Unlock time: "); 7738 dumpTimeAgo(pw, tempStringBuilder, nowRealtime, userData.unlockRealtime); 7739 7740 pw.print(" Last entered foreground: "); 7741 dumpTimeAgo(pw, tempStringBuilder, now, userData.mLastEnteredForegroundTimeMillis); 7742 7743 pw.print(" Has profile owner: "); 7744 pw.println(mIsUserManaged.get(userId)); 7745 7746 pw.println(" Restrictions:"); 7747 synchronized (mRestrictionsLock) { 7748 UserRestrictionsUtils.dumpRestrictions( 7749 pw, " ", mBaseUserRestrictions.getRestrictions(userInfo.id)); 7750 pw.println(" Device policy restrictions:"); 7751 UserRestrictionsUtils.dumpRestrictions( 7752 pw, " ", 7753 mDevicePolicyUserRestrictions.getRestrictions(userInfo.id)); 7754 pw.println(" Effective restrictions:"); 7755 UserRestrictionsUtils.dumpRestrictions( 7756 pw, " ", 7757 mCachedEffectiveUserRestrictions.getRestrictions(userInfo.id)); 7758 } 7759 7760 if (userData.account != null) { 7761 pw.print(" Account name: " + userData.account); 7762 pw.println(); 7763 } 7764 7765 if (userData.seedAccountName != null) { 7766 pw.print(" Seed account name: " + userData.seedAccountName); 7767 pw.println(); 7768 if (userData.seedAccountType != null) { 7769 pw.print(" account type: " + userData.seedAccountType); 7770 pw.println(); 7771 } 7772 if (userData.seedAccountOptions != null) { 7773 pw.print(" account options exist"); 7774 pw.println(); 7775 } 7776 } 7777 7778 pw.print(" Can have profile: "); 7779 pw.println(userInfo.canHaveProfile()); 7780 7781 if (userData.userProperties != null) { 7782 userData.userProperties.println(pw, " "); 7783 } 7784 7785 pw.println(" Ignore errors preparing storage: " 7786 + userData.getIgnorePrepareStorageErrors()); 7787 } 7788 7789 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) { 7790 if (time == 0) { 7791 pw.println("<unknown>"); 7792 } else { 7793 sb.setLength(0); 7794 TimeUtils.formatDuration(nowTime - time, sb); 7795 sb.append(" ago"); 7796 pw.println(sb); 7797 } 7798 } 7799 7800 final class MainHandler extends Handler { 7801 7802 @Override 7803 public void handleMessage(Message msg) { 7804 switch (msg.what) { 7805 case WRITE_USER_LIST_MSG: { 7806 removeMessages(WRITE_USER_LIST_MSG); 7807 synchronized (mPackagesLock) { 7808 writeUserListLP(); 7809 } 7810 break; 7811 } 7812 case WRITE_USER_MSG: 7813 removeMessages(WRITE_USER_MSG, msg.obj); 7814 synchronized (mPackagesLock) { 7815 int userId = (int) msg.obj; 7816 UserData userData = getUserDataNoChecks(userId); 7817 if (userData != null) { 7818 writeUserLP(userData); 7819 } else { 7820 Slog.i(LOG_TAG, "handle(WRITE_USER_MSG): no data for user " + userId 7821 + ", it was probably removed before handler could handle it"); 7822 } 7823 } 7824 break; 7825 } 7826 } 7827 } 7828 7829 /** 7830 * @param userId 7831 * @return whether the user has been initialized yet 7832 */ 7833 boolean isUserInitialized(@UserIdInt int userId) { 7834 return mLocalService.isUserInitialized(userId); 7835 } 7836 7837 private class LocalService extends UserManagerInternal { 7838 @Override 7839 public void setDevicePolicyUserRestrictions(@UserIdInt int originatingUserId, 7840 @NonNull Bundle global, @NonNull RestrictionsSet local, 7841 boolean isDeviceOwner) { 7842 UserManagerService.this.setDevicePolicyUserRestrictionsInner(originatingUserId, 7843 global, local, isDeviceOwner); 7844 } 7845 7846 @Override 7847 public void setUserRestriction(@UserIdInt int userId, @NonNull String key, boolean value) { 7848 UserManagerService.this.setUserRestrictionInner(userId, key, value); 7849 } 7850 7851 @Override 7852 public boolean getUserRestriction(@UserIdInt int userId, String key) { 7853 return getUserRestrictions(userId).getBoolean(key); 7854 } 7855 7856 @Override 7857 public void addUserRestrictionsListener(UserRestrictionsListener listener) { 7858 synchronized (mUserRestrictionsListeners) { 7859 mUserRestrictionsListeners.add(listener); 7860 } 7861 } 7862 7863 @Override 7864 public void removeUserRestrictionsListener(UserRestrictionsListener listener) { 7865 synchronized (mUserRestrictionsListeners) { 7866 mUserRestrictionsListeners.remove(listener); 7867 } 7868 } 7869 7870 @Override 7871 public void addUserLifecycleListener(UserLifecycleListener listener) { 7872 synchronized (mUserLifecycleListeners) { 7873 mUserLifecycleListeners.add(listener); 7874 } 7875 } 7876 7877 @Override 7878 public void removeUserLifecycleListener(UserLifecycleListener listener) { 7879 synchronized (mUserLifecycleListeners) { 7880 mUserLifecycleListeners.remove(listener); 7881 } 7882 } 7883 7884 // TODO(b/258213147): Remove 7885 @Override 7886 public void setDeviceManaged(boolean isManaged) { 7887 synchronized (mUsersLock) { 7888 mIsDeviceManaged = isManaged; 7889 } 7890 } 7891 7892 // TODO(b/258213147): Remove 7893 @Override 7894 public boolean isDeviceManaged() { 7895 synchronized (mUsersLock) { 7896 return mIsDeviceManaged; 7897 } 7898 } 7899 7900 // TODO(b/258213147): Remove 7901 @Override 7902 public void setUserManaged(@UserIdInt int userId, boolean isManaged) { 7903 synchronized (mUsersLock) { 7904 mIsUserManaged.put(userId, isManaged); 7905 } 7906 } 7907 7908 // TODO(b/258213147): Remove 7909 @Override 7910 public boolean isUserManaged(@UserIdInt int userId) { 7911 synchronized (mUsersLock) { 7912 return mIsUserManaged.get(userId); 7913 } 7914 } 7915 7916 @Override 7917 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) { 7918 final long ident = Binder.clearCallingIdentity(); 7919 try { 7920 synchronized (mPackagesLock) { 7921 UserData userData = getUserDataNoChecks(userId); 7922 if (userData == null || userData.info.partial) { 7923 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId); 7924 return; 7925 } 7926 writeBitmapLP(userData.info, bitmap); 7927 writeUserLP(userData); 7928 } 7929 sendUserInfoChangedBroadcast(userId); 7930 } finally { 7931 Binder.restoreCallingIdentity(ident); 7932 } 7933 } 7934 7935 @Override 7936 public void setForceEphemeralUsers(boolean forceEphemeralUsers) { 7937 synchronized (mUsersLock) { 7938 mForceEphemeralUsers = forceEphemeralUsers; 7939 } 7940 } 7941 7942 @Override 7943 public void removeAllUsers() { 7944 if (UserHandle.USER_SYSTEM == getCurrentUserId()) { 7945 // Remove the non-system users straight away. 7946 removeAllUsersExceptSystemAndPermanentAdminMain(); 7947 } else { 7948 // Switch to the system user first and then remove the other users. 7949 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() { 7950 @Override 7951 public void onReceive(Context context, Intent intent) { 7952 int userId = 7953 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 7954 if (userId != UserHandle.USER_SYSTEM) { 7955 return; 7956 } 7957 mContext.unregisterReceiver(this); 7958 removeAllUsersExceptSystemAndPermanentAdminMain(); 7959 } 7960 }; 7961 IntentFilter userSwitchedFilter = new IntentFilter(); 7962 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED); 7963 mContext.registerReceiver( 7964 userSwitchedReceiver, userSwitchedFilter, null, mHandler); 7965 7966 // Switch to the system user. 7967 ActivityManager am = 7968 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); 7969 am.switchUser(UserHandle.USER_SYSTEM); 7970 } 7971 } 7972 7973 @Override 7974 public void onEphemeralUserStop(@UserIdInt int userId) { 7975 synchronized (mUsersLock) { 7976 UserInfo userInfo = getUserInfoLU(userId); 7977 if (userInfo != null && userInfo.isEphemeral()) { 7978 // Do not allow switching back to the ephemeral user again as the user is going 7979 // to be deleted. 7980 addUserInfoFlags(userInfo, UserInfo.FLAG_DISABLED); 7981 if (userInfo.isGuest()) { 7982 // Indicate that the guest will be deleted after it stops. 7983 userInfo.guestToRemove = true; 7984 } 7985 } 7986 } 7987 } 7988 7989 @Override 7990 public @NonNull UserInfo createUserEvenWhenDisallowed( 7991 @Nullable String name, @NonNull String userType, @UserInfoFlag int flags, 7992 @Nullable String[] disallowedPackages, @Nullable Object token) 7993 throws UserManager.CheckedUserOperationException { 7994 7995 return createUserInternalUnchecked(name, userType, flags, 7996 UserHandle.USER_NULL, /* preCreated= */ false, disallowedPackages, token); 7997 } 7998 7999 @Override 8000 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) { 8001 return removeUserWithProfilesUnchecked(userId); 8002 } 8003 8004 @Override 8005 public boolean isUserRunning(@UserIdInt int userId) { 8006 int state; 8007 synchronized (mUserStates) { 8008 state = mUserStates.get(userId, UserState.STATE_NONE); 8009 } 8010 8011 return state != UserState.STATE_NONE 8012 && state != UserState.STATE_STOPPING 8013 && state != UserState.STATE_SHUTDOWN; 8014 } 8015 8016 @Override 8017 public void setUserState(@UserIdInt int userId, int userState) { 8018 synchronized (mUserStates) { 8019 mUserStates.put(userId, userState); 8020 } 8021 } 8022 8023 @Override 8024 public void removeUserState(@UserIdInt int userId) { 8025 synchronized (mUserStates) { 8026 mUserStates.delete(userId); 8027 } 8028 } 8029 8030 @Override 8031 public int[] getUserIds() { 8032 return UserManagerService.this.getUserIds(); 8033 } 8034 8035 @Override 8036 public @NonNull List<UserInfo> getUsers(boolean excludeDying) { 8037 return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */ true); 8038 } 8039 8040 @Override 8041 public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying, 8042 boolean excludePreCreated) { 8043 return UserManagerService.this.getUsersInternal(excludePartial, excludeDying, 8044 excludePreCreated); 8045 } 8046 8047 @Override 8048 public @NonNull int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) { 8049 synchronized (mUsersLock) { 8050 return getProfileIdsLU(userId, null /* userType */, enabledOnly, /* excludeHidden */ 8051 false).toArray(); 8052 } 8053 } 8054 8055 @Override 8056 public int[] getProfileIdsExcludingHidden(@UserIdInt int userId, boolean enabledOnly) { 8057 synchronized (mUsersLock) { 8058 return getProfileIdsLU(userId, null /* userType */, enabledOnly, /* excludeHidden */ 8059 true).toArray(); 8060 } 8061 } 8062 8063 @Override 8064 public @Nullable LauncherUserInfo getLauncherUserInfo(@UserIdInt int userId) { 8065 UserInfo userInfo; 8066 synchronized (mUsersLock) { 8067 userInfo = getUserInfoLU(userId); 8068 } 8069 if (userInfo != null) { 8070 final UserTypeDetails userDetails = getUserTypeDetails(userInfo); 8071 8072 if (Flags.addLauncherUserConfig()) { 8073 Bundle config = new Bundle(); 8074 if (userInfo.isPrivateProfile()) { 8075 try { 8076 int parentId = getProfileParentIdUnchecked(userId); 8077 config.putBoolean(PRIVATE_SPACE_ENTRYPOINT_HIDDEN, 8078 Settings.Secure.getIntForUser(mContext.getContentResolver(), 8079 HIDE_PRIVATESPACE_ENTRY_POINT, parentId) == 1); 8080 } catch (Settings.SettingNotFoundException e) { 8081 config.putBoolean(PRIVATE_SPACE_ENTRYPOINT_HIDDEN, false); 8082 } 8083 } 8084 return new LauncherUserInfo.Builder(userDetails.getName(), 8085 userInfo.serialNumber, config).build(); 8086 } 8087 8088 return new LauncherUserInfo.Builder(userDetails.getName(), 8089 userInfo.serialNumber).build(); 8090 } else { 8091 return null; 8092 } 8093 } 8094 8095 @Override 8096 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) { 8097 int state; 8098 synchronized (mUserStates) { 8099 state = mUserStates.get(userId, -1); 8100 } 8101 // Special case: in the stopping/shutdown state, CE storage can still be unlocked. 8102 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) { 8103 return StorageManager.isCeStorageUnlocked(userId); 8104 } 8105 return (state == UserState.STATE_RUNNING_UNLOCKING) 8106 || (state == UserState.STATE_RUNNING_UNLOCKED); 8107 } 8108 8109 /** 8110 * The return values of this method are cached in clients. If the 8111 * logic in this function changes then the cache invalidation code 8112 * may need to be revisited. 8113 */ 8114 @Override 8115 public boolean isUserUnlocked(@UserIdInt int userId) { 8116 int state; 8117 synchronized (mUserStates) { 8118 state = mUserStates.get(userId, -1); 8119 } 8120 // Special case: in the stopping/shutdown state, CE storage can still be unlocked. 8121 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) { 8122 return StorageManager.isCeStorageUnlocked(userId); 8123 } 8124 return state == UserState.STATE_RUNNING_UNLOCKED; 8125 } 8126 8127 @Override 8128 public boolean isUserInitialized(@UserIdInt int userId) { 8129 final UserInfo userInfo = getUserInfo(userId); 8130 return userInfo != null && (userInfo.flags & UserInfo.FLAG_INITIALIZED) != 0; 8131 } 8132 8133 @Override 8134 public boolean exists(@UserIdInt int userId) { 8135 return getUserInfoNoChecks(userId) != null; 8136 } 8137 8138 @Override 8139 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg, 8140 boolean throwSecurityException) { 8141 if (targetUserId == callingUserId) { 8142 return true; 8143 } 8144 synchronized (mUsersLock) { 8145 UserInfo callingUserInfo = getUserInfoLU(callingUserId); 8146 if (callingUserInfo == null || callingUserInfo.isProfile()) { 8147 if (throwSecurityException) { 8148 throw new SecurityException( 8149 debugMsg + " for another profile " 8150 + targetUserId + " from " + callingUserId); 8151 } 8152 Slog.w(LOG_TAG, debugMsg + " for another profile " 8153 + targetUserId + " from " + callingUserId); 8154 return false; 8155 } 8156 8157 UserInfo targetUserInfo = getUserInfoLU(targetUserId); 8158 if (targetUserInfo == null || !targetUserInfo.isEnabled()) { 8159 // Do not throw any exception here as this could happen due to race conditions 8160 // between the system updating its state and the client getting notified. 8161 if (throwSecurityException) { 8162 Slog.w(LOG_TAG, debugMsg + " for disabled profile " 8163 + targetUserId + " from " + callingUserId); 8164 } 8165 return false; 8166 } 8167 8168 // TODO(b/276473320): Probably use isSameUserOrProfileGroupOrTargetIsCommunal. 8169 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID || 8170 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) { 8171 if (throwSecurityException) { 8172 throw new SecurityException( 8173 debugMsg + " for unrelated profile " + targetUserId); 8174 } 8175 return false; 8176 } 8177 } 8178 return true; 8179 } 8180 8181 @Override 8182 public int getProfileParentId(@UserIdInt int userId) { 8183 return getProfileParentIdUnchecked(userId); 8184 } 8185 8186 @Override 8187 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId, 8188 String value, int callingUid) { 8189 return UserManagerService.this.isSettingRestrictedForUser(setting, userId, 8190 value, callingUid); 8191 } 8192 8193 @Override 8194 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) { 8195 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) { 8196 return false; 8197 } 8198 Bundle restrictions = getEffectiveUserRestrictions(userId); 8199 return restrictions != null && restrictions.getBoolean(restrictionKey); 8200 } 8201 8202 @Override 8203 public @Nullable UserInfo getUserInfo(@UserIdInt int userId) { 8204 UserData userData; 8205 synchronized (mUsersLock) { 8206 userData = mUsers.get(userId); 8207 } 8208 return userData == null ? null : userData.info; 8209 } 8210 8211 @Override 8212 public @NonNull UserInfo[] getUserInfos() { 8213 synchronized (mUsersLock) { 8214 int userSize = mUsers.size(); 8215 UserInfo[] allInfos = new UserInfo[userSize]; 8216 for (int i = 0; i < userSize; i++) { 8217 allInfos[i] = mUsers.valueAt(i).info; 8218 } 8219 return allInfos; 8220 } 8221 } 8222 8223 @Override 8224 public void setDefaultCrossProfileIntentFilters( 8225 @UserIdInt int parentUserId, @UserIdInt int profileUserId) { 8226 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(profileUserId); 8227 final Bundle restrictions = getEffectiveUserRestrictions(profileUserId); 8228 UserManagerService.this.setDefaultCrossProfileIntentFilters( 8229 profileUserId, userTypeDetails, restrictions, parentUserId); 8230 } 8231 8232 @Override 8233 public boolean shouldIgnorePrepareStorageErrors(int userId) { 8234 synchronized (mUsersLock) { 8235 UserData userData = mUsers.get(userId); 8236 return userData != null && userData.getIgnorePrepareStorageErrors(); 8237 } 8238 } 8239 8240 @Override 8241 public @Nullable UserProperties getUserProperties(@UserIdInt int userId) { 8242 final UserProperties props = getUserPropertiesInternal(userId); 8243 if (props == null) { 8244 Slog.w(LOG_TAG, "A null UserProperties was returned for user " + userId); 8245 } 8246 return props; 8247 } 8248 8249 @Override 8250 @UserAssignmentResult 8251 public int assignUserToDisplayOnStart(@UserIdInt int userId, 8252 @UserIdInt int profileGroupId, @UserStartMode int userStartMode, int displayId) { 8253 8254 final UserProperties properties = getUserProperties(userId); 8255 final boolean isAlwaysVisible = properties != null && properties.getAlwaysVisible(); 8256 8257 return mUserVisibilityMediator.assignUserToDisplayOnStart(userId, profileGroupId, 8258 userStartMode, displayId, isAlwaysVisible); 8259 } 8260 8261 @Override 8262 public boolean assignUserToExtraDisplay(int userId, int displayId) { 8263 return mUserVisibilityMediator.assignUserToExtraDisplay(userId, displayId); 8264 } 8265 8266 @Override 8267 public boolean unassignUserFromExtraDisplay(int userId, int displayId) { 8268 return mUserVisibilityMediator.unassignUserFromExtraDisplay(userId, displayId); 8269 } 8270 8271 @Override 8272 public void unassignUserFromDisplayOnStop(@UserIdInt int userId) { 8273 mUserVisibilityMediator.unassignUserFromDisplayOnStop(userId); 8274 } 8275 8276 @Override 8277 public boolean isUserVisible(@UserIdInt int userId) { 8278 return mUserVisibilityMediator.isUserVisible(userId); 8279 } 8280 8281 @Override 8282 public boolean isUserVisible(@UserIdInt int userId, int displayId) { 8283 return mUserVisibilityMediator.isUserVisible(userId, displayId); 8284 } 8285 8286 @Override 8287 public boolean isVisibleBackgroundFullUser(@UserIdInt int userId) { 8288 if (!UserManager.isVisibleBackgroundUsersEnabled()) { 8289 return false; 8290 } 8291 boolean isForeground = userId == getCurrentUserId(); 8292 boolean isProfile = isProfileUnchecked(userId); 8293 boolean isVisible = isUserVisible(userId); 8294 return isVisible && !isForeground && !isProfile; 8295 } 8296 8297 @Override 8298 public int getMainDisplayAssignedToUser(@UserIdInt int userId) { 8299 return mUserVisibilityMediator.getMainDisplayAssignedToUser(userId); 8300 } 8301 8302 @Override 8303 public @Nullable int[] getDisplaysAssignedToUser(@UserIdInt int userId) { 8304 return mUserVisibilityMediator.getDisplaysAssignedToUser(userId); 8305 } 8306 8307 @Override 8308 public @UserIdInt int getUserAssignedToDisplay(int displayId) { 8309 return mUserVisibilityMediator.getUserAssignedToDisplay(displayId); 8310 } 8311 8312 @Override 8313 public void addUserVisibilityListener(UserVisibilityListener listener) { 8314 mUserVisibilityMediator.addListener(listener); 8315 } 8316 8317 @Override 8318 public void removeUserVisibilityListener(UserVisibilityListener listener) { 8319 mUserVisibilityMediator.removeListener(listener); 8320 } 8321 8322 @Override 8323 public void onSystemUserVisibilityChanged(boolean visible) { 8324 mUserVisibilityMediator.onSystemUserVisibilityChanged(visible); 8325 } 8326 8327 @Override 8328 public int[] getUserTypesForStatsd(@UserIdInt int[] userIds) { 8329 if (userIds == null) { 8330 return null; 8331 } 8332 final int[] userTypes = new int[userIds.length]; 8333 for (int i = 0; i < userTypes.length; i++) { 8334 final UserInfo userInfo = getUserInfo(userIds[i]); 8335 if (userInfo == null) { 8336 // Not possible because the input user ids should all be valid 8337 userTypes[i] = mUserJourneyLogger.getUserTypeForStatsd(""); 8338 } else { 8339 userTypes[i] = mUserJourneyLogger.getUserTypeForStatsd(userInfo.userType); 8340 } 8341 } 8342 return userTypes; 8343 } 8344 8345 @Override 8346 public @UserIdInt int getMainUserId() { 8347 return getMainUserIdUnchecked(); 8348 } 8349 8350 @Override 8351 public @UserIdInt int getBootUser(boolean waitUntilSet) 8352 throws UserManager.CheckedUserOperationException { 8353 if (waitUntilSet) { 8354 final TimingsTraceAndSlog t = new TimingsTraceAndSlog(); 8355 t.traceBegin("wait-boot-user"); 8356 try { 8357 if (mBootUserLatch.getCount() != 0) { 8358 Slogf.d(LOG_TAG, 8359 "Sleeping for boot user to be set. " 8360 + "Max sleep for Time: %d", BOOT_USER_SET_TIMEOUT_MS); 8361 } 8362 if (!mBootUserLatch.await(BOOT_USER_SET_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { 8363 Slogf.w(LOG_TAG, "Boot user not set. Timeout: %d", 8364 BOOT_USER_SET_TIMEOUT_MS); 8365 } 8366 } catch (InterruptedException e) { 8367 Thread.currentThread().interrupt(); 8368 Slogf.w(LOG_TAG, e, "InterruptedException during wait for boot user."); 8369 } 8370 t.traceEnd(); 8371 } 8372 8373 return getBootUserUnchecked(); 8374 } 8375 8376 @Override 8377 public @CanBeNULL @UserIdInt int getCommunalProfileId() { 8378 return getCommunalProfileIdUnchecked(); 8379 } 8380 8381 @Override 8382 public @CanBeNULL @UserIdInt int getSupervisingProfileId() { 8383 return UserManagerService.this.getSupervisingProfileId(); 8384 } 8385 } // class LocalService 8386 8387 8388 8389 /** 8390 * Check if user has restrictions 8391 * @param restriction restrictions to check 8392 * @param userId id of the user 8393 * 8394 * @throws {@link android.os.UserManager.CheckedUserOperationException} if user has any of the 8395 * specified restrictions 8396 */ 8397 private void enforceUserRestriction(String restriction, @UserIdInt int userId, String message) 8398 throws UserManager.CheckedUserOperationException { 8399 if (hasUserRestriction(restriction, userId)) { 8400 String errorMessage = (message != null ? (message + ": ") : "") 8401 + restriction + " is enabled."; 8402 Slog.w(LOG_TAG, errorMessage); 8403 if (android.multiuser.Flags.showDifferentCreationErrorForUnsupportedDevices()) { 8404 throw new UserManager.CheckedUserOperationException(errorMessage, 8405 USER_OPERATION_ERROR_USER_RESTRICTED); 8406 } else { 8407 throw new UserManager.CheckedUserOperationException(errorMessage, 8408 USER_OPERATION_ERROR_UNKNOWN); 8409 } 8410 } 8411 } 8412 8413 /** 8414 * Throws CheckedUserOperationException and shows error log 8415 * @param message message for exception and logging 8416 * @param userOperationResult result/error code 8417 * @throws UserManager.CheckedUserOperationException 8418 */ 8419 private void throwCheckedUserOperationException(@NonNull String message, 8420 @UserManager.UserOperationResult int userOperationResult) 8421 throws UserManager.CheckedUserOperationException { 8422 Slog.e(LOG_TAG, message); 8423 throw new UserManager.CheckedUserOperationException(message, userOperationResult); 8424 } 8425 8426 /* Remove all the users except the system and permanent admin main.*/ 8427 private void removeAllUsersExceptSystemAndPermanentAdminMain() { 8428 ArrayList<UserInfo> usersToRemove = new ArrayList<>(); 8429 synchronized (mUsersLock) { 8430 final int userSize = mUsers.size(); 8431 for (int i = 0; i < userSize; i++) { 8432 UserInfo ui = mUsers.valueAt(i).info; 8433 if (ui.id != UserHandle.USER_SYSTEM && !isNonRemovableMainUser(ui)) { 8434 usersToRemove.add(ui); 8435 } 8436 } 8437 } 8438 for (UserInfo ui: usersToRemove) { 8439 removeUser(ui.id); 8440 } 8441 } 8442 8443 private static void debug(String message) { 8444 Slog.d(LOG_TAG, message 8445 + (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : "")); 8446 } 8447 8448 /** @see #getMaxUsersOfTypePerParent(UserTypeDetails) */ 8449 @VisibleForTesting 8450 int getMaxUsersOfTypePerParent(String userType) { 8451 final UserTypeDetails type = mUserTypes.get(userType); 8452 if (type == null) { 8453 return 0; 8454 } 8455 return getMaxUsersOfTypePerParent(type); 8456 } 8457 8458 /** 8459 * Returns the maximum number of users allowed for the given userTypeDetails per parent user. 8460 * This is applicable for user types that are {@link UserTypeDetails#isProfile()}. 8461 * If there is no maximum, {@link UserTypeDetails#UNLIMITED_NUMBER_OF_USERS} is returned. 8462 * Under certain circumstances (such as after a change-user-type) the max value can actually 8463 * be exceeded: this is allowed in order to keep the device in a usable state. 8464 * An error is logged in {@link UserManagerService#upgradeProfileToTypeLU} 8465 */ 8466 private static int getMaxUsersOfTypePerParent(UserTypeDetails userTypeDetails) { 8467 final int defaultMax = userTypeDetails.getMaxAllowedPerParent(); 8468 if (!Build.IS_DEBUGGABLE) { 8469 return defaultMax; 8470 } else { 8471 if (userTypeDetails.isManagedProfile()) { 8472 return SystemProperties.getInt("persist.sys.max_profiles", defaultMax); 8473 } 8474 } 8475 return defaultMax; 8476 } 8477 8478 @GuardedBy("mUsersLock") 8479 @VisibleForTesting 8480 int getFreeProfileBadgeLU(int parentUserId, String userType) { 8481 Set<Integer> usedBadges = new ArraySet<>(); 8482 final int userSize = mUsers.size(); 8483 for (int i = 0; i < userSize; i++) { 8484 UserInfo ui = mUsers.valueAt(i).info; 8485 // Check which badge indexes are already used by this profile group. 8486 if (ui.userType.equals(userType) 8487 && ui.profileGroupId == parentUserId 8488 && !mRemovingUserIds.get(ui.id)) { 8489 usedBadges.add(ui.profileBadge); 8490 } 8491 } 8492 int maxUsersOfType = getMaxUsersOfTypePerParent(userType); 8493 if (maxUsersOfType == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) { 8494 maxUsersOfType = Integer.MAX_VALUE; 8495 } 8496 for (int i = 0; i < maxUsersOfType; i++) { 8497 if (!usedBadges.contains(i)) { 8498 return i; 8499 } 8500 } 8501 return 0; 8502 } 8503 8504 /** 8505 * Formerly: Checks if the given user has a profile associated with it. 8506 * Now: Just throws. Do not use it. 8507 * @param userId The parent user (passing in a profile user is not supported) 8508 * @deprecated 8509 */ 8510 boolean hasProfile(@UserIdInt int userId) { 8511 if (!android.content.pm.Flags.removeCrossUserPermissionHack()) { 8512 synchronized (mUsersLock) { 8513 UserInfo userInfo = getUserInfoLU(userId); 8514 final int userSize = mUsers.size(); 8515 for (int i = 0; i < userSize; i++) { 8516 UserInfo profile = mUsers.valueAt(i).info; 8517 if (userId != profile.id && isSameProfileGroup(userInfo, profile)) { 8518 return true; 8519 } 8520 } 8521 return false; 8522 } 8523 } else { 8524 // TODO(b/332664521): Remove this method entirely. It is no longer used. 8525 throw new UnsupportedOperationException(); 8526 } 8527 } 8528 8529 /** 8530 * Checks if the calling package name matches with the calling UID, throw 8531 * {@link SecurityException} if not. 8532 */ 8533 private void verifyCallingPackage(String callingPackage, int callingUid) { 8534 int packageUid = mPm.snapshotComputer() 8535 .getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid)); 8536 if (packageUid != callingUid) { 8537 throw new SecurityException("Specified package " + callingPackage 8538 + " does not match the calling uid " + callingUid); 8539 } 8540 } 8541 8542 /** Retrieves the internal package manager interface. */ 8543 private PackageManagerInternal getPackageManagerInternal() { 8544 // Don't need to synchonize; worst-case scenario LocalServices will be called twice. 8545 if (mPmInternal == null) { 8546 mPmInternal = LocalServices.getService(PackageManagerInternal.class); 8547 } 8548 return mPmInternal; 8549 } 8550 8551 /** Returns the internal device policy manager interface. */ 8552 private DevicePolicyManagerInternal getDevicePolicyManagerInternal() { 8553 if (mDevicePolicyManagerInternal == null) { 8554 mDevicePolicyManagerInternal = 8555 LocalServices.getService(DevicePolicyManagerInternal.class); 8556 } 8557 return mDevicePolicyManagerInternal; 8558 } 8559 8560 /** Returns the internal activity manager interface. */ 8561 private @Nullable ActivityManagerInternal getActivityManagerInternal() { 8562 if (mAmInternal == null) { 8563 mAmInternal = LocalServices.getService(ActivityManagerInternal.class); 8564 } 8565 return mAmInternal; 8566 } 8567 8568 /** 8569 * Returns true, when user has {@link UserInfo#FLAG_MAIN} and system property 8570 * {@link com.android.internal.R.bool#config_isMainUserPermanentAdmin} is true. 8571 */ 8572 private boolean isNonRemovableMainUser(UserInfo userInfo) { 8573 return userInfo.isMain() && isMainUserPermanentAdmin(); 8574 } 8575 8576 /** 8577 * Returns true if {@link com.android.internal.R.bool#config_isMainUserPermanentAdmin} is true. 8578 * If the main user is a permanent admin user it can't be deleted 8579 * or downgraded to non-admin status. 8580 */ 8581 public boolean isMainUserPermanentAdmin() { 8582 return getSystemResources().getBoolean(R.bool.config_isMainUserPermanentAdmin); 8583 } 8584 8585 /** 8586 * Returns true if {@link com.android.internal.R.bool#config_canSwitchToHeadlessSystemUser} 8587 * is true. If allowed, headless system user can run in the foreground even though 8588 * it is not a full user. 8589 */ 8590 public boolean canSwitchToHeadlessSystemUser() { 8591 return getSystemResources().getBoolean(R.bool.config_canSwitchToHeadlessSystemUser); 8592 } 8593 8594 /** 8595 * Returns instance of {@link com.android.server.pm.UserJourneyLogger}. 8596 */ 8597 public UserJourneyLogger getUserJourneyLogger() { 8598 return mUserJourneyLogger; 8599 } 8600 8601 } 8602