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