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