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