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