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