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