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