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