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