UserManagerService.java revision 7a1e68279460cba8483ce289147284a27d38b648
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
22import android.Manifest;
23import android.annotation.NonNull;
24import android.annotation.Nullable;
25import android.annotation.UserIdInt;
26import android.app.Activity;
27import android.app.ActivityManager;
28import android.app.ActivityManagerInternal;
29import android.app.ActivityManagerNative;
30import android.app.AppGlobals;
31import android.app.IActivityManager;
32import android.app.IStopUserCallback;
33import android.app.KeyguardManager;
34import android.app.PendingIntent;
35import android.content.BroadcastReceiver;
36import android.content.ComponentName;
37import android.content.Context;
38import android.content.Intent;
39import android.content.IntentFilter;
40import android.content.IntentSender;
41import android.content.pm.IPackageManager;
42import android.content.pm.PackageManager;
43import android.content.pm.PackageManager.NameNotFoundException;
44import android.content.pm.UserInfo;
45import android.content.res.Resources;
46import android.graphics.Bitmap;
47import android.os.Binder;
48import android.os.Build;
49import android.os.Bundle;
50import android.os.Debug;
51import android.os.Environment;
52import android.os.FileUtils;
53import android.os.Handler;
54import android.os.IBinder;
55import android.os.IUserManager;
56import android.os.Message;
57import android.os.ParcelFileDescriptor;
58import android.os.Parcelable;
59import android.os.PersistableBundle;
60import android.os.Process;
61import android.os.RemoteException;
62import android.os.ResultReceiver;
63import android.os.SELinux;
64import android.os.ServiceManager;
65import android.os.ShellCommand;
66import android.os.UserHandle;
67import android.os.UserManager;
68import android.os.UserManagerInternal;
69import android.os.UserManagerInternal.UserRestrictionsListener;
70import android.os.storage.StorageManager;
71import android.security.GateKeeper;
72import android.service.gatekeeper.IGateKeeperService;
73import android.system.ErrnoException;
74import android.system.Os;
75import android.system.OsConstants;
76import android.text.TextUtils;
77import android.util.AtomicFile;
78import android.util.IntArray;
79import android.util.Log;
80import android.util.Slog;
81import android.util.SparseArray;
82import android.util.SparseBooleanArray;
83import android.util.SparseIntArray;
84import android.util.TimeUtils;
85import android.util.Xml;
86
87import com.android.internal.annotations.GuardedBy;
88import com.android.internal.annotations.VisibleForTesting;
89import com.android.internal.app.IAppOpsService;
90import com.android.internal.logging.MetricsLogger;
91import com.android.internal.util.FastXmlSerializer;
92import com.android.internal.util.Preconditions;
93import com.android.internal.util.XmlUtils;
94import com.android.internal.widget.LockPatternUtils;
95import com.android.server.LocalServices;
96import com.android.server.SystemService;
97import com.android.server.am.UserState;
98
99import libcore.io.IoUtils;
100import libcore.util.Objects;
101
102import org.xmlpull.v1.XmlPullParser;
103import org.xmlpull.v1.XmlPullParserException;
104import org.xmlpull.v1.XmlSerializer;
105
106import java.io.BufferedOutputStream;
107import java.io.File;
108import java.io.FileDescriptor;
109import java.io.FileInputStream;
110import java.io.FileNotFoundException;
111import java.io.FileOutputStream;
112import java.io.IOException;
113import java.io.PrintWriter;
114import java.nio.charset.StandardCharsets;
115import java.util.ArrayList;
116import java.util.List;
117
118/**
119 * Service for {@link UserManager}.
120 *
121 * Method naming convention:
122 * <ul>
123 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
124 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
125 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
126 * </ul>
127 */
128public class UserManagerService extends IUserManager.Stub {
129
130    private static final String LOG_TAG = "UserManagerService";
131    static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
132    private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
133
134    private static final String TAG_NAME = "name";
135    private static final String TAG_ACCOUNT = "account";
136    private static final String ATTR_FLAGS = "flags";
137    private static final String ATTR_ICON_PATH = "icon";
138    private static final String ATTR_ID = "id";
139    private static final String ATTR_CREATION_TIME = "created";
140    private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
141    private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
142    private static final String ATTR_SERIAL_NO = "serialNumber";
143    private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
144    private static final String ATTR_PARTIAL = "partial";
145    private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
146    private static final String ATTR_USER_VERSION = "version";
147    private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
148    private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
149    private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
150    private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
151    private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
152    private static final String TAG_USERS = "users";
153    private static final String TAG_USER = "user";
154    private static final String TAG_RESTRICTIONS = "restrictions";
155    private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
156    private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
157    private static final String TAG_ENTRY = "entry";
158    private static final String TAG_VALUE = "value";
159    private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
160    private static final String ATTR_KEY = "key";
161    private static final String ATTR_VALUE_TYPE = "type";
162    private static final String ATTR_MULTIPLE = "m";
163
164    private static final String ATTR_TYPE_STRING_ARRAY = "sa";
165    private static final String ATTR_TYPE_STRING = "s";
166    private static final String ATTR_TYPE_BOOLEAN = "b";
167    private static final String ATTR_TYPE_INTEGER = "i";
168    private static final String ATTR_TYPE_BUNDLE = "B";
169    private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
170
171    private static final String USER_INFO_DIR = "system" + File.separator + "users";
172    private static final String USER_LIST_FILENAME = "userlist.xml";
173    private static final String USER_PHOTO_FILENAME = "photo.png";
174    private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
175
176    private static final String RESTRICTIONS_FILE_PREFIX = "res_";
177    private static final String XML_SUFFIX = ".xml";
178
179    private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
180            UserInfo.FLAG_MANAGED_PROFILE
181            | UserInfo.FLAG_EPHEMERAL
182            | UserInfo.FLAG_RESTRICTED
183            | UserInfo.FLAG_GUEST
184            | UserInfo.FLAG_DEMO;
185
186    private static final int MIN_USER_ID = 10;
187    // We need to keep process uid within Integer.MAX_VALUE.
188    private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
189
190    private static final int USER_VERSION = 6;
191
192    private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
193
194    // Maximum number of managed profiles permitted per user is 1. This cannot be increased
195    // without first making sure that the rest of the framework is prepared for it.
196    private static final int MAX_MANAGED_PROFILES = 1;
197
198    static final int WRITE_USER_MSG = 1;
199    static final int WRITE_USER_DELAY = 2*1000;  // 2 seconds
200
201    private static final String XATTR_SERIAL = "user.serial";
202
203    // Tron counters
204    private static final String TRON_GUEST_CREATED = "users_guest_created";
205    private static final String TRON_USER_CREATED = "users_user_created";
206
207    private final Context mContext;
208    private final PackageManagerService mPm;
209    private final Object mPackagesLock;
210    // Short-term lock for internal state, when interaction/sync with PM is not required
211    private final Object mUsersLock = new Object();
212    private final Object mRestrictionsLock = new Object();
213
214    private final Handler mHandler;
215
216    private final File mUsersDir;
217    private final File mUserListFile;
218
219    private static final IBinder mUserRestriconToken = new Binder();
220
221    /**
222     * User-related information that is used for persisting to flash. Only UserInfo is
223     * directly exposed to other system apps.
224     */
225    private static class UserData {
226        // Basic user information and properties
227        UserInfo info;
228        // Account name used when there is a strong association between a user and an account
229        String account;
230        // Account information for seeding into a newly created user. This could also be
231        // used for login validation for an existing user, for updating their credentials.
232        // In the latter case, data may not need to be persisted as it is only valid for the
233        // current login session.
234        String seedAccountName;
235        String seedAccountType;
236        PersistableBundle seedAccountOptions;
237        // Whether to perist the seed account information to be available after a boot
238        boolean persistSeedData;
239
240        void clearSeedAccountData() {
241            seedAccountName = null;
242            seedAccountType = null;
243            seedAccountOptions = null;
244            persistSeedData = false;
245        }
246    }
247
248    @GuardedBy("mUsersLock")
249    private final SparseArray<UserData> mUsers = new SparseArray<>();
250
251    /**
252     * User restrictions set via UserManager.  This doesn't include restrictions set by
253     * device owner / profile owners.
254     *
255     * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
256     * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
257     * maybe shared between {@link #mBaseUserRestrictions} and
258     * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
259     * (Otherwise we won't be able to detect what restrictions have changed in
260     * {@link #updateUserRestrictionsInternalLR}.
261     */
262    @GuardedBy("mRestrictionsLock")
263    private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
264
265    /**
266     * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
267     * with device / profile owner restrictions.  We'll initialize it lazily; use
268     * {@link #getEffectiveUserRestrictions} to access it.
269     *
270     * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
271     * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
272     * maybe shared between {@link #mBaseUserRestrictions} and
273     * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
274     * (Otherwise we won't be able to detect what restrictions have changed in
275     * {@link #updateUserRestrictionsInternalLR}.
276     */
277    @GuardedBy("mRestrictionsLock")
278    private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
279
280    /**
281     * User restrictions that have already been applied in
282     * {@link #updateUserRestrictionsInternalLR(Bundle, int)}.  We use it to detect restrictions
283     * that have changed since the last
284     * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
285     */
286    @GuardedBy("mRestrictionsLock")
287    private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
288
289    /**
290     * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
291     * that should be applied to all users, including guests.
292     */
293    @GuardedBy("mRestrictionsLock")
294    private Bundle mDevicePolicyGlobalUserRestrictions;
295
296    /**
297     * Id of the user that set global restrictions.
298     */
299    @GuardedBy("mRestrictionsLock")
300    private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
301
302    /**
303     * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
304     * for each user.
305     */
306    @GuardedBy("mRestrictionsLock")
307    private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
308
309    @GuardedBy("mGuestRestrictions")
310    private final Bundle mGuestRestrictions = new Bundle();
311
312    /**
313     * Set of user IDs being actively removed. Removed IDs linger in this set
314     * for several seconds to work around a VFS caching issue.
315     */
316    @GuardedBy("mUsersLock")
317    private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
318
319    @GuardedBy("mUsersLock")
320    private int[] mUserIds;
321    @GuardedBy("mPackagesLock")
322    private int mNextSerialNumber;
323    private int mUserVersion = 0;
324
325    private IAppOpsService mAppOpsService;
326
327    private final LocalService mLocalService;
328
329    @GuardedBy("mUsersLock")
330    private boolean mIsDeviceManaged;
331
332    @GuardedBy("mUsersLock")
333    private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
334
335    @GuardedBy("mUserRestrictionsListeners")
336    private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
337            new ArrayList<>();
338
339    private final LockPatternUtils mLockPatternUtils;
340
341    private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
342            "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
343
344    private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
345        @Override
346        public void onReceive(Context context, Intent intent) {
347            if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
348                final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
349                final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
350                setQuietModeEnabled(userHandle, false);
351                if (target != null) {
352                    try {
353                        mContext.startIntentSender(target, null, 0, 0, 0);
354                    } catch (IntentSender.SendIntentException e) {
355                        /* ignore */
356                    }
357                }
358            }
359        }
360    };
361
362    /**
363     * Whether all users should be created ephemeral.
364     */
365    @GuardedBy("mUsersLock")
366    private boolean mForceEphemeralUsers;
367
368    @GuardedBy("mUserStates")
369    private final SparseIntArray mUserStates = new SparseIntArray();
370
371    private static UserManagerService sInstance;
372
373    public static UserManagerService getInstance() {
374        synchronized (UserManagerService.class) {
375            return sInstance;
376        }
377    }
378
379    public static class LifeCycle extends SystemService {
380
381        private UserManagerService mUms;
382
383        /**
384         * @param context
385         */
386        public LifeCycle(Context context) {
387            super(context);
388        }
389
390        @Override
391        public void onStart() {
392            mUms = UserManagerService.getInstance();
393            publishBinderService(Context.USER_SERVICE, mUms);
394        }
395
396        @Override
397        public void onBootPhase(int phase) {
398            if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
399                mUms.cleanupPartialUsers();
400            }
401        }
402    }
403
404    @VisibleForTesting
405    UserManagerService(File dataDir) {
406        this(null, null, new Object(), dataDir);
407    }
408
409    /**
410     * Called by package manager to create the service.  This is closely
411     * associated with the package manager, and the given lock is the
412     * package manager's own lock.
413     */
414    UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
415        this(context, pm, packagesLock, Environment.getDataDirectory());
416    }
417
418    private UserManagerService(Context context, PackageManagerService pm,
419            Object packagesLock, File dataDir) {
420        mContext = context;
421        mPm = pm;
422        mPackagesLock = packagesLock;
423        mHandler = new MainHandler();
424        synchronized (mPackagesLock) {
425            mUsersDir = new File(dataDir, USER_INFO_DIR);
426            mUsersDir.mkdirs();
427            // Make zeroth user directory, for services to migrate their files to that location
428            File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
429            userZeroDir.mkdirs();
430            FileUtils.setPermissions(mUsersDir.toString(),
431                    FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
432                    -1, -1);
433            mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
434            initDefaultGuestRestrictions();
435            readUserListLP();
436            sInstance = this;
437        }
438        mLocalService = new LocalService();
439        LocalServices.addService(UserManagerInternal.class, mLocalService);
440        mLockPatternUtils = new LockPatternUtils(mContext);
441        mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
442    }
443
444    void systemReady() {
445        mAppOpsService = IAppOpsService.Stub.asInterface(
446                ServiceManager.getService(Context.APP_OPS_SERVICE));
447
448        synchronized (mRestrictionsLock) {
449            applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
450        }
451
452        UserInfo currentGuestUser = findCurrentGuestUser();
453        if (currentGuestUser != null && !hasUserRestriction(
454                UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
455            // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
456            // to it, in case this guest was created in a previous version where this
457            // user restriction was not a default guest restriction.
458            setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
459        }
460
461        mContext.registerReceiver(mDisableQuietModeCallback,
462                new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
463                null, mHandler);
464    }
465
466    void cleanupPartialUsers() {
467        // Prune out any partially created, partially removed and ephemeral users.
468        ArrayList<UserInfo> partials = new ArrayList<>();
469        synchronized (mUsersLock) {
470            final int userSize = mUsers.size();
471            for (int i = 0; i < userSize; i++) {
472                UserInfo ui = mUsers.valueAt(i).info;
473                if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
474                    partials.add(ui);
475                    mRemovingUserIds.append(ui.id, true);
476                    ui.partial = true;
477                }
478            }
479        }
480        final int partialsSize = partials.size();
481        for (int i = 0; i < partialsSize; i++) {
482            UserInfo ui = partials.get(i);
483            Slog.w(LOG_TAG, "Removing partially created user " + ui.id
484                    + " (name=" + ui.name + ")");
485            removeUserState(ui.id);
486        }
487    }
488
489    @Override
490    public String getUserAccount(int userId) {
491        checkManageUserAndAcrossUsersFullPermission("get user account");
492        synchronized (mUsersLock) {
493            return mUsers.get(userId).account;
494        }
495    }
496
497    @Override
498    public void setUserAccount(int userId, String accountName) {
499        checkManageUserAndAcrossUsersFullPermission("set user account");
500        UserData userToUpdate = null;
501        synchronized (mPackagesLock) {
502            synchronized (mUsersLock) {
503                final UserData userData = mUsers.get(userId);
504                if (userData == null) {
505                    Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
506                    return;
507                }
508                String currentAccount = userData.account;
509                if (!Objects.equal(currentAccount, accountName)) {
510                    userData.account = accountName;
511                    userToUpdate = userData;
512                }
513            }
514
515            if (userToUpdate != null) {
516                writeUserLP(userToUpdate);
517            }
518        }
519    }
520
521    @Override
522    public UserInfo getPrimaryUser() {
523        checkManageUsersPermission("query users");
524        synchronized (mUsersLock) {
525            final int userSize = mUsers.size();
526            for (int i = 0; i < userSize; i++) {
527                UserInfo ui = mUsers.valueAt(i).info;
528                if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
529                    return ui;
530                }
531            }
532        }
533        return null;
534    }
535
536    @Override
537    public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
538        checkManageOrCreateUsersPermission("query users");
539        synchronized (mUsersLock) {
540            ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
541            final int userSize = mUsers.size();
542            for (int i = 0; i < userSize; i++) {
543                UserInfo ui = mUsers.valueAt(i).info;
544                if (ui.partial) {
545                    continue;
546                }
547                if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
548                    users.add(userWithName(ui));
549                }
550            }
551            return users;
552        }
553    }
554
555    @Override
556    public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
557        boolean returnFullInfo = true;
558        if (userId != UserHandle.getCallingUserId()) {
559            checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
560        } else {
561            returnFullInfo = hasManageUsersPermission();
562        }
563        final long ident = Binder.clearCallingIdentity();
564        try {
565            synchronized (mUsersLock) {
566                return getProfilesLU(userId, enabledOnly, returnFullInfo);
567            }
568        } finally {
569            Binder.restoreCallingIdentity(ident);
570        }
571    }
572
573    @Override
574    public int[] getProfileIds(int userId, boolean enabledOnly) {
575        if (userId != UserHandle.getCallingUserId()) {
576            checkManageUsersPermission("getting profiles related to user " + userId);
577        }
578        final long ident = Binder.clearCallingIdentity();
579        try {
580            synchronized (mUsersLock) {
581                return getProfileIdsLU(userId, enabledOnly).toArray();
582            }
583        } finally {
584            Binder.restoreCallingIdentity(ident);
585        }
586    }
587
588    /** Assume permissions already checked and caller's identity cleared */
589    private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
590        IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
591        ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
592        for (int i = 0; i < profileIds.size(); i++) {
593            int profileId = profileIds.get(i);
594            UserInfo userInfo = mUsers.get(profileId).info;
595            // If full info is not required - clear PII data to prevent 3P apps from reading it
596            if (!fullInfo) {
597                userInfo = new UserInfo(userInfo);
598                userInfo.name = null;
599                userInfo.iconPath = null;
600            } else {
601                userInfo = userWithName(userInfo);
602            }
603            users.add(userInfo);
604        }
605        return users;
606    }
607
608    /**
609     *  Assume permissions already checked and caller's identity cleared
610     */
611    private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
612        UserInfo user = getUserInfoLU(userId);
613        IntArray result = new IntArray(mUsers.size());
614        if (user == null) {
615            // Probably a dying user
616            return result;
617        }
618        final int userSize = mUsers.size();
619        for (int i = 0; i < userSize; i++) {
620            UserInfo profile = mUsers.valueAt(i).info;
621            if (!isProfileOf(user, profile)) {
622                continue;
623            }
624            if (enabledOnly && !profile.isEnabled()) {
625                continue;
626            }
627            if (mRemovingUserIds.get(profile.id)) {
628                continue;
629            }
630            if (profile.partial) {
631                continue;
632            }
633            result.add(profile.id);
634        }
635        return result;
636    }
637
638    @Override
639    public int getCredentialOwnerProfile(int userHandle) {
640        checkManageUsersPermission("get the credential owner");
641        if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
642            synchronized (mUsersLock) {
643                UserInfo profileParent = getProfileParentLU(userHandle);
644                if (profileParent != null) {
645                    return profileParent.id;
646                }
647            }
648        }
649
650        return userHandle;
651    }
652
653    @Override
654    public boolean isSameProfileGroup(int userId, int otherUserId) {
655        if (userId == otherUserId) return true;
656        checkManageUsersPermission("check if in the same profile group");
657        return isSameProfileGroupNoChecks(userId, otherUserId);
658    }
659
660    private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
661        synchronized (mUsersLock) {
662            UserInfo userInfo = getUserInfoLU(userId);
663            if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
664                return false;
665            }
666            UserInfo otherUserInfo = getUserInfoLU(otherUserId);
667            if (otherUserInfo == null
668                    || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
669                return false;
670            }
671            return userInfo.profileGroupId == otherUserInfo.profileGroupId;
672        }
673    }
674
675    @Override
676    public UserInfo getProfileParent(int userHandle) {
677        checkManageUsersPermission("get the profile parent");
678        synchronized (mUsersLock) {
679            return getProfileParentLU(userHandle);
680        }
681    }
682
683    private UserInfo getProfileParentLU(int userHandle) {
684        UserInfo profile = getUserInfoLU(userHandle);
685        if (profile == null) {
686            return null;
687        }
688        int parentUserId = profile.profileGroupId;
689        if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
690            return null;
691        } else {
692            return getUserInfoLU(parentUserId);
693        }
694    }
695
696    private static boolean isProfileOf(UserInfo user, UserInfo profile) {
697        return user.id == profile.id ||
698                (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
699                && user.profileGroupId == profile.profileGroupId);
700    }
701
702    private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
703            UserHandle parentHandle, boolean inQuietMode) {
704        Intent intent = new Intent();
705        if (inQuietMode) {
706            intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
707        } else {
708            intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
709        }
710        intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
711        intent.putExtra(Intent.EXTRA_USER, profileHandle);
712        intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
713        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
714        mContext.sendBroadcastAsUser(intent, parentHandle);
715    }
716
717    @Override
718    public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
719        checkManageUsersPermission("silence profile");
720        boolean changed = false;
721        UserInfo profile, parent;
722        synchronized (mPackagesLock) {
723            synchronized (mUsersLock) {
724                profile = getUserInfoLU(userHandle);
725                parent = getProfileParentLU(userHandle);
726
727            }
728            if (profile == null || !profile.isManagedProfile()) {
729                throw new IllegalArgumentException("User " + userHandle + " is not a profile");
730            }
731            if (profile.isQuietModeEnabled() != enableQuietMode) {
732                profile.flags ^= UserInfo.FLAG_QUIET_MODE;
733                writeUserLP(getUserDataLU(profile.id));
734                changed = true;
735            }
736        }
737        if (changed) {
738            long identity = Binder.clearCallingIdentity();
739            try {
740                if (enableQuietMode) {
741                    ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
742                    LocalServices.getService(ActivityManagerInternal.class)
743                            .killForegroundAppsForUser(userHandle);
744                } else {
745                    ActivityManagerNative.getDefault().startUserInBackground(userHandle);
746                }
747            } catch (RemoteException e) {
748                Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
749            } finally {
750                Binder.restoreCallingIdentity(identity);
751            }
752
753            broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
754                    enableQuietMode);
755        }
756    }
757
758    @Override
759    public boolean isQuietModeEnabled(int userHandle) {
760        synchronized (mPackagesLock) {
761            UserInfo info;
762            synchronized (mUsersLock) {
763                info = getUserInfoLU(userHandle);
764            }
765            if (info == null || !info.isManagedProfile()) {
766                return false;
767            }
768            return info.isQuietModeEnabled();
769        }
770    }
771
772    @Override
773    public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
774        checkManageUsersPermission("silence profile");
775        if (StorageManager.isUserKeyUnlocked(userHandle)
776                || !mLockPatternUtils.isSecure(userHandle)) {
777            // if the user is already unlocked, no need to show a profile challenge
778            setQuietModeEnabled(userHandle, false);
779            return true;
780        }
781
782        long identity = Binder.clearCallingIdentity();
783        try {
784            // otherwise, we show a profile challenge to trigger decryption of the user
785            final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
786                    Context.KEYGUARD_SERVICE);
787            // We should use userHandle not credentialOwnerUserId here, as even if it is unified
788            // lock, confirm screenlock page will know and show personal challenge, and unlock
789            // work profile when personal challenge is correct
790            final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
791                    userHandle);
792            if (unlockIntent == null) {
793                return false;
794            }
795            final Intent callBackIntent = new Intent(
796                    ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
797            if (target != null) {
798                callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
799            }
800            callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
801            callBackIntent.setPackage(mContext.getPackageName());
802            callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
803            final PendingIntent pendingIntent = PendingIntent.getBroadcast(
804                    mContext,
805                    0,
806                    callBackIntent,
807                    PendingIntent.FLAG_CANCEL_CURRENT |
808                            PendingIntent.FLAG_ONE_SHOT |
809                            PendingIntent.FLAG_IMMUTABLE);
810            // After unlocking the challenge, it will disable quiet mode and run the original
811            // intentSender
812            unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
813            unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
814            mContext.startActivity(unlockIntent);
815        } finally {
816            Binder.restoreCallingIdentity(identity);
817        }
818        return false;
819    }
820
821    @Override
822    public void setUserEnabled(int userId) {
823        checkManageUsersPermission("enable user");
824        synchronized (mPackagesLock) {
825            UserInfo info;
826            synchronized (mUsersLock) {
827                info = getUserInfoLU(userId);
828            }
829            if (info != null && !info.isEnabled()) {
830                info.flags ^= UserInfo.FLAG_DISABLED;
831                writeUserLP(getUserDataLU(info.id));
832            }
833        }
834    }
835
836    @Override
837    public UserInfo getUserInfo(int userId) {
838        checkManageOrCreateUsersPermission("query user");
839        synchronized (mUsersLock) {
840            return userWithName(getUserInfoLU(userId));
841        }
842    }
843
844    /**
845     * Returns a UserInfo object with the name filled in, for Owner, or the original
846     * if the name is already set.
847     */
848    private UserInfo userWithName(UserInfo orig) {
849        if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
850            UserInfo withName = new UserInfo(orig);
851            withName.name = getOwnerName();
852            return withName;
853        } else {
854            return orig;
855        }
856    }
857
858    @Override
859    public boolean isManagedProfile(int userId) {
860        int callingUserId = UserHandle.getCallingUserId();
861        if (callingUserId != userId && !hasManageUsersPermission()) {
862            if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
863                throw new SecurityException(
864                        "You need MANAGE_USERS permission to: check if specified user a " +
865                        "managed profile outside your profile group");
866            }
867        }
868        synchronized (mUsersLock) {
869            UserInfo userInfo = getUserInfoLU(userId);
870            return userInfo != null && userInfo.isManagedProfile();
871        }
872    }
873
874    @Override
875    public boolean isUserUnlockingOrUnlocked(int userId) {
876        checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
877        return mLocalService.isUserUnlockingOrUnlocked(userId);
878    }
879
880    @Override
881    public boolean isUserUnlocked(int userId) {
882        checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
883        return mLocalService.isUserUnlockingOrUnlocked(userId);
884    }
885
886    @Override
887    public boolean isUserRunning(int userId) {
888        checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
889        return mLocalService.isUserRunning(userId);
890    }
891
892    private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
893        int callingUserId = UserHandle.getCallingUserId();
894        if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
895                hasManageUsersPermission()) {
896            return;
897        }
898        if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
899                Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
900            throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
901                    + "to: check " + name);
902        }
903    }
904
905    @Override
906    public boolean isDemoUser(int userId) {
907        int callingUserId = UserHandle.getCallingUserId();
908        if (callingUserId != userId && !hasManageUsersPermission()) {
909            throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
910                    + " is a demo user");
911        }
912        synchronized (mUsersLock) {
913            UserInfo userInfo = getUserInfoLU(userId);
914            return userInfo != null && userInfo.isDemo();
915        }
916    }
917
918    @Override
919    public boolean isRestricted() {
920        synchronized (mUsersLock) {
921            return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
922        }
923    }
924
925    @Override
926    public boolean canHaveRestrictedProfile(int userId) {
927        checkManageUsersPermission("canHaveRestrictedProfile");
928        synchronized (mUsersLock) {
929            final UserInfo userInfo = getUserInfoLU(userId);
930            if (userInfo == null || !userInfo.canHaveProfile()) {
931                return false;
932            }
933            if (!userInfo.isAdmin()) {
934                return false;
935            }
936            // restricted profile can be created if there is no DO set and the admin user has no PO;
937            return !mIsDeviceManaged && !mIsUserManaged.get(userId);
938        }
939    }
940
941    /*
942     * Should be locked on mUsers before calling this.
943     */
944    private UserInfo getUserInfoLU(int userId) {
945        final UserData userData = mUsers.get(userId);
946        // If it is partial and not in the process of being removed, return as unknown user.
947        if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
948            Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
949            return null;
950        }
951        return userData != null ? userData.info : null;
952    }
953
954    private UserData getUserDataLU(int userId) {
955        final UserData userData = mUsers.get(userId);
956        // If it is partial and not in the process of being removed, return as unknown user.
957        if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
958            return null;
959        }
960        return userData;
961    }
962
963    /**
964     * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
965     * <p>No permissions checking or any addition checks are made</p>
966     */
967    private UserInfo getUserInfoNoChecks(int userId) {
968        synchronized (mUsersLock) {
969            final UserData userData = mUsers.get(userId);
970            return userData != null ? userData.info : null;
971        }
972    }
973
974    /**
975     * Obtains {@link #mUsersLock} and return UserData from mUsers.
976     * <p>No permissions checking or any addition checks are made</p>
977     */
978    private UserData getUserDataNoChecks(int userId) {
979        synchronized (mUsersLock) {
980            return mUsers.get(userId);
981        }
982    }
983
984    /** Called by PackageManagerService */
985    public boolean exists(int userId) {
986        return getUserInfoNoChecks(userId) != null;
987    }
988
989    @Override
990    public void setUserName(int userId, String name) {
991        checkManageUsersPermission("rename users");
992        boolean changed = false;
993        synchronized (mPackagesLock) {
994            UserData userData = getUserDataNoChecks(userId);
995            if (userData == null || userData.info.partial) {
996                Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
997                return;
998            }
999            if (name != null && !name.equals(userData.info.name)) {
1000                userData.info.name = name;
1001                writeUserLP(userData);
1002                changed = true;
1003            }
1004        }
1005        if (changed) {
1006            sendUserInfoChangedBroadcast(userId);
1007        }
1008    }
1009
1010    @Override
1011    public void setUserIcon(int userId, Bitmap bitmap) {
1012        checkManageUsersPermission("update users");
1013        if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1014            Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1015            return;
1016        }
1017        mLocalService.setUserIcon(userId, bitmap);
1018    }
1019
1020
1021
1022    private void sendUserInfoChangedBroadcast(int userId) {
1023        Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1024        changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1025        changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1026        mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
1027    }
1028
1029    @Override
1030    public ParcelFileDescriptor getUserIcon(int targetUserId) {
1031        String iconPath;
1032        synchronized (mPackagesLock) {
1033            UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1034            if (targetUserInfo == null || targetUserInfo.partial) {
1035                Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
1036                return null;
1037            }
1038
1039            final int callingUserId = UserHandle.getCallingUserId();
1040            final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1041            final int targetGroupId = targetUserInfo.profileGroupId;
1042            final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1043                    && callingGroupId == targetGroupId);
1044            if ((callingUserId != targetUserId) && !sameGroup) {
1045                checkManageUsersPermission("get the icon of a user who is not related");
1046            }
1047
1048            if (targetUserInfo.iconPath == null) {
1049                return null;
1050            }
1051            iconPath = targetUserInfo.iconPath;
1052        }
1053
1054        try {
1055            return ParcelFileDescriptor.open(
1056                    new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1057        } catch (FileNotFoundException e) {
1058            Log.e(LOG_TAG, "Couldn't find icon file", e);
1059        }
1060        return null;
1061    }
1062
1063    public void makeInitialized(int userId) {
1064        checkManageUsersPermission("makeInitialized");
1065        boolean scheduleWriteUser = false;
1066        UserData userData;
1067        synchronized (mUsersLock) {
1068            userData = mUsers.get(userId);
1069            if (userData == null || userData.info.partial) {
1070                Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
1071                return;
1072            }
1073            if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1074                userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1075                scheduleWriteUser = true;
1076            }
1077        }
1078        if (scheduleWriteUser) {
1079            scheduleWriteUser(userData);
1080        }
1081    }
1082
1083    /**
1084     * If default guest restrictions haven't been initialized yet, add the basic
1085     * restrictions.
1086     */
1087    private void initDefaultGuestRestrictions() {
1088        synchronized (mGuestRestrictions) {
1089            if (mGuestRestrictions.isEmpty()) {
1090                mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
1091                mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
1092                mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1093                mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1094            }
1095        }
1096    }
1097
1098    @Override
1099    public Bundle getDefaultGuestRestrictions() {
1100        checkManageUsersPermission("getDefaultGuestRestrictions");
1101        synchronized (mGuestRestrictions) {
1102            return new Bundle(mGuestRestrictions);
1103        }
1104    }
1105
1106    @Override
1107    public void setDefaultGuestRestrictions(Bundle restrictions) {
1108        checkManageUsersPermission("setDefaultGuestRestrictions");
1109        synchronized (mGuestRestrictions) {
1110            mGuestRestrictions.clear();
1111            mGuestRestrictions.putAll(restrictions);
1112        }
1113        synchronized (mPackagesLock) {
1114            writeUserListLP();
1115        }
1116    }
1117
1118    /**
1119     * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1120     */
1121    void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
1122            @Nullable Bundle global) {
1123        Preconditions.checkNotNull(local);
1124        boolean globalChanged = false;
1125        boolean localChanged;
1126        synchronized (mRestrictionsLock) {
1127            if (global != null) {
1128                // Update global.
1129                globalChanged = !UserRestrictionsUtils.areEqual(
1130                        mDevicePolicyGlobalUserRestrictions, global);
1131                if (globalChanged) {
1132                    mDevicePolicyGlobalUserRestrictions = global;
1133                }
1134                // Remember the global restriction owner userId to be able to make a distinction
1135                // in getUserRestrictionSource on who set local policies.
1136                mGlobalRestrictionOwnerUserId = userId;
1137            } else {
1138                if (mGlobalRestrictionOwnerUserId == userId) {
1139                    // When profile owner sets restrictions it passes null global bundle and we
1140                    // reset global restriction owner userId.
1141                    // This means this user used to have DO, but now the DO is gone and the user
1142                    // instead has PO.
1143                    mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1144                }
1145            }
1146            {
1147                // Update local.
1148                final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1149                localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1150                if (localChanged) {
1151                    mDevicePolicyLocalUserRestrictions.put(userId, local);
1152                }
1153            }
1154        }
1155        if (DBG) {
1156            Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1157                            + " global=" + global + (globalChanged ? " (changed)" : "")
1158                            + " local=" + local + (localChanged ? " (changed)" : "")
1159            );
1160        }
1161        // Don't call them within the mRestrictionsLock.
1162        synchronized (mPackagesLock) {
1163            if (localChanged) {
1164                writeUserLP(getUserDataNoChecks(userId));
1165            }
1166            if (globalChanged) {
1167                writeUserListLP();
1168            }
1169        }
1170
1171        synchronized (mRestrictionsLock) {
1172            if (globalChanged) {
1173                applyUserRestrictionsForAllUsersLR();
1174            } else if (localChanged) {
1175                applyUserRestrictionsLR(userId);
1176            }
1177        }
1178    }
1179
1180    @GuardedBy("mRestrictionsLock")
1181    private Bundle computeEffectiveUserRestrictionsLR(int userId) {
1182        final Bundle baseRestrictions =
1183                UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1184        final Bundle global = mDevicePolicyGlobalUserRestrictions;
1185        final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
1186
1187        if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1188            // Common case first.
1189            return baseRestrictions;
1190        }
1191        final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1192        UserRestrictionsUtils.merge(effective, global);
1193        UserRestrictionsUtils.merge(effective, local);
1194
1195        return effective;
1196    }
1197
1198    @GuardedBy("mRestrictionsLock")
1199    private void invalidateEffectiveUserRestrictionsLR(int userId) {
1200        if (DBG) {
1201            Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1202        }
1203        mCachedEffectiveUserRestrictions.remove(userId);
1204    }
1205
1206    private Bundle getEffectiveUserRestrictions(int userId) {
1207        synchronized (mRestrictionsLock) {
1208            Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1209            if (restrictions == null) {
1210                restrictions = computeEffectiveUserRestrictionsLR(userId);
1211                mCachedEffectiveUserRestrictions.put(userId, restrictions);
1212            }
1213            return restrictions;
1214        }
1215    }
1216
1217    /** @return a specific user restriction that's in effect currently. */
1218    @Override
1219    public boolean hasUserRestriction(String restrictionKey, int userId) {
1220        if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1221            return false;
1222        }
1223        Bundle restrictions = getEffectiveUserRestrictions(userId);
1224        return restrictions != null && restrictions.getBoolean(restrictionKey);
1225    }
1226
1227    /**
1228     * @hide
1229     *
1230     * Returns who set a user restriction on a user.
1231     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1232     * @param restrictionKey the string key representing the restriction
1233     * @param userId the id of the user for whom to retrieve the restrictions.
1234     * @return The source of user restriction. Any combination of
1235     *         {@link UserManager#RESTRICTION_NOT_SET},
1236     *         {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1237     *         {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1238     *         and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1239     */
1240    @Override
1241    public int getUserRestrictionSource(String restrictionKey, int userId) {
1242        checkManageUsersPermission("getUserRestrictionSource");
1243        int result = UserManager.RESTRICTION_NOT_SET;
1244
1245        // Shortcut for the most common case
1246        if (!hasUserRestriction(restrictionKey, userId)) {
1247            return result;
1248        }
1249
1250        if (hasBaseUserRestriction(restrictionKey, userId)) {
1251            result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1252        }
1253
1254        synchronized(mRestrictionsLock) {
1255            Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1256            if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1257                    && localRestrictions.getBoolean(restrictionKey)) {
1258                // Local restrictions may have been set by device owner the userId of which is
1259                // stored in mGlobalRestrictionOwnerUserId.
1260                if (mGlobalRestrictionOwnerUserId == userId) {
1261                    result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1262                } else {
1263                    result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1264                }
1265            }
1266            if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1267                    && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1268                result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1269            }
1270        }
1271
1272        return result;
1273    }
1274
1275    /**
1276     * @return UserRestrictions that are in effect currently.  This always returns a new
1277     * {@link Bundle}.
1278     */
1279    @Override
1280    public Bundle getUserRestrictions(int userId) {
1281        return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
1282    }
1283
1284    @Override
1285    public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1286        checkManageUsersPermission("hasBaseUserRestriction");
1287        if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1288            return false;
1289        }
1290        synchronized (mRestrictionsLock) {
1291            Bundle bundle = mBaseUserRestrictions.get(userId);
1292            return (bundle != null && bundle.getBoolean(restrictionKey, false));
1293        }
1294    }
1295
1296    @Override
1297    public void setUserRestriction(String key, boolean value, int userId) {
1298        checkManageUsersPermission("setUserRestriction");
1299        if (!UserRestrictionsUtils.isValidRestriction(key)) {
1300            return;
1301        }
1302        synchronized (mRestrictionsLock) {
1303            // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1304            // a copy.
1305            final Bundle newRestrictions = UserRestrictionsUtils.clone(
1306                    mBaseUserRestrictions.get(userId));
1307            newRestrictions.putBoolean(key, value);
1308
1309            updateUserRestrictionsInternalLR(newRestrictions, userId);
1310        }
1311    }
1312
1313    /**
1314     * Optionally updating user restrictions, calculate the effective user restrictions and also
1315     * propagate to other services and system settings.
1316     *
1317     * @param newRestrictions User restrictions to set.
1318     *      If null, will not update user restrictions and only does the propagation.
1319     * @param userId target user ID.
1320     */
1321    @GuardedBy("mRestrictionsLock")
1322    private void updateUserRestrictionsInternalLR(
1323            @Nullable Bundle newRestrictions, int userId) {
1324
1325        final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1326                mAppliedUserRestrictions.get(userId));
1327
1328        // Update base restrictions.
1329        if (newRestrictions != null) {
1330            // If newRestrictions == the current one, it's probably a bug.
1331            final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1332
1333            Preconditions.checkState(prevBaseRestrictions != newRestrictions);
1334            Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1335                    != newRestrictions);
1336
1337            if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1338                mBaseUserRestrictions.put(userId, newRestrictions);
1339                scheduleWriteUser(getUserDataNoChecks(userId));
1340            }
1341        }
1342
1343        final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
1344
1345        mCachedEffectiveUserRestrictions.put(userId, effective);
1346
1347        // Apply the new restrictions.
1348        if (DBG) {
1349            debug("Applying user restrictions: userId=" + userId
1350                    + " new=" + effective + " prev=" + prevAppliedRestrictions);
1351        }
1352
1353        if (mAppOpsService != null) { // We skip it until system-ready.
1354            mHandler.post(new Runnable() {
1355                @Override
1356                public void run() {
1357                    try {
1358                        mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1359                    } catch (RemoteException e) {
1360                        Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1361                    }
1362                }
1363            });
1364        }
1365
1366        propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
1367
1368        mAppliedUserRestrictions.put(userId, new Bundle(effective));
1369    }
1370
1371    private void propagateUserRestrictionsLR(final int userId,
1372            Bundle newRestrictions, Bundle prevRestrictions) {
1373        // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1374        // actually, but we still need some kind of synchronization otherwise we might end up
1375        // calling listeners out-of-order, thus "LR".
1376
1377        if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1378            return;
1379        }
1380
1381        final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1382        final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1383
1384        mHandler.post(new Runnable() {
1385            @Override
1386            public void run() {
1387                UserRestrictionsUtils.applyUserRestrictions(
1388                        mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
1389
1390                final UserRestrictionsListener[] listeners;
1391                synchronized (mUserRestrictionsListeners) {
1392                    listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1393                    mUserRestrictionsListeners.toArray(listeners);
1394                }
1395                for (int i = 0; i < listeners.length; i++) {
1396                    listeners[i].onUserRestrictionsChanged(userId,
1397                            newRestrictionsFinal, prevRestrictionsFinal);
1398                }
1399            }
1400        });
1401    }
1402
1403    // Package private for the inner class.
1404    void applyUserRestrictionsLR(int userId) {
1405        updateUserRestrictionsInternalLR(null, userId);
1406    }
1407
1408    @GuardedBy("mRestrictionsLock")
1409    // Package private for the inner class.
1410    void applyUserRestrictionsForAllUsersLR() {
1411        if (DBG) {
1412            debug("applyUserRestrictionsForAllUsersLR");
1413        }
1414        // First, invalidate all cached values.
1415        mCachedEffectiveUserRestrictions.clear();
1416
1417        // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1418        // it on a handler.
1419        final Runnable r = new Runnable() {
1420            @Override
1421            public void run() {
1422                // Then get the list of running users.
1423                final int[] runningUsers;
1424                try {
1425                    runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1426                } catch (RemoteException e) {
1427                    Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1428                    return;
1429                }
1430                // Then re-calculate the effective restrictions and apply, only for running users.
1431                // It's okay if a new user has started after the getRunningUserIds() call,
1432                // because we'll do the same thing (re-calculate the restrictions and apply)
1433                // when we start a user.
1434                synchronized (mRestrictionsLock) {
1435                    for (int i = 0; i < runningUsers.length; i++) {
1436                        applyUserRestrictionsLR(runningUsers[i]);
1437                    }
1438                }
1439            }
1440        };
1441        mHandler.post(r);
1442    }
1443
1444    /**
1445     * Check if we've hit the limit of how many users can be created.
1446     */
1447    private boolean isUserLimitReached() {
1448        int count;
1449        synchronized (mUsersLock) {
1450            count = getAliveUsersExcludingGuestsCountLU();
1451        }
1452        return count >= UserManager.getMaxSupportedUsers();
1453    }
1454
1455    @Override
1456    public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
1457        checkManageUsersPermission("check if more managed profiles can be added.");
1458        if (ActivityManager.isLowRamDeviceStatic()) {
1459            return false;
1460        }
1461        if (!mContext.getPackageManager().hasSystemFeature(
1462                PackageManager.FEATURE_MANAGED_USERS)) {
1463            return false;
1464        }
1465        // Limit number of managed profiles that can be created
1466        final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1467        final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1468        if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
1469            return false;
1470        }
1471        synchronized(mUsersLock) {
1472            UserInfo userInfo = getUserInfoLU(userId);
1473            if (!userInfo.canHaveProfile()) {
1474                return false;
1475            }
1476            int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1477                    - profilesRemovedCount;
1478            // We allow creating a managed profile in the special case where there is only one user.
1479            return usersCountAfterRemoving  == 1
1480                    || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
1481        }
1482    }
1483
1484    private int getAliveUsersExcludingGuestsCountLU() {
1485        int aliveUserCount = 0;
1486        final int totalUserCount = mUsers.size();
1487        // Skip over users being removed
1488        for (int i = 0; i < totalUserCount; i++) {
1489            UserInfo user = mUsers.valueAt(i).info;
1490            if (!mRemovingUserIds.get(user.id)
1491                    && !user.isGuest() && !user.partial) {
1492                aliveUserCount++;
1493            }
1494        }
1495        return aliveUserCount;
1496    }
1497
1498    /**
1499     * Enforces that only the system UID or root's UID or apps that have the
1500     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1501     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1502     * permissions can make certain calls to the UserManager.
1503     *
1504     * @param message used as message if SecurityException is thrown
1505     * @throws SecurityException if the caller does not have enough privilege.
1506     */
1507    private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1508        final int uid = Binder.getCallingUid();
1509        if (uid != Process.SYSTEM_UID && uid != 0
1510                && ActivityManager.checkComponentPermission(
1511                Manifest.permission.MANAGE_USERS,
1512                uid, -1, true) != PackageManager.PERMISSION_GRANTED
1513                && ActivityManager.checkComponentPermission(
1514                Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1515                uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1516            throw new SecurityException(
1517                    "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1518                            + message);
1519        }
1520    }
1521
1522    /**
1523     * Enforces that only the system UID or root's UID or apps that have the
1524     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
1525     * permission can make certain calls to the UserManager.
1526     *
1527     * @param message used as message if SecurityException is thrown
1528     * @throws SecurityException if the caller is not system or root
1529     * @see #hasManageUsersPermission()
1530     */
1531    private static final void checkManageUsersPermission(String message) {
1532        if (!hasManageUsersPermission()) {
1533            throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1534        }
1535    }
1536
1537    /**
1538     * Enforces that only the system UID or root's UID or apps that have the
1539     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1540     * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1541     * can make certain calls to the UserManager.
1542     *
1543     * @param message used as message if SecurityException is thrown
1544     * @throws SecurityException if the caller is not system or root
1545     * @see #hasManageOrCreateUsersPermission()
1546     */
1547    private static final void checkManageOrCreateUsersPermission(String message) {
1548        if (!hasManageOrCreateUsersPermission()) {
1549            throw new SecurityException(
1550                    "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1551        }
1552    }
1553
1554    /**
1555     * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1556     * to create user/profiles other than what is allowed for
1557     * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1558     * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1559     */
1560    private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1561        if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1562            if (!hasManageOrCreateUsersPermission()) {
1563                throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1564                        + "permission to create an user with flags: " + creationFlags);
1565            }
1566        } else if (!hasManageUsersPermission()) {
1567            throw new SecurityException("You need MANAGE_USERS permission to create an user "
1568                    + " with flags: " + creationFlags);
1569        }
1570    }
1571
1572    /**
1573     * @return whether the calling UID is system UID or root's UID or the calling app has the
1574     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1575     */
1576    private static final boolean hasManageUsersPermission() {
1577        final int callingUid = Binder.getCallingUid();
1578        return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1579                || callingUid == Process.ROOT_UID
1580                || ActivityManager.checkComponentPermission(
1581                        android.Manifest.permission.MANAGE_USERS,
1582                        callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1583    }
1584
1585    /**
1586     * @return whether the calling UID is system UID or root's UID or the calling app has the
1587     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1588     * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1589     */
1590    private static final boolean hasManageOrCreateUsersPermission() {
1591        final int callingUid = Binder.getCallingUid();
1592        return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1593                || callingUid == Process.ROOT_UID
1594                || ActivityManager.checkComponentPermission(
1595                        android.Manifest.permission.MANAGE_USERS,
1596                        callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1597                || ActivityManager.checkComponentPermission(
1598                        android.Manifest.permission.CREATE_USERS,
1599                        callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1600    }
1601
1602    /**
1603     * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1604     * UserManager.
1605     *
1606     * @param message used as message if SecurityException is thrown
1607     * @throws SecurityException if the caller is not system or root
1608     */
1609    private static void checkSystemOrRoot(String message) {
1610        final int uid = Binder.getCallingUid();
1611        if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1612            throw new SecurityException("Only system may: " + message);
1613        }
1614    }
1615
1616    private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
1617        try {
1618            File dir = new File(mUsersDir, Integer.toString(info.id));
1619            File file = new File(dir, USER_PHOTO_FILENAME);
1620            File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
1621            if (!dir.exists()) {
1622                dir.mkdir();
1623                FileUtils.setPermissions(
1624                        dir.getPath(),
1625                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1626                        -1, -1);
1627            }
1628            FileOutputStream os;
1629            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1630                    && tmp.renameTo(file) && SELinux.restorecon(file)) {
1631                info.iconPath = file.getAbsolutePath();
1632            }
1633            try {
1634                os.close();
1635            } catch (IOException ioe) {
1636                // What the ... !
1637            }
1638            tmp.delete();
1639        } catch (FileNotFoundException e) {
1640            Slog.w(LOG_TAG, "Error setting photo for user ", e);
1641        }
1642    }
1643
1644    /**
1645     * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1646     * cache it elsewhere.
1647     * @return the array of user ids.
1648     */
1649    public int[] getUserIds() {
1650        synchronized (mUsersLock) {
1651            return mUserIds;
1652        }
1653    }
1654
1655    private void readUserListLP() {
1656        if (!mUserListFile.exists()) {
1657            fallbackToSingleUserLP();
1658            return;
1659        }
1660        FileInputStream fis = null;
1661        AtomicFile userListFile = new AtomicFile(mUserListFile);
1662        try {
1663            fis = userListFile.openRead();
1664            XmlPullParser parser = Xml.newPullParser();
1665            parser.setInput(fis, StandardCharsets.UTF_8.name());
1666            int type;
1667            while ((type = parser.next()) != XmlPullParser.START_TAG
1668                    && type != XmlPullParser.END_DOCUMENT) {
1669                // Skip
1670            }
1671
1672            if (type != XmlPullParser.START_TAG) {
1673                Slog.e(LOG_TAG, "Unable to read user list");
1674                fallbackToSingleUserLP();
1675                return;
1676            }
1677
1678            mNextSerialNumber = -1;
1679            if (parser.getName().equals(TAG_USERS)) {
1680                String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1681                if (lastSerialNumber != null) {
1682                    mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1683                }
1684                String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1685                if (versionNumber != null) {
1686                    mUserVersion = Integer.parseInt(versionNumber);
1687                }
1688            }
1689
1690            final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1691
1692            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1693                if (type == XmlPullParser.START_TAG) {
1694                    final String name = parser.getName();
1695                    if (name.equals(TAG_USER)) {
1696                        String id = parser.getAttributeValue(null, ATTR_ID);
1697
1698                        UserData userData = readUserLP(Integer.parseInt(id));
1699
1700                        if (userData != null) {
1701                            synchronized (mUsersLock) {
1702                                mUsers.put(userData.info.id, userData);
1703                                if (mNextSerialNumber < 0
1704                                        || mNextSerialNumber <= userData.info.id) {
1705                                    mNextSerialNumber = userData.info.id + 1;
1706                                }
1707                            }
1708                        }
1709                    } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
1710                        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1711                                && type != XmlPullParser.END_TAG) {
1712                            if (type == XmlPullParser.START_TAG) {
1713                                if (parser.getName().equals(TAG_RESTRICTIONS)) {
1714                                    synchronized (mGuestRestrictions) {
1715                                        UserRestrictionsUtils
1716                                                .readRestrictions(parser, mGuestRestrictions);
1717                                    }
1718                                } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1719                                        ) {
1720                                    UserRestrictionsUtils.readRestrictions(parser,
1721                                            newDevicePolicyGlobalUserRestrictions);
1722                                }
1723                                break;
1724                            }
1725                        }
1726                    } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1727                        String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1728                        if (ownerUserId != null) {
1729                            mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1730                        }
1731                    }
1732                }
1733            }
1734            synchronized (mRestrictionsLock) {
1735                mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1736            }
1737            updateUserIds();
1738            upgradeIfNecessaryLP();
1739        } catch (IOException | XmlPullParserException e) {
1740            fallbackToSingleUserLP();
1741        } finally {
1742            IoUtils.closeQuietly(fis);
1743        }
1744    }
1745
1746    /**
1747     * Upgrade steps between versions, either for fixing bugs or changing the data format.
1748     */
1749    private void upgradeIfNecessaryLP() {
1750        final int originalVersion = mUserVersion;
1751        int userVersion = mUserVersion;
1752        if (userVersion < 1) {
1753            // Assign a proper name for the owner, if not initialized correctly before
1754            UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1755            if ("Primary".equals(userData.info.name)) {
1756                userData.info.name =
1757                        mContext.getResources().getString(com.android.internal.R.string.owner_name);
1758                scheduleWriteUser(userData);
1759            }
1760            userVersion = 1;
1761        }
1762
1763        if (userVersion < 2) {
1764            // Owner should be marked as initialized
1765            UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1766            if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1767                userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1768                scheduleWriteUser(userData);
1769            }
1770            userVersion = 2;
1771        }
1772
1773
1774        if (userVersion < 4) {
1775            userVersion = 4;
1776        }
1777
1778        if (userVersion < 5) {
1779            initDefaultGuestRestrictions();
1780            userVersion = 5;
1781        }
1782
1783        if (userVersion < 6) {
1784            final boolean splitSystemUser = UserManager.isSplitSystemUser();
1785            synchronized (mUsersLock) {
1786                for (int i = 0; i < mUsers.size(); i++) {
1787                    UserData userData = mUsers.valueAt(i);
1788                    // In non-split mode, only user 0 can have restricted profiles
1789                    if (!splitSystemUser && userData.info.isRestricted()
1790                            && (userData.info.restrictedProfileParentId
1791                                    == UserInfo.NO_PROFILE_GROUP_ID)) {
1792                        userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1793                        scheduleWriteUser(userData);
1794                    }
1795                }
1796            }
1797            userVersion = 6;
1798        }
1799
1800        if (userVersion < USER_VERSION) {
1801            Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1802                    + USER_VERSION);
1803        } else {
1804            mUserVersion = userVersion;
1805
1806            if (originalVersion < mUserVersion) {
1807                writeUserListLP();
1808            }
1809        }
1810    }
1811
1812    private void fallbackToSingleUserLP() {
1813        int flags = UserInfo.FLAG_INITIALIZED;
1814        // In split system user mode, the admin and primary flags are assigned to the first human
1815        // user.
1816        if (!UserManager.isSplitSystemUser()) {
1817            flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1818        }
1819        // Create the system user
1820        UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
1821        UserData userData = new UserData();
1822        userData.info = system;
1823        synchronized (mUsersLock) {
1824            mUsers.put(system.id, userData);
1825        }
1826        mNextSerialNumber = MIN_USER_ID;
1827        mUserVersion = USER_VERSION;
1828
1829        Bundle restrictions = new Bundle();
1830        try {
1831            final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1832                    com.android.internal.R.array.config_defaultFirstUserRestrictions);
1833            for (String userRestriction : defaultFirstUserRestrictions) {
1834                if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1835                    restrictions.putBoolean(userRestriction, true);
1836                }
1837            }
1838        } catch (Resources.NotFoundException e) {
1839            Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1840        }
1841
1842        synchronized (mRestrictionsLock) {
1843            mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1844        }
1845
1846        updateUserIds();
1847        initDefaultGuestRestrictions();
1848
1849        writeUserLP(userData);
1850        writeUserListLP();
1851    }
1852
1853    private String getOwnerName() {
1854        return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1855    }
1856
1857    private void scheduleWriteUser(UserData UserData) {
1858        if (DBG) {
1859            debug("scheduleWriteUser");
1860        }
1861        // No need to wrap it within a lock -- worst case, we'll just post the same message
1862        // twice.
1863        if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1864            Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
1865            mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1866        }
1867    }
1868
1869    /*
1870     * Writes the user file in this format:
1871     *
1872     * <user flags="20039023" id="0">
1873     *   <name>Primary</name>
1874     * </user>
1875     */
1876    private void writeUserLP(UserData userData) {
1877        if (DBG) {
1878            debug("writeUserLP " + userData);
1879        }
1880        FileOutputStream fos = null;
1881        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
1882        try {
1883            fos = userFile.startWrite();
1884            final BufferedOutputStream bos = new BufferedOutputStream(fos);
1885
1886            // XmlSerializer serializer = XmlUtils.serializerInstance();
1887            final XmlSerializer serializer = new FastXmlSerializer();
1888            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
1889            serializer.startDocument(null, true);
1890            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1891
1892            final UserInfo userInfo = userData.info;
1893            serializer.startTag(null, TAG_USER);
1894            serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
1895            serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
1896            serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
1897            serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1898            serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1899                    Long.toString(userInfo.lastLoggedInTime));
1900            if (userInfo.lastLoggedInFingerprint != null) {
1901                serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1902                        userInfo.lastLoggedInFingerprint);
1903            }
1904            if (userInfo.iconPath != null) {
1905                serializer.attribute(null,  ATTR_ICON_PATH, userInfo.iconPath);
1906            }
1907            if (userInfo.partial) {
1908                serializer.attribute(null, ATTR_PARTIAL, "true");
1909            }
1910            if (userInfo.guestToRemove) {
1911                serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1912            }
1913            if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1914                serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1915                        Integer.toString(userInfo.profileGroupId));
1916            }
1917            if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1918                serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1919                        Integer.toString(userInfo.restrictedProfileParentId));
1920            }
1921            // Write seed data
1922            if (userData.persistSeedData) {
1923                if (userData.seedAccountName != null) {
1924                    serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1925                }
1926                if (userData.seedAccountType != null) {
1927                    serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1928                }
1929            }
1930            if (userInfo.name != null) {
1931                serializer.startTag(null, TAG_NAME);
1932                serializer.text(userInfo.name);
1933                serializer.endTag(null, TAG_NAME);
1934            }
1935            synchronized (mRestrictionsLock) {
1936                UserRestrictionsUtils.writeRestrictions(serializer,
1937                        mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1938                UserRestrictionsUtils.writeRestrictions(serializer,
1939                        mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1940                        TAG_DEVICE_POLICY_RESTRICTIONS);
1941            }
1942
1943            if (userData.account != null) {
1944                serializer.startTag(null, TAG_ACCOUNT);
1945                serializer.text(userData.account);
1946                serializer.endTag(null, TAG_ACCOUNT);
1947            }
1948
1949            if (userData.persistSeedData && userData.seedAccountOptions != null) {
1950                serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1951                userData.seedAccountOptions.saveToXml(serializer);
1952                serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1953            }
1954            serializer.endTag(null, TAG_USER);
1955
1956            serializer.endDocument();
1957            userFile.finishWrite(fos);
1958        } catch (Exception ioe) {
1959            Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
1960            userFile.failWrite(fos);
1961        }
1962    }
1963
1964    /*
1965     * Writes the user list file in this format:
1966     *
1967     * <users nextSerialNumber="3">
1968     *   <user id="0"></user>
1969     *   <user id="2"></user>
1970     * </users>
1971     */
1972    private void writeUserListLP() {
1973        if (DBG) {
1974            debug("writeUserList");
1975        }
1976        FileOutputStream fos = null;
1977        AtomicFile userListFile = new AtomicFile(mUserListFile);
1978        try {
1979            fos = userListFile.startWrite();
1980            final BufferedOutputStream bos = new BufferedOutputStream(fos);
1981
1982            // XmlSerializer serializer = XmlUtils.serializerInstance();
1983            final XmlSerializer serializer = new FastXmlSerializer();
1984            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
1985            serializer.startDocument(null, true);
1986            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1987
1988            serializer.startTag(null, TAG_USERS);
1989            serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
1990            serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
1991
1992            serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
1993            synchronized (mGuestRestrictions) {
1994                UserRestrictionsUtils
1995                        .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1996            }
1997            serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
1998            synchronized (mRestrictionsLock) {
1999                UserRestrictionsUtils.writeRestrictions(serializer,
2000                        mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
2001            }
2002            serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
2003            serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
2004            serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
2005            int[] userIdsToWrite;
2006            synchronized (mUsersLock) {
2007                userIdsToWrite = new int[mUsers.size()];
2008                for (int i = 0; i < userIdsToWrite.length; i++) {
2009                    UserInfo user = mUsers.valueAt(i).info;
2010                    userIdsToWrite[i] = user.id;
2011                }
2012            }
2013            for (int id : userIdsToWrite) {
2014                serializer.startTag(null, TAG_USER);
2015                serializer.attribute(null, ATTR_ID, Integer.toString(id));
2016                serializer.endTag(null, TAG_USER);
2017            }
2018
2019            serializer.endTag(null, TAG_USERS);
2020
2021            serializer.endDocument();
2022            userListFile.finishWrite(fos);
2023        } catch (Exception e) {
2024            userListFile.failWrite(fos);
2025            Slog.e(LOG_TAG, "Error writing user list");
2026        }
2027    }
2028
2029    private UserData readUserLP(int id) {
2030        int flags = 0;
2031        int serialNumber = id;
2032        String name = null;
2033        String account = null;
2034        String iconPath = null;
2035        long creationTime = 0L;
2036        long lastLoggedInTime = 0L;
2037        String lastLoggedInFingerprint = null;
2038        int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
2039        int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
2040        boolean partial = false;
2041        boolean guestToRemove = false;
2042        boolean persistSeedData = false;
2043        String seedAccountName = null;
2044        String seedAccountType = null;
2045        PersistableBundle seedAccountOptions = null;
2046        Bundle baseRestrictions = new Bundle();
2047        Bundle localRestrictions = new Bundle();
2048
2049        FileInputStream fis = null;
2050        try {
2051            AtomicFile userFile =
2052                    new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2053            fis = userFile.openRead();
2054            XmlPullParser parser = Xml.newPullParser();
2055            parser.setInput(fis, StandardCharsets.UTF_8.name());
2056            int type;
2057            while ((type = parser.next()) != XmlPullParser.START_TAG
2058                    && type != XmlPullParser.END_DOCUMENT) {
2059                // Skip
2060            }
2061
2062            if (type != XmlPullParser.START_TAG) {
2063                Slog.e(LOG_TAG, "Unable to read user " + id);
2064                return null;
2065            }
2066
2067            if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2068                int storedId = readIntAttribute(parser, ATTR_ID, -1);
2069                if (storedId != id) {
2070                    Slog.e(LOG_TAG, "User id does not match the file name");
2071                    return null;
2072                }
2073                serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2074                flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2075                iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2076                creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2077                lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2078                lastLoggedInFingerprint = parser.getAttributeValue(null,
2079                        ATTR_LAST_LOGGED_IN_FINGERPRINT);
2080                profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2081                        UserInfo.NO_PROFILE_GROUP_ID);
2082                restrictedProfileParentId = readIntAttribute(parser,
2083                        ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2084                String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2085                if ("true".equals(valueString)) {
2086                    partial = true;
2087                }
2088                valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2089                if ("true".equals(valueString)) {
2090                    guestToRemove = true;
2091                }
2092
2093                seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2094                seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2095                if (seedAccountName != null || seedAccountType != null) {
2096                    persistSeedData = true;
2097                }
2098
2099                int outerDepth = parser.getDepth();
2100                while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2101                       && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2102                    if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2103                        continue;
2104                    }
2105                    String tag = parser.getName();
2106                    if (TAG_NAME.equals(tag)) {
2107                        type = parser.next();
2108                        if (type == XmlPullParser.TEXT) {
2109                            name = parser.getText();
2110                        }
2111                    } else if (TAG_RESTRICTIONS.equals(tag)) {
2112                        UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2113                    } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2114                        UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
2115                    } else if (TAG_ACCOUNT.equals(tag)) {
2116                        type = parser.next();
2117                        if (type == XmlPullParser.TEXT) {
2118                            account = parser.getText();
2119                        }
2120                    } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2121                        seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2122                        persistSeedData = true;
2123                    }
2124                }
2125            }
2126
2127            // Create the UserInfo object that gets passed around
2128            UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2129            userInfo.serialNumber = serialNumber;
2130            userInfo.creationTime = creationTime;
2131            userInfo.lastLoggedInTime = lastLoggedInTime;
2132            userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2133            userInfo.partial = partial;
2134            userInfo.guestToRemove = guestToRemove;
2135            userInfo.profileGroupId = profileGroupId;
2136            userInfo.restrictedProfileParentId = restrictedProfileParentId;
2137
2138            // Create the UserData object that's internal to this class
2139            UserData userData = new UserData();
2140            userData.info = userInfo;
2141            userData.account = account;
2142            userData.seedAccountName = seedAccountName;
2143            userData.seedAccountType = seedAccountType;
2144            userData.persistSeedData = persistSeedData;
2145            userData.seedAccountOptions = seedAccountOptions;
2146
2147            synchronized (mRestrictionsLock) {
2148                mBaseUserRestrictions.put(id, baseRestrictions);
2149                mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2150            }
2151            return userData;
2152        } catch (IOException ioe) {
2153        } catch (XmlPullParserException pe) {
2154        } finally {
2155            if (fis != null) {
2156                try {
2157                    fis.close();
2158                } catch (IOException e) {
2159                }
2160            }
2161        }
2162        return null;
2163    }
2164
2165    private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2166        String valueString = parser.getAttributeValue(null, attr);
2167        if (valueString == null) return defaultValue;
2168        try {
2169            return Integer.parseInt(valueString);
2170        } catch (NumberFormatException nfe) {
2171            return defaultValue;
2172        }
2173    }
2174
2175    private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2176        String valueString = parser.getAttributeValue(null, attr);
2177        if (valueString == null) return defaultValue;
2178        try {
2179            return Long.parseLong(valueString);
2180        } catch (NumberFormatException nfe) {
2181            return defaultValue;
2182        }
2183    }
2184
2185    /**
2186     * Removes the app restrictions file for a specific package and user id, if it exists.
2187     */
2188    private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2189        synchronized (mPackagesLock) {
2190            File dir = Environment.getUserSystemDirectory(userId);
2191            File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2192            if (resFile.exists()) {
2193                resFile.delete();
2194            }
2195        }
2196    }
2197
2198    @Override
2199    public UserInfo createProfileForUser(String name, int flags, int userId) {
2200        checkManageOrCreateUsersPermission(flags);
2201        return createUserInternal(name, flags, userId);
2202    }
2203
2204    @Override
2205    public UserInfo createUser(String name, int flags) {
2206        checkManageOrCreateUsersPermission(flags);
2207        return createUserInternal(name, flags, UserHandle.USER_NULL);
2208    }
2209
2210    private UserInfo createUserInternal(String name, int flags, int parentId) {
2211        if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
2212            Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2213            return null;
2214        }
2215        return createUserInternalUnchecked(name, flags, parentId);
2216    }
2217
2218    private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
2219        if (ActivityManager.isLowRamDeviceStatic()) {
2220            return null;
2221        }
2222        final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
2223        final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
2224        final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
2225        final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
2226        final long ident = Binder.clearCallingIdentity();
2227        UserInfo userInfo;
2228        UserData userData;
2229        final int userId;
2230        try {
2231            synchronized (mPackagesLock) {
2232                UserData parent = null;
2233                if (parentId != UserHandle.USER_NULL) {
2234                    synchronized (mUsersLock) {
2235                        parent = getUserDataLU(parentId);
2236                    }
2237                    if (parent == null) return null;
2238                }
2239                if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2240                    Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2241                    return null;
2242                }
2243                if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2244                    // If we're not adding a guest/demo user or a managed profile and the limit has
2245                    // been reached, cannot add a user.
2246                    return null;
2247                }
2248                // If we're adding a guest and there already exists one, bail.
2249                if (isGuest && findCurrentGuestUser() != null) {
2250                    return null;
2251                }
2252                // In legacy mode, restricted profile's parent can only be the owner user
2253                if (isRestricted && !UserManager.isSplitSystemUser()
2254                        && (parentId != UserHandle.USER_SYSTEM)) {
2255                    Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2256                    return null;
2257                }
2258                if (isRestricted && UserManager.isSplitSystemUser()) {
2259                    if (parent == null) {
2260                        Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2261                                + "specified");
2262                        return null;
2263                    }
2264                    if (!parent.info.canHaveProfile()) {
2265                        Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2266                                + "created for the specified parent user id " + parentId);
2267                        return null;
2268                    }
2269                }
2270                if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2271                        && (flags & UserInfo.FLAG_DEMO) == 0) {
2272                    Log.e(LOG_TAG,
2273                            "Ephemeral users are supported on split-system-user systems only.");
2274                    return null;
2275                }
2276                // In split system user mode, we assign the first human user the primary flag.
2277                // And if there is no device owner, we also assign the admin flag to primary user.
2278                if (UserManager.isSplitSystemUser()
2279                        && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2280                    flags |= UserInfo.FLAG_PRIMARY;
2281                    synchronized (mUsersLock) {
2282                        if (!mIsDeviceManaged) {
2283                            flags |= UserInfo.FLAG_ADMIN;
2284                        }
2285                    }
2286                }
2287
2288                userId = getNextAvailableId();
2289                Environment.getUserSystemDirectory(userId).mkdirs();
2290                boolean ephemeralGuests = Resources.getSystem()
2291                        .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
2292
2293                synchronized (mUsersLock) {
2294                    // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2295                    if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2296                            || (parent != null && parent.info.isEphemeral())) {
2297                        flags |= UserInfo.FLAG_EPHEMERAL;
2298                    }
2299
2300                    userInfo = new UserInfo(userId, name, null, flags);
2301                    userInfo.serialNumber = mNextSerialNumber++;
2302                    long now = System.currentTimeMillis();
2303                    userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2304                    userInfo.partial = true;
2305                    userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
2306                    userData = new UserData();
2307                    userData.info = userInfo;
2308                    mUsers.put(userId, userData);
2309                }
2310                writeUserLP(userData);
2311                writeUserListLP();
2312                if (parent != null) {
2313                    if (isManagedProfile) {
2314                        if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2315                            parent.info.profileGroupId = parent.info.id;
2316                            writeUserLP(parent);
2317                        }
2318                        userInfo.profileGroupId = parent.info.profileGroupId;
2319                    } else if (isRestricted) {
2320                        if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2321                            parent.info.restrictedProfileParentId = parent.info.id;
2322                            writeUserLP(parent);
2323                        }
2324                        userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
2325                    }
2326                }
2327            }
2328            final StorageManager storage = mContext.getSystemService(StorageManager.class);
2329            storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
2330            mPm.prepareUserData(userId, userInfo.serialNumber,
2331                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2332            mPm.createNewUser(userId);
2333            userInfo.partial = false;
2334            synchronized (mPackagesLock) {
2335                writeUserLP(userData);
2336            }
2337            updateUserIds();
2338            Bundle restrictions = new Bundle();
2339            if (isGuest) {
2340                synchronized (mGuestRestrictions) {
2341                    restrictions.putAll(mGuestRestrictions);
2342                }
2343            }
2344            synchronized (mRestrictionsLock) {
2345                mBaseUserRestrictions.append(userId, restrictions);
2346            }
2347            mPm.onNewUserCreated(userId);
2348            Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2349            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2350            mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2351                    android.Manifest.permission.MANAGE_USERS);
2352            MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
2353        } finally {
2354            Binder.restoreCallingIdentity(ident);
2355        }
2356        return userInfo;
2357    }
2358
2359    /**
2360     * @hide
2361     */
2362    @Override
2363    public UserInfo createRestrictedProfile(String name, int parentUserId) {
2364        checkManageOrCreateUsersPermission("setupRestrictedProfile");
2365        final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2366        if (user == null) {
2367            return null;
2368        }
2369        long identity = Binder.clearCallingIdentity();
2370        try {
2371            setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2372            // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2373            // the putIntForUser() will fail.
2374            android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2375                    android.provider.Settings.Secure.LOCATION_MODE,
2376                    android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2377            setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2378        } finally {
2379            Binder.restoreCallingIdentity(identity);
2380        }
2381        return user;
2382    }
2383
2384    /**
2385     * Find the current guest user. If the Guest user is partial,
2386     * then do not include it in the results as it is about to die.
2387     */
2388    private UserInfo findCurrentGuestUser() {
2389        synchronized (mUsersLock) {
2390            final int size = mUsers.size();
2391            for (int i = 0; i < size; i++) {
2392                final UserInfo user = mUsers.valueAt(i).info;
2393                if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2394                    return user;
2395                }
2396            }
2397        }
2398        return null;
2399    }
2400
2401    /**
2402     * Mark this guest user for deletion to allow us to create another guest
2403     * and switch to that user before actually removing this guest.
2404     * @param userHandle the userid of the current guest
2405     * @return whether the user could be marked for deletion
2406     */
2407    @Override
2408    public boolean markGuestForDeletion(int userHandle) {
2409        checkManageUsersPermission("Only the system can remove users");
2410        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2411                UserManager.DISALLOW_REMOVE_USER, false)) {
2412            Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2413            return false;
2414        }
2415
2416        long ident = Binder.clearCallingIdentity();
2417        try {
2418            final UserData userData;
2419            synchronized (mPackagesLock) {
2420                synchronized (mUsersLock) {
2421                    userData = mUsers.get(userHandle);
2422                    if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
2423                        return false;
2424                    }
2425                }
2426                if (!userData.info.isGuest()) {
2427                    return false;
2428                }
2429                // We set this to a guest user that is to be removed. This is a temporary state
2430                // where we are allowed to add new Guest users, even if this one is still not
2431                // removed. This user will still show up in getUserInfo() calls.
2432                // If we don't get around to removing this Guest user, it will be purged on next
2433                // startup.
2434                userData.info.guestToRemove = true;
2435                // Mark it as disabled, so that it isn't returned any more when
2436                // profiles are queried.
2437                userData.info.flags |= UserInfo.FLAG_DISABLED;
2438                writeUserLP(userData);
2439            }
2440        } finally {
2441            Binder.restoreCallingIdentity(ident);
2442        }
2443        return true;
2444    }
2445
2446    /**
2447     * Removes a user and all data directories created for that user. This method should be called
2448     * after the user's processes have been terminated.
2449     * @param userHandle the user's id
2450     */
2451    @Override
2452    public boolean removeUser(int userHandle) {
2453        checkManageOrCreateUsersPermission("Only the system can remove users");
2454        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2455                UserManager.DISALLOW_REMOVE_USER, false)) {
2456            Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2457            return false;
2458        }
2459
2460        long ident = Binder.clearCallingIdentity();
2461        try {
2462            final UserData userData;
2463            int currentUser = ActivityManager.getCurrentUser();
2464            if (currentUser == userHandle) {
2465                Log.w(LOG_TAG, "Current user cannot be removed");
2466                return false;
2467            }
2468            synchronized (mPackagesLock) {
2469                synchronized (mUsersLock) {
2470                    userData = mUsers.get(userHandle);
2471                    if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
2472                        return false;
2473                    }
2474
2475                    // We remember deleted user IDs to prevent them from being
2476                    // reused during the current boot; they can still be reused
2477                    // after a reboot.
2478                    mRemovingUserIds.put(userHandle, true);
2479                }
2480
2481                try {
2482                    mAppOpsService.removeUser(userHandle);
2483                } catch (RemoteException e) {
2484                    Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2485                }
2486                // Set this to a partially created user, so that the user will be purged
2487                // on next startup, in case the runtime stops now before stopping and
2488                // removing the user completely.
2489                userData.info.partial = true;
2490                // Mark it as disabled, so that it isn't returned any more when
2491                // profiles are queried.
2492                userData.info.flags |= UserInfo.FLAG_DISABLED;
2493                writeUserLP(userData);
2494            }
2495
2496            if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2497                    && userData.info.isManagedProfile()) {
2498                // Send broadcast to notify system that the user removed was a
2499                // managed user.
2500                sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
2501            }
2502
2503            if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2504            int res;
2505            try {
2506                res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2507                new IStopUserCallback.Stub() {
2508                            @Override
2509                            public void userStopped(int userId) {
2510                                finishRemoveUser(userId);
2511                            }
2512                            @Override
2513                            public void userStopAborted(int userId) {
2514                            }
2515                        });
2516            } catch (RemoteException e) {
2517                return false;
2518            }
2519            return res == ActivityManager.USER_OP_SUCCESS;
2520        } finally {
2521            Binder.restoreCallingIdentity(ident);
2522        }
2523    }
2524
2525    void finishRemoveUser(final int userHandle) {
2526        if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
2527        // Let other services shutdown any activity and clean up their state before completely
2528        // wiping the user's system directory and removing from the user list
2529        long ident = Binder.clearCallingIdentity();
2530        try {
2531            Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2532            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
2533            mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2534                    android.Manifest.permission.MANAGE_USERS,
2535
2536                    new BroadcastReceiver() {
2537                        @Override
2538                        public void onReceive(Context context, Intent intent) {
2539                            if (DBG) {
2540                                Slog.i(LOG_TAG,
2541                                        "USER_REMOVED broadcast sent, cleaning up user data "
2542                                        + userHandle);
2543                            }
2544                            new Thread() {
2545                                @Override
2546                                public void run() {
2547                                    // Clean up any ActivityManager state
2548                                    LocalServices.getService(ActivityManagerInternal.class)
2549                                            .onUserRemoved(userHandle);
2550                                    removeUserState(userHandle);
2551                                }
2552                            }.start();
2553                        }
2554                    },
2555
2556                    null, Activity.RESULT_OK, null, null);
2557        } finally {
2558            Binder.restoreCallingIdentity(ident);
2559        }
2560    }
2561
2562    private void removeUserState(final int userHandle) {
2563        try {
2564            mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2565        } catch (IllegalStateException e) {
2566            // This may be simply because the user was partially created.
2567            Slog.i(LOG_TAG,
2568                "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2569        }
2570
2571        // Cleanup gatekeeper secure user id
2572        try {
2573            final IGateKeeperService gk = GateKeeper.getService();
2574            if (gk != null) {
2575                gk.clearSecureUserId(userHandle);
2576            }
2577        } catch (Exception ex) {
2578            Slog.w(LOG_TAG, "unable to clear GK secure user id");
2579        }
2580
2581        // Cleanup package manager settings
2582        mPm.cleanUpUser(this, userHandle);
2583
2584        // Clean up all data before removing metadata
2585        mPm.destroyUserData(userHandle,
2586                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2587
2588        // Remove this user from the list
2589        synchronized (mUsersLock) {
2590            mUsers.remove(userHandle);
2591            mIsUserManaged.delete(userHandle);
2592        }
2593        synchronized (mUserStates) {
2594            mUserStates.delete(userHandle);
2595        }
2596        synchronized (mRestrictionsLock) {
2597            mBaseUserRestrictions.remove(userHandle);
2598            mAppliedUserRestrictions.remove(userHandle);
2599            mCachedEffectiveUserRestrictions.remove(userHandle);
2600            mDevicePolicyLocalUserRestrictions.remove(userHandle);
2601        }
2602        // Update the user list
2603        synchronized (mPackagesLock) {
2604            writeUserListLP();
2605        }
2606        // Remove user file
2607        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2608        userFile.delete();
2609        updateUserIds();
2610    }
2611
2612    private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
2613        Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
2614        managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2615                Intent.FLAG_RECEIVER_FOREGROUND);
2616        managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
2617        managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
2618        mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
2619    }
2620
2621    @Override
2622    public Bundle getApplicationRestrictions(String packageName) {
2623        return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2624    }
2625
2626    @Override
2627    public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
2628        if (UserHandle.getCallingUserId() != userId
2629                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
2630            checkSystemOrRoot("get application restrictions for other users/apps");
2631        }
2632        synchronized (mPackagesLock) {
2633            // Read the restrictions from XML
2634            return readApplicationRestrictionsLP(packageName, userId);
2635        }
2636    }
2637
2638    @Override
2639    public void setApplicationRestrictions(String packageName, Bundle restrictions,
2640            int userId) {
2641        checkSystemOrRoot("set application restrictions");
2642        if (restrictions != null) {
2643            restrictions.setDefusable(true);
2644        }
2645        synchronized (mPackagesLock) {
2646            if (restrictions == null || restrictions.isEmpty()) {
2647                cleanAppRestrictionsForPackage(packageName, userId);
2648            } else {
2649                // Write the restrictions to XML
2650                writeApplicationRestrictionsLP(packageName, restrictions, userId);
2651            }
2652        }
2653
2654        // Notify package of changes via an intent - only sent to explicitly registered receivers.
2655        Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2656        changeIntent.setPackage(packageName);
2657        changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2658        mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
2659    }
2660
2661    private int getUidForPackage(String packageName) {
2662        long ident = Binder.clearCallingIdentity();
2663        try {
2664            return mContext.getPackageManager().getApplicationInfo(packageName,
2665                    PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
2666        } catch (NameNotFoundException nnfe) {
2667            return -1;
2668        } finally {
2669            Binder.restoreCallingIdentity(ident);
2670        }
2671    }
2672
2673    private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
2674        AtomicFile restrictionsFile =
2675                new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2676                        packageToRestrictionsFileName(packageName)));
2677        return readApplicationRestrictionsLP(restrictionsFile);
2678    }
2679
2680    @VisibleForTesting
2681    static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
2682        final Bundle restrictions = new Bundle();
2683        final ArrayList<String> values = new ArrayList<>();
2684        if (!restrictionsFile.getBaseFile().exists()) {
2685            return restrictions;
2686        }
2687
2688        FileInputStream fis = null;
2689        try {
2690            fis = restrictionsFile.openRead();
2691            XmlPullParser parser = Xml.newPullParser();
2692            parser.setInput(fis, StandardCharsets.UTF_8.name());
2693            XmlUtils.nextElement(parser);
2694            if (parser.getEventType() != XmlPullParser.START_TAG) {
2695                Slog.e(LOG_TAG, "Unable to read restrictions file "
2696                        + restrictionsFile.getBaseFile());
2697                return restrictions;
2698            }
2699            while (parser.next() != XmlPullParser.END_DOCUMENT) {
2700                readEntry(restrictions, values, parser);
2701            }
2702        } catch (IOException|XmlPullParserException e) {
2703            Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
2704        } finally {
2705            IoUtils.closeQuietly(fis);
2706        }
2707        return restrictions;
2708    }
2709
2710    private static void readEntry(Bundle restrictions, ArrayList<String> values,
2711            XmlPullParser parser) throws XmlPullParserException, IOException {
2712        int type = parser.getEventType();
2713        if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2714            String key = parser.getAttributeValue(null, ATTR_KEY);
2715            String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2716            String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2717            if (multiple != null) {
2718                values.clear();
2719                int count = Integer.parseInt(multiple);
2720                while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2721                    if (type == XmlPullParser.START_TAG
2722                            && parser.getName().equals(TAG_VALUE)) {
2723                        values.add(parser.nextText().trim());
2724                        count--;
2725                    }
2726                }
2727                String [] valueStrings = new String[values.size()];
2728                values.toArray(valueStrings);
2729                restrictions.putStringArray(key, valueStrings);
2730            } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2731                restrictions.putBundle(key, readBundleEntry(parser, values));
2732            } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2733                final int outerDepth = parser.getDepth();
2734                ArrayList<Bundle> bundleList = new ArrayList<>();
2735                while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2736                    Bundle childBundle = readBundleEntry(parser, values);
2737                    bundleList.add(childBundle);
2738                }
2739                restrictions.putParcelableArray(key,
2740                        bundleList.toArray(new Bundle[bundleList.size()]));
2741            } else {
2742                String value = parser.nextText().trim();
2743                if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2744                    restrictions.putBoolean(key, Boolean.parseBoolean(value));
2745                } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2746                    restrictions.putInt(key, Integer.parseInt(value));
2747                } else {
2748                    restrictions.putString(key, value);
2749                }
2750            }
2751        }
2752    }
2753
2754    private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2755            throws IOException, XmlPullParserException {
2756        Bundle childBundle = new Bundle();
2757        final int outerDepth = parser.getDepth();
2758        while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2759            readEntry(childBundle, values, parser);
2760        }
2761        return childBundle;
2762    }
2763
2764    private void writeApplicationRestrictionsLP(String packageName,
2765            Bundle restrictions, int userId) {
2766        AtomicFile restrictionsFile = new AtomicFile(
2767                new File(Environment.getUserSystemDirectory(userId),
2768                        packageToRestrictionsFileName(packageName)));
2769        writeApplicationRestrictionsLP(restrictions, restrictionsFile);
2770    }
2771
2772    @VisibleForTesting
2773    static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
2774        FileOutputStream fos = null;
2775        try {
2776            fos = restrictionsFile.startWrite();
2777            final BufferedOutputStream bos = new BufferedOutputStream(fos);
2778
2779            final XmlSerializer serializer = new FastXmlSerializer();
2780            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
2781            serializer.startDocument(null, true);
2782            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2783
2784            serializer.startTag(null, TAG_RESTRICTIONS);
2785            writeBundle(restrictions, serializer);
2786            serializer.endTag(null, TAG_RESTRICTIONS);
2787
2788            serializer.endDocument();
2789            restrictionsFile.finishWrite(fos);
2790        } catch (Exception e) {
2791            restrictionsFile.failWrite(fos);
2792            Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2793        }
2794    }
2795
2796    private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2797            throws IOException {
2798        for (String key : restrictions.keySet()) {
2799            Object value = restrictions.get(key);
2800            serializer.startTag(null, TAG_ENTRY);
2801            serializer.attribute(null, ATTR_KEY, key);
2802
2803            if (value instanceof Boolean) {
2804                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2805                serializer.text(value.toString());
2806            } else if (value instanceof Integer) {
2807                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2808                serializer.text(value.toString());
2809            } else if (value == null || value instanceof String) {
2810                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2811                serializer.text(value != null ? (String) value : "");
2812            } else if (value instanceof Bundle) {
2813                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2814                writeBundle((Bundle) value, serializer);
2815            } else if (value instanceof Parcelable[]) {
2816                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2817                Parcelable[] array = (Parcelable[]) value;
2818                for (Parcelable parcelable : array) {
2819                    if (!(parcelable instanceof Bundle)) {
2820                        throw new IllegalArgumentException("bundle-array can only hold Bundles");
2821                    }
2822                    serializer.startTag(null, TAG_ENTRY);
2823                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2824                    writeBundle((Bundle) parcelable, serializer);
2825                    serializer.endTag(null, TAG_ENTRY);
2826                }
2827            } else {
2828                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2829                String[] values = (String[]) value;
2830                serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2831                for (String choice : values) {
2832                    serializer.startTag(null, TAG_VALUE);
2833                    serializer.text(choice != null ? choice : "");
2834                    serializer.endTag(null, TAG_VALUE);
2835                }
2836            }
2837            serializer.endTag(null, TAG_ENTRY);
2838        }
2839    }
2840
2841    @Override
2842    public int getUserSerialNumber(int userHandle) {
2843        synchronized (mUsersLock) {
2844            if (!exists(userHandle)) return -1;
2845            return getUserInfoLU(userHandle).serialNumber;
2846        }
2847    }
2848
2849    @Override
2850    public int getUserHandle(int userSerialNumber) {
2851        synchronized (mUsersLock) {
2852            for (int userId : mUserIds) {
2853                UserInfo info = getUserInfoLU(userId);
2854                if (info != null && info.serialNumber == userSerialNumber) return userId;
2855            }
2856            // Not found
2857            return -1;
2858        }
2859    }
2860
2861    @Override
2862    public long getUserCreationTime(int userHandle) {
2863        int callingUserId = UserHandle.getCallingUserId();
2864        UserInfo userInfo = null;
2865        synchronized (mUsersLock) {
2866            if (callingUserId == userHandle) {
2867                userInfo = getUserInfoLU(userHandle);
2868            } else {
2869                UserInfo parent = getProfileParentLU(userHandle);
2870                if (parent != null && parent.id == callingUserId) {
2871                    userInfo = getUserInfoLU(userHandle);
2872                }
2873            }
2874        }
2875        if (userInfo == null) {
2876            throw new SecurityException("userHandle can only be the calling user or a managed "
2877                    + "profile associated with this user");
2878        }
2879        return userInfo.creationTime;
2880    }
2881
2882    /**
2883     * Caches the list of user ids in an array, adjusting the array size when necessary.
2884     */
2885    private void updateUserIds() {
2886        int num = 0;
2887        synchronized (mUsersLock) {
2888            final int userSize = mUsers.size();
2889            for (int i = 0; i < userSize; i++) {
2890                if (!mUsers.valueAt(i).info.partial) {
2891                    num++;
2892                }
2893            }
2894            final int[] newUsers = new int[num];
2895            int n = 0;
2896            for (int i = 0; i < userSize; i++) {
2897                if (!mUsers.valueAt(i).info.partial) {
2898                    newUsers[n++] = mUsers.keyAt(i);
2899                }
2900            }
2901            mUserIds = newUsers;
2902        }
2903    }
2904
2905    /**
2906     * Called right before a user is started. This gives us a chance to prepare
2907     * app storage and apply any user restrictions.
2908     */
2909    public void onBeforeStartUser(int userId) {
2910        final int userSerial = getUserSerialNumber(userId);
2911        mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2912        mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
2913
2914        if (userId != UserHandle.USER_SYSTEM) {
2915            synchronized (mRestrictionsLock) {
2916                applyUserRestrictionsLR(userId);
2917            }
2918        }
2919
2920        maybeInitializeDemoMode(userId);
2921    }
2922
2923    /**
2924     * Called right before a user is unlocked. This gives us a chance to prepare
2925     * app storage.
2926     */
2927    public void onBeforeUnlockUser(@UserIdInt int userId) {
2928        final int userSerial = getUserSerialNumber(userId);
2929        mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2930        mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
2931    }
2932
2933    /**
2934     * Make a note of the last started time of a user and do some cleanup.
2935     * This is called with ActivityManagerService lock held.
2936     * @param userId the user that was just foregrounded
2937     */
2938    public void onUserLoggedIn(@UserIdInt int userId) {
2939        UserData userData = getUserDataNoChecks(userId);
2940        if (userData == null || userData.info.partial) {
2941            Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2942            return;
2943        }
2944
2945        final long now = System.currentTimeMillis();
2946        if (now > EPOCH_PLUS_30_YEARS) {
2947            userData.info.lastLoggedInTime = now;
2948        }
2949        userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2950        scheduleWriteUser(userData);
2951    }
2952
2953    private void maybeInitializeDemoMode(int userId) {
2954        if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
2955            String demoLauncher =
2956                    mContext.getResources().getString(
2957                            com.android.internal.R.string.config_demoModeLauncherComponent);
2958            if (!TextUtils.isEmpty(demoLauncher)) {
2959                ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
2960                String demoLauncherPkg = componentToEnable.getPackageName();
2961                try {
2962                    final IPackageManager iPm = AppGlobals.getPackageManager();
2963                    iPm.setComponentEnabledSetting(componentToEnable,
2964                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2965                            /* userId= */ userId);
2966                    iPm.setApplicationEnabledSetting(demoLauncherPkg,
2967                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2968                            /* userId= */ userId, null);
2969                } catch (RemoteException re) {
2970                    // Internal, shouldn't happen
2971                }
2972            }
2973        }
2974    }
2975
2976    /**
2977     * Returns the next available user id, filling in any holes in the ids.
2978     * TODO: May not be a good idea to recycle ids, in case it results in confusion
2979     * for data and battery stats collection, or unexpected cross-talk.
2980     */
2981    private int getNextAvailableId() {
2982        synchronized (mUsersLock) {
2983            int i = MIN_USER_ID;
2984            while (i < MAX_USER_ID) {
2985                if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
2986                    return i;
2987                }
2988                i++;
2989            }
2990        }
2991        throw new IllegalStateException("No user id available!");
2992    }
2993
2994    private String packageToRestrictionsFileName(String packageName) {
2995        return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2996    }
2997
2998    /**
2999     * Enforce that serial number stored in user directory inode matches the
3000     * given expected value. Gracefully sets the serial number if currently
3001     * undefined.
3002     *
3003     * @throws IOException when problem extracting serial number, or serial
3004     *             number is mismatched.
3005     */
3006    public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
3007        if (StorageManager.isFileEncryptedEmulatedOnly()) {
3008            // When we're emulating FBE, the directory may have been chmod
3009            // 000'ed, meaning we can't read the serial number to enforce it;
3010            // instead of destroying the user, just log a warning.
3011            Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3012            return;
3013        }
3014
3015        final int foundSerial = getSerialNumber(file);
3016        Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3017
3018        if (foundSerial == -1) {
3019            Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3020            try {
3021                setSerialNumber(file, serialNumber);
3022            } catch (IOException e) {
3023                Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3024            }
3025
3026        } else if (foundSerial != serialNumber) {
3027            throw new IOException("Found serial number " + foundSerial
3028                    + " doesn't match expected " + serialNumber);
3029        }
3030    }
3031
3032    /**
3033     * Set serial number stored in user directory inode.
3034     *
3035     * @throws IOException if serial number was already set
3036     */
3037    private static void setSerialNumber(File file, int serialNumber)
3038            throws IOException {
3039        try {
3040            final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3041            Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3042        } catch (ErrnoException e) {
3043            throw e.rethrowAsIOException();
3044        }
3045    }
3046
3047    /**
3048     * Return serial number stored in user directory inode.
3049     *
3050     * @return parsed serial number, or -1 if not set
3051     */
3052    private static int getSerialNumber(File file) throws IOException {
3053        try {
3054            final byte[] buf = new byte[256];
3055            final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
3056            final String serial = new String(buf, 0, len);
3057            try {
3058                return Integer.parseInt(serial);
3059            } catch (NumberFormatException e) {
3060                throw new IOException("Bad serial number: " + serial);
3061            }
3062        } catch (ErrnoException e) {
3063            if (e.errno == OsConstants.ENODATA) {
3064                return -1;
3065            } else {
3066                throw e.rethrowAsIOException();
3067            }
3068        }
3069    }
3070
3071    @Override
3072    public void setSeedAccountData(int userId, String accountName, String accountType,
3073            PersistableBundle accountOptions, boolean persist) {
3074        checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3075        synchronized (mPackagesLock) {
3076            final UserData userData;
3077            synchronized (mUsersLock) {
3078                userData = getUserDataLU(userId);
3079                if (userData == null) {
3080                    Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3081                    return;
3082                }
3083                userData.seedAccountName = accountName;
3084                userData.seedAccountType = accountType;
3085                userData.seedAccountOptions = accountOptions;
3086                userData.persistSeedData = persist;
3087            }
3088            if (persist) {
3089                writeUserLP(userData);
3090            }
3091        }
3092    }
3093
3094    @Override
3095    public String getSeedAccountName() throws RemoteException {
3096        checkManageUsersPermission("Cannot get seed account information");
3097        synchronized (mUsersLock) {
3098            UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3099            return userData.seedAccountName;
3100        }
3101    }
3102
3103    @Override
3104    public String getSeedAccountType() throws RemoteException {
3105        checkManageUsersPermission("Cannot get seed account information");
3106        synchronized (mUsersLock) {
3107            UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3108            return userData.seedAccountType;
3109        }
3110    }
3111
3112    @Override
3113    public PersistableBundle getSeedAccountOptions() throws RemoteException {
3114        checkManageUsersPermission("Cannot get seed account information");
3115        synchronized (mUsersLock) {
3116            UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3117            return userData.seedAccountOptions;
3118        }
3119    }
3120
3121    @Override
3122    public void clearSeedAccountData() throws RemoteException {
3123        checkManageUsersPermission("Cannot clear seed account information");
3124        synchronized (mPackagesLock) {
3125            UserData userData;
3126            synchronized (mUsersLock) {
3127                userData = getUserDataLU(UserHandle.getCallingUserId());
3128                if (userData == null) return;
3129                userData.clearSeedAccountData();
3130            }
3131            writeUserLP(userData);
3132        }
3133    }
3134
3135    @Override
3136    public boolean someUserHasSeedAccount(String accountName, String accountType)
3137            throws RemoteException {
3138        checkManageUsersPermission("Cannot check seed account information");
3139        synchronized (mUsersLock) {
3140            final int userSize = mUsers.size();
3141            for (int i = 0; i < userSize; i++) {
3142                final UserData data = mUsers.valueAt(i);
3143                if (data.info.isInitialized()) continue;
3144                if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3145                    continue;
3146                }
3147                if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3148                    continue;
3149                }
3150                return true;
3151            }
3152        }
3153        return false;
3154    }
3155
3156    @Override
3157    public void onShellCommand(FileDescriptor in, FileDescriptor out,
3158            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3159        (new Shell()).exec(this, in, out, err, args, resultReceiver);
3160    }
3161
3162    int onShellCommand(Shell shell, String cmd) {
3163        if (cmd == null) {
3164            return shell.handleDefaultCommands(cmd);
3165        }
3166
3167        final PrintWriter pw = shell.getOutPrintWriter();
3168        try {
3169            switch(cmd) {
3170                case "list":
3171                    return runList(pw);
3172            }
3173        } catch (RemoteException e) {
3174            pw.println("Remote exception: " + e);
3175        }
3176        return -1;
3177    }
3178
3179    private int runList(PrintWriter pw) throws RemoteException {
3180        final IActivityManager am = ActivityManagerNative.getDefault();
3181        final List<UserInfo> users = getUsers(false);
3182        if (users == null) {
3183            pw.println("Error: couldn't get users");
3184            return 1;
3185        } else {
3186            pw.println("Users:");
3187            for (int i = 0; i < users.size(); i++) {
3188                String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
3189                pw.println("\t" + users.get(i).toString() + running);
3190            }
3191            return 0;
3192        }
3193    }
3194
3195    @Override
3196    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3197        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3198                != PackageManager.PERMISSION_GRANTED) {
3199            pw.println("Permission Denial: can't dump UserManager from from pid="
3200                    + Binder.getCallingPid()
3201                    + ", uid=" + Binder.getCallingUid()
3202                    + " without permission "
3203                    + android.Manifest.permission.DUMP);
3204            return;
3205        }
3206
3207        long now = System.currentTimeMillis();
3208        StringBuilder sb = new StringBuilder();
3209        synchronized (mPackagesLock) {
3210            synchronized (mUsersLock) {
3211                pw.println("Users:");
3212                for (int i = 0; i < mUsers.size(); i++) {
3213                    UserData userData = mUsers.valueAt(i);
3214                    if (userData == null) {
3215                        continue;
3216                    }
3217                    UserInfo userInfo = userData.info;
3218                    final int userId = userInfo.id;
3219                    pw.print("  "); pw.print(userInfo);
3220                    pw.print(" serialNo="); pw.print(userInfo.serialNumber);
3221                    if (mRemovingUserIds.get(userId)) {
3222                        pw.print(" <removing> ");
3223                    }
3224                    if (userInfo.partial) {
3225                        pw.print(" <partial>");
3226                    }
3227                    pw.println();
3228                    pw.print("    Created: ");
3229                    if (userInfo.creationTime == 0) {
3230                        pw.println("<unknown>");
3231                    } else {
3232                        sb.setLength(0);
3233                        TimeUtils.formatDuration(now - userInfo.creationTime, sb);
3234                        sb.append(" ago");
3235                        pw.println(sb);
3236                    }
3237                    pw.print("    Last logged in: ");
3238                    if (userInfo.lastLoggedInTime == 0) {
3239                        pw.println("<unknown>");
3240                    } else {
3241                        sb.setLength(0);
3242                        TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
3243                        sb.append(" ago");
3244                        pw.println(sb);
3245                    }
3246                    pw.print("    Last logged in fingerprint: ");
3247                    pw.println(userInfo.lastLoggedInFingerprint);
3248                    pw.print("    Has profile owner: ");
3249                    pw.println(mIsUserManaged.get(userId));
3250                    pw.println("    Restrictions:");
3251                    synchronized (mRestrictionsLock) {
3252                        UserRestrictionsUtils.dumpRestrictions(
3253                                pw, "      ", mBaseUserRestrictions.get(userInfo.id));
3254                        pw.println("    Device policy local restrictions:");
3255                        UserRestrictionsUtils.dumpRestrictions(
3256                                pw, "      ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
3257                        pw.println("    Effective restrictions:");
3258                        UserRestrictionsUtils.dumpRestrictions(
3259                                pw, "      ", mCachedEffectiveUserRestrictions.get(userInfo.id));
3260                    }
3261
3262                    if (userData.account != null) {
3263                        pw.print("    Account name: " + userData.account);
3264                        pw.println();
3265                    }
3266
3267                    if (userData.seedAccountName != null) {
3268                        pw.print("    Seed account name: " + userData.seedAccountName);
3269                        pw.println();
3270                        if (userData.seedAccountType != null) {
3271                            pw.print("         account type: " + userData.seedAccountType);
3272                            pw.println();
3273                        }
3274                        if (userData.seedAccountOptions != null) {
3275                            pw.print("         account options exist");
3276                            pw.println();
3277                        }
3278                    }
3279                }
3280            }
3281            pw.println();
3282            pw.println("  Device policy global restrictions:");
3283            synchronized (mRestrictionsLock) {
3284                UserRestrictionsUtils
3285                        .dumpRestrictions(pw, "    ", mDevicePolicyGlobalUserRestrictions);
3286            }
3287            pw.println();
3288            pw.println("  Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3289            pw.println();
3290            pw.println("  Guest restrictions:");
3291            synchronized (mGuestRestrictions) {
3292                UserRestrictionsUtils.dumpRestrictions(pw, "    ", mGuestRestrictions);
3293            }
3294            synchronized (mUsersLock) {
3295                pw.println();
3296                pw.println("  Device managed: " + mIsDeviceManaged);
3297            }
3298            synchronized (mUserStates) {
3299                pw.println("  Started users state: " + mUserStates);
3300            }
3301            // Dump some capabilities
3302            pw.println();
3303            pw.println("  Max users: " + UserManager.getMaxSupportedUsers());
3304            pw.println("  Supports switchable users: " + UserManager.supportsMultipleUsers());
3305            pw.println("  All guests ephemeral: " + Resources.getSystem().getBoolean(
3306                    com.android.internal.R.bool.config_guestUserEphemeral));
3307        }
3308    }
3309
3310    final class MainHandler extends Handler {
3311
3312        @Override
3313        public void handleMessage(Message msg) {
3314            switch (msg.what) {
3315                case WRITE_USER_MSG:
3316                    removeMessages(WRITE_USER_MSG, msg.obj);
3317                    synchronized (mPackagesLock) {
3318                        int userId = ((UserData) msg.obj).info.id;
3319                        UserData userData = getUserDataNoChecks(userId);
3320                        if (userData != null) {
3321                            writeUserLP(userData);
3322                        }
3323                    }
3324            }
3325        }
3326    }
3327
3328    /**
3329     * @param userId
3330     * @return whether the user has been initialized yet
3331     */
3332    boolean isInitialized(int userId) {
3333        return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3334    }
3335
3336    private class LocalService extends UserManagerInternal {
3337        @Override
3338        public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3339                @Nullable Bundle globalRestrictions) {
3340            UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
3341                    globalRestrictions);
3342        }
3343
3344        @Override
3345        public Bundle getBaseUserRestrictions(int userId) {
3346            synchronized (mRestrictionsLock) {
3347                return mBaseUserRestrictions.get(userId);
3348            }
3349        }
3350
3351        @Override
3352        public void setBaseUserRestrictionsByDpmsForMigration(
3353                int userId, Bundle baseRestrictions) {
3354            synchronized (mRestrictionsLock) {
3355                mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
3356                invalidateEffectiveUserRestrictionsLR(userId);
3357            }
3358
3359            final UserData userData = getUserDataNoChecks(userId);
3360            synchronized (mPackagesLock) {
3361                if (userData != null) {
3362                    writeUserLP(userData);
3363                } else {
3364                    Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3365                }
3366            }
3367        }
3368
3369        @Override
3370        public boolean getUserRestriction(int userId, String key) {
3371            return getUserRestrictions(userId).getBoolean(key);
3372        }
3373
3374        @Override
3375        public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3376            synchronized (mUserRestrictionsListeners) {
3377                mUserRestrictionsListeners.add(listener);
3378            }
3379        }
3380
3381        @Override
3382        public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3383            synchronized (mUserRestrictionsListeners) {
3384                mUserRestrictionsListeners.remove(listener);
3385            }
3386        }
3387
3388        @Override
3389        public void setDeviceManaged(boolean isManaged) {
3390            synchronized (mUsersLock) {
3391                mIsDeviceManaged = isManaged;
3392            }
3393        }
3394
3395        @Override
3396        public void setUserManaged(int userId, boolean isManaged) {
3397            synchronized (mUsersLock) {
3398                mIsUserManaged.put(userId, isManaged);
3399            }
3400        }
3401
3402        @Override
3403        public void setUserIcon(int userId, Bitmap bitmap) {
3404            long ident = Binder.clearCallingIdentity();
3405            try {
3406                synchronized (mPackagesLock) {
3407                    UserData userData = getUserDataNoChecks(userId);
3408                    if (userData == null || userData.info.partial) {
3409                        Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3410                        return;
3411                    }
3412                    writeBitmapLP(userData.info, bitmap);
3413                    writeUserLP(userData);
3414                }
3415                sendUserInfoChangedBroadcast(userId);
3416            } finally {
3417                Binder.restoreCallingIdentity(ident);
3418            }
3419        }
3420
3421        @Override
3422        public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3423            synchronized (mUsersLock) {
3424                mForceEphemeralUsers = forceEphemeralUsers;
3425            }
3426        }
3427
3428        @Override
3429        public void removeAllUsers() {
3430            if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3431                // Remove the non-system users straight away.
3432                removeNonSystemUsers();
3433            } else {
3434                // Switch to the system user first and then remove the other users.
3435                BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3436                    @Override
3437                    public void onReceive(Context context, Intent intent) {
3438                        int userId =
3439                                intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3440                        if (userId != UserHandle.USER_SYSTEM) {
3441                            return;
3442                        }
3443                        mContext.unregisterReceiver(this);
3444                        removeNonSystemUsers();
3445                    }
3446                };
3447                IntentFilter userSwitchedFilter = new IntentFilter();
3448                userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3449                mContext.registerReceiver(
3450                        userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3451
3452                // Switch to the system user.
3453                ActivityManager am =
3454                        (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3455                am.switchUser(UserHandle.USER_SYSTEM);
3456            }
3457        }
3458
3459        @Override
3460        public void onEphemeralUserStop(int userId) {
3461            synchronized (mUsersLock) {
3462               UserInfo userInfo = getUserInfoLU(userId);
3463               if (userInfo != null && userInfo.isEphemeral()) {
3464                    // Do not allow switching back to the ephemeral user again as the user is going
3465                    // to be deleted.
3466                    userInfo.flags |= UserInfo.FLAG_DISABLED;
3467                    if (userInfo.isGuest()) {
3468                        // Indicate that the guest will be deleted after it stops.
3469                        userInfo.guestToRemove = true;
3470                    }
3471               }
3472            }
3473        }
3474
3475        @Override
3476        public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3477            UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3478            // Keep this in sync with UserManager.createUser
3479            if (user != null && !user.isAdmin()) {
3480                setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3481                setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3482            }
3483            return user;
3484        }
3485
3486        @Override
3487        public boolean isUserRunning(int userId) {
3488            synchronized (mUserStates) {
3489                return mUserStates.get(userId, -1) >= 0;
3490            }
3491        }
3492
3493        @Override
3494        public void setUserState(int userId, int userState) {
3495            synchronized (mUserStates) {
3496                mUserStates.put(userId, userState);
3497            }
3498        }
3499
3500        @Override
3501        public void removeUserState(int userId) {
3502            synchronized (mUserStates) {
3503                mUserStates.delete(userId);
3504            }
3505        }
3506
3507        @Override
3508        public boolean isUserUnlockingOrUnlocked(int userId) {
3509            synchronized (mUserStates) {
3510                int state = mUserStates.get(userId, -1);
3511                return (state == UserState.STATE_RUNNING_UNLOCKING)
3512                        || (state == UserState.STATE_RUNNING_UNLOCKED);
3513            }
3514        }
3515
3516        @Override
3517        public boolean isUserUnlocked(int userId) {
3518            synchronized (mUserStates) {
3519                int state = mUserStates.get(userId, -1);
3520                return state == UserState.STATE_RUNNING_UNLOCKED;
3521            }
3522        }
3523    }
3524
3525    /* Remove all the users except of the system one. */
3526    private void removeNonSystemUsers() {
3527        ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3528        synchronized (mUsersLock) {
3529            final int userSize = mUsers.size();
3530            for (int i = 0; i < userSize; i++) {
3531                UserInfo ui = mUsers.valueAt(i).info;
3532                if (ui.id != UserHandle.USER_SYSTEM) {
3533                    usersToRemove.add(ui);
3534                }
3535            }
3536        }
3537        for (UserInfo ui: usersToRemove) {
3538            removeUser(ui.id);
3539        }
3540    }
3541
3542    private class Shell extends ShellCommand {
3543        @Override
3544        public int onCommand(String cmd) {
3545            return onShellCommand(this, cmd);
3546        }
3547
3548        @Override
3549        public void onHelp() {
3550            final PrintWriter pw = getOutPrintWriter();
3551            pw.println("User manager (user) commands:");
3552            pw.println("  help");
3553            pw.println("    Print this help text.");
3554            pw.println("");
3555            pw.println("  list");
3556            pw.println("    Prints all users on the system.");
3557        }
3558    }
3559
3560    private static void debug(String message) {
3561        Log.d(LOG_TAG, message +
3562                (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, "  ") : ""));
3563    }
3564}
3565