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