UserManagerService.java revision eb437d4dffb310857e19bb619778dc5b6b7febff
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.SystemApi;
26import android.annotation.UserIdInt;
27import android.app.Activity;
28import android.app.ActivityManager;
29import android.app.ActivityManagerInternal;
30import android.app.ActivityManagerNative;
31import android.app.AppGlobals;
32import android.app.IActivityManager;
33import android.app.IStopUserCallback;
34import android.app.KeyguardManager;
35import android.app.admin.DevicePolicyManager;
36import android.content.BroadcastReceiver;
37import android.content.ComponentName;
38import android.content.Context;
39import android.content.Intent;
40import android.content.IntentFilter;
41import android.content.IntentSender;
42import android.content.pm.PackageManager;
43import android.content.pm.PackageManager.NameNotFoundException;
44import android.content.pm.UserInfo;
45import android.content.res.Resources;
46import android.graphics.Bitmap;
47import android.os.Binder;
48import android.os.Build;
49import android.os.Bundle;
50import android.os.Debug;
51import android.os.Environment;
52import android.os.FileUtils;
53import android.os.Handler;
54import android.os.IBinder;
55import android.os.IUserManager;
56import android.os.Message;
57import android.os.ParcelFileDescriptor;
58import android.os.Parcelable;
59import android.os.PersistableBundle;
60import android.os.Process;
61import android.os.RemoteException;
62import android.os.ResultReceiver;
63import android.os.SELinux;
64import android.os.ServiceManager;
65import android.os.ShellCommand;
66import android.os.UserHandle;
67import android.os.UserManager;
68import android.os.UserManagerInternal;
69import android.os.UserManagerInternal.UserRestrictionsListener;
70import android.os.storage.StorageManager;
71import android.system.ErrnoException;
72import android.system.Os;
73import android.system.OsConstants;
74import android.text.TextUtils;
75import android.util.AtomicFile;
76import android.util.IntArray;
77import android.util.Log;
78import android.util.Slog;
79import android.util.SparseArray;
80import android.util.SparseBooleanArray;
81import android.util.TimeUtils;
82import android.util.Xml;
83
84import com.android.internal.annotations.GuardedBy;
85import com.android.internal.annotations.VisibleForTesting;
86import com.android.internal.app.IAppOpsService;
87import com.android.internal.logging.MetricsLogger;
88import com.android.internal.util.FastXmlSerializer;
89import com.android.internal.util.Preconditions;
90import com.android.internal.util.XmlUtils;
91import com.android.internal.widget.LockPatternUtils;
92import com.android.server.LocalServices;
93
94import libcore.io.IoUtils;
95import libcore.util.Objects;
96
97import org.xmlpull.v1.XmlPullParser;
98import org.xmlpull.v1.XmlPullParserException;
99import org.xmlpull.v1.XmlSerializer;
100
101import java.io.BufferedOutputStream;
102import java.io.File;
103import java.io.FileDescriptor;
104import java.io.FileInputStream;
105import java.io.FileNotFoundException;
106import java.io.FileOutputStream;
107import java.io.IOException;
108import java.io.PrintWriter;
109import java.nio.charset.StandardCharsets;
110import java.util.ArrayList;
111import java.util.List;
112
113/**
114 * Service for {@link UserManager}.
115 *
116 * Method naming convention:
117 * <ul>
118 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
119 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
120 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
121 * </ul>
122 */
123public class UserManagerService extends IUserManager.Stub {
124    private static final String LOG_TAG = "UserManagerService";
125    static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
126    private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
127
128    private static final String TAG_NAME = "name";
129    private static final String TAG_ACCOUNT = "account";
130    private static final String ATTR_FLAGS = "flags";
131    private static final String ATTR_ICON_PATH = "icon";
132    private static final String ATTR_ID = "id";
133    private static final String ATTR_CREATION_TIME = "created";
134    private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
135    private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
136    private static final String ATTR_SERIAL_NO = "serialNumber";
137    private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
138    private static final String ATTR_PARTIAL = "partial";
139    private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
140    private static final String ATTR_USER_VERSION = "version";
141    private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
142    private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
143    private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
144    private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
145    private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
146    private static final String TAG_USERS = "users";
147    private static final String TAG_USER = "user";
148    private static final String TAG_RESTRICTIONS = "restrictions";
149    private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
150    private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
151    private static final String TAG_ENTRY = "entry";
152    private static final String TAG_VALUE = "value";
153    private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
154    private static final String ATTR_KEY = "key";
155    private static final String ATTR_VALUE_TYPE = "type";
156    private static final String ATTR_MULTIPLE = "m";
157
158    private static final String ATTR_TYPE_STRING_ARRAY = "sa";
159    private static final String ATTR_TYPE_STRING = "s";
160    private static final String ATTR_TYPE_BOOLEAN = "b";
161    private static final String ATTR_TYPE_INTEGER = "i";
162    private static final String ATTR_TYPE_BUNDLE = "B";
163    private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
164
165    private static final String USER_INFO_DIR = "system" + File.separator + "users";
166    private static final String USER_LIST_FILENAME = "userlist.xml";
167    private static final String USER_PHOTO_FILENAME = "photo.png";
168    private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
169
170    private static final String RESTRICTIONS_FILE_PREFIX = "res_";
171    private static final String XML_SUFFIX = ".xml";
172
173    private static final int MIN_USER_ID = 10;
174    // We need to keep process uid within Integer.MAX_VALUE.
175    private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
176
177    private static final int USER_VERSION = 6;
178
179    private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
180
181    // Maximum number of managed profiles permitted per user is 1. This cannot be increased
182    // without first making sure that the rest of the framework is prepared for it.
183    private static final int MAX_MANAGED_PROFILES = 1;
184
185    static final int WRITE_USER_MSG = 1;
186    static final int WRITE_USER_DELAY = 2*1000;  // 2 seconds
187
188    private static final String XATTR_SERIAL = "user.serial";
189
190    // Tron counters
191    private static final String TRON_GUEST_CREATED = "users_guest_created";
192    private static final String TRON_USER_CREATED = "users_user_created";
193
194    private final Context mContext;
195    private final PackageManagerService mPm;
196    private final Object mPackagesLock;
197    // Short-term lock for internal state, when interaction/sync with PM is not required
198    private final Object mUsersLock = new Object();
199    private final Object mRestrictionsLock = new Object();
200
201    private final Handler mHandler;
202
203    private final File mUsersDir;
204    private final File mUserListFile;
205
206    private static final IBinder mUserRestriconToken = new Binder();
207
208    /**
209     * User-related information that is used for persisting to flash. Only UserInfo is
210     * directly exposed to other system apps.
211     */
212    private static class UserData {
213        // Basic user information and properties
214        UserInfo info;
215        // Account name used when there is a strong association between a user and an account
216        String account;
217        // Account information for seeding into a newly created user. This could also be
218        // used for login validation for an existing user, for updating their credentials.
219        // In the latter case, data may not need to be persisted as it is only valid for the
220        // current login session.
221        String seedAccountName;
222        String seedAccountType;
223        PersistableBundle seedAccountOptions;
224        // Whether to perist the seed account information to be available after a boot
225        boolean persistSeedData;
226
227        void clearSeedAccountData() {
228            seedAccountName = null;
229            seedAccountType = null;
230            seedAccountOptions = null;
231            persistSeedData = false;
232        }
233    }
234
235    @GuardedBy("mUsersLock")
236    private final SparseArray<UserData> mUsers = new SparseArray<>();
237
238    /**
239     * User restrictions set via UserManager.  This doesn't include restrictions set by
240     * device owner / profile owners.
241     *
242     * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
243     * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
244     * maybe shared between {@link #mBaseUserRestrictions} and
245     * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
246     * (Otherwise we won't be able to detect what restrictions have changed in
247     * {@link #updateUserRestrictionsInternalLR}.
248     */
249    @GuardedBy("mRestrictionsLock")
250    private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
251
252    /**
253     * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
254     * with device / profile owner restrictions.  We'll initialize it lazily; use
255     * {@link #getEffectiveUserRestrictions} to access it.
256     *
257     * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
258     * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
259     * maybe shared between {@link #mBaseUserRestrictions} and
260     * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
261     * (Otherwise we won't be able to detect what restrictions have changed in
262     * {@link #updateUserRestrictionsInternalLR}.
263     */
264    @GuardedBy("mRestrictionsLock")
265    private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
266
267    /**
268     * User restrictions that have already been applied in
269     * {@link #updateUserRestrictionsInternalLR(Bundle, int)}.  We use it to detect restrictions
270     * that have changed since the last
271     * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
272     */
273    @GuardedBy("mRestrictionsLock")
274    private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
275
276    /**
277     * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
278     * that should be applied to all users, including guests.
279     */
280    @GuardedBy("mRestrictionsLock")
281    private Bundle mDevicePolicyGlobalUserRestrictions;
282
283    /**
284     * Id of the user that set global restrictions.
285     */
286    @GuardedBy("mRestrictionsLock")
287    private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
288
289    /**
290     * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
291     * for each user.
292     */
293    @GuardedBy("mRestrictionsLock")
294    private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
295
296    @GuardedBy("mGuestRestrictions")
297    private final Bundle mGuestRestrictions = new Bundle();
298
299    /**
300     * Set of user IDs being actively removed. Removed IDs linger in this set
301     * for several seconds to work around a VFS caching issue.
302     */
303    @GuardedBy("mUsersLock")
304    private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
305
306    @GuardedBy("mUsersLock")
307    private int[] mUserIds;
308    @GuardedBy("mPackagesLock")
309    private int mNextSerialNumber;
310    private int mUserVersion = 0;
311
312    private IAppOpsService mAppOpsService;
313
314    private final LocalService mLocalService;
315
316    @GuardedBy("mUsersLock")
317    private boolean mIsDeviceManaged;
318
319    @GuardedBy("mUsersLock")
320    private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
321
322    @GuardedBy("mUserRestrictionsListeners")
323    private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
324            new ArrayList<>();
325
326    private final LockPatternUtils mLockPatternUtils;
327
328    /**
329     * Whether all users should be created ephemeral.
330     */
331    @GuardedBy("mUsersLock")
332    private boolean mForceEphemeralUsers;
333
334    @GuardedBy("mUsersLock")
335    private final SparseBooleanArray mUnlockingOrUnlockedUsers = new SparseBooleanArray();
336
337    private static UserManagerService sInstance;
338
339    public static UserManagerService getInstance() {
340        synchronized (UserManagerService.class) {
341            return sInstance;
342        }
343    }
344
345    @VisibleForTesting
346    UserManagerService(File dataDir) {
347        this(null, null, new Object(), dataDir);
348    }
349
350    /**
351     * Called by package manager to create the service.  This is closely
352     * associated with the package manager, and the given lock is the
353     * package manager's own lock.
354     */
355    UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
356        this(context, pm, packagesLock, Environment.getDataDirectory());
357    }
358
359    private UserManagerService(Context context, PackageManagerService pm,
360            Object packagesLock, File dataDir) {
361        mContext = context;
362        mPm = pm;
363        mPackagesLock = packagesLock;
364        mHandler = new MainHandler();
365        synchronized (mPackagesLock) {
366            mUsersDir = new File(dataDir, USER_INFO_DIR);
367            mUsersDir.mkdirs();
368            // Make zeroth user directory, for services to migrate their files to that location
369            File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
370            userZeroDir.mkdirs();
371            FileUtils.setPermissions(mUsersDir.toString(),
372                    FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
373                    -1, -1);
374            mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
375            initDefaultGuestRestrictions();
376            readUserListLP();
377            sInstance = this;
378        }
379        mLocalService = new LocalService();
380        LocalServices.addService(UserManagerInternal.class, mLocalService);
381        mLockPatternUtils = new LockPatternUtils(mContext);
382    }
383
384    void systemReady() {
385        // Prune out any partially created, partially removed and ephemeral users.
386        ArrayList<UserInfo> partials = new ArrayList<>();
387        synchronized (mUsersLock) {
388            final int userSize = mUsers.size();
389            for (int i = 0; i < userSize; i++) {
390                UserInfo ui = mUsers.valueAt(i).info;
391                if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
392                    partials.add(ui);
393                }
394            }
395        }
396        final int partialsSize = partials.size();
397        for (int i = 0; i < partialsSize; i++) {
398            UserInfo ui = partials.get(i);
399            Slog.w(LOG_TAG, "Removing partially created user " + ui.id
400                    + " (name=" + ui.name + ")");
401            removeUserState(ui.id);
402        }
403
404        mAppOpsService = IAppOpsService.Stub.asInterface(
405                ServiceManager.getService(Context.APP_OPS_SERVICE));
406
407        synchronized (mRestrictionsLock) {
408            applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
409        }
410
411        UserInfo currentGuestUser = findCurrentGuestUser();
412        if (currentGuestUser != null && !hasUserRestriction(
413                UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
414            // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
415            // to it, in case this guest was created in a previous version where this
416            // user restriction was not a default guest restriction.
417            setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
418        }
419
420        maybeInitializeDemoMode(UserHandle.USER_SYSTEM);
421}
422
423    @Override
424    public String getUserAccount(int userId) {
425        checkManageUserAndAcrossUsersFullPermission("get user account");
426        synchronized (mUsersLock) {
427            return mUsers.get(userId).account;
428        }
429    }
430
431    @Override
432    public void setUserAccount(int userId, String accountName) {
433        checkManageUserAndAcrossUsersFullPermission("set user account");
434        UserData userToUpdate = null;
435        synchronized (mPackagesLock) {
436            synchronized (mUsersLock) {
437                final UserData userData = mUsers.get(userId);
438                if (userData == null) {
439                    Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
440                    return;
441                }
442                String currentAccount = userData.account;
443                if (!Objects.equal(currentAccount, accountName)) {
444                    userData.account = accountName;
445                    userToUpdate = userData;
446                }
447            }
448
449            if (userToUpdate != null) {
450                writeUserLP(userToUpdate);
451            }
452        }
453    }
454
455    @Override
456    public UserInfo getPrimaryUser() {
457        checkManageUsersPermission("query users");
458        synchronized (mUsersLock) {
459            final int userSize = mUsers.size();
460            for (int i = 0; i < userSize; i++) {
461                UserInfo ui = mUsers.valueAt(i).info;
462                if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
463                    return ui;
464                }
465            }
466        }
467        return null;
468    }
469
470    @Override
471    public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
472        checkManageUsersPermission("query users");
473        synchronized (mUsersLock) {
474            ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
475            final int userSize = mUsers.size();
476            for (int i = 0; i < userSize; i++) {
477                UserInfo ui = mUsers.valueAt(i).info;
478                if (ui.partial) {
479                    continue;
480                }
481                if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
482                    users.add(userWithName(ui));
483                }
484            }
485            return users;
486        }
487    }
488
489    @Override
490    public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
491        boolean returnFullInfo = true;
492        if (userId != UserHandle.getCallingUserId()) {
493            checkManageUsersPermission("getting profiles related to user " + userId);
494        } else {
495            returnFullInfo = hasManageUsersPermission();
496        }
497        final long ident = Binder.clearCallingIdentity();
498        try {
499            synchronized (mUsersLock) {
500                return getProfilesLU(userId, enabledOnly, returnFullInfo);
501            }
502        } finally {
503            Binder.restoreCallingIdentity(ident);
504        }
505    }
506
507    @Override
508    public int[] getProfileIds(int userId, boolean enabledOnly) {
509        if (userId != UserHandle.getCallingUserId()) {
510            checkManageUsersPermission("getting profiles related to user " + userId);
511        }
512        final long ident = Binder.clearCallingIdentity();
513        try {
514            synchronized (mUsersLock) {
515                return getProfileIdsLU(userId, enabledOnly).toArray();
516            }
517        } finally {
518            Binder.restoreCallingIdentity(ident);
519        }
520    }
521
522    /** Assume permissions already checked and caller's identity cleared */
523    private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
524        IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
525        ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
526        for (int i = 0; i < profileIds.size(); i++) {
527            int profileId = profileIds.get(i);
528            UserInfo userInfo = mUsers.get(profileId).info;
529            // If full info is not required - clear PII data to prevent 3P apps from reading it
530            if (!fullInfo) {
531                userInfo = new UserInfo(userInfo);
532                userInfo.name = null;
533                userInfo.iconPath = null;
534            } else {
535                userInfo = userWithName(userInfo);
536            }
537            users.add(userInfo);
538        }
539        return users;
540    }
541
542    /**
543     *  Assume permissions already checked and caller's identity cleared
544     */
545    private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
546        UserInfo user = getUserInfoLU(userId);
547        IntArray result = new IntArray(mUsers.size());
548        if (user == null) {
549            // Probably a dying user
550            return result;
551        }
552        final int userSize = mUsers.size();
553        for (int i = 0; i < userSize; i++) {
554            UserInfo profile = mUsers.valueAt(i).info;
555            if (!isProfileOf(user, profile)) {
556                continue;
557            }
558            if (enabledOnly && !profile.isEnabled()) {
559                continue;
560            }
561            if (mRemovingUserIds.get(profile.id)) {
562                continue;
563            }
564            if (profile.partial) {
565                continue;
566            }
567            result.add(profile.id);
568        }
569        return result;
570    }
571
572    @Override
573    public int getCredentialOwnerProfile(int userHandle) {
574        checkManageUsersPermission("get the credential owner");
575        if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
576            synchronized (mUsersLock) {
577                UserInfo profileParent = getProfileParentLU(userHandle);
578                if (profileParent != null) {
579                    return profileParent.id;
580                }
581            }
582        }
583
584        return userHandle;
585    }
586
587    @Override
588    public boolean isSameProfileGroup(int userId, int otherUserId) {
589        if (userId == otherUserId) return true;
590        checkManageUsersPermission("check if in the same profile group");
591        synchronized (mPackagesLock) {
592            return isSameProfileGroupLP(userId, otherUserId);
593        }
594    }
595
596    private boolean isSameProfileGroupLP(int userId, int otherUserId) {
597        synchronized (mUsersLock) {
598            UserInfo userInfo = getUserInfoLU(userId);
599            if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
600                return false;
601            }
602            UserInfo otherUserInfo = getUserInfoLU(otherUserId);
603            if (otherUserInfo == null
604                    || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
605                return false;
606            }
607            return userInfo.profileGroupId == otherUserInfo.profileGroupId;
608        }
609    }
610
611    @Override
612    public UserInfo getProfileParent(int userHandle) {
613        checkManageUsersPermission("get the profile parent");
614        synchronized (mUsersLock) {
615            return getProfileParentLU(userHandle);
616        }
617    }
618
619    private UserInfo getProfileParentLU(int userHandle) {
620        UserInfo profile = getUserInfoLU(userHandle);
621        if (profile == null) {
622            return null;
623        }
624        int parentUserId = profile.profileGroupId;
625        if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
626            return null;
627        } else {
628            return getUserInfoLU(parentUserId);
629        }
630    }
631
632    private static boolean isProfileOf(UserInfo user, UserInfo profile) {
633        return user.id == profile.id ||
634                (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
635                && user.profileGroupId == profile.profileGroupId);
636    }
637
638    private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
639            UserHandle parentHandle, boolean inQuietMode) {
640        Intent intent = new Intent();
641        if (inQuietMode) {
642            intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
643        } else {
644            intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
645        }
646        intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
647        intent.putExtra(Intent.EXTRA_USER, profileHandle);
648        intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
649        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
650        mContext.sendBroadcastAsUser(intent, parentHandle);
651    }
652
653    @Override
654    public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
655        checkManageUsersPermission("silence profile");
656        boolean changed = false;
657        UserInfo profile, parent;
658        synchronized (mPackagesLock) {
659            synchronized (mUsersLock) {
660                profile = getUserInfoLU(userHandle);
661                parent = getProfileParentLU(userHandle);
662
663            }
664            if (profile == null || !profile.isManagedProfile()) {
665                throw new IllegalArgumentException("User " + userHandle + " is not a profile");
666            }
667            if (profile.isQuietModeEnabled() != enableQuietMode) {
668                profile.flags ^= UserInfo.FLAG_QUIET_MODE;
669                writeUserLP(getUserDataLU(profile.id));
670                changed = true;
671            }
672        }
673        if (changed) {
674            long identity = Binder.clearCallingIdentity();
675            try {
676                if (enableQuietMode) {
677                    LocalServices.getService(ActivityManagerInternal.class)
678                            .killForegroundAppsForUser(userHandle);
679                    ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
680                } else {
681                    ActivityManagerNative.getDefault().startUserInBackground(userHandle);
682                }
683            } catch (RemoteException e) {
684                Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
685            } finally {
686                Binder.restoreCallingIdentity(identity);
687            }
688
689            broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
690                    enableQuietMode);
691        }
692    }
693
694    @Override
695    public boolean isQuietModeEnabled(int userHandle) {
696        synchronized (mPackagesLock) {
697            UserInfo info;
698            synchronized (mUsersLock) {
699                info = getUserInfoLU(userHandle);
700            }
701            if (info == null || !info.isManagedProfile()) {
702                return false;
703            }
704            return info.isQuietModeEnabled();
705        }
706    }
707
708    @Override
709    public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
710        if (StorageManager.isUserKeyUnlocked(userHandle)
711                || !mLockPatternUtils.isSecure(userHandle)) {
712            // if the user is already unlocked, no need to show a profile challenge
713            setQuietModeEnabled(userHandle, false);
714            return true;
715        }
716
717        long identity = Binder.clearCallingIdentity();
718        try {
719            // otherwise, we show a profile challenge to trigger decryption of the user
720            final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
721                    Context.KEYGUARD_SERVICE);
722            // We should use userHandle not credentialOwnerUserId here, as even if it is unified
723            // lock, confirm screenlock page will know and show personal challenge, and unlock
724            // work profile when personal challenge is correct
725            final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
726                    userHandle);
727            if (unlockIntent == null) {
728                return false;
729            }
730            if (target != null) {
731                unlockIntent.putExtra(Intent.EXTRA_INTENT, target);
732            }
733            unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
734            mContext.startActivity(unlockIntent);
735        } finally {
736            Binder.restoreCallingIdentity(identity);
737        }
738        return false;
739    }
740
741    @Override
742    public void setUserEnabled(int userId) {
743        checkManageUsersPermission("enable user");
744        synchronized (mPackagesLock) {
745            UserInfo info;
746            synchronized (mUsersLock) {
747                info = getUserInfoLU(userId);
748            }
749            if (info != null && !info.isEnabled()) {
750                info.flags ^= UserInfo.FLAG_DISABLED;
751                writeUserLP(getUserDataLU(info.id));
752            }
753        }
754    }
755
756    @Override
757    public UserInfo getUserInfo(int userId) {
758        checkManageUsersPermission("query user");
759        synchronized (mUsersLock) {
760            return userWithName(getUserInfoLU(userId));
761        }
762    }
763
764    /**
765     * Returns a UserInfo object with the name filled in, for Owner, or the original
766     * if the name is already set.
767     */
768    private UserInfo userWithName(UserInfo orig) {
769        if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
770            UserInfo withName = new UserInfo(orig);
771            withName.name = getOwnerName();
772            return withName;
773        } else {
774            return orig;
775        }
776    }
777
778    @Override
779    public boolean isManagedProfile(int userId) {
780        int callingUserId = UserHandle.getCallingUserId();
781        if (callingUserId != userId && !hasManageUsersPermission()) {
782            synchronized (mPackagesLock) {
783                if (!isSameProfileGroupLP(callingUserId, userId)) {
784                    throw new SecurityException(
785                            "You need MANAGE_USERS permission to: check if specified user a " +
786                            "managed profile outside your profile group");
787                }
788            }
789        }
790        synchronized (mUsersLock) {
791            UserInfo userInfo =  getUserInfoLU(userId);
792            return userInfo != null && userInfo.isManagedProfile();
793        }
794    }
795
796    @Override
797    public boolean isRestricted() {
798        synchronized (mUsersLock) {
799            return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
800        }
801    }
802
803    @Override
804    public boolean canHaveRestrictedProfile(int userId) {
805        checkManageUsersPermission("canHaveRestrictedProfile");
806        synchronized (mUsersLock) {
807            final UserInfo userInfo = getUserInfoLU(userId);
808            if (userInfo == null || !userInfo.canHaveProfile()) {
809                return false;
810            }
811            if (!userInfo.isAdmin()) {
812                return false;
813            }
814            // restricted profile can be created if there is no DO set and the admin user has no PO;
815            return !mIsDeviceManaged && !mIsUserManaged.get(userId);
816        }
817    }
818
819    /*
820     * Should be locked on mUsers before calling this.
821     */
822    private UserInfo getUserInfoLU(int userId) {
823        final UserData userData = mUsers.get(userId);
824        // If it is partial and not in the process of being removed, return as unknown user.
825        if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
826            Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
827            return null;
828        }
829        return userData != null ? userData.info : null;
830    }
831
832    private UserData getUserDataLU(int userId) {
833        final UserData userData = mUsers.get(userId);
834        // If it is partial and not in the process of being removed, return as unknown user.
835        if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
836            return null;
837        }
838        return userData;
839    }
840
841    /**
842     * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
843     * <p>No permissions checking or any addition checks are made</p>
844     */
845    private UserInfo getUserInfoNoChecks(int userId) {
846        synchronized (mUsersLock) {
847            final UserData userData = mUsers.get(userId);
848            return userData != null ? userData.info : null;
849        }
850    }
851
852    /**
853     * Obtains {@link #mUsersLock} and return UserData from mUsers.
854     * <p>No permissions checking or any addition checks are made</p>
855     */
856    private UserData getUserDataNoChecks(int userId) {
857        synchronized (mUsersLock) {
858            return mUsers.get(userId);
859        }
860    }
861
862    /** Called by PackageManagerService */
863    public boolean exists(int userId) {
864        return getUserInfoNoChecks(userId) != null;
865    }
866
867    @Override
868    public void setUserName(int userId, String name) {
869        checkManageUsersPermission("rename users");
870        boolean changed = false;
871        synchronized (mPackagesLock) {
872            UserData userData = getUserDataNoChecks(userId);
873            if (userData == null || userData.info.partial) {
874                Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
875                return;
876            }
877            if (name != null && !name.equals(userData.info.name)) {
878                userData.info.name = name;
879                writeUserLP(userData);
880                changed = true;
881            }
882        }
883        if (changed) {
884            sendUserInfoChangedBroadcast(userId);
885        }
886    }
887
888    @Override
889    public void setUserIcon(int userId, Bitmap bitmap) {
890        checkManageUsersPermission("update users");
891        if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
892            Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
893            return;
894        }
895        mLocalService.setUserIcon(userId, bitmap);
896    }
897
898
899
900    private void sendUserInfoChangedBroadcast(int userId) {
901        Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
902        changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
903        changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
904        mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
905    }
906
907    @Override
908    public ParcelFileDescriptor getUserIcon(int targetUserId) {
909        String iconPath;
910        synchronized (mPackagesLock) {
911            UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
912            if (targetUserInfo == null || targetUserInfo.partial) {
913                Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
914                return null;
915            }
916
917            final int callingUserId = UserHandle.getCallingUserId();
918            final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
919            final int targetGroupId = targetUserInfo.profileGroupId;
920            final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
921                    && callingGroupId == targetGroupId);
922            if ((callingUserId != targetUserId) && !sameGroup) {
923                checkManageUsersPermission("get the icon of a user who is not related");
924            }
925
926            if (targetUserInfo.iconPath == null) {
927                return null;
928            }
929            iconPath = targetUserInfo.iconPath;
930        }
931
932        try {
933            return ParcelFileDescriptor.open(
934                    new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
935        } catch (FileNotFoundException e) {
936            Log.e(LOG_TAG, "Couldn't find icon file", e);
937        }
938        return null;
939    }
940
941    public void makeInitialized(int userId) {
942        checkManageUsersPermission("makeInitialized");
943        boolean scheduleWriteUser = false;
944        UserData userData;
945        synchronized (mUsersLock) {
946            userData = mUsers.get(userId);
947            if (userData == null || userData.info.partial) {
948                Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
949                return;
950            }
951            if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
952                userData.info.flags |= UserInfo.FLAG_INITIALIZED;
953                scheduleWriteUser = true;
954            }
955        }
956        if (scheduleWriteUser) {
957            scheduleWriteUser(userData);
958        }
959    }
960
961    /**
962     * If default guest restrictions haven't been initialized yet, add the basic
963     * restrictions.
964     */
965    private void initDefaultGuestRestrictions() {
966        synchronized (mGuestRestrictions) {
967            if (mGuestRestrictions.isEmpty()) {
968                mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
969                mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
970                mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
971                mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
972            }
973        }
974    }
975
976    @Override
977    public Bundle getDefaultGuestRestrictions() {
978        checkManageUsersPermission("getDefaultGuestRestrictions");
979        synchronized (mGuestRestrictions) {
980            return new Bundle(mGuestRestrictions);
981        }
982    }
983
984    @Override
985    public void setDefaultGuestRestrictions(Bundle restrictions) {
986        checkManageUsersPermission("setDefaultGuestRestrictions");
987        synchronized (mGuestRestrictions) {
988            mGuestRestrictions.clear();
989            mGuestRestrictions.putAll(restrictions);
990        }
991        synchronized (mPackagesLock) {
992            writeUserListLP();
993        }
994    }
995
996    /**
997     * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
998     */
999    void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
1000            @Nullable Bundle global) {
1001        Preconditions.checkNotNull(local);
1002        boolean globalChanged = false;
1003        boolean localChanged;
1004        synchronized (mRestrictionsLock) {
1005            if (global != null) {
1006                // Update global.
1007                globalChanged = !UserRestrictionsUtils.areEqual(
1008                        mDevicePolicyGlobalUserRestrictions, global);
1009                if (globalChanged) {
1010                    mDevicePolicyGlobalUserRestrictions = global;
1011                }
1012                // Remember the global restriction owner userId to be able to make a distinction
1013                // in getUserRestrictionSource on who set local policies.
1014                mGlobalRestrictionOwnerUserId = userId;
1015            } else {
1016                // When profile owner sets restrictions it passes null global bundle and we reset
1017                // global restriction owner userId.
1018                mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
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            mUnlockingOrUnlockedUsers.delete(userHandle);
2383        }
2384        synchronized (mRestrictionsLock) {
2385            mBaseUserRestrictions.remove(userHandle);
2386            mAppliedUserRestrictions.remove(userHandle);
2387            mCachedEffectiveUserRestrictions.remove(userHandle);
2388            mDevicePolicyLocalUserRestrictions.remove(userHandle);
2389        }
2390        // Update the user list
2391        synchronized (mPackagesLock) {
2392            writeUserListLP();
2393        }
2394        // Remove user file
2395        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2396        userFile.delete();
2397        updateUserIds();
2398
2399        // Now that we've purged all the metadata above, destroy the actual data
2400        // on disk; if we battery pull in here we'll finish cleaning up when
2401        // reconciling after reboot.
2402        mPm.destroyUserData(userHandle,
2403                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2404    }
2405
2406    private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
2407        Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
2408        managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2409                Intent.FLAG_RECEIVER_FOREGROUND);
2410        managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
2411        managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
2412        mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
2413    }
2414
2415    @Override
2416    public Bundle getApplicationRestrictions(String packageName) {
2417        return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2418    }
2419
2420    @Override
2421    public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
2422        if (UserHandle.getCallingUserId() != userId
2423                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
2424            checkSystemOrRoot("get application restrictions for other users/apps");
2425        }
2426        synchronized (mPackagesLock) {
2427            // Read the restrictions from XML
2428            return readApplicationRestrictionsLP(packageName, userId);
2429        }
2430    }
2431
2432    @Override
2433    public void setApplicationRestrictions(String packageName, Bundle restrictions,
2434            int userId) {
2435        checkSystemOrRoot("set application restrictions");
2436        if (restrictions != null) {
2437            restrictions.setDefusable(true);
2438        }
2439        synchronized (mPackagesLock) {
2440            if (restrictions == null || restrictions.isEmpty()) {
2441                cleanAppRestrictionsForPackage(packageName, userId);
2442            } else {
2443                // Write the restrictions to XML
2444                writeApplicationRestrictionsLP(packageName, restrictions, userId);
2445            }
2446        }
2447
2448        // Notify package of changes via an intent - only sent to explicitly registered receivers.
2449        Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2450        changeIntent.setPackage(packageName);
2451        changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2452        mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
2453    }
2454
2455    private int getUidForPackage(String packageName) {
2456        long ident = Binder.clearCallingIdentity();
2457        try {
2458            return mContext.getPackageManager().getApplicationInfo(packageName,
2459                    PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
2460        } catch (NameNotFoundException nnfe) {
2461            return -1;
2462        } finally {
2463            Binder.restoreCallingIdentity(ident);
2464        }
2465    }
2466
2467    private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
2468        AtomicFile restrictionsFile =
2469                new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2470                        packageToRestrictionsFileName(packageName)));
2471        return readApplicationRestrictionsLP(restrictionsFile);
2472    }
2473
2474    @VisibleForTesting
2475    static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
2476        final Bundle restrictions = new Bundle();
2477        final ArrayList<String> values = new ArrayList<>();
2478        if (!restrictionsFile.getBaseFile().exists()) {
2479            return restrictions;
2480        }
2481
2482        FileInputStream fis = null;
2483        try {
2484            fis = restrictionsFile.openRead();
2485            XmlPullParser parser = Xml.newPullParser();
2486            parser.setInput(fis, StandardCharsets.UTF_8.name());
2487            XmlUtils.nextElement(parser);
2488            if (parser.getEventType() != XmlPullParser.START_TAG) {
2489                Slog.e(LOG_TAG, "Unable to read restrictions file "
2490                        + restrictionsFile.getBaseFile());
2491                return restrictions;
2492            }
2493            while (parser.next() != XmlPullParser.END_DOCUMENT) {
2494                readEntry(restrictions, values, parser);
2495            }
2496        } catch (IOException|XmlPullParserException e) {
2497            Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
2498        } finally {
2499            IoUtils.closeQuietly(fis);
2500        }
2501        return restrictions;
2502    }
2503
2504    private static void readEntry(Bundle restrictions, ArrayList<String> values,
2505            XmlPullParser parser) throws XmlPullParserException, IOException {
2506        int type = parser.getEventType();
2507        if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2508            String key = parser.getAttributeValue(null, ATTR_KEY);
2509            String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2510            String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2511            if (multiple != null) {
2512                values.clear();
2513                int count = Integer.parseInt(multiple);
2514                while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2515                    if (type == XmlPullParser.START_TAG
2516                            && parser.getName().equals(TAG_VALUE)) {
2517                        values.add(parser.nextText().trim());
2518                        count--;
2519                    }
2520                }
2521                String [] valueStrings = new String[values.size()];
2522                values.toArray(valueStrings);
2523                restrictions.putStringArray(key, valueStrings);
2524            } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2525                restrictions.putBundle(key, readBundleEntry(parser, values));
2526            } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2527                final int outerDepth = parser.getDepth();
2528                ArrayList<Bundle> bundleList = new ArrayList<>();
2529                while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2530                    Bundle childBundle = readBundleEntry(parser, values);
2531                    bundleList.add(childBundle);
2532                }
2533                restrictions.putParcelableArray(key,
2534                        bundleList.toArray(new Bundle[bundleList.size()]));
2535            } else {
2536                String value = parser.nextText().trim();
2537                if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2538                    restrictions.putBoolean(key, Boolean.parseBoolean(value));
2539                } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2540                    restrictions.putInt(key, Integer.parseInt(value));
2541                } else {
2542                    restrictions.putString(key, value);
2543                }
2544            }
2545        }
2546    }
2547
2548    private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2549            throws IOException, XmlPullParserException {
2550        Bundle childBundle = new Bundle();
2551        final int outerDepth = parser.getDepth();
2552        while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2553            readEntry(childBundle, values, parser);
2554        }
2555        return childBundle;
2556    }
2557
2558    private void writeApplicationRestrictionsLP(String packageName,
2559            Bundle restrictions, int userId) {
2560        AtomicFile restrictionsFile = new AtomicFile(
2561                new File(Environment.getUserSystemDirectory(userId),
2562                        packageToRestrictionsFileName(packageName)));
2563        writeApplicationRestrictionsLP(restrictions, restrictionsFile);
2564    }
2565
2566    @VisibleForTesting
2567    static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
2568        FileOutputStream fos = null;
2569        try {
2570            fos = restrictionsFile.startWrite();
2571            final BufferedOutputStream bos = new BufferedOutputStream(fos);
2572
2573            final XmlSerializer serializer = new FastXmlSerializer();
2574            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
2575            serializer.startDocument(null, true);
2576            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2577
2578            serializer.startTag(null, TAG_RESTRICTIONS);
2579            writeBundle(restrictions, serializer);
2580            serializer.endTag(null, TAG_RESTRICTIONS);
2581
2582            serializer.endDocument();
2583            restrictionsFile.finishWrite(fos);
2584        } catch (Exception e) {
2585            restrictionsFile.failWrite(fos);
2586            Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2587        }
2588    }
2589
2590    private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2591            throws IOException {
2592        for (String key : restrictions.keySet()) {
2593            Object value = restrictions.get(key);
2594            serializer.startTag(null, TAG_ENTRY);
2595            serializer.attribute(null, ATTR_KEY, key);
2596
2597            if (value instanceof Boolean) {
2598                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2599                serializer.text(value.toString());
2600            } else if (value instanceof Integer) {
2601                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2602                serializer.text(value.toString());
2603            } else if (value == null || value instanceof String) {
2604                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2605                serializer.text(value != null ? (String) value : "");
2606            } else if (value instanceof Bundle) {
2607                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2608                writeBundle((Bundle) value, serializer);
2609            } else if (value instanceof Parcelable[]) {
2610                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2611                Parcelable[] array = (Parcelable[]) value;
2612                for (Parcelable parcelable : array) {
2613                    if (!(parcelable instanceof Bundle)) {
2614                        throw new IllegalArgumentException("bundle-array can only hold Bundles");
2615                    }
2616                    serializer.startTag(null, TAG_ENTRY);
2617                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2618                    writeBundle((Bundle) parcelable, serializer);
2619                    serializer.endTag(null, TAG_ENTRY);
2620                }
2621            } else {
2622                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2623                String[] values = (String[]) value;
2624                serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2625                for (String choice : values) {
2626                    serializer.startTag(null, TAG_VALUE);
2627                    serializer.text(choice != null ? choice : "");
2628                    serializer.endTag(null, TAG_VALUE);
2629                }
2630            }
2631            serializer.endTag(null, TAG_ENTRY);
2632        }
2633    }
2634
2635    @Override
2636    public int getUserSerialNumber(int userHandle) {
2637        synchronized (mUsersLock) {
2638            if (!exists(userHandle)) return -1;
2639            return getUserInfoLU(userHandle).serialNumber;
2640        }
2641    }
2642
2643    @Override
2644    public int getUserHandle(int userSerialNumber) {
2645        synchronized (mUsersLock) {
2646            for (int userId : mUserIds) {
2647                UserInfo info = getUserInfoLU(userId);
2648                if (info != null && info.serialNumber == userSerialNumber) return userId;
2649            }
2650            // Not found
2651            return -1;
2652        }
2653    }
2654
2655    @Override
2656    public long getUserCreationTime(int userHandle) {
2657        int callingUserId = UserHandle.getCallingUserId();
2658        UserInfo userInfo = null;
2659        synchronized (mUsersLock) {
2660            if (callingUserId == userHandle) {
2661                userInfo = getUserInfoLU(userHandle);
2662            } else {
2663                UserInfo parent = getProfileParentLU(userHandle);
2664                if (parent != null && parent.id == callingUserId) {
2665                    userInfo = getUserInfoLU(userHandle);
2666                }
2667            }
2668        }
2669        if (userInfo == null) {
2670            throw new SecurityException("userHandle can only be the calling user or a managed "
2671                    + "profile associated with this user");
2672        }
2673        return userInfo.creationTime;
2674    }
2675
2676    /**
2677     * Caches the list of user ids in an array, adjusting the array size when necessary.
2678     */
2679    private void updateUserIds() {
2680        int num = 0;
2681        synchronized (mUsersLock) {
2682            final int userSize = mUsers.size();
2683            for (int i = 0; i < userSize; i++) {
2684                if (!mUsers.valueAt(i).info.partial) {
2685                    num++;
2686                }
2687            }
2688            final int[] newUsers = new int[num];
2689            int n = 0;
2690            for (int i = 0; i < userSize; i++) {
2691                if (!mUsers.valueAt(i).info.partial) {
2692                    newUsers[n++] = mUsers.keyAt(i);
2693                }
2694            }
2695            mUserIds = newUsers;
2696        }
2697    }
2698
2699    /**
2700     * Called right before a user is started. This gives us a chance to prepare
2701     * app storage and apply any user restrictions.
2702     */
2703    public void onBeforeStartUser(int userId) {
2704        final int userSerial = getUserSerialNumber(userId);
2705        mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2706        mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
2707
2708        if (userId != UserHandle.USER_SYSTEM) {
2709            synchronized (mRestrictionsLock) {
2710                applyUserRestrictionsLR(userId);
2711            }
2712            UserInfo userInfo = getUserInfoNoChecks(userId);
2713            if (userInfo != null && !userInfo.isInitialized()) {
2714                mPm.onBeforeUserStartUninitialized(userId);
2715            }
2716        }
2717
2718        maybeInitializeDemoMode(userId);
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     * This is called with ActivityManagerService lock held.
2734     * @param userId the user that was just foregrounded
2735     */
2736    public void onUserLoggedIn(@UserIdInt int userId) {
2737        UserData userData = getUserDataNoChecks(userId);
2738        if (userData == null || userData.info.partial) {
2739            Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2740            return;
2741        }
2742
2743        final long now = System.currentTimeMillis();
2744        if (now > EPOCH_PLUS_30_YEARS) {
2745            userData.info.lastLoggedInTime = now;
2746        }
2747        userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2748        scheduleWriteUser(userData);
2749    }
2750
2751    private void maybeInitializeDemoMode(int userId) {
2752        if (UserManager.isDeviceInDemoMode(mContext)) {
2753            String demoLauncher =
2754                    mContext.getResources().getString(
2755                            com.android.internal.R.string.config_demoModeLauncherComponent);
2756            if (!TextUtils.isEmpty(demoLauncher)) {
2757                ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
2758                try {
2759                    AppGlobals.getPackageManager().setComponentEnabledSetting(componentToEnable,
2760                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2761                            /* userId= */ userId);
2762                } catch (RemoteException re) {
2763                    // Internal, shouldn't happen
2764                }
2765            }
2766        }
2767    }
2768
2769    /**
2770     * Returns the next available user id, filling in any holes in the ids.
2771     * TODO: May not be a good idea to recycle ids, in case it results in confusion
2772     * for data and battery stats collection, or unexpected cross-talk.
2773     */
2774    private int getNextAvailableId() {
2775        synchronized (mUsersLock) {
2776            int i = MIN_USER_ID;
2777            while (i < MAX_USER_ID) {
2778                if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
2779                    return i;
2780                }
2781                i++;
2782            }
2783        }
2784        throw new IllegalStateException("No user id available!");
2785    }
2786
2787    private String packageToRestrictionsFileName(String packageName) {
2788        return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2789    }
2790
2791    /**
2792     * Enforce that serial number stored in user directory inode matches the
2793     * given expected value. Gracefully sets the serial number if currently
2794     * undefined.
2795     *
2796     * @throws IOException when problem extracting serial number, or serial
2797     *             number is mismatched.
2798     */
2799    public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2800        final int foundSerial = getSerialNumber(file);
2801        Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2802
2803        if (foundSerial == -1) {
2804            Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2805            try {
2806                setSerialNumber(file, serialNumber);
2807            } catch (IOException e) {
2808                Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2809            }
2810
2811        } else if (foundSerial != serialNumber) {
2812            throw new IOException("Found serial number " + foundSerial
2813                    + " doesn't match expected " + serialNumber);
2814        }
2815    }
2816
2817    /**
2818     * Set serial number stored in user directory inode.
2819     *
2820     * @throws IOException if serial number was already set
2821     */
2822    private static void setSerialNumber(File file, int serialNumber)
2823            throws IOException {
2824        try {
2825            final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2826            Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2827        } catch (ErrnoException e) {
2828            throw e.rethrowAsIOException();
2829        }
2830    }
2831
2832    /**
2833     * Return serial number stored in user directory inode.
2834     *
2835     * @return parsed serial number, or -1 if not set
2836     */
2837    private static int getSerialNumber(File file) throws IOException {
2838        try {
2839            final byte[] buf = new byte[256];
2840            final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2841            final String serial = new String(buf, 0, len);
2842            try {
2843                return Integer.parseInt(serial);
2844            } catch (NumberFormatException e) {
2845                throw new IOException("Bad serial number: " + serial);
2846            }
2847        } catch (ErrnoException e) {
2848            if (e.errno == OsConstants.ENODATA) {
2849                return -1;
2850            } else {
2851                throw e.rethrowAsIOException();
2852            }
2853        }
2854    }
2855
2856    @Override
2857    public void setSeedAccountData(int userId, String accountName, String accountType,
2858            PersistableBundle accountOptions, boolean persist) {
2859        checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2860        synchronized (mPackagesLock) {
2861            final UserData userData;
2862            synchronized (mUsersLock) {
2863                userData = getUserDataLU(userId);
2864                if (userData == null) {
2865                    Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2866                    return;
2867                }
2868                userData.seedAccountName = accountName;
2869                userData.seedAccountType = accountType;
2870                userData.seedAccountOptions = accountOptions;
2871                userData.persistSeedData = persist;
2872            }
2873            if (persist) {
2874                writeUserLP(userData);
2875            }
2876        }
2877    }
2878
2879    @Override
2880    public String getSeedAccountName() throws RemoteException {
2881        checkManageUsersPermission("Cannot get seed account information");
2882        synchronized (mUsersLock) {
2883            UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2884            return userData.seedAccountName;
2885        }
2886    }
2887
2888    @Override
2889    public String getSeedAccountType() throws RemoteException {
2890        checkManageUsersPermission("Cannot get seed account information");
2891        synchronized (mUsersLock) {
2892            UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2893            return userData.seedAccountType;
2894        }
2895    }
2896
2897    @Override
2898    public PersistableBundle getSeedAccountOptions() throws RemoteException {
2899        checkManageUsersPermission("Cannot get seed account information");
2900        synchronized (mUsersLock) {
2901            UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2902            return userData.seedAccountOptions;
2903        }
2904    }
2905
2906    @Override
2907    public void clearSeedAccountData() throws RemoteException {
2908        checkManageUsersPermission("Cannot clear seed account information");
2909        synchronized (mPackagesLock) {
2910            UserData userData;
2911            synchronized (mUsersLock) {
2912                userData = getUserDataLU(UserHandle.getCallingUserId());
2913                if (userData == null) return;
2914                userData.clearSeedAccountData();
2915            }
2916            writeUserLP(userData);
2917        }
2918    }
2919
2920    @Override
2921    public boolean someUserHasSeedAccount(String accountName, String accountType)
2922            throws RemoteException {
2923        checkManageUsersPermission("Cannot check seed account information");
2924        synchronized (mUsersLock) {
2925            final int userSize = mUsers.size();
2926            for (int i = 0; i < userSize; i++) {
2927                final UserData data = mUsers.valueAt(i);
2928                if (data.info.isInitialized()) continue;
2929                if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2930                    continue;
2931                }
2932                if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2933                    continue;
2934                }
2935                return true;
2936            }
2937        }
2938        return false;
2939    }
2940
2941    @Override
2942    public void onShellCommand(FileDescriptor in, FileDescriptor out,
2943            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2944        (new Shell()).exec(this, in, out, err, args, resultReceiver);
2945    }
2946
2947    int onShellCommand(Shell shell, String cmd) {
2948        if (cmd == null) {
2949            return shell.handleDefaultCommands(cmd);
2950        }
2951
2952        final PrintWriter pw = shell.getOutPrintWriter();
2953        try {
2954            switch(cmd) {
2955                case "list":
2956                    return runList(pw);
2957            }
2958        } catch (RemoteException e) {
2959            pw.println("Remote exception: " + e);
2960        }
2961        return -1;
2962    }
2963
2964    private int runList(PrintWriter pw) throws RemoteException {
2965        final IActivityManager am = ActivityManagerNative.getDefault();
2966        final List<UserInfo> users = getUsers(false);
2967        if (users == null) {
2968            pw.println("Error: couldn't get users");
2969            return 1;
2970        } else {
2971            pw.println("Users:");
2972            for (int i = 0; i < users.size(); i++) {
2973                String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
2974                pw.println("\t" + users.get(i).toString() + running);
2975            }
2976            return 0;
2977        }
2978    }
2979
2980    @Override
2981    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2982        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2983                != PackageManager.PERMISSION_GRANTED) {
2984            pw.println("Permission Denial: can't dump UserManager from from pid="
2985                    + Binder.getCallingPid()
2986                    + ", uid=" + Binder.getCallingUid()
2987                    + " without permission "
2988                    + android.Manifest.permission.DUMP);
2989            return;
2990        }
2991
2992        long now = System.currentTimeMillis();
2993        StringBuilder sb = new StringBuilder();
2994        synchronized (mPackagesLock) {
2995            synchronized (mUsersLock) {
2996                pw.println("Users:");
2997                for (int i = 0; i < mUsers.size(); i++) {
2998                    UserData userData = mUsers.valueAt(i);
2999                    if (userData == null) {
3000                        continue;
3001                    }
3002                    UserInfo userInfo = userData.info;
3003                    final int userId = userInfo.id;
3004                    pw.print("  "); pw.print(userInfo);
3005                    pw.print(" serialNo="); pw.print(userInfo.serialNumber);
3006                    if (mRemovingUserIds.get(userId)) {
3007                        pw.print(" <removing> ");
3008                    }
3009                    if (userInfo.partial) {
3010                        pw.print(" <partial>");
3011                    }
3012                    pw.println();
3013                    pw.print("    Created: ");
3014                    if (userInfo.creationTime == 0) {
3015                        pw.println("<unknown>");
3016                    } else {
3017                        sb.setLength(0);
3018                        TimeUtils.formatDuration(now - userInfo.creationTime, sb);
3019                        sb.append(" ago");
3020                        pw.println(sb);
3021                    }
3022                    pw.print("    Last logged in: ");
3023                    if (userInfo.lastLoggedInTime == 0) {
3024                        pw.println("<unknown>");
3025                    } else {
3026                        sb.setLength(0);
3027                        TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
3028                        sb.append(" ago");
3029                        pw.println(sb);
3030                    }
3031                    pw.print("    Last logged in fingerprint: ");
3032                    pw.println(userInfo.lastLoggedInFingerprint);
3033                    pw.print("    Has profile owner: ");
3034                    pw.println(mIsUserManaged.get(userId));
3035                    pw.println("    Restrictions:");
3036                    synchronized (mRestrictionsLock) {
3037                        UserRestrictionsUtils.dumpRestrictions(
3038                                pw, "      ", mBaseUserRestrictions.get(userInfo.id));
3039                        pw.println("    Device policy local restrictions:");
3040                        UserRestrictionsUtils.dumpRestrictions(
3041                                pw, "      ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
3042                        pw.println("    Effective restrictions:");
3043                        UserRestrictionsUtils.dumpRestrictions(
3044                                pw, "      ", mCachedEffectiveUserRestrictions.get(userInfo.id));
3045                    }
3046
3047                    if (userData.account != null) {
3048                        pw.print("    Account name: " + userData.account);
3049                        pw.println();
3050                    }
3051
3052                    if (userData.seedAccountName != null) {
3053                        pw.print("    Seed account name: " + userData.seedAccountName);
3054                        pw.println();
3055                        if (userData.seedAccountType != null) {
3056                            pw.print("         account type: " + userData.seedAccountType);
3057                            pw.println();
3058                        }
3059                        if (userData.seedAccountOptions != null) {
3060                            pw.print("         account options exist");
3061                            pw.println();
3062                        }
3063                    }
3064                }
3065            }
3066            pw.println();
3067            pw.println("  Device policy global restrictions:");
3068            synchronized (mRestrictionsLock) {
3069                UserRestrictionsUtils
3070                        .dumpRestrictions(pw, "    ", mDevicePolicyGlobalUserRestrictions);
3071            }
3072            pw.println();
3073            pw.println("  Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3074            pw.println();
3075            pw.println("  Guest restrictions:");
3076            synchronized (mGuestRestrictions) {
3077                UserRestrictionsUtils.dumpRestrictions(pw, "    ", mGuestRestrictions);
3078            }
3079            synchronized (mUsersLock) {
3080                pw.println();
3081                pw.println("  Device managed: " + mIsDeviceManaged);
3082            }
3083            // Dump some capabilities
3084            pw.println();
3085            pw.println("  Max users: " + UserManager.getMaxSupportedUsers());
3086            pw.println("  Supports switchable users: " + UserManager.supportsMultipleUsers());
3087            pw.println("  All guests ephemeral: " + Resources.getSystem().getBoolean(
3088                    com.android.internal.R.bool.config_guestUserEphemeral));
3089        }
3090    }
3091
3092    final class MainHandler extends Handler {
3093
3094        @Override
3095        public void handleMessage(Message msg) {
3096            switch (msg.what) {
3097                case WRITE_USER_MSG:
3098                    removeMessages(WRITE_USER_MSG, msg.obj);
3099                    synchronized (mPackagesLock) {
3100                        int userId = ((UserData) msg.obj).info.id;
3101                        UserData userData = getUserDataNoChecks(userId);
3102                        if (userData != null) {
3103                            writeUserLP(userData);
3104                        }
3105                    }
3106            }
3107        }
3108    }
3109
3110    /**
3111     * @param userId
3112     * @return whether the user has been initialized yet
3113     */
3114    boolean isInitialized(int userId) {
3115        return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3116    }
3117
3118    private class LocalService extends UserManagerInternal {
3119        @Override
3120        public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3121                @Nullable Bundle globalRestrictions) {
3122            UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
3123                    globalRestrictions);
3124        }
3125
3126        @Override
3127        public Bundle getBaseUserRestrictions(int userId) {
3128            synchronized (mRestrictionsLock) {
3129                return mBaseUserRestrictions.get(userId);
3130            }
3131        }
3132
3133        @Override
3134        public void setBaseUserRestrictionsByDpmsForMigration(
3135                int userId, Bundle baseRestrictions) {
3136            synchronized (mRestrictionsLock) {
3137                mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
3138                invalidateEffectiveUserRestrictionsLR(userId);
3139            }
3140
3141            final UserData userData = getUserDataNoChecks(userId);
3142            synchronized (mPackagesLock) {
3143                if (userData != null) {
3144                    writeUserLP(userData);
3145                } else {
3146                    Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3147                }
3148            }
3149        }
3150
3151        @Override
3152        public boolean getUserRestriction(int userId, String key) {
3153            return getUserRestrictions(userId).getBoolean(key);
3154        }
3155
3156        @Override
3157        public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3158            synchronized (mUserRestrictionsListeners) {
3159                mUserRestrictionsListeners.add(listener);
3160            }
3161        }
3162
3163        @Override
3164        public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3165            synchronized (mUserRestrictionsListeners) {
3166                mUserRestrictionsListeners.remove(listener);
3167            }
3168        }
3169
3170        @Override
3171        public void setDeviceManaged(boolean isManaged) {
3172            synchronized (mUsersLock) {
3173                mIsDeviceManaged = isManaged;
3174            }
3175        }
3176
3177        @Override
3178        public void setUserManaged(int userId, boolean isManaged) {
3179            synchronized (mUsersLock) {
3180                mIsUserManaged.put(userId, isManaged);
3181            }
3182        }
3183
3184        @Override
3185        public void setUserIcon(int userId, Bitmap bitmap) {
3186            long ident = Binder.clearCallingIdentity();
3187            try {
3188                synchronized (mPackagesLock) {
3189                    UserData userData = getUserDataNoChecks(userId);
3190                    if (userData == null || userData.info.partial) {
3191                        Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3192                        return;
3193                    }
3194                    writeBitmapLP(userData.info, bitmap);
3195                    writeUserLP(userData);
3196                }
3197                sendUserInfoChangedBroadcast(userId);
3198            } finally {
3199                Binder.restoreCallingIdentity(ident);
3200            }
3201        }
3202
3203        @Override
3204        public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3205            synchronized (mUsersLock) {
3206                mForceEphemeralUsers = forceEphemeralUsers;
3207            }
3208        }
3209
3210        @Override
3211        public void removeAllUsers() {
3212            if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3213                // Remove the non-system users straight away.
3214                removeNonSystemUsers();
3215            } else {
3216                // Switch to the system user first and then remove the other users.
3217                BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3218                    @Override
3219                    public void onReceive(Context context, Intent intent) {
3220                        int userId =
3221                                intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3222                        if (userId != UserHandle.USER_SYSTEM) {
3223                            return;
3224                        }
3225                        mContext.unregisterReceiver(this);
3226                        removeNonSystemUsers();
3227                    }
3228                };
3229                IntentFilter userSwitchedFilter = new IntentFilter();
3230                userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3231                mContext.registerReceiver(
3232                        userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3233
3234                // Switch to the system user.
3235                ActivityManager am =
3236                        (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3237                am.switchUser(UserHandle.USER_SYSTEM);
3238            }
3239        }
3240
3241        @Override
3242        public void onEphemeralUserStop(int userId) {
3243            synchronized (mUsersLock) {
3244               UserInfo userInfo = getUserInfoLU(userId);
3245               if (userInfo != null && userInfo.isEphemeral()) {
3246                    // Do not allow switching back to the ephemeral user again as the user is going
3247                    // to be deleted.
3248                    userInfo.flags |= UserInfo.FLAG_DISABLED;
3249                    if (userInfo.isGuest()) {
3250                        // Indicate that the guest will be deleted after it stops.
3251                        userInfo.guestToRemove = true;
3252                    }
3253               }
3254            }
3255        }
3256
3257        @Override
3258        public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3259            UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3260            // Keep this in sync with UserManager.createUser
3261            if (user != null && !user.isAdmin()) {
3262                setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3263                setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3264            }
3265            return user;
3266        }
3267
3268        @Override
3269        public void setUserUnlockingOrUnlocked(int userId, boolean unlockingOrUnlocked) {
3270            synchronized (mUsersLock) {
3271                mUnlockingOrUnlockedUsers.put(userId, unlockingOrUnlocked);
3272            }
3273        }
3274
3275        @Override
3276        public boolean isUserUnlockingOrUnlocked(int userId) {
3277            synchronized (mUsersLock) {
3278                return mUnlockingOrUnlockedUsers.get(userId);
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