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