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