UserManagerService.java revision 75175025f8d727d9841308fa0afcb9a7a1a118cd
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        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1051                UserManager.DISALLOW_ADD_USER, false)) {
1052            Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1053            return null;
1054        }
1055        final long ident = Binder.clearCallingIdentity();
1056        UserInfo userInfo = null;
1057        try {
1058            synchronized (mInstallLock) {
1059                synchronized (mPackagesLock) {
1060                    UserInfo parent = null;
1061                    if (parentId != UserHandle.USER_NULL) {
1062                        parent = getUserInfoLocked(parentId);
1063                        if (parent == null) return null;
1064                    }
1065                    if (isUserLimitReachedLocked()) return null;
1066                    int userId = getNextAvailableIdLocked();
1067                    userInfo = new UserInfo(userId, name, null, flags);
1068                    File userPath = new File(mBaseUserPath, Integer.toString(userId));
1069                    userInfo.serialNumber = mNextSerialNumber++;
1070                    long now = System.currentTimeMillis();
1071                    userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1072                    userInfo.partial = true;
1073                    Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1074                    mUsers.put(userId, userInfo);
1075                    writeUserListLocked();
1076                    if (parent != null) {
1077                        if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1078                            parent.profileGroupId = parent.id;
1079                            writeUserLocked(parent);
1080                        }
1081                        userInfo.profileGroupId = parent.profileGroupId;
1082                    }
1083                    writeUserLocked(userInfo);
1084                    mPm.createNewUserLILPw(userId, userPath);
1085                    userInfo.partial = false;
1086                    writeUserLocked(userInfo);
1087                    updateUserIdsLocked();
1088                    Bundle restrictions = new Bundle();
1089                    mUserRestrictions.append(userId, restrictions);
1090                }
1091            }
1092            if (userInfo != null) {
1093                Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1094                addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1095                mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1096                        android.Manifest.permission.MANAGE_USERS);
1097            }
1098        } finally {
1099            Binder.restoreCallingIdentity(ident);
1100        }
1101        return userInfo;
1102    }
1103
1104    /**
1105     * Removes a user and all data directories created for that user. This method should be called
1106     * after the user's processes have been terminated.
1107     * @param userHandle the user's id
1108     */
1109    public boolean removeUser(int userHandle) {
1110        checkManageUsersPermission("Only the system can remove users");
1111        long ident = Binder.clearCallingIdentity();
1112        try {
1113            final UserInfo user;
1114            synchronized (mPackagesLock) {
1115                user = mUsers.get(userHandle);
1116                if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1117                    return false;
1118                }
1119                mRemovingUserIds.put(userHandle, true);
1120                try {
1121                    mAppOpsService.removeUser(userHandle);
1122                } catch (RemoteException e) {
1123                    Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1124                }
1125                // Set this to a partially created user, so that the user will be purged
1126                // on next startup, in case the runtime stops now before stopping and
1127                // removing the user completely.
1128                user.partial = true;
1129                // Mark it as disabled, so that it isn't returned any more when
1130                // profiles are queried.
1131                user.flags |= UserInfo.FLAG_DISABLED;
1132                writeUserLocked(user);
1133            }
1134
1135            if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1136                    && user.isManagedProfile()) {
1137                // Send broadcast to notify system that the user removed was a
1138                // managed user.
1139                sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1140            }
1141
1142            if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1143            int res;
1144            try {
1145                res = ActivityManagerNative.getDefault().stopUser(userHandle,
1146                        new IStopUserCallback.Stub() {
1147                            @Override
1148                            public void userStopped(int userId) {
1149                                finishRemoveUser(userId);
1150                            }
1151                            @Override
1152                            public void userStopAborted(int userId) {
1153                            }
1154                        });
1155            } catch (RemoteException e) {
1156                return false;
1157            }
1158            return res == ActivityManager.USER_OP_SUCCESS;
1159        } finally {
1160            Binder.restoreCallingIdentity(ident);
1161        }
1162    }
1163
1164    void finishRemoveUser(final int userHandle) {
1165        if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
1166        // Let other services shutdown any activity and clean up their state before completely
1167        // wiping the user's system directory and removing from the user list
1168        long ident = Binder.clearCallingIdentity();
1169        try {
1170            Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1171            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
1172            mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1173                    android.Manifest.permission.MANAGE_USERS,
1174
1175                    new BroadcastReceiver() {
1176                        @Override
1177                        public void onReceive(Context context, Intent intent) {
1178                            if (DBG) {
1179                                Slog.i(LOG_TAG,
1180                                        "USER_REMOVED broadcast sent, cleaning up user data "
1181                                        + userHandle);
1182                            }
1183                            new Thread() {
1184                                public void run() {
1185                                    synchronized (mInstallLock) {
1186                                        synchronized (mPackagesLock) {
1187                                            removeUserStateLocked(userHandle);
1188                                        }
1189                                    }
1190                                }
1191                            }.start();
1192                        }
1193                    },
1194
1195                    null, Activity.RESULT_OK, null, null);
1196        } finally {
1197            Binder.restoreCallingIdentity(ident);
1198        }
1199    }
1200
1201    private void removeUserStateLocked(final int userHandle) {
1202        // Cleanup package manager settings
1203        mPm.cleanUpUserLILPw(userHandle);
1204
1205        // Remove this user from the list
1206        mUsers.remove(userHandle);
1207
1208        // Have user ID linger for several seconds to let external storage VFS
1209        // cache entries expire. This must be greater than the 'entry_valid'
1210        // timeout used by the FUSE daemon.
1211        mHandler.postDelayed(new Runnable() {
1212            @Override
1213            public void run() {
1214                synchronized (mPackagesLock) {
1215                    mRemovingUserIds.delete(userHandle);
1216                }
1217            }
1218        }, MINUTE_IN_MILLIS);
1219
1220        mRestrictionsPinStates.remove(userHandle);
1221        // Remove user file
1222        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
1223        userFile.delete();
1224        // Update the user list
1225        writeUserListLocked();
1226        updateUserIdsLocked();
1227        removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1228    }
1229
1230    private void removeDirectoryRecursive(File parent) {
1231        if (parent.isDirectory()) {
1232            String[] files = parent.list();
1233            for (String filename : files) {
1234                File child = new File(parent, filename);
1235                removeDirectoryRecursive(child);
1236            }
1237        }
1238        parent.delete();
1239    }
1240
1241    private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
1242        Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
1243        managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1244                Intent.FLAG_RECEIVER_FOREGROUND);
1245        managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1246        mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
1247    }
1248
1249    @Override
1250    public Bundle getApplicationRestrictions(String packageName) {
1251        return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1252    }
1253
1254    @Override
1255    public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
1256        if (UserHandle.getCallingUserId() != userId
1257                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
1258            checkManageUsersPermission("Only system can get restrictions for other users/apps");
1259        }
1260        synchronized (mPackagesLock) {
1261            // Read the restrictions from XML
1262            return readApplicationRestrictionsLocked(packageName, userId);
1263        }
1264    }
1265
1266    @Override
1267    public void setApplicationRestrictions(String packageName, Bundle restrictions,
1268            int userId) {
1269        if (UserHandle.getCallingUserId() != userId
1270                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
1271            checkManageUsersPermission("Only system can set restrictions for other users/apps");
1272        }
1273        synchronized (mPackagesLock) {
1274            // Write the restrictions to XML
1275            writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1276        }
1277
1278        // Notify package of changes via an intent - only sent to explicitly registered receivers.
1279        Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1280        changeIntent.setPackage(packageName);
1281        changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1282        mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1283    }
1284
1285    @Override
1286    public boolean setRestrictionsChallenge(String newPin) {
1287        checkManageUsersPermission("Only system can modify the restrictions pin");
1288        int userId = UserHandle.getCallingUserId();
1289        synchronized (mPackagesLock) {
1290            RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1291            if (pinState == null) {
1292                pinState = new RestrictionsPinState();
1293            }
1294            if (newPin == null) {
1295                pinState.salt = 0;
1296                pinState.pinHash = null;
1297            } else {
1298                try {
1299                    pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1300                } catch (NoSuchAlgorithmException e) {
1301                    pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1302                }
1303                pinState.pinHash = passwordToHash(newPin, pinState.salt);
1304                pinState.failedAttempts = 0;
1305            }
1306            mRestrictionsPinStates.put(userId, pinState);
1307            writeUserLocked(mUsers.get(userId));
1308        }
1309        return true;
1310    }
1311
1312    @Override
1313    public int checkRestrictionsChallenge(String pin) {
1314        checkManageUsersPermission("Only system can verify the restrictions pin");
1315        int userId = UserHandle.getCallingUserId();
1316        synchronized (mPackagesLock) {
1317            RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1318            // If there's no pin set, return error code
1319            if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1320                return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1321            } else if (pin == null) {
1322                // If just checking if user can be prompted, return remaining time
1323                int waitTime = getRemainingTimeForPinAttempt(pinState);
1324                Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1325                return waitTime;
1326            } else {
1327                int waitTime = getRemainingTimeForPinAttempt(pinState);
1328                Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1329                if (waitTime > 0) {
1330                    return waitTime;
1331                }
1332                if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1333                    pinState.failedAttempts = 0;
1334                    writeUserLocked(mUsers.get(userId));
1335                    return UserManager.PIN_VERIFICATION_SUCCESS;
1336                } else {
1337                    pinState.failedAttempts++;
1338                    pinState.lastAttemptTime = System.currentTimeMillis();
1339                    writeUserLocked(mUsers.get(userId));
1340                    return waitTime;
1341                }
1342            }
1343        }
1344    }
1345
1346    private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1347        int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1348                BACKOFF_TIMES.length - 1);
1349        int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1350                BACKOFF_TIMES[backoffIndex] : 0;
1351        return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1352                0);
1353    }
1354
1355    @Override
1356    public boolean hasRestrictionsChallenge() {
1357        int userId = UserHandle.getCallingUserId();
1358        synchronized (mPackagesLock) {
1359            return hasRestrictionsPinLocked(userId);
1360        }
1361    }
1362
1363    private boolean hasRestrictionsPinLocked(int userId) {
1364        RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1365        if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1366            return false;
1367        }
1368        return true;
1369    }
1370
1371    @Override
1372    public void removeRestrictions() {
1373        checkManageUsersPermission("Only system can remove restrictions");
1374        final int userHandle = UserHandle.getCallingUserId();
1375        removeRestrictionsForUser(userHandle, true);
1376    }
1377
1378    private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
1379        synchronized (mPackagesLock) {
1380            // Remove all user restrictions
1381            setUserRestrictions(new Bundle(), userHandle);
1382            // Remove restrictions pin
1383            setRestrictionsChallenge(null);
1384            // Remove any app restrictions
1385            cleanAppRestrictions(userHandle, true);
1386        }
1387        if (unblockApps) {
1388            unblockAllAppsForUser(userHandle);
1389        }
1390    }
1391
1392    private void unblockAllAppsForUser(final int userHandle) {
1393        mHandler.post(new Runnable() {
1394            @Override
1395            public void run() {
1396                List<ApplicationInfo> apps =
1397                        mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1398                                userHandle).getList();
1399                final long ident = Binder.clearCallingIdentity();
1400                try {
1401                    for (ApplicationInfo appInfo : apps) {
1402                        if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1403                                && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1404                            mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1405                                    userHandle);
1406                        }
1407                    }
1408                } finally {
1409                    Binder.restoreCallingIdentity(ident);
1410                }
1411            }
1412        });
1413    }
1414
1415    /*
1416     * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1417     * Not the most secure, but it is at least a second level of protection. First level is that
1418     * the file is in a location only readable by the system process.
1419     * @param password the password.
1420     * @param salt the randomly generated salt
1421     * @return the hash of the pattern in a String.
1422     */
1423    private String passwordToHash(String password, long salt) {
1424        if (password == null) {
1425            return null;
1426        }
1427        String algo = null;
1428        String hashed = salt + password;
1429        try {
1430            byte[] saltedPassword = (password + salt).getBytes();
1431            byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1432            byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1433            hashed = toHex(sha1) + toHex(md5);
1434        } catch (NoSuchAlgorithmException e) {
1435            Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1436        }
1437        return hashed;
1438    }
1439
1440    private static String toHex(byte[] ary) {
1441        final String hex = "0123456789ABCDEF";
1442        String ret = "";
1443        for (int i = 0; i < ary.length; i++) {
1444            ret += hex.charAt((ary[i] >> 4) & 0xf);
1445            ret += hex.charAt(ary[i] & 0xf);
1446        }
1447        return ret;
1448    }
1449
1450    private int getUidForPackage(String packageName) {
1451        long ident = Binder.clearCallingIdentity();
1452        try {
1453            return mContext.getPackageManager().getApplicationInfo(packageName,
1454                    PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1455        } catch (NameNotFoundException nnfe) {
1456            return -1;
1457        } finally {
1458            Binder.restoreCallingIdentity(ident);
1459        }
1460    }
1461
1462    private Bundle readApplicationRestrictionsLocked(String packageName,
1463            int userId) {
1464        final Bundle restrictions = new Bundle();
1465        final ArrayList<String> values = new ArrayList<String>();
1466
1467        FileInputStream fis = null;
1468        try {
1469            AtomicFile restrictionsFile =
1470                    new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1471                            packageToRestrictionsFileName(packageName)));
1472            fis = restrictionsFile.openRead();
1473            XmlPullParser parser = Xml.newPullParser();
1474            parser.setInput(fis, null);
1475            int type;
1476            while ((type = parser.next()) != XmlPullParser.START_TAG
1477                    && type != XmlPullParser.END_DOCUMENT) {
1478                ;
1479            }
1480
1481            if (type != XmlPullParser.START_TAG) {
1482                Slog.e(LOG_TAG, "Unable to read restrictions file "
1483                        + restrictionsFile.getBaseFile());
1484                return restrictions;
1485            }
1486
1487            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1488                if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1489                    String key = parser.getAttributeValue(null, ATTR_KEY);
1490                    String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1491                    String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1492                    if (multiple != null) {
1493                        int count = Integer.parseInt(multiple);
1494                        while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1495                            if (type == XmlPullParser.START_TAG
1496                                    && parser.getName().equals(TAG_VALUE)) {
1497                                values.add(parser.nextText().trim());
1498                                count--;
1499                            }
1500                        }
1501                        String [] valueStrings = new String[values.size()];
1502                        values.toArray(valueStrings);
1503                        restrictions.putStringArray(key, valueStrings);
1504                    } else {
1505                        String value = parser.nextText().trim();
1506                        if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1507                            restrictions.putBoolean(key, Boolean.parseBoolean(value));
1508                        } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1509                            restrictions.putInt(key, Integer.parseInt(value));
1510                        } else {
1511                            restrictions.putString(key, value);
1512                        }
1513                    }
1514                }
1515            }
1516        } catch (IOException ioe) {
1517        } catch (XmlPullParserException pe) {
1518        } finally {
1519            if (fis != null) {
1520                try {
1521                    fis.close();
1522                } catch (IOException e) {
1523                }
1524            }
1525        }
1526        return restrictions;
1527    }
1528
1529    private void writeApplicationRestrictionsLocked(String packageName,
1530            Bundle restrictions, int userId) {
1531        FileOutputStream fos = null;
1532        AtomicFile restrictionsFile = new AtomicFile(
1533                new File(Environment.getUserSystemDirectory(userId),
1534                        packageToRestrictionsFileName(packageName)));
1535        try {
1536            fos = restrictionsFile.startWrite();
1537            final BufferedOutputStream bos = new BufferedOutputStream(fos);
1538
1539            // XmlSerializer serializer = XmlUtils.serializerInstance();
1540            final XmlSerializer serializer = new FastXmlSerializer();
1541            serializer.setOutput(bos, "utf-8");
1542            serializer.startDocument(null, true);
1543            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1544
1545            serializer.startTag(null, TAG_RESTRICTIONS);
1546
1547            for (String key : restrictions.keySet()) {
1548                Object value = restrictions.get(key);
1549                serializer.startTag(null, TAG_ENTRY);
1550                serializer.attribute(null, ATTR_KEY, key);
1551
1552                if (value instanceof Boolean) {
1553                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1554                    serializer.text(value.toString());
1555                } else if (value instanceof Integer) {
1556                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1557                    serializer.text(value.toString());
1558                } else if (value == null || value instanceof String) {
1559                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1560                    serializer.text(value != null ? (String) value : "");
1561                } else {
1562                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1563                    String[] values = (String[]) value;
1564                    serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1565                    for (String choice : values) {
1566                        serializer.startTag(null, TAG_VALUE);
1567                        serializer.text(choice != null ? choice : "");
1568                        serializer.endTag(null, TAG_VALUE);
1569                    }
1570                }
1571                serializer.endTag(null, TAG_ENTRY);
1572            }
1573
1574            serializer.endTag(null, TAG_RESTRICTIONS);
1575
1576            serializer.endDocument();
1577            restrictionsFile.finishWrite(fos);
1578        } catch (Exception e) {
1579            restrictionsFile.failWrite(fos);
1580            Slog.e(LOG_TAG, "Error writing application restrictions list");
1581        }
1582    }
1583
1584    @Override
1585    public int getUserSerialNumber(int userHandle) {
1586        synchronized (mPackagesLock) {
1587            if (!exists(userHandle)) return -1;
1588            return getUserInfoLocked(userHandle).serialNumber;
1589        }
1590    }
1591
1592    @Override
1593    public int getUserHandle(int userSerialNumber) {
1594        synchronized (mPackagesLock) {
1595            for (int userId : mUserIds) {
1596                if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
1597            }
1598            // Not found
1599            return -1;
1600        }
1601    }
1602
1603    /**
1604     * Caches the list of user ids in an array, adjusting the array size when necessary.
1605     */
1606    private void updateUserIdsLocked() {
1607        int num = 0;
1608        for (int i = 0; i < mUsers.size(); i++) {
1609            if (!mUsers.valueAt(i).partial) {
1610                num++;
1611            }
1612        }
1613        final int[] newUsers = new int[num];
1614        int n = 0;
1615        for (int i = 0; i < mUsers.size(); i++) {
1616            if (!mUsers.valueAt(i).partial) {
1617                newUsers[n++] = mUsers.keyAt(i);
1618            }
1619        }
1620        mUserIds = newUsers;
1621    }
1622
1623    /**
1624     * Make a note of the last started time of a user and do some cleanup.
1625     * @param userId the user that was just foregrounded
1626     */
1627    public void userForeground(int userId) {
1628        synchronized (mPackagesLock) {
1629            UserInfo user = mUsers.get(userId);
1630            long now = System.currentTimeMillis();
1631            if (user == null || user.partial) {
1632                Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1633                return;
1634            }
1635            if (now > EPOCH_PLUS_30_YEARS) {
1636                user.lastLoggedInTime = now;
1637                writeUserLocked(user);
1638            }
1639            // If this is not a restricted profile and there is no restrictions pin, clean up
1640            // all restrictions files that might have been left behind, else clean up just the
1641            // ones with uninstalled packages
1642            RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1643            final long salt = pinState == null ? 0 : pinState.salt;
1644            cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
1645        }
1646    }
1647
1648    /**
1649     * Returns the next available user id, filling in any holes in the ids.
1650     * TODO: May not be a good idea to recycle ids, in case it results in confusion
1651     * for data and battery stats collection, or unexpected cross-talk.
1652     * @return
1653     */
1654    private int getNextAvailableIdLocked() {
1655        synchronized (mPackagesLock) {
1656            int i = MIN_USER_ID;
1657            while (i < Integer.MAX_VALUE) {
1658                if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
1659                    break;
1660                }
1661                i++;
1662            }
1663            return i;
1664        }
1665    }
1666
1667    private String packageToRestrictionsFileName(String packageName) {
1668        return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1669    }
1670
1671    private String restrictionsFileNameToPackage(String fileName) {
1672        return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1673                (int) (fileName.length() - XML_SUFFIX.length()));
1674    }
1675
1676    @Override
1677    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1678        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1679                != PackageManager.PERMISSION_GRANTED) {
1680            pw.println("Permission Denial: can't dump UserManager from from pid="
1681                    + Binder.getCallingPid()
1682                    + ", uid=" + Binder.getCallingUid()
1683                    + " without permission "
1684                    + android.Manifest.permission.DUMP);
1685            return;
1686        }
1687
1688        long now = System.currentTimeMillis();
1689        StringBuilder sb = new StringBuilder();
1690        synchronized (mPackagesLock) {
1691            pw.println("Users:");
1692            for (int i = 0; i < mUsers.size(); i++) {
1693                UserInfo user = mUsers.valueAt(i);
1694                if (user == null) continue;
1695                pw.print("  "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
1696                if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
1697                if (user.partial) pw.print(" <partial>");
1698                pw.println();
1699                pw.print("    Created: ");
1700                if (user.creationTime == 0) {
1701                    pw.println("<unknown>");
1702                } else {
1703                    sb.setLength(0);
1704                    TimeUtils.formatDuration(now - user.creationTime, sb);
1705                    sb.append(" ago");
1706                    pw.println(sb);
1707                }
1708                pw.print("    Last logged in: ");
1709                if (user.lastLoggedInTime == 0) {
1710                    pw.println("<unknown>");
1711                } else {
1712                    sb.setLength(0);
1713                    TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1714                    sb.append(" ago");
1715                    pw.println(sb);
1716                }
1717            }
1718        }
1719    }
1720
1721    private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1722        @Override
1723        public void onPackageRemoved(String pkg, int uid) {
1724            final int userId = this.getChangingUserId();
1725            // Package could be disappearing because it is being blocked, so also check if
1726            // it has been uninstalled.
1727            final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1728            if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1729                cleanAppRestrictionsForPackage(pkg, userId);
1730            }
1731        }
1732    };
1733}
1734