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