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