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