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