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