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