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