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