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