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