UserManagerService.java revision f3ece36535d4999cf2bfd2175a33da6c3cdf298e
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        serializer.endTag(null, TAG_RESTRICTIONS);
922    }
923
924    private UserInfo readUserLocked(int id) {
925        int flags = 0;
926        int serialNumber = id;
927        String name = null;
928        String iconPath = null;
929        long creationTime = 0L;
930        long lastLoggedInTime = 0L;
931        long salt = 0L;
932        String pinHash = null;
933        int failedAttempts = 0;
934        int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
935        long lastAttemptTime = 0L;
936        boolean partial = false;
937        boolean guestToRemove = false;
938        Bundle restrictions = new Bundle();
939
940        FileInputStream fis = null;
941        try {
942            AtomicFile userFile =
943                    new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
944            fis = userFile.openRead();
945            XmlPullParser parser = Xml.newPullParser();
946            parser.setInput(fis, null);
947            int type;
948            while ((type = parser.next()) != XmlPullParser.START_TAG
949                    && type != XmlPullParser.END_DOCUMENT) {
950                ;
951            }
952
953            if (type != XmlPullParser.START_TAG) {
954                Slog.e(LOG_TAG, "Unable to read user " + id);
955                return null;
956            }
957
958            if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
959                int storedId = readIntAttribute(parser, ATTR_ID, -1);
960                if (storedId != id) {
961                    Slog.e(LOG_TAG, "User id does not match the file name");
962                    return null;
963                }
964                serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
965                flags = readIntAttribute(parser, ATTR_FLAGS, 0);
966                iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
967                creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
968                lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
969                salt = readLongAttribute(parser, ATTR_SALT, 0L);
970                pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
971                failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
972                lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
973                profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
974                        UserInfo.NO_PROFILE_GROUP_ID);
975                String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
976                if ("true".equals(valueString)) {
977                    partial = true;
978                }
979                valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
980                if ("true".equals(valueString)) {
981                    guestToRemove = true;
982                }
983
984                int outerDepth = parser.getDepth();
985                while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
986                       && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
987                    if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
988                        continue;
989                    }
990                    String tag = parser.getName();
991                    if (TAG_NAME.equals(tag)) {
992                        type = parser.next();
993                        if (type == XmlPullParser.TEXT) {
994                            name = parser.getText();
995                        }
996                    } else if (TAG_RESTRICTIONS.equals(tag)) {
997                        readRestrictionsLocked(parser, restrictions);
998                    }
999                }
1000            }
1001
1002            UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
1003            userInfo.serialNumber = serialNumber;
1004            userInfo.creationTime = creationTime;
1005            userInfo.lastLoggedInTime = lastLoggedInTime;
1006            userInfo.partial = partial;
1007            userInfo.guestToRemove = guestToRemove;
1008            userInfo.profileGroupId = profileGroupId;
1009            mUserRestrictions.append(id, restrictions);
1010            if (salt != 0L) {
1011                RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
1012                if (pinState == null) {
1013                    pinState = new RestrictionsPinState();
1014                    mRestrictionsPinStates.put(id, pinState);
1015                }
1016                pinState.salt = salt;
1017                pinState.pinHash = pinHash;
1018                pinState.failedAttempts = failedAttempts;
1019                pinState.lastAttemptTime = lastAttemptTime;
1020            }
1021            return userInfo;
1022
1023        } catch (IOException ioe) {
1024        } catch (XmlPullParserException pe) {
1025        } finally {
1026            if (fis != null) {
1027                try {
1028                    fis.close();
1029                } catch (IOException e) {
1030                }
1031            }
1032        }
1033        return null;
1034    }
1035
1036    private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1037            throws IOException {
1038        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1039        readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1040        readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1041        readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1042        readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1043        readBoolean(parser, restrictions,
1044                UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1045        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1046        readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1047        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1048        readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1049        readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1050        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1051        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1052        readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1053        readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1054        readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1055        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1056        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1057        readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1058        readBoolean(parser, restrictions,
1059                UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1060        readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1061        readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
1062        readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1063        readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
1064        readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
1065        readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1066        readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
1067        readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
1068    }
1069
1070    private void readBoolean(XmlPullParser parser, Bundle restrictions,
1071            String restrictionKey) {
1072        String value = parser.getAttributeValue(null, restrictionKey);
1073        if (value != null) {
1074            restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1075        }
1076    }
1077
1078    private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1079            throws IOException {
1080        if (restrictions.containsKey(restrictionKey)) {
1081            xml.attribute(null, restrictionKey,
1082                    Boolean.toString(restrictions.getBoolean(restrictionKey)));
1083        }
1084    }
1085
1086    private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1087        String valueString = parser.getAttributeValue(null, attr);
1088        if (valueString == null) return defaultValue;
1089        try {
1090            return Integer.parseInt(valueString);
1091        } catch (NumberFormatException nfe) {
1092            return defaultValue;
1093        }
1094    }
1095
1096    private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1097        String valueString = parser.getAttributeValue(null, attr);
1098        if (valueString == null) return defaultValue;
1099        try {
1100            return Long.parseLong(valueString);
1101        } catch (NumberFormatException nfe) {
1102            return defaultValue;
1103        }
1104    }
1105
1106    private boolean isPackageInstalled(String pkg, int userId) {
1107        final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1108                PackageManager.GET_UNINSTALLED_PACKAGES,
1109                userId);
1110        if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1111            return false;
1112        }
1113        return true;
1114    }
1115
1116    /**
1117     * Removes all the restrictions files (res_<packagename>) for a given user.
1118     * Does not do any permissions checking.
1119     */
1120    private void cleanAppRestrictions(int userId) {
1121        synchronized (mPackagesLock) {
1122            File dir = Environment.getUserSystemDirectory(userId);
1123            String[] files = dir.list();
1124            if (files == null) return;
1125            for (String fileName : files) {
1126                if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1127                    File resFile = new File(dir, fileName);
1128                    if (resFile.exists()) {
1129                        resFile.delete();
1130                    }
1131                }
1132            }
1133        }
1134    }
1135
1136    /**
1137     * Removes the app restrictions file for a specific package and user id, if it exists.
1138     */
1139    private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1140        synchronized (mPackagesLock) {
1141            File dir = Environment.getUserSystemDirectory(userId);
1142            File resFile = new File(dir, packageToRestrictionsFileName(pkg));
1143            if (resFile.exists()) {
1144                resFile.delete();
1145            }
1146        }
1147    }
1148
1149    @Override
1150    public UserInfo createProfileForUser(String name, int flags, int userId) {
1151        checkManageUsersPermission("Only the system can create users");
1152        if (userId != UserHandle.USER_OWNER) {
1153            Slog.w(LOG_TAG, "Only user owner can have profiles");
1154            return null;
1155        }
1156        return createUserInternal(name, flags, userId);
1157    }
1158
1159    @Override
1160    public UserInfo createUser(String name, int flags) {
1161        checkManageUsersPermission("Only the system can create users");
1162        return createUserInternal(name, flags, UserHandle.USER_NULL);
1163    }
1164
1165    private UserInfo createUserInternal(String name, int flags, int parentId) {
1166        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1167                UserManager.DISALLOW_ADD_USER, false)) {
1168            Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1169            return null;
1170        }
1171        final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
1172        final long ident = Binder.clearCallingIdentity();
1173        UserInfo userInfo = null;
1174        try {
1175            synchronized (mInstallLock) {
1176                synchronized (mPackagesLock) {
1177                    UserInfo parent = null;
1178                    if (parentId != UserHandle.USER_NULL) {
1179                        parent = getUserInfoLocked(parentId);
1180                        if (parent == null) return null;
1181                    }
1182                    // If we're not adding a guest user and the limit has been reached,
1183                    // cannot add a user.
1184                    if (!isGuest && isUserLimitReachedLocked()) {
1185                        return null;
1186                    }
1187                    // If we're adding a guest and there already exists one, bail.
1188                    if (isGuest && findCurrentGuestUserLocked() != null) {
1189                        return null;
1190                    }
1191                    // Limit number of managed profiles that can be created
1192                    if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1193                            && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1194                                >= MAX_MANAGED_PROFILES) {
1195                        return null;
1196                    }
1197                    int userId = getNextAvailableIdLocked();
1198                    userInfo = new UserInfo(userId, name, null, flags);
1199                    File userPath = new File(mBaseUserPath, Integer.toString(userId));
1200                    userInfo.serialNumber = mNextSerialNumber++;
1201                    long now = System.currentTimeMillis();
1202                    userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1203                    userInfo.partial = true;
1204                    Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1205                    mUsers.put(userId, userInfo);
1206                    writeUserListLocked();
1207                    if (parent != null) {
1208                        if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1209                            parent.profileGroupId = parent.id;
1210                            scheduleWriteUserLocked(parent);
1211                        }
1212                        userInfo.profileGroupId = parent.profileGroupId;
1213                    }
1214                    mPm.createNewUserLILPw(userId, userPath);
1215                    userInfo.partial = false;
1216                    scheduleWriteUserLocked(userInfo);
1217                    updateUserIdsLocked();
1218                    Bundle restrictions = new Bundle();
1219                    mUserRestrictions.append(userId, restrictions);
1220                }
1221            }
1222            if (userInfo != null) {
1223                Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1224                addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1225                mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1226                        android.Manifest.permission.MANAGE_USERS);
1227            }
1228        } finally {
1229            Binder.restoreCallingIdentity(ident);
1230        }
1231        return userInfo;
1232    }
1233
1234    private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1235        int count = 0;
1236        for (int i = mUsers.size() - 1; i >= 0; i--) {
1237            UserInfo user = mUsers.valueAt(i);
1238            if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1239                if ((user.flags & flags) != 0) {
1240                    count++;
1241                }
1242            }
1243        }
1244        return count;
1245    }
1246
1247    /**
1248     * Find the current guest user. If the Guest user is partial,
1249     * then do not include it in the results as it is about to die.
1250     * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1251     * the special handling of Guests being removed.
1252     */
1253    private UserInfo findCurrentGuestUserLocked() {
1254        final int size = mUsers.size();
1255        for (int i = 0; i < size; i++) {
1256            final UserInfo user = mUsers.valueAt(i);
1257            if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1258                return user;
1259            }
1260        }
1261        return null;
1262    }
1263
1264    /**
1265     * Mark this guest user for deletion to allow us to create another guest
1266     * and switch to that user before actually removing this guest.
1267     * @param userHandle the userid of the current guest
1268     * @return whether the user could be marked for deletion
1269     */
1270    public boolean markGuestForDeletion(int userHandle) {
1271        checkManageUsersPermission("Only the system can remove users");
1272        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1273                UserManager.DISALLOW_REMOVE_USER, false)) {
1274            Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1275            return false;
1276        }
1277
1278        long ident = Binder.clearCallingIdentity();
1279        try {
1280            final UserInfo user;
1281            synchronized (mPackagesLock) {
1282                user = mUsers.get(userHandle);
1283                if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1284                    return false;
1285                }
1286                if (!user.isGuest()) {
1287                    return false;
1288                }
1289                // We set this to a guest user that is to be removed. This is a temporary state
1290                // where we are allowed to add new Guest users, even if this one is still not
1291                // removed. This user will still show up in getUserInfo() calls.
1292                // If we don't get around to removing this Guest user, it will be purged on next
1293                // startup.
1294                user.guestToRemove = true;
1295                // Mark it as disabled, so that it isn't returned any more when
1296                // profiles are queried.
1297                user.flags |= UserInfo.FLAG_DISABLED;
1298                writeUserLocked(user);
1299            }
1300        } finally {
1301            Binder.restoreCallingIdentity(ident);
1302        }
1303        return true;
1304    }
1305
1306    /**
1307     * Removes a user and all data directories created for that user. This method should be called
1308     * after the user's processes have been terminated.
1309     * @param userHandle the user's id
1310     */
1311    public boolean removeUser(int userHandle) {
1312        checkManageUsersPermission("Only the system can remove users");
1313        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1314                UserManager.DISALLOW_REMOVE_USER, false)) {
1315            Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1316            return false;
1317        }
1318
1319        long ident = Binder.clearCallingIdentity();
1320        try {
1321            final UserInfo user;
1322            synchronized (mPackagesLock) {
1323                user = mUsers.get(userHandle);
1324                if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1325                    return false;
1326                }
1327
1328                // We remember deleted user IDs to prevent them from being
1329                // reused during the current boot; they can still be reused
1330                // after a reboot.
1331                mRemovingUserIds.put(userHandle, true);
1332
1333                try {
1334                    mAppOpsService.removeUser(userHandle);
1335                } catch (RemoteException e) {
1336                    Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1337                }
1338                // Set this to a partially created user, so that the user will be purged
1339                // on next startup, in case the runtime stops now before stopping and
1340                // removing the user completely.
1341                user.partial = true;
1342                // Mark it as disabled, so that it isn't returned any more when
1343                // profiles are queried.
1344                user.flags |= UserInfo.FLAG_DISABLED;
1345                writeUserLocked(user);
1346            }
1347
1348            if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1349                    && user.isManagedProfile()) {
1350                // Send broadcast to notify system that the user removed was a
1351                // managed user.
1352                sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1353            }
1354
1355            if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1356            int res;
1357            try {
1358                res = ActivityManagerNative.getDefault().stopUser(userHandle,
1359                        new IStopUserCallback.Stub() {
1360                            @Override
1361                            public void userStopped(int userId) {
1362                                finishRemoveUser(userId);
1363                            }
1364                            @Override
1365                            public void userStopAborted(int userId) {
1366                            }
1367                        });
1368            } catch (RemoteException e) {
1369                return false;
1370            }
1371            return res == ActivityManager.USER_OP_SUCCESS;
1372        } finally {
1373            Binder.restoreCallingIdentity(ident);
1374        }
1375    }
1376
1377    void finishRemoveUser(final int userHandle) {
1378        if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
1379        // Let other services shutdown any activity and clean up their state before completely
1380        // wiping the user's system directory and removing from the user list
1381        long ident = Binder.clearCallingIdentity();
1382        try {
1383            Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1384            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
1385            mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1386                    android.Manifest.permission.MANAGE_USERS,
1387
1388                    new BroadcastReceiver() {
1389                        @Override
1390                        public void onReceive(Context context, Intent intent) {
1391                            if (DBG) {
1392                                Slog.i(LOG_TAG,
1393                                        "USER_REMOVED broadcast sent, cleaning up user data "
1394                                        + userHandle);
1395                            }
1396                            new Thread() {
1397                                public void run() {
1398                                    synchronized (mInstallLock) {
1399                                        synchronized (mPackagesLock) {
1400                                            removeUserStateLocked(userHandle);
1401                                        }
1402                                    }
1403                                }
1404                            }.start();
1405                        }
1406                    },
1407
1408                    null, Activity.RESULT_OK, null, null);
1409        } finally {
1410            Binder.restoreCallingIdentity(ident);
1411        }
1412    }
1413
1414    private void removeUserStateLocked(final int userHandle) {
1415        // Cleanup package manager settings
1416        mPm.cleanUpUserLILPw(this, userHandle);
1417
1418        // Remove this user from the list
1419        mUsers.remove(userHandle);
1420
1421        mRestrictionsPinStates.remove(userHandle);
1422        // Remove user file
1423        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
1424        userFile.delete();
1425        // Update the user list
1426        writeUserListLocked();
1427        updateUserIdsLocked();
1428        removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1429    }
1430
1431    private void removeDirectoryRecursive(File parent) {
1432        if (parent.isDirectory()) {
1433            String[] files = parent.list();
1434            for (String filename : files) {
1435                File child = new File(parent, filename);
1436                removeDirectoryRecursive(child);
1437            }
1438        }
1439        parent.delete();
1440    }
1441
1442    private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
1443        Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
1444        managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1445                Intent.FLAG_RECEIVER_FOREGROUND);
1446        managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1447        mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
1448    }
1449
1450    @Override
1451    public Bundle getApplicationRestrictions(String packageName) {
1452        return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1453    }
1454
1455    @Override
1456    public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
1457        if (UserHandle.getCallingUserId() != userId
1458                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
1459            checkManageUsersPermission("Only system can get restrictions for other users/apps");
1460        }
1461        synchronized (mPackagesLock) {
1462            // Read the restrictions from XML
1463            return readApplicationRestrictionsLocked(packageName, userId);
1464        }
1465    }
1466
1467    @Override
1468    public void setApplicationRestrictions(String packageName, Bundle restrictions,
1469            int userId) {
1470        if (UserHandle.getCallingUserId() != userId
1471                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
1472            checkManageUsersPermission("Only system can set restrictions for other users/apps");
1473        }
1474        synchronized (mPackagesLock) {
1475            if (restrictions == null || restrictions.isEmpty()) {
1476                cleanAppRestrictionsForPackage(packageName, userId);
1477            } else {
1478                // Write the restrictions to XML
1479                writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1480            }
1481        }
1482
1483        if (isPackageInstalled(packageName, userId)) {
1484            // Notify package of changes via an intent - only sent to explicitly registered receivers.
1485            Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1486            changeIntent.setPackage(packageName);
1487            changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1488            mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1489        }
1490    }
1491
1492    @Override
1493    public boolean setRestrictionsChallenge(String newPin) {
1494        checkManageUsersPermission("Only system can modify the restrictions pin");
1495        int userId = UserHandle.getCallingUserId();
1496        synchronized (mPackagesLock) {
1497            RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1498            if (pinState == null) {
1499                pinState = new RestrictionsPinState();
1500            }
1501            if (newPin == null) {
1502                pinState.salt = 0;
1503                pinState.pinHash = null;
1504            } else {
1505                try {
1506                    pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1507                } catch (NoSuchAlgorithmException e) {
1508                    pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1509                }
1510                pinState.pinHash = passwordToHash(newPin, pinState.salt);
1511                pinState.failedAttempts = 0;
1512            }
1513            mRestrictionsPinStates.put(userId, pinState);
1514            writeUserLocked(mUsers.get(userId));
1515        }
1516        return true;
1517    }
1518
1519    @Override
1520    public int checkRestrictionsChallenge(String pin) {
1521        checkManageUsersPermission("Only system can verify the restrictions pin");
1522        int userId = UserHandle.getCallingUserId();
1523        synchronized (mPackagesLock) {
1524            RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1525            // If there's no pin set, return error code
1526            if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1527                return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1528            } else if (pin == null) {
1529                // If just checking if user can be prompted, return remaining time
1530                int waitTime = getRemainingTimeForPinAttempt(pinState);
1531                Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1532                return waitTime;
1533            } else {
1534                int waitTime = getRemainingTimeForPinAttempt(pinState);
1535                Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1536                if (waitTime > 0) {
1537                    return waitTime;
1538                }
1539                if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1540                    pinState.failedAttempts = 0;
1541                    scheduleWriteUserLocked(mUsers.get(userId));
1542                    return UserManager.PIN_VERIFICATION_SUCCESS;
1543                } else {
1544                    pinState.failedAttempts++;
1545                    pinState.lastAttemptTime = System.currentTimeMillis();
1546                    scheduleWriteUserLocked(mUsers.get(userId));
1547                    return waitTime;
1548                }
1549            }
1550        }
1551    }
1552
1553    private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1554        int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1555                BACKOFF_TIMES.length - 1);
1556        int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1557                BACKOFF_TIMES[backoffIndex] : 0;
1558        return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1559                0);
1560    }
1561
1562    @Override
1563    public boolean hasRestrictionsChallenge() {
1564        int userId = UserHandle.getCallingUserId();
1565        synchronized (mPackagesLock) {
1566            return hasRestrictionsPinLocked(userId);
1567        }
1568    }
1569
1570    private boolean hasRestrictionsPinLocked(int userId) {
1571        RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1572        if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1573            return false;
1574        }
1575        return true;
1576    }
1577
1578    @Override
1579    public void removeRestrictions() {
1580        checkManageUsersPermission("Only system can remove restrictions");
1581        final int userHandle = UserHandle.getCallingUserId();
1582        removeRestrictionsForUser(userHandle, true);
1583    }
1584
1585    private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
1586        synchronized (mPackagesLock) {
1587            // Remove all user restrictions
1588            setUserRestrictions(new Bundle(), userHandle);
1589            // Remove restrictions pin
1590            setRestrictionsChallenge(null);
1591            // Remove any app restrictions
1592            cleanAppRestrictions(userHandle);
1593        }
1594        if (unhideApps) {
1595            unhideAllInstalledAppsForUser(userHandle);
1596        }
1597    }
1598
1599    private void unhideAllInstalledAppsForUser(final int userHandle) {
1600        mHandler.post(new Runnable() {
1601            @Override
1602            public void run() {
1603                List<ApplicationInfo> apps =
1604                        mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1605                                userHandle).getList();
1606                final long ident = Binder.clearCallingIdentity();
1607                try {
1608                    for (ApplicationInfo appInfo : apps) {
1609                        if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1610                                && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1611                                        != 0) {
1612                            mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
1613                                    userHandle);
1614                        }
1615                    }
1616                } finally {
1617                    Binder.restoreCallingIdentity(ident);
1618                }
1619            }
1620        });
1621    }
1622
1623    /*
1624     * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1625     * Not the most secure, but it is at least a second level of protection. First level is that
1626     * the file is in a location only readable by the system process.
1627     * @param password the password.
1628     * @param salt the randomly generated salt
1629     * @return the hash of the pattern in a String.
1630     */
1631    private String passwordToHash(String password, long salt) {
1632        if (password == null) {
1633            return null;
1634        }
1635        String algo = null;
1636        String hashed = salt + password;
1637        try {
1638            byte[] saltedPassword = (password + salt).getBytes();
1639            byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1640            byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1641            hashed = toHex(sha1) + toHex(md5);
1642        } catch (NoSuchAlgorithmException e) {
1643            Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1644        }
1645        return hashed;
1646    }
1647
1648    private static String toHex(byte[] ary) {
1649        final String hex = "0123456789ABCDEF";
1650        String ret = "";
1651        for (int i = 0; i < ary.length; i++) {
1652            ret += hex.charAt((ary[i] >> 4) & 0xf);
1653            ret += hex.charAt(ary[i] & 0xf);
1654        }
1655        return ret;
1656    }
1657
1658    private int getUidForPackage(String packageName) {
1659        long ident = Binder.clearCallingIdentity();
1660        try {
1661            return mContext.getPackageManager().getApplicationInfo(packageName,
1662                    PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1663        } catch (NameNotFoundException nnfe) {
1664            return -1;
1665        } finally {
1666            Binder.restoreCallingIdentity(ident);
1667        }
1668    }
1669
1670    private Bundle readApplicationRestrictionsLocked(String packageName,
1671            int userId) {
1672        final Bundle restrictions = new Bundle();
1673        final ArrayList<String> values = new ArrayList<String>();
1674
1675        FileInputStream fis = null;
1676        try {
1677            AtomicFile restrictionsFile =
1678                    new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1679                            packageToRestrictionsFileName(packageName)));
1680            fis = restrictionsFile.openRead();
1681            XmlPullParser parser = Xml.newPullParser();
1682            parser.setInput(fis, null);
1683            int type;
1684            while ((type = parser.next()) != XmlPullParser.START_TAG
1685                    && type != XmlPullParser.END_DOCUMENT) {
1686                ;
1687            }
1688
1689            if (type != XmlPullParser.START_TAG) {
1690                Slog.e(LOG_TAG, "Unable to read restrictions file "
1691                        + restrictionsFile.getBaseFile());
1692                return restrictions;
1693            }
1694
1695            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1696                if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1697                    String key = parser.getAttributeValue(null, ATTR_KEY);
1698                    String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1699                    String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1700                    if (multiple != null) {
1701                        values.clear();
1702                        int count = Integer.parseInt(multiple);
1703                        while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1704                            if (type == XmlPullParser.START_TAG
1705                                    && parser.getName().equals(TAG_VALUE)) {
1706                                values.add(parser.nextText().trim());
1707                                count--;
1708                            }
1709                        }
1710                        String [] valueStrings = new String[values.size()];
1711                        values.toArray(valueStrings);
1712                        restrictions.putStringArray(key, valueStrings);
1713                    } else {
1714                        String value = parser.nextText().trim();
1715                        if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1716                            restrictions.putBoolean(key, Boolean.parseBoolean(value));
1717                        } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1718                            restrictions.putInt(key, Integer.parseInt(value));
1719                        } else {
1720                            restrictions.putString(key, value);
1721                        }
1722                    }
1723                }
1724            }
1725        } catch (IOException ioe) {
1726        } catch (XmlPullParserException pe) {
1727        } finally {
1728            if (fis != null) {
1729                try {
1730                    fis.close();
1731                } catch (IOException e) {
1732                }
1733            }
1734        }
1735        return restrictions;
1736    }
1737
1738    private void writeApplicationRestrictionsLocked(String packageName,
1739            Bundle restrictions, int userId) {
1740        FileOutputStream fos = null;
1741        AtomicFile restrictionsFile = new AtomicFile(
1742                new File(Environment.getUserSystemDirectory(userId),
1743                        packageToRestrictionsFileName(packageName)));
1744        try {
1745            fos = restrictionsFile.startWrite();
1746            final BufferedOutputStream bos = new BufferedOutputStream(fos);
1747
1748            // XmlSerializer serializer = XmlUtils.serializerInstance();
1749            final XmlSerializer serializer = new FastXmlSerializer();
1750            serializer.setOutput(bos, "utf-8");
1751            serializer.startDocument(null, true);
1752            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1753
1754            serializer.startTag(null, TAG_RESTRICTIONS);
1755
1756            for (String key : restrictions.keySet()) {
1757                Object value = restrictions.get(key);
1758                serializer.startTag(null, TAG_ENTRY);
1759                serializer.attribute(null, ATTR_KEY, key);
1760
1761                if (value instanceof Boolean) {
1762                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1763                    serializer.text(value.toString());
1764                } else if (value instanceof Integer) {
1765                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1766                    serializer.text(value.toString());
1767                } else if (value == null || value instanceof String) {
1768                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1769                    serializer.text(value != null ? (String) value : "");
1770                } else {
1771                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1772                    String[] values = (String[]) value;
1773                    serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1774                    for (String choice : values) {
1775                        serializer.startTag(null, TAG_VALUE);
1776                        serializer.text(choice != null ? choice : "");
1777                        serializer.endTag(null, TAG_VALUE);
1778                    }
1779                }
1780                serializer.endTag(null, TAG_ENTRY);
1781            }
1782
1783            serializer.endTag(null, TAG_RESTRICTIONS);
1784
1785            serializer.endDocument();
1786            restrictionsFile.finishWrite(fos);
1787        } catch (Exception e) {
1788            restrictionsFile.failWrite(fos);
1789            Slog.e(LOG_TAG, "Error writing application restrictions list");
1790        }
1791    }
1792
1793    @Override
1794    public int getUserSerialNumber(int userHandle) {
1795        synchronized (mPackagesLock) {
1796            if (!exists(userHandle)) return -1;
1797            return getUserInfoLocked(userHandle).serialNumber;
1798        }
1799    }
1800
1801    @Override
1802    public int getUserHandle(int userSerialNumber) {
1803        synchronized (mPackagesLock) {
1804            for (int userId : mUserIds) {
1805                UserInfo info = getUserInfoLocked(userId);
1806                if (info != null && info.serialNumber == userSerialNumber) return userId;
1807            }
1808            // Not found
1809            return -1;
1810        }
1811    }
1812
1813    /**
1814     * Caches the list of user ids in an array, adjusting the array size when necessary.
1815     */
1816    private void updateUserIdsLocked() {
1817        int num = 0;
1818        for (int i = 0; i < mUsers.size(); i++) {
1819            if (!mUsers.valueAt(i).partial) {
1820                num++;
1821            }
1822        }
1823        final int[] newUsers = new int[num];
1824        int n = 0;
1825        for (int i = 0; i < mUsers.size(); i++) {
1826            if (!mUsers.valueAt(i).partial) {
1827                newUsers[n++] = mUsers.keyAt(i);
1828            }
1829        }
1830        mUserIds = newUsers;
1831    }
1832
1833    /**
1834     * Make a note of the last started time of a user and do some cleanup.
1835     * @param userId the user that was just foregrounded
1836     */
1837    public void userForeground(int userId) {
1838        synchronized (mPackagesLock) {
1839            UserInfo user = mUsers.get(userId);
1840            long now = System.currentTimeMillis();
1841            if (user == null || user.partial) {
1842                Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1843                return;
1844            }
1845            if (now > EPOCH_PLUS_30_YEARS) {
1846                user.lastLoggedInTime = now;
1847                scheduleWriteUserLocked(user);
1848            }
1849        }
1850    }
1851
1852    /**
1853     * Returns the next available user id, filling in any holes in the ids.
1854     * TODO: May not be a good idea to recycle ids, in case it results in confusion
1855     * for data and battery stats collection, or unexpected cross-talk.
1856     * @return
1857     */
1858    private int getNextAvailableIdLocked() {
1859        synchronized (mPackagesLock) {
1860            int i = MIN_USER_ID;
1861            while (i < Integer.MAX_VALUE) {
1862                if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
1863                    break;
1864                }
1865                i++;
1866            }
1867            return i;
1868        }
1869    }
1870
1871    private String packageToRestrictionsFileName(String packageName) {
1872        return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1873    }
1874
1875    private String restrictionsFileNameToPackage(String fileName) {
1876        return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1877                (int) (fileName.length() - XML_SUFFIX.length()));
1878    }
1879
1880    @Override
1881    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1882        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1883                != PackageManager.PERMISSION_GRANTED) {
1884            pw.println("Permission Denial: can't dump UserManager from from pid="
1885                    + Binder.getCallingPid()
1886                    + ", uid=" + Binder.getCallingUid()
1887                    + " without permission "
1888                    + android.Manifest.permission.DUMP);
1889            return;
1890        }
1891
1892        long now = System.currentTimeMillis();
1893        StringBuilder sb = new StringBuilder();
1894        synchronized (mPackagesLock) {
1895            pw.println("Users:");
1896            for (int i = 0; i < mUsers.size(); i++) {
1897                UserInfo user = mUsers.valueAt(i);
1898                if (user == null) continue;
1899                pw.print("  "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
1900                if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
1901                if (user.partial) pw.print(" <partial>");
1902                pw.println();
1903                pw.print("    Created: ");
1904                if (user.creationTime == 0) {
1905                    pw.println("<unknown>");
1906                } else {
1907                    sb.setLength(0);
1908                    TimeUtils.formatDuration(now - user.creationTime, sb);
1909                    sb.append(" ago");
1910                    pw.println(sb);
1911                }
1912                pw.print("    Last logged in: ");
1913                if (user.lastLoggedInTime == 0) {
1914                    pw.println("<unknown>");
1915                } else {
1916                    sb.setLength(0);
1917                    TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1918                    sb.append(" ago");
1919                    pw.println(sb);
1920                }
1921            }
1922        }
1923    }
1924
1925    final class MainHandler extends Handler {
1926
1927        @Override
1928        public void handleMessage(Message msg) {
1929            switch (msg.what) {
1930                case WRITE_USER_MSG:
1931                    removeMessages(WRITE_USER_MSG, msg.obj);
1932                    synchronized (mPackagesLock) {
1933                        int userId = ((UserInfo) msg.obj).id;
1934                        UserInfo userInfo = mUsers.get(userId);
1935                        if (userInfo != null) {
1936                            writeUserLocked(userInfo);
1937                        }
1938                    }
1939            }
1940        }
1941    }
1942}
1943