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