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