UserManagerService.java revision 5d7e9516861b8248f728641d7ae7a54b82a1255d
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 android.annotation.NonNull;
20import android.annotation.Nullable;
21import android.app.Activity;
22import android.app.ActivityManager;
23import android.app.ActivityManagerInternal;
24import android.app.ActivityManagerNative;
25import android.app.IActivityManager;
26import android.app.IStopUserCallback;
27import android.app.admin.DevicePolicyManager;
28import android.app.admin.DevicePolicyManagerInternal;
29import android.content.BroadcastReceiver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.pm.ApplicationInfo;
33import android.content.pm.PackageManager;
34import android.content.pm.PackageManager.NameNotFoundException;
35import android.content.pm.UserInfo;
36import android.graphics.Bitmap;
37import android.os.Binder;
38import android.os.Bundle;
39import android.os.Environment;
40import android.os.FileUtils;
41import android.os.Handler;
42import android.os.IUserManager;
43import android.os.Message;
44import android.os.ParcelFileDescriptor;
45import android.os.Parcelable;
46import android.os.Process;
47import android.os.RemoteException;
48import android.os.ResultReceiver;
49import android.os.ServiceManager;
50import android.os.ShellCommand;
51import android.os.SystemProperties;
52import android.os.UserHandle;
53import android.os.UserManager;
54import android.os.UserManagerInternal;
55import android.os.UserManagerInternal.UserRestrictionsListener;
56import android.os.storage.StorageManager;
57import android.os.storage.VolumeInfo;
58import android.system.ErrnoException;
59import android.system.Os;
60import android.system.OsConstants;
61import android.util.AtomicFile;
62import android.util.Log;
63import android.util.Slog;
64import android.util.SparseArray;
65import android.util.SparseBooleanArray;
66import android.util.TimeUtils;
67import android.util.Xml;
68
69import com.android.internal.annotations.GuardedBy;
70import com.android.internal.annotations.VisibleForTesting;
71import com.android.internal.app.IAppOpsService;
72import com.android.internal.util.FastXmlSerializer;
73import com.android.internal.util.Preconditions;
74import com.android.internal.util.XmlUtils;
75import com.android.server.LocalServices;
76
77import org.xmlpull.v1.XmlPullParser;
78import org.xmlpull.v1.XmlPullParserException;
79import org.xmlpull.v1.XmlSerializer;
80
81import java.io.BufferedOutputStream;
82import java.io.File;
83import java.io.FileDescriptor;
84import java.io.FileInputStream;
85import java.io.FileNotFoundException;
86import java.io.FileOutputStream;
87import java.io.IOException;
88import java.io.PrintWriter;
89import java.nio.charset.StandardCharsets;
90import java.util.ArrayList;
91import java.util.List;
92
93import libcore.io.IoUtils;
94
95/**
96 * Service for {@link UserManager}.
97 *
98 * Method naming convention:
99 * <ul>
100 * <li> Methods suffixed with "LILP" should be called within {@link #mInstallLock} and
101 * {@link #mPackagesLock} locks obtained in the respective order.
102 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
103 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
104 * </ul>
105 */
106public class UserManagerService extends IUserManager.Stub {
107    private static final String LOG_TAG = "UserManagerService";
108    private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
109
110    private static final String TAG_NAME = "name";
111    private static final String ATTR_FLAGS = "flags";
112    private static final String ATTR_ICON_PATH = "icon";
113    private static final String ATTR_ID = "id";
114    private static final String ATTR_CREATION_TIME = "created";
115    private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
116    private static final String ATTR_SERIAL_NO = "serialNumber";
117    private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
118    private static final String ATTR_PARTIAL = "partial";
119    private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
120    private static final String ATTR_USER_VERSION = "version";
121    private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
122    private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
123    private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
124    private static final String TAG_USERS = "users";
125    private static final String TAG_USER = "user";
126    private static final String TAG_RESTRICTIONS = "restrictions";
127    private static final String TAG_ENTRY = "entry";
128    private static final String TAG_VALUE = "value";
129    private static final String ATTR_KEY = "key";
130    private static final String ATTR_VALUE_TYPE = "type";
131    private static final String ATTR_MULTIPLE = "m";
132
133    private static final String ATTR_TYPE_STRING_ARRAY = "sa";
134    private static final String ATTR_TYPE_STRING = "s";
135    private static final String ATTR_TYPE_BOOLEAN = "b";
136    private static final String ATTR_TYPE_INTEGER = "i";
137    private static final String ATTR_TYPE_BUNDLE = "B";
138    private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
139
140    private static final String USER_INFO_DIR = "system" + File.separator + "users";
141    private static final String USER_LIST_FILENAME = "userlist.xml";
142    private static final String USER_PHOTO_FILENAME = "photo.png";
143    private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
144
145    private static final String RESTRICTIONS_FILE_PREFIX = "res_";
146    private static final String XML_SUFFIX = ".xml";
147
148    private static final int MIN_USER_ID = 10;
149    // We need to keep process uid within Integer.MAX_VALUE.
150    private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
151
152    private static final int USER_VERSION = 6;
153
154    private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
155
156    // Maximum number of managed profiles permitted per user is 1. This cannot be increased
157    // without first making sure that the rest of the framework is prepared for it.
158    private static final int MAX_MANAGED_PROFILES = 1;
159
160    static final int WRITE_USER_MSG = 1;
161    static final int WRITE_USER_DELAY = 2*1000;  // 2 seconds
162
163    private static final String XATTR_SERIAL = "user.serial";
164
165    private final Context mContext;
166    private final PackageManagerService mPm;
167    private final Object mInstallLock;
168    private final Object mPackagesLock;
169    // Short-term lock for internal state, when interaction/sync with PM is not required
170    private final Object mUsersLock = new Object();
171    private final Object mRestrictionsLock = new Object();
172
173    private final Handler mHandler;
174
175    private final File mUsersDir;
176    private final File mUserListFile;
177
178    @GuardedBy("mUsersLock")
179    private final SparseArray<UserInfo> mUsers = new SparseArray<>();
180
181    /**
182     * User restrictions set via UserManager.  This doesn't include restrictions set by
183     * device owner / profile owners.
184     *
185     * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
186     * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
187     * maybe shared between {@link #mBaseUserRestrictions} and
188     * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
189     * (Otherwise we won't be able to detect what restrictions have changed in
190     * {@link #updateUserRestrictionsInternalLR}.
191     */
192    @GuardedBy("mRestrictionsLock")
193    private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
194
195    /**
196     * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
197     * with device / profile owner restrictions.  We'll initialize it lazily; use
198     * {@link #getEffectiveUserRestrictions} to access it.
199     *
200     * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
201     * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
202     * maybe shared between {@link #mBaseUserRestrictions} and
203     * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
204     * (Otherwise we won't be able to detect what restrictions have changed in
205     * {@link #updateUserRestrictionsInternalLR}.
206     */
207    @GuardedBy("mRestrictionsLock")
208    private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
209
210    /**
211     * User restrictions that have already been applied in {@link #applyUserRestrictionsLR}.  We
212     * use it to detect restrictions that have changed since the last
213     * {@link #applyUserRestrictionsLR} call.
214     */
215    @GuardedBy("mRestrictionsLock")
216    private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
217
218    private final Bundle mGuestRestrictions = new Bundle();
219
220    /**
221     * Set of user IDs being actively removed. Removed IDs linger in this set
222     * for several seconds to work around a VFS caching issue.
223     */
224    @GuardedBy("mUsersLock")
225    private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
226
227    @GuardedBy("mUsersLock")
228    private int[] mUserIds;
229    private int mNextSerialNumber;
230    private int mUserVersion = 0;
231
232    private IAppOpsService mAppOpsService;
233
234    private final LocalService mLocalService;
235
236    @GuardedBy("mUserRestrictionsListeners")
237    private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
238            new ArrayList<>();
239
240    private static UserManagerService sInstance;
241
242    public static UserManagerService getInstance() {
243        synchronized (UserManagerService.class) {
244            return sInstance;
245        }
246    }
247
248    /**
249     * Available for testing purposes.
250     */
251    UserManagerService(File dataDir, File baseUserPath) {
252        this(null, null, new Object(), new Object(), dataDir, baseUserPath);
253    }
254
255    /**
256     * Called by package manager to create the service.  This is closely
257     * associated with the package manager, and the given lock is the
258     * package manager's own lock.
259     */
260    UserManagerService(Context context, PackageManagerService pm,
261            Object installLock, Object packagesLock) {
262        this(context, pm, installLock, packagesLock,
263                Environment.getDataDirectory(),
264                new File(Environment.getDataDirectory(), "user"));
265    }
266
267    /**
268     * Available for testing purposes.
269     */
270    private UserManagerService(Context context, PackageManagerService pm,
271            Object installLock, Object packagesLock,
272            File dataDir, File baseUserPath) {
273        mContext = context;
274        mPm = pm;
275        mInstallLock = installLock;
276        mPackagesLock = packagesLock;
277        mHandler = new MainHandler();
278        synchronized (mInstallLock) {
279            synchronized (mPackagesLock) {
280                mUsersDir = new File(dataDir, USER_INFO_DIR);
281                mUsersDir.mkdirs();
282                // Make zeroth user directory, for services to migrate their files to that location
283                File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
284                userZeroDir.mkdirs();
285                FileUtils.setPermissions(mUsersDir.toString(),
286                        FileUtils.S_IRWXU|FileUtils.S_IRWXG
287                        |FileUtils.S_IROTH|FileUtils.S_IXOTH,
288                        -1, -1);
289                mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
290                initDefaultGuestRestrictions();
291                readUserListLILP();
292                sInstance = this;
293            }
294        }
295        mLocalService = new LocalService();
296        LocalServices.addService(UserManagerInternal.class, mLocalService);
297    }
298
299    void systemReady() {
300        synchronized (mInstallLock) {
301            synchronized (mPackagesLock) {
302                synchronized (mUsersLock) {
303                    // Prune out any partially created/partially removed users.
304                    ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
305                    final int userSize = mUsers.size();
306                    for (int i = 0; i < userSize; i++) {
307                        UserInfo ui = mUsers.valueAt(i);
308                        if ((ui.partial || ui.guestToRemove) && i != 0) {
309                            partials.add(ui);
310                        }
311                    }
312                    final int partialsSize = partials.size();
313                    for (int i = 0; i < partialsSize; i++) {
314                        UserInfo ui = partials.get(i);
315                        Slog.w(LOG_TAG, "Removing partially created user " + ui.id
316                                + " (name=" + ui.name + ")");
317                        removeUserStateLILP(ui.id);
318                    }
319                }
320            }
321        }
322        onUserForeground(UserHandle.USER_SYSTEM);
323        mAppOpsService = IAppOpsService.Stub.asInterface(
324                ServiceManager.getService(Context.APP_OPS_SERVICE));
325        for (int i = 0; i < mUserIds.length; ++i) {
326            final int userId = mUserIds[i];
327            try {
328                mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
329            } catch (RemoteException e) {
330                Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
331            }
332        }
333    }
334
335    @Override
336    public UserInfo getPrimaryUser() {
337        checkManageUsersPermission("query users");
338        synchronized (mUsersLock) {
339            final int userSize = mUsers.size();
340            for (int i = 0; i < userSize; i++) {
341                UserInfo ui = mUsers.valueAt(i);
342                if (ui.isPrimary()) {
343                    return ui;
344                }
345            }
346        }
347        return null;
348    }
349
350    @Override
351    public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
352        checkManageUsersPermission("query users");
353        synchronized (mUsersLock) {
354            ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
355            final int userSize = mUsers.size();
356            for (int i = 0; i < userSize; i++) {
357                UserInfo ui = mUsers.valueAt(i);
358                if (ui.partial) {
359                    continue;
360                }
361                if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
362                    users.add(ui);
363                }
364            }
365            return users;
366        }
367    }
368
369    @Override
370    public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
371        if (userId != UserHandle.getCallingUserId()) {
372            checkManageUsersPermission("getting profiles related to user " + userId);
373        }
374        final long ident = Binder.clearCallingIdentity();
375        try {
376            synchronized (mUsersLock) {
377                return getProfilesLU(userId, enabledOnly);
378            }
379        } finally {
380            Binder.restoreCallingIdentity(ident);
381        }
382    }
383
384    /** Assume permissions already checked and caller's identity cleared */
385    private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
386        UserInfo user = getUserInfoLU(userId);
387        ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
388        if (user == null) {
389            // Probably a dying user
390            return users;
391        }
392        final int userSize = mUsers.size();
393        for (int i = 0; i < userSize; i++) {
394            UserInfo profile = mUsers.valueAt(i);
395            if (!isProfileOf(user, profile)) {
396                continue;
397            }
398            if (enabledOnly && !profile.isEnabled()) {
399                continue;
400            }
401            if (mRemovingUserIds.get(profile.id)) {
402                continue;
403            }
404            users.add(profile);
405        }
406        return users;
407    }
408
409    @Override
410    public int getCredentialOwnerProfile(int userHandle) {
411        checkManageUsersPermission("get the credential owner");
412        if (!mContext.getSystemService(StorageManager.class).isPerUserEncryptionEnabled()) {
413            synchronized (mUsersLock) {
414                UserInfo profileParent = getProfileParentLU(userHandle);
415                if (profileParent != null) {
416                    return profileParent.id;
417                }
418            }
419        }
420
421        return userHandle;
422    }
423
424    @Override
425    public boolean isSameProfileGroup(int userId, int otherUserId) {
426        if (userId == otherUserId) return true;
427        checkManageUsersPermission("check if in the same profile group");
428        synchronized (mPackagesLock) {
429            return isSameProfileGroupLP(userId, otherUserId);
430        }
431    }
432
433    private boolean isSameProfileGroupLP(int userId, int otherUserId) {
434        synchronized (mUsersLock) {
435            UserInfo userInfo = getUserInfoLU(userId);
436            if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
437                return false;
438            }
439            UserInfo otherUserInfo = getUserInfoLU(otherUserId);
440            if (otherUserInfo == null
441                    || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
442                return false;
443            }
444            return userInfo.profileGroupId == otherUserInfo.profileGroupId;
445        }
446    }
447
448    @Override
449    public UserInfo getProfileParent(int userHandle) {
450        checkManageUsersPermission("get the profile parent");
451        synchronized (mUsersLock) {
452            return getProfileParentLU(userHandle);
453        }
454    }
455
456    private UserInfo getProfileParentLU(int userHandle) {
457        UserInfo profile = getUserInfoLU(userHandle);
458        if (profile == null) {
459            return null;
460        }
461        int parentUserId = profile.profileGroupId;
462        if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
463            return null;
464        } else {
465            return getUserInfoLU(parentUserId);
466        }
467    }
468
469    private static boolean isProfileOf(UserInfo user, UserInfo profile) {
470        return user.id == profile.id ||
471                (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
472                && user.profileGroupId == profile.profileGroupId);
473    }
474
475    @Override
476    public void setUserEnabled(int userId) {
477        checkManageUsersPermission("enable user");
478        synchronized (mPackagesLock) {
479            UserInfo info;
480            synchronized (mUsersLock) {
481                info = getUserInfoLU(userId);
482            }
483            if (info != null && !info.isEnabled()) {
484                info.flags ^= UserInfo.FLAG_DISABLED;
485                writeUserLP(info);
486            }
487        }
488    }
489
490    @Override
491    public UserInfo getUserInfo(int userId) {
492        checkManageUsersPermission("query user");
493        synchronized (mUsersLock) {
494            return getUserInfoLU(userId);
495        }
496    }
497
498    @Override
499    public boolean isRestricted() {
500        synchronized (mUsersLock) {
501            return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
502        }
503    }
504
505    @Override
506    public boolean canHaveRestrictedProfile(int userId) {
507        checkManageUsersPermission("canHaveRestrictedProfile");
508        synchronized (mUsersLock) {
509            final UserInfo userInfo = getUserInfoLU(userId);
510            if (userInfo == null || !userInfo.canHaveProfile()) {
511                return false;
512            }
513            if (!userInfo.isAdmin()) {
514                return false;
515            }
516        }
517        DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
518                Context.DEVICE_POLICY_SERVICE);
519        // restricted profile can be created if there is no DO set and the admin user has no PO
520        return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
521    }
522
523    /*
524     * Should be locked on mUsers before calling this.
525     */
526    private UserInfo getUserInfoLU(int userId) {
527        UserInfo ui = mUsers.get(userId);
528        // If it is partial and not in the process of being removed, return as unknown user.
529        if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
530            Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
531            return null;
532        }
533        return ui;
534    }
535
536    /**
537     * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
538     * <p>No permissions checking or any addition checks are made</p>
539     */
540    private UserInfo getUserInfoNoChecks(int userId) {
541        synchronized (mUsersLock) {
542            return mUsers.get(userId);
543        }
544    }
545
546    /** Called by PackageManagerService */
547    public boolean exists(int userId) {
548        return getUserInfoNoChecks(userId) != null;
549    }
550
551    @Override
552    public void setUserName(int userId, String name) {
553        checkManageUsersPermission("rename users");
554        boolean changed = false;
555        synchronized (mPackagesLock) {
556            UserInfo info = getUserInfoNoChecks(userId);
557            if (info == null || info.partial) {
558                Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
559                return;
560            }
561            if (name != null && !name.equals(info.name)) {
562                info.name = name;
563                writeUserLP(info);
564                changed = true;
565            }
566        }
567        if (changed) {
568            sendUserInfoChangedBroadcast(userId);
569        }
570    }
571
572    @Override
573    public void setUserIcon(int userId, Bitmap bitmap) {
574        checkManageUsersPermission("update users");
575        long ident = Binder.clearCallingIdentity();
576        try {
577            synchronized (mPackagesLock) {
578                UserInfo info = getUserInfoNoChecks(userId);
579                if (info == null || info.partial) {
580                    Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
581                    return;
582                }
583                writeBitmapLP(info, bitmap);
584                writeUserLP(info);
585            }
586            sendUserInfoChangedBroadcast(userId);
587        } finally {
588            Binder.restoreCallingIdentity(ident);
589        }
590    }
591
592    private void sendUserInfoChangedBroadcast(int userId) {
593        Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
594        changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
595        changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
596        mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
597    }
598
599    @Override
600    public ParcelFileDescriptor getUserIcon(int userId) {
601        String iconPath;
602        synchronized (mPackagesLock) {
603            UserInfo info = getUserInfoNoChecks(userId);
604            if (info == null || info.partial) {
605                Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
606                return null;
607            }
608            int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
609            if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
610                    || callingGroupId != info.profileGroupId) {
611                checkManageUsersPermission("get the icon of a user who is not related");
612            }
613            if (info.iconPath == null) {
614                return null;
615            }
616            iconPath = info.iconPath;
617        }
618
619        try {
620            return ParcelFileDescriptor.open(
621                    new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
622        } catch (FileNotFoundException e) {
623            Log.e(LOG_TAG, "Couldn't find icon file", e);
624        }
625        return null;
626    }
627
628    public void makeInitialized(int userId) {
629        checkManageUsersPermission("makeInitialized");
630        synchronized (mPackagesLock) {
631            UserInfo info = getUserInfoNoChecks(userId);
632            if (info == null || info.partial) {
633                Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
634                // TODO Check if we should return here instead of a null check below
635            }
636            if (info != null && (info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
637                info.flags |= UserInfo.FLAG_INITIALIZED;
638                scheduleWriteUser(info);
639            }
640        }
641    }
642
643    /**
644     * If default guest restrictions haven't been initialized yet, add the basic
645     * restrictions.
646     */
647    private void initDefaultGuestRestrictions() {
648        if (mGuestRestrictions.isEmpty()) {
649            mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
650            mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
651        }
652    }
653
654    @Override
655    public Bundle getDefaultGuestRestrictions() {
656        checkManageUsersPermission("getDefaultGuestRestrictions");
657        // TODO Switch to mGuestRestrictions for locking
658        synchronized (mPackagesLock) {
659            return new Bundle(mGuestRestrictions);
660        }
661    }
662
663    @Override
664    public void setDefaultGuestRestrictions(Bundle restrictions) {
665        checkManageUsersPermission("setDefaultGuestRestrictions");
666        synchronized (mInstallLock) {
667            synchronized (mPackagesLock) {
668                mGuestRestrictions.clear();
669                mGuestRestrictions.putAll(restrictions);
670                writeUserListLILP();
671            }
672        }
673    }
674
675    @GuardedBy("mRestrictionsLock")
676    private Bundle computeEffectiveUserRestrictionsLR(int userId) {
677        final DevicePolicyManagerInternal dpmi =
678                LocalServices.getService(DevicePolicyManagerInternal.class);
679        final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
680
681        final Bundle effective;
682        if (dpmi == null) {
683            // TODO Make sure it's because DPMS is disabled and not because we called it too early.
684            effective = systemRestrictions;
685        } else {
686            effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
687        }
688        return effective;
689    }
690
691    @GuardedBy("mRestrictionsLock")
692    private void invalidateEffectiveUserRestrictionsLR(int userId) {
693        if (DBG) {
694            Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
695        }
696        mCachedEffectiveUserRestrictions.remove(userId);
697    }
698
699    private Bundle getEffectiveUserRestrictions(int userId) {
700        synchronized (mRestrictionsLock) {
701            Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
702            if (restrictions == null) {
703                restrictions = computeEffectiveUserRestrictionsLR(userId);
704                mCachedEffectiveUserRestrictions.put(userId, restrictions);
705            }
706            return restrictions;
707        }
708    }
709
710    /** @return a specific user restriction that's in effect currently. */
711    @Override
712    public boolean hasUserRestriction(String restrictionKey, int userId) {
713        Bundle restrictions = getEffectiveUserRestrictions(userId);
714        return restrictions != null && restrictions.getBoolean(restrictionKey);
715    }
716
717    /**
718     * @return UserRestrictions that are in effect currently.  This always returns a new
719     * {@link Bundle}.
720     */
721    @Override
722    public Bundle getUserRestrictions(int userId) {
723        Bundle restrictions = getEffectiveUserRestrictions(userId);
724        return restrictions != null ? new Bundle(restrictions) : new Bundle();
725    }
726
727    @Override
728    public void setUserRestriction(String key, boolean value, int userId) {
729        checkManageUsersPermission("setUserRestriction");
730        if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
731            setUserRestrictionNoCheck(key, value, userId);
732        }
733    }
734
735    @Override
736    public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
737        checkSystemOrRoot("setSystemControlledUserRestriction");
738        setUserRestrictionNoCheck(key, value, userId);
739    }
740
741    private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
742        synchronized (mRestrictionsLock) {
743            // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
744            // a copy.
745            final Bundle newRestrictions = new Bundle();
746            UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
747            newRestrictions.putBoolean(key, value);
748
749            updateUserRestrictionsInternalLR(newRestrictions, userId);
750        }
751    }
752
753    /**
754     * Optionally updating user restrictions, calculate the effective user restrictions by
755     * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
756     * apply it to {@link com.android.server.AppOpsService}.
757     * TODO applyUserRestrictionsLocked() should also apply to system settings.
758     *
759     * @param newRestrictions User restrictions to set.  If null, only the effective restrictions
760     *     will be updated.  Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
761     *     or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
762     * @param userId target user ID.
763     */
764    @GuardedBy("mRestrictionsLock")
765    private void updateUserRestrictionsInternalLR(
766            @Nullable Bundle newRestrictions, int userId) {
767        if (DBG) {
768            Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
769                    + " bundle=" + newRestrictions);
770        }
771        // Update system restrictions.
772        if (newRestrictions != null) {
773            // If newRestrictions == the current one, it's probably a bug.
774            Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
775            Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
776                    != newRestrictions);
777            mBaseUserRestrictions.put(userId, newRestrictions);
778            scheduleWriteUser(mUsers.get(userId));
779        }
780
781        final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
782
783        mCachedEffectiveUserRestrictions.put(userId, effective);
784
785        applyUserRestrictionsLR(userId, effective);
786    }
787
788    @GuardedBy("mRestrictionsLock")
789    private void applyUserRestrictionsLR(int userId, Bundle newRestrictions) {
790        if (newRestrictions == null) {
791            newRestrictions = Bundle.EMPTY;
792        }
793
794        Bundle prevRestrictions = mAppliedUserRestrictions.get(userId);
795        if (prevRestrictions == null) {
796            prevRestrictions = Bundle.EMPTY;
797        }
798
799        if (DBG) {
800            Log.d(LOG_TAG, "applyUserRestrictionsRL userId=" + userId
801                    + " new=" + newRestrictions + " prev=" + prevRestrictions);
802        }
803
804        final long token = Binder.clearCallingIdentity();
805        try {
806            mAppOpsService.setUserRestrictions(newRestrictions, userId);
807        } catch (RemoteException e) {
808            Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
809        } finally {
810            Binder.restoreCallingIdentity(token);
811        }
812
813        UserRestrictionsUtils.applyUserRestrictionsLR(
814                mContext, userId, newRestrictions, prevRestrictions);
815
816        notifyUserRestrictionsListeners(userId, newRestrictions, prevRestrictions);
817
818        mAppliedUserRestrictions.put(userId, new Bundle(newRestrictions));
819    }
820
821    private void notifyUserRestrictionsListeners(final int userId,
822            Bundle newRestrictions, Bundle prevRestrictions) {
823
824        final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
825        final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
826
827        mHandler.post(new Runnable() {
828            @Override
829            public void run() {
830                final UserRestrictionsListener[] listeners;
831                synchronized (mUserRestrictionsListeners) {
832                    listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
833                    mUserRestrictionsListeners.toArray(listeners);
834                }
835                for (int i = 0; i < listeners.length; i++) {
836                    listeners[i].onUserRestrictionsChanged(userId,
837                            newRestrictionsFinal, prevRestrictionsFinal);
838                }
839            }
840        });
841    }
842
843    @GuardedBy("mRestrictionsLock")
844    private void updateEffectiveUserRestrictionsLR(int userId) {
845        updateUserRestrictionsInternalLR(null, userId);
846    }
847
848    @GuardedBy("mRestrictionsLock")
849    private void updateEffectiveUserRestrictionsForAllUsersLR() {
850        // First, invalidate all cached values.
851        mCachedEffectiveUserRestrictions.clear();
852
853        // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
854        // it on a handler.
855        final Runnable r = new Runnable() {
856            @Override
857            public void run() {
858                // Then get the list of running users.
859                final int[] runningUsers;
860                try {
861                    runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
862                } catch (RemoteException e) {
863                    Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
864                    return;
865                }
866                // Then re-calculate the effective restrictions and apply, only for running users.
867                // It's okay if a new user has started after the getRunningUserIds() call,
868                // because we'll do the same thing (re-calculate the restrictions and apply)
869                // when we start a user.
870                // TODO: "Apply restrictions upon user start hasn't been implemented.  Implement it.
871                synchronized (mRestrictionsLock) {
872                    for (int i = 0; i < runningUsers.length; i++) {
873                        updateUserRestrictionsInternalLR(null, runningUsers[i]);
874                    }
875                }
876            }
877        };
878        mHandler.post(r);
879    }
880
881    /**
882     * Check if we've hit the limit of how many users can be created.
883     */
884    private boolean isUserLimitReached() {
885        int count;
886        synchronized (mUsersLock) {
887            count = getAliveUsersExcludingGuestsCountLU();
888        }
889        return count >= UserManager.getMaxSupportedUsers();
890    }
891
892    @Override
893    public boolean canAddMoreManagedProfiles(int userId) {
894        checkManageUsersPermission("check if more managed profiles can be added.");
895        if (ActivityManager.isLowRamDeviceStatic()) {
896            return false;
897        }
898        if (!mContext.getPackageManager().hasSystemFeature(
899                PackageManager.FEATURE_MANAGED_USERS)) {
900            return false;
901        }
902        // Limit number of managed profiles that can be created
903        int managedProfilesCount = getProfiles(userId, true).size() - 1;
904        if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
905            return false;
906        }
907        synchronized(mUsersLock) {
908            UserInfo userInfo = getUserInfoLU(userId);
909            if (!userInfo.canHaveProfile()) {
910                return false;
911            }
912            int usersCount = getAliveUsersExcludingGuestsCountLU();
913            // We allow creating a managed profile in the special case where there is only one user.
914            return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
915        }
916    }
917
918    private int getAliveUsersExcludingGuestsCountLU() {
919        int aliveUserCount = 0;
920        final int totalUserCount = mUsers.size();
921        // Skip over users being removed
922        for (int i = 0; i < totalUserCount; i++) {
923            UserInfo user = mUsers.valueAt(i);
924            if (!mRemovingUserIds.get(user.id)
925                    && !user.isGuest() && !user.partial) {
926                aliveUserCount++;
927            }
928        }
929        return aliveUserCount;
930    }
931
932    /**
933     * Enforces that only the system UID or root's UID or apps that have the
934     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
935     * permission can make certain calls to the UserManager.
936     *
937     * @param message used as message if SecurityException is thrown
938     * @throws SecurityException if the caller is not system or root
939     */
940    private static final void checkManageUsersPermission(String message) {
941        final int uid = Binder.getCallingUid();
942        if (uid != Process.SYSTEM_UID && uid != 0
943                && ActivityManager.checkComponentPermission(
944                        android.Manifest.permission.MANAGE_USERS,
945                        uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
946            throw new SecurityException("You need MANAGE_USERS permission to: " + message);
947        }
948    }
949
950    private static void checkSystemOrRoot(String message) {
951        final int uid = Binder.getCallingUid();
952        if (uid != Process.SYSTEM_UID && uid != 0) {
953            throw new SecurityException("Only system may call: " + message);
954        }
955    }
956
957    private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
958        try {
959            File dir = new File(mUsersDir, Integer.toString(info.id));
960            File file = new File(dir, USER_PHOTO_FILENAME);
961            File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
962            if (!dir.exists()) {
963                dir.mkdir();
964                FileUtils.setPermissions(
965                        dir.getPath(),
966                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
967                        -1, -1);
968            }
969            FileOutputStream os;
970            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
971                    && tmp.renameTo(file)) {
972                info.iconPath = file.getAbsolutePath();
973            }
974            try {
975                os.close();
976            } catch (IOException ioe) {
977                // What the ... !
978            }
979            tmp.delete();
980        } catch (FileNotFoundException e) {
981            Slog.w(LOG_TAG, "Error setting photo for user ", e);
982        }
983    }
984
985    /**
986     * Returns an array of user ids. This array is cached here for quick access, so do not modify or
987     * cache it elsewhere.
988     * @return the array of user ids.
989     */
990    public int[] getUserIds() {
991        synchronized (mUsersLock) {
992            return mUserIds;
993        }
994    }
995
996    private void readUserListLILP() {
997        if (!mUserListFile.exists()) {
998            fallbackToSingleUserLILP();
999            return;
1000        }
1001        FileInputStream fis = null;
1002        AtomicFile userListFile = new AtomicFile(mUserListFile);
1003        try {
1004            fis = userListFile.openRead();
1005            XmlPullParser parser = Xml.newPullParser();
1006            parser.setInput(fis, StandardCharsets.UTF_8.name());
1007            int type;
1008            while ((type = parser.next()) != XmlPullParser.START_TAG
1009                    && type != XmlPullParser.END_DOCUMENT) {
1010                ;
1011            }
1012
1013            if (type != XmlPullParser.START_TAG) {
1014                Slog.e(LOG_TAG, "Unable to read user list");
1015                fallbackToSingleUserLILP();
1016                return;
1017            }
1018
1019            mNextSerialNumber = -1;
1020            if (parser.getName().equals(TAG_USERS)) {
1021                String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1022                if (lastSerialNumber != null) {
1023                    mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1024                }
1025                String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1026                if (versionNumber != null) {
1027                    mUserVersion = Integer.parseInt(versionNumber);
1028                }
1029            }
1030
1031            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1032                if (type == XmlPullParser.START_TAG) {
1033                    final String name = parser.getName();
1034                    if (name.equals(TAG_USER)) {
1035                        String id = parser.getAttributeValue(null, ATTR_ID);
1036                        UserInfo user = readUserLILP(Integer.parseInt(id));
1037
1038                        if (user != null) {
1039                            synchronized (mUsersLock) {
1040                                mUsers.put(user.id, user);
1041                                if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1042                                    mNextSerialNumber = user.id + 1;
1043                                }
1044                            }
1045                        }
1046                    } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
1047                        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1048                                && type != XmlPullParser.END_TAG) {
1049                            if (type == XmlPullParser.START_TAG) {
1050                                if (parser.getName().equals(TAG_RESTRICTIONS)) {
1051                                    UserRestrictionsUtils
1052                                            .readRestrictions(parser, mGuestRestrictions);
1053                                }
1054                                break;
1055                            }
1056                        }
1057                    }
1058                }
1059            }
1060            updateUserIds();
1061            upgradeIfNecessaryLILP();
1062        } catch (IOException ioe) {
1063            fallbackToSingleUserLILP();
1064        } catch (XmlPullParserException pe) {
1065            fallbackToSingleUserLILP();
1066        } finally {
1067            if (fis != null) {
1068                try {
1069                    fis.close();
1070                } catch (IOException e) {
1071                }
1072            }
1073        }
1074    }
1075
1076    /**
1077     * Upgrade steps between versions, either for fixing bugs or changing the data format.
1078     */
1079    private void upgradeIfNecessaryLILP() {
1080        int userVersion = mUserVersion;
1081        if (userVersion < 1) {
1082            // Assign a proper name for the owner, if not initialized correctly before
1083            UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
1084            if ("Primary".equals(user.name)) {
1085                user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
1086                scheduleWriteUser(user);
1087            }
1088            userVersion = 1;
1089        }
1090
1091        if (userVersion < 2) {
1092            // Owner should be marked as initialized
1093            UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
1094            if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1095                user.flags |= UserInfo.FLAG_INITIALIZED;
1096                scheduleWriteUser(user);
1097            }
1098            userVersion = 2;
1099        }
1100
1101
1102        if (userVersion < 4) {
1103            userVersion = 4;
1104        }
1105
1106        if (userVersion < 5) {
1107            initDefaultGuestRestrictions();
1108            userVersion = 5;
1109        }
1110
1111        if (userVersion < 6) {
1112            final boolean splitSystemUser = UserManager.isSplitSystemUser();
1113            synchronized (mUsersLock) {
1114                for (int i = 0; i < mUsers.size(); i++) {
1115                    UserInfo user = mUsers.valueAt(i);
1116                    // In non-split mode, only user 0 can have restricted profiles
1117                    if (!splitSystemUser && user.isRestricted()
1118                            && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1119                        user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1120                        scheduleWriteUser(user);
1121                    }
1122                }
1123            }
1124            userVersion = 6;
1125        }
1126
1127        if (userVersion < USER_VERSION) {
1128            Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1129                    + USER_VERSION);
1130        } else {
1131            mUserVersion = userVersion;
1132            writeUserListLILP();
1133        }
1134    }
1135
1136    private void fallbackToSingleUserLILP() {
1137        int flags = UserInfo.FLAG_INITIALIZED;
1138        // In split system user mode, the admin and primary flags are assigned to the first human
1139        // user.
1140        if (!UserManager.isSplitSystemUser()) {
1141            flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1142        }
1143        // Create the system user
1144        UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
1145                mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
1146                flags);
1147        synchronized (mUsersLock) {
1148            mUsers.put(system.id, system);
1149        }
1150        mNextSerialNumber = MIN_USER_ID;
1151        mUserVersion = USER_VERSION;
1152
1153        Bundle restrictions = new Bundle();
1154        synchronized (mRestrictionsLock) {
1155            mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1156        }
1157
1158        updateUserIds();
1159        initDefaultGuestRestrictions();
1160
1161        writeUserListLILP();
1162        writeUserLP(system);
1163    }
1164
1165    private void scheduleWriteUser(UserInfo userInfo) {
1166        // No need to wrap it within a lock -- worst case, we'll just post the same message
1167        // twice.
1168        if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1169            Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1170            mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1171        }
1172    }
1173
1174    /*
1175     * Writes the user file in this format:
1176     *
1177     * <user flags="20039023" id="0">
1178     *   <name>Primary</name>
1179     * </user>
1180     */
1181    private void writeUserLP(UserInfo userInfo) {
1182        FileOutputStream fos = null;
1183        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
1184        try {
1185            fos = userFile.startWrite();
1186            final BufferedOutputStream bos = new BufferedOutputStream(fos);
1187
1188            // XmlSerializer serializer = XmlUtils.serializerInstance();
1189            final XmlSerializer serializer = new FastXmlSerializer();
1190            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
1191            serializer.startDocument(null, true);
1192            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1193
1194            serializer.startTag(null, TAG_USER);
1195            serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
1196            serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
1197            serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
1198            serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1199            serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1200                    Long.toString(userInfo.lastLoggedInTime));
1201            if (userInfo.iconPath != null) {
1202                serializer.attribute(null,  ATTR_ICON_PATH, userInfo.iconPath);
1203            }
1204            if (userInfo.partial) {
1205                serializer.attribute(null, ATTR_PARTIAL, "true");
1206            }
1207            if (userInfo.guestToRemove) {
1208                serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1209            }
1210            if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1211                serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1212                        Integer.toString(userInfo.profileGroupId));
1213            }
1214            if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1215                serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1216                        Integer.toString(userInfo.restrictedProfileParentId));
1217            }
1218            serializer.startTag(null, TAG_NAME);
1219            serializer.text(userInfo.name);
1220            serializer.endTag(null, TAG_NAME);
1221            Bundle restrictions;
1222            synchronized (mRestrictionsLock) {
1223                restrictions = mBaseUserRestrictions.get(userInfo.id);
1224            }
1225            if (restrictions != null) {
1226                UserRestrictionsUtils
1227                        .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
1228            }
1229            serializer.endTag(null, TAG_USER);
1230
1231            serializer.endDocument();
1232            userFile.finishWrite(fos);
1233        } catch (Exception ioe) {
1234            Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
1235            userFile.failWrite(fos);
1236        }
1237    }
1238
1239    /*
1240     * Writes the user list file in this format:
1241     *
1242     * <users nextSerialNumber="3">
1243     *   <user id="0"></user>
1244     *   <user id="2"></user>
1245     * </users>
1246     */
1247    private void writeUserListLILP() {
1248        // TODO Investigate removing a dependency on mInstallLock
1249        FileOutputStream fos = null;
1250        AtomicFile userListFile = new AtomicFile(mUserListFile);
1251        try {
1252            fos = userListFile.startWrite();
1253            final BufferedOutputStream bos = new BufferedOutputStream(fos);
1254
1255            // XmlSerializer serializer = XmlUtils.serializerInstance();
1256            final XmlSerializer serializer = new FastXmlSerializer();
1257            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
1258            serializer.startDocument(null, true);
1259            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1260
1261            serializer.startTag(null, TAG_USERS);
1262            serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
1263            serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
1264
1265            serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
1266            UserRestrictionsUtils
1267                    .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1268            serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
1269            int[] userIdsToWrite;
1270            synchronized (mUsersLock) {
1271                userIdsToWrite = new int[mUsers.size()];
1272                for (int i = 0; i < userIdsToWrite.length; i++) {
1273                    UserInfo user = mUsers.valueAt(i);
1274                    userIdsToWrite[i] = user.id;
1275                }
1276            }
1277            for (int id : userIdsToWrite) {
1278                serializer.startTag(null, TAG_USER);
1279                serializer.attribute(null, ATTR_ID, Integer.toString(id));
1280                serializer.endTag(null, TAG_USER);
1281            }
1282
1283            serializer.endTag(null, TAG_USERS);
1284
1285            serializer.endDocument();
1286            userListFile.finishWrite(fos);
1287        } catch (Exception e) {
1288            userListFile.failWrite(fos);
1289            Slog.e(LOG_TAG, "Error writing user list");
1290        }
1291    }
1292
1293    private UserInfo readUserLILP(int id) {
1294        int flags = 0;
1295        int serialNumber = id;
1296        String name = null;
1297        String iconPath = null;
1298        long creationTime = 0L;
1299        long lastLoggedInTime = 0L;
1300        int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
1301        int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
1302        boolean partial = false;
1303        boolean guestToRemove = false;
1304        Bundle restrictions = new Bundle();
1305
1306        FileInputStream fis = null;
1307        try {
1308            AtomicFile userFile =
1309                    new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
1310            fis = userFile.openRead();
1311            XmlPullParser parser = Xml.newPullParser();
1312            parser.setInput(fis, StandardCharsets.UTF_8.name());
1313            int type;
1314            while ((type = parser.next()) != XmlPullParser.START_TAG
1315                    && type != XmlPullParser.END_DOCUMENT) {
1316                ;
1317            }
1318
1319            if (type != XmlPullParser.START_TAG) {
1320                Slog.e(LOG_TAG, "Unable to read user " + id);
1321                return null;
1322            }
1323
1324            if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
1325                int storedId = readIntAttribute(parser, ATTR_ID, -1);
1326                if (storedId != id) {
1327                    Slog.e(LOG_TAG, "User id does not match the file name");
1328                    return null;
1329                }
1330                serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1331                flags = readIntAttribute(parser, ATTR_FLAGS, 0);
1332                iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
1333                creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1334                lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
1335                profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1336                        UserInfo.NO_PROFILE_GROUP_ID);
1337                restrictedProfileParentId = readIntAttribute(parser,
1338                        ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
1339                String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1340                if ("true".equals(valueString)) {
1341                    partial = true;
1342                }
1343                valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1344                if ("true".equals(valueString)) {
1345                    guestToRemove = true;
1346                }
1347
1348                int outerDepth = parser.getDepth();
1349                while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1350                       && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1351                    if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1352                        continue;
1353                    }
1354                    String tag = parser.getName();
1355                    if (TAG_NAME.equals(tag)) {
1356                        type = parser.next();
1357                        if (type == XmlPullParser.TEXT) {
1358                            name = parser.getText();
1359                        }
1360                    } else if (TAG_RESTRICTIONS.equals(tag)) {
1361                        UserRestrictionsUtils.readRestrictions(parser, restrictions);
1362                    }
1363                }
1364            }
1365
1366            UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
1367            userInfo.serialNumber = serialNumber;
1368            userInfo.creationTime = creationTime;
1369            userInfo.lastLoggedInTime = lastLoggedInTime;
1370            userInfo.partial = partial;
1371            userInfo.guestToRemove = guestToRemove;
1372            userInfo.profileGroupId = profileGroupId;
1373            userInfo.restrictedProfileParentId = restrictedProfileParentId;
1374            synchronized (mRestrictionsLock) {
1375                mBaseUserRestrictions.append(id, restrictions);
1376            }
1377            return userInfo;
1378
1379        } catch (IOException ioe) {
1380        } catch (XmlPullParserException pe) {
1381        } finally {
1382            if (fis != null) {
1383                try {
1384                    fis.close();
1385                } catch (IOException e) {
1386                }
1387            }
1388        }
1389        return null;
1390    }
1391
1392    private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1393        String valueString = parser.getAttributeValue(null, attr);
1394        if (valueString == null) return defaultValue;
1395        try {
1396            return Integer.parseInt(valueString);
1397        } catch (NumberFormatException nfe) {
1398            return defaultValue;
1399        }
1400    }
1401
1402    private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1403        String valueString = parser.getAttributeValue(null, attr);
1404        if (valueString == null) return defaultValue;
1405        try {
1406            return Long.parseLong(valueString);
1407        } catch (NumberFormatException nfe) {
1408            return defaultValue;
1409        }
1410    }
1411
1412    private boolean isPackageInstalled(String pkg, int userId) {
1413        final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1414                PackageManager.GET_UNINSTALLED_PACKAGES,
1415                userId);
1416        if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1417            return false;
1418        }
1419        return true;
1420    }
1421
1422    /**
1423     * Removes all the restrictions files (res_<packagename>) for a given user.
1424     * Does not do any permissions checking.
1425     */
1426    private void cleanAppRestrictions(int userId) {
1427        synchronized (mPackagesLock) {
1428            File dir = Environment.getUserSystemDirectory(userId);
1429            String[] files = dir.list();
1430            if (files == null) return;
1431            for (String fileName : files) {
1432                if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1433                    File resFile = new File(dir, fileName);
1434                    if (resFile.exists()) {
1435                        resFile.delete();
1436                    }
1437                }
1438            }
1439        }
1440    }
1441
1442    /**
1443     * Removes the app restrictions file for a specific package and user id, if it exists.
1444     */
1445    private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1446        synchronized (mPackagesLock) {
1447            File dir = Environment.getUserSystemDirectory(userId);
1448            File resFile = new File(dir, packageToRestrictionsFileName(pkg));
1449            if (resFile.exists()) {
1450                resFile.delete();
1451            }
1452        }
1453    }
1454
1455    @Override
1456    public UserInfo createProfileForUser(String name, int flags, int userId) {
1457        checkManageUsersPermission("Only the system can create users");
1458        return createUserInternal(name, flags, userId);
1459    }
1460
1461    @Override
1462    public UserInfo createUser(String name, int flags) {
1463        checkManageUsersPermission("Only the system can create users");
1464        return createUserInternal(name, flags, UserHandle.USER_NULL);
1465    }
1466
1467    private UserInfo createUserInternal(String name, int flags, int parentId) {
1468        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1469                UserManager.DISALLOW_ADD_USER, false)) {
1470            Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1471            return null;
1472        }
1473        if (ActivityManager.isLowRamDeviceStatic()) {
1474            return null;
1475        }
1476        final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
1477        final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
1478        final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
1479        final long ident = Binder.clearCallingIdentity();
1480        UserInfo userInfo = null;
1481        final int userId;
1482        try {
1483            synchronized (mInstallLock) {
1484                synchronized (mPackagesLock) {
1485                    UserInfo parent = null;
1486                    if (parentId != UserHandle.USER_NULL) {
1487                        synchronized (mUsersLock) {
1488                            parent = getUserInfoLU(parentId);
1489                        }
1490                        if (parent == null) return null;
1491                    }
1492                    if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1493                        Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1494                        return null;
1495                    }
1496                    if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1497                        // If we're not adding a guest user or a managed profile and the limit has
1498                        // been reached, cannot add a user.
1499                        return null;
1500                    }
1501                    // If we're adding a guest and there already exists one, bail.
1502                    if (isGuest && findCurrentGuestUser() != null) {
1503                        return null;
1504                    }
1505                    // In legacy mode, restricted profile's parent can only be the owner user
1506                    if (isRestricted && !UserManager.isSplitSystemUser()
1507                            && (parentId != UserHandle.USER_SYSTEM)) {
1508                        Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1509                        return null;
1510                    }
1511                    if (isRestricted && UserManager.isSplitSystemUser()) {
1512                        if (parent == null) {
1513                            Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1514                                    + "specified");
1515                            return null;
1516                        }
1517                        if (!parent.canHaveProfile()) {
1518                            Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1519                                    + "created for the specified parent user id " + parentId);
1520                            return null;
1521                        }
1522                    }
1523                    // In split system user mode, we assign the first human user the primary flag.
1524                    // And if there is no device owner, we also assign the admin flag to primary
1525                    // user.
1526                    if (UserManager.isSplitSystemUser()
1527                            && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1528                        flags |= UserInfo.FLAG_PRIMARY;
1529                        DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1530                                mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1531                        if (devicePolicyManager == null
1532                                || devicePolicyManager.getDeviceOwner() == null) {
1533                            flags |= UserInfo.FLAG_ADMIN;
1534                        }
1535                    }
1536                    userId = getNextAvailableId();
1537                    userInfo = new UserInfo(userId, name, null, flags);
1538                    userInfo.serialNumber = mNextSerialNumber++;
1539                    long now = System.currentTimeMillis();
1540                    userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1541                    userInfo.partial = true;
1542                    Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1543                    mUsers.put(userId, userInfo);
1544                    writeUserListLILP();
1545                    if (parent != null) {
1546                        if (isManagedProfile) {
1547                            if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1548                                parent.profileGroupId = parent.id;
1549                                scheduleWriteUser(parent);
1550                            }
1551                            userInfo.profileGroupId = parent.profileGroupId;
1552                        } else if (isRestricted) {
1553                            if (!parent.canHaveProfile()) {
1554                                Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1555                            }
1556                            if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1557                                parent.restrictedProfileParentId = parent.id;
1558                                scheduleWriteUser(parent);
1559                            }
1560                            userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
1561                        }
1562                    }
1563                    final StorageManager storage = mContext.getSystemService(StorageManager.class);
1564                    for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1565                        final String volumeUuid = vol.getFsUuid();
1566                        try {
1567                            final File userDir = Environment.getDataUserDirectory(volumeUuid,
1568                                    userId);
1569                            prepareUserDirectory(mContext, volumeUuid, userId);
1570                            enforceSerialNumber(userDir, userInfo.serialNumber);
1571                        } catch (IOException e) {
1572                            Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1573                        }
1574                    }
1575                    mPm.createNewUserLILPw(userId);
1576                    userInfo.partial = false;
1577                    scheduleWriteUser(userInfo);
1578                    updateUserIds();
1579                    Bundle restrictions = new Bundle();
1580                    synchronized (mRestrictionsLock) {
1581                        mBaseUserRestrictions.append(userId, restrictions);
1582                    }
1583                }
1584            }
1585            mPm.newUserCreated(userId);
1586            if (userInfo != null) {
1587                Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1588                addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1589                mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1590                        android.Manifest.permission.MANAGE_USERS);
1591            }
1592        } finally {
1593            Binder.restoreCallingIdentity(ident);
1594        }
1595        return userInfo;
1596    }
1597
1598    /**
1599     * @hide
1600     */
1601    public UserInfo createRestrictedProfile(String name, int parentUserId) {
1602        checkManageUsersPermission("setupRestrictedProfile");
1603        final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1604        if (user == null) {
1605            return null;
1606        }
1607        setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1608        // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1609        // the putIntForUser() will fail.
1610        android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1611                android.provider.Settings.Secure.LOCATION_MODE,
1612                android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1613        setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1614        return user;
1615    }
1616
1617    /**
1618     * Find the current guest user. If the Guest user is partial,
1619     * then do not include it in the results as it is about to die.
1620     */
1621    private UserInfo findCurrentGuestUser() {
1622        synchronized (mUsersLock) {
1623            final int size = mUsers.size();
1624            for (int i = 0; i < size; i++) {
1625                final UserInfo user = mUsers.valueAt(i);
1626                if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1627                    return user;
1628                }
1629            }
1630        }
1631        return null;
1632    }
1633
1634    /**
1635     * Mark this guest user for deletion to allow us to create another guest
1636     * and switch to that user before actually removing this guest.
1637     * @param userHandle the userid of the current guest
1638     * @return whether the user could be marked for deletion
1639     */
1640    public boolean markGuestForDeletion(int userHandle) {
1641        checkManageUsersPermission("Only the system can remove users");
1642        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1643                UserManager.DISALLOW_REMOVE_USER, false)) {
1644            Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1645            return false;
1646        }
1647
1648        long ident = Binder.clearCallingIdentity();
1649        try {
1650            final UserInfo user;
1651            synchronized (mPackagesLock) {
1652                synchronized (mUsersLock) {
1653                    user = mUsers.get(userHandle);
1654                    if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1655                        return false;
1656                    }
1657                }
1658                if (!user.isGuest()) {
1659                    return false;
1660                }
1661                // We set this to a guest user that is to be removed. This is a temporary state
1662                // where we are allowed to add new Guest users, even if this one is still not
1663                // removed. This user will still show up in getUserInfo() calls.
1664                // If we don't get around to removing this Guest user, it will be purged on next
1665                // startup.
1666                user.guestToRemove = true;
1667                // Mark it as disabled, so that it isn't returned any more when
1668                // profiles are queried.
1669                user.flags |= UserInfo.FLAG_DISABLED;
1670                writeUserLP(user);
1671            }
1672        } finally {
1673            Binder.restoreCallingIdentity(ident);
1674        }
1675        return true;
1676    }
1677
1678    /**
1679     * Removes a user and all data directories created for that user. This method should be called
1680     * after the user's processes have been terminated.
1681     * @param userHandle the user's id
1682     */
1683    public boolean removeUser(int userHandle) {
1684        checkManageUsersPermission("Only the system can remove users");
1685        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1686                UserManager.DISALLOW_REMOVE_USER, false)) {
1687            Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1688            return false;
1689        }
1690
1691        long ident = Binder.clearCallingIdentity();
1692        try {
1693            final UserInfo user;
1694            int currentUser = ActivityManager.getCurrentUser();
1695            if (currentUser == userHandle) {
1696                Log.w(LOG_TAG, "Current user cannot be removed");
1697                return false;
1698            }
1699            synchronized (mPackagesLock) {
1700                synchronized (mUsersLock) {
1701                    user = mUsers.get(userHandle);
1702                    if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1703                        return false;
1704                    }
1705
1706                    // We remember deleted user IDs to prevent them from being
1707                    // reused during the current boot; they can still be reused
1708                    // after a reboot.
1709                    mRemovingUserIds.put(userHandle, true);
1710                }
1711
1712                try {
1713                    mAppOpsService.removeUser(userHandle);
1714                } catch (RemoteException e) {
1715                    Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1716                }
1717                // Set this to a partially created user, so that the user will be purged
1718                // on next startup, in case the runtime stops now before stopping and
1719                // removing the user completely.
1720                user.partial = true;
1721                // Mark it as disabled, so that it isn't returned any more when
1722                // profiles are queried.
1723                user.flags |= UserInfo.FLAG_DISABLED;
1724                writeUserLP(user);
1725            }
1726
1727            if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1728                    && user.isManagedProfile()) {
1729                // Send broadcast to notify system that the user removed was a
1730                // managed user.
1731                sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1732            }
1733
1734            if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1735            int res;
1736            try {
1737                res = ActivityManagerNative.getDefault().stopUser(userHandle,
1738                        new IStopUserCallback.Stub() {
1739                            @Override
1740                            public void userStopped(int userId) {
1741                                finishRemoveUser(userId);
1742                            }
1743                            @Override
1744                            public void userStopAborted(int userId) {
1745                            }
1746                        });
1747            } catch (RemoteException e) {
1748                return false;
1749            }
1750            return res == ActivityManager.USER_OP_SUCCESS;
1751        } finally {
1752            Binder.restoreCallingIdentity(ident);
1753        }
1754    }
1755
1756    void finishRemoveUser(final int userHandle) {
1757        if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
1758        // Let other services shutdown any activity and clean up their state before completely
1759        // wiping the user's system directory and removing from the user list
1760        long ident = Binder.clearCallingIdentity();
1761        try {
1762            Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1763            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
1764            mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1765                    android.Manifest.permission.MANAGE_USERS,
1766
1767                    new BroadcastReceiver() {
1768                        @Override
1769                        public void onReceive(Context context, Intent intent) {
1770                            if (DBG) {
1771                                Slog.i(LOG_TAG,
1772                                        "USER_REMOVED broadcast sent, cleaning up user data "
1773                                        + userHandle);
1774                            }
1775                            new Thread() {
1776                                public void run() {
1777                                    // Clean up any ActivityManager state
1778                                    LocalServices.getService(ActivityManagerInternal.class)
1779                                            .onUserRemoved(userHandle);
1780                                    synchronized (mInstallLock) {
1781                                        synchronized (mPackagesLock) {
1782                                            removeUserStateLILP(userHandle);
1783                                        }
1784                                    }
1785                                }
1786                            }.start();
1787                        }
1788                    },
1789
1790                    null, Activity.RESULT_OK, null, null);
1791        } finally {
1792            Binder.restoreCallingIdentity(ident);
1793        }
1794    }
1795
1796    private void removeUserStateLILP(final int userHandle) {
1797        mContext.getSystemService(StorageManager.class)
1798            .deleteUserKey(userHandle);
1799        // Cleanup package manager settings
1800        mPm.cleanUpUserLILPw(this, userHandle);
1801
1802        // Remove this user from the list
1803        synchronized (mUsersLock) {
1804            mUsers.remove(userHandle);
1805        }
1806        // Remove user file
1807        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
1808        userFile.delete();
1809        // Update the user list
1810        writeUserListLILP();
1811        updateUserIds();
1812        removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1813    }
1814
1815    private void removeDirectoryRecursive(File parent) {
1816        if (parent.isDirectory()) {
1817            String[] files = parent.list();
1818            for (String filename : files) {
1819                File child = new File(parent, filename);
1820                removeDirectoryRecursive(child);
1821            }
1822        }
1823        parent.delete();
1824    }
1825
1826    private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
1827        Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
1828        managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1829                Intent.FLAG_RECEIVER_FOREGROUND);
1830        managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1831        mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
1832    }
1833
1834    @Override
1835    public Bundle getApplicationRestrictions(String packageName) {
1836        return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1837    }
1838
1839    @Override
1840    public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
1841        if (UserHandle.getCallingUserId() != userId
1842                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
1843            checkManageUsersPermission("get application restrictions for other users/apps");
1844        }
1845        synchronized (mPackagesLock) {
1846            // Read the restrictions from XML
1847            return readApplicationRestrictionsLP(packageName, userId);
1848        }
1849    }
1850
1851    @Override
1852    public void setApplicationRestrictions(String packageName, Bundle restrictions,
1853            int userId) {
1854        checkManageUsersPermission("set application restrictions");
1855        synchronized (mPackagesLock) {
1856            if (restrictions == null || restrictions.isEmpty()) {
1857                cleanAppRestrictionsForPackage(packageName, userId);
1858            } else {
1859                // Write the restrictions to XML
1860                writeApplicationRestrictionsLP(packageName, restrictions, userId);
1861            }
1862        }
1863
1864        if (isPackageInstalled(packageName, userId)) {
1865            // Notify package of changes via an intent - only sent to explicitly registered receivers.
1866            Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1867            changeIntent.setPackage(packageName);
1868            changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1869            mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1870        }
1871    }
1872
1873    private void unhideAllInstalledAppsForUser(final int userHandle) {
1874        mHandler.post(new Runnable() {
1875            @Override
1876            public void run() {
1877                List<ApplicationInfo> apps =
1878                        mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1879                                userHandle).getList();
1880                final long ident = Binder.clearCallingIdentity();
1881                try {
1882                    for (ApplicationInfo appInfo : apps) {
1883                        if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1884                                && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1885                                        != 0) {
1886                            mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
1887                                    userHandle);
1888                        }
1889                    }
1890                } finally {
1891                    Binder.restoreCallingIdentity(ident);
1892                }
1893            }
1894        });
1895    }
1896    private int getUidForPackage(String packageName) {
1897        long ident = Binder.clearCallingIdentity();
1898        try {
1899            return mContext.getPackageManager().getApplicationInfo(packageName,
1900                    PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1901        } catch (NameNotFoundException nnfe) {
1902            return -1;
1903        } finally {
1904            Binder.restoreCallingIdentity(ident);
1905        }
1906    }
1907
1908    private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
1909        AtomicFile restrictionsFile =
1910                new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1911                        packageToRestrictionsFileName(packageName)));
1912        return readApplicationRestrictionsLP(restrictionsFile);
1913    }
1914
1915    @VisibleForTesting
1916    static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
1917        final Bundle restrictions = new Bundle();
1918        final ArrayList<String> values = new ArrayList<>();
1919        if (!restrictionsFile.getBaseFile().exists()) {
1920            return restrictions;
1921        }
1922
1923        FileInputStream fis = null;
1924        try {
1925            fis = restrictionsFile.openRead();
1926            XmlPullParser parser = Xml.newPullParser();
1927            parser.setInput(fis, StandardCharsets.UTF_8.name());
1928            XmlUtils.nextElement(parser);
1929            if (parser.getEventType() != XmlPullParser.START_TAG) {
1930                Slog.e(LOG_TAG, "Unable to read restrictions file "
1931                        + restrictionsFile.getBaseFile());
1932                return restrictions;
1933            }
1934            while (parser.next() != XmlPullParser.END_DOCUMENT) {
1935                readEntry(restrictions, values, parser);
1936            }
1937        } catch (IOException|XmlPullParserException e) {
1938            Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
1939        } finally {
1940            IoUtils.closeQuietly(fis);
1941        }
1942        return restrictions;
1943    }
1944
1945    private static void readEntry(Bundle restrictions, ArrayList<String> values,
1946            XmlPullParser parser) throws XmlPullParserException, IOException {
1947        int type = parser.getEventType();
1948        if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1949            String key = parser.getAttributeValue(null, ATTR_KEY);
1950            String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1951            String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1952            if (multiple != null) {
1953                values.clear();
1954                int count = Integer.parseInt(multiple);
1955                while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1956                    if (type == XmlPullParser.START_TAG
1957                            && parser.getName().equals(TAG_VALUE)) {
1958                        values.add(parser.nextText().trim());
1959                        count--;
1960                    }
1961                }
1962                String [] valueStrings = new String[values.size()];
1963                values.toArray(valueStrings);
1964                restrictions.putStringArray(key, valueStrings);
1965            } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1966                restrictions.putBundle(key, readBundleEntry(parser, values));
1967            } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1968                final int outerDepth = parser.getDepth();
1969                ArrayList<Bundle> bundleList = new ArrayList<>();
1970                while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1971                    Bundle childBundle = readBundleEntry(parser, values);
1972                    bundleList.add(childBundle);
1973                }
1974                restrictions.putParcelableArray(key,
1975                        bundleList.toArray(new Bundle[bundleList.size()]));
1976            } else {
1977                String value = parser.nextText().trim();
1978                if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1979                    restrictions.putBoolean(key, Boolean.parseBoolean(value));
1980                } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1981                    restrictions.putInt(key, Integer.parseInt(value));
1982                } else {
1983                    restrictions.putString(key, value);
1984                }
1985            }
1986        }
1987    }
1988
1989    private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1990            throws IOException, XmlPullParserException {
1991        Bundle childBundle = new Bundle();
1992        final int outerDepth = parser.getDepth();
1993        while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1994            readEntry(childBundle, values, parser);
1995        }
1996        return childBundle;
1997    }
1998
1999    private void writeApplicationRestrictionsLP(String packageName,
2000            Bundle restrictions, int userId) {
2001        AtomicFile restrictionsFile = new AtomicFile(
2002                new File(Environment.getUserSystemDirectory(userId),
2003                        packageToRestrictionsFileName(packageName)));
2004        writeApplicationRestrictionsLP(restrictions, restrictionsFile);
2005    }
2006
2007    @VisibleForTesting
2008    static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
2009        FileOutputStream fos = null;
2010        try {
2011            fos = restrictionsFile.startWrite();
2012            final BufferedOutputStream bos = new BufferedOutputStream(fos);
2013
2014            final XmlSerializer serializer = new FastXmlSerializer();
2015            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
2016            serializer.startDocument(null, true);
2017            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2018
2019            serializer.startTag(null, TAG_RESTRICTIONS);
2020            writeBundle(restrictions, serializer);
2021            serializer.endTag(null, TAG_RESTRICTIONS);
2022
2023            serializer.endDocument();
2024            restrictionsFile.finishWrite(fos);
2025        } catch (Exception e) {
2026            restrictionsFile.failWrite(fos);
2027            Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2028        }
2029    }
2030
2031    private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2032            throws IOException {
2033        for (String key : restrictions.keySet()) {
2034            Object value = restrictions.get(key);
2035            serializer.startTag(null, TAG_ENTRY);
2036            serializer.attribute(null, ATTR_KEY, key);
2037
2038            if (value instanceof Boolean) {
2039                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2040                serializer.text(value.toString());
2041            } else if (value instanceof Integer) {
2042                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2043                serializer.text(value.toString());
2044            } else if (value == null || value instanceof String) {
2045                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2046                serializer.text(value != null ? (String) value : "");
2047            } else if (value instanceof Bundle) {
2048                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2049                writeBundle((Bundle) value, serializer);
2050            } else if (value instanceof Parcelable[]) {
2051                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2052                Parcelable[] array = (Parcelable[]) value;
2053                for (Parcelable parcelable : array) {
2054                    if (!(parcelable instanceof Bundle)) {
2055                        throw new IllegalArgumentException("bundle-array can only hold Bundles");
2056                    }
2057                    serializer.startTag(null, TAG_ENTRY);
2058                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2059                    writeBundle((Bundle) parcelable, serializer);
2060                    serializer.endTag(null, TAG_ENTRY);
2061                }
2062            } else {
2063                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2064                String[] values = (String[]) value;
2065                serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2066                for (String choice : values) {
2067                    serializer.startTag(null, TAG_VALUE);
2068                    serializer.text(choice != null ? choice : "");
2069                    serializer.endTag(null, TAG_VALUE);
2070                }
2071            }
2072            serializer.endTag(null, TAG_ENTRY);
2073        }
2074    }
2075
2076    @Override
2077    public int getUserSerialNumber(int userHandle) {
2078        synchronized (mUsersLock) {
2079            if (!exists(userHandle)) return -1;
2080            return getUserInfoLU(userHandle).serialNumber;
2081        }
2082    }
2083
2084    @Override
2085    public int getUserHandle(int userSerialNumber) {
2086        synchronized (mUsersLock) {
2087            for (int userId : mUserIds) {
2088                UserInfo info = getUserInfoLU(userId);
2089                if (info != null && info.serialNumber == userSerialNumber) return userId;
2090            }
2091            // Not found
2092            return -1;
2093        }
2094    }
2095
2096    @Override
2097    public long getUserCreationTime(int userHandle) {
2098        int callingUserId = UserHandle.getCallingUserId();
2099        UserInfo userInfo = null;
2100        synchronized (mUsersLock) {
2101            if (callingUserId == userHandle) {
2102                userInfo = getUserInfoLU(userHandle);
2103            } else {
2104                UserInfo parent = getProfileParentLU(userHandle);
2105                if (parent != null && parent.id == callingUserId) {
2106                    userInfo = getUserInfoLU(userHandle);
2107                }
2108            }
2109        }
2110        if (userInfo == null) {
2111            throw new SecurityException("userHandle can only be the calling user or a managed "
2112                    + "profile associated with this user");
2113        }
2114        return userInfo.creationTime;
2115    }
2116
2117    /**
2118     * Caches the list of user ids in an array, adjusting the array size when necessary.
2119     */
2120    private void updateUserIds() {
2121        int num = 0;
2122        synchronized (mUsersLock) {
2123            final int userSize = mUsers.size();
2124            for (int i = 0; i < userSize; i++) {
2125                if (!mUsers.valueAt(i).partial) {
2126                    num++;
2127                }
2128            }
2129            final int[] newUsers = new int[num];
2130            int n = 0;
2131            for (int i = 0; i < userSize; i++) {
2132                if (!mUsers.valueAt(i).partial) {
2133                    newUsers[n++] = mUsers.keyAt(i);
2134                }
2135            }
2136            mUserIds = newUsers;
2137        }
2138    }
2139
2140    /**
2141     * Make a note of the last started time of a user and do some cleanup.
2142     * @param userId the user that was just foregrounded
2143     */
2144    public void onUserForeground(int userId) {
2145        synchronized (mPackagesLock) {
2146            UserInfo user = getUserInfoNoChecks(userId);
2147            long now = System.currentTimeMillis();
2148            if (user == null || user.partial) {
2149                Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2150                return;
2151            }
2152            if (now > EPOCH_PLUS_30_YEARS) {
2153                user.lastLoggedInTime = now;
2154                scheduleWriteUser(user);
2155            }
2156        }
2157    }
2158
2159    /**
2160     * Returns the next available user id, filling in any holes in the ids.
2161     * TODO: May not be a good idea to recycle ids, in case it results in confusion
2162     * for data and battery stats collection, or unexpected cross-talk.
2163     * @return
2164     */
2165    private int getNextAvailableId() {
2166        synchronized (mUsersLock) {
2167            int i = MIN_USER_ID;
2168            while (i < MAX_USER_ID) {
2169                if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
2170                    return i;
2171                }
2172                i++;
2173            }
2174        }
2175        throw new IllegalStateException("No user id available!");
2176    }
2177
2178    private String packageToRestrictionsFileName(String packageName) {
2179        return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2180    }
2181
2182    /**
2183     * Create new {@code /data/user/[id]} directory and sets default
2184     * permissions.
2185     */
2186    public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2187        final StorageManager storage = context.getSystemService(StorageManager.class);
2188        final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2189        storage.createNewUserDir(userId, userDir);
2190    }
2191
2192    /**
2193     * Enforce that serial number stored in user directory inode matches the
2194     * given expected value. Gracefully sets the serial number if currently
2195     * undefined.
2196     *
2197     * @throws IOException when problem extracting serial number, or serial
2198     *             number is mismatched.
2199     */
2200    public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2201        final int foundSerial = getSerialNumber(file);
2202        Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2203
2204        if (foundSerial == -1) {
2205            Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2206            try {
2207                setSerialNumber(file, serialNumber);
2208            } catch (IOException e) {
2209                Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2210            }
2211
2212        } else if (foundSerial != serialNumber) {
2213            throw new IOException("Found serial number " + foundSerial
2214                    + " doesn't match expected " + serialNumber);
2215        }
2216    }
2217
2218    /**
2219     * Set serial number stored in user directory inode.
2220     *
2221     * @throws IOException if serial number was already set
2222     */
2223    private static void setSerialNumber(File file, int serialNumber)
2224            throws IOException {
2225        try {
2226            final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2227            Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2228        } catch (ErrnoException e) {
2229            throw e.rethrowAsIOException();
2230        }
2231    }
2232
2233    /**
2234     * Return serial number stored in user directory inode.
2235     *
2236     * @return parsed serial number, or -1 if not set
2237     */
2238    private static int getSerialNumber(File file) throws IOException {
2239        try {
2240            final byte[] buf = new byte[256];
2241            final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2242            final String serial = new String(buf, 0, len);
2243            try {
2244                return Integer.parseInt(serial);
2245            } catch (NumberFormatException e) {
2246                throw new IOException("Bad serial number: " + serial);
2247            }
2248        } catch (ErrnoException e) {
2249            if (e.errno == OsConstants.ENODATA) {
2250                return -1;
2251            } else {
2252                throw e.rethrowAsIOException();
2253            }
2254        }
2255    }
2256
2257    @Override
2258    public void onShellCommand(FileDescriptor in, FileDescriptor out,
2259            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2260        (new Shell()).exec(this, in, out, err, args, resultReceiver);
2261    }
2262
2263    int onShellCommand(Shell shell, String cmd) {
2264        if (cmd == null) {
2265            return shell.handleDefaultCommands(cmd);
2266        }
2267
2268        final PrintWriter pw = shell.getOutPrintWriter();
2269        try {
2270            switch(cmd) {
2271                case "list":
2272                    return runList(pw);
2273            }
2274        } catch (RemoteException e) {
2275            pw.println("Remote exception: " + e);
2276        }
2277        return -1;
2278    }
2279
2280    private int runList(PrintWriter pw) throws RemoteException {
2281        final IActivityManager am = ActivityManagerNative.getDefault();
2282        final List<UserInfo> users = getUsers(false);
2283        if (users == null) {
2284            pw.println("Error: couldn't get users");
2285            return 1;
2286        } else {
2287            pw.println("Users:");
2288            for (int i = 0; i < users.size(); i++) {
2289                String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
2290                pw.println("\t" + users.get(i).toString() + running);
2291            }
2292            return 0;
2293        }
2294    }
2295
2296    @Override
2297    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2298        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2299                != PackageManager.PERMISSION_GRANTED) {
2300            pw.println("Permission Denial: can't dump UserManager from from pid="
2301                    + Binder.getCallingPid()
2302                    + ", uid=" + Binder.getCallingUid()
2303                    + " without permission "
2304                    + android.Manifest.permission.DUMP);
2305            return;
2306        }
2307
2308        long now = System.currentTimeMillis();
2309        StringBuilder sb = new StringBuilder();
2310        synchronized (mPackagesLock) {
2311            synchronized (mUsersLock) {
2312                pw.println("Users:");
2313                for (int i = 0; i < mUsers.size(); i++) {
2314                    UserInfo user = mUsers.valueAt(i);
2315                    if (user == null) {
2316                        continue;
2317                    }
2318                    pw.print("  "); pw.print(user);
2319                    pw.print(" serialNo="); pw.print(user.serialNumber);
2320                    if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2321                        pw.print(" <removing> ");
2322                    }
2323                    if (user.partial) {
2324                        pw.print(" <partial>");
2325                    }
2326                    pw.println();
2327                    pw.print("    Created: ");
2328                    if (user.creationTime == 0) {
2329                        pw.println("<unknown>");
2330                    } else {
2331                        sb.setLength(0);
2332                        TimeUtils.formatDuration(now - user.creationTime, sb);
2333                        sb.append(" ago");
2334                        pw.println(sb);
2335                    }
2336                    pw.print("    Last logged in: ");
2337                    if (user.lastLoggedInTime == 0) {
2338                        pw.println("<unknown>");
2339                    } else {
2340                        sb.setLength(0);
2341                        TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2342                        sb.append(" ago");
2343                        pw.println(sb);
2344                    }
2345                    pw.println("    Restrictions:");
2346                    synchronized (mRestrictionsLock) {
2347                        UserRestrictionsUtils.dumpRestrictions(
2348                                pw, "      ", mBaseUserRestrictions.get(user.id));
2349                        pw.println("    Effective restrictions:");
2350                        UserRestrictionsUtils.dumpRestrictions(
2351                                pw, "      ", mCachedEffectiveUserRestrictions.get(user.id));
2352                    }
2353                }
2354            }
2355            pw.println();
2356            pw.println("Guest restrictions:");
2357            UserRestrictionsUtils.dumpRestrictions(pw, "  ", mGuestRestrictions);
2358        }
2359    }
2360
2361    final class MainHandler extends Handler {
2362
2363        @Override
2364        public void handleMessage(Message msg) {
2365            switch (msg.what) {
2366                case WRITE_USER_MSG:
2367                    removeMessages(WRITE_USER_MSG, msg.obj);
2368                    synchronized (mPackagesLock) {
2369                        int userId = ((UserInfo) msg.obj).id;
2370                        UserInfo userInfo = getUserInfoNoChecks(userId);
2371                        if (userInfo != null) {
2372                            writeUserLP(userInfo);
2373                        }
2374                    }
2375            }
2376        }
2377    }
2378
2379    /**
2380     * @param userId
2381     * @return whether the user has been initialized yet
2382     */
2383    boolean isInitialized(int userId) {
2384        return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2385    }
2386
2387    private class LocalService extends UserManagerInternal {
2388
2389        @Override
2390        public Object getUserRestrictionsLock() {
2391            return mRestrictionsLock;
2392        }
2393
2394        @Override
2395        @GuardedBy("mRestrictionsLock")
2396        public void updateEffectiveUserRestrictionsLR(int userId) {
2397            UserManagerService.this.updateEffectiveUserRestrictionsLR(userId);
2398        }
2399
2400        @Override
2401        @GuardedBy("mRestrictionsLock")
2402        public void updateEffectiveUserRestrictionsForAllUsersLR() {
2403            UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersLR();
2404        }
2405
2406        @Override
2407        public Bundle getBaseUserRestrictions(int userId) {
2408            synchronized (mRestrictionsLock) {
2409                return mBaseUserRestrictions.get(userId);
2410            }
2411        }
2412
2413        @Override
2414        public void setBaseUserRestrictionsByDpmsForMigration(
2415                int userId, Bundle baseRestrictions) {
2416            synchronized (mRestrictionsLock) {
2417                mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
2418                invalidateEffectiveUserRestrictionsLR(userId);
2419            }
2420
2421            final UserInfo userInfo = getUserInfoNoChecks(userId);
2422            synchronized (mPackagesLock) {
2423                if (userInfo != null) {
2424                    writeUserLP(userInfo);
2425                } else {
2426                    Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2427                }
2428            }
2429        }
2430
2431        @Override
2432        public boolean getUserRestriction(int userId, String key) {
2433            return getUserRestrictions(userId).getBoolean(key);
2434        }
2435
2436        @Override
2437        public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2438            synchronized (mUserRestrictionsListeners) {
2439                mUserRestrictionsListeners.add(listener);
2440            }
2441        }
2442
2443        @Override
2444        public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2445            synchronized (mUserRestrictionsListeners) {
2446                mUserRestrictionsListeners.remove(listener);
2447            }
2448        }
2449    }
2450
2451    private class Shell extends ShellCommand {
2452        @Override
2453        public int onCommand(String cmd) {
2454            return onShellCommand(this, cmd);
2455        }
2456
2457        @Override
2458        public void onHelp() {
2459            final PrintWriter pw = getOutPrintWriter();
2460            pw.println("User manager (user) commands:");
2461            pw.println("  help");
2462            pw.println("    Print this help text.");
2463            pw.println("");
2464            pw.println("  list");
2465            pw.println("    Prints all users on the system.");
2466        }
2467    }
2468}
2469