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