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