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