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