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