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