• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 int MAX_USER_STRING_LENGTH = 500;
289 
290     private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
291 
292     static final int WRITE_USER_MSG = 1;
293     static final int WRITE_USER_LIST_MSG = 2;
294     static final int WRITE_USER_DELAY = 2*1000;  // 2 seconds
295 
296     private static final long BOOT_USER_SET_TIMEOUT_MS = 300_000;
297 
298     // Tron counters
299     private static final String TRON_GUEST_CREATED = "users_guest_created";
300     private static final String TRON_USER_CREATED = "users_user_created";
301     private static final String TRON_DEMO_CREATED = "users_demo_created";
302 
303     // App ops that should be restricted in quiet mode
304     private static final int[] QUIET_MODE_RESTRICTED_APP_OPS = {
305             AppOpsManager.OP_COARSE_LOCATION,
306             AppOpsManager.OP_FINE_LOCATION,
307             AppOpsManager.OP_GPS,
308             AppOpsManager.OP_BODY_SENSORS,
309             AppOpsManager.OP_ACTIVITY_RECOGNITION,
310             AppOpsManager.OP_BLUETOOTH_SCAN,
311             AppOpsManager.OP_NEARBY_WIFI_DEVICES,
312             AppOpsManager.OP_RECORD_AUDIO,
313             AppOpsManager.OP_CAMERA,
314     };
315 
316     private final Context mContext;
317     private final PackageManagerService mPm;
318 
319     /**
320      * Lock for packages. If using with {@link #mUsersLock}, {@link #mPackagesLock} should be
321      * acquired first.
322      */
323     private final Object mPackagesLock;
324     private final UserDataPreparer mUserDataPreparer;
325     /**
326      * Short-term lock for internal state, when interaction/sync with PM is not required. If using
327      * with {@link #mPackagesLock}, {@link #mPackagesLock} should be acquired first.
328      */
329     private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
330     private final Object mRestrictionsLock = new Object();
331     // Used for serializing access to app restriction files
332     private final Object mAppRestrictionsLock = new Object();
333 
334     private final Handler mHandler;
335 
336     private final File mUsersDir;
337     private final File mUserListFile;
338 
339     private final IBinder mUserRestrictionToken = new Binder();
340     private final IBinder mQuietModeToken = new Binder();
341 
342     /** Installs system packages based on user-type. */
343     private final UserSystemPackageInstaller mSystemPackageInstaller;
344 
345     private PackageManagerInternal mPmInternal;
346     private DevicePolicyManagerInternal mDevicePolicyManagerInternal;
347     private ActivityManagerInternal mAmInternal;
348 
349     /** Indicates that this is the 1st boot after the system user mode was changed by emulation. */
350     private boolean mUpdatingSystemUserMode;
351 
352     /** Count down latch to wait while boot user is not set.*/
353     private final CountDownLatch mBootUserLatch = new CountDownLatch(1);
354     /**
355      * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
356      */
357     @VisibleForTesting
358     static class UserData {
359         // Basic user information and properties
360         @NonNull UserInfo info;
361         // Account name used when there is a strong association between a user and an account
362         String account;
363         // Account information for seeding into a newly created user. This could also be
364         // used for login validation for an existing user, for updating their credentials.
365         // In the latter case, data may not need to be persisted as it is only valid for the
366         // current login session.
367         String seedAccountName;
368         String seedAccountType;
369         PersistableBundle seedAccountOptions;
370         // Whether to perist the seed account information to be available after a boot
371         boolean persistSeedData;
372 
373         /** Properties of the user whose default values originate from its user type. */
374         UserProperties userProperties;
375 
376         /** Elapsed realtime since boot when the user started. */
377         long startRealtime;
378 
379         /** Elapsed realtime since boot when the user was unlocked. */
380         long unlockRealtime;
381 
382         /** Wall clock time in millis when the user last entered the foreground. */
383         long mLastEnteredForegroundTimeMillis;
384 
385         private long mLastRequestQuietModeEnabledMillis;
386 
387         /**
388          * {@code true} if the system should ignore errors when preparing the
389          * storage directories for this user. This is {@code false} for all new
390          * users; it will only be {@code true} for users that already existed
391          * on-disk from an older version of Android.
392          */
393         private boolean mIgnorePrepareStorageErrors;
394 
setLastRequestQuietModeEnabledMillis(long millis)395         void setLastRequestQuietModeEnabledMillis(long millis) {
396             mLastRequestQuietModeEnabledMillis = millis;
397         }
398 
getLastRequestQuietModeEnabledMillis()399         long getLastRequestQuietModeEnabledMillis() {
400             return mLastRequestQuietModeEnabledMillis;
401         }
402 
getIgnorePrepareStorageErrors()403         boolean getIgnorePrepareStorageErrors() {
404             return mIgnorePrepareStorageErrors;
405         }
406 
407         @SuppressWarnings("AndroidFrameworkCompatChange")  // This is not an app-visible API.
setIgnorePrepareStorageErrors()408         void setIgnorePrepareStorageErrors() {
409             // This method won't be called for new users.  But to fully rule out
410             // the possibility of mIgnorePrepareStorageErrors ever being true
411             // for any user on any device that launched with T or later, we also
412             // explicitly check that DEVICE_INITIAL_SDK_INT is below T before
413             // honoring the request to set mIgnorePrepareStorageErrors to true.
414             if (Build.VERSION.DEVICE_INITIAL_SDK_INT < Build.VERSION_CODES.TIRAMISU) {
415                 mIgnorePrepareStorageErrors = true;
416                 return;
417             }
418             Slog.w(LOG_TAG, "Not setting mIgnorePrepareStorageErrors to true"
419                     + " since this is a new device");
420         }
421 
clearSeedAccountData()422         void clearSeedAccountData() {
423             seedAccountName = null;
424             seedAccountType = null;
425             seedAccountOptions = null;
426             persistSeedData = false;
427         }
428     }
429 
430     @GuardedBy("mUsersLock")
431     private final SparseArray<UserData> mUsers;
432 
433     /**
434      * Map of user type names to their corresponding {@link UserTypeDetails}.
435      * Should not be modified after UserManagerService constructor finishes.
436      */
437     private final ArrayMap<String, UserTypeDetails> mUserTypes;
438 
439     /**
440      * User restrictions set via UserManager.  This doesn't include restrictions set by
441      * device owner / profile owners. Only non-empty restriction bundles are stored.
442      *
443      * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
444      * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
445      * maybe shared between {@link #mBaseUserRestrictions} and
446      * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
447      * (Otherwise we won't be able to detect what restrictions have changed in
448      * {@link #updateUserRestrictionsInternalLR}.
449      */
450     @GuardedBy("mRestrictionsLock")
451     private final RestrictionsSet mBaseUserRestrictions = new RestrictionsSet();
452 
453     /**
454      * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
455      * with device / profile owner restrictions.  We'll initialize it lazily; use
456      * {@link #getEffectiveUserRestrictions} to access it.
457      *
458      * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
459      * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
460      * maybe shared between {@link #mBaseUserRestrictions} and
461      * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
462      * (Otherwise we won't be able to detect what restrictions have changed in
463      * {@link #updateUserRestrictionsInternalLR}.
464      */
465     @GuardedBy("mRestrictionsLock")
466     private final RestrictionsSet mCachedEffectiveUserRestrictions = new RestrictionsSet();
467 
468     /**
469      * User restrictions that have already been applied in
470      * {@link #updateUserRestrictionsInternalLR(Bundle, int)}.  We use it to detect restrictions
471      * that have changed since the last
472      * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
473      */
474     @GuardedBy("mRestrictionsLock")
475     private final RestrictionsSet mAppliedUserRestrictions = new RestrictionsSet();
476 
477     /**
478      * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
479      * for each user. Restrictions that apply to all users (global) are represented by
480      * {@link com.android.os.UserHandle.USER_ALL}.
481      * The key is the user id of the user whom the restrictions are targeting.
482      */
483     @GuardedBy("mRestrictionsLock")
484     private final RestrictionsSet mDevicePolicyUserRestrictions = new RestrictionsSet();
485 
486     @GuardedBy("mGuestRestrictions")
487     private final Bundle mGuestRestrictions = new Bundle();
488 
489     /**
490      * Set of user IDs that are being removed or were removed during the current boot.  User IDs in
491      * this set aren't reused until the device is rebooted, unless MAX_USER_ID is reached.  Some
492      * services don't fully clear out in-memory user state upon user removal; this behavior is
493      * intended to mitigate such issues by limiting user ID reuse.  This array applies to any type
494      * of user (including pre-created users) when they are removed.  Use {@link
495      * #addRemovingUserIdLocked(int)} to add elements to this array.
496      */
497     @GuardedBy("mUsersLock")
498     private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
499 
500     /**
501      * Queue of recently removed userIds. Used for recycling of userIds
502      */
503     @GuardedBy("mUsersLock")
504     private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
505 
506     @GuardedBy("mUsersLock")
507     private int[] mUserIds;
508 
509     @GuardedBy("mUsersLock")
510     private int[] mUserIdsIncludingPreCreated;
511 
512     @GuardedBy("mPackagesLock")
513     private int mNextSerialNumber;
514     private int mUserVersion = 0;
515     private int mUserTypeVersion = 0;
516 
517     private IAppOpsService mAppOpsService;
518 
519     private final LocalService mLocalService;
520 
521     @GuardedBy("mUsersLock")
522     private boolean mIsDeviceManaged;
523 
524     @GuardedBy("mUsersLock")
525     private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
526 
527     @GuardedBy("mUserRestrictionsListeners")
528     private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
529             new ArrayList<>();
530 
531     @GuardedBy("mUserLifecycleListeners")
532     private final ArrayList<UserLifecycleListener> mUserLifecycleListeners = new ArrayList<>();
533 
534     private final UserJourneyLogger mUserJourneyLogger = new UserJourneyLogger();
535 
536     private final LockPatternUtils mLockPatternUtils;
537 
538     private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
539             "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
540 
541     private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
542         @Override
543         public void onReceive(Context context, Intent intent) {
544             if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
545                 return;
546             }
547             final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT, android.content.IntentSender.class);
548             final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
549             // Call setQuietModeEnabled on bg thread to avoid ANR
550             BackgroundThread.getHandler().post(() ->
551                     setQuietModeEnabled(userId, false, target, /* callingPackage */ null));
552         }
553     };
554 
555     /**
556      * Cache the owner name string, since it could be read repeatedly on a critical code path
557      * but hit by slow IO. This could be eliminated once we have the cached UserInfo in place.
558      */
559     private final AtomicReference<String> mOwnerName = new AtomicReference<>();
560 
561     private final TypedValue mOwnerNameTypedValue = new TypedValue();
562 
563     private final Configuration mLastConfiguration = new Configuration();
564 
565     private final BroadcastReceiver mConfigurationChangeReceiver = new BroadcastReceiver() {
566         @Override
567         public void onReceive(Context context, Intent intent) {
568             if (!Intent.ACTION_CONFIGURATION_CHANGED.equals(intent.getAction())) {
569                 return;
570             }
571             invalidateOwnerNameIfNecessary(context.getResources(), false /* forceUpdate */);
572         }
573     };
574 
575     // TODO(b/161915546): remove once userWithName() is fixed / removed
576     // Use to debug / dump when user 0 is allocated at userWithName()
577     public static final boolean DBG_ALLOCATION = false; // DO NOT SUBMIT WITH TRUE
578     public final AtomicInteger mUser0Allocations;
579 
580     /**
581      * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
582      *
583      * @see #requestQuietModeEnabled(String, boolean, int, IntentSender, int)
584      */
585     private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
586         private final IntentSender mTarget;
587 
DisableQuietModeUserUnlockedCallback(IntentSender target)588         public DisableQuietModeUserUnlockedCallback(IntentSender target) {
589             Objects.requireNonNull(target);
590             mTarget = target;
591         }
592 
593         @Override
onStarted(int id, Bundle extras)594         public void onStarted(int id, Bundle extras) {}
595 
596         @Override
onProgress(int id, int progress, Bundle extras)597         public void onProgress(int id, int progress, Bundle extras) {}
598 
599         @Override
onFinished(int id, Bundle extras)600         public void onFinished(int id, Bundle extras) {
601             mHandler.post(() -> {
602                 try {
603                     mContext.startIntentSender(mTarget, null, 0, 0, 0);
604                 } catch (IntentSender.SendIntentException e) {
605                     Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
606                 }
607             });
608         }
609     }
610 
611     /**
612      * Whether all users should be created ephemeral.
613      */
614     @GuardedBy("mUsersLock")
615     private boolean mForceEphemeralUsers;
616 
617     /**
618      * The member mUserStates affects the return value of isUserUnlocked.
619      * If any value in mUserStates changes, then the binder cache for
620      * isUserUnlocked must be invalidated.  When adding mutating methods to
621      * WatchedUserStates, be sure to invalidate the cache in the new
622      * methods.
623      */
624     private class WatchedUserStates {
625         final SparseIntArray states;
WatchedUserStates()626         public WatchedUserStates() {
627             states = new SparseIntArray();
628             invalidateIsUserUnlockedCache();
629         }
get(@serIdInt int userId)630         public int get(@UserIdInt int userId) {
631             return states.get(userId);
632         }
get(@serIdInt int userId, int fallback)633         public int get(@UserIdInt int userId, int fallback) {
634             return states.indexOfKey(userId) >= 0 ? states.get(userId) : fallback;
635         }
put(@serIdInt int userId, int state)636         public void put(@UserIdInt int userId, int state) {
637             states.put(userId, state);
638             invalidateIsUserUnlockedCache();
639         }
delete(@serIdInt int userId)640         public void delete(@UserIdInt int userId) {
641             states.delete(userId);
642             invalidateIsUserUnlockedCache();
643         }
has(@serIdInt int userId)644         public boolean has(@UserIdInt int userId) {
645             return states.get(userId, UserHandle.USER_NULL) != UserHandle.USER_NULL;
646         }
647         @Override
toString()648         public String toString() {
649             return states.toString();
650         }
invalidateIsUserUnlockedCache()651         private void invalidateIsUserUnlockedCache() {
652             UserManager.invalidateIsUserUnlockedCache();
653         }
654     }
655     @GuardedBy("mUserStates")
656     private final WatchedUserStates mUserStates = new WatchedUserStates();
657 
658     private final UserVisibilityMediator mUserVisibilityMediator;
659 
660     @GuardedBy("mUsersLock")
661     private @UserIdInt int mBootUser = UserHandle.USER_NULL;
662 
663     private static UserManagerService sInstance;
664 
getInstance()665     public static UserManagerService getInstance() {
666         synchronized (UserManagerService.class) {
667             return sInstance;
668         }
669     }
670 
671     public static class LifeCycle extends SystemService {
672 
673         private UserManagerService mUms;
674 
675         /**
676          * @param context
677          */
LifeCycle(Context context)678         public LifeCycle(Context context) {
679             super(context);
680         }
681 
682         @Override
onStart()683         public void onStart() {
684             mUms = UserManagerService.getInstance();
685             publishBinderService(Context.USER_SERVICE, mUms);
686         }
687 
688         @Override
onBootPhase(int phase)689         public void onBootPhase(int phase) {
690             if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
691                 mUms.cleanupPartialUsers();
692 
693                 if (mUms.mPm.isDeviceUpgrading()) {
694                     mUms.cleanupPreCreatedUsers();
695                 }
696 
697                 mUms.registerStatsCallbacks();
698             }
699         }
700 
701         @Override
onUserStarting(@onNull TargetUser targetUser)702         public void onUserStarting(@NonNull TargetUser targetUser) {
703             boolean isProfileInQuietMode = false;
704             synchronized (mUms.mUsersLock) {
705                 final UserData user = mUms.getUserDataLU(targetUser.getUserIdentifier());
706                 if (user != null) {
707                     user.startRealtime = SystemClock.elapsedRealtime();
708                     if (targetUser.getUserIdentifier() == UserHandle.USER_SYSTEM
709                             && targetUser.isFull()) {
710                         mUms.setLastEnteredForegroundTimeToNow(user);
711                     } else if (user.info.isManagedProfile() && user.info.isQuietModeEnabled()) {
712                         isProfileInQuietMode = true;
713                     }
714                 }
715             }
716             if (isProfileInQuietMode) {
717                 mUms.setAppOpsRestrictedForQuietMode(targetUser.getUserIdentifier(), true);
718             }
719         }
720 
721         @Override
onUserUnlocking(@onNull TargetUser targetUser)722         public void onUserUnlocking(@NonNull TargetUser targetUser) {
723             synchronized (mUms.mUsersLock) {
724                 final UserData user = mUms.getUserDataLU(targetUser.getUserIdentifier());
725                 if (user != null) {
726                     user.unlockRealtime = SystemClock.elapsedRealtime();
727                 }
728             }
729         }
730 
731         @Override
onUserSwitching(@onNull TargetUser from, @NonNull TargetUser to)732         public void onUserSwitching(@NonNull TargetUser from, @NonNull TargetUser to) {
733             synchronized (mUms.mUsersLock) {
734                 final UserData user = mUms.getUserDataLU(to.getUserIdentifier());
735                 if (user != null) {
736                     mUms.setLastEnteredForegroundTimeToNow(user);
737                 }
738             }
739         }
740 
741         @Override
onUserStopping(@onNull TargetUser targetUser)742         public void onUserStopping(@NonNull TargetUser targetUser) {
743             synchronized (mUms.mUsersLock) {
744                 final UserData user = mUms.getUserDataLU(targetUser.getUserIdentifier());
745                 if (user != null) {
746                     user.startRealtime = 0;
747                     user.unlockRealtime = 0;
748                 }
749             }
750         }
751     }
752 
753     // TODO(b/28848102) Add support for test dependencies injection
754     @VisibleForTesting
UserManagerService(Context context)755     UserManagerService(Context context) {
756         this(context, /* pm= */ null, /* userDataPreparer= */ null,
757                 /* packagesLock= */ new Object(), context.getCacheDir(), /* users= */ null);
758     }
759 
760     /**
761      * Called by package manager to create the service.  This is closely
762      * associated with the package manager, and the given lock is the
763      * package manager's own lock.
764      */
UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer, Object packagesLock)765     UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
766             Object packagesLock) {
767         this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory(),
768                 /* users= */ null);
769     }
770 
771     @VisibleForTesting
UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer, Object packagesLock, File dataDir, SparseArray<UserData> users)772     UserManagerService(Context context, PackageManagerService pm,
773             UserDataPreparer userDataPreparer, Object packagesLock, File dataDir,
774             SparseArray<UserData> users) {
775         mContext = context;
776         mPm = pm;
777         mPackagesLock = packagesLock;
778         mUsers = users != null ? users : new SparseArray<>();
779         mHandler = new MainHandler();
780         mUserVisibilityMediator = new UserVisibilityMediator(mHandler);
781         mUserDataPreparer = userDataPreparer;
782         mUserTypes = UserTypeFactory.getUserTypes();
783         invalidateOwnerNameIfNecessary(context.getResources(), true /* forceUpdate */);
784         synchronized (mPackagesLock) {
785             mUsersDir = new File(dataDir, USER_INFO_DIR);
786             mUsersDir.mkdirs();
787             // Make zeroth user directory, for services to migrate their files to that location
788             File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
789             userZeroDir.mkdirs();
790             FileUtils.setPermissions(mUsersDir.toString(),
791                     FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
792                     -1, -1);
793             mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
794             initDefaultGuestRestrictions();
795             readUserListLP();
796             sInstance = this;
797         }
798         mSystemPackageInstaller = new UserSystemPackageInstaller(this, mUserTypes);
799         mLocalService = new LocalService();
800         LocalServices.addService(UserManagerInternal.class, mLocalService);
801         mLockPatternUtils = new LockPatternUtils(mContext);
802         mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
803         mUser0Allocations = DBG_ALLOCATION ? new AtomicInteger() : null;
804         emulateSystemUserModeIfNeeded();
805     }
806 
systemReady()807     void systemReady() {
808         mAppOpsService = IAppOpsService.Stub.asInterface(
809                 ServiceManager.getService(Context.APP_OPS_SERVICE));
810 
811         synchronized (mRestrictionsLock) {
812             applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
813         }
814 
815         mContext.registerReceiver(mDisableQuietModeCallback,
816                 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
817                 null, mHandler);
818 
819         mContext.registerReceiver(mConfigurationChangeReceiver,
820                 new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED),
821                 null, mHandler);
822 
823         markEphemeralUsersForRemoval();
824     }
825 
826     /**
827      * This method retrieves the  {@link UserManagerInternal} only for the purpose of
828      * PackageManagerService construction.
829      */
getInternalForInjectorOnly()830     UserManagerInternal getInternalForInjectorOnly() {
831         return mLocalService;
832     }
833 
834     /** Marks all ephemeral users as slated for deletion. **/
markEphemeralUsersForRemoval()835     private void markEphemeralUsersForRemoval() {
836         synchronized (mUsersLock) {
837             final int userSize = mUsers.size();
838             for (int i = 0; i < userSize; i++) {
839                 final UserInfo ui = mUsers.valueAt(i).info;
840                 if (ui.isEphemeral() && !ui.preCreated && ui.id != UserHandle.USER_SYSTEM) {
841                     addRemovingUserIdLocked(ui.id);
842                     ui.partial = true;
843                     ui.flags |= UserInfo.FLAG_DISABLED;
844                 }
845             }
846         }
847     }
848 
849     /* Prunes out any partially created or partially removed users. */
cleanupPartialUsers()850     private void cleanupPartialUsers() {
851         ArrayList<UserInfo> partials = new ArrayList<>();
852         synchronized (mUsersLock) {
853             final int userSize = mUsers.size();
854             for (int i = 0; i < userSize; i++) {
855                 UserInfo ui = mUsers.valueAt(i).info;
856                 if ((ui.partial || ui.guestToRemove) && ui.id != UserHandle.USER_SYSTEM) {
857                     partials.add(ui);
858                     if (!mRemovingUserIds.get(ui.id)) {
859                         addRemovingUserIdLocked(ui.id);
860                     }
861                     ui.partial = true;
862                 }
863             }
864         }
865         final int partialsSize = partials.size();
866         for (int i = 0; i < partialsSize; i++) {
867             UserInfo ui = partials.get(i);
868             Slog.w(LOG_TAG, "Removing partially created user " + ui.id
869                     + " (name=" + ui.name + ")");
870             removeUserState(ui.id);
871         }
872     }
873 
874     /**
875      * Removes any pre-created users from the system. Should be invoked after OTAs, to ensure
876      * pre-created users are not stale. New pre-created pool can be re-created after the update.
877      */
cleanupPreCreatedUsers()878     private void cleanupPreCreatedUsers() {
879         final ArrayList<UserInfo> preCreatedUsers;
880         synchronized (mUsersLock) {
881             final int userSize = mUsers.size();
882             preCreatedUsers = new ArrayList<>(userSize);
883             for (int i = 0; i < userSize; i++) {
884                 UserInfo ui = mUsers.valueAt(i).info;
885                 if (ui.preCreated) {
886                     preCreatedUsers.add(ui);
887                     addRemovingUserIdLocked(ui.id);
888                     ui.flags |= UserInfo.FLAG_DISABLED;
889                     ui.partial = true;
890                 }
891             }
892         }
893         final int preCreatedSize = preCreatedUsers.size();
894         for (int i = 0; i < preCreatedSize; i++) {
895             UserInfo ui = preCreatedUsers.get(i);
896             Slog.i(LOG_TAG, "Removing pre-created user " + ui.id);
897             removeUserState(ui.id);
898         }
899     }
900 
901     @Override
getUserAccount(@serIdInt int userId)902     public String getUserAccount(@UserIdInt int userId) {
903         checkManageUserAndAcrossUsersFullPermission("get user account");
904         synchronized (mUsersLock) {
905             return mUsers.get(userId).account;
906         }
907     }
908 
909     @Override
setUserAccount(@serIdInt int userId, String accountName)910     public void setUserAccount(@UserIdInt int userId, String accountName) {
911         checkManageUserAndAcrossUsersFullPermission("set user account");
912         UserData userToUpdate = null;
913         synchronized (mPackagesLock) {
914             synchronized (mUsersLock) {
915                 final UserData userData = mUsers.get(userId);
916                 if (userData == null) {
917                     Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
918                     return;
919                 }
920                 String currentAccount = userData.account;
921                 if (!Objects.equals(currentAccount, accountName)) {
922                     userData.account = accountName;
923                     userToUpdate = userData;
924                 }
925             }
926 
927             if (userToUpdate != null) {
928                 writeUserLP(userToUpdate);
929             }
930         }
931     }
932 
933     @Override
getPrimaryUser()934     public UserInfo getPrimaryUser() {
935         checkManageUsersPermission("query users");
936         synchronized (mUsersLock) {
937             final int userSize = mUsers.size();
938             for (int i = 0; i < userSize; i++) {
939                 UserInfo ui = mUsers.valueAt(i).info;
940                 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
941                     return ui;
942                 }
943             }
944         }
945         return null;
946     }
947 
948     @Override
getMainUserId()949     public @UserIdInt int getMainUserId() {
950         checkQueryOrCreateUsersPermission("get main user id");
951         return getMainUserIdUnchecked();
952     }
953 
getMainUserIdUnchecked()954     private @UserIdInt int getMainUserIdUnchecked() {
955         synchronized (mUsersLock) {
956             final int userSize = mUsers.size();
957             for (int i = 0; i < userSize; i++) {
958                 final UserInfo user = mUsers.valueAt(i).info;
959                 if (user.isMain() && !mRemovingUserIds.get(user.id)) {
960                     return user.id;
961                 }
962             }
963         }
964         return UserHandle.USER_NULL;
965     }
966 
967     @Override
setBootUser(@serIdInt int userId)968     public void setBootUser(@UserIdInt int userId) {
969         checkCreateUsersPermission("Set boot user");
970         synchronized (mUsersLock) {
971             // TODO(b/263381643): Change to EventLog.
972             Slogf.i(LOG_TAG, "setBootUser %d", userId);
973             mBootUser = userId;
974         }
975         mBootUserLatch.countDown();
976     }
977 
978     @Override
getBootUser()979     public @UserIdInt int getBootUser() {
980         checkCreateUsersPermission("Get boot user");
981         try {
982             return getBootUserUnchecked();
983         } catch (UserManager.CheckedUserOperationException e) {
984             throw e.toServiceSpecificException();
985         }
986     }
987 
getBootUserUnchecked()988     private @UserIdInt int getBootUserUnchecked() throws UserManager.CheckedUserOperationException {
989         synchronized (mUsersLock) {
990             if (mBootUser != UserHandle.USER_NULL) {
991                 final UserData userData = mUsers.get(mBootUser);
992                 if (userData != null && userData.info.supportsSwitchToByUser()) {
993                     Slogf.i(LOG_TAG, "Using provided boot user: %d", mBootUser);
994                     return mBootUser;
995                 } else {
996                     Slogf.w(LOG_TAG,
997                             "Provided boot user cannot be switched to: %d", mBootUser);
998                 }
999             }
1000         }
1001 
1002         if (isHeadlessSystemUserMode()) {
1003             // Return the previous foreground user, if there is one.
1004             final int previousUser = getPreviousFullUserToEnterForeground();
1005             if (previousUser != UserHandle.USER_NULL) {
1006                 Slogf.i(LOG_TAG, "Boot user is previous user %d", previousUser);
1007                 return previousUser;
1008             }
1009             // No previous user. Return the first switchable user if there is one.
1010             synchronized (mUsersLock) {
1011                 final int userSize = mUsers.size();
1012                 for (int i = 0; i < userSize; i++) {
1013                     final UserData userData = mUsers.valueAt(i);
1014                     if (userData.info.supportsSwitchToByUser()) {
1015                         int firstSwitchable = userData.info.id;
1016                         Slogf.i(LOG_TAG,
1017                                 "Boot user is first switchable user %d", firstSwitchable);
1018                         return firstSwitchable;
1019                     }
1020                 }
1021             }
1022             // No switchable users found. Uh oh!
1023             throw new UserManager.CheckedUserOperationException(
1024                     "No switchable users found", USER_OPERATION_ERROR_UNKNOWN);
1025         }
1026         // Not HSUM, return system user.
1027         return UserHandle.USER_SYSTEM;
1028     }
1029 
1030 
1031     @Override
getPreviousFullUserToEnterForeground()1032     public int getPreviousFullUserToEnterForeground() {
1033         checkQueryOrCreateUsersPermission("get previous user");
1034         int previousUser = UserHandle.USER_NULL;
1035         long latestEnteredTime = 0;
1036         final int currentUser = getCurrentUserId();
1037         synchronized (mUsersLock) {
1038             final int userSize = mUsers.size();
1039             for (int i = 0; i < userSize; i++) {
1040                 final UserData userData = mUsers.valueAt(i);
1041                 final int userId = userData.info.id;
1042                 if (userId != currentUser && userData.info.isFull() && !userData.info.partial
1043                         && userData.info.isEnabled() && !mRemovingUserIds.get(userId)) {
1044                     final long userEnteredTime = userData.mLastEnteredForegroundTimeMillis;
1045                     if (userEnteredTime > latestEnteredTime) {
1046                         latestEnteredTime = userEnteredTime;
1047                         previousUser = userId;
1048                     }
1049                 }
1050             }
1051         }
1052         return previousUser;
1053     }
1054 
getUsers(boolean excludeDying)1055     public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
1056         return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */
1057                 true);
1058     }
1059 
1060     @Override
getUsers(boolean excludePartial, boolean excludeDying, boolean excludePreCreated)1061     public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
1062             boolean excludePreCreated) {
1063         checkCreateUsersPermission("query users");
1064         return getUsersInternal(excludePartial, excludeDying, excludePreCreated);
1065     }
1066 
getUsersInternal(boolean excludePartial, boolean excludeDying, boolean excludePreCreated)1067     private @NonNull List<UserInfo> getUsersInternal(boolean excludePartial, boolean excludeDying,
1068             boolean excludePreCreated) {
1069         synchronized (mUsersLock) {
1070             ArrayList<UserInfo> users = new ArrayList<>(mUsers.size());
1071             final int userSize = mUsers.size();
1072             for (int i = 0; i < userSize; i++) {
1073                 UserInfo ui = mUsers.valueAt(i).info;
1074                 if ((excludePartial && ui.partial)
1075                         || (excludeDying && mRemovingUserIds.get(ui.id))
1076                         || (excludePreCreated && ui.preCreated)) {
1077                     continue;
1078                 }
1079                 users.add(userWithName(ui));
1080             }
1081             return users;
1082         }
1083     }
1084 
1085     @Override
getProfiles(@serIdInt int userId, boolean enabledOnly)1086     public List<UserInfo> getProfiles(@UserIdInt int userId, boolean enabledOnly) {
1087         boolean returnFullInfo;
1088         if (userId != UserHandle.getCallingUserId()) {
1089             checkQueryOrCreateUsersPermission("getting profiles related to user " + userId);
1090             returnFullInfo = true;
1091         } else {
1092             returnFullInfo = hasCreateUsersPermission();
1093         }
1094         final long ident = Binder.clearCallingIdentity();
1095         try {
1096             synchronized (mUsersLock) {
1097                 return getProfilesLU(userId, /* userType */ null, enabledOnly, returnFullInfo);
1098             }
1099         } finally {
1100             Binder.restoreCallingIdentity(ident);
1101         }
1102     }
1103 
1104     // TODO(b/142482943): Will probably need a getProfiles(userType). But permissions may vary.
1105 
1106     @Override
getProfileIds(@serIdInt int userId, boolean enabledOnly)1107     public int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) {
1108         return getProfileIds(userId, null, enabledOnly);
1109     }
1110 
1111     // TODO(b/142482943): Probably @Override and make this accessible in UserManager.
1112     /**
1113      * Returns all the users of type userType that are in the same profile group as userId
1114      * (including userId itself, if it is of the appropriate user type).
1115      *
1116      * <p>If userType is non-{@code null}, only returns users that are of type userType.
1117      * If enabledOnly, only returns users that are not {@link UserInfo#FLAG_DISABLED}.
1118      */
getProfileIds(@serIdInt int userId, @Nullable String userType, boolean enabledOnly)1119     public int[] getProfileIds(@UserIdInt int userId, @Nullable String userType,
1120             boolean enabledOnly) {
1121         if (userId != UserHandle.getCallingUserId()) {
1122             checkQueryOrCreateUsersPermission("getting profiles related to user " + userId);
1123         }
1124         final long ident = Binder.clearCallingIdentity();
1125         try {
1126             synchronized (mUsersLock) {
1127                 return getProfileIdsLU(userId, userType, enabledOnly).toArray();
1128             }
1129         } finally {
1130             Binder.restoreCallingIdentity(ident);
1131         }
1132     }
1133 
1134     /** Assume permissions already checked and caller's identity cleared */
1135     @GuardedBy("mUsersLock")
getProfilesLU(@serIdInt int userId, @Nullable String userType, boolean enabledOnly, boolean fullInfo)1136     private List<UserInfo> getProfilesLU(@UserIdInt int userId, @Nullable String userType,
1137             boolean enabledOnly, boolean fullInfo) {
1138         IntArray profileIds = getProfileIdsLU(userId, userType, enabledOnly);
1139         ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
1140         for (int i = 0; i < profileIds.size(); i++) {
1141             int profileId = profileIds.get(i);
1142             UserInfo userInfo = mUsers.get(profileId).info;
1143             // If full info is not required - clear PII data to prevent 3P apps from reading it
1144             if (!fullInfo) {
1145                 userInfo = new UserInfo(userInfo);
1146                 userInfo.name = null;
1147                 userInfo.iconPath = null;
1148             } else {
1149                 userInfo = userWithName(userInfo);
1150             }
1151             users.add(userInfo);
1152         }
1153         return users;
1154     }
1155 
1156     /**
1157      *  Assume permissions already checked and caller's identity cleared
1158      *  <p>If userType is {@code null}, returns all profiles for user; else, only returns
1159      *  profiles of that type.
1160      */
1161     @GuardedBy("mUsersLock")
getProfileIdsLU(@serIdInt int userId, @Nullable String userType, boolean enabledOnly)1162     private IntArray getProfileIdsLU(@UserIdInt int userId, @Nullable String userType,
1163             boolean enabledOnly) {
1164         UserInfo user = getUserInfoLU(userId);
1165         IntArray result = new IntArray(mUsers.size());
1166         if (user == null) {
1167             // Probably a dying user
1168             return result;
1169         }
1170         final int userSize = mUsers.size();
1171         for (int i = 0; i < userSize; i++) {
1172             UserInfo profile = mUsers.valueAt(i).info;
1173             if (!isProfileOf(user, profile)) {
1174                 continue;
1175             }
1176             if (enabledOnly && !profile.isEnabled()) {
1177                 continue;
1178             }
1179             if (mRemovingUserIds.get(profile.id)) {
1180                 continue;
1181             }
1182             if (profile.partial) {
1183                 continue;
1184             }
1185             if (userType != null && !userType.equals(profile.userType)) {
1186                 continue;
1187             }
1188             result.add(profile.id);
1189         }
1190         return result;
1191     }
1192 
1193     @Override
getCredentialOwnerProfile(@serIdInt int userId)1194     public int getCredentialOwnerProfile(@UserIdInt int userId) {
1195         checkManageUsersPermission("get the credential owner");
1196         if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
1197             synchronized (mUsersLock) {
1198                 UserInfo profileParent = getProfileParentLU(userId);
1199                 if (profileParent != null) {
1200                     return profileParent.id;
1201                 }
1202             }
1203         }
1204 
1205         return userId;
1206     }
1207 
1208     @Override
isSameProfileGroup(@serIdInt int userId, int otherUserId)1209     public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) {
1210         if (userId == otherUserId) return true;
1211         checkQueryUsersPermission("check if in the same profile group");
1212         return isSameProfileGroupNoChecks(userId, otherUserId);
1213     }
1214 
isSameProfileGroupNoChecks(@serIdInt int userId, int otherUserId)1215     private boolean isSameProfileGroupNoChecks(@UserIdInt int userId, int otherUserId) {
1216         synchronized (mUsersLock) {
1217             UserInfo userInfo = getUserInfoLU(userId);
1218             if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1219                 return false;
1220             }
1221             UserInfo otherUserInfo = getUserInfoLU(otherUserId);
1222             if (otherUserInfo == null
1223                     || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1224                 return false;
1225             }
1226             return userInfo.profileGroupId == otherUserInfo.profileGroupId;
1227         }
1228     }
1229 
1230     @Override
getProfileParent(@serIdInt int userId)1231     public UserInfo getProfileParent(@UserIdInt int userId) {
1232         if (!hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) {
1233             throw new SecurityException(
1234                     "You need MANAGE_USERS or INTERACT_ACROSS_USERS permission to get the "
1235                             + "profile parent");
1236         }
1237         synchronized (mUsersLock) {
1238             return getProfileParentLU(userId);
1239         }
1240     }
1241 
1242     @Override
getProfileParentId(@serIdInt int userId)1243     public int getProfileParentId(@UserIdInt int userId) {
1244         checkManageUsersPermission("get the profile parent");
1245         return getProfileParentIdUnchecked(userId);
1246     }
1247 
getProfileParentIdUnchecked(@serIdInt int userId)1248     private @UserIdInt int getProfileParentIdUnchecked(@UserIdInt int userId) {
1249         synchronized (mUsersLock) {
1250             UserInfo profileParent = getProfileParentLU(userId);
1251             if (profileParent == null) {
1252                 return userId;
1253             }
1254             return profileParent.id;
1255         }
1256     }
1257 
1258 
1259     @GuardedBy("mUsersLock")
getProfileParentLU(@serIdInt int userId)1260     private UserInfo getProfileParentLU(@UserIdInt int userId) {
1261         UserInfo profile = getUserInfoLU(userId);
1262         if (profile == null) {
1263             return null;
1264         }
1265         int parentUserId = profile.profileGroupId;
1266         if (parentUserId == userId || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
1267             return null;
1268         } else {
1269             return getUserInfoLU(parentUserId);
1270         }
1271     }
1272 
isProfileOf(UserInfo user, UserInfo profile)1273     private static boolean isProfileOf(UserInfo user, UserInfo profile) {
1274         return user.id == profile.id ||
1275                 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1276                 && user.profileGroupId == profile.profileGroupId);
1277     }
1278 
broadcastProfileAvailabilityChanges(UserHandle profileHandle, UserHandle parentHandle, boolean inQuietMode)1279     private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
1280             UserHandle parentHandle, boolean inQuietMode) {
1281         Intent intent = new Intent();
1282         if (inQuietMode) {
1283             intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
1284         } else {
1285             intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
1286         }
1287         intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
1288         intent.putExtra(Intent.EXTRA_USER, profileHandle);
1289         intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
1290         getDevicePolicyManagerInternal().broadcastIntentToManifestReceivers(
1291                 intent, parentHandle, /* requiresPermission= */ true);
1292         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
1293         final Bundle options = new BroadcastOptions()
1294                 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE)
1295                 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
1296                 // Both actions use single namespace because only the final state matters.
1297                 .setDeliveryGroupMatchingKey(
1298                         Intent.ACTION_MANAGED_PROFILE_AVAILABLE /* namespace */,
1299                         String.valueOf(profileHandle.getIdentifier()) /* key */)
1300                 .toBundle();
1301         mContext.sendBroadcastAsUser(intent, parentHandle, /* receiverPermission= */ null, options);
1302     }
1303 
1304     @Override
requestQuietModeEnabled(@onNull String callingPackage, boolean enableQuietMode, @UserIdInt int userId, @Nullable IntentSender target, @QuietModeFlag int flags)1305     public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
1306             @UserIdInt int userId, @Nullable IntentSender target, @QuietModeFlag int flags) {
1307         Objects.requireNonNull(callingPackage);
1308 
1309         if (enableQuietMode && target != null) {
1310             throw new IllegalArgumentException(
1311                     "target should only be specified when we are disabling quiet mode.");
1312         }
1313 
1314         final boolean dontAskCredential =
1315                 (flags & UserManager.QUIET_MODE_DISABLE_DONT_ASK_CREDENTIAL) != 0;
1316         final boolean onlyIfCredentialNotRequired =
1317                 (flags & UserManager.QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED) != 0;
1318         if (dontAskCredential && onlyIfCredentialNotRequired) {
1319             throw new IllegalArgumentException("invalid flags: " + flags);
1320         }
1321 
1322         ensureCanModifyQuietMode(
1323                 callingPackage, Binder.getCallingUid(), userId, target != null, dontAskCredential);
1324 
1325         if (onlyIfCredentialNotRequired && callingPackage.equals(
1326                 getPackageManagerInternal().getSystemUiServiceComponent().getPackageName())) {
1327             // This is to prevent SysUI from accidentally allowing the profile to turned on
1328             // without password when keyguard is still locked.
1329             throw new SecurityException("SystemUI is not allowed to set "
1330                     + "QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED");
1331         }
1332 
1333         final long identity = Binder.clearCallingIdentity();
1334         try {
1335             if (enableQuietMode) {
1336                 setQuietModeEnabled(userId, true /* enableQuietMode */, target, callingPackage);
1337                 return true;
1338             }
1339             final boolean hasUnifiedChallenge =
1340                     mLockPatternUtils.isManagedProfileWithUnifiedChallenge(userId);
1341             if (hasUnifiedChallenge) {
1342                 KeyguardManager km = mContext.getSystemService(KeyguardManager.class);
1343                 // Normally only attempt to auto-unlock unified challenge if keyguard is not showing
1344                 // (to stop turning profile on automatically via the QS tile), except when we
1345                 // are called with QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED, in which
1346                 // case always attempt to auto-unlock.
1347                 if (!km.isDeviceLocked(mLocalService.getProfileParentId(userId))
1348                         || onlyIfCredentialNotRequired) {
1349                     mLockPatternUtils.tryUnlockWithCachedUnifiedChallenge(userId);
1350                 }
1351             }
1352             final boolean needToShowConfirmCredential = !dontAskCredential
1353                     && mLockPatternUtils.isSecure(userId)
1354                     && (!hasUnifiedChallenge || !StorageManager.isUserKeyUnlocked(userId));
1355             if (needToShowConfirmCredential) {
1356                 if (onlyIfCredentialNotRequired) {
1357                     return false;
1358                 }
1359                 showConfirmCredentialToDisableQuietMode(userId, target);
1360                 return false;
1361             }
1362             setQuietModeEnabled(userId, false /* enableQuietMode */, target, callingPackage);
1363             return true;
1364         } finally {
1365             Binder.restoreCallingIdentity(identity);
1366         }
1367     }
1368 
1369     /**
1370      * The caller can modify quiet mode if it meets one of these conditions:
1371      * <ul>
1372      *     <li>Has system UID or root UID</li>
1373      *     <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
1374      *     <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
1375      *     <li>Is the foreground default launcher app</li>
1376      * </ul>
1377      * <p>
1378      * If caller wants to start an intent after disabling the quiet mode, or if it is targeting a
1379      * user in a different profile group from the caller, it must have
1380      * {@link Manifest.permission#MANAGE_USERS}.
1381      */
ensureCanModifyQuietMode(String callingPackage, int callingUid, @UserIdInt int targetUserId, boolean startIntent, boolean dontAskCredential)1382     private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
1383             @UserIdInt int targetUserId, boolean startIntent, boolean dontAskCredential) {
1384         verifyCallingPackage(callingPackage, callingUid);
1385 
1386         if (hasManageUsersPermission()) {
1387             return;
1388         }
1389         if (startIntent) {
1390             throw new SecurityException("MANAGE_USERS permission is required to start intent "
1391                     + "after disabling quiet mode.");
1392         }
1393         if (dontAskCredential) {
1394             throw new SecurityException("MANAGE_USERS permission is required to disable quiet "
1395                     + "mode without credentials.");
1396         }
1397         if (!isSameProfileGroupNoChecks(UserHandle.getUserId(callingUid), targetUserId)) {
1398             throw new SecurityException("MANAGE_USERS permission is required to modify quiet mode "
1399                     + "for a different profile group.");
1400         }
1401         final boolean hasModifyQuietModePermission = hasPermissionGranted(
1402                 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
1403         if (hasModifyQuietModePermission) {
1404             return;
1405         }
1406 
1407         final ShortcutServiceInternal shortcutInternal =
1408                 LocalServices.getService(ShortcutServiceInternal.class);
1409         if (shortcutInternal != null) {
1410             boolean isForegroundLauncher =
1411                     shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
1412             if (isForegroundLauncher) {
1413                 return;
1414             }
1415         }
1416         throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
1417                 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
1418     }
1419 
setQuietModeEnabled(@serIdInt int userId, boolean enableQuietMode, IntentSender target, @Nullable String callingPackage)1420     private void setQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
1421             IntentSender target, @Nullable String callingPackage) {
1422         final UserInfo profile, parent;
1423         final UserData profileUserData;
1424         synchronized (mUsersLock) {
1425             profile = getUserInfoLU(userId);
1426             parent = getProfileParentLU(userId);
1427 
1428             if (profile == null || !profile.isManagedProfile()) {
1429                 throw new IllegalArgumentException("User " + userId + " is not a profile");
1430             }
1431             if (profile.isQuietModeEnabled() == enableQuietMode) {
1432                 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
1433                 return;
1434             }
1435             profile.flags ^= UserInfo.FLAG_QUIET_MODE;
1436             profileUserData = getUserDataLU(profile.id);
1437         }
1438         synchronized (mPackagesLock) {
1439             writeUserLP(profileUserData);
1440         }
1441         if (getDevicePolicyManagerInternal().isKeepProfilesRunningEnabled()) {
1442             // New behavior: when quiet mode is enabled, profile user is running, but apps are
1443             // suspended.
1444             getPackageManagerInternal().setPackagesSuspendedForQuietMode(userId, enableQuietMode);
1445             setAppOpsRestrictedForQuietMode(userId, enableQuietMode);
1446 
1447             if (enableQuietMode
1448                     && !mLockPatternUtils.isManagedProfileWithUnifiedChallenge(userId)) {
1449                 mContext.getSystemService(TrustManager.class).setDeviceLockedForUser(userId, true);
1450             }
1451 
1452             if (!enableQuietMode && target != null) {
1453                 try {
1454                     mContext.startIntentSender(target, null, 0, 0, 0);
1455                 } catch (IntentSender.SendIntentException e) {
1456                     Slog.e(LOG_TAG, "Failed to start intent after disabling quiet mode", e);
1457                 }
1458             }
1459         } else {
1460             // Old behavior: when quiet is enabled, profile user is stopped.
1461             // Old quiet mode behavior: profile user is stopped.
1462             // TODO(b/265683382) Remove once rollout complete.
1463             try {
1464                 if (enableQuietMode) {
1465                     ActivityManager.getService().stopUser(userId, /* force= */ true, null);
1466                     LocalServices.getService(ActivityManagerInternal.class)
1467                             .killForegroundAppsForUser(userId);
1468                 } else {
1469                     IProgressListener callback = target != null
1470                             ? new DisableQuietModeUserUnlockedCallback(target)
1471                             : null;
1472                     ActivityManager.getService().startProfileWithListener(userId, callback);
1473                 }
1474             } catch (RemoteException e) {
1475                 // Should not happen, same process.
1476                 e.rethrowAsRuntimeException();
1477             }
1478         }
1479 
1480         logQuietModeEnabled(userId, enableQuietMode, callingPackage);
1481         broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
1482                 enableQuietMode);
1483     }
1484 
setAppOpsRestrictedForQuietMode(@serIdInt int userId, boolean restrict)1485     private void setAppOpsRestrictedForQuietMode(@UserIdInt int userId, boolean restrict) {
1486         for (int opCode : QUIET_MODE_RESTRICTED_APP_OPS) {
1487             try {
1488                 mAppOpsService.setUserRestriction(
1489                         opCode, restrict, mQuietModeToken, userId, /* excludedPackageTags= */ null);
1490             } catch (RemoteException e) {
1491                 Slog.w(LOG_TAG, "Unable to limit app ops", e);
1492             }
1493         }
1494     }
1495 
logQuietModeEnabled(@serIdInt int userId, boolean enableQuietMode, @Nullable String callingPackage)1496     private void logQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
1497             @Nullable String callingPackage) {
1498         Slogf.i(LOG_TAG,
1499                 "requestQuietModeEnabled called by package %s, with enableQuietMode %b.",
1500                 callingPackage,
1501                 enableQuietMode);
1502         UserData userData;
1503         synchronized (mUsersLock) {
1504             userData = getUserDataLU(userId);
1505         }
1506         if (userData == null) {
1507             return;
1508         }
1509         final long now = System.currentTimeMillis();
1510         final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
1511                 ? now - userData.getLastRequestQuietModeEnabledMillis()
1512                 : now - userData.info.creationTime);
1513         DevicePolicyEventLogger
1514                 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
1515                 .setStrings(callingPackage)
1516                 .setBoolean(enableQuietMode)
1517                 .setTimePeriod(period)
1518                 .write();
1519         userData.setLastRequestQuietModeEnabledMillis(now);
1520     }
1521 
1522     @Override
isQuietModeEnabled(@serIdInt int userId)1523     public boolean isQuietModeEnabled(@UserIdInt int userId) {
1524         synchronized (mPackagesLock) {
1525             UserInfo info;
1526             synchronized (mUsersLock) {
1527                 info = getUserInfoLU(userId);
1528             }
1529             if (info == null || !info.isManagedProfile()) {
1530                 return false;
1531             }
1532             return info.isQuietModeEnabled();
1533         }
1534     }
1535 
1536     /**
1537      * Show confirm credential screen to unlock user in order to turn off quiet mode.
1538      */
showConfirmCredentialToDisableQuietMode( @serIdInt int userId, @Nullable IntentSender target)1539     private void showConfirmCredentialToDisableQuietMode(
1540             @UserIdInt int userId, @Nullable IntentSender target) {
1541         // otherwise, we show a profile challenge to trigger decryption of the user
1542         final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
1543                 Context.KEYGUARD_SERVICE);
1544         // We should use userId not credentialOwnerUserId here, as even if it is unified
1545         // lock, confirm screenlock page will know and show personal challenge, and unlock
1546         // work profile when personal challenge is correct
1547         final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
1548         if (unlockIntent == null) {
1549             return;
1550         }
1551         final Intent callBackIntent = new Intent(
1552                 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1553         if (target != null) {
1554             callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
1555         }
1556         callBackIntent.putExtra(Intent.EXTRA_USER_ID, userId);
1557         callBackIntent.setPackage(mContext.getPackageName());
1558         callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1559         final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1560                 mContext,
1561                 0,
1562                 callBackIntent,
1563                 PendingIntent.FLAG_CANCEL_CURRENT |
1564                         PendingIntent.FLAG_ONE_SHOT |
1565                         PendingIntent.FLAG_IMMUTABLE);
1566         // After unlocking the challenge, it will disable quiet mode and run the original
1567         // intentSender
1568         unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1569         unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1570         mContext.startActivityAsUser(
1571                 unlockIntent, UserHandle.of(getProfileParentIdUnchecked(userId)));
1572     }
1573 
1574     @Override
setUserEnabled(@serIdInt int userId)1575     public void setUserEnabled(@UserIdInt int userId) {
1576         checkManageUsersPermission("enable user");
1577         UserInfo info;
1578         boolean wasUserDisabled = false;
1579         synchronized (mPackagesLock) {
1580             synchronized (mUsersLock) {
1581                 info = getUserInfoLU(userId);
1582                 if (info != null && !info.isEnabled()) {
1583                     wasUserDisabled = true;
1584                     info.flags ^= UserInfo.FLAG_DISABLED;
1585                     writeUserLP(getUserDataLU(info.id));
1586                 }
1587             }
1588         }
1589         if (wasUserDisabled && info != null && info.isProfile()) {
1590             sendProfileAddedBroadcast(info.profileGroupId, info.id);
1591         }
1592     }
1593 
1594     @Override
setUserAdmin(@serIdInt int userId)1595     public void setUserAdmin(@UserIdInt int userId) {
1596         checkManageUserAndAcrossUsersFullPermission("set user admin");
1597         mUserJourneyLogger.logUserJourneyBegin(userId, USER_JOURNEY_GRANT_ADMIN);
1598         UserInfo info;
1599         synchronized (mPackagesLock) {
1600             synchronized (mUsersLock) {
1601                 info = getUserInfoLU(userId);
1602             }
1603             if (info == null) {
1604                 // Exit if no user found with that id,
1605                 mUserJourneyLogger.logNullUserJourneyError(USER_JOURNEY_GRANT_ADMIN,
1606                         getCurrentUserId(), userId, /* userType */ "", /* userFlags */ -1);
1607                 return;
1608             } else if (info.isAdmin()) {
1609                 // Exit if the user is already an Admin.
1610                 mUserJourneyLogger.logUserJourneyFinishWithError(getCurrentUserId(), info,
1611                         USER_JOURNEY_GRANT_ADMIN, ERROR_CODE_USER_ALREADY_AN_ADMIN);
1612                 return;
1613             }
1614             info.flags ^= UserInfo.FLAG_ADMIN;
1615             writeUserLP(getUserDataLU(info.id));
1616         }
1617         mUserJourneyLogger.logUserJourneyFinishWithError(getCurrentUserId(), info,
1618                 USER_JOURNEY_GRANT_ADMIN, ERROR_CODE_UNSPECIFIED);
1619     }
1620 
1621     @Override
revokeUserAdmin(@serIdInt int userId)1622     public void revokeUserAdmin(@UserIdInt int userId) {
1623         checkManageUserAndAcrossUsersFullPermission("revoke admin privileges");
1624         mUserJourneyLogger.logUserJourneyBegin(userId, USER_JOURNEY_REVOKE_ADMIN);
1625         UserData user;
1626         synchronized (mPackagesLock) {
1627             synchronized (mUsersLock) {
1628                 user = getUserDataLU(userId);
1629                 if (user == null) {
1630                     // Exit if no user found with that id
1631                     mUserJourneyLogger.logNullUserJourneyError(
1632                             USER_JOURNEY_REVOKE_ADMIN,
1633                             getCurrentUserId(), userId, "", -1);
1634                     return;
1635                 } else if (!user.info.isAdmin()) {
1636                     // Exit if no user is not an Admin.
1637                     mUserJourneyLogger.logUserJourneyFinishWithError(getCurrentUserId(), user.info,
1638                             USER_JOURNEY_REVOKE_ADMIN, ERROR_CODE_USER_IS_NOT_AN_ADMIN);
1639                     return;
1640                 }
1641                 user.info.flags ^= UserInfo.FLAG_ADMIN;
1642                 writeUserLP(user);
1643             }
1644         }
1645         mUserJourneyLogger.logUserJourneyFinishWithError(getCurrentUserId(), user.info,
1646                 USER_JOURNEY_REVOKE_ADMIN, ERROR_CODE_UNSPECIFIED);
1647     }
1648 
1649     /**
1650      * Evicts a user's CE key by stopping and restarting the user.
1651      *
1652      * The key is evicted automatically by the user controller when the user has stopped.
1653      */
1654     @Override
evictCredentialEncryptionKey(@serIdInt int userId)1655     public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1656         checkManageUsersPermission("evict CE key");
1657         final IActivityManager am = ActivityManagerNative.getDefault();
1658         final long identity = Binder.clearCallingIdentity();
1659         // TODO(b/280054081): save userStartMode when user started and re-use it here instead
1660         final int userStartMode = isProfileUnchecked(userId)
1661                 ? UserManagerInternal.USER_START_MODE_BACKGROUND_VISIBLE
1662                 : UserManagerInternal.USER_START_MODE_BACKGROUND;
1663         try {
1664             am.restartUserInBackground(userId, userStartMode);
1665         } catch (RemoteException re) {
1666             throw re.rethrowAsRuntimeException();
1667         } finally {
1668             Binder.restoreCallingIdentity(identity);
1669         }
1670     }
1671 
1672     /**
1673      * Returns whether the given user (specified by userId) is of the given user type, such as
1674      * {@link UserManager#USER_TYPE_FULL_GUEST}.
1675      */
1676     @Override
isUserOfType(@serIdInt int userId, String userType)1677     public boolean isUserOfType(@UserIdInt int userId, String userType) {
1678         checkQueryOrCreateUsersPermission("check user type");
1679         return userType != null && userType.equals(getUserTypeNoChecks(userId));
1680     }
1681 
1682     /**
1683      * Returns the user type of the given userId, or null if the user doesn't exist.
1684      * <p>No permissions checks are made (but userId checks may be made).
1685      */
getUserTypeNoChecks(@serIdInt int userId)1686     private @Nullable String getUserTypeNoChecks(@UserIdInt int userId) {
1687         synchronized (mUsersLock) {
1688             final UserInfo userInfo = getUserInfoLU(userId);
1689             return userInfo != null ? userInfo.userType : null;
1690         }
1691     }
1692 
1693     /**
1694      * Returns the UserTypeDetails of the given userId's user type, or null if the no such user.
1695      * <p>No permissions checks are made (but userId checks may be made).
1696      */
getUserTypeDetailsNoChecks(@serIdInt int userId)1697     private @Nullable UserTypeDetails getUserTypeDetailsNoChecks(@UserIdInt int userId) {
1698         final String typeStr = getUserTypeNoChecks(userId);
1699         return typeStr != null ? mUserTypes.get(typeStr) : null;
1700     }
1701 
1702     /**
1703      * Returns the UserTypeDetails of the given userInfo's user type (or null for a null userInfo).
1704      */
getUserTypeDetails(@ullable UserInfo userInfo)1705     private @Nullable UserTypeDetails getUserTypeDetails(@Nullable UserInfo userInfo) {
1706         final String typeStr = userInfo != null ? userInfo.userType : null;
1707         return typeStr != null ? mUserTypes.get(typeStr) : null;
1708     }
1709 
1710     @Override
getUserInfo(@serIdInt int userId)1711     public UserInfo getUserInfo(@UserIdInt int userId) {
1712         checkQueryOrCreateUsersPermission("query user");
1713         synchronized (mUsersLock) {
1714             return userWithName(getUserInfoLU(userId));
1715         }
1716     }
1717 
1718     /**
1719      * Returns a UserInfo object with the name filled in, for Owner and Guest, or the original
1720      * if the name is already set.
1721      *
1722      * Note: Currently, the resulting name can be null if a user was truly created with a null name.
1723      */
userWithName(UserInfo orig)1724     private UserInfo userWithName(UserInfo orig) {
1725         if (orig != null && orig.name == null) {
1726             String name = null;
1727             if (orig.id == UserHandle.USER_SYSTEM) {
1728                 if (DBG_ALLOCATION) {
1729                     final int number = mUser0Allocations.incrementAndGet();
1730                     Slog.w(LOG_TAG, "System user instantiated at least " + number + " times");
1731                 }
1732                 name = getOwnerName();
1733             } else if (orig.isMain()) {
1734                 name = getOwnerName();
1735             } else if (orig.isGuest()) {
1736                 name = getGuestName();
1737             }
1738             if (name != null) {
1739                 final UserInfo withName = new UserInfo(orig);
1740                 withName.name = name;
1741                 return withName;
1742             }
1743         }
1744         return orig;
1745     }
1746 
1747     /** Returns whether the given user type is one of the FULL user types. */
isUserTypeSubtypeOfFull(String userType)1748     boolean isUserTypeSubtypeOfFull(String userType) {
1749         UserTypeDetails userTypeDetails = mUserTypes.get(userType);
1750         return userTypeDetails != null && userTypeDetails.isFull();
1751     }
1752 
1753     /** Returns whether the given user type is one of the PROFILE user types. */
isUserTypeSubtypeOfProfile(String userType)1754     boolean isUserTypeSubtypeOfProfile(String userType) {
1755         UserTypeDetails userTypeDetails = mUserTypes.get(userType);
1756         return userTypeDetails != null && userTypeDetails.isProfile();
1757     }
1758 
1759     /** Returns whether the given user type is one of the SYSTEM user types. */
isUserTypeSubtypeOfSystem(String userType)1760     boolean isUserTypeSubtypeOfSystem(String userType) {
1761         UserTypeDetails userTypeDetails = mUserTypes.get(userType);
1762         return userTypeDetails != null && userTypeDetails.isSystem();
1763     }
1764 
1765     /**
1766      * Returns a *copy* of the given user's UserProperties, stripping out any information for which
1767      * the caller lacks permission.
1768      */
1769     @Override
getUserPropertiesCopy(@serIdInt int userId)1770     public @NonNull UserProperties getUserPropertiesCopy(@UserIdInt int userId) {
1771         checkQueryOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserProperties");
1772         final UserProperties origProperties = getUserPropertiesInternal(userId);
1773         if (origProperties != null) {
1774             boolean exposeAllFields = Binder.getCallingUid() == Process.SYSTEM_UID;
1775             boolean hasManage = hasManageUsersPermission();
1776             boolean hasQuery = hasQueryUsersPermission();
1777             return new UserProperties(origProperties, exposeAllFields, hasManage, hasQuery);
1778         }
1779         // A non-existent or partial user will reach here.
1780         throw new IllegalArgumentException("Cannot access properties for user " + userId);
1781     }
1782 
1783     /** Returns the user's actual, canonical UserProperties object. Do not edit it externally. */
getUserPropertiesInternal(@serIdInt int userId)1784     private @Nullable UserProperties getUserPropertiesInternal(@UserIdInt int userId) {
1785         synchronized (mUsersLock) {
1786             final UserData userData = getUserDataLU(userId);
1787             if (userData != null) {
1788                 return userData.userProperties;
1789             }
1790         }
1791         return null;
1792     }
1793 
1794     @Override
hasBadge(@serIdInt int userId)1795     public boolean hasBadge(@UserIdInt int userId) {
1796         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "hasBadge");
1797         final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1798         return userTypeDetails != null && userTypeDetails.hasBadge();
1799     }
1800 
1801     @Override
getUserBadgeLabelResId(@serIdInt int userId)1802     public @StringRes int getUserBadgeLabelResId(@UserIdInt int userId) {
1803         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId,
1804                 "getUserBadgeLabelResId");
1805         final UserInfo userInfo = getUserInfoNoChecks(userId);
1806         final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo);
1807         if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) {
1808             Slog.e(LOG_TAG, "Requested badge label for non-badged user " + userId);
1809             return Resources.ID_NULL;
1810         }
1811         final int badgeIndex = userInfo.profileBadge;
1812         return userTypeDetails.getBadgeLabel(badgeIndex);
1813     }
1814 
1815     /**
1816      * @return the color (not the resource ID) to be used for the user's badge in light theme
1817      */
1818     @Override
getUserBadgeColorResId(@serIdInt int userId)1819     public @ColorRes int getUserBadgeColorResId(@UserIdInt int userId) {
1820         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId,
1821                 "getUserBadgeColorResId");
1822         final UserInfo userInfo = getUserInfoNoChecks(userId);
1823         final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo);
1824         if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) {
1825             Slog.e(LOG_TAG, "Requested badge dark color for non-badged user " + userId);
1826             return Resources.ID_NULL;
1827         }
1828         return userTypeDetails.getBadgeColor(userInfo.profileBadge);
1829     }
1830 
1831     /**
1832      * @return the color (not the resource ID) to be used for the user's badge in dark theme
1833      */
1834     @Override
getUserBadgeDarkColorResId(@serIdInt int userId)1835     public @ColorRes int getUserBadgeDarkColorResId(@UserIdInt int userId) {
1836         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId,
1837                 "getUserBadgeDarkColorResId");
1838         final UserInfo userInfo = getUserInfoNoChecks(userId);
1839         final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo);
1840         if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) {
1841             Slog.e(LOG_TAG, "Requested badge color for non-badged user " + userId);
1842             return Resources.ID_NULL;
1843         }
1844         return userTypeDetails.getDarkThemeBadgeColor(userInfo.profileBadge);
1845     }
1846 
1847     @Override
getUserIconBadgeResId(@serIdInt int userId)1848     public @DrawableRes int getUserIconBadgeResId(@UserIdInt int userId) {
1849         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserIconBadgeResId");
1850         final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1851         if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
1852             Slog.e(LOG_TAG, "Requested icon badge for non-badged user " + userId);
1853             return Resources.ID_NULL;
1854         }
1855         return userTypeDetails.getIconBadge();
1856     }
1857 
1858     @Override
getUserBadgeResId(@serIdInt int userId)1859     public @DrawableRes int getUserBadgeResId(@UserIdInt int userId) {
1860         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserBadgeResId");
1861         final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1862         if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
1863             Slog.e(LOG_TAG, "Requested badge for non-badged user " + userId);
1864             return Resources.ID_NULL;
1865         }
1866         return userTypeDetails.getBadgePlain();
1867     }
1868 
1869     @Override
getUserBadgeNoBackgroundResId(@serIdInt int userId)1870     public @DrawableRes int getUserBadgeNoBackgroundResId(@UserIdInt int userId) {
1871         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId,
1872                 "getUserBadgeNoBackgroundResId");
1873         final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1874         if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
1875             Slog.e(LOG_TAG, "Requested badge (no background) for non-badged user " + userId);
1876             return Resources.ID_NULL;
1877         }
1878         return userTypeDetails.getBadgeNoBackground();
1879     }
1880 
isProfile(@serIdInt int userId)1881     public boolean isProfile(@UserIdInt int userId) {
1882         checkQueryOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isProfile");
1883         return isProfileUnchecked(userId);
1884     }
1885 
isProfileUnchecked(@serIdInt int userId)1886     private boolean isProfileUnchecked(@UserIdInt int userId) {
1887         synchronized (mUsersLock) {
1888             UserInfo userInfo = getUserInfoLU(userId);
1889             return userInfo != null && userInfo.isProfile();
1890         }
1891     }
1892 
1893     /**
1894      * Returns the user type (if it is a profile), empty string (if it isn't a profile),
1895      * or null (if the user doesn't exist).
1896      */
1897     @Override
getProfileType(@serIdInt int userId)1898     public @Nullable String getProfileType(@UserIdInt int userId) {
1899         checkQueryOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getProfileType");
1900         synchronized (mUsersLock) {
1901             UserInfo userInfo = getUserInfoLU(userId);
1902             if (userInfo != null) {
1903                 return userInfo.isProfile() ? userInfo.userType : "";
1904             }
1905             return null;
1906         }
1907     }
1908 
1909     @Override
isUserUnlockingOrUnlocked(@serIdInt int userId)1910     public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
1911         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId,
1912                 "isUserUnlockingOrUnlocked");
1913         return mLocalService.isUserUnlockingOrUnlocked(userId);
1914     }
1915 
1916     @Override
isUserUnlocked(@serIdInt int userId)1917     public boolean isUserUnlocked(@UserIdInt int userId) {
1918         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
1919         return mLocalService.isUserUnlocked(userId);
1920     }
1921 
1922     @Override
isUserRunning(@serIdInt int userId)1923     public boolean isUserRunning(@UserIdInt int userId) {
1924         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isUserRunning");
1925         return mLocalService.isUserRunning(userId);
1926     }
1927 
1928     @Override
isUserForeground(@serIdInt int userId)1929     public boolean isUserForeground(@UserIdInt int userId) {
1930         final int callingUserId = UserHandle.getCallingUserId();
1931         if (callingUserId != userId
1932                 && !hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) {
1933             throw new SecurityException("Caller from user " + callingUserId + " needs MANAGE_USERS "
1934                     + "or INTERACT_ACROSS_USERS permission to check if another user (" + userId
1935                     + ") is running in the foreground");
1936         }
1937 
1938         return userId == getCurrentUserId();
1939     }
1940 
1941     @Override
isUserVisible(@serIdInt int userId)1942     public boolean isUserVisible(@UserIdInt int userId) {
1943         int callingUserId = UserHandle.getCallingUserId();
1944         if (callingUserId != userId
1945                 && !hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) {
1946             throw new SecurityException("Caller from user " + callingUserId + " needs MANAGE_USERS "
1947                     + "or INTERACT_ACROSS_USERS permission to check if another user (" + userId
1948                     + ") is visible");
1949         }
1950 
1951         return mUserVisibilityMediator.isUserVisible(userId);
1952     }
1953 
1954     /**
1955      * Gets the current and target user ids as a {@link Pair}, calling
1956      * {@link ActivityManagerInternal} directly (and without performing any permission check).
1957      *
1958      * @return ids of current foreground user and the target user. Target user will be
1959      * {@link UserHandle#USER_NULL} if there is not an ongoing user switch. And if
1960      * {@link ActivityManagerInternal} is not available yet, they will both be
1961      * {@link UserHandle#USER_NULL}.
1962      */
1963     @VisibleForTesting
1964     @NonNull
getCurrentAndTargetUserIds()1965     Pair<Integer, Integer> getCurrentAndTargetUserIds() {
1966         ActivityManagerInternal activityManagerInternal = getActivityManagerInternal();
1967         if (activityManagerInternal == null) {
1968             Slog.w(LOG_TAG, "getCurrentAndTargetUserId() called too early, "
1969                     + "ActivityManagerInternal is not set yet");
1970             return new Pair<>(UserHandle.USER_NULL, UserHandle.USER_NULL);
1971         }
1972         return activityManagerInternal.getCurrentAndTargetUserIds();
1973     }
1974 
1975     /**
1976      * Gets the current user id, calling {@link ActivityManagerInternal} directly (and without
1977      * performing any permission check).
1978      *
1979      * @return id of current foreground user, or {@link UserHandle#USER_NULL} if
1980      * {@link ActivityManagerInternal} is not available yet.
1981      */
1982     @VisibleForTesting
getCurrentUserId()1983     int getCurrentUserId() {
1984         ActivityManagerInternal activityManagerInternal = getActivityManagerInternal();
1985         if (activityManagerInternal == null) {
1986             Slog.w(LOG_TAG, "getCurrentUserId() called too early, ActivityManagerInternal"
1987                     + " is not set yet");
1988             return UserHandle.USER_NULL;
1989         }
1990         return activityManagerInternal.getCurrentUserId();
1991     }
1992 
1993     /**
1994      * Gets whether the user is the current foreground user or a started profile of that user.
1995      *
1996      * <p>Doesn't perform any permission check.
1997      */
1998     @VisibleForTesting
isCurrentUserOrRunningProfileOfCurrentUser(@serIdInt int userId)1999     boolean isCurrentUserOrRunningProfileOfCurrentUser(@UserIdInt int userId) {
2000         int currentUserId = getCurrentUserId();
2001 
2002         if (currentUserId == userId) {
2003             return true;
2004         }
2005 
2006         if (isProfileUnchecked(userId)) {
2007             int parentId = getProfileParentIdUnchecked(userId);
2008             if (parentId == currentUserId) {
2009                 return isUserRunning(userId);
2010             }
2011         }
2012 
2013         return false;
2014     }
2015 
2016     // Called by UserManagerServiceShellCommand
isUserVisibleOnDisplay(@serIdInt int userId, int displayId)2017     boolean isUserVisibleOnDisplay(@UserIdInt int userId, int displayId) {
2018         return mUserVisibilityMediator.isUserVisible(userId, displayId);
2019     }
2020 
2021     @Override
getVisibleUsers()2022     public int[] getVisibleUsers() {
2023         if (!hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) {
2024             throw new SecurityException("Caller needs MANAGE_USERS or INTERACT_ACROSS_USERS "
2025                     + "permission to get list of visible users");
2026         }
2027         final long ident = Binder.clearCallingIdentity();
2028         try {
2029             return mUserVisibilityMediator.getVisibleUsers().toArray();
2030         } finally {
2031             Binder.restoreCallingIdentity(ident);
2032         }
2033     }
2034 
2035     @Override
getMainDisplayIdAssignedToUser()2036     public int getMainDisplayIdAssignedToUser() {
2037         // Not checking for any permission as it returns info about calling user
2038         int userId = UserHandle.getUserId(Binder.getCallingUid());
2039         int displayId = mUserVisibilityMediator.getMainDisplayAssignedToUser(userId);
2040         return displayId;
2041     }
2042 
2043     @Override
getUserName()2044     public @NonNull String getUserName() {
2045         final int callingUid = Binder.getCallingUid();
2046         if (!hasQueryOrCreateUsersPermission()
2047                 && !hasPermissionGranted(
2048                         android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED, callingUid)) {
2049             throw new SecurityException("You need MANAGE_USERS, CREATE_USERS, QUERY_USERS, or "
2050                     + "GET_ACCOUNTS_PRIVILEGED permissions to: get user name");
2051         }
2052         final int userId = UserHandle.getUserId(callingUid);
2053         synchronized (mUsersLock) {
2054             UserInfo userInfo = userWithName(getUserInfoLU(userId));
2055             if (userInfo != null && userInfo.name != null) {
2056                 return userInfo.name;
2057             }
2058             return "";
2059         }
2060     }
2061 
2062     @Override
getUserStartRealtime()2063     public long getUserStartRealtime() {
2064         final int userId = UserHandle.getUserId(Binder.getCallingUid());
2065         synchronized (mUsersLock) {
2066             final UserData user = getUserDataLU(userId);
2067             if (user != null) {
2068                 return user.startRealtime;
2069             }
2070             return 0;
2071         }
2072     }
2073 
2074     @Override
getUserUnlockRealtime()2075     public long getUserUnlockRealtime() {
2076         synchronized (mUsersLock) {
2077             final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
2078             if (user != null) {
2079                 return user.unlockRealtime;
2080             }
2081             return 0;
2082         }
2083     }
2084 
2085     /**
2086      * Enforces that the calling user is in the same profile group as {@code userId} or that only
2087      * the system UID or root's UID or apps that have the
2088      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS INTERACT_ACROSS_USERS}
2089      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
2090      * can make certain calls to the UserManager.
2091      *
2092      * @param name used as message if SecurityException is thrown
2093      * @throws SecurityException if the caller lacks the required permissions.
2094      */
checkManageOrInteractPermissionIfCallerInOtherProfileGroup(@serIdInt int userId, String name)2095     private void checkManageOrInteractPermissionIfCallerInOtherProfileGroup(@UserIdInt int userId,
2096             String name) {
2097         final int callingUserId = UserHandle.getCallingUserId();
2098         if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId)) {
2099             return;
2100         }
2101         if (hasManageUsersPermission()) {
2102             return;
2103         }
2104         if (hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
2105                 Binder.getCallingUid())) {
2106             return;
2107         }
2108         throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
2109                 + "to: check " + name);
2110     }
2111 
2112     /**
2113      * Enforces that the calling user is in the same profile group as {@code userId} or that only
2114      * the system UID or root's UID or apps that have the
2115      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS INTERACT_ACROSS_USERS}
2116      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2117      * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS}
2118      * can make certain calls to the UserManager.
2119      *
2120      * @param name used as message if SecurityException is thrown
2121      * @throws SecurityException if the caller lacks the required permissions.
2122      */
checkQueryOrInteractPermissionIfCallerInOtherProfileGroup( @serIdInt int userId, String name)2123     private void checkQueryOrInteractPermissionIfCallerInOtherProfileGroup(
2124             @UserIdInt int userId, String name) {
2125         final int callingUserId = UserHandle.getCallingUserId();
2126         if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId)) {
2127             return;
2128         }
2129         if (hasQueryUsersPermission()) {
2130             return;
2131         }
2132         if (hasPermissionGranted(
2133                 Manifest.permission.INTERACT_ACROSS_USERS, Binder.getCallingUid())) {
2134             return;
2135         }
2136         throw new SecurityException("You need INTERACT_ACROSS_USERS, MANAGE_USERS, or QUERY_USERS "
2137                 + "permission to: check " + name);
2138     }
2139 
2140     /**
2141      * Enforces that the calling user is in the same profile group as {@code userId} or that only
2142      * the system UID or root's UID or apps that have the
2143      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2144      * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} or
2145      * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS}
2146      * can make certain calls to the UserManager.
2147      *
2148      * @param userId the user's id
2149      * @param name used as message if SecurityException is thrown
2150      * @throws SecurityException if the caller lacks the required permissions.
2151      */
checkQueryOrCreateUsersPermissionIfCallerInOtherProfileGroup( @serIdInt int userId, String name)2152     private void checkQueryOrCreateUsersPermissionIfCallerInOtherProfileGroup(
2153             @UserIdInt int userId, String name) {
2154         final int callingUserId = UserHandle.getCallingUserId();
2155         if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId)) {
2156             return;
2157         }
2158         checkQueryOrCreateUsersPermission(name);
2159     }
2160 
2161     @Override
isDemoUser(@serIdInt int userId)2162     public boolean isDemoUser(@UserIdInt int userId) {
2163         final int callingUserId = UserHandle.getCallingUserId();
2164         if (callingUserId != userId && !hasManageUsersPermission()) {
2165             throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
2166                     + " is a demo user");
2167         }
2168         synchronized (mUsersLock) {
2169             UserInfo userInfo = getUserInfoLU(userId);
2170             return userInfo != null && userInfo.isDemo();
2171         }
2172     }
2173 
2174     @Override
isAdminUser(@serIdInt int userId)2175     public boolean isAdminUser(@UserIdInt int userId) {
2176         checkQueryOrCreateUsersPermissionIfCallerInOtherProfileGroup(userId, "isAdminUser");
2177         synchronized (mUsersLock) {
2178             final UserInfo userInfo = getUserInfoLU(userId);
2179             return userInfo != null && userInfo.isAdmin();
2180         }
2181     }
2182 
2183     @Override
isPreCreated(@serIdInt int userId)2184     public boolean isPreCreated(@UserIdInt int userId) {
2185         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isPreCreated");
2186         synchronized (mUsersLock) {
2187             UserInfo userInfo = getUserInfoLU(userId);
2188             return userInfo != null && userInfo.preCreated;
2189         }
2190     }
2191 
2192     /**
2193      * Returns whether switching users is currently allowed for the provided user.
2194      * <p>
2195      * Switching users is not allowed in the following cases:
2196      * <li>the user is in a phone call</li>
2197      * <li>{@link UserManager#DISALLOW_USER_SWITCH} is set</li>
2198      * <li>system user hasn't been unlocked yet</li>
2199      *
2200      * @return A {@link UserManager.UserSwitchabilityResult} flag indicating if the user is
2201      * switchable.
2202      */
getUserSwitchability(int userId)2203     public @UserManager.UserSwitchabilityResult int getUserSwitchability(int userId) {
2204         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserSwitchability");
2205 
2206         final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2207         t.traceBegin("getUserSwitchability-" + userId);
2208 
2209         int flags = UserManager.SWITCHABILITY_STATUS_OK;
2210 
2211         t.traceBegin("TM.isInCall");
2212         final long identity = Binder.clearCallingIdentity();
2213         try {
2214             final TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
2215             if (telecomManager != null && telecomManager.isInCall()) {
2216                 flags |= UserManager.SWITCHABILITY_STATUS_USER_IN_CALL;
2217             }
2218         } finally {
2219             Binder.restoreCallingIdentity(identity);
2220         }
2221         t.traceEnd();
2222 
2223         t.traceBegin("hasUserRestriction-DISALLOW_USER_SWITCH");
2224         if (mLocalService.hasUserRestriction(DISALLOW_USER_SWITCH, userId)) {
2225             flags |= UserManager.SWITCHABILITY_STATUS_USER_SWITCH_DISALLOWED;
2226         }
2227         t.traceEnd();
2228 
2229         // System User is always unlocked in Headless System User Mode, so ignore this flag
2230         if (!isHeadlessSystemUserMode()) {
2231             t.traceBegin("getInt-ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED");
2232             final boolean allowUserSwitchingWhenSystemUserLocked = Settings.Global.getInt(
2233                     mContext.getContentResolver(),
2234                     Settings.Global.ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED, 0) != 0;
2235             t.traceEnd();
2236             t.traceBegin("isUserUnlocked-USER_SYSTEM");
2237             final boolean systemUserUnlocked = mLocalService.isUserUnlocked(UserHandle.USER_SYSTEM);
2238             t.traceEnd();
2239 
2240             if (!allowUserSwitchingWhenSystemUserLocked && !systemUserUnlocked) {
2241                 flags |= UserManager.SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED;
2242             }
2243         }
2244         t.traceEnd();
2245 
2246         return flags;
2247     }
2248 
2249     @VisibleForTesting
isUserSwitcherEnabled(@serIdInt int mUserId)2250     boolean isUserSwitcherEnabled(@UserIdInt int mUserId) {
2251         boolean multiUserSettingOn = Settings.Global.getInt(mContext.getContentResolver(),
2252                 Settings.Global.USER_SWITCHER_ENABLED,
2253                 Resources.getSystem().getBoolean(com.android.internal
2254                         .R.bool.config_showUserSwitcherByDefault) ? 1 : 0) != 0;
2255 
2256         return UserManager.supportsMultipleUsers()
2257                 && !hasUserRestriction(DISALLOW_USER_SWITCH, mUserId)
2258                 && !UserManager.isDeviceInDemoMode(mContext)
2259                 && multiUserSettingOn;
2260     }
2261 
2262     @Override
isUserSwitcherEnabled(boolean showEvenIfNotActionable, @UserIdInt int mUserId)2263     public boolean isUserSwitcherEnabled(boolean showEvenIfNotActionable,
2264             @UserIdInt int mUserId) {
2265         if (!isUserSwitcherEnabled(mUserId)) {
2266             return false;
2267         }
2268         // The feature is enabled. But is it worth showing?
2269         return showEvenIfNotActionable
2270                 || !hasUserRestriction(UserManager.DISALLOW_ADD_USER, mUserId) // Can add new user
2271                 || areThereMultipleSwitchableUsers(); // There are switchable users
2272     }
2273 
2274     /** Returns true if there is more than one user that can be switched to. */
areThereMultipleSwitchableUsers()2275     private boolean areThereMultipleSwitchableUsers() {
2276         List<UserInfo> aliveUsers = getUsers(true, true, true);
2277         boolean isAnyAliveUser = false;
2278         for (UserInfo userInfo : aliveUsers) {
2279             if (userInfo.supportsSwitchToByUser()) {
2280                 if (isAnyAliveUser) {
2281                     return true;
2282                 }
2283                 isAnyAliveUser = true;
2284             }
2285         }
2286         return false;
2287     }
2288 
2289     @Override
isRestricted(@serIdInt int userId)2290     public boolean isRestricted(@UserIdInt int userId) {
2291         if (userId != UserHandle.getCallingUserId()) {
2292             checkCreateUsersPermission("query isRestricted for user " + userId);
2293         }
2294         synchronized (mUsersLock) {
2295             final UserInfo userInfo = getUserInfoLU(userId);
2296             return userInfo == null ? false : userInfo.isRestricted();
2297         }
2298     }
2299 
2300     @Override
canHaveRestrictedProfile(@serIdInt int userId)2301     public boolean canHaveRestrictedProfile(@UserIdInt int userId) {
2302         checkManageUsersPermission("canHaveRestrictedProfile");
2303         synchronized (mUsersLock) {
2304             final UserInfo userInfo = getUserInfoLU(userId);
2305             if (userInfo == null || !userInfo.canHaveProfile()) {
2306                 return false;
2307             }
2308             if (!userInfo.isAdmin()) {
2309                 return false;
2310             }
2311             // restricted profile can be created if there is no DO set and the admin user has no PO;
2312             return !mIsDeviceManaged && !mIsUserManaged.get(userId);
2313         }
2314     }
2315 
2316     @Override
hasRestrictedProfiles(@serIdInt int userId)2317     public boolean hasRestrictedProfiles(@UserIdInt int userId) {
2318         checkManageUsersPermission("hasRestrictedProfiles");
2319         synchronized (mUsersLock) {
2320             final int userSize = mUsers.size();
2321             for (int i = 0; i < userSize; i++) {
2322                 UserInfo profile = mUsers.valueAt(i).info;
2323                 if (userId != profile.id
2324                         && profile.restrictedProfileParentId == userId) {
2325                     return true;
2326                 }
2327             }
2328             return false;
2329         }
2330     }
2331 
2332     /*
2333      * Should be locked on mUsers before calling this.
2334      */
2335     @GuardedBy("mUsersLock")
getUserInfoLU(@serIdInt int userId)2336     private UserInfo getUserInfoLU(@UserIdInt int userId) {
2337         final UserData userData = mUsers.get(userId);
2338         // If it is partial and not in the process of being removed, return as unknown user.
2339         if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
2340             Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
2341             return null;
2342         }
2343         return userData != null ? userData.info : null;
2344     }
2345 
2346     @GuardedBy("mUsersLock")
getUserDataLU(@serIdInt int userId)2347     private UserData getUserDataLU(@UserIdInt int userId) {
2348         final UserData userData = mUsers.get(userId);
2349         // If it is partial and not in the process of being removed, return as unknown user.
2350         if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
2351             return null;
2352         }
2353         return userData;
2354     }
2355 
2356     /**
2357      * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
2358      * <p>No permissions checking or any addition checks are made</p>
2359      */
getUserInfoNoChecks(@serIdInt int userId)2360     private UserInfo getUserInfoNoChecks(@UserIdInt int userId) {
2361         synchronized (mUsersLock) {
2362             final UserData userData = mUsers.get(userId);
2363             return userData != null ? userData.info : null;
2364         }
2365     }
2366 
2367     /**
2368      * Obtains {@link #mUsersLock} and return UserData from mUsers.
2369      * <p>No permissions checking or any addition checks are made</p>
2370      */
getUserDataNoChecks(@serIdInt int userId)2371     private UserData getUserDataNoChecks(@UserIdInt int userId) {
2372         synchronized (mUsersLock) {
2373             return mUsers.get(userId);
2374         }
2375     }
2376 
2377     /** Called by PackageManagerService */
exists(@serIdInt int userId)2378     public boolean exists(@UserIdInt int userId) {
2379         return mLocalService.exists(userId);
2380     }
2381 
2382     /**
2383      * Returns user's {@link  CrossProfileIntentFilter.AccessControlLevel}, which is derived from
2384      * {@link UserTypeDetails}. If user does not have defined their access control level,
2385      * returns default {@link CrossProfileIntentFilter#ACCESS_LEVEL_ALL}
2386      */
2387     private @CrossProfileIntentFilter.AccessControlLevel int
getCrossProfileIntentFilterAccessControl(@serIdInt int userId)2388                 getCrossProfileIntentFilterAccessControl(@UserIdInt int userId) {
2389         final UserProperties userProperties = getUserPropertiesInternal(userId);
2390         return userProperties != null ? userProperties.getCrossProfileIntentFilterAccessControl() :
2391                 CrossProfileIntentFilter.ACCESS_LEVEL_ALL;
2392     }
2393 
2394     /**
2395      * Verifies if calling user is allowed to access {@link CrossProfileIntentFilter} between given
2396      * source and target user.
2397      * @param sourceUserId userId for which CrossProfileIntentFilter would be configured
2398      * @param targetUserId target user where we can resolve given intent filter
2399      * @param callingUid user accessing api
2400      * @param addCrossProfileIntentFilter if the operation is addition or not.
2401      * @throws SecurityException is calling user is not allowed to access.
2402      */
enforceCrossProfileIntentFilterAccess( int sourceUserId, int targetUserId, int callingUid, boolean addCrossProfileIntentFilter)2403     public void enforceCrossProfileIntentFilterAccess(
2404             int sourceUserId, int targetUserId,
2405             int callingUid, boolean addCrossProfileIntentFilter) {
2406         if (!isCrossProfileIntentFilterAccessible(sourceUserId, targetUserId,
2407                 addCrossProfileIntentFilter)) {
2408             throw new SecurityException("CrossProfileIntentFilter cannot be accessed by user "
2409                     + callingUid);
2410         }
2411     }
2412 
2413     /**
2414      * Checks if {@link CrossProfileIntentFilter} can be accessed by calling user for given source
2415      * and target user. There are following rules of access
2416      * 1. For {@link CrossProfileIntentFilter#ACCESS_LEVEL_ALL},
2417      *  irrespective of user we would allow access(addition/modification/removal)
2418      * 2. For {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM},
2419      *  only system/root user would be able to access(addition/modification/removal)
2420      * 3. For {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM_ADD_ONLY},
2421      *  only system/root user would be able to add but not modify/remove. Once added, it cannot be
2422      *  modified or removed
2423      * @param sourceUserId userId for which CrossProfileIntentFilter would be configured
2424      * @param targetUserId target user where we can resolve given intent filter
2425      * @param addCrossProfileIntentFilter if the operation is addition or not.
2426      * @return true if {@link CrossProfileIntentFilter} can be accessed by calling user
2427      */
isCrossProfileIntentFilterAccessible(int sourceUserId, int targetUserId, boolean addCrossProfileIntentFilter)2428     public boolean isCrossProfileIntentFilterAccessible(int sourceUserId, int targetUserId,
2429             boolean addCrossProfileIntentFilter) {
2430         int effectiveAccessControl =
2431                 getCrossProfileIntentFilterAccessControl(sourceUserId, targetUserId);
2432 
2433         /*
2434         For {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM}, if accessing user is not
2435         system or root disallowing access to {@link CrossProfileIntentFilter}
2436          */
2437         if (CrossProfileIntentFilter.ACCESS_LEVEL_SYSTEM == effectiveAccessControl
2438                 && !PackageManagerServiceUtils.isSystemOrRoot()) {
2439             return false;
2440         }
2441 
2442         /*
2443         For {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM_ADD_ONLY}, allowing only
2444         system user to add {@link CrossProfileIntentFilter}. All users(including system) are
2445         disallowed to modify/remove.
2446          */
2447         if (CrossProfileIntentFilter.ACCESS_LEVEL_SYSTEM_ADD_ONLY == effectiveAccessControl
2448                 && (!addCrossProfileIntentFilter || !PackageManagerServiceUtils.isSystemOrRoot())) {
2449             return false;
2450         }
2451         return true;
2452     }
2453 
2454     /**
2455      * Returns {@link CrossProfileIntentFilter.AccessControlLevel}
2456      * that should be assigned to {@link CrossProfileIntentFilter}
2457      * computed from source user's and target user's
2458      * {@link CrossProfileIntentFilter.AccessControlLevel}.
2459      * The Access Level is configured per {@link CrossProfileIntentFilter} and its property of edge
2460      * between source and target user e.g. for all {@link CrossProfileIntentFilter}s configured
2461      * between Primary user and Clone profile should have access level of
2462      * {@link CrossProfileIntentFilter#ACCESS_LEVEL_SYSTEM} which is driven by highest
2463      * access value from source or target. The higher value means higher restrictions.
2464      * @param sourceUserId userId of source user for whom CrossProfileIntentFilter will be stored
2465      * @param targetUserId userId of target user for whom Cross Profile access would be allowed
2466      * @return least privileged {@link CrossProfileIntentFilter.AccessControlLevel} from source or
2467      * target user.
2468      */
2469     public @CrossProfileIntentFilter.AccessControlLevel int
getCrossProfileIntentFilterAccessControl(int sourceUserId, int targetUserId)2470                 getCrossProfileIntentFilterAccessControl(int sourceUserId, int targetUserId) {
2471         int sourceAccessControlLevel,
2472                 targetAccessControlLevel, effectiveAccessControl;
2473         sourceAccessControlLevel = getCrossProfileIntentFilterAccessControl(sourceUserId);
2474         targetAccessControlLevel = getCrossProfileIntentFilterAccessControl(targetUserId);
2475         effectiveAccessControl = Math.max(sourceAccessControlLevel, targetAccessControlLevel);
2476         return effectiveAccessControl;
2477     }
2478 
2479     @Override
setUserName(@serIdInt int userId, String name)2480     public void setUserName(@UserIdInt int userId, String name) {
2481         checkManageUsersPermission("rename users");
2482         synchronized (mPackagesLock) {
2483             UserData userData = getUserDataNoChecks(userId);
2484             if (userData == null || userData.info.partial) {
2485                 Slogf.w(LOG_TAG, "setUserName: unknown user #%d", userId);
2486                 return;
2487             }
2488             if (Objects.equals(name, userData.info.name)) {
2489                 Slogf.i(LOG_TAG, "setUserName: ignoring for user #%d as it didn't change (%s)",
2490                         userId, getRedacted(name));
2491                 return;
2492             }
2493             if (name == null) {
2494                 Slogf.i(LOG_TAG, "setUserName: resetting name of user #%d", userId);
2495             } else {
2496                 Slogf.i(LOG_TAG, "setUserName: setting name of user #%d to %s", userId,
2497                         getRedacted(name));
2498             }
2499             userData.info.name = name;
2500             writeUserLP(userData);
2501         }
2502         final long ident = Binder.clearCallingIdentity();
2503         try {
2504             sendUserInfoChangedBroadcast(userId);
2505         } finally {
2506             Binder.restoreCallingIdentity(ident);
2507         }
2508     }
2509 
2510     @Override
setUserEphemeral(@serIdInt int userId, boolean enableEphemeral)2511     public boolean setUserEphemeral(@UserIdInt int userId, boolean enableEphemeral) {
2512         checkCreateUsersPermission("update ephemeral user flag");
2513         UserData userToUpdate = null;
2514         synchronized (mPackagesLock) {
2515             synchronized (mUsersLock) {
2516                 final UserData userData = mUsers.get(userId);
2517                 if (userData == null) {
2518                     Slog.e(LOG_TAG, "User not found for setting ephemeral mode: u" + userId);
2519                     return false;
2520                 }
2521                 boolean isEphemeralUser = (userData.info.flags & UserInfo.FLAG_EPHEMERAL) != 0;
2522                 boolean isEphemeralOnCreateUser =
2523                         (userData.info.flags & UserInfo.FLAG_EPHEMERAL_ON_CREATE) != 0;
2524                 // when user is created in ephemeral mode via FLAG_EPHEMERAL
2525                 // its state cannot be changed to non ephemeral.
2526                 // FLAG_EPHEMERAL_ON_CREATE is used to keep track of this state
2527                 if (isEphemeralOnCreateUser && !enableEphemeral) {
2528                     Slog.e(LOG_TAG, "Failed to change user state to non-ephemeral for user "
2529                             + userId);
2530                     return false;
2531                 }
2532                 if (isEphemeralUser != enableEphemeral) {
2533                     if (enableEphemeral) {
2534                         userData.info.flags |= UserInfo.FLAG_EPHEMERAL;
2535                     } else {
2536                         userData.info.flags &= ~UserInfo.FLAG_EPHEMERAL;
2537                     }
2538                     userToUpdate = userData;
2539                 }
2540             }
2541             if (userToUpdate != null) {
2542                 writeUserLP(userToUpdate);
2543             }
2544         }
2545         return true;
2546     }
2547 
2548     @Override
setUserIcon(@serIdInt int userId, Bitmap bitmap)2549     public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
2550         try {
2551             checkManageUsersPermission("update users");
2552             enforceUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId,
2553                     "Cannot set user icon");
2554             mLocalService.setUserIcon(userId, bitmap);
2555         } catch (UserManager.CheckedUserOperationException e) {
2556             throw e.toServiceSpecificException();
2557         }
2558     }
2559 
2560 
2561 
sendUserInfoChangedBroadcast(@serIdInt int userId)2562     private void sendUserInfoChangedBroadcast(@UserIdInt int userId) {
2563         Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
2564         changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2565         changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2566         mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
2567     }
2568 
2569     @Override
getUserIcon(int targetUserId)2570     public ParcelFileDescriptor getUserIcon(int targetUserId) {
2571         if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
2572             throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
2573                     + "permissions to: get user icon");
2574         }
2575         String iconPath;
2576         synchronized (mPackagesLock) {
2577             UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
2578             if (targetUserInfo == null || targetUserInfo.partial) {
2579                 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
2580                 return null;
2581             }
2582 
2583             final int callingUserId = UserHandle.getCallingUserId();
2584             final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
2585             final int targetGroupId = targetUserInfo.profileGroupId;
2586             final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
2587                     && callingGroupId == targetGroupId);
2588             if ((callingUserId != targetUserId) && !sameGroup) {
2589                 checkManageUsersPermission("get the icon of a user who is not related");
2590             }
2591 
2592             if (targetUserInfo.iconPath == null) {
2593                 return null;
2594             }
2595             iconPath = targetUserInfo.iconPath;
2596         }
2597 
2598         try {
2599             return ParcelFileDescriptor.open(
2600                     new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
2601         } catch (FileNotFoundException e) {
2602             Slog.e(LOG_TAG, "Couldn't find icon file", e);
2603         }
2604         return null;
2605     }
2606 
makeInitialized(@serIdInt int userId)2607     public void makeInitialized(@UserIdInt int userId) {
2608         if (DBG) Slog.d(LOG_TAG, "makeInitialized(" + userId + ")");
2609         checkManageUsersPermission("makeInitialized");
2610         boolean scheduleWriteUser = false;
2611         UserData userData;
2612         synchronized (mUsersLock) {
2613             userData = mUsers.get(userId);
2614             if (userData == null || userData.info.partial) {
2615                 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
2616                 return;
2617             }
2618             if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2619                 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2620                 scheduleWriteUser = true;
2621             }
2622         }
2623         if (scheduleWriteUser) {
2624             scheduleWriteUser(userId);
2625         }
2626     }
2627 
2628     /**
2629      * If default guest restrictions haven't been initialized yet, add the basic
2630      * restrictions.
2631      */
initDefaultGuestRestrictions()2632     private void initDefaultGuestRestrictions() {
2633         synchronized (mGuestRestrictions) {
2634             if (mGuestRestrictions.isEmpty()) {
2635                 UserTypeDetails guestType = mUserTypes.get(UserManager.USER_TYPE_FULL_GUEST);
2636                 if (guestType == null) {
2637                     Slog.wtf(LOG_TAG, "Can't set default guest restrictions: type doesn't exist.");
2638                     return;
2639                 }
2640                 guestType.addDefaultRestrictionsTo(mGuestRestrictions);
2641             }
2642         }
2643     }
2644 
2645     @Override
getDefaultGuestRestrictions()2646     public Bundle getDefaultGuestRestrictions() {
2647         checkManageUsersPermission("getDefaultGuestRestrictions");
2648         synchronized (mGuestRestrictions) {
2649             return new Bundle(mGuestRestrictions);
2650         }
2651     }
2652 
2653     @Override
setDefaultGuestRestrictions(Bundle restrictions)2654     public void setDefaultGuestRestrictions(Bundle restrictions) {
2655         checkManageUsersPermission("setDefaultGuestRestrictions");
2656         final List<UserInfo> guests = getGuestUsers();
2657         synchronized (mRestrictionsLock) {
2658             for (int i = 0; i < guests.size(); i++) {
2659                 updateUserRestrictionsInternalLR(restrictions, guests.get(i).id);
2660             }
2661         }
2662         synchronized (mGuestRestrictions) {
2663             mGuestRestrictions.clear();
2664             mGuestRestrictions.putAll(restrictions);
2665         }
2666         synchronized (mPackagesLock) {
2667             writeUserListLP();
2668         }
2669     }
2670 
2671     @VisibleForTesting
setUserRestrictionInner(int userId, @NonNull String key, boolean value)2672     void setUserRestrictionInner(int userId, @NonNull String key, boolean value) {
2673         if (!UserRestrictionsUtils.isValidRestriction(key)) {
2674             Slog.e(LOG_TAG, "Setting invalid restriction " + key);
2675             return;
2676         }
2677         synchronized (mRestrictionsLock) {
2678             final Bundle newRestrictions = BundleUtils.clone(
2679                     mDevicePolicyUserRestrictions.getRestrictions(userId));
2680             newRestrictions.putBoolean(key, value);
2681 
2682             if (mDevicePolicyUserRestrictions.updateRestrictions(userId, newRestrictions)) {
2683                 if (userId == UserHandle.USER_ALL) {
2684                     applyUserRestrictionsForAllUsersLR();
2685                 } else {
2686                     applyUserRestrictionsLR(userId);
2687                 }
2688             }
2689         }
2690     }
2691 
2692     /**
2693      * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
2694      */
setDevicePolicyUserRestrictionsInner(@serIdInt int originatingUserId, @NonNull Bundle global, @NonNull RestrictionsSet local, boolean isDeviceOwner)2695     private void setDevicePolicyUserRestrictionsInner(@UserIdInt int originatingUserId,
2696             @NonNull Bundle global, @NonNull RestrictionsSet local,
2697             boolean isDeviceOwner) {
2698         synchronized (mRestrictionsLock) {
2699             final IntArray updatedUserIds = mDevicePolicyUserRestrictions.getUserIds();
2700 
2701             mCachedEffectiveUserRestrictions.removeAllRestrictions();
2702             mDevicePolicyUserRestrictions.removeAllRestrictions();
2703 
2704             mDevicePolicyUserRestrictions.updateRestrictions(UserHandle.USER_ALL, global);
2705 
2706             final IntArray localUserIds = local.getUserIds();
2707             for (int i = 0; i < localUserIds.size(); i++) {
2708                 final int userId = localUserIds.get(i);
2709                 mDevicePolicyUserRestrictions.updateRestrictions(userId,
2710                         local.getRestrictions(userId));
2711                 updatedUserIds.add(userId);
2712             }
2713 
2714             applyUserRestrictionsForAllUsersLR();
2715             for (int i = 0; i < updatedUserIds.size(); i++) {
2716                 if (updatedUserIds.get(i) == UserHandle.USER_ALL) {
2717                     continue;
2718                 }
2719                 applyUserRestrictionsLR(updatedUserIds.get(i));
2720             }
2721         }
2722     }
2723 
2724     @GuardedBy("mRestrictionsLock")
computeEffectiveUserRestrictionsLR(@serIdInt int userId)2725     private Bundle computeEffectiveUserRestrictionsLR(@UserIdInt int userId) {
2726         final Bundle baseRestrictions = mBaseUserRestrictions.getRestrictionsNonNull(userId);
2727 
2728         final Bundle global = mDevicePolicyUserRestrictions.getRestrictionsNonNull(
2729                 UserHandle.USER_ALL);
2730         final Bundle local = mDevicePolicyUserRestrictions.getRestrictionsNonNull(userId);
2731 
2732         if (global.isEmpty() && local.isEmpty()) {
2733             // Common case first.
2734             return baseRestrictions;
2735         }
2736         final Bundle effective = BundleUtils.clone(baseRestrictions);
2737         UserRestrictionsUtils.merge(effective, global);
2738         UserRestrictionsUtils.merge(effective, local);
2739 
2740         return effective;
2741     }
2742 
2743     @GuardedBy("mRestrictionsLock")
invalidateEffectiveUserRestrictionsLR(@serIdInt int userId)2744     private void invalidateEffectiveUserRestrictionsLR(@UserIdInt int userId) {
2745         if (DBG) {
2746             Slog.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
2747         }
2748         mCachedEffectiveUserRestrictions.remove(userId);
2749     }
2750 
getEffectiveUserRestrictions(@serIdInt int userId)2751     private Bundle getEffectiveUserRestrictions(@UserIdInt int userId) {
2752         synchronized (mRestrictionsLock) {
2753             Bundle restrictions = mCachedEffectiveUserRestrictions.getRestrictions(userId);
2754             if (restrictions == null) {
2755                 restrictions = computeEffectiveUserRestrictionsLR(userId);
2756                 mCachedEffectiveUserRestrictions.updateRestrictions(userId, restrictions);
2757             }
2758             return restrictions;
2759         }
2760     }
2761 
2762     /** @return a specific user restriction that's in effect currently. */
2763     @Override
hasUserRestriction(String restrictionKey, @UserIdInt int userId)2764     public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
2765         if (!userExists(userId)) {
2766             return false;
2767         }
2768         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "hasUserRestriction");
2769         return mLocalService.hasUserRestriction(restrictionKey, userId);
2770     }
2771 
2772     /** @return if any user has the given restriction. */
2773     @Override
hasUserRestrictionOnAnyUser(String restrictionKey)2774     public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
2775         if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
2776             return false;
2777         }
2778         final List<UserInfo> users = getUsers(/* excludeDying= */ true);
2779         for (int i = 0; i < users.size(); i++) {
2780             final int userId = users.get(i).id;
2781             Bundle restrictions = getEffectiveUserRestrictions(userId);
2782             if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
2783                 return true;
2784             }
2785         }
2786         return false;
2787     }
2788 
2789     @Override
isSettingRestrictedForUser(String setting, @UserIdInt int userId, String value, int callingUid)2790     public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
2791             String value, int callingUid) {
2792         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2793             throw new SecurityException("Non-system caller");
2794         }
2795         return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
2796                 value, callingUid);
2797     }
2798 
2799     @Override
addUserRestrictionsListener(final IUserRestrictionsListener listener)2800     public void addUserRestrictionsListener(final IUserRestrictionsListener listener) {
2801         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2802             throw new SecurityException("Non-system caller");
2803         }
2804 
2805         // NOTE: unregistering not supported; only client is the settings provider,
2806         // which installs a single static permanent listener.  If that listener goes
2807         // bad it implies the whole system process is going to crash.
2808         mLocalService.addUserRestrictionsListener(
2809                 (int userId, Bundle newRestrict, Bundle prevRestrict) -> {
2810                     try {
2811                         listener.onUserRestrictionsChanged(userId, newRestrict, prevRestrict);
2812                     } catch (RemoteException re) {
2813                         Slog.e("IUserRestrictionsListener",
2814                                 "Unable to invoke listener: " + re.getMessage());
2815                     }
2816                 });
2817     }
2818 
2819     /**
2820      * @hide
2821      *
2822      * Returns who set a user restriction on a user.
2823      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2824      * @param restrictionKey the string key representing the restriction
2825      * @param userId the id of the user for whom to retrieve the restrictions.
2826      * @return The source of user restriction. Any combination of
2827      *         {@link UserManager#RESTRICTION_NOT_SET},
2828      *         {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
2829      *         {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
2830      *         and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
2831      */
2832     @Override
getUserRestrictionSource(String restrictionKey, @UserIdInt int userId)2833     public int getUserRestrictionSource(String restrictionKey, @UserIdInt int userId) {
2834         List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey,  userId);
2835         // Get "bitwise or" of restriction sources for all enforcing users.
2836         int result = UserManager.RESTRICTION_NOT_SET;
2837         for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
2838             result |= enforcingUsers.get(i).getUserRestrictionSource();
2839         }
2840         return result;
2841     }
2842 
2843     @Override
getUserRestrictionSources( String restrictionKey, @UserIdInt int userId)2844     public List<EnforcingUser> getUserRestrictionSources(
2845             String restrictionKey, @UserIdInt int userId) {
2846         checkQueryUsersPermission("call getUserRestrictionSources.");
2847 
2848         // Shortcut for the most common case
2849         if (!hasUserRestriction(restrictionKey, userId)) {
2850             return Collections.emptyList();
2851         }
2852 
2853         final List<EnforcingUser> result = new ArrayList<>();
2854 
2855         // Check if it is base restriction.
2856         if (hasBaseUserRestriction(restrictionKey, userId)) {
2857             result.add(new EnforcingUser(
2858                     UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
2859         }
2860 
2861         result.addAll(getDevicePolicyManagerInternal()
2862                 .getUserRestrictionSources(restrictionKey, userId));
2863         return result;
2864     }
2865 
2866     /**
2867      * @return UserRestrictions that are in effect currently.  This always returns a new
2868      * {@link Bundle}.
2869      */
2870     @Override
getUserRestrictions(@serIdInt int userId)2871     public Bundle getUserRestrictions(@UserIdInt int userId) {
2872         checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserRestrictions");
2873         return BundleUtils.clone(getEffectiveUserRestrictions(userId));
2874     }
2875 
2876     @Override
hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId)2877     public boolean hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId) {
2878         checkCreateUsersPermission("hasBaseUserRestriction");
2879         if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
2880             return false;
2881         }
2882         synchronized (mRestrictionsLock) {
2883             Bundle bundle = mBaseUserRestrictions.getRestrictions(userId);
2884             return (bundle != null && bundle.getBoolean(restrictionKey, false));
2885         }
2886     }
2887 
2888     @Override
setUserRestriction(String key, boolean value, @UserIdInt int userId)2889     public void setUserRestriction(String key, boolean value, @UserIdInt int userId) {
2890         checkManageUsersPermission("setUserRestriction");
2891         if (!UserRestrictionsUtils.isValidRestriction(key)) {
2892             return;
2893         }
2894 
2895         if (!userExists(userId)) {
2896             Slogf.w(LOG_TAG, "Cannot set user restriction %s. User with id %d does not exist",
2897                     key, userId);
2898             return;
2899         }
2900         synchronized (mRestrictionsLock) {
2901             // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
2902             // a copy.
2903             final Bundle newRestrictions = BundleUtils.clone(
2904                     mBaseUserRestrictions.getRestrictions(userId));
2905             newRestrictions.putBoolean(key, value);
2906 
2907             updateUserRestrictionsInternalLR(newRestrictions, userId);
2908         }
2909     }
2910 
2911     /**
2912      * Optionally updating user restrictions, calculate the effective user restrictions and also
2913      * propagate to other services and system settings.
2914      *
2915      * @param newBaseRestrictions User restrictions to set.
2916      *      If null, will not update user restrictions and only does the propagation.
2917      * @param userId target user ID.
2918      */
2919     @GuardedBy("mRestrictionsLock")
updateUserRestrictionsInternalLR( @ullable Bundle newBaseRestrictions, @UserIdInt int userId)2920     private void updateUserRestrictionsInternalLR(
2921             @Nullable Bundle newBaseRestrictions, @UserIdInt int userId) {
2922         final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
2923                 mAppliedUserRestrictions.getRestrictions(userId));
2924 
2925         // Update base restrictions.
2926         if (newBaseRestrictions != null) {
2927             // If newBaseRestrictions == the current one, it's probably a bug.
2928             final Bundle prevBaseRestrictions = mBaseUserRestrictions.getRestrictions(userId);
2929 
2930             Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
2931             Preconditions.checkState(mCachedEffectiveUserRestrictions.getRestrictions(userId)
2932                     != newBaseRestrictions);
2933 
2934             if (mBaseUserRestrictions.updateRestrictions(userId, new Bundle(newBaseRestrictions))) {
2935                 scheduleWriteUser(userId);
2936             }
2937         }
2938 
2939         final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
2940 
2941         mCachedEffectiveUserRestrictions.updateRestrictions(userId, new Bundle(effective));
2942 
2943         // Apply the new restrictions.
2944         if (DBG) {
2945             debug("Applying user restrictions: userId=" + userId
2946                     + " new=" + effective + " prev=" + prevAppliedRestrictions);
2947         }
2948 
2949         if (mAppOpsService != null) { // We skip it until system-ready.
2950             mHandler.post(() -> {
2951                 try {
2952                     mAppOpsService.setUserRestrictions(effective, mUserRestrictionToken, userId);
2953                 } catch (RemoteException e) {
2954                     Slog.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
2955                 }
2956             });
2957         }
2958 
2959         propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
2960 
2961         mAppliedUserRestrictions.updateRestrictions(userId, new Bundle(effective));
2962     }
2963 
2964     @GuardedBy("mRestrictionsLock")
propagateUserRestrictionsLR(final int userId, Bundle newRestrictions, Bundle prevRestrictions)2965     private void propagateUserRestrictionsLR(final int userId,
2966             Bundle newRestrictions, Bundle prevRestrictions) {
2967         // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
2968         // actually, but we still need some kind of synchronization otherwise we might end up
2969         // calling listeners out-of-order, thus "LR".
2970 
2971         if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
2972             return;
2973         }
2974 
2975         final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
2976         final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
2977 
2978         mHandler.post(new Runnable() {
2979             @Override
2980             public void run() {
2981                 UserRestrictionsUtils.applyUserRestrictions(
2982                         mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
2983 
2984                 final UserRestrictionsListener[] listeners;
2985                 synchronized (mUserRestrictionsListeners) {
2986                     listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
2987                     mUserRestrictionsListeners.toArray(listeners);
2988                 }
2989                 for (int i = 0; i < listeners.length; i++) {
2990                     listeners[i].onUserRestrictionsChanged(userId,
2991                             newRestrictionsFinal, prevRestrictionsFinal);
2992                 }
2993 
2994                 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
2995                         .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2996                 // Setting the MOST_RECENT policy allows us to discard older broadcasts
2997                 // still waiting to be delivered.
2998                 final Bundle options = BroadcastOptions.makeBasic()
2999                         .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
3000                         .toBundle();
3001                 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId),
3002                         null /* receiverPermission */, options);
3003             }
3004         });
3005     }
3006 
3007     // Package private for the inner class.
3008     @GuardedBy("mRestrictionsLock")
applyUserRestrictionsLR(@serIdInt int userId)3009     private void applyUserRestrictionsLR(@UserIdInt int userId) {
3010         updateUserRestrictionsInternalLR(null, userId);
3011         scheduleWriteUser(userId);
3012     }
3013 
3014     @GuardedBy("mRestrictionsLock")
3015     // Package private for the inner class.
applyUserRestrictionsForAllUsersLR()3016     private void applyUserRestrictionsForAllUsersLR() {
3017         if (DBG) {
3018             debug("applyUserRestrictionsForAllUsersLR");
3019         }
3020         // First, invalidate all cached values.
3021         mCachedEffectiveUserRestrictions.removeAllRestrictions();
3022 
3023         // We don't want to call into ActivityManagerService while taking a lock, so we'll call
3024         // it on a handler.
3025         final Runnable r = new Runnable() {
3026             @Override
3027             public void run() {
3028                 // Then get the list of running users.
3029                 final int[] runningUsers;
3030                 try {
3031                     runningUsers = ActivityManager.getService().getRunningUserIds();
3032                 } catch (RemoteException e) {
3033                     Slog.w(LOG_TAG, "Unable to access ActivityManagerService");
3034                     return;
3035                 }
3036                 // Then re-calculate the effective restrictions and apply, only for running users.
3037                 // It's okay if a new user has started after the getRunningUserIds() call,
3038                 // because we'll do the same thing (re-calculate the restrictions and apply)
3039                 // when we start a user.
3040                 synchronized (mRestrictionsLock) {
3041                     for (int i = 0; i < runningUsers.length; i++) {
3042                         applyUserRestrictionsLR(runningUsers[i]);
3043                     }
3044                 }
3045             }
3046         };
3047         mHandler.post(r);
3048     }
3049 
3050     /**
3051      * Check if we've hit the limit of how many users can be created.
3052      */
isUserLimitReached()3053     private boolean isUserLimitReached() {
3054         int count;
3055         synchronized (mUsersLock) {
3056             count = getAliveUsersExcludingGuestsCountLU();
3057         }
3058         return count >= UserManager.getMaxSupportedUsers()
3059                 && !isCreationOverrideEnabled();
3060     }
3061 
3062     /**
3063      * Returns whether more users of the given type can be added (based on how many users of that
3064      * type already exist).
3065      *
3066      * <p>For checking whether more profiles can be added to a particular parent use
3067      * {@link #canAddMoreProfilesToUser}.
3068      */
canAddMoreUsersOfType(@onNull UserTypeDetails userTypeDetails)3069     private boolean canAddMoreUsersOfType(@NonNull UserTypeDetails userTypeDetails) {
3070         if (!isUserTypeEnabled(userTypeDetails)) {
3071             return false;
3072         }
3073         final int max = userTypeDetails.getMaxAllowed();
3074         if (max == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
3075             return true; // Indicates that there is no max.
3076         }
3077         return getNumberOfUsersOfType(userTypeDetails.getName()) < max
3078                 || isCreationOverrideEnabled();
3079     }
3080 
3081     /**
3082      * Returns the remaining number of users of the given type that can be created. (taking into
3083      * account the total number of users on the device as well as how many exist of that type)
3084      */
3085     @Override
getRemainingCreatableUserCount(String userType)3086     public int getRemainingCreatableUserCount(String userType) {
3087         checkQueryOrCreateUsersPermission("get the remaining number of users that can be added.");
3088         final UserTypeDetails type = mUserTypes.get(userType);
3089         if (type == null || !isUserTypeEnabled(type)) {
3090             return 0;
3091         }
3092         synchronized (mUsersLock) {
3093             final int userCount = getAliveUsersExcludingGuestsCountLU();
3094 
3095             // Limit total number of users that can be created (except for guest and demo)
3096             int result =
3097                     UserManager.isUserTypeGuest(userType) || UserManager.isUserTypeDemo(userType)
3098                         ? Integer.MAX_VALUE
3099                         : (UserManager.getMaxSupportedUsers() - userCount);
3100 
3101             // Managed profiles have their own specific rules.
3102             if (type.isManagedProfile()) {
3103                 if (!mContext.getPackageManager().hasSystemFeature(
3104                         PackageManager.FEATURE_MANAGED_USERS)) {
3105                     return 0;
3106                 }
3107                 // Special case: Allow creating a managed profile anyway if there's only 1 user
3108                 if (result <= 0 & userCount == 1) {
3109                     result = 1;
3110                 }
3111             }
3112             if (result <= 0) {
3113                 return 0;
3114             }
3115 
3116             // Limit against max allowed for type
3117             result = Math.min(result,
3118                     type.getMaxAllowed() == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS
3119                         ? Integer.MAX_VALUE
3120                         : (type.getMaxAllowed() - getNumberOfUsersOfType(userType)));
3121 
3122             return Math.max(0, result);
3123         }
3124     }
3125 
3126     /**
3127      * Gets the number of users of the given user type.
3128      * Does not include users that are about to die.
3129      */
getNumberOfUsersOfType(String userType)3130     private int getNumberOfUsersOfType(String userType) {
3131         int count = 0;
3132         synchronized (mUsersLock) {
3133             final int size = mUsers.size();
3134             for (int i = 0; i < size; i++) {
3135                 final UserInfo user = mUsers.valueAt(i).info;
3136                 if (user.userType.equals(userType)
3137                         && !user.guestToRemove
3138                         && !mRemovingUserIds.get(user.id)
3139                         && !user.preCreated) {
3140                     count++;
3141                 }
3142             }
3143         }
3144         return count;
3145     }
3146 
3147     /**
3148      * Returns whether more users of the given type can be added (based on how many users of that
3149      * type already exist).
3150      */
3151     @Override
canAddMoreUsersOfType(String userType)3152     public boolean canAddMoreUsersOfType(String userType) {
3153         checkCreateUsersPermission("check if more users can be added.");
3154         final UserTypeDetails userTypeDetails = mUserTypes.get(userType);
3155         return userTypeDetails != null && canAddMoreUsersOfType(userTypeDetails);
3156     }
3157 
3158     /** Returns whether the creation of users of the given user type is enabled on this device. */
3159     @Override
isUserTypeEnabled(String userType)3160     public boolean isUserTypeEnabled(String userType) {
3161         checkCreateUsersPermission("check if user type is enabled.");
3162         final UserTypeDetails userTypeDetails = mUserTypes.get(userType);
3163         return userTypeDetails != null && isUserTypeEnabled(userTypeDetails);
3164     }
3165 
3166     /** Returns whether the creation of users of the given user type is enabled on this device. */
isUserTypeEnabled(@onNull UserTypeDetails userTypeDetails)3167     private boolean isUserTypeEnabled(@NonNull UserTypeDetails userTypeDetails) {
3168         return userTypeDetails.isEnabled() || isCreationOverrideEnabled();
3169     }
3170 
3171     /**
3172      * Returns whether to almost-always allow creating users even beyond their limit or if disabled.
3173      * For Debug builds only.
3174      */
isCreationOverrideEnabled()3175     private boolean isCreationOverrideEnabled() {
3176         return Build.isDebuggable()
3177                 && SystemProperties.getBoolean(DEV_CREATE_OVERRIDE_PROPERTY, false);
3178     }
3179 
3180     @Override
canAddMoreManagedProfiles(@serIdInt int userId, boolean allowedToRemoveOne)3181     public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
3182         return canAddMoreProfilesToUser(UserManager.USER_TYPE_PROFILE_MANAGED, userId,
3183                 allowedToRemoveOne);
3184     }
3185 
3186     /** Returns whether more profiles of the given type can be added to the given parent userId. */
3187     @Override
canAddMoreProfilesToUser(String userType, @UserIdInt int userId, boolean allowedToRemoveOne)3188     public boolean canAddMoreProfilesToUser(String userType, @UserIdInt int userId,
3189             boolean allowedToRemoveOne) {
3190         return 0 < getRemainingCreatableProfileCount(userType, userId, allowedToRemoveOne)
3191                 || isCreationOverrideEnabled();
3192     }
3193 
3194     @Override
getRemainingCreatableProfileCount(@onNull String userType, @UserIdInt int userId)3195     public int getRemainingCreatableProfileCount(@NonNull String userType, @UserIdInt int userId) {
3196         return getRemainingCreatableProfileCount(userType, userId, false);
3197     }
3198 
3199     /**
3200      * Returns the remaining number of profiles of the given type that can be added to the given
3201      * user. (taking into account the total number of users on the device as well as how many
3202      * profiles exist of that type both in general and for the given user)
3203      */
getRemainingCreatableProfileCount(@onNull String userType, @UserIdInt int userId, boolean allowedToRemoveOne)3204     private int getRemainingCreatableProfileCount(@NonNull String userType, @UserIdInt int userId,
3205             boolean allowedToRemoveOne) {
3206         checkQueryOrCreateUsersPermission(
3207                 "get the remaining number of profiles that can be added to the given user.");
3208         final UserTypeDetails type = mUserTypes.get(userType);
3209         if (type == null || !isUserTypeEnabled(type)) {
3210             return 0;
3211         }
3212         // Managed profiles have their own specific rules.
3213         final boolean isManagedProfile = type.isManagedProfile();
3214         if (isManagedProfile) {
3215             if (!mContext.getPackageManager().hasSystemFeature(
3216                     PackageManager.FEATURE_MANAGED_USERS)) {
3217                 return 0;
3218             }
3219         }
3220         synchronized (mUsersLock) {
3221             // Check if the parent exists and its type is even allowed to have a profile.
3222             UserInfo userInfo = getUserInfoLU(userId);
3223             if (userInfo == null || !userInfo.canHaveProfile()) {
3224                 return 0;
3225             }
3226 
3227             final int userTypeCount = getProfileIds(userId, userType, false).length;
3228             final int profilesRemovedCount = userTypeCount > 0 && allowedToRemoveOne ? 1 : 0;
3229             final int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
3230                     - profilesRemovedCount;
3231 
3232             // Limit total number of users that can be created
3233             int result = UserManager.getMaxSupportedUsers() - usersCountAfterRemoving;
3234 
3235             // Special case: Allow creating a managed profile anyway if there's only 1 user
3236             if (result <= 0 && isManagedProfile && usersCountAfterRemoving == 1) {
3237                 result = 1;
3238             }
3239 
3240             // Limit the number of profiles of this type that can be created.
3241             final int maxUsersOfType = getMaxUsersOfTypePerParent(type);
3242             if (maxUsersOfType != UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
3243                 result = Math.min(result, maxUsersOfType - (userTypeCount - profilesRemovedCount));
3244             }
3245             if (result <= 0) {
3246                 return 0;
3247             }
3248 
3249             // Limit against max allowed for type (beyond max allowed per parent)
3250             if (type.getMaxAllowed() != UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
3251                 result = Math.min(result, type.getMaxAllowed()
3252                         - (getNumberOfUsersOfType(userType) - profilesRemovedCount));
3253             }
3254 
3255             return Math.max(0, result);
3256         }
3257     }
3258 
3259     @GuardedBy("mUsersLock")
getAliveUsersExcludingGuestsCountLU()3260     private int getAliveUsersExcludingGuestsCountLU() {
3261         int aliveUserCount = 0;
3262         final int totalUserCount = mUsers.size();
3263         // Skip over users being removed
3264         for (int i = 0; i < totalUserCount; i++) {
3265             UserInfo user = mUsers.valueAt(i).info;
3266             if (!mRemovingUserIds.get(user.id) && !user.isGuest() && !user.preCreated) {
3267                 aliveUserCount++;
3268             }
3269         }
3270         return aliveUserCount;
3271     }
3272 
3273     /**
3274      * Enforces that only the system UID or root's UID or apps that have the
3275      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
3276      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
3277      * permissions can make certain calls to the UserManager.
3278      *
3279      * @param message used as message if SecurityException is thrown
3280      * @throws SecurityException if the caller does not have enough privilege.
3281      */
checkManageUserAndAcrossUsersFullPermission(String message)3282     private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
3283         final int uid = Binder.getCallingUid();
3284 
3285         if (uid == Process.SYSTEM_UID || uid == 0) {
3286             // System UID or root's UID are granted privilege.
3287             return;
3288         }
3289 
3290         if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
3291                 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
3292             // Apps with both permissions are granted privilege.
3293             return;
3294         }
3295 
3296         throw new SecurityException(
3297                 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
3298     }
3299 
hasPermissionGranted(String permission, int uid)3300     private static boolean hasPermissionGranted(String permission, int uid) {
3301         return ActivityManager.checkComponentPermission(
3302                 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
3303                 PackageManager.PERMISSION_GRANTED;
3304     }
3305 
3306     /**
3307      * Enforces that only the system UID or root's UID or apps that have the
3308      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
3309      * permission can make certain calls to the UserManager.
3310      *
3311      * @param message used as message if SecurityException is thrown
3312      * @throws SecurityException if the caller is not system or root
3313      * @see #hasManageUsersPermission()
3314      */
checkManageUsersPermission(String message)3315     private static final void checkManageUsersPermission(String message) {
3316         if (!hasManageUsersPermission()) {
3317             throw new SecurityException("You need MANAGE_USERS permission to: " + message);
3318         }
3319     }
3320 
3321     /**
3322      * Enforces that only the system UID or root's UID or apps that have the
3323      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
3324      * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
3325      * can make certain calls to the UserManager.
3326      *
3327      * @param message used as message if SecurityException is thrown
3328      * @throws SecurityException if the caller is not system or root
3329      * @see #hasCreateUsersPermission()
3330      */
checkCreateUsersPermission(String message)3331     private static final void checkCreateUsersPermission(String message) {
3332         if (!hasCreateUsersPermission()) {
3333             throw new SecurityException(
3334                     "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
3335         }
3336     }
3337 
3338     /**
3339      * Enforces that only the system UID or root's UID or apps that have the
3340      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
3341      * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS}
3342      * can make certain calls to the UserManager.
3343      *
3344      * @param message used as message if SecurityException is thrown
3345      * @throws SecurityException if the caller lacks the required permissions.
3346      */
checkQueryUsersPermission(String message)3347     private static final void checkQueryUsersPermission(String message) {
3348         if (!hasQueryUsersPermission()) {
3349             throw new SecurityException(
3350                     "You either need MANAGE_USERS or QUERY_USERS permission to: " + message);
3351         }
3352     }
3353 
3354     /**
3355      * Enforces that only the system UID or root's UID or apps that have the
3356      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
3357      * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} or
3358      * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS}
3359      * can make certain calls to the UserManager.
3360      *
3361      * @param message used as message if SecurityException is thrown
3362      * @throws SecurityException if the caller lacks the required permissions.
3363      */
checkQueryOrCreateUsersPermission(String message)3364     private static final void checkQueryOrCreateUsersPermission(String message) {
3365         if (!hasQueryOrCreateUsersPermission()) {
3366             throw new SecurityException(
3367                     "You either need MANAGE_USERS, CREATE_USERS, or QUERY_USERS permission to: "
3368                             + message);
3369         }
3370     }
3371 
3372     /**
3373      * Similar to {@link #checkCreateUsersPermission(String)} but when the caller is tries
3374      * to create user/profiles other than what is allowed for
3375      * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
3376      * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
3377      */
checkCreateUsersPermission(int creationFlags)3378     private static final void checkCreateUsersPermission(int creationFlags) {
3379         if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
3380             if (!hasCreateUsersPermission()) {
3381                 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
3382                         + "permission to create an user with flags: " + creationFlags);
3383             }
3384         } else if (!hasManageUsersPermission()) {
3385             throw new SecurityException("You need MANAGE_USERS permission to create an user "
3386                     + " with flags: " + creationFlags);
3387         }
3388     }
3389 
3390     /**
3391      * @return whether the calling UID is system UID or root's UID or the calling app has the
3392      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
3393      */
hasManageUsersPermission()3394     private static final boolean hasManageUsersPermission() {
3395         final int callingUid = Binder.getCallingUid();
3396         return hasManageUsersPermission(callingUid);
3397     }
3398 
3399     /**
3400      * @return whether the given UID is system UID or root's UID or the has the permission
3401      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
3402      */
hasManageUsersPermission(int callingUid)3403     private static boolean hasManageUsersPermission(int callingUid) {
3404         return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
3405                 || callingUid == Process.ROOT_UID
3406                 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
3407     }
3408 
3409     /**
3410      * @return whether the calling UID is system UID or root's UID or the calling app has the
3411      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
3412      */
hasManageUsersOrPermission(String alternativePermission)3413     private static final boolean hasManageUsersOrPermission(String alternativePermission) {
3414         final int callingUid = Binder.getCallingUid();
3415         return hasManageUsersPermission(callingUid)
3416                 || hasPermissionGranted(alternativePermission, callingUid);
3417     }
3418 
3419     /**
3420      * @return whether the calling UID is system UID or root's UID or the calling app has the
3421      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
3422      * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
3423      */
hasCreateUsersPermission()3424     private static final boolean hasCreateUsersPermission() {
3425         return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
3426     }
3427 
3428     /**
3429      * @return whether the calling UID is system UID or root's UID or the calling app has the
3430      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
3431      * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS}.
3432      */
hasQueryUsersPermission()3433     private static final boolean hasQueryUsersPermission() {
3434         return hasManageUsersOrPermission(android.Manifest.permission.QUERY_USERS);
3435     }
3436 
3437     /**
3438      * @return whether the calling UID is system UID or root's UID or the calling app has
3439      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
3440      * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} or
3441      * {@link android.Manifest.permission#QUERY_USERS QUERY_USERS}.
3442      */
hasQueryOrCreateUsersPermission()3443     private static final boolean hasQueryOrCreateUsersPermission() {
3444         return hasCreateUsersPermission()
3445                 || hasPermissionGranted(Manifest.permission.QUERY_USERS, Binder.getCallingUid());
3446     }
3447 
3448     /**
3449      * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
3450      * UserManager.
3451      *
3452      * @param message used as message if SecurityException is thrown
3453      * @throws SecurityException if the caller is not system or root
3454      */
checkSystemOrRoot(String message)3455     private static void checkSystemOrRoot(String message) {
3456         final int uid = Binder.getCallingUid();
3457         if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
3458             throw new SecurityException("Only system may: " + message);
3459         }
3460     }
3461 
3462     @GuardedBy({"mPackagesLock"})
writeBitmapLP(UserInfo info, Bitmap bitmap)3463     private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
3464         try {
3465             File dir = new File(mUsersDir, Integer.toString(info.id));
3466             File file = new File(dir, USER_PHOTO_FILENAME);
3467             File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
3468             if (!dir.exists()) {
3469                 dir.mkdir();
3470                 FileUtils.setPermissions(
3471                         dir.getPath(),
3472                         FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3473                         -1, -1);
3474             }
3475             FileOutputStream os;
3476             if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
3477                     && tmp.renameTo(file) && SELinux.restorecon(file)) {
3478                 info.iconPath = file.getAbsolutePath();
3479             }
3480             try {
3481                 os.close();
3482             } catch (IOException ioe) {
3483                 // What the ... !
3484             }
3485             tmp.delete();
3486         } catch (FileNotFoundException e) {
3487             Slog.w(LOG_TAG, "Error setting photo for user ", e);
3488         }
3489     }
3490 
3491     /**
3492      * Returns an array of user ids.
3493      *
3494      * <p>This array is cached here for quick access, so do not modify or cache it elsewhere.
3495      *
3496      * @return the array of user ids.
3497      */
getUserIds()3498     public @NonNull int[] getUserIds() {
3499         synchronized (mUsersLock) {
3500             return mUserIds;
3501         }
3502     }
3503 
3504     /**
3505      * Checks whether user with a given ID exists.
3506      * @param id User id to be checked.
3507      */
3508     @VisibleForTesting
userExists(int id)3509     boolean userExists(int id) {
3510         synchronized (mUsersLock) {
3511             for (int userId : mUserIds) {
3512                 if (userId == id) {
3513                     return true;
3514                 }
3515             }
3516         }
3517         return false;
3518     }
3519 
3520     /**
3521      * Returns an array of user ids, including pre-created users.
3522      *
3523      * <p>This method should only used for the specific cases that need to handle pre-created users;
3524      * most callers should call {@link #getUserIds()} instead.
3525      *
3526      * <p>This array is cached here for quick access, so do not modify or
3527      * cache it elsewhere.
3528      *
3529      * @return the array of user ids.
3530      */
getUserIdsIncludingPreCreated()3531     public @NonNull int[] getUserIdsIncludingPreCreated() {
3532         synchronized (mUsersLock) {
3533             return mUserIdsIncludingPreCreated;
3534         }
3535     }
3536 
3537     /** Checks whether the device is currently in headless system user mode (for any reason). */
3538     @Override
isHeadlessSystemUserMode()3539     public boolean isHeadlessSystemUserMode() {
3540         synchronized (mUsersLock) {
3541             final UserData systemUserData = mUsers.get(UserHandle.USER_SYSTEM);
3542             return !systemUserData.info.isFull();
3543         }
3544     }
3545 
3546     /**
3547      * Checks whether the default state of the device is headless system user mode, i.e. what the
3548      * mode would be if we did a fresh factory reset.
3549      * If the mode is  being emulated (via SYSTEM_USER_MODE_EMULATION_PROPERTY) then that will be
3550      * returned instead.
3551      * Note that, even in the absence of emulation, a device might deviate from the current default
3552      * due to an OTA changing the default (which won't change the already-decided mode).
3553      */
isDefaultHeadlessSystemUserMode()3554     private boolean isDefaultHeadlessSystemUserMode() {
3555         if (!Build.isDebuggable()) {
3556             return RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER;
3557         }
3558 
3559         final String emulatedValue = SystemProperties.get(SYSTEM_USER_MODE_EMULATION_PROPERTY);
3560         if (!TextUtils.isEmpty(emulatedValue)) {
3561             if (UserManager.SYSTEM_USER_MODE_EMULATION_HEADLESS.equals(emulatedValue)) return true;
3562             if (UserManager.SYSTEM_USER_MODE_EMULATION_FULL.equals(emulatedValue)) return false;
3563             if (!UserManager.SYSTEM_USER_MODE_EMULATION_DEFAULT.equals(emulatedValue)) {
3564                 Slogf.e(LOG_TAG, "isDefaultHeadlessSystemUserMode(): ignoring invalid valued of "
3565                                 + "property %s: %s",
3566                         SYSTEM_USER_MODE_EMULATION_PROPERTY, emulatedValue);
3567             }
3568         }
3569 
3570         return RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER;
3571     }
3572 
3573     /**
3574      * Called on boot to change the system user mode (for example, from headless to full or
3575      * vice versa) for development purposes.
3576      */
emulateSystemUserModeIfNeeded()3577     private void emulateSystemUserModeIfNeeded() {
3578         if (!Build.isDebuggable()) {
3579             return;
3580         }
3581         if (TextUtils.isEmpty(SystemProperties.get(SYSTEM_USER_MODE_EMULATION_PROPERTY))) {
3582             return;
3583         }
3584 
3585         final boolean newHeadlessSystemUserMode = isDefaultHeadlessSystemUserMode();
3586 
3587         // Update system user type
3588         synchronized (mPackagesLock) {
3589             synchronized (mUsersLock) {
3590                 final UserData systemUserData = mUsers.get(UserHandle.USER_SYSTEM);
3591                 if (systemUserData == null) {
3592                     Slogf.wtf(LOG_TAG, "emulateSystemUserModeIfNeeded(): no system user data");
3593                     return;
3594                 }
3595                 final int oldMainUserId = getMainUserIdUnchecked();
3596                 final int oldSysFlags = systemUserData.info.flags;
3597                 final int newSysFlags;
3598                 final String newUserType;
3599                 if (newHeadlessSystemUserMode) {
3600                     newUserType = UserManager.USER_TYPE_SYSTEM_HEADLESS;
3601                     newSysFlags = oldSysFlags & ~UserInfo.FLAG_FULL & ~UserInfo.FLAG_MAIN;
3602                 } else {
3603                     newUserType = UserManager.USER_TYPE_FULL_SYSTEM;
3604                     newSysFlags = oldSysFlags | UserInfo.FLAG_FULL | UserInfo.FLAG_MAIN;
3605                 }
3606 
3607                 if (systemUserData.info.userType.equals(newUserType)) {
3608                     Slogf.d(LOG_TAG, "emulateSystemUserModeIfNeeded(): system user type is already "
3609                             + "%s, returning", newUserType);
3610                     return;
3611                 }
3612                 Slogf.i(LOG_TAG, "Persisting emulated system user data: type changed from %s to "
3613                         + "%s, flags changed from %s to %s",
3614                         systemUserData.info.userType, newUserType,
3615                         UserInfo.flagsToString(oldSysFlags), UserInfo.flagsToString(newSysFlags));
3616 
3617                 systemUserData.info.userType = newUserType;
3618                 systemUserData.info.flags = newSysFlags;
3619                 writeUserLP(systemUserData);
3620 
3621                 // Designate the MainUser to a reasonable choice if needed.
3622                 final UserData oldMain = getUserDataNoChecks(oldMainUserId);
3623                 if (newHeadlessSystemUserMode) {
3624                     final boolean mainIsAlreadyNonSystem =
3625                             oldMain != null && (oldMain.info.flags & UserInfo.FLAG_SYSTEM) == 0;
3626                     if (!mainIsAlreadyNonSystem && isMainUserPermanentAdmin()) {
3627                         // We need a new choice for Main. Pick the oldest.
3628                         // If no oldest, don't set any. Let the BootUserInitializer do that later.
3629                         final UserInfo newMainUser = getEarliestCreatedFullUser();
3630                         if (newMainUser != null) {
3631                             Slogf.i(LOG_TAG, "Designating user " + newMainUser.id + " to be Main");
3632                             newMainUser.flags |= UserInfo.FLAG_MAIN;
3633                             writeUserLP(getUserDataNoChecks(newMainUser.id));
3634                         }
3635                     }
3636                 } else {
3637                     // We already made user 0 Main above. Now strip it from the old Main user.
3638                     // TODO(b/256624031): For now, we demand the Main user (if there is one) is
3639                     //  always the system in non-HSUM. In the future, when we relax this, change how
3640                     //  we handle MAIN.
3641                     if (oldMain != null && (oldMain.info.flags & UserInfo.FLAG_SYSTEM) == 0) {
3642                         Slogf.i(LOG_TAG, "Transferring Main to user 0 from " + oldMain.info.id);
3643                         oldMain.info.flags &= ~UserInfo.FLAG_MAIN;
3644                         writeUserLP(oldMain);
3645                     } else {
3646                         Slogf.i(LOG_TAG, "Designated user 0 to be Main");
3647                     }
3648                 }
3649             }
3650         }
3651 
3652         // Update emulated mode, which will used to trigger an update on user packages
3653         mUpdatingSystemUserMode = true;
3654     }
3655 
3656 
getUserListFile()3657     private ResilientAtomicFile getUserListFile() {
3658         File tempBackup = new File(mUserListFile.getParent(), mUserListFile.getName() + ".backup");
3659         File reserveCopy = new File(mUserListFile.getParent(),
3660                 mUserListFile.getName() + ".reservecopy");
3661         int fileMode = FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IXOTH;
3662         return new ResilientAtomicFile(mUserListFile, tempBackup, reserveCopy, fileMode,
3663                 "user list", (priority, msg) -> {
3664             Slog.e(LOG_TAG, msg);
3665             // Something went wrong, schedule full rewrite.
3666             scheduleWriteUserList();
3667         });
3668     }
3669 
3670     @GuardedBy({"mPackagesLock"})
readUserListLP()3671     private void readUserListLP() {
3672         try (ResilientAtomicFile file = getUserListFile()) {
3673             FileInputStream fin = null;
3674             try {
3675                 fin = file.openRead();
3676                 if (fin == null) {
3677                     Slog.e(LOG_TAG, "userlist.xml not found, fallback to single user");
3678                     fallbackToSingleUserLP();
3679                     return;
3680                 }
3681 
3682                 final TypedXmlPullParser parser = Xml.resolvePullParser(fin);
3683                 int type;
3684                 while ((type = parser.next()) != XmlPullParser.START_TAG
3685                         && type != XmlPullParser.END_DOCUMENT) {
3686                     // Skip
3687                 }
3688 
3689                 if (type != XmlPullParser.START_TAG) {
3690                     Slog.e(LOG_TAG, "Unable to read user list");
3691                     fallbackToSingleUserLP();
3692                     return;
3693                 }
3694 
3695                 mNextSerialNumber = -1;
3696                 if (parser.getName().equals(TAG_USERS)) {
3697                     mNextSerialNumber =
3698                             parser.getAttributeInt(null, ATTR_NEXT_SERIAL_NO, mNextSerialNumber);
3699                     mUserVersion =
3700                             parser.getAttributeInt(null, ATTR_USER_VERSION, mUserVersion);
3701                     mUserTypeVersion =
3702                             parser.getAttributeInt(null, ATTR_USER_TYPE_VERSION, mUserTypeVersion);
3703                 }
3704 
3705                 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3706                     if (type == XmlPullParser.START_TAG) {
3707                         final String name = parser.getName();
3708                         if (name.equals(TAG_USER)) {
3709                             UserData userData = readUserLP(parser.getAttributeInt(null, ATTR_ID),
3710                                     mUserVersion);
3711 
3712                             if (userData != null) {
3713                                 synchronized (mUsersLock) {
3714                                     mUsers.put(userData.info.id, userData);
3715                                     if (mNextSerialNumber < 0
3716                                             || mNextSerialNumber <= userData.info.id) {
3717                                         mNextSerialNumber = userData.info.id + 1;
3718                                     }
3719                                 }
3720                             }
3721                         } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
3722                             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3723                                     && type != XmlPullParser.END_TAG) {
3724                                 if (type == XmlPullParser.START_TAG) {
3725                                     if (parser.getName().equals(TAG_RESTRICTIONS)) {
3726                                         synchronized (mGuestRestrictions) {
3727                                             UserRestrictionsUtils
3728                                                     .readRestrictions(parser, mGuestRestrictions);
3729                                         }
3730                                     }
3731                                     break;
3732                                 }
3733                             }
3734                         }
3735                     }
3736                 }
3737 
3738                 updateUserIds();
3739                 upgradeIfNecessaryLP();
3740             } catch (Exception e) {
3741                 // Remove corrupted file and retry.
3742                 file.failRead(fin, e);
3743                 readUserListLP();
3744                 return;
3745             }
3746         }
3747 
3748         synchronized (mUsersLock) {
3749             if (mUsers.size() == 0) {
3750                 Slog.e(LOG_TAG, "mUsers is empty, fallback to single user");
3751                 fallbackToSingleUserLP();
3752             }
3753         }
3754     }
3755 
3756     /**
3757      * Upgrade steps between versions, either for fixing bugs or changing the data format.
3758      */
3759     @GuardedBy({"mPackagesLock"})
upgradeIfNecessaryLP()3760     private void upgradeIfNecessaryLP() {
3761         upgradeIfNecessaryLP(mUserVersion, mUserTypeVersion);
3762     }
3763 
3764     /**
3765      * Version of {@link #upgradeIfNecessaryLP()} that takes in the userVersion for testing
3766      * purposes. For non-tests, use {@link #upgradeIfNecessaryLP()}.
3767      */
3768     @GuardedBy({"mPackagesLock"})
3769     @VisibleForTesting
upgradeIfNecessaryLP(int userVersion, int userTypeVersion)3770     void upgradeIfNecessaryLP(int userVersion, int userTypeVersion) {
3771         Slog.i(LOG_TAG, "Upgrading users from userVersion " + userVersion + " to " + USER_VERSION);
3772         Set<Integer> userIdsToWrite = new ArraySet<>();
3773         final int originalVersion = mUserVersion;
3774         final int originalUserTypeVersion = mUserTypeVersion;
3775         if (userVersion < 1) {
3776             // Assign a proper name for the owner, if not initialized correctly before
3777             UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
3778             if ("Primary".equals(userData.info.name)) {
3779                 userData.info.name =
3780                         mContext.getResources().getString(com.android.internal.R.string.owner_name);
3781                 userIdsToWrite.add(userData.info.id);
3782             }
3783             userVersion = 1;
3784         }
3785 
3786         if (userVersion < 2) {
3787             // Owner should be marked as initialized
3788             UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
3789             if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
3790                 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
3791                 userIdsToWrite.add(userData.info.id);
3792             }
3793             userVersion = 2;
3794         }
3795 
3796 
3797         if (userVersion < 4) {
3798             userVersion = 4;
3799         }
3800 
3801         if (userVersion < 5) {
3802             initDefaultGuestRestrictions();
3803             userVersion = 5;
3804         }
3805 
3806         if (userVersion < 6) {
3807             synchronized (mUsersLock) {
3808                 for (int i = 0; i < mUsers.size(); i++) {
3809                     UserData userData = mUsers.valueAt(i);
3810                     // Only system user can have restricted profiles
3811                     if (userData.info.isRestricted() && (userData.info.restrictedProfileParentId
3812                             == UserInfo.NO_PROFILE_GROUP_ID)) {
3813                         userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
3814                         userIdsToWrite.add(userData.info.id);
3815                     }
3816                 }
3817             }
3818             userVersion = 6;
3819         }
3820 
3821         if (userVersion < 7) {
3822             // Previously only one user could enforce global restrictions, now it is per-user.
3823             synchronized (mRestrictionsLock) {
3824                 if (mDevicePolicyUserRestrictions.removeRestrictionsForAllUsers(
3825                         UserManager.ENSURE_VERIFY_APPS)) {
3826                     mDevicePolicyUserRestrictions.getRestrictionsNonNull(UserHandle.USER_ALL)
3827                             .putBoolean(UserManager.ENSURE_VERIFY_APPS, true);
3828                 }
3829             }
3830             // DISALLOW_CONFIG_WIFI was made a default guest restriction some time during version 6.
3831             final List<UserInfo> guestUsers = getGuestUsers();
3832             for (int i = 0; i < guestUsers.size(); i++) {
3833                 final UserInfo guestUser = guestUsers.get(i);
3834                 if (guestUser != null && !hasUserRestriction(
3835                         UserManager.DISALLOW_CONFIG_WIFI, guestUser.id)) {
3836                     setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, guestUser.id);
3837                 }
3838             }
3839             userVersion = 7;
3840         }
3841 
3842         if (userVersion < 8) {
3843             // Added FLAG_FULL and FLAG_SYSTEM flags.
3844             synchronized (mUsersLock) {
3845                 UserData userData = mUsers.get(UserHandle.USER_SYSTEM);
3846                 userData.info.flags |= UserInfo.FLAG_SYSTEM;
3847                 // We assume that isDefaultHeadlessSystemUserMode() does not change during the OTA
3848                 // from userVersion < 8 since it is documented that pre-R devices do not support its
3849                 // modification. Therefore, its current value should be the same as the pre-update
3850                 // version.
3851                 if (!isDefaultHeadlessSystemUserMode()) {
3852                     userData.info.flags |= UserInfo.FLAG_FULL;
3853                 }
3854                 userIdsToWrite.add(userData.info.id);
3855 
3856                 // Mark FULL all non-profile users except USER_SYSTEM.
3857                 // Start index at 1 since USER_SYSTEM is the smallest userId and we're skipping it.
3858                 for (int i = 1; i < mUsers.size(); i++) {
3859                     userData = mUsers.valueAt(i);
3860                     if ((userData.info.flags & UserInfo.FLAG_MANAGED_PROFILE) == 0) {
3861                         userData.info.flags |= UserInfo.FLAG_FULL;
3862                         userIdsToWrite.add(userData.info.id);
3863                     }
3864                 }
3865             }
3866             userVersion = 8;
3867         }
3868 
3869         if (userVersion < 9) {
3870             // Convert from UserInfo flags to UserTypes. Apply FLAG_PROFILE to FLAG_MANAGED_PROFILE.
3871             synchronized (mUsersLock) {
3872                 for (int i = 0; i < mUsers.size(); i++) {
3873                     UserData userData = mUsers.valueAt(i);
3874                     final int flags = userData.info.flags;
3875                     if ((flags & UserInfo.FLAG_SYSTEM) != 0) {
3876                         if ((flags & UserInfo.FLAG_FULL) != 0) {
3877                             userData.info.userType = UserManager.USER_TYPE_FULL_SYSTEM;
3878                         } else {
3879                             userData.info.userType = UserManager.USER_TYPE_SYSTEM_HEADLESS;
3880                         }
3881                     } else {
3882                         try {
3883                             userData.info.userType = UserInfo.getDefaultUserType(flags);
3884                         } catch (IllegalArgumentException e) {
3885                             // TODO(b/142482943): What should we do here? Delete user? Crashloop?
3886                             throw new IllegalStateException("Cannot upgrade user with flags "
3887                                     + Integer.toHexString(flags) + " because it doesn't correspond "
3888                                     + "to a valid user type.", e);
3889                         }
3890                     }
3891                     // OEMs are responsible for their own custom upgrade logic here.
3892 
3893                     final UserTypeDetails userTypeDetails = mUserTypes.get(userData.info.userType);
3894                     if (userTypeDetails == null) {
3895                         throw new IllegalStateException(
3896                                 "Cannot upgrade user with flags " + Integer.toHexString(flags)
3897                                         + " because " + userData.info.userType + " isn't defined"
3898                                         + " on this device!");
3899                     }
3900                     userData.info.flags |= userTypeDetails.getDefaultUserInfoFlags();
3901                     userIdsToWrite.add(userData.info.id);
3902                 }
3903             }
3904             userVersion = 9;
3905         }
3906 
3907         if (userVersion < 10) {
3908             // Add UserProperties.
3909             synchronized (mUsersLock) {
3910                 for (int i = 0; i < mUsers.size(); i++) {
3911                     final UserData userData = mUsers.valueAt(i);
3912                     final UserTypeDetails userTypeDetails = mUserTypes.get(userData.info.userType);
3913                     if (userTypeDetails == null) {
3914                         throw new IllegalStateException(
3915                                 "Cannot upgrade user because " + userData.info.userType
3916                                         + " isn't defined on this device!");
3917                     }
3918                     userData.userProperties = new UserProperties(
3919                             userTypeDetails.getDefaultUserPropertiesReference());
3920                     userIdsToWrite.add(userData.info.id);
3921                 }
3922             }
3923             userVersion = 10;
3924         }
3925 
3926         if (userVersion < 11) {
3927             // Add FLAG_MAIN
3928             if (isHeadlessSystemUserMode()) {
3929                 if (isMainUserPermanentAdmin()) {
3930                     final UserInfo earliestCreatedUser = getEarliestCreatedFullUser();
3931                     if (earliestCreatedUser != null) {
3932                         earliestCreatedUser.flags |= UserInfo.FLAG_MAIN;
3933                         userIdsToWrite.add(earliestCreatedUser.id);
3934                     }
3935                 }
3936             } else { // not isHeadlessSystemUserMode
3937                 synchronized (mUsersLock) {
3938                     final UserData userData = mUsers.get(UserHandle.USER_SYSTEM);
3939                     userData.info.flags |= UserInfo.FLAG_MAIN;
3940                     userIdsToWrite.add(userData.info.id);
3941                 }
3942             }
3943             userVersion = 11;
3944         }
3945 
3946         // Reminder: If you add another upgrade, make sure to increment USER_VERSION too.
3947 
3948         // Done with userVersion changes, moving on to deal with userTypeVersion upgrades
3949         // Upgrade from previous user type to a new user type
3950         final int newUserTypeVersion = UserTypeFactory.getUserTypeVersion();
3951         if (newUserTypeVersion > userTypeVersion) {
3952             synchronized (mUsersLock) {
3953                 upgradeUserTypesLU(UserTypeFactory.getUserTypeUpgrades(), mUserTypes,
3954                         userTypeVersion, userIdsToWrite);
3955             }
3956         }
3957 
3958         if (userVersion < USER_VERSION) {
3959             Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
3960                     + USER_VERSION);
3961         } else {
3962             if (userVersion > USER_VERSION) {
3963                 Slog.wtf(LOG_TAG, "Upgraded user version " + mUserVersion + " is higher the SDK's "
3964                         + "one of " + USER_VERSION + ". Someone forgot to update USER_VERSION?");
3965             }
3966 
3967             mUserVersion = userVersion;
3968             mUserTypeVersion = newUserTypeVersion;
3969 
3970             if (originalVersion < mUserVersion || originalUserTypeVersion < mUserTypeVersion) {
3971                 for (int userId : userIdsToWrite) {
3972                     UserData userData = getUserDataNoChecks(userId);
3973                     if (userData != null) {
3974                         writeUserLP(userData);
3975                     }
3976                 }
3977                 writeUserListLP();
3978             }
3979         }
3980     }
3981 
3982     @GuardedBy("mUsersLock")
upgradeUserTypesLU(@onNull List<UserTypeFactory.UserTypeUpgrade> upgradeOps, @NonNull ArrayMap<String, UserTypeDetails> userTypes, final int formerUserTypeVersion, @NonNull Set<Integer> userIdsToWrite)3983     private void upgradeUserTypesLU(@NonNull List<UserTypeFactory.UserTypeUpgrade> upgradeOps,
3984             @NonNull ArrayMap<String, UserTypeDetails> userTypes,
3985             final int formerUserTypeVersion,
3986             @NonNull Set<Integer> userIdsToWrite) {
3987         for (UserTypeFactory.UserTypeUpgrade userTypeUpgrade : upgradeOps) {
3988             if (DBG) {
3989                 Slog.i(LOG_TAG, "Upgrade: " + userTypeUpgrade.getFromType() + " to: "
3990                         + userTypeUpgrade.getToType() + " maxVersion: "
3991                         + userTypeUpgrade.getUpToVersion());
3992             }
3993 
3994             // upgrade user type if version up to getUpToVersion()
3995             if (formerUserTypeVersion <= userTypeUpgrade.getUpToVersion()) {
3996                 for (int i = 0; i < mUsers.size(); i++) {
3997                     UserData userData = mUsers.valueAt(i);
3998                     if (userTypeUpgrade.getFromType().equals(userData.info.userType)) {
3999                         final UserTypeDetails newUserType = userTypes.get(
4000                                 userTypeUpgrade.getToType());
4001 
4002                         if (newUserType == null) {
4003                             throw new IllegalStateException(
4004                                     "Upgrade destination user type not defined: "
4005                                             + userTypeUpgrade.getToType());
4006                         }
4007 
4008                         upgradeProfileToTypeLU(userData.info, newUserType);
4009                         userIdsToWrite.add(userData.info.id);
4010                     }
4011                 }
4012             }
4013         }
4014     }
4015 
4016     /**
4017      * Changes the user type of a profile to a new user type.
4018      * @param userInfo    The user to be updated.
4019      * @param newUserType The new user type.
4020      */
4021     @GuardedBy("mUsersLock")
4022     @VisibleForTesting
upgradeProfileToTypeLU(@onNull UserInfo userInfo, @NonNull UserTypeDetails newUserType)4023     void upgradeProfileToTypeLU(@NonNull UserInfo userInfo, @NonNull UserTypeDetails newUserType) {
4024         Slog.i(LOG_TAG, "Upgrading user " + userInfo.id
4025                 + " from " + userInfo.userType
4026                 + " to " + newUserType.getName());
4027 
4028         if (!userInfo.isProfile()) {
4029             throw new IllegalStateException(
4030                     "Can only upgrade profile types. " + userInfo.userType
4031                             + " is not a profile type.");
4032         }
4033 
4034         // Exceeded maximum profiles for parent user: log error, but allow upgrade
4035         if (!canAddMoreProfilesToUser(newUserType.getName(), userInfo.profileGroupId, false)) {
4036             Slog.w(LOG_TAG,
4037                     "Exceeded maximum profiles of type " + newUserType.getName() + " for user "
4038                             + userInfo.id + ". Maximum allowed= "
4039                             + newUserType.getMaxAllowedPerParent());
4040         }
4041 
4042         final UserTypeDetails oldUserType = mUserTypes.get(userInfo.userType);
4043         final int oldFlags;
4044         if (oldUserType != null) {
4045             oldFlags = oldUserType.getDefaultUserInfoFlags();
4046         } else {
4047             // if oldUserType is missing from config_user_types.xml -> can only assume FLAG_PROFILE
4048             oldFlags = UserInfo.FLAG_PROFILE;
4049         }
4050 
4051         //convert userData to newUserType
4052         userInfo.userType = newUserType.getName();
4053         // remove old default flags and add newUserType's default flags
4054         userInfo.flags = newUserType.getDefaultUserInfoFlags() | (userInfo.flags ^ oldFlags);
4055 
4056         // merge existing base restrictions with the new type's default restrictions
4057         synchronized (mRestrictionsLock) {
4058             if (!BundleUtils.isEmpty(newUserType.getDefaultRestrictions())) {
4059                 final Bundle newRestrictions = BundleUtils.clone(
4060                         mBaseUserRestrictions.getRestrictions(userInfo.id));
4061                 UserRestrictionsUtils.merge(newRestrictions,
4062                         newUserType.getDefaultRestrictions());
4063                 updateUserRestrictionsInternalLR(newRestrictions, userInfo.id);
4064                 if (DBG) {
4065                     Slog.i(LOG_TAG, "Updated user " + userInfo.id
4066                             + " restrictions to " + newRestrictions);
4067                 }
4068             }
4069         }
4070 
4071         // re-compute badge index
4072         userInfo.profileBadge = getFreeProfileBadgeLU(userInfo.profileGroupId, userInfo.userType);
4073     }
4074 
4075     /** Returns the oldest Full Admin user, or null is if there none. */
getEarliestCreatedFullUser()4076     private @Nullable UserInfo getEarliestCreatedFullUser() {
4077         final List<UserInfo> users = getUsersInternal(true, true, true);
4078         UserInfo earliestUser = null;
4079         long earliestCreationTime = Long.MAX_VALUE;
4080         for (int i = 0; i < users.size(); i++) {
4081             final UserInfo info = users.get(i);
4082             if (info.isFull() && info.isAdmin() && info.creationTime >= 0
4083                     && info.creationTime < earliestCreationTime) {
4084                 earliestCreationTime = info.creationTime;
4085                 earliestUser = info;
4086             }
4087         }
4088         return earliestUser;
4089     }
4090 
4091     @GuardedBy({"mPackagesLock"})
fallbackToSingleUserLP()4092     private void fallbackToSingleUserLP() {
4093         // Create the system user
4094         final String systemUserType = isDefaultHeadlessSystemUserMode()
4095                 ? UserManager.USER_TYPE_SYSTEM_HEADLESS
4096                 : UserManager.USER_TYPE_FULL_SYSTEM;
4097         final int flags = mUserTypes.get(systemUserType).getDefaultUserInfoFlags()
4098                 | UserInfo.FLAG_INITIALIZED;
4099         final UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
4100                 /* name= */ null, /* iconPath= */ null, flags, systemUserType);
4101         final UserData userData = putUserInfo(system);
4102         userData.userProperties = new UserProperties(
4103                 mUserTypes.get(userData.info.userType).getDefaultUserPropertiesReference());
4104         mNextSerialNumber = MIN_USER_ID;
4105         mUserVersion = USER_VERSION;
4106         mUserTypeVersion = UserTypeFactory.getUserTypeVersion();
4107 
4108         final Bundle restrictions = new Bundle();
4109         try {
4110             final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
4111                     com.android.internal.R.array.config_defaultFirstUserRestrictions);
4112             for (String userRestriction : defaultFirstUserRestrictions) {
4113                 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
4114                     restrictions.putBoolean(userRestriction, true);
4115                 }
4116             }
4117         } catch (Resources.NotFoundException e) {
4118             Slog.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
4119         }
4120 
4121         if (!restrictions.isEmpty()) {
4122             synchronized (mRestrictionsLock) {
4123                 mBaseUserRestrictions.updateRestrictions(UserHandle.USER_SYSTEM,
4124                         restrictions);
4125             }
4126         }
4127 
4128         initDefaultGuestRestrictions();
4129 
4130         writeUserLP(userData);
4131         writeUserListLP();
4132     }
4133 
getOwnerName()4134     private String getOwnerName() {
4135         return mOwnerName.get();
4136     }
4137 
getGuestName()4138     private String getGuestName() {
4139         return mContext.getString(com.android.internal.R.string.guest_name);
4140     }
4141 
invalidateOwnerNameIfNecessary(@onNull Resources res, boolean forceUpdate)4142     private void invalidateOwnerNameIfNecessary(@NonNull Resources res, boolean forceUpdate) {
4143         final int configChanges = mLastConfiguration.updateFrom(res.getConfiguration());
4144         if (forceUpdate || (configChanges & mOwnerNameTypedValue.changingConfigurations) != 0) {
4145             res.getValue(com.android.internal.R.string.owner_name, mOwnerNameTypedValue, true);
4146             final CharSequence ownerName = mOwnerNameTypedValue.coerceToString();
4147             mOwnerName.set(ownerName != null ? ownerName.toString() : null);
4148         }
4149     }
4150 
scheduleWriteUserList()4151     private void scheduleWriteUserList() {
4152         if (DBG) {
4153             debug("scheduleWriteUserList");
4154         }
4155         // No need to wrap it within a lock -- worst case, we'll just post the same message
4156         // twice.
4157         if (!mHandler.hasMessages(WRITE_USER_LIST_MSG)) {
4158             Message msg = mHandler.obtainMessage(WRITE_USER_LIST_MSG);
4159             mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
4160         }
4161     }
4162 
scheduleWriteUser(@serIdInt int userId)4163     private void scheduleWriteUser(@UserIdInt int userId) {
4164         if (DBG) {
4165             debug("scheduleWriteUser");
4166         }
4167         // No need to wrap it within a lock -- worst case, we'll just post the same message
4168         // twice.
4169         if (!mHandler.hasMessages(WRITE_USER_MSG, userId)) {
4170             Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userId);
4171             mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
4172         }
4173     }
4174 
getUserFile(int userId)4175     private ResilientAtomicFile getUserFile(int userId) {
4176         File file = new File(mUsersDir, userId + XML_SUFFIX);
4177         File tempBackup = new File(mUsersDir, userId + XML_SUFFIX + ".backup");
4178         File reserveCopy = new File(mUsersDir, userId + XML_SUFFIX + ".reservecopy");
4179         int fileMode = FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IXOTH;
4180         return new ResilientAtomicFile(file, tempBackup, reserveCopy, fileMode,
4181                 "user info", (priority, msg) -> {
4182             Slog.e(LOG_TAG, msg);
4183             // Something went wrong, schedule full rewrite.
4184             UserData userData = getUserDataNoChecks(userId);
4185             if (userData != null) {
4186                 scheduleWriteUser(userId);
4187             }
4188         });
4189     }
4190 
4191     @GuardedBy({"mPackagesLock"})
4192     private void writeUserLP(UserData userData) {
4193         if (DBG) {
4194             debug("writeUserLP " + userData);
4195         }
4196         try (ResilientAtomicFile userFile = getUserFile(userData.info.id)) {
4197             FileOutputStream fos = null;
4198             try {
4199                 fos = userFile.startWrite();
4200                 writeUserLP(userData, fos);
4201                 userFile.finishWrite(fos);
4202             } catch (Exception ioe) {
4203                 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
4204                 userFile.failWrite(fos);
4205             }
4206         }
4207     }
4208 
4209     /*
4210      * Writes the user file in this format:
4211      *
4212      * <user flags="20039023" id="0">
4213      *   <name>Primary</name>
4214      * </user>
4215      */
4216     @GuardedBy({"mPackagesLock"})
4217     @VisibleForTesting
4218     void writeUserLP(UserData userData, OutputStream os)
4219             throws IOException, XmlPullParserException {
4220         final TypedXmlSerializer serializer = Xml.resolveSerializer(os);
4221         serializer.startDocument(null, true);
4222         serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
4223 
4224         final UserInfo userInfo = userData.info;
4225         serializer.startTag(null, TAG_USER);
4226         serializer.attributeInt(null, ATTR_ID, userInfo.id);
4227         serializer.attributeInt(null, ATTR_SERIAL_NO, userInfo.serialNumber);
4228         serializer.attributeInt(null, ATTR_FLAGS, userInfo.flags);
4229         serializer.attribute(null, ATTR_TYPE, userInfo.userType);
4230         serializer.attributeLong(null, ATTR_CREATION_TIME, userInfo.creationTime);
4231         serializer.attributeLong(null, ATTR_LAST_LOGGED_IN_TIME, userInfo.lastLoggedInTime);
4232         if (userInfo.lastLoggedInFingerprint != null) {
4233             serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
4234                     userInfo.lastLoggedInFingerprint);
4235         }
4236         serializer.attributeLong(
4237                 null, ATTR_LAST_ENTERED_FOREGROUND_TIME, userData.mLastEnteredForegroundTimeMillis);
4238         if (userInfo.iconPath != null) {
4239             serializer.attribute(null,  ATTR_ICON_PATH, userInfo.iconPath);
4240         }
4241         if (userInfo.partial) {
4242             serializer.attributeBoolean(null, ATTR_PARTIAL, true);
4243         }
4244         if (userInfo.preCreated) {
4245             serializer.attributeBoolean(null, ATTR_PRE_CREATED, true);
4246         }
4247         if (userInfo.convertedFromPreCreated) {
4248             serializer.attributeBoolean(null, ATTR_CONVERTED_FROM_PRE_CREATED, true);
4249         }
4250         if (userInfo.guestToRemove) {
4251             serializer.attributeBoolean(null, ATTR_GUEST_TO_REMOVE, true);
4252         }
4253         if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
4254             serializer.attributeInt(null, ATTR_PROFILE_GROUP_ID, userInfo.profileGroupId);
4255         }
4256         serializer.attributeInt(null, ATTR_PROFILE_BADGE, userInfo.profileBadge);
4257         if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
4258             serializer.attributeInt(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
4259                     userInfo.restrictedProfileParentId);
4260         }
4261         // Write seed data
4262         if (userData.persistSeedData) {
4263             if (userData.seedAccountName != null) {
4264                 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME,
4265                         truncateString(userData.seedAccountName));
4266             }
4267             if (userData.seedAccountType != null) {
4268                 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE,
4269                         truncateString(userData.seedAccountType));
4270             }
4271         }
4272         if (userInfo.name != null) {
4273             serializer.startTag(null, TAG_NAME);
4274             serializer.text(truncateString(userInfo.name));
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) {
4324         if (original == null || original.length() <= MAX_USER_STRING_LENGTH) {
4325             return original;
4326         }
4327         return original.substring(0, MAX_USER_STRING_LENGTH);
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);
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                 userData.seedAccountType = truncateString(accountType);
6384                 userData.seedAccountOptions = accountOptions;
6385                 userData.persistSeedData = persist;
6386             }
6387             if (persist) {
6388                 writeUserLP(userData);
6389             }
6390         }
6391     }
6392 
6393     @Override
6394     public String getSeedAccountName(@UserIdInt int userId) throws RemoteException {
6395         checkManageUsersPermission("Cannot get seed account information");
6396         synchronized (mUsersLock) {
6397             final UserData userData = getUserDataLU(userId);
6398             return userData == null ? null : userData.seedAccountName;
6399         }
6400     }
6401 
6402     @Override
6403     public String getSeedAccountType(@UserIdInt int userId) throws RemoteException {
6404         checkManageUsersPermission("Cannot get seed account information");
6405         synchronized (mUsersLock) {
6406             final UserData userData = getUserDataLU(userId);
6407             return userData == null ? null : userData.seedAccountType;
6408         }
6409     }
6410 
6411     @Override
6412     public PersistableBundle getSeedAccountOptions(@UserIdInt int userId) throws RemoteException {
6413         checkManageUsersPermission("Cannot get seed account information");
6414         synchronized (mUsersLock) {
6415             final UserData userData = getUserDataLU(userId);
6416             return userData == null ? null : userData.seedAccountOptions;
6417         }
6418     }
6419 
6420     @Override
6421     public void clearSeedAccountData(@UserIdInt int userId) throws RemoteException {
6422         checkManageUsersPermission("Cannot clear seed account information");
6423         synchronized (mPackagesLock) {
6424             UserData userData;
6425             synchronized (mUsersLock) {
6426                 userData = getUserDataLU(userId);
6427                 if (userData == null) return;
6428                 userData.clearSeedAccountData();
6429             }
6430             writeUserLP(userData);
6431         }
6432     }
6433 
6434     @Override
6435     public boolean someUserHasSeedAccount(String accountName, String accountType) {
6436         checkManageUsersPermission("check seed account information");
6437         return someUserHasSeedAccountNoChecks(accountName, accountType);
6438     }
6439 
6440     private boolean someUserHasSeedAccountNoChecks(String accountName, String accountType) {
6441         synchronized (mUsersLock) {
6442             final int userSize = mUsers.size();
6443             for (int i = 0; i < userSize; i++) {
6444                 final UserData data = mUsers.valueAt(i);
6445                 if (data.info.isInitialized()) continue;
6446                 if (mRemovingUserIds.get(data.info.id)) continue;
6447                 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
6448                     continue;
6449                 }
6450                 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
6451                     continue;
6452                 }
6453                 return true;
6454             }
6455         }
6456         return false;
6457     }
6458 
6459     @Override
6460     public boolean someUserHasAccount(String accountName, String accountType) {
6461         checkCreateUsersPermission("check seed account information");
6462         return someUserHasAccountNoChecks(accountName, accountType);
6463     }
6464 
6465     private boolean someUserHasAccountNoChecks(
6466             String accountName, String accountType) {
6467         if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
6468             return false;
6469         }
6470 
6471         final Account account = new Account(accountName, accountType);
6472 
6473         return Binder.withCleanCallingIdentity(() ->
6474                 AccountManager.get(mContext).someUserHasAccount(account)
6475                         || someUserHasSeedAccountNoChecks(accountName, accountType));
6476     }
6477 
6478     private void setLastEnteredForegroundTimeToNow(@NonNull UserData userData) {
6479         userData.mLastEnteredForegroundTimeMillis = System.currentTimeMillis();
6480         scheduleWriteUser(userData.info.id);
6481     }
6482 
6483     @Override
6484     public void onShellCommand(FileDescriptor in, FileDescriptor out,
6485             FileDescriptor err, String[] args, ShellCallback callback,
6486             ResultReceiver resultReceiver) {
6487         (new UserManagerServiceShellCommand(this, mSystemPackageInstaller,
6488                 mLockPatternUtils, mContext))
6489                 .exec(this, in, out, err, args, callback, resultReceiver);
6490     }
6491 
6492     @Override
6493     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6494         if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
6495 
6496         final long now = System.currentTimeMillis();
6497         final long nowRealtime = SystemClock.elapsedRealtime();
6498         final StringBuilder sb = new StringBuilder();
6499 
6500         if (args != null && args.length > 0) {
6501             switch (args[0]) {
6502                 case "--user":
6503                     dumpUser(pw, UserHandle.parseUserArg(args[1]), sb, now, nowRealtime);
6504                     return;
6505                 case "--visibility-mediator":
6506                     mUserVisibilityMediator.dump(pw, args);
6507                     return;
6508             }
6509         }
6510 
6511         final int currentUserId = getCurrentUserId();
6512         pw.print("Current user: ");
6513         if (currentUserId != UserHandle.USER_NULL) {
6514             pw.println(currentUserId);
6515         } else {
6516             pw.println("N/A");
6517         }
6518 
6519         pw.println();
6520         synchronized (mPackagesLock) {
6521             synchronized (mUsersLock) {
6522                 pw.println("Users:");
6523                 for (int i = 0; i < mUsers.size(); i++) {
6524                     UserData userData = mUsers.valueAt(i);
6525                     if (userData == null) {
6526                         continue;
6527                     }
6528                     dumpUserLocked(pw, userData, sb, now, nowRealtime);
6529                 }
6530             }
6531 
6532             pw.println();
6533             pw.println("Device properties:");
6534             pw.println("  Device policy global restrictions:");
6535             synchronized (mRestrictionsLock) {
6536                 UserRestrictionsUtils.dumpRestrictions(
6537                         pw, "    ",
6538                         mDevicePolicyUserRestrictions.getRestrictions(UserHandle.USER_ALL));
6539             }
6540             pw.println("  Guest restrictions:");
6541             synchronized (mGuestRestrictions) {
6542                 UserRestrictionsUtils.dumpRestrictions(pw, "    ", mGuestRestrictions);
6543             }
6544             synchronized (mUsersLock) {
6545                 pw.println();
6546                 pw.println("  Device managed: " + mIsDeviceManaged);
6547                 if (mRemovingUserIds.size() > 0) {
6548                     pw.println();
6549                     pw.println("  Recently removed userIds: " + mRecentlyRemovedIds);
6550                 }
6551             }
6552             synchronized (mUserStates) {
6553                 pw.print("  Started users state: [");
6554                 final int size = mUserStates.states.size();
6555                 for (int i = 0; i < size; i++) {
6556                     final int userId = mUserStates.states.keyAt(i);
6557                     final int state = mUserStates.states.valueAt(i);
6558                     pw.print(userId);
6559                     pw.print('=');
6560                     pw.print(UserState.stateToString(state));
6561                     if (i != size - 1) pw.print(", ");
6562                 }
6563                 pw.println(']');
6564             }
6565             synchronized (mUsersLock) {
6566                 pw.print("  Cached user IDs: ");
6567                 pw.println(Arrays.toString(mUserIds));
6568                 pw.print("  Cached user IDs (including pre-created): ");
6569                 pw.println(Arrays.toString(mUserIdsIncludingPreCreated));
6570             }
6571         } // synchronized (mPackagesLock)
6572 
6573         pw.println();
6574         mUserVisibilityMediator.dump(pw, args);
6575         pw.println();
6576 
6577         // Dump some capabilities
6578         pw.println();
6579         pw.print("  Max users: " + UserManager.getMaxSupportedUsers());
6580         pw.println(" (limit reached: " + isUserLimitReached() + ")");
6581         pw.println("  Supports switchable users: " + UserManager.supportsMultipleUsers());
6582         pw.println("  All guests ephemeral: " + Resources.getSystem().getBoolean(
6583                 com.android.internal.R.bool.config_guestUserEphemeral));
6584         pw.println("  Force ephemeral users: " + mForceEphemeralUsers);
6585         final boolean isHeadlessSystemUserMode = isHeadlessSystemUserMode();
6586         pw.println("  Is headless-system mode: " + isHeadlessSystemUserMode);
6587         if (isHeadlessSystemUserMode != RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER) {
6588             pw.println("  (differs from the current default build value)");
6589         }
6590         if (!TextUtils.isEmpty(SystemProperties.get(SYSTEM_USER_MODE_EMULATION_PROPERTY))) {
6591             pw.println("  (emulated by 'cmd user set-system-user-mode-emulation')");
6592             if (mUpdatingSystemUserMode) {
6593                 pw.println("  (and being updated after boot)");
6594             }
6595         }
6596         pw.println("  User version: " + mUserVersion);
6597         pw.println("  Owner name: " + getOwnerName());
6598         if (DBG_ALLOCATION) {
6599             pw.println("  System user allocations: " + mUser0Allocations.get());
6600         }
6601         synchronized (mUsersLock) {
6602             pw.println("  Boot user: " + mBootUser);
6603         }
6604 
6605         pw.println();
6606         pw.println("Number of listeners for");
6607         synchronized (mUserRestrictionsListeners) {
6608             pw.println("  restrictions: " + mUserRestrictionsListeners.size());
6609         }
6610         synchronized (mUserLifecycleListeners) {
6611             pw.println("  user lifecycle events: " + mUserLifecycleListeners.size());
6612         }
6613 
6614         // Dump UserTypes
6615         pw.println();
6616         pw.println("User types version: " + mUserTypeVersion);
6617         pw.println("User types (" + mUserTypes.size() + " types):");
6618         for (int i = 0; i < mUserTypes.size(); i++) {
6619             pw.println("    " + mUserTypes.keyAt(i) + ": ");
6620             mUserTypes.valueAt(i).dump(pw, "        ");
6621         }
6622 
6623         // TODO: create IndentingPrintWriter at the beginning of dump() and use the proper
6624         // indentation methods instead of explicit printing "  "
6625         try (IndentingPrintWriter ipw = new IndentingPrintWriter(pw)) {
6626 
6627             // Dump SystemPackageInstaller info
6628             ipw.println();
6629             mSystemPackageInstaller.dump(ipw);
6630 
6631             // NOTE: pw's not available after this point as it's auto-closed by ipw, so new dump
6632             // statements should use ipw below
6633         }
6634     }
6635 
6636     private void dumpUser(PrintWriter pw, @UserIdInt int userId, StringBuilder sb, long now,
6637             long nowRealtime) {
6638         if (userId == UserHandle.USER_CURRENT) {
6639             final int currentUserId = getCurrentUserId();
6640             pw.print("Current user: ");
6641             if (currentUserId == UserHandle.USER_NULL) {
6642                 pw.println("Cannot determine current user");
6643                 return;
6644             }
6645             userId = currentUserId;
6646         }
6647 
6648         synchronized (mUsersLock) {
6649             final UserData userData = mUsers.get(userId);
6650             if (userData == null) {
6651                 pw.println("User " + userId + " not found");
6652                 return;
6653             }
6654             dumpUserLocked(pw, userData, sb, now, nowRealtime);
6655         }
6656     }
6657 
6658     @GuardedBy("mUsersLock")
6659     private void dumpUserLocked(PrintWriter pw, UserData userData, StringBuilder tempStringBuilder,
6660             long now, long nowRealtime) {
6661         final UserInfo userInfo = userData.info;
6662         final int userId = userInfo.id;
6663         pw.print("  "); pw.print(userInfo);
6664         pw.print(" serialNo="); pw.print(userInfo.serialNumber);
6665         pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
6666         if (userInfo.profileGroupId != userInfo.id
6667                 &&  userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
6668             pw.print(" parentId="); pw.print(userInfo.profileGroupId);
6669         }
6670 
6671         if (mRemovingUserIds.get(userId)) {
6672             pw.print(" <removing> ");
6673         }
6674         if (userInfo.partial) {
6675             pw.print(" <partial>");
6676         }
6677         if (userInfo.preCreated) {
6678             pw.print(" <pre-created>");
6679         }
6680         if (userInfo.convertedFromPreCreated) {
6681             pw.print(" <converted>");
6682         }
6683         pw.println();
6684         pw.print("    Type: "); pw.println(userInfo.userType);
6685         pw.print("    Flags: "); pw.print(userInfo.flags); pw.print(" (");
6686         pw.print(UserInfo.flagsToString(userInfo.flags)); pw.println(")");
6687         pw.print("    State: ");
6688         final int state;
6689         synchronized (mUserStates) {
6690             state = mUserStates.get(userId, -1);
6691         }
6692         pw.println(UserState.stateToString(state));
6693         pw.print("    Created: ");
6694         dumpTimeAgo(pw, tempStringBuilder, now, userInfo.creationTime);
6695 
6696         pw.print("    Last logged in: ");
6697         dumpTimeAgo(pw, tempStringBuilder, now, userInfo.lastLoggedInTime);
6698 
6699         pw.print("    Last logged in fingerprint: ");
6700         pw.println(userInfo.lastLoggedInFingerprint);
6701 
6702         pw.print("    Start time: ");
6703         dumpTimeAgo(pw, tempStringBuilder, nowRealtime, userData.startRealtime);
6704 
6705         pw.print("    Unlock time: ");
6706         dumpTimeAgo(pw, tempStringBuilder, nowRealtime, userData.unlockRealtime);
6707 
6708         pw.print("    Last entered foreground: ");
6709         dumpTimeAgo(pw, tempStringBuilder, now, userData.mLastEnteredForegroundTimeMillis);
6710 
6711         pw.print("    Has profile owner: ");
6712         pw.println(mIsUserManaged.get(userId));
6713         pw.println("    Restrictions:");
6714         synchronized (mRestrictionsLock) {
6715             UserRestrictionsUtils.dumpRestrictions(
6716                     pw, "      ", mBaseUserRestrictions.getRestrictions(userInfo.id));
6717             pw.println("    Device policy restrictions:");
6718             UserRestrictionsUtils.dumpRestrictions(
6719                     pw, "      ",
6720                     mDevicePolicyUserRestrictions.getRestrictions(userInfo.id));
6721             pw.println("    Effective restrictions:");
6722             UserRestrictionsUtils.dumpRestrictions(
6723                     pw, "      ",
6724                     mCachedEffectiveUserRestrictions.getRestrictions(userInfo.id));
6725         }
6726 
6727         if (userData.account != null) {
6728             pw.print("    Account name: " + userData.account);
6729             pw.println();
6730         }
6731 
6732         if (userData.seedAccountName != null) {
6733             pw.print("    Seed account name: " + userData.seedAccountName);
6734             pw.println();
6735             if (userData.seedAccountType != null) {
6736                 pw.print("         account type: " + userData.seedAccountType);
6737                 pw.println();
6738             }
6739             if (userData.seedAccountOptions != null) {
6740                 pw.print("         account options exist");
6741                 pw.println();
6742             }
6743         }
6744 
6745         if (userData.userProperties != null) {
6746             userData.userProperties.println(pw, "    ");
6747         }
6748 
6749         pw.println("    Ignore errors preparing storage: "
6750                 + userData.getIgnorePrepareStorageErrors());
6751     }
6752 
6753     private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
6754         if (time == 0) {
6755             pw.println("<unknown>");
6756         } else {
6757             sb.setLength(0);
6758             TimeUtils.formatDuration(nowTime - time, sb);
6759             sb.append(" ago");
6760             pw.println(sb);
6761         }
6762     }
6763 
6764     final class MainHandler extends Handler {
6765 
6766         @Override
6767         public void handleMessage(Message msg) {
6768             switch (msg.what) {
6769                 case WRITE_USER_LIST_MSG: {
6770                     removeMessages(WRITE_USER_LIST_MSG);
6771                     synchronized (mPackagesLock) {
6772                         writeUserListLP();
6773                     }
6774                     break;
6775                 }
6776                 case WRITE_USER_MSG:
6777                     removeMessages(WRITE_USER_MSG, msg.obj);
6778                     synchronized (mPackagesLock) {
6779                         int userId = (int) msg.obj;
6780                         UserData userData = getUserDataNoChecks(userId);
6781                         if (userData != null) {
6782                             writeUserLP(userData);
6783                         } else {
6784                             Slog.i(LOG_TAG, "handle(WRITE_USER_MSG): no data for user " + userId
6785                                     + ", it was probably removed before handler could handle it");
6786                         }
6787                     }
6788                     break;
6789             }
6790         }
6791     }
6792 
6793     /**
6794      * @param userId
6795      * @return whether the user has been initialized yet
6796      */
6797     boolean isUserInitialized(@UserIdInt int userId) {
6798         return mLocalService.isUserInitialized(userId);
6799     }
6800 
6801     private class LocalService extends UserManagerInternal {
6802         @Override
6803         public void setDevicePolicyUserRestrictions(@UserIdInt int originatingUserId,
6804                 @NonNull Bundle global, @NonNull RestrictionsSet local,
6805                 boolean isDeviceOwner) {
6806             UserManagerService.this.setDevicePolicyUserRestrictionsInner(originatingUserId,
6807                     global, local, isDeviceOwner);
6808         }
6809 
6810         @Override
6811         public void setUserRestriction(int userId, @NonNull String key, boolean value) {
6812             UserManagerService.this.setUserRestrictionInner(userId, key, value);
6813         }
6814 
6815         @Override
6816         public boolean getUserRestriction(@UserIdInt int userId, String key) {
6817             return getUserRestrictions(userId).getBoolean(key);
6818         }
6819 
6820         @Override
6821         public void addUserRestrictionsListener(UserRestrictionsListener listener) {
6822             synchronized (mUserRestrictionsListeners) {
6823                 mUserRestrictionsListeners.add(listener);
6824             }
6825         }
6826 
6827         @Override
6828         public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
6829             synchronized (mUserRestrictionsListeners) {
6830                 mUserRestrictionsListeners.remove(listener);
6831             }
6832         }
6833 
6834         @Override
6835         public void addUserLifecycleListener(UserLifecycleListener listener) {
6836             synchronized (mUserLifecycleListeners) {
6837                 mUserLifecycleListeners.add(listener);
6838             }
6839         }
6840 
6841         @Override
6842         public void removeUserLifecycleListener(UserLifecycleListener listener) {
6843             synchronized (mUserLifecycleListeners) {
6844                 mUserLifecycleListeners.remove(listener);
6845             }
6846         }
6847 
6848         // TODO(b/258213147): Remove
6849         @Override
6850         public void setDeviceManaged(boolean isManaged) {
6851             synchronized (mUsersLock) {
6852                 mIsDeviceManaged = isManaged;
6853             }
6854         }
6855 
6856         // TODO(b/258213147): Remove
6857         @Override
6858         public boolean isDeviceManaged() {
6859             synchronized (mUsersLock) {
6860                 return mIsDeviceManaged;
6861             }
6862         }
6863 
6864         // TODO(b/258213147): Remove
6865         @Override
6866         public void setUserManaged(@UserIdInt int userId, boolean isManaged) {
6867             synchronized (mUsersLock) {
6868                 mIsUserManaged.put(userId, isManaged);
6869             }
6870         }
6871 
6872         // TODO(b/258213147): Remove
6873         @Override
6874         public boolean isUserManaged(@UserIdInt int userId) {
6875             synchronized (mUsersLock) {
6876                 return mIsUserManaged.get(userId);
6877             }
6878         }
6879 
6880         @Override
6881         public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
6882             final long ident = Binder.clearCallingIdentity();
6883             try {
6884                 synchronized (mPackagesLock) {
6885                     UserData userData = getUserDataNoChecks(userId);
6886                     if (userData == null || userData.info.partial) {
6887                         Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
6888                         return;
6889                     }
6890                     writeBitmapLP(userData.info, bitmap);
6891                     writeUserLP(userData);
6892                 }
6893                 sendUserInfoChangedBroadcast(userId);
6894             } finally {
6895                 Binder.restoreCallingIdentity(ident);
6896             }
6897         }
6898 
6899         @Override
6900         public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
6901             synchronized (mUsersLock) {
6902                 mForceEphemeralUsers = forceEphemeralUsers;
6903             }
6904         }
6905 
6906         @Override
6907         public void removeAllUsers() {
6908             if (UserHandle.USER_SYSTEM == getCurrentUserId()) {
6909                 // Remove the non-system users straight away.
6910                 removeAllUsersExceptSystemAndPermanentAdminMain();
6911             } else {
6912                 // Switch to the system user first and then remove the other users.
6913                 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
6914                     @Override
6915                     public void onReceive(Context context, Intent intent) {
6916                         int userId =
6917                                 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
6918                         if (userId != UserHandle.USER_SYSTEM) {
6919                             return;
6920                         }
6921                         mContext.unregisterReceiver(this);
6922                         removeAllUsersExceptSystemAndPermanentAdminMain();
6923                     }
6924                 };
6925                 IntentFilter userSwitchedFilter = new IntentFilter();
6926                 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
6927                 mContext.registerReceiver(
6928                         userSwitchedReceiver, userSwitchedFilter, null, mHandler);
6929 
6930                 // Switch to the system user.
6931                 ActivityManager am =
6932                         (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
6933                 am.switchUser(UserHandle.USER_SYSTEM);
6934             }
6935         }
6936 
6937         @Override
6938         public void onEphemeralUserStop(@UserIdInt int userId) {
6939             synchronized (mUsersLock) {
6940                UserInfo userInfo = getUserInfoLU(userId);
6941                if (userInfo != null && userInfo.isEphemeral()) {
6942                     // Do not allow switching back to the ephemeral user again as the user is going
6943                     // to be deleted.
6944                     userInfo.flags |= UserInfo.FLAG_DISABLED;
6945                     if (userInfo.isGuest()) {
6946                         // Indicate that the guest will be deleted after it stops.
6947                         userInfo.guestToRemove = true;
6948                     }
6949                }
6950             }
6951         }
6952 
6953         @Override
6954         public @NonNull UserInfo createUserEvenWhenDisallowed(
6955                 @Nullable String name, @NonNull String userType, @UserInfoFlag int flags,
6956                 @Nullable String[] disallowedPackages, @Nullable Object token)
6957                 throws UserManager.CheckedUserOperationException {
6958 
6959             return createUserInternalUnchecked(name, userType, flags,
6960                     UserHandle.USER_NULL, /* preCreated= */ false, disallowedPackages, token);
6961         }
6962 
6963         @Override
6964         public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
6965             return removeUserWithProfilesUnchecked(userId);
6966         }
6967 
6968         @Override
6969         public boolean isUserRunning(@UserIdInt int userId) {
6970             int state;
6971             synchronized (mUserStates) {
6972                 state =  mUserStates.get(userId, UserState.STATE_NONE);
6973             }
6974 
6975             return state != UserState.STATE_NONE
6976                     && state != UserState.STATE_STOPPING
6977                     && state != UserState.STATE_SHUTDOWN;
6978         }
6979 
6980         @Override
6981         public void setUserState(@UserIdInt int userId, int userState) {
6982             synchronized (mUserStates) {
6983                 mUserStates.put(userId, userState);
6984             }
6985         }
6986 
6987         @Override
6988         public void removeUserState(@UserIdInt int userId) {
6989             synchronized (mUserStates) {
6990                 mUserStates.delete(userId);
6991             }
6992         }
6993 
6994         @Override
6995         public int[] getUserIds() {
6996             return UserManagerService.this.getUserIds();
6997         }
6998 
6999         @Override
7000         public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
7001             return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */ true);
7002         }
7003 
7004         @Override
7005         public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
7006                 boolean excludePreCreated) {
7007             return UserManagerService.this.getUsersInternal(excludePartial, excludeDying,
7008                     excludePreCreated);
7009         }
7010 
7011         @Override
7012         public @NonNull int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) {
7013             synchronized (mUsersLock) {
7014                 return getProfileIdsLU(userId, null /* userType */, enabledOnly).toArray();
7015             }
7016         }
7017 
7018         @Override
7019         public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
7020             int state;
7021             synchronized (mUserStates) {
7022                 state = mUserStates.get(userId, -1);
7023             }
7024             // Special case, in the stopping/shutdown state user key can still be unlocked
7025             if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
7026                 return StorageManager.isUserKeyUnlocked(userId);
7027             }
7028             return (state == UserState.STATE_RUNNING_UNLOCKING)
7029                     || (state == UserState.STATE_RUNNING_UNLOCKED);
7030         }
7031 
7032         /**
7033          * The return values of this method are cached in clients.  If the
7034          * logic in this function changes then the cache invalidation code
7035          * may need to be revisited.
7036          */
7037         @Override
7038         public boolean isUserUnlocked(@UserIdInt int userId) {
7039             int state;
7040             synchronized (mUserStates) {
7041                 state = mUserStates.get(userId, -1);
7042             }
7043             // Special case, in the stopping/shutdown state user key can still be unlocked
7044             if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
7045                 return StorageManager.isUserKeyUnlocked(userId);
7046             }
7047             return state == UserState.STATE_RUNNING_UNLOCKED;
7048         }
7049 
7050         @Override
7051         public boolean isUserInitialized(@UserIdInt int userId) {
7052             return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
7053         }
7054 
7055         @Override
7056         public boolean exists(@UserIdInt int userId) {
7057             return getUserInfoNoChecks(userId) != null;
7058         }
7059 
7060         @Override
7061         public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
7062                 boolean throwSecurityException) {
7063             if (targetUserId == callingUserId) {
7064                 return true;
7065             }
7066             synchronized (mUsersLock) {
7067                 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
7068                 if (callingUserInfo == null || callingUserInfo.isProfile()) {
7069                     if (throwSecurityException) {
7070                         throw new SecurityException(
7071                                 debugMsg + " for another profile "
7072                                         + targetUserId + " from " + callingUserId);
7073                     }
7074                     Slog.w(LOG_TAG, debugMsg + " for another profile "
7075                             + targetUserId + " from " + callingUserId);
7076                     return false;
7077                 }
7078 
7079                 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
7080                 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
7081                     // Do not throw any exception here as this could happen due to race conditions
7082                     // between the system updating its state and the client getting notified.
7083                     if (throwSecurityException) {
7084                         Slog.w(LOG_TAG, debugMsg + " for disabled profile "
7085                                 + targetUserId + " from " + callingUserId);
7086                     }
7087                     return false;
7088                 }
7089 
7090                 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
7091                         targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
7092                     if (throwSecurityException) {
7093                         throw new SecurityException(
7094                                 debugMsg + " for unrelated profile " + targetUserId);
7095                     }
7096                     return false;
7097                 }
7098             }
7099             return true;
7100         }
7101 
7102         @Override
7103         public int getProfileParentId(@UserIdInt int userId) {
7104             return getProfileParentIdUnchecked(userId);
7105         }
7106 
7107         @Override
7108         public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
7109                 String value, int callingUid) {
7110             return UserManagerService.this.isSettingRestrictedForUser(setting, userId,
7111                     value, callingUid);
7112         }
7113 
7114         @Override
7115         public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
7116             if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
7117                 return false;
7118             }
7119             Bundle restrictions = getEffectiveUserRestrictions(userId);
7120             return restrictions != null && restrictions.getBoolean(restrictionKey);
7121         }
7122 
7123         @Override
7124         public @Nullable UserInfo getUserInfo(@UserIdInt int userId) {
7125             UserData userData;
7126             synchronized (mUsersLock) {
7127                 userData = mUsers.get(userId);
7128             }
7129             return userData == null ? null : userData.info;
7130         }
7131 
7132         @Override
7133         public @NonNull UserInfo[] getUserInfos() {
7134             synchronized (mUsersLock) {
7135                 int userSize = mUsers.size();
7136                 UserInfo[] allInfos = new UserInfo[userSize];
7137                 for (int i = 0; i < userSize; i++) {
7138                     allInfos[i] = mUsers.valueAt(i).info;
7139                 }
7140                 return allInfos;
7141             }
7142         }
7143 
7144         @Override
7145         public void setDefaultCrossProfileIntentFilters(
7146                 @UserIdInt int parentUserId, @UserIdInt int profileUserId) {
7147             final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(profileUserId);
7148             final Bundle restrictions = getEffectiveUserRestrictions(profileUserId);
7149             UserManagerService.this.setDefaultCrossProfileIntentFilters(
7150                     profileUserId, userTypeDetails, restrictions, parentUserId);
7151         }
7152 
7153         @Override
7154         public boolean shouldIgnorePrepareStorageErrors(int userId) {
7155             synchronized (mUsersLock) {
7156                 UserData userData = mUsers.get(userId);
7157                 return userData != null && userData.getIgnorePrepareStorageErrors();
7158             }
7159         }
7160 
7161         @Override
7162         public @Nullable UserProperties getUserProperties(@UserIdInt int userId) {
7163             final UserProperties props = getUserPropertiesInternal(userId);
7164             if (props == null) {
7165                 Slog.w(LOG_TAG, "A null UserProperties was returned for user " + userId);
7166             }
7167             return props;
7168         }
7169 
7170         @Override
7171         @UserAssignmentResult
7172         public int assignUserToDisplayOnStart(@UserIdInt int userId,
7173                 @UserIdInt int profileGroupId, @UserStartMode int userStartMode, int displayId) {
7174             return mUserVisibilityMediator.assignUserToDisplayOnStart(userId, profileGroupId,
7175                     userStartMode, displayId);
7176         }
7177 
7178         @Override
7179         public boolean assignUserToExtraDisplay(int userId, int displayId) {
7180             return mUserVisibilityMediator.assignUserToExtraDisplay(userId, displayId);
7181         }
7182 
7183         @Override
7184         public boolean unassignUserFromExtraDisplay(int userId, int displayId) {
7185             return mUserVisibilityMediator.unassignUserFromExtraDisplay(userId, displayId);
7186         }
7187 
7188         @Override
7189         public void unassignUserFromDisplayOnStop(@UserIdInt int userId) {
7190             mUserVisibilityMediator.unassignUserFromDisplayOnStop(userId);
7191         }
7192 
7193         @Override
7194         public boolean isUserVisible(@UserIdInt int userId) {
7195             return mUserVisibilityMediator.isUserVisible(userId);
7196         }
7197 
7198         @Override
7199         public boolean isUserVisible(@UserIdInt int userId, int displayId) {
7200             return mUserVisibilityMediator.isUserVisible(userId, displayId);
7201         }
7202 
7203         @Override
7204         public int getMainDisplayAssignedToUser(@UserIdInt int userId) {
7205             return mUserVisibilityMediator.getMainDisplayAssignedToUser(userId);
7206         }
7207 
7208         @Override
7209         public @Nullable int[] getDisplaysAssignedToUser(@UserIdInt int userId) {
7210             return mUserVisibilityMediator.getDisplaysAssignedToUser(userId);
7211         }
7212 
7213         @Override
7214         public @UserIdInt int getUserAssignedToDisplay(int displayId) {
7215             return mUserVisibilityMediator.getUserAssignedToDisplay(displayId);
7216         }
7217 
7218         @Override
7219         public void addUserVisibilityListener(UserVisibilityListener listener) {
7220             mUserVisibilityMediator.addListener(listener);
7221         }
7222 
7223         @Override
7224         public void removeUserVisibilityListener(UserVisibilityListener listener) {
7225             mUserVisibilityMediator.removeListener(listener);
7226         }
7227 
7228         @Override
7229         public void onSystemUserVisibilityChanged(boolean visible) {
7230             mUserVisibilityMediator.onSystemUserVisibilityChanged(visible);
7231         }
7232 
7233         @Override
7234         public int[] getUserTypesForStatsd(@UserIdInt int[] userIds) {
7235             if (userIds == null) {
7236                 return null;
7237             }
7238             final int[] userTypes = new int[userIds.length];
7239             for (int i = 0; i < userTypes.length; i++) {
7240                 final UserInfo userInfo = getUserInfo(userIds[i]);
7241                 if (userInfo == null) {
7242                     // Not possible because the input user ids should all be valid
7243                     userTypes[i] = mUserJourneyLogger.getUserTypeForStatsd("");
7244                 } else {
7245                     userTypes[i] = mUserJourneyLogger.getUserTypeForStatsd(userInfo.userType);
7246                 }
7247             }
7248             return userTypes;
7249         }
7250 
7251         @Override
7252         public @UserIdInt int getMainUserId() {
7253             return getMainUserIdUnchecked();
7254         }
7255 
7256         @Override
7257         public @UserIdInt int getBootUser(boolean waitUntilSet)
7258                 throws UserManager.CheckedUserOperationException {
7259             if (waitUntilSet) {
7260                 final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
7261                 t.traceBegin("wait-boot-user");
7262                 try {
7263                     if (mBootUserLatch.getCount() != 0) {
7264                         Slogf.d(LOG_TAG,
7265                                 "Sleeping for boot user to be set. "
7266                                 + "Max sleep for Time: %d", BOOT_USER_SET_TIMEOUT_MS);
7267                     }
7268                     if (!mBootUserLatch.await(BOOT_USER_SET_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
7269                         Slogf.w(LOG_TAG, "Boot user not set. Timeout: %d",
7270                                 BOOT_USER_SET_TIMEOUT_MS);
7271                     }
7272                 } catch (InterruptedException e) {
7273                     Thread.currentThread().interrupt();
7274                     Slogf.w(LOG_TAG, e, "InterruptedException during wait for boot user.");
7275                 }
7276                 t.traceEnd();
7277             }
7278 
7279             return getBootUserUnchecked();
7280         }
7281 
7282     } // class LocalService
7283 
7284 
7285 
7286     /**
7287      * Check if user has restrictions
7288      * @param restriction restrictions to check
7289      * @param userId id of the user
7290      *
7291      * @throws {@link android.os.UserManager.CheckedUserOperationException} if user has any of the
7292      *      specified restrictions
7293      */
7294     private void enforceUserRestriction(String restriction, @UserIdInt int userId, String message)
7295             throws UserManager.CheckedUserOperationException {
7296         if (hasUserRestriction(restriction, userId)) {
7297             String errorMessage = (message != null ? (message + ": ") : "")
7298                     + restriction + " is enabled.";
7299             Slog.w(LOG_TAG, errorMessage);
7300             throw new UserManager.CheckedUserOperationException(errorMessage,
7301                     USER_OPERATION_ERROR_UNKNOWN);
7302         }
7303     }
7304 
7305     /**
7306      * Throws CheckedUserOperationException and shows error log
7307      * @param message message for exception and logging
7308      * @param userOperationResult result/error code
7309      * @throws UserManager.CheckedUserOperationException
7310      */
7311     private void throwCheckedUserOperationException(@NonNull String message,
7312             @UserManager.UserOperationResult int userOperationResult)
7313             throws UserManager.CheckedUserOperationException {
7314         Slog.e(LOG_TAG, message);
7315         throw new UserManager.CheckedUserOperationException(message, userOperationResult);
7316     }
7317 
7318     /* Remove all the users except the system and permanent admin main.*/
7319     private void removeAllUsersExceptSystemAndPermanentAdminMain() {
7320         ArrayList<UserInfo> usersToRemove = new ArrayList<>();
7321         synchronized (mUsersLock) {
7322             final int userSize = mUsers.size();
7323             for (int i = 0; i < userSize; i++) {
7324                 UserInfo ui = mUsers.valueAt(i).info;
7325                 if (ui.id != UserHandle.USER_SYSTEM && !isNonRemovableMainUser(ui)) {
7326                     usersToRemove.add(ui);
7327                 }
7328             }
7329         }
7330         for (UserInfo ui: usersToRemove) {
7331             removeUser(ui.id);
7332         }
7333     }
7334 
7335     private static void debug(String message) {
7336         Slog.d(LOG_TAG, message
7337                 + (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, "  ") : ""));
7338     }
7339 
7340     /** @see #getMaxUsersOfTypePerParent(UserTypeDetails) */
7341     @VisibleForTesting
7342     int getMaxUsersOfTypePerParent(String userType) {
7343         final UserTypeDetails type = mUserTypes.get(userType);
7344         if (type == null) {
7345             return 0;
7346         }
7347         return getMaxUsersOfTypePerParent(type);
7348     }
7349 
7350     /**
7351      * Returns the maximum number of users allowed for the given userTypeDetails per parent user.
7352      * This is applicable for user types that are {@link UserTypeDetails#isProfile()}.
7353      * If there is no maximum, {@link UserTypeDetails#UNLIMITED_NUMBER_OF_USERS} is returned.
7354      * Under certain circumstances (such as after a change-user-type) the max value can actually
7355      * be exceeded: this is allowed in order to keep the device in a usable state.
7356      * An error is logged in {@link UserManagerService#upgradeProfileToTypeLU}
7357      */
7358     private static int getMaxUsersOfTypePerParent(UserTypeDetails userTypeDetails) {
7359         final int defaultMax = userTypeDetails.getMaxAllowedPerParent();
7360         if (!Build.IS_DEBUGGABLE) {
7361             return defaultMax;
7362         } else {
7363             if (userTypeDetails.isManagedProfile()) {
7364                 return SystemProperties.getInt("persist.sys.max_profiles", defaultMax);
7365             }
7366         }
7367         return defaultMax;
7368     }
7369 
7370     @GuardedBy("mUsersLock")
7371     @VisibleForTesting
7372     int getFreeProfileBadgeLU(int parentUserId, String userType) {
7373         Set<Integer> usedBadges = new ArraySet<>();
7374         final int userSize = mUsers.size();
7375         for (int i = 0; i < userSize; i++) {
7376             UserInfo ui = mUsers.valueAt(i).info;
7377             // Check which badge indexes are already used by this profile group.
7378             if (ui.userType.equals(userType)
7379                     && ui.profileGroupId == parentUserId
7380                     && !mRemovingUserIds.get(ui.id)) {
7381                 usedBadges.add(ui.profileBadge);
7382             }
7383         }
7384         int maxUsersOfType = getMaxUsersOfTypePerParent(userType);
7385         if (maxUsersOfType == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
7386             maxUsersOfType = Integer.MAX_VALUE;
7387         }
7388         for (int i = 0; i < maxUsersOfType; i++) {
7389             if (!usedBadges.contains(i)) {
7390                 return i;
7391             }
7392         }
7393         return 0;
7394     }
7395 
7396     /**
7397      * Checks if the given user has a profile associated with it.
7398      * @param userId The parent user
7399      * @return
7400      */
7401     boolean hasProfile(@UserIdInt int userId) {
7402         synchronized (mUsersLock) {
7403             UserInfo userInfo = getUserInfoLU(userId);
7404             final int userSize = mUsers.size();
7405             for (int i = 0; i < userSize; i++) {
7406                 UserInfo profile = mUsers.valueAt(i).info;
7407                 if (userId != profile.id && isProfileOf(userInfo, profile)) {
7408                     return true;
7409                 }
7410             }
7411             return false;
7412         }
7413     }
7414 
7415     /**
7416      * Checks if the calling package name matches with the calling UID, throw
7417      * {@link SecurityException} if not.
7418      */
7419     private void verifyCallingPackage(String callingPackage, int callingUid) {
7420         int packageUid = mPm.snapshotComputer()
7421                 .getPackageUid(callingPackage, 0,  UserHandle.getUserId(callingUid));
7422         if (packageUid != callingUid) {
7423             throw new SecurityException("Specified package " + callingPackage
7424                     + " does not match the calling uid " + callingUid);
7425         }
7426     }
7427 
7428     /** Retrieves the internal package manager interface. */
7429     private PackageManagerInternal getPackageManagerInternal() {
7430         // Don't need to synchonize; worst-case scenario LocalServices will be called twice.
7431         if (mPmInternal == null) {
7432             mPmInternal = LocalServices.getService(PackageManagerInternal.class);
7433         }
7434         return mPmInternal;
7435     }
7436 
7437     /** Returns the internal device policy manager interface. */
7438     private DevicePolicyManagerInternal getDevicePolicyManagerInternal() {
7439         if (mDevicePolicyManagerInternal == null) {
7440             mDevicePolicyManagerInternal =
7441                     LocalServices.getService(DevicePolicyManagerInternal.class);
7442         }
7443         return mDevicePolicyManagerInternal;
7444     }
7445 
7446     /** Returns the internal activity manager interface. */
7447     private @Nullable ActivityManagerInternal getActivityManagerInternal() {
7448         if (mAmInternal == null) {
7449             mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
7450         }
7451         return mAmInternal;
7452     }
7453 
7454     /**
7455      * Returns true, when user has {@link UserInfo#FLAG_MAIN} and system property
7456      * {@link com.android.internal.R.bool#config_isMainUserPermanentAdmin} is true.
7457      */
7458     private boolean isNonRemovableMainUser(UserInfo userInfo) {
7459         return userInfo.isMain() && isMainUserPermanentAdmin();
7460     }
7461 
7462     /**
7463      * Returns true if {@link com.android.internal.R.bool#config_isMainUserPermanentAdmin} is true.
7464      * If the main user is a permanent admin user it can't be deleted
7465      * or downgraded to non-admin status.
7466      */
7467     public boolean isMainUserPermanentAdmin() {
7468         return Resources.getSystem()
7469                 .getBoolean(R.bool.config_isMainUserPermanentAdmin);
7470     }
7471 
7472     /**
7473      * Returns true if {@link com.android.internal.R.bool#config_canSwitchToHeadlessSystemUser}
7474      * is true. If allowed, headless system user can run in the foreground even though
7475      * it is not a full user.
7476      */
7477     public boolean canSwitchToHeadlessSystemUser() {
7478         return Resources.getSystem()
7479                 .getBoolean(R.bool.config_canSwitchToHeadlessSystemUser);
7480     }
7481 
7482     /**
7483      * Returns instance of {@link com.android.server.pm.UserJourneyLogger}.
7484      */
7485     public UserJourneyLogger getUserJourneyLogger() {
7486         return mUserJourneyLogger;
7487     }
7488 
7489 }
7490