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