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