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