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