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