UserManagerService.java revision f9fc6d6cc05595241bc7ced6d4cab97b45f9b901
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, boolean allowedToRemoveOne) {
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        final int managedProfilesCount = getProfiles(userId, true).size() - 1;
904        final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
905        if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
906            return false;
907        }
908        synchronized(mUsersLock) {
909            UserInfo userInfo = getUserInfoLU(userId);
910            if (!userInfo.canHaveProfile()) {
911                return false;
912            }
913            int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
914                    - profilesRemovedCount;
915            // We allow creating a managed profile in the special case where there is only one user.
916            return usersCountAfterRemoving  == 1
917                    || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
918        }
919    }
920
921    private int getAliveUsersExcludingGuestsCountLU() {
922        int aliveUserCount = 0;
923        final int totalUserCount = mUsers.size();
924        // Skip over users being removed
925        for (int i = 0; i < totalUserCount; i++) {
926            UserInfo user = mUsers.valueAt(i);
927            if (!mRemovingUserIds.get(user.id)
928                    && !user.isGuest() && !user.partial) {
929                aliveUserCount++;
930            }
931        }
932        return aliveUserCount;
933    }
934
935    /**
936     * Enforces that only the system UID or root's UID or apps that have the
937     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
938     * permission can make certain calls to the UserManager.
939     *
940     * @param message used as message if SecurityException is thrown
941     * @throws SecurityException if the caller is not system or root
942     */
943    private static final void checkManageUsersPermission(String message) {
944        final int uid = Binder.getCallingUid();
945        if (uid != Process.SYSTEM_UID && uid != 0
946                && ActivityManager.checkComponentPermission(
947                        android.Manifest.permission.MANAGE_USERS,
948                        uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
949            throw new SecurityException("You need MANAGE_USERS permission to: " + message);
950        }
951    }
952
953    private static void checkSystemOrRoot(String message) {
954        final int uid = Binder.getCallingUid();
955        if (uid != Process.SYSTEM_UID && uid != 0) {
956            throw new SecurityException("Only system may call: " + message);
957        }
958    }
959
960    private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
961        try {
962            File dir = new File(mUsersDir, Integer.toString(info.id));
963            File file = new File(dir, USER_PHOTO_FILENAME);
964            File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
965            if (!dir.exists()) {
966                dir.mkdir();
967                FileUtils.setPermissions(
968                        dir.getPath(),
969                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
970                        -1, -1);
971            }
972            FileOutputStream os;
973            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
974                    && tmp.renameTo(file)) {
975                info.iconPath = file.getAbsolutePath();
976            }
977            try {
978                os.close();
979            } catch (IOException ioe) {
980                // What the ... !
981            }
982            tmp.delete();
983        } catch (FileNotFoundException e) {
984            Slog.w(LOG_TAG, "Error setting photo for user ", e);
985        }
986    }
987
988    /**
989     * Returns an array of user ids. This array is cached here for quick access, so do not modify or
990     * cache it elsewhere.
991     * @return the array of user ids.
992     */
993    public int[] getUserIds() {
994        synchronized (mUsersLock) {
995            return mUserIds;
996        }
997    }
998
999    private void readUserListLILP() {
1000        if (!mUserListFile.exists()) {
1001            fallbackToSingleUserLILP();
1002            return;
1003        }
1004        FileInputStream fis = null;
1005        AtomicFile userListFile = new AtomicFile(mUserListFile);
1006        try {
1007            fis = userListFile.openRead();
1008            XmlPullParser parser = Xml.newPullParser();
1009            parser.setInput(fis, StandardCharsets.UTF_8.name());
1010            int type;
1011            while ((type = parser.next()) != XmlPullParser.START_TAG
1012                    && type != XmlPullParser.END_DOCUMENT) {
1013                ;
1014            }
1015
1016            if (type != XmlPullParser.START_TAG) {
1017                Slog.e(LOG_TAG, "Unable to read user list");
1018                fallbackToSingleUserLILP();
1019                return;
1020            }
1021
1022            mNextSerialNumber = -1;
1023            if (parser.getName().equals(TAG_USERS)) {
1024                String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1025                if (lastSerialNumber != null) {
1026                    mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1027                }
1028                String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1029                if (versionNumber != null) {
1030                    mUserVersion = Integer.parseInt(versionNumber);
1031                }
1032            }
1033
1034            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1035                if (type == XmlPullParser.START_TAG) {
1036                    final String name = parser.getName();
1037                    if (name.equals(TAG_USER)) {
1038                        String id = parser.getAttributeValue(null, ATTR_ID);
1039                        UserInfo user = readUserLILP(Integer.parseInt(id));
1040
1041                        if (user != null) {
1042                            synchronized (mUsersLock) {
1043                                mUsers.put(user.id, user);
1044                                if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1045                                    mNextSerialNumber = user.id + 1;
1046                                }
1047                            }
1048                        }
1049                    } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
1050                        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1051                                && type != XmlPullParser.END_TAG) {
1052                            if (type == XmlPullParser.START_TAG) {
1053                                if (parser.getName().equals(TAG_RESTRICTIONS)) {
1054                                    UserRestrictionsUtils
1055                                            .readRestrictions(parser, mGuestRestrictions);
1056                                }
1057                                break;
1058                            }
1059                        }
1060                    }
1061                }
1062            }
1063            updateUserIds();
1064            upgradeIfNecessaryLILP();
1065        } catch (IOException ioe) {
1066            fallbackToSingleUserLILP();
1067        } catch (XmlPullParserException pe) {
1068            fallbackToSingleUserLILP();
1069        } finally {
1070            if (fis != null) {
1071                try {
1072                    fis.close();
1073                } catch (IOException e) {
1074                }
1075            }
1076        }
1077    }
1078
1079    /**
1080     * Upgrade steps between versions, either for fixing bugs or changing the data format.
1081     */
1082    private void upgradeIfNecessaryLILP() {
1083        int userVersion = mUserVersion;
1084        if (userVersion < 1) {
1085            // Assign a proper name for the owner, if not initialized correctly before
1086            UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
1087            if ("Primary".equals(user.name)) {
1088                user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
1089                scheduleWriteUser(user);
1090            }
1091            userVersion = 1;
1092        }
1093
1094        if (userVersion < 2) {
1095            // Owner should be marked as initialized
1096            UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
1097            if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1098                user.flags |= UserInfo.FLAG_INITIALIZED;
1099                scheduleWriteUser(user);
1100            }
1101            userVersion = 2;
1102        }
1103
1104
1105        if (userVersion < 4) {
1106            userVersion = 4;
1107        }
1108
1109        if (userVersion < 5) {
1110            initDefaultGuestRestrictions();
1111            userVersion = 5;
1112        }
1113
1114        if (userVersion < 6) {
1115            final boolean splitSystemUser = UserManager.isSplitSystemUser();
1116            synchronized (mUsersLock) {
1117                for (int i = 0; i < mUsers.size(); i++) {
1118                    UserInfo user = mUsers.valueAt(i);
1119                    // In non-split mode, only user 0 can have restricted profiles
1120                    if (!splitSystemUser && user.isRestricted()
1121                            && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1122                        user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1123                        scheduleWriteUser(user);
1124                    }
1125                }
1126            }
1127            userVersion = 6;
1128        }
1129
1130        if (userVersion < USER_VERSION) {
1131            Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1132                    + USER_VERSION);
1133        } else {
1134            mUserVersion = userVersion;
1135            writeUserListLILP();
1136        }
1137    }
1138
1139    private void fallbackToSingleUserLILP() {
1140        int flags = UserInfo.FLAG_INITIALIZED;
1141        // In split system user mode, the admin and primary flags are assigned to the first human
1142        // user.
1143        if (!UserManager.isSplitSystemUser()) {
1144            flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1145        }
1146        // Create the system user
1147        UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
1148                mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
1149                flags);
1150        synchronized (mUsersLock) {
1151            mUsers.put(system.id, system);
1152        }
1153        mNextSerialNumber = MIN_USER_ID;
1154        mUserVersion = USER_VERSION;
1155
1156        Bundle restrictions = new Bundle();
1157        synchronized (mRestrictionsLock) {
1158            mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1159        }
1160
1161        updateUserIds();
1162        initDefaultGuestRestrictions();
1163
1164        writeUserListLILP();
1165        writeUserLP(system);
1166    }
1167
1168    private void scheduleWriteUser(UserInfo userInfo) {
1169        // No need to wrap it within a lock -- worst case, we'll just post the same message
1170        // twice.
1171        if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1172            Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1173            mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1174        }
1175    }
1176
1177    /*
1178     * Writes the user file in this format:
1179     *
1180     * <user flags="20039023" id="0">
1181     *   <name>Primary</name>
1182     * </user>
1183     */
1184    private void writeUserLP(UserInfo userInfo) {
1185        FileOutputStream fos = null;
1186        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
1187        try {
1188            fos = userFile.startWrite();
1189            final BufferedOutputStream bos = new BufferedOutputStream(fos);
1190
1191            // XmlSerializer serializer = XmlUtils.serializerInstance();
1192            final XmlSerializer serializer = new FastXmlSerializer();
1193            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
1194            serializer.startDocument(null, true);
1195            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1196
1197            serializer.startTag(null, TAG_USER);
1198            serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
1199            serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
1200            serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
1201            serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1202            serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1203                    Long.toString(userInfo.lastLoggedInTime));
1204            if (userInfo.iconPath != null) {
1205                serializer.attribute(null,  ATTR_ICON_PATH, userInfo.iconPath);
1206            }
1207            if (userInfo.partial) {
1208                serializer.attribute(null, ATTR_PARTIAL, "true");
1209            }
1210            if (userInfo.guestToRemove) {
1211                serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1212            }
1213            if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1214                serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1215                        Integer.toString(userInfo.profileGroupId));
1216            }
1217            if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1218                serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1219                        Integer.toString(userInfo.restrictedProfileParentId));
1220            }
1221            serializer.startTag(null, TAG_NAME);
1222            serializer.text(userInfo.name);
1223            serializer.endTag(null, TAG_NAME);
1224            Bundle restrictions;
1225            synchronized (mRestrictionsLock) {
1226                restrictions = mBaseUserRestrictions.get(userInfo.id);
1227            }
1228            if (restrictions != null) {
1229                UserRestrictionsUtils
1230                        .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
1231            }
1232            serializer.endTag(null, TAG_USER);
1233
1234            serializer.endDocument();
1235            userFile.finishWrite(fos);
1236        } catch (Exception ioe) {
1237            Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
1238            userFile.failWrite(fos);
1239        }
1240    }
1241
1242    /*
1243     * Writes the user list file in this format:
1244     *
1245     * <users nextSerialNumber="3">
1246     *   <user id="0"></user>
1247     *   <user id="2"></user>
1248     * </users>
1249     */
1250    private void writeUserListLILP() {
1251        // TODO Investigate removing a dependency on mInstallLock
1252        FileOutputStream fos = null;
1253        AtomicFile userListFile = new AtomicFile(mUserListFile);
1254        try {
1255            fos = userListFile.startWrite();
1256            final BufferedOutputStream bos = new BufferedOutputStream(fos);
1257
1258            // XmlSerializer serializer = XmlUtils.serializerInstance();
1259            final XmlSerializer serializer = new FastXmlSerializer();
1260            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
1261            serializer.startDocument(null, true);
1262            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1263
1264            serializer.startTag(null, TAG_USERS);
1265            serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
1266            serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
1267
1268            serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
1269            UserRestrictionsUtils
1270                    .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1271            serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
1272            int[] userIdsToWrite;
1273            synchronized (mUsersLock) {
1274                userIdsToWrite = new int[mUsers.size()];
1275                for (int i = 0; i < userIdsToWrite.length; i++) {
1276                    UserInfo user = mUsers.valueAt(i);
1277                    userIdsToWrite[i] = user.id;
1278                }
1279            }
1280            for (int id : userIdsToWrite) {
1281                serializer.startTag(null, TAG_USER);
1282                serializer.attribute(null, ATTR_ID, Integer.toString(id));
1283                serializer.endTag(null, TAG_USER);
1284            }
1285
1286            serializer.endTag(null, TAG_USERS);
1287
1288            serializer.endDocument();
1289            userListFile.finishWrite(fos);
1290        } catch (Exception e) {
1291            userListFile.failWrite(fos);
1292            Slog.e(LOG_TAG, "Error writing user list");
1293        }
1294    }
1295
1296    private UserInfo readUserLILP(int id) {
1297        int flags = 0;
1298        int serialNumber = id;
1299        String name = null;
1300        String iconPath = null;
1301        long creationTime = 0L;
1302        long lastLoggedInTime = 0L;
1303        int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
1304        int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
1305        boolean partial = false;
1306        boolean guestToRemove = false;
1307        Bundle restrictions = new Bundle();
1308
1309        FileInputStream fis = null;
1310        try {
1311            AtomicFile userFile =
1312                    new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
1313            fis = userFile.openRead();
1314            XmlPullParser parser = Xml.newPullParser();
1315            parser.setInput(fis, StandardCharsets.UTF_8.name());
1316            int type;
1317            while ((type = parser.next()) != XmlPullParser.START_TAG
1318                    && type != XmlPullParser.END_DOCUMENT) {
1319                ;
1320            }
1321
1322            if (type != XmlPullParser.START_TAG) {
1323                Slog.e(LOG_TAG, "Unable to read user " + id);
1324                return null;
1325            }
1326
1327            if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
1328                int storedId = readIntAttribute(parser, ATTR_ID, -1);
1329                if (storedId != id) {
1330                    Slog.e(LOG_TAG, "User id does not match the file name");
1331                    return null;
1332                }
1333                serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1334                flags = readIntAttribute(parser, ATTR_FLAGS, 0);
1335                iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
1336                creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1337                lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
1338                profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1339                        UserInfo.NO_PROFILE_GROUP_ID);
1340                restrictedProfileParentId = readIntAttribute(parser,
1341                        ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
1342                String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1343                if ("true".equals(valueString)) {
1344                    partial = true;
1345                }
1346                valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1347                if ("true".equals(valueString)) {
1348                    guestToRemove = true;
1349                }
1350
1351                int outerDepth = parser.getDepth();
1352                while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1353                       && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1354                    if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1355                        continue;
1356                    }
1357                    String tag = parser.getName();
1358                    if (TAG_NAME.equals(tag)) {
1359                        type = parser.next();
1360                        if (type == XmlPullParser.TEXT) {
1361                            name = parser.getText();
1362                        }
1363                    } else if (TAG_RESTRICTIONS.equals(tag)) {
1364                        UserRestrictionsUtils.readRestrictions(parser, restrictions);
1365                    }
1366                }
1367            }
1368
1369            UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
1370            userInfo.serialNumber = serialNumber;
1371            userInfo.creationTime = creationTime;
1372            userInfo.lastLoggedInTime = lastLoggedInTime;
1373            userInfo.partial = partial;
1374            userInfo.guestToRemove = guestToRemove;
1375            userInfo.profileGroupId = profileGroupId;
1376            userInfo.restrictedProfileParentId = restrictedProfileParentId;
1377            synchronized (mRestrictionsLock) {
1378                mBaseUserRestrictions.append(id, restrictions);
1379            }
1380            return userInfo;
1381
1382        } catch (IOException ioe) {
1383        } catch (XmlPullParserException pe) {
1384        } finally {
1385            if (fis != null) {
1386                try {
1387                    fis.close();
1388                } catch (IOException e) {
1389                }
1390            }
1391        }
1392        return null;
1393    }
1394
1395    private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1396        String valueString = parser.getAttributeValue(null, attr);
1397        if (valueString == null) return defaultValue;
1398        try {
1399            return Integer.parseInt(valueString);
1400        } catch (NumberFormatException nfe) {
1401            return defaultValue;
1402        }
1403    }
1404
1405    private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1406        String valueString = parser.getAttributeValue(null, attr);
1407        if (valueString == null) return defaultValue;
1408        try {
1409            return Long.parseLong(valueString);
1410        } catch (NumberFormatException nfe) {
1411            return defaultValue;
1412        }
1413    }
1414
1415    private boolean isPackageInstalled(String pkg, int userId) {
1416        final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1417                PackageManager.GET_UNINSTALLED_PACKAGES,
1418                userId);
1419        if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1420            return false;
1421        }
1422        return true;
1423    }
1424
1425    /**
1426     * Removes all the restrictions files (res_<packagename>) for a given user.
1427     * Does not do any permissions checking.
1428     */
1429    private void cleanAppRestrictions(int userId) {
1430        synchronized (mPackagesLock) {
1431            File dir = Environment.getUserSystemDirectory(userId);
1432            String[] files = dir.list();
1433            if (files == null) return;
1434            for (String fileName : files) {
1435                if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1436                    File resFile = new File(dir, fileName);
1437                    if (resFile.exists()) {
1438                        resFile.delete();
1439                    }
1440                }
1441            }
1442        }
1443    }
1444
1445    /**
1446     * Removes the app restrictions file for a specific package and user id, if it exists.
1447     */
1448    private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1449        synchronized (mPackagesLock) {
1450            File dir = Environment.getUserSystemDirectory(userId);
1451            File resFile = new File(dir, packageToRestrictionsFileName(pkg));
1452            if (resFile.exists()) {
1453                resFile.delete();
1454            }
1455        }
1456    }
1457
1458    @Override
1459    public UserInfo createProfileForUser(String name, int flags, int userId) {
1460        checkManageUsersPermission("Only the system can create users");
1461        return createUserInternal(name, flags, userId);
1462    }
1463
1464    @Override
1465    public UserInfo createUser(String name, int flags) {
1466        checkManageUsersPermission("Only the system can create users");
1467        return createUserInternal(name, flags, UserHandle.USER_NULL);
1468    }
1469
1470    private UserInfo createUserInternal(String name, int flags, int parentId) {
1471        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1472                UserManager.DISALLOW_ADD_USER, false)) {
1473            Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1474            return null;
1475        }
1476        if (ActivityManager.isLowRamDeviceStatic()) {
1477            return null;
1478        }
1479        final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
1480        final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
1481        final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
1482        final long ident = Binder.clearCallingIdentity();
1483        UserInfo userInfo = null;
1484        final int userId;
1485        try {
1486            synchronized (mInstallLock) {
1487                synchronized (mPackagesLock) {
1488                    UserInfo parent = null;
1489                    if (parentId != UserHandle.USER_NULL) {
1490                        synchronized (mUsersLock) {
1491                            parent = getUserInfoLU(parentId);
1492                        }
1493                        if (parent == null) return null;
1494                    }
1495                    if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1496                        Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1497                        return null;
1498                    }
1499                    if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1500                        // If we're not adding a guest user or a managed profile and the limit has
1501                        // been reached, cannot add a user.
1502                        return null;
1503                    }
1504                    // If we're adding a guest and there already exists one, bail.
1505                    if (isGuest && findCurrentGuestUser() != null) {
1506                        return null;
1507                    }
1508                    // In legacy mode, restricted profile's parent can only be the owner user
1509                    if (isRestricted && !UserManager.isSplitSystemUser()
1510                            && (parentId != UserHandle.USER_SYSTEM)) {
1511                        Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1512                        return null;
1513                    }
1514                    if (isRestricted && UserManager.isSplitSystemUser()) {
1515                        if (parent == null) {
1516                            Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1517                                    + "specified");
1518                            return null;
1519                        }
1520                        if (!parent.canHaveProfile()) {
1521                            Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1522                                    + "created for the specified parent user id " + parentId);
1523                            return null;
1524                        }
1525                    }
1526                    // In split system user mode, we assign the first human user the primary flag.
1527                    // And if there is no device owner, we also assign the admin flag to primary
1528                    // user.
1529                    if (UserManager.isSplitSystemUser()
1530                            && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1531                        flags |= UserInfo.FLAG_PRIMARY;
1532                        DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1533                                mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1534                        if (devicePolicyManager == null
1535                                || devicePolicyManager.getDeviceOwner() == null) {
1536                            flags |= UserInfo.FLAG_ADMIN;
1537                        }
1538                    }
1539                    userId = getNextAvailableId();
1540                    userInfo = new UserInfo(userId, name, null, flags);
1541                    userInfo.serialNumber = mNextSerialNumber++;
1542                    long now = System.currentTimeMillis();
1543                    userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1544                    userInfo.partial = true;
1545                    Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1546                    mUsers.put(userId, userInfo);
1547                    writeUserListLILP();
1548                    if (parent != null) {
1549                        if (isManagedProfile) {
1550                            if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1551                                parent.profileGroupId = parent.id;
1552                                scheduleWriteUser(parent);
1553                            }
1554                            userInfo.profileGroupId = parent.profileGroupId;
1555                        } else if (isRestricted) {
1556                            if (!parent.canHaveProfile()) {
1557                                Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1558                            }
1559                            if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1560                                parent.restrictedProfileParentId = parent.id;
1561                                scheduleWriteUser(parent);
1562                            }
1563                            userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
1564                        }
1565                    }
1566
1567                    final StorageManager storage = mContext.getSystemService(StorageManager.class);
1568                    storage.createUserKey(userId, userInfo.serialNumber);
1569                    for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1570                        final String volumeUuid = vol.getFsUuid();
1571                        try {
1572                            final File userDir = Environment.getDataUserDirectory(volumeUuid,
1573                                    userId);
1574                            storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1575                            enforceSerialNumber(userDir, userInfo.serialNumber);
1576                        } catch (IOException e) {
1577                            Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1578                        }
1579                    }
1580                    mPm.createNewUserLILPw(userId);
1581                    userInfo.partial = false;
1582                    scheduleWriteUser(userInfo);
1583                    updateUserIds();
1584                    Bundle restrictions = new Bundle();
1585                    synchronized (mRestrictionsLock) {
1586                        mBaseUserRestrictions.append(userId, restrictions);
1587                    }
1588                }
1589            }
1590            mPm.newUserCreated(userId);
1591            if (userInfo != null) {
1592                Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1593                addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1594                mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1595                        android.Manifest.permission.MANAGE_USERS);
1596            }
1597        } finally {
1598            Binder.restoreCallingIdentity(ident);
1599        }
1600        return userInfo;
1601    }
1602
1603    /**
1604     * @hide
1605     */
1606    public UserInfo createRestrictedProfile(String name, int parentUserId) {
1607        checkManageUsersPermission("setupRestrictedProfile");
1608        final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1609        if (user == null) {
1610            return null;
1611        }
1612        setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1613        // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1614        // the putIntForUser() will fail.
1615        android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1616                android.provider.Settings.Secure.LOCATION_MODE,
1617                android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1618        setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1619        return user;
1620    }
1621
1622    /**
1623     * Find the current guest user. If the Guest user is partial,
1624     * then do not include it in the results as it is about to die.
1625     */
1626    private UserInfo findCurrentGuestUser() {
1627        synchronized (mUsersLock) {
1628            final int size = mUsers.size();
1629            for (int i = 0; i < size; i++) {
1630                final UserInfo user = mUsers.valueAt(i);
1631                if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1632                    return user;
1633                }
1634            }
1635        }
1636        return null;
1637    }
1638
1639    /**
1640     * Mark this guest user for deletion to allow us to create another guest
1641     * and switch to that user before actually removing this guest.
1642     * @param userHandle the userid of the current guest
1643     * @return whether the user could be marked for deletion
1644     */
1645    public boolean markGuestForDeletion(int userHandle) {
1646        checkManageUsersPermission("Only the system can remove users");
1647        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1648                UserManager.DISALLOW_REMOVE_USER, false)) {
1649            Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1650            return false;
1651        }
1652
1653        long ident = Binder.clearCallingIdentity();
1654        try {
1655            final UserInfo user;
1656            synchronized (mPackagesLock) {
1657                synchronized (mUsersLock) {
1658                    user = mUsers.get(userHandle);
1659                    if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1660                        return false;
1661                    }
1662                }
1663                if (!user.isGuest()) {
1664                    return false;
1665                }
1666                // We set this to a guest user that is to be removed. This is a temporary state
1667                // where we are allowed to add new Guest users, even if this one is still not
1668                // removed. This user will still show up in getUserInfo() calls.
1669                // If we don't get around to removing this Guest user, it will be purged on next
1670                // startup.
1671                user.guestToRemove = true;
1672                // Mark it as disabled, so that it isn't returned any more when
1673                // profiles are queried.
1674                user.flags |= UserInfo.FLAG_DISABLED;
1675                writeUserLP(user);
1676            }
1677        } finally {
1678            Binder.restoreCallingIdentity(ident);
1679        }
1680        return true;
1681    }
1682
1683    /**
1684     * Removes a user and all data directories created for that user. This method should be called
1685     * after the user's processes have been terminated.
1686     * @param userHandle the user's id
1687     */
1688    public boolean removeUser(int userHandle) {
1689        checkManageUsersPermission("Only the system can remove users");
1690        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1691                UserManager.DISALLOW_REMOVE_USER, false)) {
1692            Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1693            return false;
1694        }
1695
1696        long ident = Binder.clearCallingIdentity();
1697        try {
1698            final UserInfo user;
1699            int currentUser = ActivityManager.getCurrentUser();
1700            if (currentUser == userHandle) {
1701                Log.w(LOG_TAG, "Current user cannot be removed");
1702                return false;
1703            }
1704            synchronized (mPackagesLock) {
1705                synchronized (mUsersLock) {
1706                    user = mUsers.get(userHandle);
1707                    if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1708                        return false;
1709                    }
1710
1711                    // We remember deleted user IDs to prevent them from being
1712                    // reused during the current boot; they can still be reused
1713                    // after a reboot.
1714                    mRemovingUserIds.put(userHandle, true);
1715                }
1716
1717                try {
1718                    mAppOpsService.removeUser(userHandle);
1719                } catch (RemoteException e) {
1720                    Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1721                }
1722                // Set this to a partially created user, so that the user will be purged
1723                // on next startup, in case the runtime stops now before stopping and
1724                // removing the user completely.
1725                user.partial = true;
1726                // Mark it as disabled, so that it isn't returned any more when
1727                // profiles are queried.
1728                user.flags |= UserInfo.FLAG_DISABLED;
1729                writeUserLP(user);
1730            }
1731
1732            if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1733                    && user.isManagedProfile()) {
1734                // Send broadcast to notify system that the user removed was a
1735                // managed user.
1736                sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1737            }
1738
1739            if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1740            int res;
1741            try {
1742                res = ActivityManagerNative.getDefault().stopUser(userHandle,
1743                        new IStopUserCallback.Stub() {
1744                            @Override
1745                            public void userStopped(int userId) {
1746                                finishRemoveUser(userId);
1747                            }
1748                            @Override
1749                            public void userStopAborted(int userId) {
1750                            }
1751                        });
1752            } catch (RemoteException e) {
1753                return false;
1754            }
1755            return res == ActivityManager.USER_OP_SUCCESS;
1756        } finally {
1757            Binder.restoreCallingIdentity(ident);
1758        }
1759    }
1760
1761    void finishRemoveUser(final int userHandle) {
1762        if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
1763        // Let other services shutdown any activity and clean up their state before completely
1764        // wiping the user's system directory and removing from the user list
1765        long ident = Binder.clearCallingIdentity();
1766        try {
1767            Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1768            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
1769            mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1770                    android.Manifest.permission.MANAGE_USERS,
1771
1772                    new BroadcastReceiver() {
1773                        @Override
1774                        public void onReceive(Context context, Intent intent) {
1775                            if (DBG) {
1776                                Slog.i(LOG_TAG,
1777                                        "USER_REMOVED broadcast sent, cleaning up user data "
1778                                        + userHandle);
1779                            }
1780                            new Thread() {
1781                                public void run() {
1782                                    // Clean up any ActivityManager state
1783                                    LocalServices.getService(ActivityManagerInternal.class)
1784                                            .onUserRemoved(userHandle);
1785                                    synchronized (mInstallLock) {
1786                                        synchronized (mPackagesLock) {
1787                                            removeUserStateLILP(userHandle);
1788                                        }
1789                                    }
1790                                }
1791                            }.start();
1792                        }
1793                    },
1794
1795                    null, Activity.RESULT_OK, null, null);
1796        } finally {
1797            Binder.restoreCallingIdentity(ident);
1798        }
1799    }
1800
1801    private void removeUserStateLILP(final int userHandle) {
1802        mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
1803        // Cleanup package manager settings
1804        mPm.cleanUpUserLILPw(this, userHandle);
1805
1806        // Remove this user from the list
1807        synchronized (mUsersLock) {
1808            mUsers.remove(userHandle);
1809        }
1810        // Remove user file
1811        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
1812        userFile.delete();
1813        // Update the user list
1814        writeUserListLILP();
1815        updateUserIds();
1816        removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1817    }
1818
1819    private void removeDirectoryRecursive(File parent) {
1820        if (parent.isDirectory()) {
1821            String[] files = parent.list();
1822            for (String filename : files) {
1823                File child = new File(parent, filename);
1824                removeDirectoryRecursive(child);
1825            }
1826        }
1827        parent.delete();
1828    }
1829
1830    private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
1831        Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
1832        managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1833                Intent.FLAG_RECEIVER_FOREGROUND);
1834        managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1835        mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
1836    }
1837
1838    @Override
1839    public Bundle getApplicationRestrictions(String packageName) {
1840        return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1841    }
1842
1843    @Override
1844    public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
1845        if (UserHandle.getCallingUserId() != userId
1846                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
1847            checkManageUsersPermission("get application restrictions for other users/apps");
1848        }
1849        synchronized (mPackagesLock) {
1850            // Read the restrictions from XML
1851            return readApplicationRestrictionsLP(packageName, userId);
1852        }
1853    }
1854
1855    @Override
1856    public void setApplicationRestrictions(String packageName, Bundle restrictions,
1857            int userId) {
1858        checkManageUsersPermission("set application restrictions");
1859        synchronized (mPackagesLock) {
1860            if (restrictions == null || restrictions.isEmpty()) {
1861                cleanAppRestrictionsForPackage(packageName, userId);
1862            } else {
1863                // Write the restrictions to XML
1864                writeApplicationRestrictionsLP(packageName, restrictions, userId);
1865            }
1866        }
1867
1868        if (isPackageInstalled(packageName, userId)) {
1869            // Notify package of changes via an intent - only sent to explicitly registered receivers.
1870            Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1871            changeIntent.setPackage(packageName);
1872            changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1873            mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1874        }
1875    }
1876
1877    private void unhideAllInstalledAppsForUser(final int userHandle) {
1878        mHandler.post(new Runnable() {
1879            @Override
1880            public void run() {
1881                List<ApplicationInfo> apps =
1882                        mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1883                                userHandle).getList();
1884                final long ident = Binder.clearCallingIdentity();
1885                try {
1886                    for (ApplicationInfo appInfo : apps) {
1887                        if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1888                                && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1889                                        != 0) {
1890                            mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
1891                                    userHandle);
1892                        }
1893                    }
1894                } finally {
1895                    Binder.restoreCallingIdentity(ident);
1896                }
1897            }
1898        });
1899    }
1900    private int getUidForPackage(String packageName) {
1901        long ident = Binder.clearCallingIdentity();
1902        try {
1903            return mContext.getPackageManager().getApplicationInfo(packageName,
1904                    PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1905        } catch (NameNotFoundException nnfe) {
1906            return -1;
1907        } finally {
1908            Binder.restoreCallingIdentity(ident);
1909        }
1910    }
1911
1912    private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
1913        AtomicFile restrictionsFile =
1914                new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1915                        packageToRestrictionsFileName(packageName)));
1916        return readApplicationRestrictionsLP(restrictionsFile);
1917    }
1918
1919    @VisibleForTesting
1920    static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
1921        final Bundle restrictions = new Bundle();
1922        final ArrayList<String> values = new ArrayList<>();
1923        if (!restrictionsFile.getBaseFile().exists()) {
1924            return restrictions;
1925        }
1926
1927        FileInputStream fis = null;
1928        try {
1929            fis = restrictionsFile.openRead();
1930            XmlPullParser parser = Xml.newPullParser();
1931            parser.setInput(fis, StandardCharsets.UTF_8.name());
1932            XmlUtils.nextElement(parser);
1933            if (parser.getEventType() != XmlPullParser.START_TAG) {
1934                Slog.e(LOG_TAG, "Unable to read restrictions file "
1935                        + restrictionsFile.getBaseFile());
1936                return restrictions;
1937            }
1938            while (parser.next() != XmlPullParser.END_DOCUMENT) {
1939                readEntry(restrictions, values, parser);
1940            }
1941        } catch (IOException|XmlPullParserException e) {
1942            Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
1943        } finally {
1944            IoUtils.closeQuietly(fis);
1945        }
1946        return restrictions;
1947    }
1948
1949    private static void readEntry(Bundle restrictions, ArrayList<String> values,
1950            XmlPullParser parser) throws XmlPullParserException, IOException {
1951        int type = parser.getEventType();
1952        if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1953            String key = parser.getAttributeValue(null, ATTR_KEY);
1954            String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1955            String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1956            if (multiple != null) {
1957                values.clear();
1958                int count = Integer.parseInt(multiple);
1959                while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1960                    if (type == XmlPullParser.START_TAG
1961                            && parser.getName().equals(TAG_VALUE)) {
1962                        values.add(parser.nextText().trim());
1963                        count--;
1964                    }
1965                }
1966                String [] valueStrings = new String[values.size()];
1967                values.toArray(valueStrings);
1968                restrictions.putStringArray(key, valueStrings);
1969            } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1970                restrictions.putBundle(key, readBundleEntry(parser, values));
1971            } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1972                final int outerDepth = parser.getDepth();
1973                ArrayList<Bundle> bundleList = new ArrayList<>();
1974                while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1975                    Bundle childBundle = readBundleEntry(parser, values);
1976                    bundleList.add(childBundle);
1977                }
1978                restrictions.putParcelableArray(key,
1979                        bundleList.toArray(new Bundle[bundleList.size()]));
1980            } else {
1981                String value = parser.nextText().trim();
1982                if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1983                    restrictions.putBoolean(key, Boolean.parseBoolean(value));
1984                } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1985                    restrictions.putInt(key, Integer.parseInt(value));
1986                } else {
1987                    restrictions.putString(key, value);
1988                }
1989            }
1990        }
1991    }
1992
1993    private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1994            throws IOException, XmlPullParserException {
1995        Bundle childBundle = new Bundle();
1996        final int outerDepth = parser.getDepth();
1997        while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1998            readEntry(childBundle, values, parser);
1999        }
2000        return childBundle;
2001    }
2002
2003    private void writeApplicationRestrictionsLP(String packageName,
2004            Bundle restrictions, int userId) {
2005        AtomicFile restrictionsFile = new AtomicFile(
2006                new File(Environment.getUserSystemDirectory(userId),
2007                        packageToRestrictionsFileName(packageName)));
2008        writeApplicationRestrictionsLP(restrictions, restrictionsFile);
2009    }
2010
2011    @VisibleForTesting
2012    static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
2013        FileOutputStream fos = null;
2014        try {
2015            fos = restrictionsFile.startWrite();
2016            final BufferedOutputStream bos = new BufferedOutputStream(fos);
2017
2018            final XmlSerializer serializer = new FastXmlSerializer();
2019            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
2020            serializer.startDocument(null, true);
2021            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2022
2023            serializer.startTag(null, TAG_RESTRICTIONS);
2024            writeBundle(restrictions, serializer);
2025            serializer.endTag(null, TAG_RESTRICTIONS);
2026
2027            serializer.endDocument();
2028            restrictionsFile.finishWrite(fos);
2029        } catch (Exception e) {
2030            restrictionsFile.failWrite(fos);
2031            Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2032        }
2033    }
2034
2035    private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2036            throws IOException {
2037        for (String key : restrictions.keySet()) {
2038            Object value = restrictions.get(key);
2039            serializer.startTag(null, TAG_ENTRY);
2040            serializer.attribute(null, ATTR_KEY, key);
2041
2042            if (value instanceof Boolean) {
2043                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2044                serializer.text(value.toString());
2045            } else if (value instanceof Integer) {
2046                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2047                serializer.text(value.toString());
2048            } else if (value == null || value instanceof String) {
2049                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2050                serializer.text(value != null ? (String) value : "");
2051            } else if (value instanceof Bundle) {
2052                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2053                writeBundle((Bundle) value, serializer);
2054            } else if (value instanceof Parcelable[]) {
2055                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2056                Parcelable[] array = (Parcelable[]) value;
2057                for (Parcelable parcelable : array) {
2058                    if (!(parcelable instanceof Bundle)) {
2059                        throw new IllegalArgumentException("bundle-array can only hold Bundles");
2060                    }
2061                    serializer.startTag(null, TAG_ENTRY);
2062                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2063                    writeBundle((Bundle) parcelable, serializer);
2064                    serializer.endTag(null, TAG_ENTRY);
2065                }
2066            } else {
2067                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2068                String[] values = (String[]) value;
2069                serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2070                for (String choice : values) {
2071                    serializer.startTag(null, TAG_VALUE);
2072                    serializer.text(choice != null ? choice : "");
2073                    serializer.endTag(null, TAG_VALUE);
2074                }
2075            }
2076            serializer.endTag(null, TAG_ENTRY);
2077        }
2078    }
2079
2080    @Override
2081    public int getUserSerialNumber(int userHandle) {
2082        synchronized (mUsersLock) {
2083            if (!exists(userHandle)) return -1;
2084            return getUserInfoLU(userHandle).serialNumber;
2085        }
2086    }
2087
2088    @Override
2089    public int getUserHandle(int userSerialNumber) {
2090        synchronized (mUsersLock) {
2091            for (int userId : mUserIds) {
2092                UserInfo info = getUserInfoLU(userId);
2093                if (info != null && info.serialNumber == userSerialNumber) return userId;
2094            }
2095            // Not found
2096            return -1;
2097        }
2098    }
2099
2100    @Override
2101    public long getUserCreationTime(int userHandle) {
2102        int callingUserId = UserHandle.getCallingUserId();
2103        UserInfo userInfo = null;
2104        synchronized (mUsersLock) {
2105            if (callingUserId == userHandle) {
2106                userInfo = getUserInfoLU(userHandle);
2107            } else {
2108                UserInfo parent = getProfileParentLU(userHandle);
2109                if (parent != null && parent.id == callingUserId) {
2110                    userInfo = getUserInfoLU(userHandle);
2111                }
2112            }
2113        }
2114        if (userInfo == null) {
2115            throw new SecurityException("userHandle can only be the calling user or a managed "
2116                    + "profile associated with this user");
2117        }
2118        return userInfo.creationTime;
2119    }
2120
2121    /**
2122     * Caches the list of user ids in an array, adjusting the array size when necessary.
2123     */
2124    private void updateUserIds() {
2125        int num = 0;
2126        synchronized (mUsersLock) {
2127            final int userSize = mUsers.size();
2128            for (int i = 0; i < userSize; i++) {
2129                if (!mUsers.valueAt(i).partial) {
2130                    num++;
2131                }
2132            }
2133            final int[] newUsers = new int[num];
2134            int n = 0;
2135            for (int i = 0; i < userSize; i++) {
2136                if (!mUsers.valueAt(i).partial) {
2137                    newUsers[n++] = mUsers.keyAt(i);
2138                }
2139            }
2140            mUserIds = newUsers;
2141        }
2142    }
2143
2144    /**
2145     * Make a note of the last started time of a user and do some cleanup.
2146     * @param userId the user that was just foregrounded
2147     */
2148    public void onUserForeground(int userId) {
2149        synchronized (mPackagesLock) {
2150            UserInfo user = getUserInfoNoChecks(userId);
2151            long now = System.currentTimeMillis();
2152            if (user == null || user.partial) {
2153                Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2154                return;
2155            }
2156            if (now > EPOCH_PLUS_30_YEARS) {
2157                user.lastLoggedInTime = now;
2158                scheduleWriteUser(user);
2159            }
2160        }
2161    }
2162
2163    /**
2164     * Returns the next available user id, filling in any holes in the ids.
2165     * TODO: May not be a good idea to recycle ids, in case it results in confusion
2166     * for data and battery stats collection, or unexpected cross-talk.
2167     * @return
2168     */
2169    private int getNextAvailableId() {
2170        synchronized (mUsersLock) {
2171            int i = MIN_USER_ID;
2172            while (i < MAX_USER_ID) {
2173                if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
2174                    return i;
2175                }
2176                i++;
2177            }
2178        }
2179        throw new IllegalStateException("No user id available!");
2180    }
2181
2182    private String packageToRestrictionsFileName(String packageName) {
2183        return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2184    }
2185
2186    /**
2187     * Enforce that serial number stored in user directory inode matches the
2188     * given expected value. Gracefully sets the serial number if currently
2189     * undefined.
2190     *
2191     * @throws IOException when problem extracting serial number, or serial
2192     *             number is mismatched.
2193     */
2194    public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2195        final int foundSerial = getSerialNumber(file);
2196        Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2197
2198        if (foundSerial == -1) {
2199            Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2200            try {
2201                setSerialNumber(file, serialNumber);
2202            } catch (IOException e) {
2203                Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2204            }
2205
2206        } else if (foundSerial != serialNumber) {
2207            throw new IOException("Found serial number " + foundSerial
2208                    + " doesn't match expected " + serialNumber);
2209        }
2210    }
2211
2212    /**
2213     * Set serial number stored in user directory inode.
2214     *
2215     * @throws IOException if serial number was already set
2216     */
2217    private static void setSerialNumber(File file, int serialNumber)
2218            throws IOException {
2219        try {
2220            final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2221            Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2222        } catch (ErrnoException e) {
2223            throw e.rethrowAsIOException();
2224        }
2225    }
2226
2227    /**
2228     * Return serial number stored in user directory inode.
2229     *
2230     * @return parsed serial number, or -1 if not set
2231     */
2232    private static int getSerialNumber(File file) throws IOException {
2233        try {
2234            final byte[] buf = new byte[256];
2235            final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2236            final String serial = new String(buf, 0, len);
2237            try {
2238                return Integer.parseInt(serial);
2239            } catch (NumberFormatException e) {
2240                throw new IOException("Bad serial number: " + serial);
2241            }
2242        } catch (ErrnoException e) {
2243            if (e.errno == OsConstants.ENODATA) {
2244                return -1;
2245            } else {
2246                throw e.rethrowAsIOException();
2247            }
2248        }
2249    }
2250
2251    @Override
2252    public void onShellCommand(FileDescriptor in, FileDescriptor out,
2253            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2254        (new Shell()).exec(this, in, out, err, args, resultReceiver);
2255    }
2256
2257    int onShellCommand(Shell shell, String cmd) {
2258        if (cmd == null) {
2259            return shell.handleDefaultCommands(cmd);
2260        }
2261
2262        final PrintWriter pw = shell.getOutPrintWriter();
2263        try {
2264            switch(cmd) {
2265                case "list":
2266                    return runList(pw);
2267            }
2268        } catch (RemoteException e) {
2269            pw.println("Remote exception: " + e);
2270        }
2271        return -1;
2272    }
2273
2274    private int runList(PrintWriter pw) throws RemoteException {
2275        final IActivityManager am = ActivityManagerNative.getDefault();
2276        final List<UserInfo> users = getUsers(false);
2277        if (users == null) {
2278            pw.println("Error: couldn't get users");
2279            return 1;
2280        } else {
2281            pw.println("Users:");
2282            for (int i = 0; i < users.size(); i++) {
2283                String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
2284                pw.println("\t" + users.get(i).toString() + running);
2285            }
2286            return 0;
2287        }
2288    }
2289
2290    @Override
2291    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2292        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2293                != PackageManager.PERMISSION_GRANTED) {
2294            pw.println("Permission Denial: can't dump UserManager from from pid="
2295                    + Binder.getCallingPid()
2296                    + ", uid=" + Binder.getCallingUid()
2297                    + " without permission "
2298                    + android.Manifest.permission.DUMP);
2299            return;
2300        }
2301
2302        long now = System.currentTimeMillis();
2303        StringBuilder sb = new StringBuilder();
2304        synchronized (mPackagesLock) {
2305            synchronized (mUsersLock) {
2306                pw.println("Users:");
2307                for (int i = 0; i < mUsers.size(); i++) {
2308                    UserInfo user = mUsers.valueAt(i);
2309                    if (user == null) {
2310                        continue;
2311                    }
2312                    pw.print("  "); pw.print(user);
2313                    pw.print(" serialNo="); pw.print(user.serialNumber);
2314                    if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2315                        pw.print(" <removing> ");
2316                    }
2317                    if (user.partial) {
2318                        pw.print(" <partial>");
2319                    }
2320                    pw.println();
2321                    pw.print("    Created: ");
2322                    if (user.creationTime == 0) {
2323                        pw.println("<unknown>");
2324                    } else {
2325                        sb.setLength(0);
2326                        TimeUtils.formatDuration(now - user.creationTime, sb);
2327                        sb.append(" ago");
2328                        pw.println(sb);
2329                    }
2330                    pw.print("    Last logged in: ");
2331                    if (user.lastLoggedInTime == 0) {
2332                        pw.println("<unknown>");
2333                    } else {
2334                        sb.setLength(0);
2335                        TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2336                        sb.append(" ago");
2337                        pw.println(sb);
2338                    }
2339                    pw.println("    Restrictions:");
2340                    synchronized (mRestrictionsLock) {
2341                        UserRestrictionsUtils.dumpRestrictions(
2342                                pw, "      ", mBaseUserRestrictions.get(user.id));
2343                        pw.println("    Effective restrictions:");
2344                        UserRestrictionsUtils.dumpRestrictions(
2345                                pw, "      ", mCachedEffectiveUserRestrictions.get(user.id));
2346                    }
2347                }
2348            }
2349            pw.println();
2350            pw.println("Guest restrictions:");
2351            UserRestrictionsUtils.dumpRestrictions(pw, "  ", mGuestRestrictions);
2352        }
2353    }
2354
2355    final class MainHandler extends Handler {
2356
2357        @Override
2358        public void handleMessage(Message msg) {
2359            switch (msg.what) {
2360                case WRITE_USER_MSG:
2361                    removeMessages(WRITE_USER_MSG, msg.obj);
2362                    synchronized (mPackagesLock) {
2363                        int userId = ((UserInfo) msg.obj).id;
2364                        UserInfo userInfo = getUserInfoNoChecks(userId);
2365                        if (userInfo != null) {
2366                            writeUserLP(userInfo);
2367                        }
2368                    }
2369            }
2370        }
2371    }
2372
2373    /**
2374     * @param userId
2375     * @return whether the user has been initialized yet
2376     */
2377    boolean isInitialized(int userId) {
2378        return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2379    }
2380
2381    private class LocalService extends UserManagerInternal {
2382
2383        @Override
2384        public Object getUserRestrictionsLock() {
2385            return mRestrictionsLock;
2386        }
2387
2388        @Override
2389        @GuardedBy("mRestrictionsLock")
2390        public void updateEffectiveUserRestrictionsLR(int userId) {
2391            UserManagerService.this.updateEffectiveUserRestrictionsLR(userId);
2392        }
2393
2394        @Override
2395        @GuardedBy("mRestrictionsLock")
2396        public void updateEffectiveUserRestrictionsForAllUsersLR() {
2397            UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersLR();
2398        }
2399
2400        @Override
2401        public Bundle getBaseUserRestrictions(int userId) {
2402            synchronized (mRestrictionsLock) {
2403                return mBaseUserRestrictions.get(userId);
2404            }
2405        }
2406
2407        @Override
2408        public void setBaseUserRestrictionsByDpmsForMigration(
2409                int userId, Bundle baseRestrictions) {
2410            synchronized (mRestrictionsLock) {
2411                mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
2412                invalidateEffectiveUserRestrictionsLR(userId);
2413            }
2414
2415            final UserInfo userInfo = getUserInfoNoChecks(userId);
2416            synchronized (mPackagesLock) {
2417                if (userInfo != null) {
2418                    writeUserLP(userInfo);
2419                } else {
2420                    Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2421                }
2422            }
2423        }
2424
2425        @Override
2426        public boolean getUserRestriction(int userId, String key) {
2427            return getUserRestrictions(userId).getBoolean(key);
2428        }
2429
2430        @Override
2431        public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2432            synchronized (mUserRestrictionsListeners) {
2433                mUserRestrictionsListeners.add(listener);
2434            }
2435        }
2436
2437        @Override
2438        public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2439            synchronized (mUserRestrictionsListeners) {
2440                mUserRestrictionsListeners.remove(listener);
2441            }
2442        }
2443    }
2444
2445    private class Shell extends ShellCommand {
2446        @Override
2447        public int onCommand(String cmd) {
2448            return onShellCommand(this, cmd);
2449        }
2450
2451        @Override
2452        public void onHelp() {
2453            final PrintWriter pw = getOutPrintWriter();
2454            pw.println("User manager (user) commands:");
2455            pw.println("  help");
2456            pw.println("    Print this help text.");
2457            pw.println("");
2458            pw.println("  list");
2459            pw.println("    Prints all users on the system.");
2460        }
2461    }
2462}
2463