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