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