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