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