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