UserManagerService.java revision 83c79317cc8e000fabc5ce82961a2b5e6f3b0ab3
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
22import android.Manifest;
23import android.annotation.NonNull;
24import android.annotation.Nullable;
25import android.annotation.UserIdInt;
26import android.app.Activity;
27import android.app.ActivityManager;
28import android.app.ActivityManagerInternal;
29import android.app.ActivityManagerNative;
30import android.app.IActivityManager;
31import android.app.IStopUserCallback;
32import android.app.KeyguardManager;
33import android.app.PendingIntent;
34import android.content.BroadcastReceiver;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.IntentSender;
39import android.content.pm.PackageManager;
40import android.content.pm.PackageManager.NameNotFoundException;
41import android.content.pm.ShortcutServiceInternal;
42import android.content.pm.UserInfo;
43import android.content.res.Resources;
44import android.graphics.Bitmap;
45import android.os.Binder;
46import android.os.Build;
47import android.os.Bundle;
48import android.os.Debug;
49import android.os.Environment;
50import android.os.FileUtils;
51import android.os.Handler;
52import android.os.IBinder;
53import android.os.IProgressListener;
54import android.os.IUserManager;
55import android.os.Message;
56import android.os.ParcelFileDescriptor;
57import android.os.Parcelable;
58import android.os.PersistableBundle;
59import android.os.Process;
60import android.os.RemoteException;
61import android.os.ResultReceiver;
62import android.os.SELinux;
63import android.os.ServiceManager;
64import android.os.ShellCallback;
65import android.os.ShellCommand;
66import android.os.SystemClock;
67import android.os.SystemProperties;
68import android.os.UserHandle;
69import android.os.UserManager;
70import android.os.UserManager.EnforcingUser;
71import android.os.UserManagerInternal;
72import android.os.UserManagerInternal.UserRestrictionsListener;
73import android.os.storage.StorageManager;
74import android.security.GateKeeper;
75import android.service.gatekeeper.IGateKeeperService;
76import android.util.AtomicFile;
77import android.util.IntArray;
78import android.util.Log;
79import android.util.Slog;
80import android.util.SparseArray;
81import android.util.SparseBooleanArray;
82import android.util.SparseIntArray;
83import android.util.SparseLongArray;
84import android.util.TimeUtils;
85import android.util.Xml;
86
87import com.android.internal.annotations.GuardedBy;
88import com.android.internal.annotations.VisibleForTesting;
89import com.android.internal.app.IAppOpsService;
90import com.android.internal.logging.MetricsLogger;
91import com.android.internal.os.BackgroundThread;
92import com.android.internal.util.DumpUtils;
93import com.android.internal.util.FastXmlSerializer;
94import com.android.internal.util.Preconditions;
95import com.android.internal.util.XmlUtils;
96import com.android.internal.widget.LockPatternUtils;
97import com.android.server.LocalServices;
98import com.android.server.LockGuard;
99import com.android.server.SystemService;
100import com.android.server.am.UserState;
101import com.android.server.storage.DeviceStorageMonitorInternal;
102
103import libcore.io.IoUtils;
104
105import org.xmlpull.v1.XmlPullParser;
106import org.xmlpull.v1.XmlPullParserException;
107import org.xmlpull.v1.XmlSerializer;
108
109import java.io.BufferedOutputStream;
110import java.io.File;
111import java.io.FileDescriptor;
112import java.io.FileInputStream;
113import java.io.FileNotFoundException;
114import java.io.FileOutputStream;
115import java.io.IOException;
116import java.io.InputStream;
117import java.io.OutputStream;
118import java.io.PrintWriter;
119import java.nio.charset.StandardCharsets;
120import java.util.ArrayList;
121import java.util.Collections;
122import java.util.LinkedList;
123import java.util.List;
124import java.util.Objects;
125
126/**
127 * Service for {@link UserManager}.
128 *
129 * Method naming convention:
130 * <ul>
131 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
132 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
133 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
134 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
135 * </ul>
136 */
137public class UserManagerService extends IUserManager.Stub {
138
139    private static final String LOG_TAG = "UserManagerService";
140    static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
141    private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
142    // Can be used for manual testing of id recycling
143    private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
144
145    private static final String TAG_NAME = "name";
146    private static final String TAG_ACCOUNT = "account";
147    private static final String ATTR_FLAGS = "flags";
148    private static final String ATTR_ICON_PATH = "icon";
149    private static final String ATTR_ID = "id";
150    private static final String ATTR_CREATION_TIME = "created";
151    private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
152    private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
153    private static final String ATTR_SERIAL_NO = "serialNumber";
154    private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
155    private static final String ATTR_PARTIAL = "partial";
156    private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
157    private static final String ATTR_USER_VERSION = "version";
158    private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
159    private static final String ATTR_PROFILE_BADGE = "profileBadge";
160    private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
161    private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
162    private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
163    private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
164    private static final String TAG_USERS = "users";
165    private static final String TAG_USER = "user";
166    private static final String TAG_RESTRICTIONS = "restrictions";
167    private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
168    private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
169            "device_policy_global_restrictions";
170    /** Legacy name for device owner id tag. */
171    private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
172    private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
173    private static final String TAG_ENTRY = "entry";
174    private static final String TAG_VALUE = "value";
175    private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
176    private static final String ATTR_KEY = "key";
177    private static final String ATTR_VALUE_TYPE = "type";
178    private static final String ATTR_MULTIPLE = "m";
179
180    private static final String ATTR_TYPE_STRING_ARRAY = "sa";
181    private static final String ATTR_TYPE_STRING = "s";
182    private static final String ATTR_TYPE_BOOLEAN = "b";
183    private static final String ATTR_TYPE_INTEGER = "i";
184    private static final String ATTR_TYPE_BUNDLE = "B";
185    private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
186
187    private static final String USER_INFO_DIR = "system" + File.separator + "users";
188    private static final String USER_LIST_FILENAME = "userlist.xml";
189    private static final String USER_PHOTO_FILENAME = "photo.png";
190    private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
191
192    private static final String RESTRICTIONS_FILE_PREFIX = "res_";
193    private static final String XML_SUFFIX = ".xml";
194
195    private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
196            UserInfo.FLAG_MANAGED_PROFILE
197            | UserInfo.FLAG_EPHEMERAL
198            | UserInfo.FLAG_RESTRICTED
199            | UserInfo.FLAG_GUEST
200            | UserInfo.FLAG_DEMO;
201
202    @VisibleForTesting
203    static final int MIN_USER_ID = 10;
204    // We need to keep process uid within Integer.MAX_VALUE.
205    @VisibleForTesting
206    static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
207
208    // Max size of the queue of recently removed users
209    @VisibleForTesting
210    static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
211
212    private static final int USER_VERSION = 7;
213
214    private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
215
216    // Maximum number of managed profiles permitted per user is 1. This cannot be increased
217    // without first making sure that the rest of the framework is prepared for it.
218    @VisibleForTesting
219    static final int MAX_MANAGED_PROFILES = 1;
220
221    static final int WRITE_USER_MSG = 1;
222    static final int WRITE_USER_DELAY = 2*1000;  // 2 seconds
223
224    // Tron counters
225    private static final String TRON_GUEST_CREATED = "users_guest_created";
226    private static final String TRON_USER_CREATED = "users_user_created";
227    private static final String TRON_DEMO_CREATED = "users_demo_created";
228
229    private final Context mContext;
230    private final PackageManagerService mPm;
231    private final Object mPackagesLock;
232    private final UserDataPreparer mUserDataPreparer;
233    // Short-term lock for internal state, when interaction/sync with PM is not required
234    private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
235    private final Object mRestrictionsLock = new Object();
236    // Used for serializing access to app restriction files
237    private final Object mAppRestrictionsLock = new Object();
238
239    private final Handler mHandler;
240
241    private final File mUsersDir;
242    private final File mUserListFile;
243
244    private static final IBinder mUserRestriconToken = new Binder();
245
246    /**
247     * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
248     */
249    @VisibleForTesting
250    static class UserData {
251        // Basic user information and properties
252        UserInfo info;
253        // Account name used when there is a strong association between a user and an account
254        String account;
255        // Account information for seeding into a newly created user. This could also be
256        // used for login validation for an existing user, for updating their credentials.
257        // In the latter case, data may not need to be persisted as it is only valid for the
258        // current login session.
259        String seedAccountName;
260        String seedAccountType;
261        PersistableBundle seedAccountOptions;
262        // Whether to perist the seed account information to be available after a boot
263        boolean persistSeedData;
264
265        /** Elapsed realtime since boot when the user started. */
266        long startRealtime;
267
268        /** Elapsed realtime since boot when the user was unlocked. */
269        long unlockRealtime;
270
271        void clearSeedAccountData() {
272            seedAccountName = null;
273            seedAccountType = null;
274            seedAccountOptions = null;
275            persistSeedData = false;
276        }
277    }
278
279    @GuardedBy("mUsersLock")
280    private final SparseArray<UserData> mUsers = new SparseArray<>();
281
282    /**
283     * User restrictions set via UserManager.  This doesn't include restrictions set by
284     * device owner / profile owners. Only non-empty restriction bundles are stored.
285     *
286     * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
287     * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
288     * maybe shared between {@link #mBaseUserRestrictions} and
289     * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
290     * (Otherwise we won't be able to detect what restrictions have changed in
291     * {@link #updateUserRestrictionsInternalLR}.
292     */
293    @GuardedBy("mRestrictionsLock")
294    private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
295
296    /**
297     * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
298     * with device / profile owner restrictions.  We'll initialize it lazily; use
299     * {@link #getEffectiveUserRestrictions} to access it.
300     *
301     * DO NOT Change existing {@link Bundle} in it.  When changing a restriction for a user,
302     * a new {@link Bundle} should always be created and set.  This is because a {@link Bundle}
303     * maybe shared between {@link #mBaseUserRestrictions} and
304     * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
305     * (Otherwise we won't be able to detect what restrictions have changed in
306     * {@link #updateUserRestrictionsInternalLR}.
307     */
308    @GuardedBy("mRestrictionsLock")
309    private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
310
311    /**
312     * User restrictions that have already been applied in
313     * {@link #updateUserRestrictionsInternalLR(Bundle, int)}.  We use it to detect restrictions
314     * that have changed since the last
315     * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
316     */
317    @GuardedBy("mRestrictionsLock")
318    private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
319
320    /**
321     * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
322     * that should be applied to all users, including guests. Only non-empty restriction bundles are
323     * stored.
324     */
325    @GuardedBy("mRestrictionsLock")
326    private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
327
328    /**
329     * Id of the user that set global restrictions.
330     */
331    @GuardedBy("mRestrictionsLock")
332    private int mDeviceOwnerUserId = UserHandle.USER_NULL;
333
334    /**
335     * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
336     * for each user. Only non-empty restriction bundles are stored.
337     */
338    @GuardedBy("mRestrictionsLock")
339    private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
340
341    @GuardedBy("mGuestRestrictions")
342    private final Bundle mGuestRestrictions = new Bundle();
343
344    /**
345     * Set of user IDs being actively removed. Removed IDs linger in this set
346     * for several seconds to work around a VFS caching issue.
347     * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
348     */
349    @GuardedBy("mUsersLock")
350    private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
351
352    /**
353     * Queue of recently removed userIds. Used for recycling of userIds
354     */
355    @GuardedBy("mUsersLock")
356    private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
357
358    @GuardedBy("mUsersLock")
359    private int[] mUserIds;
360    @GuardedBy("mPackagesLock")
361    private int mNextSerialNumber;
362    private int mUserVersion = 0;
363
364    private IAppOpsService mAppOpsService;
365
366    private final LocalService mLocalService;
367
368    @GuardedBy("mUsersLock")
369    private boolean mIsDeviceManaged;
370
371    @GuardedBy("mUsersLock")
372    private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
373
374    @GuardedBy("mUserRestrictionsListeners")
375    private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
376            new ArrayList<>();
377
378    private final LockPatternUtils mLockPatternUtils;
379
380    private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
381            "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
382
383    private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
384        @Override
385        public void onReceive(Context context, Intent intent) {
386            if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
387                return;
388            }
389            final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
390            final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
391            // Call setQuietModeEnabled on bg thread to avoid ANR
392            BackgroundThread.getHandler()
393                    .post(() -> setQuietModeEnabled(userHandle, false, target));
394        }
395    };
396
397    /**
398     * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
399     *
400     * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
401     */
402    private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
403        private final IntentSender mTarget;
404
405        public DisableQuietModeUserUnlockedCallback(IntentSender target) {
406            Preconditions.checkNotNull(target);
407            mTarget = target;
408        }
409
410        @Override
411        public void onStarted(int id, Bundle extras) {}
412
413        @Override
414        public void onProgress(int id, int progress, Bundle extras) {}
415
416        @Override
417        public void onFinished(int id, Bundle extras) {
418            try {
419                mContext.startIntentSender(mTarget, null, 0, 0, 0);
420            } catch (IntentSender.SendIntentException e) {
421                Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
422            }
423        }
424    }
425
426    /**
427     * Whether all users should be created ephemeral.
428     */
429    @GuardedBy("mUsersLock")
430    private boolean mForceEphemeralUsers;
431
432    @GuardedBy("mUserStates")
433    private final SparseIntArray mUserStates = new SparseIntArray();
434
435    private static UserManagerService sInstance;
436
437    public static UserManagerService getInstance() {
438        synchronized (UserManagerService.class) {
439            return sInstance;
440        }
441    }
442
443    public static class LifeCycle extends SystemService {
444
445        private UserManagerService mUms;
446
447        /**
448         * @param context
449         */
450        public LifeCycle(Context context) {
451            super(context);
452        }
453
454        @Override
455        public void onStart() {
456            mUms = UserManagerService.getInstance();
457            publishBinderService(Context.USER_SERVICE, mUms);
458        }
459
460        @Override
461        public void onBootPhase(int phase) {
462            if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
463                mUms.cleanupPartialUsers();
464            }
465        }
466
467        @Override
468        public void onStartUser(int userHandle) {
469            synchronized (mUms.mUsersLock) {
470                final UserData user = mUms.getUserDataLU(userHandle);
471                if (user != null) {
472                    user.startRealtime = SystemClock.elapsedRealtime();
473                }
474            }
475        }
476
477        @Override
478        public void onUnlockUser(int userHandle) {
479            synchronized (mUms.mUsersLock) {
480                final UserData user = mUms.getUserDataLU(userHandle);
481                if (user != null) {
482                    user.unlockRealtime = SystemClock.elapsedRealtime();
483                }
484            }
485        }
486
487        @Override
488        public void onStopUser(int userHandle) {
489            synchronized (mUms.mUsersLock) {
490                final UserData user = mUms.getUserDataLU(userHandle);
491                if (user != null) {
492                    user.startRealtime = 0;
493                    user.unlockRealtime = 0;
494                }
495            }
496        }
497    }
498
499    // TODO b/28848102 Add support for test dependencies injection
500    @VisibleForTesting
501    UserManagerService(Context context) {
502        this(context, null, null, new Object(), context.getCacheDir());
503    }
504
505    /**
506     * Called by package manager to create the service.  This is closely
507     * associated with the package manager, and the given lock is the
508     * package manager's own lock.
509     */
510    UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
511            Object packagesLock) {
512        this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
513    }
514
515    private UserManagerService(Context context, PackageManagerService pm,
516            UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
517        mContext = context;
518        mPm = pm;
519        mPackagesLock = packagesLock;
520        mHandler = new MainHandler();
521        mUserDataPreparer = userDataPreparer;
522        synchronized (mPackagesLock) {
523            mUsersDir = new File(dataDir, USER_INFO_DIR);
524            mUsersDir.mkdirs();
525            // Make zeroth user directory, for services to migrate their files to that location
526            File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
527            userZeroDir.mkdirs();
528            FileUtils.setPermissions(mUsersDir.toString(),
529                    FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
530                    -1, -1);
531            mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
532            initDefaultGuestRestrictions();
533            readUserListLP();
534            sInstance = this;
535        }
536        mLocalService = new LocalService();
537        LocalServices.addService(UserManagerInternal.class, mLocalService);
538        mLockPatternUtils = new LockPatternUtils(mContext);
539        mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
540    }
541
542    void systemReady() {
543        mAppOpsService = IAppOpsService.Stub.asInterface(
544                ServiceManager.getService(Context.APP_OPS_SERVICE));
545
546        synchronized (mRestrictionsLock) {
547            applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
548        }
549
550        UserInfo currentGuestUser = findCurrentGuestUser();
551        if (currentGuestUser != null && !hasUserRestriction(
552                UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
553            // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
554            // to it, in case this guest was created in a previous version where this
555            // user restriction was not a default guest restriction.
556            setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
557        }
558
559        mContext.registerReceiver(mDisableQuietModeCallback,
560                new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
561                null, mHandler);
562    }
563
564    void cleanupPartialUsers() {
565        // Prune out any partially created, partially removed and ephemeral users.
566        ArrayList<UserInfo> partials = new ArrayList<>();
567        synchronized (mUsersLock) {
568            final int userSize = mUsers.size();
569            for (int i = 0; i < userSize; i++) {
570                UserInfo ui = mUsers.valueAt(i).info;
571                if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
572                    partials.add(ui);
573                    addRemovingUserIdLocked(ui.id);
574                    ui.partial = true;
575                }
576            }
577        }
578        final int partialsSize = partials.size();
579        for (int i = 0; i < partialsSize; i++) {
580            UserInfo ui = partials.get(i);
581            Slog.w(LOG_TAG, "Removing partially created user " + ui.id
582                    + " (name=" + ui.name + ")");
583            removeUserState(ui.id);
584        }
585    }
586
587    @Override
588    public String getUserAccount(int userId) {
589        checkManageUserAndAcrossUsersFullPermission("get user account");
590        synchronized (mUsersLock) {
591            return mUsers.get(userId).account;
592        }
593    }
594
595    @Override
596    public void setUserAccount(int userId, String accountName) {
597        checkManageUserAndAcrossUsersFullPermission("set user account");
598        UserData userToUpdate = null;
599        synchronized (mPackagesLock) {
600            synchronized (mUsersLock) {
601                final UserData userData = mUsers.get(userId);
602                if (userData == null) {
603                    Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
604                    return;
605                }
606                String currentAccount = userData.account;
607                if (!Objects.equals(currentAccount, accountName)) {
608                    userData.account = accountName;
609                    userToUpdate = userData;
610                }
611            }
612
613            if (userToUpdate != null) {
614                writeUserLP(userToUpdate);
615            }
616        }
617    }
618
619    @Override
620    public UserInfo getPrimaryUser() {
621        checkManageUsersPermission("query users");
622        synchronized (mUsersLock) {
623            final int userSize = mUsers.size();
624            for (int i = 0; i < userSize; i++) {
625                UserInfo ui = mUsers.valueAt(i).info;
626                if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
627                    return ui;
628                }
629            }
630        }
631        return null;
632    }
633
634    @Override
635    public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
636        checkManageOrCreateUsersPermission("query users");
637        synchronized (mUsersLock) {
638            ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
639            final int userSize = mUsers.size();
640            for (int i = 0; i < userSize; i++) {
641                UserInfo ui = mUsers.valueAt(i).info;
642                if (ui.partial) {
643                    continue;
644                }
645                if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
646                    users.add(userWithName(ui));
647                }
648            }
649            return users;
650        }
651    }
652
653    @Override
654    public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
655        boolean returnFullInfo = true;
656        if (userId != UserHandle.getCallingUserId()) {
657            checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
658        } else {
659            returnFullInfo = hasManageUsersPermission();
660        }
661        final long ident = Binder.clearCallingIdentity();
662        try {
663            synchronized (mUsersLock) {
664                return getProfilesLU(userId, enabledOnly, returnFullInfo);
665            }
666        } finally {
667            Binder.restoreCallingIdentity(ident);
668        }
669    }
670
671    @Override
672    public int[] getProfileIds(int userId, boolean enabledOnly) {
673        if (userId != UserHandle.getCallingUserId()) {
674            checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
675        }
676        final long ident = Binder.clearCallingIdentity();
677        try {
678            synchronized (mUsersLock) {
679                return getProfileIdsLU(userId, enabledOnly).toArray();
680            }
681        } finally {
682            Binder.restoreCallingIdentity(ident);
683        }
684    }
685
686    /** Assume permissions already checked and caller's identity cleared */
687    private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
688        IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
689        ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
690        for (int i = 0; i < profileIds.size(); i++) {
691            int profileId = profileIds.get(i);
692            UserInfo userInfo = mUsers.get(profileId).info;
693            // If full info is not required - clear PII data to prevent 3P apps from reading it
694            if (!fullInfo) {
695                userInfo = new UserInfo(userInfo);
696                userInfo.name = null;
697                userInfo.iconPath = null;
698            } else {
699                userInfo = userWithName(userInfo);
700            }
701            users.add(userInfo);
702        }
703        return users;
704    }
705
706    /**
707     *  Assume permissions already checked and caller's identity cleared
708     */
709    private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
710        UserInfo user = getUserInfoLU(userId);
711        IntArray result = new IntArray(mUsers.size());
712        if (user == null) {
713            // Probably a dying user
714            return result;
715        }
716        final int userSize = mUsers.size();
717        for (int i = 0; i < userSize; i++) {
718            UserInfo profile = mUsers.valueAt(i).info;
719            if (!isProfileOf(user, profile)) {
720                continue;
721            }
722            if (enabledOnly && !profile.isEnabled()) {
723                continue;
724            }
725            if (mRemovingUserIds.get(profile.id)) {
726                continue;
727            }
728            if (profile.partial) {
729                continue;
730            }
731            result.add(profile.id);
732        }
733        return result;
734    }
735
736    @Override
737    public int getCredentialOwnerProfile(int userHandle) {
738        checkManageUsersPermission("get the credential owner");
739        if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
740            synchronized (mUsersLock) {
741                UserInfo profileParent = getProfileParentLU(userHandle);
742                if (profileParent != null) {
743                    return profileParent.id;
744                }
745            }
746        }
747
748        return userHandle;
749    }
750
751    @Override
752    public boolean isSameProfileGroup(int userId, int otherUserId) {
753        if (userId == otherUserId) return true;
754        checkManageUsersPermission("check if in the same profile group");
755        return isSameProfileGroupNoChecks(userId, otherUserId);
756    }
757
758    private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
759        synchronized (mUsersLock) {
760            UserInfo userInfo = getUserInfoLU(userId);
761            if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
762                return false;
763            }
764            UserInfo otherUserInfo = getUserInfoLU(otherUserId);
765            if (otherUserInfo == null
766                    || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
767                return false;
768            }
769            return userInfo.profileGroupId == otherUserInfo.profileGroupId;
770        }
771    }
772
773    @Override
774    public UserInfo getProfileParent(int userHandle) {
775        checkManageUsersPermission("get the profile parent");
776        synchronized (mUsersLock) {
777            return getProfileParentLU(userHandle);
778        }
779    }
780
781    @Override
782    public int getProfileParentId(int userHandle) {
783        checkManageUsersPermission("get the profile parent");
784        synchronized (mUsersLock) {
785            UserInfo profileParent = getProfileParentLU(userHandle);
786            if (profileParent == null) {
787                return userHandle;
788            }
789
790            return profileParent.id;
791        }
792    }
793
794    private UserInfo getProfileParentLU(int userHandle) {
795        UserInfo profile = getUserInfoLU(userHandle);
796        if (profile == null) {
797            return null;
798        }
799        int parentUserId = profile.profileGroupId;
800        if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
801            return null;
802        } else {
803            return getUserInfoLU(parentUserId);
804        }
805    }
806
807    private static boolean isProfileOf(UserInfo user, UserInfo profile) {
808        return user.id == profile.id ||
809                (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
810                && user.profileGroupId == profile.profileGroupId);
811    }
812
813    private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
814            UserHandle parentHandle, boolean inQuietMode) {
815        Intent intent = new Intent();
816        if (inQuietMode) {
817            intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
818        } else {
819            intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
820        }
821        intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
822        intent.putExtra(Intent.EXTRA_USER, profileHandle);
823        intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
824        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
825        mContext.sendBroadcastAsUser(intent, parentHandle);
826    }
827
828    @Override
829    public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
830            int userHandle, @Nullable IntentSender target) {
831        Preconditions.checkNotNull(callingPackage);
832
833        if (enableQuietMode && target != null) {
834            throw new IllegalArgumentException(
835                    "target should only be specified when we are disabling quiet mode.");
836        }
837
838        ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
839        final long identity = Binder.clearCallingIdentity();
840        try {
841            if (enableQuietMode) {
842                setQuietModeEnabled(userHandle, true /* enableQuietMode */, target);
843                return true;
844            } else {
845                boolean needToShowConfirmCredential =
846                        mLockPatternUtils.isSecure(userHandle)
847                                && !StorageManager.isUserKeyUnlocked(userHandle);
848                if (needToShowConfirmCredential) {
849                    showConfirmCredentialToDisableQuietMode(userHandle, target);
850                    return false;
851                } else {
852                    setQuietModeEnabled(userHandle, false /* enableQuietMode */, target);
853                    return true;
854                }
855            }
856        } finally {
857            Binder.restoreCallingIdentity(identity);
858        }
859    }
860
861    /**
862     * The caller can modify quiet mode if it meets one of these conditions:
863     * <ul>
864     *     <li>Has system UID or root UID</li>
865     *     <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
866     *     <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
867     * </ul>
868     * <p>
869     * If caller wants to start an intent after disabling the quiet mode, it must has
870     * {@link Manifest.permission#MANAGE_USERS}.
871     */
872    private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
873            boolean startIntent) {
874        if (hasManageUsersPermission()) {
875            return;
876        }
877        if (startIntent) {
878            throw new SecurityException("MANAGE_USERS permission is required to start intent "
879                    + "after disabling quiet mode.");
880        }
881        final boolean hasModifyQuietModePermission = ActivityManager.checkComponentPermission(
882                Manifest.permission.MODIFY_QUIET_MODE,
883                callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
884        if (hasModifyQuietModePermission) {
885            return;
886        }
887
888        verifyCallingPackage(callingPackage, callingUid);
889        final ShortcutServiceInternal shortcutInternal =
890                LocalServices.getService(ShortcutServiceInternal.class);
891        if (shortcutInternal != null) {
892            boolean isForegroundLauncher =
893                    shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
894            if (isForegroundLauncher) {
895                return;
896            }
897        }
898        throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
899                + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
900    }
901
902    private void setQuietModeEnabled(
903            int userHandle, boolean enableQuietMode, IntentSender target) {
904        final UserInfo profile, parent;
905        final UserData profileUserData;
906        synchronized (mUsersLock) {
907            profile = getUserInfoLU(userHandle);
908            parent = getProfileParentLU(userHandle);
909
910            if (profile == null || !profile.isManagedProfile()) {
911                throw new IllegalArgumentException("User " + userHandle + " is not a profile");
912            }
913            if (profile.isQuietModeEnabled() == enableQuietMode) {
914                Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
915                return;
916            }
917            profile.flags ^= UserInfo.FLAG_QUIET_MODE;
918            profileUserData = getUserDataLU(profile.id);
919        }
920        synchronized (mPackagesLock) {
921            writeUserLP(profileUserData);
922        }
923        try {
924            if (enableQuietMode) {
925                ActivityManager.getService().stopUser(userHandle, /* force */true, null);
926                LocalServices.getService(ActivityManagerInternal.class)
927                        .killForegroundAppsForUser(userHandle);
928            } else {
929                IProgressListener callback = target != null
930                        ? new DisableQuietModeUserUnlockedCallback(target)
931                        : null;
932                ActivityManager.getService().startUserInBackgroundWithListener(
933                        userHandle, callback);
934            }
935        } catch (RemoteException e) {
936            // Should not happen, same process.
937            e.rethrowAsRuntimeException();
938        }
939        broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
940                enableQuietMode);
941    }
942
943    @Override
944    public boolean isQuietModeEnabled(int userHandle) {
945        synchronized (mPackagesLock) {
946            UserInfo info;
947            synchronized (mUsersLock) {
948                info = getUserInfoLU(userHandle);
949            }
950            if (info == null || !info.isManagedProfile()) {
951                return false;
952            }
953            return info.isQuietModeEnabled();
954        }
955    }
956
957    /**
958     * Show confirm credential screen to unlock user in order to turn off quiet mode.
959     */
960    private void showConfirmCredentialToDisableQuietMode(
961            @UserIdInt int userHandle, @Nullable IntentSender target) {
962        // otherwise, we show a profile challenge to trigger decryption of the user
963        final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
964                Context.KEYGUARD_SERVICE);
965        // We should use userHandle not credentialOwnerUserId here, as even if it is unified
966        // lock, confirm screenlock page will know and show personal challenge, and unlock
967        // work profile when personal challenge is correct
968        final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
969                userHandle);
970        if (unlockIntent == null) {
971            return;
972        }
973        final Intent callBackIntent = new Intent(
974                ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
975        if (target != null) {
976            callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
977        }
978        callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
979        callBackIntent.setPackage(mContext.getPackageName());
980        callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
981        final PendingIntent pendingIntent = PendingIntent.getBroadcast(
982                mContext,
983                0,
984                callBackIntent,
985                PendingIntent.FLAG_CANCEL_CURRENT |
986                        PendingIntent.FLAG_ONE_SHOT |
987                        PendingIntent.FLAG_IMMUTABLE);
988        // After unlocking the challenge, it will disable quiet mode and run the original
989        // intentSender
990        unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
991        unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
992        mContext.startActivity(unlockIntent);
993    }
994
995    @Override
996    public void setUserEnabled(int userId) {
997        checkManageUsersPermission("enable user");
998        synchronized (mPackagesLock) {
999            UserInfo info;
1000            synchronized (mUsersLock) {
1001                info = getUserInfoLU(userId);
1002            }
1003            if (info != null && !info.isEnabled()) {
1004                info.flags ^= UserInfo.FLAG_DISABLED;
1005                writeUserLP(getUserDataLU(info.id));
1006            }
1007        }
1008    }
1009
1010    /**
1011     * Evicts a user's CE key by stopping and restarting the user.
1012     *
1013     * The key is evicted automatically by the user controller when the user has stopped.
1014     */
1015    @Override
1016    public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1017        checkManageUsersPermission("evict CE key");
1018        final IActivityManager am = ActivityManagerNative.getDefault();
1019        final long identity = Binder.clearCallingIdentity();
1020        try {
1021            am.restartUserInBackground(userId);
1022        } catch (RemoteException re) {
1023            throw re.rethrowAsRuntimeException();
1024        } finally {
1025            Binder.restoreCallingIdentity(identity);
1026        }
1027    }
1028
1029    @Override
1030    public UserInfo getUserInfo(int userId) {
1031        checkManageOrCreateUsersPermission("query user");
1032        synchronized (mUsersLock) {
1033            return userWithName(getUserInfoLU(userId));
1034        }
1035    }
1036
1037    /**
1038     * Returns a UserInfo object with the name filled in, for Owner, or the original
1039     * if the name is already set.
1040     */
1041    private UserInfo userWithName(UserInfo orig) {
1042        if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1043            UserInfo withName = new UserInfo(orig);
1044            withName.name = getOwnerName();
1045            return withName;
1046        } else {
1047            return orig;
1048        }
1049    }
1050
1051    @Override
1052    public int getManagedProfileBadge(@UserIdInt int userId) {
1053        int callingUserId = UserHandle.getCallingUserId();
1054        if (callingUserId != userId && !hasManageUsersPermission()) {
1055            if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
1056                throw new SecurityException(
1057                        "You need MANAGE_USERS permission to: check if specified user a " +
1058                        "managed profile outside your profile group");
1059            }
1060        }
1061        synchronized (mUsersLock) {
1062            UserInfo userInfo = getUserInfoLU(userId);
1063            return userInfo != null ? userInfo.profileBadge : 0;
1064        }
1065    }
1066
1067    @Override
1068    public boolean isManagedProfile(int userId) {
1069        int callingUserId = UserHandle.getCallingUserId();
1070        if (callingUserId != userId && !hasManageUsersPermission()) {
1071            if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
1072                throw new SecurityException(
1073                        "You need MANAGE_USERS permission to: check if specified user a " +
1074                        "managed profile outside your profile group");
1075            }
1076        }
1077        synchronized (mUsersLock) {
1078            UserInfo userInfo = getUserInfoLU(userId);
1079            return userInfo != null && userInfo.isManagedProfile();
1080        }
1081    }
1082
1083    @Override
1084    public boolean isUserUnlockingOrUnlocked(int userId) {
1085        checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
1086        return mLocalService.isUserUnlockingOrUnlocked(userId);
1087    }
1088
1089    @Override
1090    public boolean isUserUnlocked(int userId) {
1091        checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
1092        return mLocalService.isUserUnlocked(userId);
1093    }
1094
1095    @Override
1096    public boolean isUserRunning(int userId) {
1097        checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1098        return mLocalService.isUserRunning(userId);
1099    }
1100
1101    @Override
1102    public long getUserStartRealtime() {
1103        final int userId = UserHandle.getUserId(Binder.getCallingUid());
1104        synchronized (mUsersLock) {
1105            final UserData user = getUserDataLU(userId);
1106            if (user != null) {
1107                return user.startRealtime;
1108            }
1109            return 0;
1110        }
1111    }
1112
1113    @Override
1114    public long getUserUnlockRealtime() {
1115        synchronized (mUsersLock) {
1116            final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1117            if (user != null) {
1118                return user.unlockRealtime;
1119            }
1120            return 0;
1121        }
1122    }
1123
1124    private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1125        int callingUserId = UserHandle.getCallingUserId();
1126        if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1127                hasManageUsersPermission()) {
1128            return;
1129        }
1130        if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
1131                Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
1132            throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1133                    + "to: check " + name);
1134        }
1135    }
1136
1137    @Override
1138    public boolean isDemoUser(int userId) {
1139        int callingUserId = UserHandle.getCallingUserId();
1140        if (callingUserId != userId && !hasManageUsersPermission()) {
1141            throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1142                    + " is a demo user");
1143        }
1144        synchronized (mUsersLock) {
1145            UserInfo userInfo = getUserInfoLU(userId);
1146            return userInfo != null && userInfo.isDemo();
1147        }
1148    }
1149
1150    @Override
1151    public boolean isRestricted() {
1152        synchronized (mUsersLock) {
1153            return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
1154        }
1155    }
1156
1157    @Override
1158    public boolean canHaveRestrictedProfile(int userId) {
1159        checkManageUsersPermission("canHaveRestrictedProfile");
1160        synchronized (mUsersLock) {
1161            final UserInfo userInfo = getUserInfoLU(userId);
1162            if (userInfo == null || !userInfo.canHaveProfile()) {
1163                return false;
1164            }
1165            if (!userInfo.isAdmin()) {
1166                return false;
1167            }
1168            // restricted profile can be created if there is no DO set and the admin user has no PO;
1169            return !mIsDeviceManaged && !mIsUserManaged.get(userId);
1170        }
1171    }
1172
1173    @Override
1174    public boolean hasRestrictedProfiles() {
1175        checkManageUsersPermission("hasRestrictedProfiles");
1176        final int callingUserId = UserHandle.getCallingUserId();
1177        synchronized (mUsersLock) {
1178            final int userSize = mUsers.size();
1179            for (int i = 0; i < userSize; i++) {
1180                UserInfo profile = mUsers.valueAt(i).info;
1181                if (callingUserId != profile.id
1182                        && profile.restrictedProfileParentId == callingUserId) {
1183                    return true;
1184                }
1185            }
1186            return false;
1187        }
1188    }
1189
1190    /*
1191     * Should be locked on mUsers before calling this.
1192     */
1193    private UserInfo getUserInfoLU(int userId) {
1194        final UserData userData = mUsers.get(userId);
1195        // If it is partial and not in the process of being removed, return as unknown user.
1196        if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1197            Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1198            return null;
1199        }
1200        return userData != null ? userData.info : null;
1201    }
1202
1203    private UserData getUserDataLU(int userId) {
1204        final UserData userData = mUsers.get(userId);
1205        // If it is partial and not in the process of being removed, return as unknown user.
1206        if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1207            return null;
1208        }
1209        return userData;
1210    }
1211
1212    /**
1213     * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1214     * <p>No permissions checking or any addition checks are made</p>
1215     */
1216    private UserInfo getUserInfoNoChecks(int userId) {
1217        synchronized (mUsersLock) {
1218            final UserData userData = mUsers.get(userId);
1219            return userData != null ? userData.info : null;
1220        }
1221    }
1222
1223    /**
1224     * Obtains {@link #mUsersLock} and return UserData from mUsers.
1225     * <p>No permissions checking or any addition checks are made</p>
1226     */
1227    private UserData getUserDataNoChecks(int userId) {
1228        synchronized (mUsersLock) {
1229            return mUsers.get(userId);
1230        }
1231    }
1232
1233    /** Called by PackageManagerService */
1234    public boolean exists(int userId) {
1235        return mLocalService.exists(userId);
1236    }
1237
1238    @Override
1239    public void setUserName(int userId, String name) {
1240        checkManageUsersPermission("rename users");
1241        boolean changed = false;
1242        synchronized (mPackagesLock) {
1243            UserData userData = getUserDataNoChecks(userId);
1244            if (userData == null || userData.info.partial) {
1245                Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1246                return;
1247            }
1248            if (name != null && !name.equals(userData.info.name)) {
1249                userData.info.name = name;
1250                writeUserLP(userData);
1251                changed = true;
1252            }
1253        }
1254        if (changed) {
1255            sendUserInfoChangedBroadcast(userId);
1256        }
1257    }
1258
1259    @Override
1260    public void setUserIcon(int userId, Bitmap bitmap) {
1261        checkManageUsersPermission("update users");
1262        if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1263            Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1264            return;
1265        }
1266        mLocalService.setUserIcon(userId, bitmap);
1267    }
1268
1269
1270
1271    private void sendUserInfoChangedBroadcast(int userId) {
1272        Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1273        changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1274        changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1275        mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
1276    }
1277
1278    @Override
1279    public ParcelFileDescriptor getUserIcon(int targetUserId) {
1280        String iconPath;
1281        synchronized (mPackagesLock) {
1282            UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1283            if (targetUserInfo == null || targetUserInfo.partial) {
1284                Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
1285                return null;
1286            }
1287
1288            final int callingUserId = UserHandle.getCallingUserId();
1289            final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1290            final int targetGroupId = targetUserInfo.profileGroupId;
1291            final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1292                    && callingGroupId == targetGroupId);
1293            if ((callingUserId != targetUserId) && !sameGroup) {
1294                checkManageUsersPermission("get the icon of a user who is not related");
1295            }
1296
1297            if (targetUserInfo.iconPath == null) {
1298                return null;
1299            }
1300            iconPath = targetUserInfo.iconPath;
1301        }
1302
1303        try {
1304            return ParcelFileDescriptor.open(
1305                    new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1306        } catch (FileNotFoundException e) {
1307            Log.e(LOG_TAG, "Couldn't find icon file", e);
1308        }
1309        return null;
1310    }
1311
1312    public void makeInitialized(int userId) {
1313        checkManageUsersPermission("makeInitialized");
1314        boolean scheduleWriteUser = false;
1315        UserData userData;
1316        synchronized (mUsersLock) {
1317            userData = mUsers.get(userId);
1318            if (userData == null || userData.info.partial) {
1319                Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
1320                return;
1321            }
1322            if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1323                userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1324                scheduleWriteUser = true;
1325            }
1326        }
1327        if (scheduleWriteUser) {
1328            scheduleWriteUser(userData);
1329        }
1330    }
1331
1332    /**
1333     * If default guest restrictions haven't been initialized yet, add the basic
1334     * restrictions.
1335     */
1336    private void initDefaultGuestRestrictions() {
1337        synchronized (mGuestRestrictions) {
1338            if (mGuestRestrictions.isEmpty()) {
1339                mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
1340                mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
1341                mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1342                mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1343            }
1344        }
1345    }
1346
1347    @Override
1348    public Bundle getDefaultGuestRestrictions() {
1349        checkManageUsersPermission("getDefaultGuestRestrictions");
1350        synchronized (mGuestRestrictions) {
1351            return new Bundle(mGuestRestrictions);
1352        }
1353    }
1354
1355    @Override
1356    public void setDefaultGuestRestrictions(Bundle restrictions) {
1357        checkManageUsersPermission("setDefaultGuestRestrictions");
1358        synchronized (mGuestRestrictions) {
1359            mGuestRestrictions.clear();
1360            mGuestRestrictions.putAll(restrictions);
1361        }
1362        synchronized (mPackagesLock) {
1363            writeUserListLP();
1364        }
1365    }
1366
1367    /**
1368     * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
1369     */
1370    private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1371            boolean isDeviceOwner, int cameraRestrictionScope) {
1372        final Bundle global = new Bundle();
1373        final Bundle local = new Bundle();
1374
1375        // Sort restrictions into local and global ensuring they don't overlap.
1376        UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1377                cameraRestrictionScope, global, local);
1378
1379        boolean globalChanged, localChanged;
1380        synchronized (mRestrictionsLock) {
1381            // Update global and local restrictions if they were changed.
1382            globalChanged = updateRestrictionsIfNeededLR(
1383                    userId, global, mDevicePolicyGlobalUserRestrictions);
1384            localChanged = updateRestrictionsIfNeededLR(
1385                    userId, local, mDevicePolicyLocalUserRestrictions);
1386
1387            if (isDeviceOwner) {
1388                // Remember the global restriction owner userId to be able to make a distinction
1389                // in getUserRestrictionSource on who set local policies.
1390                mDeviceOwnerUserId = userId;
1391            } else {
1392                if (mDeviceOwnerUserId == userId) {
1393                    // When profile owner sets restrictions it passes null global bundle and we
1394                    // reset global restriction owner userId.
1395                    // This means this user used to have DO, but now the DO is gone and the user
1396                    // instead has PO.
1397                    mDeviceOwnerUserId = UserHandle.USER_NULL;
1398                }
1399            }
1400        }
1401        if (DBG) {
1402            Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1403                            + " global=" + global + (globalChanged ? " (changed)" : "")
1404                            + " local=" + local + (localChanged ? " (changed)" : "")
1405            );
1406        }
1407        // Don't call them within the mRestrictionsLock.
1408        synchronized (mPackagesLock) {
1409            if (localChanged || globalChanged) {
1410                writeUserLP(getUserDataNoChecks(userId));
1411            }
1412        }
1413
1414        synchronized (mRestrictionsLock) {
1415            if (globalChanged) {
1416                applyUserRestrictionsForAllUsersLR();
1417            } else if (localChanged) {
1418                applyUserRestrictionsLR(userId);
1419            }
1420        }
1421    }
1422
1423    /**
1424     * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1425     * empty, record is removed from the array.
1426     * @return whether restrictions bundle is different from the old one.
1427     */
1428    private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1429            SparseArray<Bundle> restrictionsArray) {
1430        final boolean changed =
1431                !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1432        if (changed) {
1433            if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1434                restrictionsArray.put(userId, restrictions);
1435            } else {
1436                restrictionsArray.delete(userId);
1437            }
1438        }
1439        return changed;
1440    }
1441
1442    @GuardedBy("mRestrictionsLock")
1443    private Bundle computeEffectiveUserRestrictionsLR(int userId) {
1444        final Bundle baseRestrictions =
1445                UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1446        final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
1447        final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
1448
1449        if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1450            // Common case first.
1451            return baseRestrictions;
1452        }
1453        final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1454        UserRestrictionsUtils.merge(effective, global);
1455        UserRestrictionsUtils.merge(effective, local);
1456
1457        return effective;
1458    }
1459
1460    @GuardedBy("mRestrictionsLock")
1461    private void invalidateEffectiveUserRestrictionsLR(int userId) {
1462        if (DBG) {
1463            Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1464        }
1465        mCachedEffectiveUserRestrictions.remove(userId);
1466    }
1467
1468    private Bundle getEffectiveUserRestrictions(int userId) {
1469        synchronized (mRestrictionsLock) {
1470            Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1471            if (restrictions == null) {
1472                restrictions = computeEffectiveUserRestrictionsLR(userId);
1473                mCachedEffectiveUserRestrictions.put(userId, restrictions);
1474            }
1475            return restrictions;
1476        }
1477    }
1478
1479    /** @return a specific user restriction that's in effect currently. */
1480    @Override
1481    public boolean hasUserRestriction(String restrictionKey, int userId) {
1482        if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1483            return false;
1484        }
1485        Bundle restrictions = getEffectiveUserRestrictions(userId);
1486        return restrictions != null && restrictions.getBoolean(restrictionKey);
1487    }
1488
1489    /** @return if any user has the given restriction. */
1490    @Override
1491    public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1492        if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1493            return false;
1494        }
1495        final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1496        for (int i = 0; i < users.size(); i++) {
1497            final int userId = users.get(i).id;
1498            Bundle restrictions = getEffectiveUserRestrictions(userId);
1499            if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1500                return true;
1501            }
1502        }
1503        return false;
1504    }
1505
1506    /**
1507     * @hide
1508     *
1509     * Returns who set a user restriction on a user.
1510     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1511     * @param restrictionKey the string key representing the restriction
1512     * @param userId the id of the user for whom to retrieve the restrictions.
1513     * @return The source of user restriction. Any combination of
1514     *         {@link UserManager#RESTRICTION_NOT_SET},
1515     *         {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1516     *         {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1517     *         and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1518     */
1519    @Override
1520    public int getUserRestrictionSource(String restrictionKey, int userId) {
1521        List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey,  userId);
1522        // Get "bitwise or" of restriction sources for all enforcing users.
1523        int result = UserManager.RESTRICTION_NOT_SET;
1524        for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1525            result |= enforcingUsers.get(i).getUserRestrictionSource();
1526        }
1527        return result;
1528    }
1529
1530    @Override
1531    public List<EnforcingUser> getUserRestrictionSources(
1532            String restrictionKey, @UserIdInt int userId) {
1533        checkManageUsersPermission("getUserRestrictionSource");
1534
1535        // Shortcut for the most common case
1536        if (!hasUserRestriction(restrictionKey, userId)) {
1537            return Collections.emptyList();
1538        }
1539
1540        final List<EnforcingUser> result = new ArrayList<>();
1541
1542        // Check if it is base restriction.
1543        if (hasBaseUserRestriction(restrictionKey, userId)) {
1544            result.add(new EnforcingUser(
1545                    UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
1546        }
1547
1548        synchronized (mRestrictionsLock) {
1549            // Check if it is set by profile owner.
1550            Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1551            if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1552                result.add(getEnforcingUserLocked(userId));
1553            }
1554
1555            // Iterate over all users who enforce global restrictions.
1556            for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1557                Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1558                int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1559                if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1560                    result.add(getEnforcingUserLocked(profileUserId));
1561                }
1562            }
1563        }
1564        return result;
1565    }
1566
1567    @GuardedBy("mRestrictionsLock")
1568    private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1569        int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1570                : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1571        return new EnforcingUser(userId, source);
1572    }
1573
1574    /**
1575     * @return UserRestrictions that are in effect currently.  This always returns a new
1576     * {@link Bundle}.
1577     */
1578    @Override
1579    public Bundle getUserRestrictions(int userId) {
1580        return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
1581    }
1582
1583    @Override
1584    public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1585        checkManageUsersPermission("hasBaseUserRestriction");
1586        if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1587            return false;
1588        }
1589        synchronized (mRestrictionsLock) {
1590            Bundle bundle = mBaseUserRestrictions.get(userId);
1591            return (bundle != null && bundle.getBoolean(restrictionKey, false));
1592        }
1593    }
1594
1595    @Override
1596    public void setUserRestriction(String key, boolean value, int userId) {
1597        checkManageUsersPermission("setUserRestriction");
1598        if (!UserRestrictionsUtils.isValidRestriction(key)) {
1599            return;
1600        }
1601        synchronized (mRestrictionsLock) {
1602            // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1603            // a copy.
1604            final Bundle newRestrictions = UserRestrictionsUtils.clone(
1605                    mBaseUserRestrictions.get(userId));
1606            newRestrictions.putBoolean(key, value);
1607
1608            updateUserRestrictionsInternalLR(newRestrictions, userId);
1609        }
1610    }
1611
1612    /**
1613     * Optionally updating user restrictions, calculate the effective user restrictions and also
1614     * propagate to other services and system settings.
1615     *
1616     * @param newBaseRestrictions User restrictions to set.
1617     *      If null, will not update user restrictions and only does the propagation.
1618     * @param userId target user ID.
1619     */
1620    @GuardedBy("mRestrictionsLock")
1621    private void updateUserRestrictionsInternalLR(
1622            @Nullable Bundle newBaseRestrictions, int userId) {
1623        final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1624                mAppliedUserRestrictions.get(userId));
1625
1626        // Update base restrictions.
1627        if (newBaseRestrictions != null) {
1628            // If newBaseRestrictions == the current one, it's probably a bug.
1629            final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1630
1631            Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
1632            Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1633                    != newBaseRestrictions);
1634
1635            if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
1636                scheduleWriteUser(getUserDataNoChecks(userId));
1637            }
1638        }
1639
1640        final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
1641
1642        mCachedEffectiveUserRestrictions.put(userId, effective);
1643
1644        // Apply the new restrictions.
1645        if (DBG) {
1646            debug("Applying user restrictions: userId=" + userId
1647                    + " new=" + effective + " prev=" + prevAppliedRestrictions);
1648        }
1649
1650        if (mAppOpsService != null) { // We skip it until system-ready.
1651            mHandler.post(new Runnable() {
1652                @Override
1653                public void run() {
1654                    try {
1655                        mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1656                    } catch (RemoteException e) {
1657                        Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1658                    }
1659                }
1660            });
1661        }
1662
1663        propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
1664
1665        mAppliedUserRestrictions.put(userId, new Bundle(effective));
1666    }
1667
1668    private void propagateUserRestrictionsLR(final int userId,
1669            Bundle newRestrictions, Bundle prevRestrictions) {
1670        // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1671        // actually, but we still need some kind of synchronization otherwise we might end up
1672        // calling listeners out-of-order, thus "LR".
1673
1674        if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1675            return;
1676        }
1677
1678        final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1679        final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1680
1681        mHandler.post(new Runnable() {
1682            @Override
1683            public void run() {
1684                UserRestrictionsUtils.applyUserRestrictions(
1685                        mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
1686
1687                final UserRestrictionsListener[] listeners;
1688                synchronized (mUserRestrictionsListeners) {
1689                    listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1690                    mUserRestrictionsListeners.toArray(listeners);
1691                }
1692                for (int i = 0; i < listeners.length; i++) {
1693                    listeners[i].onUserRestrictionsChanged(userId,
1694                            newRestrictionsFinal, prevRestrictionsFinal);
1695                }
1696
1697                final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1698                        .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1699                mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
1700            }
1701        });
1702    }
1703
1704    // Package private for the inner class.
1705    void applyUserRestrictionsLR(int userId) {
1706        updateUserRestrictionsInternalLR(null, userId);
1707    }
1708
1709    @GuardedBy("mRestrictionsLock")
1710    // Package private for the inner class.
1711    void applyUserRestrictionsForAllUsersLR() {
1712        if (DBG) {
1713            debug("applyUserRestrictionsForAllUsersLR");
1714        }
1715        // First, invalidate all cached values.
1716        mCachedEffectiveUserRestrictions.clear();
1717
1718        // We don't want to call into ActivityManagerService while taking a lock, so we'll call
1719        // it on a handler.
1720        final Runnable r = new Runnable() {
1721            @Override
1722            public void run() {
1723                // Then get the list of running users.
1724                final int[] runningUsers;
1725                try {
1726                    runningUsers = ActivityManager.getService().getRunningUserIds();
1727                } catch (RemoteException e) {
1728                    Log.w(LOG_TAG, "Unable to access ActivityManagerService");
1729                    return;
1730                }
1731                // Then re-calculate the effective restrictions and apply, only for running users.
1732                // It's okay if a new user has started after the getRunningUserIds() call,
1733                // because we'll do the same thing (re-calculate the restrictions and apply)
1734                // when we start a user.
1735                synchronized (mRestrictionsLock) {
1736                    for (int i = 0; i < runningUsers.length; i++) {
1737                        applyUserRestrictionsLR(runningUsers[i]);
1738                    }
1739                }
1740            }
1741        };
1742        mHandler.post(r);
1743    }
1744
1745    /**
1746     * Check if we've hit the limit of how many users can be created.
1747     */
1748    private boolean isUserLimitReached() {
1749        int count;
1750        synchronized (mUsersLock) {
1751            count = getAliveUsersExcludingGuestsCountLU();
1752        }
1753        return count >= UserManager.getMaxSupportedUsers();
1754    }
1755
1756    @Override
1757    public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
1758        checkManageUsersPermission("check if more managed profiles can be added.");
1759        if (ActivityManager.isLowRamDeviceStatic()) {
1760            return false;
1761        }
1762        if (!mContext.getPackageManager().hasSystemFeature(
1763                PackageManager.FEATURE_MANAGED_USERS)) {
1764            return false;
1765        }
1766        // Limit number of managed profiles that can be created
1767        final int managedProfilesCount = getProfiles(userId, false).size() - 1;
1768        final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1769        if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
1770            return false;
1771        }
1772        synchronized(mUsersLock) {
1773            UserInfo userInfo = getUserInfoLU(userId);
1774            if (userInfo == null || !userInfo.canHaveProfile()) {
1775                return false;
1776            }
1777            int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1778                    - profilesRemovedCount;
1779            // We allow creating a managed profile in the special case where there is only one user.
1780            return usersCountAfterRemoving  == 1
1781                    || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
1782        }
1783    }
1784
1785    private int getAliveUsersExcludingGuestsCountLU() {
1786        int aliveUserCount = 0;
1787        final int totalUserCount = mUsers.size();
1788        // Skip over users being removed
1789        for (int i = 0; i < totalUserCount; i++) {
1790            UserInfo user = mUsers.valueAt(i).info;
1791            if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
1792                aliveUserCount++;
1793            }
1794        }
1795        return aliveUserCount;
1796    }
1797
1798    /**
1799     * Enforces that only the system UID or root's UID or apps that have the
1800     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1801     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1802     * permissions can make certain calls to the UserManager.
1803     *
1804     * @param message used as message if SecurityException is thrown
1805     * @throws SecurityException if the caller does not have enough privilege.
1806     */
1807    private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1808        final int uid = Binder.getCallingUid();
1809        if (uid != Process.SYSTEM_UID && uid != 0
1810                && ActivityManager.checkComponentPermission(
1811                Manifest.permission.MANAGE_USERS,
1812                uid, -1, true) != PackageManager.PERMISSION_GRANTED
1813                && ActivityManager.checkComponentPermission(
1814                Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1815                uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1816            throw new SecurityException(
1817                    "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1818                            + message);
1819        }
1820    }
1821
1822    /**
1823     * Enforces that only the system UID or root's UID or apps that have the
1824     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
1825     * permission can make certain calls to the UserManager.
1826     *
1827     * @param message used as message if SecurityException is thrown
1828     * @throws SecurityException if the caller is not system or root
1829     * @see #hasManageUsersPermission()
1830     */
1831    private static final void checkManageUsersPermission(String message) {
1832        if (!hasManageUsersPermission()) {
1833            throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1834        }
1835    }
1836
1837    /**
1838     * Enforces that only the system UID or root's UID or apps that have the
1839     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1840     * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1841     * can make certain calls to the UserManager.
1842     *
1843     * @param message used as message if SecurityException is thrown
1844     * @throws SecurityException if the caller is not system or root
1845     * @see #hasManageOrCreateUsersPermission()
1846     */
1847    private static final void checkManageOrCreateUsersPermission(String message) {
1848        if (!hasManageOrCreateUsersPermission()) {
1849            throw new SecurityException(
1850                    "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1851        }
1852    }
1853
1854    /**
1855     * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1856     * to create user/profiles other than what is allowed for
1857     * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1858     * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1859     */
1860    private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1861        if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1862            if (!hasManageOrCreateUsersPermission()) {
1863                throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1864                        + "permission to create an user with flags: " + creationFlags);
1865            }
1866        } else if (!hasManageUsersPermission()) {
1867            throw new SecurityException("You need MANAGE_USERS permission to create an user "
1868                    + " with flags: " + creationFlags);
1869        }
1870    }
1871
1872    /**
1873     * @return whether the calling UID is system UID or root's UID or the calling app has the
1874     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1875     */
1876    private static final boolean hasManageUsersPermission() {
1877        final int callingUid = Binder.getCallingUid();
1878        return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1879                || callingUid == Process.ROOT_UID
1880                || ActivityManager.checkComponentPermission(
1881                        android.Manifest.permission.MANAGE_USERS,
1882                        callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1883    }
1884
1885    /**
1886     * @return whether the calling UID is system UID or root's UID or the calling app has the
1887     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1888     * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1889     */
1890    private static final boolean hasManageOrCreateUsersPermission() {
1891        final int callingUid = Binder.getCallingUid();
1892        return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1893                || callingUid == Process.ROOT_UID
1894                || ActivityManager.checkComponentPermission(
1895                        android.Manifest.permission.MANAGE_USERS,
1896                        callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1897                || ActivityManager.checkComponentPermission(
1898                        android.Manifest.permission.CREATE_USERS,
1899                        callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1900    }
1901
1902    /**
1903     * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1904     * UserManager.
1905     *
1906     * @param message used as message if SecurityException is thrown
1907     * @throws SecurityException if the caller is not system or root
1908     */
1909    private static void checkSystemOrRoot(String message) {
1910        final int uid = Binder.getCallingUid();
1911        if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1912            throw new SecurityException("Only system may: " + message);
1913        }
1914    }
1915
1916    private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
1917        try {
1918            File dir = new File(mUsersDir, Integer.toString(info.id));
1919            File file = new File(dir, USER_PHOTO_FILENAME);
1920            File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
1921            if (!dir.exists()) {
1922                dir.mkdir();
1923                FileUtils.setPermissions(
1924                        dir.getPath(),
1925                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1926                        -1, -1);
1927            }
1928            FileOutputStream os;
1929            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1930                    && tmp.renameTo(file) && SELinux.restorecon(file)) {
1931                info.iconPath = file.getAbsolutePath();
1932            }
1933            try {
1934                os.close();
1935            } catch (IOException ioe) {
1936                // What the ... !
1937            }
1938            tmp.delete();
1939        } catch (FileNotFoundException e) {
1940            Slog.w(LOG_TAG, "Error setting photo for user ", e);
1941        }
1942    }
1943
1944    /**
1945     * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1946     * cache it elsewhere.
1947     * @return the array of user ids.
1948     */
1949    public int[] getUserIds() {
1950        synchronized (mUsersLock) {
1951            return mUserIds;
1952        }
1953    }
1954
1955    private void readUserListLP() {
1956        if (!mUserListFile.exists()) {
1957            fallbackToSingleUserLP();
1958            return;
1959        }
1960        FileInputStream fis = null;
1961        AtomicFile userListFile = new AtomicFile(mUserListFile);
1962        try {
1963            fis = userListFile.openRead();
1964            XmlPullParser parser = Xml.newPullParser();
1965            parser.setInput(fis, StandardCharsets.UTF_8.name());
1966            int type;
1967            while ((type = parser.next()) != XmlPullParser.START_TAG
1968                    && type != XmlPullParser.END_DOCUMENT) {
1969                // Skip
1970            }
1971
1972            if (type != XmlPullParser.START_TAG) {
1973                Slog.e(LOG_TAG, "Unable to read user list");
1974                fallbackToSingleUserLP();
1975                return;
1976            }
1977
1978            mNextSerialNumber = -1;
1979            if (parser.getName().equals(TAG_USERS)) {
1980                String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1981                if (lastSerialNumber != null) {
1982                    mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1983                }
1984                String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1985                if (versionNumber != null) {
1986                    mUserVersion = Integer.parseInt(versionNumber);
1987                }
1988            }
1989
1990            // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1991            // currently), take care of it in case of upgrade.
1992            Bundle oldDevicePolicyGlobalUserRestrictions = null;
1993
1994            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1995                if (type == XmlPullParser.START_TAG) {
1996                    final String name = parser.getName();
1997                    if (name.equals(TAG_USER)) {
1998                        String id = parser.getAttributeValue(null, ATTR_ID);
1999
2000                        UserData userData = readUserLP(Integer.parseInt(id));
2001
2002                        if (userData != null) {
2003                            synchronized (mUsersLock) {
2004                                mUsers.put(userData.info.id, userData);
2005                                if (mNextSerialNumber < 0
2006                                        || mNextSerialNumber <= userData.info.id) {
2007                                    mNextSerialNumber = userData.info.id + 1;
2008                                }
2009                            }
2010                        }
2011                    } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
2012                        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2013                                && type != XmlPullParser.END_TAG) {
2014                            if (type == XmlPullParser.START_TAG) {
2015                                if (parser.getName().equals(TAG_RESTRICTIONS)) {
2016                                    synchronized (mGuestRestrictions) {
2017                                        UserRestrictionsUtils
2018                                                .readRestrictions(parser, mGuestRestrictions);
2019                                    }
2020                                }
2021                                break;
2022                            }
2023                        }
2024                    } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2025                            // Legacy name, should only be encountered when upgrading from pre-O.
2026                            || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
2027                        String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2028                        if (ownerUserId != null) {
2029                            mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
2030                        }
2031                    } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2032                        // Should only happen when upgrading from pre-O (version < 7).
2033                        oldDevicePolicyGlobalUserRestrictions =
2034                                UserRestrictionsUtils.readRestrictions(parser);
2035                    }
2036                }
2037            }
2038
2039            updateUserIds();
2040            upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
2041        } catch (IOException | XmlPullParserException e) {
2042            fallbackToSingleUserLP();
2043        } finally {
2044            IoUtils.closeQuietly(fis);
2045        }
2046    }
2047
2048    /**
2049     * Upgrade steps between versions, either for fixing bugs or changing the data format.
2050     * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
2051     */
2052    private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
2053        final int originalVersion = mUserVersion;
2054        int userVersion = mUserVersion;
2055        if (userVersion < 1) {
2056            // Assign a proper name for the owner, if not initialized correctly before
2057            UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2058            if ("Primary".equals(userData.info.name)) {
2059                userData.info.name =
2060                        mContext.getResources().getString(com.android.internal.R.string.owner_name);
2061                scheduleWriteUser(userData);
2062            }
2063            userVersion = 1;
2064        }
2065
2066        if (userVersion < 2) {
2067            // Owner should be marked as initialized
2068            UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2069            if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2070                userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2071                scheduleWriteUser(userData);
2072            }
2073            userVersion = 2;
2074        }
2075
2076
2077        if (userVersion < 4) {
2078            userVersion = 4;
2079        }
2080
2081        if (userVersion < 5) {
2082            initDefaultGuestRestrictions();
2083            userVersion = 5;
2084        }
2085
2086        if (userVersion < 6) {
2087            final boolean splitSystemUser = UserManager.isSplitSystemUser();
2088            synchronized (mUsersLock) {
2089                for (int i = 0; i < mUsers.size(); i++) {
2090                    UserData userData = mUsers.valueAt(i);
2091                    // In non-split mode, only user 0 can have restricted profiles
2092                    if (!splitSystemUser && userData.info.isRestricted()
2093                            && (userData.info.restrictedProfileParentId
2094                                    == UserInfo.NO_PROFILE_GROUP_ID)) {
2095                        userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2096                        scheduleWriteUser(userData);
2097                    }
2098                }
2099            }
2100            userVersion = 6;
2101        }
2102
2103        if (userVersion < 7) {
2104            // Previously only one user could enforce global restrictions, now it is per-user.
2105            synchronized (mRestrictionsLock) {
2106                if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2107                        && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2108                    mDevicePolicyGlobalUserRestrictions.put(
2109                            mDeviceOwnerUserId, oldGlobalUserRestrictions);
2110                }
2111                // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2112                // it from local to global bundle for all users who set it.
2113                UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2114                        mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2115                );
2116            }
2117            userVersion = 7;
2118        }
2119
2120        if (userVersion < USER_VERSION) {
2121            Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2122                    + USER_VERSION);
2123        } else {
2124            mUserVersion = userVersion;
2125
2126            if (originalVersion < mUserVersion) {
2127                writeUserListLP();
2128            }
2129        }
2130    }
2131
2132    private void fallbackToSingleUserLP() {
2133        int flags = UserInfo.FLAG_INITIALIZED;
2134        // In split system user mode, the admin and primary flags are assigned to the first human
2135        // user.
2136        if (!UserManager.isSplitSystemUser()) {
2137            flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2138        }
2139        // Create the system user
2140        UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
2141        UserData userData = putUserInfo(system);
2142        mNextSerialNumber = MIN_USER_ID;
2143        mUserVersion = USER_VERSION;
2144
2145        Bundle restrictions = new Bundle();
2146        try {
2147            final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2148                    com.android.internal.R.array.config_defaultFirstUserRestrictions);
2149            for (String userRestriction : defaultFirstUserRestrictions) {
2150                if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2151                    restrictions.putBoolean(userRestriction, true);
2152                }
2153            }
2154        } catch (Resources.NotFoundException e) {
2155            Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2156        }
2157
2158        if (!restrictions.isEmpty()) {
2159            synchronized (mRestrictionsLock) {
2160                mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2161            }
2162        }
2163
2164        updateUserIds();
2165        initDefaultGuestRestrictions();
2166
2167        writeUserLP(userData);
2168        writeUserListLP();
2169    }
2170
2171    private String getOwnerName() {
2172        return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2173    }
2174
2175    private void scheduleWriteUser(UserData UserData) {
2176        if (DBG) {
2177            debug("scheduleWriteUser");
2178        }
2179        // No need to wrap it within a lock -- worst case, we'll just post the same message
2180        // twice.
2181        if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2182            Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
2183            mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2184        }
2185    }
2186
2187    private void writeUserLP(UserData userData) {
2188        if (DBG) {
2189            debug("writeUserLP " + userData);
2190        }
2191        FileOutputStream fos = null;
2192        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
2193        try {
2194            fos = userFile.startWrite();
2195            final BufferedOutputStream bos = new BufferedOutputStream(fos);
2196            writeUserLP(userData, bos);
2197            userFile.finishWrite(fos);
2198        } catch (Exception ioe) {
2199            Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
2200            userFile.failWrite(fos);
2201        }
2202    }
2203
2204    /*
2205     * Writes the user file in this format:
2206     *
2207     * <user flags="20039023" id="0">
2208     *   <name>Primary</name>
2209     * </user>
2210     */
2211    @VisibleForTesting
2212    void writeUserLP(UserData userData, OutputStream os)
2213            throws IOException, XmlPullParserException {
2214        // XmlSerializer serializer = XmlUtils.serializerInstance();
2215        final XmlSerializer serializer = new FastXmlSerializer();
2216        serializer.setOutput(os, StandardCharsets.UTF_8.name());
2217        serializer.startDocument(null, true);
2218        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2219
2220        final UserInfo userInfo = userData.info;
2221        serializer.startTag(null, TAG_USER);
2222        serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2223        serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2224        serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2225        serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2226        serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2227                Long.toString(userInfo.lastLoggedInTime));
2228        if (userInfo.lastLoggedInFingerprint != null) {
2229            serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2230                    userInfo.lastLoggedInFingerprint);
2231        }
2232        if (userInfo.iconPath != null) {
2233            serializer.attribute(null,  ATTR_ICON_PATH, userInfo.iconPath);
2234        }
2235        if (userInfo.partial) {
2236            serializer.attribute(null, ATTR_PARTIAL, "true");
2237        }
2238        if (userInfo.guestToRemove) {
2239            serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2240        }
2241        if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2242            serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2243                    Integer.toString(userInfo.profileGroupId));
2244        }
2245        serializer.attribute(null, ATTR_PROFILE_BADGE,
2246                Integer.toString(userInfo.profileBadge));
2247        if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2248            serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2249                    Integer.toString(userInfo.restrictedProfileParentId));
2250        }
2251        // Write seed data
2252        if (userData.persistSeedData) {
2253            if (userData.seedAccountName != null) {
2254                serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2255            }
2256            if (userData.seedAccountType != null) {
2257                serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2258            }
2259        }
2260        if (userInfo.name != null) {
2261            serializer.startTag(null, TAG_NAME);
2262            serializer.text(userInfo.name);
2263            serializer.endTag(null, TAG_NAME);
2264        }
2265        synchronized (mRestrictionsLock) {
2266            UserRestrictionsUtils.writeRestrictions(serializer,
2267                    mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2268            UserRestrictionsUtils.writeRestrictions(serializer,
2269                    mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2270                    TAG_DEVICE_POLICY_RESTRICTIONS);
2271            UserRestrictionsUtils.writeRestrictions(serializer,
2272                    mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2273                    TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
2274        }
2275
2276        if (userData.account != null) {
2277            serializer.startTag(null, TAG_ACCOUNT);
2278            serializer.text(userData.account);
2279            serializer.endTag(null, TAG_ACCOUNT);
2280        }
2281
2282        if (userData.persistSeedData && userData.seedAccountOptions != null) {
2283            serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2284            userData.seedAccountOptions.saveToXml(serializer);
2285            serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2286        }
2287
2288        serializer.endTag(null, TAG_USER);
2289
2290        serializer.endDocument();
2291    }
2292
2293    /*
2294     * Writes the user list file in this format:
2295     *
2296     * <users nextSerialNumber="3">
2297     *   <user id="0"></user>
2298     *   <user id="2"></user>
2299     * </users>
2300     */
2301    private void writeUserListLP() {
2302        if (DBG) {
2303            debug("writeUserList");
2304        }
2305        FileOutputStream fos = null;
2306        AtomicFile userListFile = new AtomicFile(mUserListFile);
2307        try {
2308            fos = userListFile.startWrite();
2309            final BufferedOutputStream bos = new BufferedOutputStream(fos);
2310
2311            // XmlSerializer serializer = XmlUtils.serializerInstance();
2312            final XmlSerializer serializer = new FastXmlSerializer();
2313            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
2314            serializer.startDocument(null, true);
2315            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2316
2317            serializer.startTag(null, TAG_USERS);
2318            serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
2319            serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
2320
2321            serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
2322            synchronized (mGuestRestrictions) {
2323                UserRestrictionsUtils
2324                        .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2325            }
2326            serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
2327            serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2328            serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2329            serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
2330            int[] userIdsToWrite;
2331            synchronized (mUsersLock) {
2332                userIdsToWrite = new int[mUsers.size()];
2333                for (int i = 0; i < userIdsToWrite.length; i++) {
2334                    UserInfo user = mUsers.valueAt(i).info;
2335                    userIdsToWrite[i] = user.id;
2336                }
2337            }
2338            for (int id : userIdsToWrite) {
2339                serializer.startTag(null, TAG_USER);
2340                serializer.attribute(null, ATTR_ID, Integer.toString(id));
2341                serializer.endTag(null, TAG_USER);
2342            }
2343
2344            serializer.endTag(null, TAG_USERS);
2345
2346            serializer.endDocument();
2347            userListFile.finishWrite(fos);
2348        } catch (Exception e) {
2349            userListFile.failWrite(fos);
2350            Slog.e(LOG_TAG, "Error writing user list");
2351        }
2352    }
2353
2354    private UserData readUserLP(int id) {
2355        FileInputStream fis = null;
2356        try {
2357            AtomicFile userFile =
2358                    new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2359            fis = userFile.openRead();
2360            return readUserLP(id, fis);
2361        } catch (IOException ioe) {
2362            Slog.e(LOG_TAG, "Error reading user list");
2363        } catch (XmlPullParserException pe) {
2364            Slog.e(LOG_TAG, "Error reading user list");
2365        } finally {
2366            IoUtils.closeQuietly(fis);
2367        }
2368        return null;
2369    }
2370
2371    @VisibleForTesting
2372    UserData readUserLP(int id, InputStream is) throws IOException,
2373            XmlPullParserException {
2374        int flags = 0;
2375        int serialNumber = id;
2376        String name = null;
2377        String account = null;
2378        String iconPath = null;
2379        long creationTime = 0L;
2380        long lastLoggedInTime = 0L;
2381        String lastLoggedInFingerprint = null;
2382        int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
2383        int profileBadge = 0;
2384        int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
2385        boolean partial = false;
2386        boolean guestToRemove = false;
2387        boolean persistSeedData = false;
2388        String seedAccountName = null;
2389        String seedAccountType = null;
2390        PersistableBundle seedAccountOptions = null;
2391        Bundle baseRestrictions = null;
2392        Bundle localRestrictions = null;
2393        Bundle globalRestrictions = null;
2394
2395        XmlPullParser parser = Xml.newPullParser();
2396        parser.setInput(is, StandardCharsets.UTF_8.name());
2397        int type;
2398        while ((type = parser.next()) != XmlPullParser.START_TAG
2399                && type != XmlPullParser.END_DOCUMENT) {
2400            // Skip
2401        }
2402
2403        if (type != XmlPullParser.START_TAG) {
2404            Slog.e(LOG_TAG, "Unable to read user " + id);
2405            return null;
2406        }
2407
2408        if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2409            int storedId = readIntAttribute(parser, ATTR_ID, -1);
2410            if (storedId != id) {
2411                Slog.e(LOG_TAG, "User id does not match the file name");
2412                return null;
2413            }
2414            serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2415            flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2416            iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2417            creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2418            lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2419            lastLoggedInFingerprint = parser.getAttributeValue(null,
2420                    ATTR_LAST_LOGGED_IN_FINGERPRINT);
2421            profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2422                    UserInfo.NO_PROFILE_GROUP_ID);
2423            profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2424            restrictedProfileParentId = readIntAttribute(parser,
2425                    ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2426            String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2427            if ("true".equals(valueString)) {
2428                partial = true;
2429            }
2430            valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2431            if ("true".equals(valueString)) {
2432                guestToRemove = true;
2433            }
2434
2435            seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2436            seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2437            if (seedAccountName != null || seedAccountType != null) {
2438                persistSeedData = true;
2439            }
2440
2441            int outerDepth = parser.getDepth();
2442            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2443                    && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2444                if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2445                    continue;
2446                }
2447                String tag = parser.getName();
2448                if (TAG_NAME.equals(tag)) {
2449                    type = parser.next();
2450                    if (type == XmlPullParser.TEXT) {
2451                        name = parser.getText();
2452                    }
2453                } else if (TAG_RESTRICTIONS.equals(tag)) {
2454                    baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2455                } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2456                    localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2457                } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2458                    globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2459                } else if (TAG_ACCOUNT.equals(tag)) {
2460                    type = parser.next();
2461                    if (type == XmlPullParser.TEXT) {
2462                        account = parser.getText();
2463                    }
2464                } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2465                    seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2466                    persistSeedData = true;
2467                }
2468            }
2469        }
2470
2471        // Create the UserInfo object that gets passed around
2472        UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2473        userInfo.serialNumber = serialNumber;
2474        userInfo.creationTime = creationTime;
2475        userInfo.lastLoggedInTime = lastLoggedInTime;
2476        userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2477        userInfo.partial = partial;
2478        userInfo.guestToRemove = guestToRemove;
2479        userInfo.profileGroupId = profileGroupId;
2480        userInfo.profileBadge = profileBadge;
2481        userInfo.restrictedProfileParentId = restrictedProfileParentId;
2482
2483        // Create the UserData object that's internal to this class
2484        UserData userData = new UserData();
2485        userData.info = userInfo;
2486        userData.account = account;
2487        userData.seedAccountName = seedAccountName;
2488        userData.seedAccountType = seedAccountType;
2489        userData.persistSeedData = persistSeedData;
2490        userData.seedAccountOptions = seedAccountOptions;
2491
2492        synchronized (mRestrictionsLock) {
2493            if (baseRestrictions != null) {
2494                mBaseUserRestrictions.put(id, baseRestrictions);
2495            }
2496            if (localRestrictions != null) {
2497                mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2498            }
2499            if (globalRestrictions != null) {
2500                mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2501            }
2502        }
2503        return userData;
2504    }
2505
2506    private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2507        String valueString = parser.getAttributeValue(null, attr);
2508        if (valueString == null) return defaultValue;
2509        try {
2510            return Integer.parseInt(valueString);
2511        } catch (NumberFormatException nfe) {
2512            return defaultValue;
2513        }
2514    }
2515
2516    private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2517        String valueString = parser.getAttributeValue(null, attr);
2518        if (valueString == null) return defaultValue;
2519        try {
2520            return Long.parseLong(valueString);
2521        } catch (NumberFormatException nfe) {
2522            return defaultValue;
2523        }
2524    }
2525
2526    /**
2527     * Removes the app restrictions file for a specific package and user id, if it exists.
2528     */
2529    private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2530        File dir = Environment.getUserSystemDirectory(userId);
2531        File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2532        if (resFile.exists()) {
2533            resFile.delete();
2534        }
2535    }
2536
2537    @Override
2538    public UserInfo createProfileForUser(String name, int flags, int userId,
2539            String[] disallowedPackages) {
2540        checkManageOrCreateUsersPermission(flags);
2541        return createUserInternal(name, flags, userId, disallowedPackages);
2542    }
2543
2544    @Override
2545    public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2546            String[] disallowedPackages) {
2547        checkManageOrCreateUsersPermission(flags);
2548        return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2549    }
2550
2551    @Override
2552    public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2553        checkManageOrCreateUsersPermission("Only the system can remove users");
2554        return removeUserUnchecked(userHandle);
2555    }
2556
2557    @Override
2558    public UserInfo createUser(String name, int flags) {
2559        checkManageOrCreateUsersPermission(flags);
2560        return createUserInternal(name, flags, UserHandle.USER_NULL);
2561    }
2562
2563    private UserInfo createUserInternal(String name, int flags, int parentId) {
2564        return createUserInternal(name, flags, parentId, null);
2565    }
2566
2567    private UserInfo createUserInternal(String name, int flags, int parentId,
2568            String[] disallowedPackages) {
2569        String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2570                ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2571                : UserManager.DISALLOW_ADD_USER;
2572        if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2573            Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
2574            return null;
2575        }
2576        return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2577    }
2578
2579    private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2580            String[] disallowedPackages) {
2581        DeviceStorageMonitorInternal dsm = LocalServices
2582                .getService(DeviceStorageMonitorInternal.class);
2583        if (dsm.isMemoryLow()) {
2584            Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2585            return null;
2586        }
2587        final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
2588        final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
2589        final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
2590        final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
2591        final long ident = Binder.clearCallingIdentity();
2592        UserInfo userInfo;
2593        UserData userData;
2594        final int userId;
2595        try {
2596            synchronized (mPackagesLock) {
2597                UserData parent = null;
2598                if (parentId != UserHandle.USER_NULL) {
2599                    synchronized (mUsersLock) {
2600                        parent = getUserDataLU(parentId);
2601                    }
2602                    if (parent == null) return null;
2603                }
2604                if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2605                    Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2606                    return null;
2607                }
2608                if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2609                    // If we're not adding a guest/demo user or a managed profile and the limit has
2610                    // been reached, cannot add a user.
2611                    return null;
2612                }
2613                // If we're adding a guest and there already exists one, bail.
2614                if (isGuest && findCurrentGuestUser() != null) {
2615                    return null;
2616                }
2617                // In legacy mode, restricted profile's parent can only be the owner user
2618                if (isRestricted && !UserManager.isSplitSystemUser()
2619                        && (parentId != UserHandle.USER_SYSTEM)) {
2620                    Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2621                    return null;
2622                }
2623                if (isRestricted && UserManager.isSplitSystemUser()) {
2624                    if (parent == null) {
2625                        Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2626                                + "specified");
2627                        return null;
2628                    }
2629                    if (!parent.info.canHaveProfile()) {
2630                        Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2631                                + "created for the specified parent user id " + parentId);
2632                        return null;
2633                    }
2634                }
2635                // In split system user mode, we assign the first human user the primary flag.
2636                // And if there is no device owner, we also assign the admin flag to primary user.
2637                if (UserManager.isSplitSystemUser()
2638                        && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2639                    flags |= UserInfo.FLAG_PRIMARY;
2640                    synchronized (mUsersLock) {
2641                        if (!mIsDeviceManaged) {
2642                            flags |= UserInfo.FLAG_ADMIN;
2643                        }
2644                    }
2645                }
2646
2647                userId = getNextAvailableId();
2648                Environment.getUserSystemDirectory(userId).mkdirs();
2649                boolean ephemeralGuests = Resources.getSystem()
2650                        .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
2651
2652                synchronized (mUsersLock) {
2653                    // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2654                    if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2655                            || (parent != null && parent.info.isEphemeral())) {
2656                        flags |= UserInfo.FLAG_EPHEMERAL;
2657                    }
2658
2659                    userInfo = new UserInfo(userId, name, null, flags);
2660                    userInfo.serialNumber = mNextSerialNumber++;
2661                    long now = System.currentTimeMillis();
2662                    userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2663                    userInfo.partial = true;
2664                    userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
2665                    if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2666                        userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2667                    }
2668                    userData = new UserData();
2669                    userData.info = userInfo;
2670                    mUsers.put(userId, userData);
2671                }
2672                writeUserLP(userData);
2673                writeUserListLP();
2674                if (parent != null) {
2675                    if (isManagedProfile) {
2676                        if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2677                            parent.info.profileGroupId = parent.info.id;
2678                            writeUserLP(parent);
2679                        }
2680                        userInfo.profileGroupId = parent.info.profileGroupId;
2681                    } else if (isRestricted) {
2682                        if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2683                            parent.info.restrictedProfileParentId = parent.info.id;
2684                            writeUserLP(parent);
2685                        }
2686                        userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
2687                    }
2688                }
2689            }
2690            final StorageManager storage = mContext.getSystemService(StorageManager.class);
2691            storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
2692            mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
2693                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2694            mPm.createNewUser(userId, disallowedPackages);
2695            userInfo.partial = false;
2696            synchronized (mPackagesLock) {
2697                writeUserLP(userData);
2698            }
2699            updateUserIds();
2700            Bundle restrictions = new Bundle();
2701            if (isGuest) {
2702                synchronized (mGuestRestrictions) {
2703                    restrictions.putAll(mGuestRestrictions);
2704                }
2705            }
2706            synchronized (mRestrictionsLock) {
2707                mBaseUserRestrictions.append(userId, restrictions);
2708            }
2709            mPm.onNewUserCreated(userId);
2710            Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2711            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2712            mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2713                    android.Manifest.permission.MANAGE_USERS);
2714            MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2715                    : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
2716        } finally {
2717            Binder.restoreCallingIdentity(ident);
2718        }
2719        return userInfo;
2720    }
2721
2722    @VisibleForTesting
2723    UserData putUserInfo(UserInfo userInfo) {
2724        final UserData userData = new UserData();
2725        userData.info = userInfo;
2726        synchronized (mUsers) {
2727            mUsers.put(userInfo.id, userData);
2728        }
2729        return userData;
2730    }
2731
2732    @VisibleForTesting
2733    void removeUserInfo(int userId) {
2734        synchronized (mUsers) {
2735            mUsers.remove(userId);
2736        }
2737    }
2738
2739    /**
2740     * @hide
2741     */
2742    @Override
2743    public UserInfo createRestrictedProfile(String name, int parentUserId) {
2744        checkManageOrCreateUsersPermission("setupRestrictedProfile");
2745        final UserInfo user = createProfileForUser(
2746                name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
2747        if (user == null) {
2748            return null;
2749        }
2750        long identity = Binder.clearCallingIdentity();
2751        try {
2752            setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2753            // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2754            // the putIntForUser() will fail.
2755            android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2756                    android.provider.Settings.Secure.LOCATION_MODE,
2757                    android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2758            setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2759        } finally {
2760            Binder.restoreCallingIdentity(identity);
2761        }
2762        return user;
2763    }
2764
2765    /**
2766     * Find the current guest user. If the Guest user is partial,
2767     * then do not include it in the results as it is about to die.
2768     */
2769    private UserInfo findCurrentGuestUser() {
2770        synchronized (mUsersLock) {
2771            final int size = mUsers.size();
2772            for (int i = 0; i < size; i++) {
2773                final UserInfo user = mUsers.valueAt(i).info;
2774                if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2775                    return user;
2776                }
2777            }
2778        }
2779        return null;
2780    }
2781
2782    /**
2783     * Mark this guest user for deletion to allow us to create another guest
2784     * and switch to that user before actually removing this guest.
2785     * @param userHandle the userid of the current guest
2786     * @return whether the user could be marked for deletion
2787     */
2788    @Override
2789    public boolean markGuestForDeletion(int userHandle) {
2790        checkManageUsersPermission("Only the system can remove users");
2791        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2792                UserManager.DISALLOW_REMOVE_USER, false)) {
2793            Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2794            return false;
2795        }
2796
2797        long ident = Binder.clearCallingIdentity();
2798        try {
2799            final UserData userData;
2800            synchronized (mPackagesLock) {
2801                synchronized (mUsersLock) {
2802                    userData = mUsers.get(userHandle);
2803                    if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
2804                        return false;
2805                    }
2806                }
2807                if (!userData.info.isGuest()) {
2808                    return false;
2809                }
2810                // We set this to a guest user that is to be removed. This is a temporary state
2811                // where we are allowed to add new Guest users, even if this one is still not
2812                // removed. This user will still show up in getUserInfo() calls.
2813                // If we don't get around to removing this Guest user, it will be purged on next
2814                // startup.
2815                userData.info.guestToRemove = true;
2816                // Mark it as disabled, so that it isn't returned any more when
2817                // profiles are queried.
2818                userData.info.flags |= UserInfo.FLAG_DISABLED;
2819                writeUserLP(userData);
2820            }
2821        } finally {
2822            Binder.restoreCallingIdentity(ident);
2823        }
2824        return true;
2825    }
2826
2827    /**
2828     * Removes a user and all data directories created for that user. This method should be called
2829     * after the user's processes have been terminated.
2830     * @param userHandle the user's id
2831     */
2832    @Override
2833    public boolean removeUser(int userHandle) {
2834        Slog.i(LOG_TAG, "removeUser u" + userHandle);
2835        checkManageOrCreateUsersPermission("Only the system can remove users");
2836
2837        final boolean isManagedProfile;
2838        synchronized (mUsersLock) {
2839            UserInfo userInfo = getUserInfoLU(userHandle);
2840            isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2841        }
2842        String restriction = isManagedProfile
2843                ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2844        if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2845            Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
2846            return false;
2847        }
2848        return removeUserUnchecked(userHandle);
2849    }
2850
2851    private boolean removeUserUnchecked(int userHandle) {
2852        long ident = Binder.clearCallingIdentity();
2853        try {
2854            final UserData userData;
2855            int currentUser = ActivityManager.getCurrentUser();
2856            if (currentUser == userHandle) {
2857                Log.w(LOG_TAG, "Current user cannot be removed");
2858                return false;
2859            }
2860            synchronized (mPackagesLock) {
2861                synchronized (mUsersLock) {
2862                    userData = mUsers.get(userHandle);
2863                    if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
2864                        return false;
2865                    }
2866
2867                    addRemovingUserIdLocked(userHandle);
2868                }
2869
2870                // Set this to a partially created user, so that the user will be purged
2871                // on next startup, in case the runtime stops now before stopping and
2872                // removing the user completely.
2873                userData.info.partial = true;
2874                // Mark it as disabled, so that it isn't returned any more when
2875                // profiles are queried.
2876                userData.info.flags |= UserInfo.FLAG_DISABLED;
2877                writeUserLP(userData);
2878            }
2879            try {
2880                mAppOpsService.removeUser(userHandle);
2881            } catch (RemoteException e) {
2882                Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2883            }
2884
2885            if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2886                    && userData.info.isManagedProfile()) {
2887                // Send broadcast to notify system that the user removed was a
2888                // managed user.
2889                sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
2890            }
2891
2892            if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2893            int res;
2894            try {
2895                res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
2896                new IStopUserCallback.Stub() {
2897                            @Override
2898                            public void userStopped(int userId) {
2899                                finishRemoveUser(userId);
2900                            }
2901                            @Override
2902                            public void userStopAborted(int userId) {
2903                            }
2904                        });
2905            } catch (RemoteException e) {
2906                return false;
2907            }
2908            return res == ActivityManager.USER_OP_SUCCESS;
2909        } finally {
2910            Binder.restoreCallingIdentity(ident);
2911        }
2912    }
2913
2914    @GuardedBy("mUsersLock")
2915    @VisibleForTesting
2916    void addRemovingUserIdLocked(int userId) {
2917        // We remember deleted user IDs to prevent them from being
2918        // reused during the current boot; they can still be reused
2919        // after a reboot or recycling of userIds.
2920        mRemovingUserIds.put(userId, true);
2921        mRecentlyRemovedIds.add(userId);
2922        // Keep LRU queue of recently removed IDs for recycling
2923        if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2924            mRecentlyRemovedIds.removeFirst();
2925        }
2926    }
2927
2928    void finishRemoveUser(final int userHandle) {
2929        if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
2930        // Let other services shutdown any activity and clean up their state before completely
2931        // wiping the user's system directory and removing from the user list
2932        long ident = Binder.clearCallingIdentity();
2933        try {
2934            Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2935            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
2936            mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2937                    android.Manifest.permission.MANAGE_USERS,
2938
2939                    new BroadcastReceiver() {
2940                        @Override
2941                        public void onReceive(Context context, Intent intent) {
2942                            if (DBG) {
2943                                Slog.i(LOG_TAG,
2944                                        "USER_REMOVED broadcast sent, cleaning up user data "
2945                                        + userHandle);
2946                            }
2947                            new Thread() {
2948                                @Override
2949                                public void run() {
2950                                    // Clean up any ActivityManager state
2951                                    LocalServices.getService(ActivityManagerInternal.class)
2952                                            .onUserRemoved(userHandle);
2953                                    removeUserState(userHandle);
2954                                }
2955                            }.start();
2956                        }
2957                    },
2958
2959                    null, Activity.RESULT_OK, null, null);
2960        } finally {
2961            Binder.restoreCallingIdentity(ident);
2962        }
2963    }
2964
2965    private void removeUserState(final int userHandle) {
2966        try {
2967            mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2968        } catch (IllegalStateException e) {
2969            // This may be simply because the user was partially created.
2970            Slog.i(LOG_TAG,
2971                "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2972        }
2973
2974        // Cleanup gatekeeper secure user id
2975        try {
2976            final IGateKeeperService gk = GateKeeper.getService();
2977            if (gk != null) {
2978                gk.clearSecureUserId(userHandle);
2979            }
2980        } catch (Exception ex) {
2981            Slog.w(LOG_TAG, "unable to clear GK secure user id");
2982        }
2983
2984        // Cleanup package manager settings
2985        mPm.cleanUpUser(this, userHandle);
2986
2987        // Clean up all data before removing metadata
2988        mUserDataPreparer.destroyUserData(userHandle,
2989                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2990
2991        // Remove this user from the list
2992        synchronized (mUsersLock) {
2993            mUsers.remove(userHandle);
2994            mIsUserManaged.delete(userHandle);
2995        }
2996        synchronized (mUserStates) {
2997            mUserStates.delete(userHandle);
2998        }
2999        synchronized (mRestrictionsLock) {
3000            mBaseUserRestrictions.remove(userHandle);
3001            mAppliedUserRestrictions.remove(userHandle);
3002            mCachedEffectiveUserRestrictions.remove(userHandle);
3003            mDevicePolicyLocalUserRestrictions.remove(userHandle);
3004            if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
3005                mDevicePolicyGlobalUserRestrictions.remove(userHandle);
3006                applyUserRestrictionsForAllUsersLR();
3007            }
3008        }
3009        // Update the user list
3010        synchronized (mPackagesLock) {
3011            writeUserListLP();
3012        }
3013        // Remove user file
3014        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3015        userFile.delete();
3016        updateUserIds();
3017        if (RELEASE_DELETED_USER_ID) {
3018            synchronized (mUsers) {
3019                mRemovingUserIds.delete(userHandle);
3020            }
3021        }
3022    }
3023
3024    private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
3025        Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
3026        managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3027                Intent.FLAG_RECEIVER_FOREGROUND);
3028        managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
3029        managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
3030        mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
3031    }
3032
3033    @Override
3034    public Bundle getApplicationRestrictions(String packageName) {
3035        return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3036    }
3037
3038    @Override
3039    public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
3040        if (UserHandle.getCallingUserId() != userId
3041                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
3042            checkSystemOrRoot("get application restrictions for other user/app " + packageName);
3043        }
3044        synchronized (mAppRestrictionsLock) {
3045            // Read the restrictions from XML
3046            return readApplicationRestrictionsLAr(packageName, userId);
3047        }
3048    }
3049
3050    @Override
3051    public void setApplicationRestrictions(String packageName, Bundle restrictions,
3052            int userId) {
3053        checkSystemOrRoot("set application restrictions");
3054        if (restrictions != null) {
3055            restrictions.setDefusable(true);
3056        }
3057        synchronized (mAppRestrictionsLock) {
3058            if (restrictions == null || restrictions.isEmpty()) {
3059                cleanAppRestrictionsForPackageLAr(packageName, userId);
3060            } else {
3061                // Write the restrictions to XML
3062                writeApplicationRestrictionsLAr(packageName, restrictions, userId);
3063            }
3064        }
3065
3066        // Notify package of changes via an intent - only sent to explicitly registered receivers.
3067        Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3068        changeIntent.setPackage(packageName);
3069        changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3070        mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
3071    }
3072
3073    private int getUidForPackage(String packageName) {
3074        long ident = Binder.clearCallingIdentity();
3075        try {
3076            return mContext.getPackageManager().getApplicationInfo(packageName,
3077                    PackageManager.MATCH_ANY_USER).uid;
3078        } catch (NameNotFoundException nnfe) {
3079            return -1;
3080        } finally {
3081            Binder.restoreCallingIdentity(ident);
3082        }
3083    }
3084
3085    @GuardedBy("mAppRestrictionsLock")
3086    private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
3087        AtomicFile restrictionsFile =
3088                new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3089                        packageToRestrictionsFileName(packageName)));
3090        return readApplicationRestrictionsLAr(restrictionsFile);
3091    }
3092
3093    @VisibleForTesting
3094    @GuardedBy("mAppRestrictionsLock")
3095    static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
3096        final Bundle restrictions = new Bundle();
3097        final ArrayList<String> values = new ArrayList<>();
3098        if (!restrictionsFile.getBaseFile().exists()) {
3099            return restrictions;
3100        }
3101
3102        FileInputStream fis = null;
3103        try {
3104            fis = restrictionsFile.openRead();
3105            XmlPullParser parser = Xml.newPullParser();
3106            parser.setInput(fis, StandardCharsets.UTF_8.name());
3107            XmlUtils.nextElement(parser);
3108            if (parser.getEventType() != XmlPullParser.START_TAG) {
3109                Slog.e(LOG_TAG, "Unable to read restrictions file "
3110                        + restrictionsFile.getBaseFile());
3111                return restrictions;
3112            }
3113            while (parser.next() != XmlPullParser.END_DOCUMENT) {
3114                readEntry(restrictions, values, parser);
3115            }
3116        } catch (IOException|XmlPullParserException e) {
3117            Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
3118        } finally {
3119            IoUtils.closeQuietly(fis);
3120        }
3121        return restrictions;
3122    }
3123
3124    private static void readEntry(Bundle restrictions, ArrayList<String> values,
3125            XmlPullParser parser) throws XmlPullParserException, IOException {
3126        int type = parser.getEventType();
3127        if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3128            String key = parser.getAttributeValue(null, ATTR_KEY);
3129            String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3130            String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3131            if (multiple != null) {
3132                values.clear();
3133                int count = Integer.parseInt(multiple);
3134                while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3135                    if (type == XmlPullParser.START_TAG
3136                            && parser.getName().equals(TAG_VALUE)) {
3137                        values.add(parser.nextText().trim());
3138                        count--;
3139                    }
3140                }
3141                String [] valueStrings = new String[values.size()];
3142                values.toArray(valueStrings);
3143                restrictions.putStringArray(key, valueStrings);
3144            } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3145                restrictions.putBundle(key, readBundleEntry(parser, values));
3146            } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3147                final int outerDepth = parser.getDepth();
3148                ArrayList<Bundle> bundleList = new ArrayList<>();
3149                while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3150                    Bundle childBundle = readBundleEntry(parser, values);
3151                    bundleList.add(childBundle);
3152                }
3153                restrictions.putParcelableArray(key,
3154                        bundleList.toArray(new Bundle[bundleList.size()]));
3155            } else {
3156                String value = parser.nextText().trim();
3157                if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3158                    restrictions.putBoolean(key, Boolean.parseBoolean(value));
3159                } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3160                    restrictions.putInt(key, Integer.parseInt(value));
3161                } else {
3162                    restrictions.putString(key, value);
3163                }
3164            }
3165        }
3166    }
3167
3168    private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3169            throws IOException, XmlPullParserException {
3170        Bundle childBundle = new Bundle();
3171        final int outerDepth = parser.getDepth();
3172        while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3173            readEntry(childBundle, values, parser);
3174        }
3175        return childBundle;
3176    }
3177
3178    @GuardedBy("mAppRestrictionsLock")
3179    private static void writeApplicationRestrictionsLAr(String packageName,
3180            Bundle restrictions, int userId) {
3181        AtomicFile restrictionsFile = new AtomicFile(
3182                new File(Environment.getUserSystemDirectory(userId),
3183                        packageToRestrictionsFileName(packageName)));
3184        writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
3185    }
3186
3187    @VisibleForTesting
3188    @GuardedBy("mAppRestrictionsLock")
3189    static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
3190        FileOutputStream fos = null;
3191        try {
3192            fos = restrictionsFile.startWrite();
3193            final BufferedOutputStream bos = new BufferedOutputStream(fos);
3194
3195            final XmlSerializer serializer = new FastXmlSerializer();
3196            serializer.setOutput(bos, StandardCharsets.UTF_8.name());
3197            serializer.startDocument(null, true);
3198            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3199
3200            serializer.startTag(null, TAG_RESTRICTIONS);
3201            writeBundle(restrictions, serializer);
3202            serializer.endTag(null, TAG_RESTRICTIONS);
3203
3204            serializer.endDocument();
3205            restrictionsFile.finishWrite(fos);
3206        } catch (Exception e) {
3207            restrictionsFile.failWrite(fos);
3208            Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3209        }
3210    }
3211
3212    private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3213            throws IOException {
3214        for (String key : restrictions.keySet()) {
3215            Object value = restrictions.get(key);
3216            serializer.startTag(null, TAG_ENTRY);
3217            serializer.attribute(null, ATTR_KEY, key);
3218
3219            if (value instanceof Boolean) {
3220                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3221                serializer.text(value.toString());
3222            } else if (value instanceof Integer) {
3223                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3224                serializer.text(value.toString());
3225            } else if (value == null || value instanceof String) {
3226                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3227                serializer.text(value != null ? (String) value : "");
3228            } else if (value instanceof Bundle) {
3229                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3230                writeBundle((Bundle) value, serializer);
3231            } else if (value instanceof Parcelable[]) {
3232                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3233                Parcelable[] array = (Parcelable[]) value;
3234                for (Parcelable parcelable : array) {
3235                    if (!(parcelable instanceof Bundle)) {
3236                        throw new IllegalArgumentException("bundle-array can only hold Bundles");
3237                    }
3238                    serializer.startTag(null, TAG_ENTRY);
3239                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3240                    writeBundle((Bundle) parcelable, serializer);
3241                    serializer.endTag(null, TAG_ENTRY);
3242                }
3243            } else {
3244                serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3245                String[] values = (String[]) value;
3246                serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3247                for (String choice : values) {
3248                    serializer.startTag(null, TAG_VALUE);
3249                    serializer.text(choice != null ? choice : "");
3250                    serializer.endTag(null, TAG_VALUE);
3251                }
3252            }
3253            serializer.endTag(null, TAG_ENTRY);
3254        }
3255    }
3256
3257    @Override
3258    public int getUserSerialNumber(int userHandle) {
3259        synchronized (mUsersLock) {
3260            if (!exists(userHandle)) return -1;
3261            return getUserInfoLU(userHandle).serialNumber;
3262        }
3263    }
3264
3265    @Override
3266    public boolean isUserNameSet(int userHandle) {
3267        synchronized (mUsersLock) {
3268            UserInfo userInfo = getUserInfoLU(userHandle);
3269            return userInfo != null && userInfo.name != null;
3270        }
3271    }
3272
3273    @Override
3274    public int getUserHandle(int userSerialNumber) {
3275        synchronized (mUsersLock) {
3276            for (int userId : mUserIds) {
3277                UserInfo info = getUserInfoLU(userId);
3278                if (info != null && info.serialNumber == userSerialNumber) return userId;
3279            }
3280            // Not found
3281            return -1;
3282        }
3283    }
3284
3285    @Override
3286    public long getUserCreationTime(int userHandle) {
3287        int callingUserId = UserHandle.getCallingUserId();
3288        UserInfo userInfo = null;
3289        synchronized (mUsersLock) {
3290            if (callingUserId == userHandle) {
3291                userInfo = getUserInfoLU(userHandle);
3292            } else {
3293                UserInfo parent = getProfileParentLU(userHandle);
3294                if (parent != null && parent.id == callingUserId) {
3295                    userInfo = getUserInfoLU(userHandle);
3296                }
3297            }
3298        }
3299        if (userInfo == null) {
3300            throw new SecurityException("userHandle can only be the calling user or a managed "
3301                    + "profile associated with this user");
3302        }
3303        return userInfo.creationTime;
3304    }
3305
3306    /**
3307     * Caches the list of user ids in an array, adjusting the array size when necessary.
3308     */
3309    private void updateUserIds() {
3310        int num = 0;
3311        synchronized (mUsersLock) {
3312            final int userSize = mUsers.size();
3313            for (int i = 0; i < userSize; i++) {
3314                if (!mUsers.valueAt(i).info.partial) {
3315                    num++;
3316                }
3317            }
3318            final int[] newUsers = new int[num];
3319            int n = 0;
3320            for (int i = 0; i < userSize; i++) {
3321                if (!mUsers.valueAt(i).info.partial) {
3322                    newUsers[n++] = mUsers.keyAt(i);
3323                }
3324            }
3325            mUserIds = newUsers;
3326        }
3327    }
3328
3329    /**
3330     * Called right before a user is started. This gives us a chance to prepare
3331     * app storage and apply any user restrictions.
3332     */
3333    public void onBeforeStartUser(int userId) {
3334        UserInfo userInfo = getUserInfo(userId);
3335        if (userInfo == null) {
3336            return;
3337        }
3338        final int userSerial = userInfo.serialNumber;
3339        // Migrate only if build fingerprints mismatch
3340        boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
3341        mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
3342        mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
3343
3344        if (userId != UserHandle.USER_SYSTEM) {
3345            synchronized (mRestrictionsLock) {
3346                applyUserRestrictionsLR(userId);
3347            }
3348        }
3349    }
3350
3351    /**
3352     * Called right before a user is unlocked. This gives us a chance to prepare
3353     * app storage.
3354     */
3355    public void onBeforeUnlockUser(@UserIdInt int userId) {
3356        UserInfo userInfo = getUserInfo(userId);
3357        if (userInfo == null) {
3358            return;
3359        }
3360        final int userSerial = userInfo.serialNumber;
3361        // Migrate only if build fingerprints mismatch
3362        boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
3363        mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
3364        mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
3365    }
3366
3367    /**
3368     * Examine all users present on given mounted volume, and destroy data
3369     * belonging to users that are no longer valid, or whose user ID has been
3370     * recycled.
3371     */
3372    void reconcileUsers(String volumeUuid) {
3373        mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3374    }
3375
3376    /**
3377     * Make a note of the last started time of a user and do some cleanup.
3378     * This is called with ActivityManagerService lock held.
3379     * @param userId the user that was just foregrounded
3380     */
3381    public void onUserLoggedIn(@UserIdInt int userId) {
3382        UserData userData = getUserDataNoChecks(userId);
3383        if (userData == null || userData.info.partial) {
3384            Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3385            return;
3386        }
3387
3388        final long now = System.currentTimeMillis();
3389        if (now > EPOCH_PLUS_30_YEARS) {
3390            userData.info.lastLoggedInTime = now;
3391        }
3392        userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3393        scheduleWriteUser(userData);
3394    }
3395
3396    /**
3397     * Returns the next available user id, filling in any holes in the ids.
3398     */
3399    @VisibleForTesting
3400    int getNextAvailableId() {
3401        int nextId;
3402        synchronized (mUsersLock) {
3403            nextId = scanNextAvailableIdLocked();
3404            if (nextId >= 0) {
3405                return nextId;
3406            }
3407            // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3408            // except most recently removed
3409            if (mRemovingUserIds.size() > 0) {
3410                Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3411                mRemovingUserIds.clear();
3412                for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3413                    mRemovingUserIds.put(recentlyRemovedId, true);
3414                }
3415                nextId = scanNextAvailableIdLocked();
3416            }
3417        }
3418        if (nextId < 0) {
3419            throw new IllegalStateException("No user id available!");
3420        }
3421        return nextId;
3422    }
3423
3424    @GuardedBy("mUsersLock")
3425    private int scanNextAvailableIdLocked() {
3426        for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3427            if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3428                return i;
3429            }
3430        }
3431        return -1;
3432    }
3433
3434    private static String packageToRestrictionsFileName(String packageName) {
3435        return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3436    }
3437
3438    @Override
3439    public void setSeedAccountData(int userId, String accountName, String accountType,
3440            PersistableBundle accountOptions, boolean persist) {
3441        checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3442        synchronized (mPackagesLock) {
3443            final UserData userData;
3444            synchronized (mUsersLock) {
3445                userData = getUserDataLU(userId);
3446                if (userData == null) {
3447                    Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3448                    return;
3449                }
3450                userData.seedAccountName = accountName;
3451                userData.seedAccountType = accountType;
3452                userData.seedAccountOptions = accountOptions;
3453                userData.persistSeedData = persist;
3454            }
3455            if (persist) {
3456                writeUserLP(userData);
3457            }
3458        }
3459    }
3460
3461    @Override
3462    public String getSeedAccountName() throws RemoteException {
3463        checkManageUsersPermission("Cannot get seed account information");
3464        synchronized (mUsersLock) {
3465            UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3466            return userData.seedAccountName;
3467        }
3468    }
3469
3470    @Override
3471    public String getSeedAccountType() throws RemoteException {
3472        checkManageUsersPermission("Cannot get seed account information");
3473        synchronized (mUsersLock) {
3474            UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3475            return userData.seedAccountType;
3476        }
3477    }
3478
3479    @Override
3480    public PersistableBundle getSeedAccountOptions() throws RemoteException {
3481        checkManageUsersPermission("Cannot get seed account information");
3482        synchronized (mUsersLock) {
3483            UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3484            return userData.seedAccountOptions;
3485        }
3486    }
3487
3488    @Override
3489    public void clearSeedAccountData() throws RemoteException {
3490        checkManageUsersPermission("Cannot clear seed account information");
3491        synchronized (mPackagesLock) {
3492            UserData userData;
3493            synchronized (mUsersLock) {
3494                userData = getUserDataLU(UserHandle.getCallingUserId());
3495                if (userData == null) return;
3496                userData.clearSeedAccountData();
3497            }
3498            writeUserLP(userData);
3499        }
3500    }
3501
3502    @Override
3503    public boolean someUserHasSeedAccount(String accountName, String accountType)
3504            throws RemoteException {
3505        checkManageUsersPermission("Cannot check seed account information");
3506        synchronized (mUsersLock) {
3507            final int userSize = mUsers.size();
3508            for (int i = 0; i < userSize; i++) {
3509                final UserData data = mUsers.valueAt(i);
3510                if (data.info.isInitialized()) continue;
3511                if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3512                    continue;
3513                }
3514                if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3515                    continue;
3516                }
3517                return true;
3518            }
3519        }
3520        return false;
3521    }
3522
3523    @Override
3524    public void onShellCommand(FileDescriptor in, FileDescriptor out,
3525            FileDescriptor err, String[] args, ShellCallback callback,
3526            ResultReceiver resultReceiver) {
3527        (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
3528    }
3529
3530    int onShellCommand(Shell shell, String cmd) {
3531        if (cmd == null) {
3532            return shell.handleDefaultCommands(cmd);
3533        }
3534
3535        final PrintWriter pw = shell.getOutPrintWriter();
3536        try {
3537            switch(cmd) {
3538                case "list":
3539                    return runList(pw);
3540            }
3541        } catch (RemoteException e) {
3542            pw.println("Remote exception: " + e);
3543        }
3544        return -1;
3545    }
3546
3547    private int runList(PrintWriter pw) throws RemoteException {
3548        final IActivityManager am = ActivityManager.getService();
3549        final List<UserInfo> users = getUsers(false);
3550        if (users == null) {
3551            pw.println("Error: couldn't get users");
3552            return 1;
3553        } else {
3554            pw.println("Users:");
3555            for (int i = 0; i < users.size(); i++) {
3556                String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
3557                pw.println("\t" + users.get(i).toString() + running);
3558            }
3559            return 0;
3560        }
3561    }
3562
3563    @Override
3564    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3565        if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
3566
3567        long now = System.currentTimeMillis();
3568        final long nowRealtime = SystemClock.elapsedRealtime();
3569        StringBuilder sb = new StringBuilder();
3570        synchronized (mPackagesLock) {
3571            synchronized (mUsersLock) {
3572                pw.println("Users:");
3573                for (int i = 0; i < mUsers.size(); i++) {
3574                    UserData userData = mUsers.valueAt(i);
3575                    if (userData == null) {
3576                        continue;
3577                    }
3578                    UserInfo userInfo = userData.info;
3579                    final int userId = userInfo.id;
3580                    pw.print("  "); pw.print(userInfo);
3581                    pw.print(" serialNo="); pw.print(userInfo.serialNumber);
3582                    if (mRemovingUserIds.get(userId)) {
3583                        pw.print(" <removing> ");
3584                    }
3585                    if (userInfo.partial) {
3586                        pw.print(" <partial>");
3587                    }
3588                    pw.println();
3589                    pw.print("    State: ");
3590                    final int state;
3591                    synchronized (mUserStates) {
3592                        state = mUserStates.get(userId, -1);
3593                    }
3594                    pw.println(UserState.stateToString(state));
3595                    pw.print("    Created: ");
3596                    dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3597
3598                    pw.print("    Last logged in: ");
3599                    dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3600
3601                    pw.print("    Last logged in fingerprint: ");
3602                    pw.println(userInfo.lastLoggedInFingerprint);
3603
3604                    pw.print("    Start time: ");
3605                    dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3606
3607                    pw.print("    Unlock time: ");
3608                    dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3609
3610                    pw.print("    Has profile owner: ");
3611                    pw.println(mIsUserManaged.get(userId));
3612                    pw.println("    Restrictions:");
3613                    synchronized (mRestrictionsLock) {
3614                        UserRestrictionsUtils.dumpRestrictions(
3615                                pw, "      ", mBaseUserRestrictions.get(userInfo.id));
3616                        pw.println("    Device policy global restrictions:");
3617                        UserRestrictionsUtils.dumpRestrictions(
3618                                pw, "      ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
3619                        pw.println("    Device policy local restrictions:");
3620                        UserRestrictionsUtils.dumpRestrictions(
3621                                pw, "      ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
3622                        pw.println("    Effective restrictions:");
3623                        UserRestrictionsUtils.dumpRestrictions(
3624                                pw, "      ", mCachedEffectiveUserRestrictions.get(userInfo.id));
3625                    }
3626
3627                    if (userData.account != null) {
3628                        pw.print("    Account name: " + userData.account);
3629                        pw.println();
3630                    }
3631
3632                    if (userData.seedAccountName != null) {
3633                        pw.print("    Seed account name: " + userData.seedAccountName);
3634                        pw.println();
3635                        if (userData.seedAccountType != null) {
3636                            pw.print("         account type: " + userData.seedAccountType);
3637                            pw.println();
3638                        }
3639                        if (userData.seedAccountOptions != null) {
3640                            pw.print("         account options exist");
3641                            pw.println();
3642                        }
3643                    }
3644                }
3645            }
3646            pw.println();
3647            pw.println("  Device owner id:" + mDeviceOwnerUserId);
3648            pw.println();
3649            pw.println("  Guest restrictions:");
3650            synchronized (mGuestRestrictions) {
3651                UserRestrictionsUtils.dumpRestrictions(pw, "    ", mGuestRestrictions);
3652            }
3653            synchronized (mUsersLock) {
3654                pw.println();
3655                pw.println("  Device managed: " + mIsDeviceManaged);
3656                if (mRemovingUserIds.size() > 0) {
3657                    pw.println();
3658                    pw.println("  Recently removed userIds: " + mRecentlyRemovedIds);
3659                }
3660            }
3661            synchronized (mUserStates) {
3662                pw.println("  Started users state: " + mUserStates);
3663            }
3664            // Dump some capabilities
3665            pw.println();
3666            pw.println("  Max users: " + UserManager.getMaxSupportedUsers());
3667            pw.println("  Supports switchable users: " + UserManager.supportsMultipleUsers());
3668            pw.println("  All guests ephemeral: " + Resources.getSystem().getBoolean(
3669                    com.android.internal.R.bool.config_guestUserEphemeral));
3670        }
3671    }
3672
3673    private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3674        if (time == 0) {
3675            pw.println("<unknown>");
3676        } else {
3677            sb.setLength(0);
3678            TimeUtils.formatDuration(nowTime - time, sb);
3679            sb.append(" ago");
3680            pw.println(sb);
3681        }
3682    }
3683
3684    final class MainHandler extends Handler {
3685
3686        @Override
3687        public void handleMessage(Message msg) {
3688            switch (msg.what) {
3689                case WRITE_USER_MSG:
3690                    removeMessages(WRITE_USER_MSG, msg.obj);
3691                    synchronized (mPackagesLock) {
3692                        int userId = ((UserData) msg.obj).info.id;
3693                        UserData userData = getUserDataNoChecks(userId);
3694                        if (userData != null) {
3695                            writeUserLP(userData);
3696                        }
3697                    }
3698            }
3699        }
3700    }
3701
3702    /**
3703     * @param userId
3704     * @return whether the user has been initialized yet
3705     */
3706    boolean isUserInitialized(int userId) {
3707        return mLocalService.isUserInitialized(userId);
3708    }
3709
3710    private class LocalService extends UserManagerInternal {
3711        @Override
3712        public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3713                boolean isDeviceOwner, int cameraRestrictionScope) {
3714            UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3715                isDeviceOwner, cameraRestrictionScope);
3716        }
3717
3718        @Override
3719        public Bundle getBaseUserRestrictions(int userId) {
3720            synchronized (mRestrictionsLock) {
3721                return mBaseUserRestrictions.get(userId);
3722            }
3723        }
3724
3725        @Override
3726        public void setBaseUserRestrictionsByDpmsForMigration(
3727                int userId, Bundle baseRestrictions) {
3728            synchronized (mRestrictionsLock) {
3729                if (updateRestrictionsIfNeededLR(
3730                        userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3731                    invalidateEffectiveUserRestrictionsLR(userId);
3732                }
3733            }
3734
3735            final UserData userData = getUserDataNoChecks(userId);
3736            synchronized (mPackagesLock) {
3737                if (userData != null) {
3738                    writeUserLP(userData);
3739                } else {
3740                    Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3741                }
3742            }
3743        }
3744
3745        @Override
3746        public boolean getUserRestriction(int userId, String key) {
3747            return getUserRestrictions(userId).getBoolean(key);
3748        }
3749
3750        @Override
3751        public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3752            synchronized (mUserRestrictionsListeners) {
3753                mUserRestrictionsListeners.add(listener);
3754            }
3755        }
3756
3757        @Override
3758        public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3759            synchronized (mUserRestrictionsListeners) {
3760                mUserRestrictionsListeners.remove(listener);
3761            }
3762        }
3763
3764        @Override
3765        public void setDeviceManaged(boolean isManaged) {
3766            synchronized (mUsersLock) {
3767                mIsDeviceManaged = isManaged;
3768            }
3769        }
3770
3771        @Override
3772        public void setUserManaged(int userId, boolean isManaged) {
3773            synchronized (mUsersLock) {
3774                mIsUserManaged.put(userId, isManaged);
3775            }
3776        }
3777
3778        @Override
3779        public void setUserIcon(int userId, Bitmap bitmap) {
3780            long ident = Binder.clearCallingIdentity();
3781            try {
3782                synchronized (mPackagesLock) {
3783                    UserData userData = getUserDataNoChecks(userId);
3784                    if (userData == null || userData.info.partial) {
3785                        Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3786                        return;
3787                    }
3788                    writeBitmapLP(userData.info, bitmap);
3789                    writeUserLP(userData);
3790                }
3791                sendUserInfoChangedBroadcast(userId);
3792            } finally {
3793                Binder.restoreCallingIdentity(ident);
3794            }
3795        }
3796
3797        @Override
3798        public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3799            synchronized (mUsersLock) {
3800                mForceEphemeralUsers = forceEphemeralUsers;
3801            }
3802        }
3803
3804        @Override
3805        public void removeAllUsers() {
3806            if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3807                // Remove the non-system users straight away.
3808                removeNonSystemUsers();
3809            } else {
3810                // Switch to the system user first and then remove the other users.
3811                BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3812                    @Override
3813                    public void onReceive(Context context, Intent intent) {
3814                        int userId =
3815                                intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3816                        if (userId != UserHandle.USER_SYSTEM) {
3817                            return;
3818                        }
3819                        mContext.unregisterReceiver(this);
3820                        removeNonSystemUsers();
3821                    }
3822                };
3823                IntentFilter userSwitchedFilter = new IntentFilter();
3824                userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3825                mContext.registerReceiver(
3826                        userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3827
3828                // Switch to the system user.
3829                ActivityManager am =
3830                        (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3831                am.switchUser(UserHandle.USER_SYSTEM);
3832            }
3833        }
3834
3835        @Override
3836        public void onEphemeralUserStop(int userId) {
3837            synchronized (mUsersLock) {
3838               UserInfo userInfo = getUserInfoLU(userId);
3839               if (userInfo != null && userInfo.isEphemeral()) {
3840                    // Do not allow switching back to the ephemeral user again as the user is going
3841                    // to be deleted.
3842                    userInfo.flags |= UserInfo.FLAG_DISABLED;
3843                    if (userInfo.isGuest()) {
3844                        // Indicate that the guest will be deleted after it stops.
3845                        userInfo.guestToRemove = true;
3846                    }
3847               }
3848            }
3849        }
3850
3851        @Override
3852        public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3853                String[] disallowedPackages) {
3854            UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3855                    disallowedPackages);
3856            // Keep this in sync with UserManager.createUser
3857            if (user != null && !user.isAdmin() && !user.isDemo()) {
3858                setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3859                setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3860            }
3861            return user;
3862        }
3863
3864        @Override
3865        public boolean removeUserEvenWhenDisallowed(int userId) {
3866            return removeUserUnchecked(userId);
3867        }
3868
3869        @Override
3870        public boolean isUserRunning(int userId) {
3871            synchronized (mUserStates) {
3872                return mUserStates.get(userId, -1) >= 0;
3873            }
3874        }
3875
3876        @Override
3877        public void setUserState(int userId, int userState) {
3878            synchronized (mUserStates) {
3879                mUserStates.put(userId, userState);
3880            }
3881        }
3882
3883        @Override
3884        public void removeUserState(int userId) {
3885            synchronized (mUserStates) {
3886                mUserStates.delete(userId);
3887            }
3888        }
3889
3890        @Override
3891        public int[] getUserIds() {
3892            return UserManagerService.this.getUserIds();
3893        }
3894
3895        @Override
3896        public boolean isUserUnlockingOrUnlocked(int userId) {
3897            int state;
3898            synchronized (mUserStates) {
3899                state = mUserStates.get(userId, -1);
3900            }
3901            // Special case, in the stopping/shutdown state user key can still be unlocked
3902            if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3903                return StorageManager.isUserKeyUnlocked(userId);
3904            }
3905            return (state == UserState.STATE_RUNNING_UNLOCKING)
3906                    || (state == UserState.STATE_RUNNING_UNLOCKED);
3907        }
3908
3909        @Override
3910        public boolean isUserUnlocked(int userId) {
3911            int state;
3912            synchronized (mUserStates) {
3913                state = mUserStates.get(userId, -1);
3914            }
3915            // Special case, in the stopping/shutdown state user key can still be unlocked
3916            if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3917                return StorageManager.isUserKeyUnlocked(userId);
3918            }
3919            return state == UserState.STATE_RUNNING_UNLOCKED;
3920        }
3921
3922        @Override
3923        public boolean isUserInitialized(int userId) {
3924            return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3925        }
3926
3927        @Override
3928        public boolean exists(int userId) {
3929            return getUserInfoNoChecks(userId) != null;
3930        }
3931    }
3932
3933    /* Remove all the users except of the system one. */
3934    private void removeNonSystemUsers() {
3935        ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3936        synchronized (mUsersLock) {
3937            final int userSize = mUsers.size();
3938            for (int i = 0; i < userSize; i++) {
3939                UserInfo ui = mUsers.valueAt(i).info;
3940                if (ui.id != UserHandle.USER_SYSTEM) {
3941                    usersToRemove.add(ui);
3942                }
3943            }
3944        }
3945        for (UserInfo ui: usersToRemove) {
3946            removeUser(ui.id);
3947        }
3948    }
3949
3950    private class Shell extends ShellCommand {
3951        @Override
3952        public int onCommand(String cmd) {
3953            return onShellCommand(this, cmd);
3954        }
3955
3956        @Override
3957        public void onHelp() {
3958            final PrintWriter pw = getOutPrintWriter();
3959            pw.println("User manager (user) commands:");
3960            pw.println("  help");
3961            pw.println("    Print this help text.");
3962            pw.println("");
3963            pw.println("  list");
3964            pw.println("    Prints all users on the system.");
3965        }
3966    }
3967
3968    private static void debug(String message) {
3969        Log.d(LOG_TAG, message +
3970                (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, "  ") : ""));
3971    }
3972
3973    @VisibleForTesting
3974    static int getMaxManagedProfiles() {
3975        // Allow overriding max managed profiles on debuggable builds for testing
3976        // of multiple profiles.
3977        if (!Build.IS_DEBUGGABLE) {
3978            return MAX_MANAGED_PROFILES;
3979        } else {
3980            return SystemProperties.getInt("persist.sys.max_profiles",
3981                    MAX_MANAGED_PROFILES);
3982        }
3983    }
3984
3985    @VisibleForTesting
3986    int getFreeProfileBadgeLU(int parentUserId) {
3987        int maxManagedProfiles = getMaxManagedProfiles();
3988        boolean[] usedBadges = new boolean[maxManagedProfiles];
3989        final int userSize = mUsers.size();
3990        for (int i = 0; i < userSize; i++) {
3991            UserInfo ui = mUsers.valueAt(i).info;
3992            // Check which badge indexes are already used by this profile group.
3993            if (ui.isManagedProfile()
3994                    && ui.profileGroupId == parentUserId
3995                    && !mRemovingUserIds.get(ui.id)
3996                    && ui.profileBadge < maxManagedProfiles) {
3997                usedBadges[ui.profileBadge] = true;
3998            }
3999        }
4000        for (int i = 0; i < maxManagedProfiles; i++) {
4001            if (!usedBadges[i]) {
4002                return i;
4003            }
4004        }
4005        return 0;
4006    }
4007
4008    /**
4009     * Checks if the given user has a managed profile associated with it.
4010     * @param userId The parent user
4011     * @return
4012     */
4013    boolean hasManagedProfile(int userId) {
4014        synchronized (mUsersLock) {
4015            UserInfo userInfo = getUserInfoLU(userId);
4016            final int userSize = mUsers.size();
4017            for (int i = 0; i < userSize; i++) {
4018                UserInfo profile = mUsers.valueAt(i).info;
4019                if (userId != profile.id && isProfileOf(userInfo, profile)) {
4020                    return true;
4021                }
4022            }
4023            return false;
4024        }
4025    }
4026
4027    /**
4028     * Check if the calling package name matches with the calling UID, throw
4029     * {@link SecurityException} if not.
4030     */
4031    private void verifyCallingPackage(String callingPackage, int callingUid) {
4032        int packageUid = mPm.getPackageUid(callingPackage, 0,  UserHandle.getUserId(callingUid));
4033        if (packageUid != callingUid) {
4034            throw new SecurityException("Specified package " + callingPackage
4035                    + " does not match the calling uid " + callingUid);
4036        }
4037    }
4038}
4039