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