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