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