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