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