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