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