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