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