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