blob: a65a18961509b96f5c8da2cfa2da14d001b613e9 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
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
Xiaohui Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070020import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070025import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070028import android.content.Context;
29import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080037import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070038import android.os.Environment;
39import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080040import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080042import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010043import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070044import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070046import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070047import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040048import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070049import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070050import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070051import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070052import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080053import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010054import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070055import android.os.storage.VolumeInfo;
56import android.system.ErrnoException;
57import android.system.Os;
58import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070059import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070060import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070061import android.util.Slog;
62import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080063import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070064import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import android.util.Xml;
66
Makoto Onuki068c54a2015-10-13 14:34:03 -070067import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070068import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040069import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080070import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070071import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070072import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070073import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080074
75import org.xmlpull.v1.XmlPullParser;
76import org.xmlpull.v1.XmlPullParserException;
77import org.xmlpull.v1.XmlSerializer;
78
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import java.io.BufferedOutputStream;
80import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070081import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070083import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import java.io.FileOutputStream;
85import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070086import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010087import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088import java.util.ArrayList;
89import java.util.List;
90
Fyodor Kupolov262f9952015-03-23 18:55:11 -070091import libcore.io.IoUtils;
92
Makoto Onuki068c54a2015-10-13 14:34:03 -070093/**
94 * Service for {@link UserManager}.
95 *
96 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -070097 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -080098 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -070099 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
100 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
101 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700102 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700103public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700104 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800105 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
106 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700107
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700110 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700112 private static final String ATTR_CREATION_TIME = "created";
113 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700114 private static final String ATTR_SERIAL_NO = "serialNumber";
115 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700116 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700117 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700118 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100119 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700120 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530121 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800124 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800125 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800126 private static final String TAG_ENTRY = "entry";
127 private static final String TAG_VALUE = "value";
128 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700129 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800130 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700131
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700132 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
133 private static final String ATTR_TYPE_STRING = "s";
134 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700135 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700136 private static final String ATTR_TYPE_BUNDLE = "B";
137 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700138
Amith Yamasani0b285492011-04-14 17:35:23 -0700139 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700140 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700141 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100142 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800144 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700145 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800146
Amith Yamasani634cf312012-10-04 17:34:21 -0700147 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700148 // We need to keep process uid within Integer.MAX_VALUE.
149 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700150
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700151 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700152
Amith Yamasani920ace02012-09-20 22:15:37 -0700153 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
154
Nicolas Prevotb8186812015-08-06 15:00:03 +0100155 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700156 // without first making sure that the rest of the framework is prepared for it.
157 private static final int MAX_MANAGED_PROFILES = 1;
158
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800159 static final int WRITE_USER_MSG = 1;
160 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530161
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700162 private static final String XATTR_SERIAL = "user.serial";
163
Dianne Hackborn4428e172012-08-24 17:43:05 -0700164 private final Context mContext;
165 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700166 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700167 // Short-term lock for internal state, when interaction/sync with PM is not required
168 private final Object mUsersLock = new Object();
169 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800171 private final Handler mHandler;
172
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173 private final File mUsersDir;
174 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700175
Fyodor Kupolov82402752015-10-28 14:54:51 -0700176 @GuardedBy("mUsersLock")
177 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700178
179 /**
180 * User restrictions set via UserManager. This doesn't include restrictions set by
181 * device owner / profile owners.
182 *
183 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
184 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
185 * maybe shared between {@link #mBaseUserRestrictions} and
186 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
187 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700188 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700189 */
190 @GuardedBy("mRestrictionsLock")
191 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
192
193 /**
194 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
195 * with device / profile owner restrictions. We'll initialize it lazily; use
196 * {@link #getEffectiveUserRestrictions} to access it.
197 *
198 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
199 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
200 * maybe shared between {@link #mBaseUserRestrictions} and
201 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
202 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700203 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700204 */
205 @GuardedBy("mRestrictionsLock")
206 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
207
Makoto Onuki4f160732015-10-27 17:15:38 -0700208 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800209 * User restrictions that have already been applied in
210 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
211 * that have changed since the last
212 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700213 */
214 @GuardedBy("mRestrictionsLock")
215 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
216
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800217 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800218 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
219 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800220 */
221 @GuardedBy("mRestrictionsLock")
222 private Bundle mDevicePolicyGlobalUserRestrictions;
223
224 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800225 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
226 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800227 */
228 @GuardedBy("mRestrictionsLock")
229 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
230
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800231 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530232 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800233
234 /**
235 * Set of user IDs being actively removed. Removed IDs linger in this set
236 * for several seconds to work around a VFS caching issue.
237 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700238 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800239 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700240
Fyodor Kupolov82402752015-10-28 14:54:51 -0700241 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700242 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800243 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700244 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700245 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700246
Jason Monk62062992014-05-06 09:55:28 -0400247 private IAppOpsService mAppOpsService;
248
Makoto Onuki068c54a2015-10-13 14:34:03 -0700249 private final LocalService mLocalService;
250
Makoto Onukie7927da2015-11-25 10:05:17 -0800251 @GuardedBy("mUsersLock")
252 private boolean mIsDeviceManaged;
253
254 @GuardedBy("mUsersLock")
255 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
256
Makoto Onukid45a4a22015-11-02 17:17:38 -0800257 @GuardedBy("mUserRestrictionsListeners")
258 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
259 new ArrayList<>();
260
Amith Yamasani258848d2012-08-10 17:06:33 -0700261 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700262
Dianne Hackborn4428e172012-08-24 17:43:05 -0700263 public static UserManagerService getInstance() {
264 synchronized (UserManagerService.class) {
265 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700266 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700268
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800269 @VisibleForTesting
270 UserManagerService(File dataDir) {
271 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700272 }
273
Dianne Hackborn4428e172012-08-24 17:43:05 -0700274 /**
275 * Called by package manager to create the service. This is closely
276 * associated with the package manager, and the given lock is the
277 * package manager's own lock.
278 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800279 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
280 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700281 }
282
Dianne Hackborn4428e172012-08-24 17:43:05 -0700283 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800284 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700285 mContext = context;
286 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700287 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800288 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800289 synchronized (mPackagesLock) {
290 mUsersDir = new File(dataDir, USER_INFO_DIR);
291 mUsersDir.mkdirs();
292 // Make zeroth user directory, for services to migrate their files to that location
293 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
294 userZeroDir.mkdirs();
295 FileUtils.setPermissions(mUsersDir.toString(),
296 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
297 -1, -1);
298 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
299 initDefaultGuestRestrictions();
300 readUserListLP();
301 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700302 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700303 mLocalService = new LocalService();
304 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700305 }
306
307 void systemReady() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800308 // Prune out any partially created/partially removed users.
309 ArrayList<UserInfo> partials = new ArrayList<>();
310 synchronized (mUsersLock) {
311 final int userSize = mUsers.size();
312 for (int i = 0; i < userSize; i++) {
313 UserInfo ui = mUsers.valueAt(i);
314 if ((ui.partial || ui.guestToRemove) && i != 0) {
315 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700316 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700317 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700318 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800319 final int partialsSize = partials.size();
320 for (int i = 0; i < partialsSize; i++) {
321 UserInfo ui = partials.get(i);
322 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
323 + " (name=" + ui.name + ")");
324 removeUserState(ui.id);
325 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800326
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700327 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800328
Jason Monk62062992014-05-06 09:55:28 -0400329 mAppOpsService = IAppOpsService.Stub.asInterface(
330 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800331
332 synchronized (mRestrictionsLock) {
333 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400334 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700335 }
336
337 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700338 public UserInfo getPrimaryUser() {
339 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700340 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700341 final int userSize = mUsers.size();
342 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700343 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800344 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700345 return ui;
346 }
347 }
348 }
349 return null;
350 }
351
352 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700353 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700354 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700355 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700356 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700357 final int userSize = mUsers.size();
358 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700359 UserInfo ui = mUsers.valueAt(i);
360 if (ui.partial) {
361 continue;
362 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800363 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700364 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700365 }
Amith Yamasani13593602012-03-22 16:16:17 -0700366 }
367 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700368 }
Amith Yamasani13593602012-03-22 16:16:17 -0700369 }
370
Amith Yamasani258848d2012-08-10 17:06:33 -0700371 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100372 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800373 if (userId != UserHandle.getCallingUserId()) {
374 checkManageUsersPermission("getting profiles related to user " + userId);
375 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700376 final long ident = Binder.clearCallingIdentity();
377 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700378 synchronized (mUsersLock) {
379 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100380 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700381 } finally {
382 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000383 }
384 }
385
Amith Yamasanibe465322014-04-24 13:45:17 -0700386 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700387 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
388 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700389 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700390 if (user == null) {
391 // Probably a dying user
392 return users;
393 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700394 final int userSize = mUsers.size();
395 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700396 UserInfo profile = mUsers.valueAt(i);
397 if (!isProfileOf(user, profile)) {
398 continue;
399 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100400 if (enabledOnly && !profile.isEnabled()) {
401 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700402 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700403 if (mRemovingUserIds.get(profile.id)) {
404 continue;
405 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700406 users.add(profile);
407 }
408 return users;
409 }
410
Jessica Hummelbe81c802014-04-22 15:49:22 +0100411 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700412 public int getCredentialOwnerProfile(int userHandle) {
413 checkManageUsersPermission("get the credential owner");
Jeff Sharkeyba512352015-11-12 20:17:45 -0800414 if (!StorageManager.isFileBasedEncryptionEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700415 synchronized (mUsersLock) {
416 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700417 if (profileParent != null) {
418 return profileParent.id;
419 }
420 }
421 }
422
423 return userHandle;
424 }
425
426 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700427 public boolean isSameProfileGroup(int userId, int otherUserId) {
428 if (userId == otherUserId) return true;
429 checkManageUsersPermission("check if in the same profile group");
430 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700431 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700432 }
433 }
434
Fyodor Kupolov82402752015-10-28 14:54:51 -0700435 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
436 synchronized (mUsersLock) {
437 UserInfo userInfo = getUserInfoLU(userId);
438 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
439 return false;
440 }
441 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
442 if (otherUserInfo == null
443 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
444 return false;
445 }
446 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700447 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700448 }
449
450 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100451 public UserInfo getProfileParent(int userHandle) {
452 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700453 synchronized (mUsersLock) {
454 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700455 }
456 }
457
Fyodor Kupolov82402752015-10-28 14:54:51 -0700458 private UserInfo getProfileParentLU(int userHandle) {
459 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700460 if (profile == null) {
461 return null;
462 }
463 int parentUserId = profile.profileGroupId;
464 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
465 return null;
466 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700467 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100468 }
469 }
470
Fyodor Kupolov82402752015-10-28 14:54:51 -0700471 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100472 return user.id == profile.id ||
473 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
474 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000475 }
476
477 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100478 public void setUserEnabled(int userId) {
479 checkManageUsersPermission("enable user");
480 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700481 UserInfo info;
482 synchronized (mUsersLock) {
483 info = getUserInfoLU(userId);
484 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100485 if (info != null && !info.isEnabled()) {
486 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700487 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100488 }
489 }
490 }
491
492 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700493 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700494 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700495 synchronized (mUsersLock) {
496 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700497 }
498 }
499
Amith Yamasani71e6c692013-03-24 17:39:28 -0700500 @Override
501 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700502 synchronized (mUsersLock) {
503 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700504 }
505 }
506
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700507 @Override
508 public boolean canHaveRestrictedProfile(int userId) {
509 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700510 synchronized (mUsersLock) {
511 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700512 if (userInfo == null || !userInfo.canHaveProfile()) {
513 return false;
514 }
515 if (!userInfo.isAdmin()) {
516 return false;
517 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800518 // restricted profile can be created if there is no DO set and the admin user has no PO;
519 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700520 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700521 }
522
Amith Yamasani195263742012-08-21 15:40:12 -0700523 /*
524 * Should be locked on mUsers before calling this.
525 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700526 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700527 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700528 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800529 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700530 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
531 return null;
532 }
533 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700534 }
535
Fyodor Kupolov82402752015-10-28 14:54:51 -0700536 /**
537 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
538 * <p>No permissions checking or any addition checks are made</p>
539 */
540 private UserInfo getUserInfoNoChecks(int userId) {
541 synchronized (mUsersLock) {
542 return mUsers.get(userId);
543 }
544 }
545
Amith Yamasani236b2b52015-08-18 14:32:14 -0700546 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700547 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700549 }
550
Amith Yamasani258848d2012-08-10 17:06:33 -0700551 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700552 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700553 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700554 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700555 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700557 if (info == null || info.partial) {
558 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
559 return;
560 }
Amith Yamasani13593602012-03-22 16:16:17 -0700561 if (name != null && !name.equals(info.name)) {
562 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700564 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700565 }
566 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700567 if (changed) {
568 sendUserInfoChangedBroadcast(userId);
569 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700570 }
571
Amith Yamasani258848d2012-08-10 17:06:33 -0700572 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700573 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700574 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400575 long ident = Binder.clearCallingIdentity();
576 try {
577 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700578 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400579 if (info == null || info.partial) {
580 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
581 return;
582 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700583 writeBitmapLP(info, bitmap);
584 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700585 }
Jason Monk9a944532014-07-08 09:31:21 -0400586 sendUserInfoChangedBroadcast(userId);
587 } finally {
588 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700589 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700590 }
591
592 private void sendUserInfoChangedBroadcast(int userId) {
593 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
594 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
595 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700596 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700597 }
598
Amith Yamasani258848d2012-08-10 17:06:33 -0700599 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100600 public ParcelFileDescriptor getUserIcon(int userId) {
601 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700602 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700603 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700604 if (info == null || info.partial) {
605 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
606 return null;
607 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700608 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100609 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
610 || callingGroupId != info.profileGroupId) {
611 checkManageUsersPermission("get the icon of a user who is not related");
612 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700613 if (info.iconPath == null) {
614 return null;
615 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100616 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700617 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100618
619 try {
620 return ParcelFileDescriptor.open(
621 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
622 } catch (FileNotFoundException e) {
623 Log.e(LOG_TAG, "Couldn't find icon file", e);
624 }
625 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700626 }
627
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700628 public void makeInitialized(int userId) {
629 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800630 boolean scheduleWriteUser = false;
631 UserInfo info;
632 synchronized (mUsersLock) {
633 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700634 if (info == null || info.partial) {
635 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800636 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700637 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800638 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700639 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800640 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700641 }
642 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800643 if (scheduleWriteUser) {
644 scheduleWriteUser(info);
645 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700646 }
647
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700648 /**
649 * If default guest restrictions haven't been initialized yet, add the basic
650 * restrictions.
651 */
652 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800653 synchronized (mGuestRestrictions) {
654 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800655 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800656 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
657 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
658 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700659 }
660 }
661
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800662 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530663 public Bundle getDefaultGuestRestrictions() {
664 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800665 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530666 return new Bundle(mGuestRestrictions);
667 }
668 }
669
670 @Override
671 public void setDefaultGuestRestrictions(Bundle restrictions) {
672 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800673 synchronized (mGuestRestrictions) {
674 mGuestRestrictions.clear();
675 mGuestRestrictions.putAll(restrictions);
676 }
677 synchronized (mPackagesLock) {
678 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530679 }
680 }
681
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800682 /**
683 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
684 */
685 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
686 @Nullable Bundle global) {
687 Preconditions.checkNotNull(local);
688 boolean globalChanged = false;
689 boolean localChanged;
690 synchronized (mRestrictionsLock) {
691 if (global != null) {
692 // Update global.
693 globalChanged = !UserRestrictionsUtils.areEqual(
694 mDevicePolicyGlobalUserRestrictions, global);
695 if (globalChanged) {
696 mDevicePolicyGlobalUserRestrictions = global;
697 }
698 }
699 {
700 // Update local.
701 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
702 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
703 if (localChanged) {
704 mDevicePolicyLocalUserRestrictions.put(userId, local);
705 }
706 }
707 }
708 if (DBG) {
709 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
710 + " global=" + global + (globalChanged ? " (changed)" : "")
711 + " local=" + local + (localChanged ? " (changed)" : "")
712 );
713 }
714 // Don't call them within the mRestrictionsLock.
715 synchronized (mPackagesLock) {
716 if (globalChanged) {
717 writeUserListLP();
718 }
719 if (localChanged) {
720 writeUserLP(getUserInfoNoChecks(userId));
721 }
722 }
723
724 synchronized (mRestrictionsLock) {
725 if (globalChanged) {
726 applyUserRestrictionsForAllUsersLR();
727 } else if (localChanged) {
728 applyUserRestrictionsLR(userId);
729 }
730 }
731 }
732
Makoto Onuki068c54a2015-10-13 14:34:03 -0700733 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700734 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800735 final Bundle baseRestrictions =
736 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
737 final Bundle global = mDevicePolicyGlobalUserRestrictions;
738 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700739
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800740 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
741 // Common case first.
742 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700743 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800744 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
745 UserRestrictionsUtils.merge(effective, global);
746 UserRestrictionsUtils.merge(effective, local);
747
Makoto Onuki068c54a2015-10-13 14:34:03 -0700748 return effective;
749 }
750
751 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700752 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700753 if (DBG) {
754 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
755 }
756 mCachedEffectiveUserRestrictions.remove(userId);
757 }
758
759 private Bundle getEffectiveUserRestrictions(int userId) {
760 synchronized (mRestrictionsLock) {
761 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
762 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700763 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700764 mCachedEffectiveUserRestrictions.put(userId, restrictions);
765 }
766 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700767 }
768 }
769
Makoto Onuki068c54a2015-10-13 14:34:03 -0700770 /** @return a specific user restriction that's in effect currently. */
771 @Override
772 public boolean hasUserRestriction(String restrictionKey, int userId) {
773 Bundle restrictions = getEffectiveUserRestrictions(userId);
774 return restrictions != null && restrictions.getBoolean(restrictionKey);
775 }
776
777 /**
778 * @return UserRestrictions that are in effect currently. This always returns a new
779 * {@link Bundle}.
780 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700781 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800782 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800783 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800784 }
785
786 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000787 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
788 checkManageUsersPermission("hasBaseUserRestriction");
789 synchronized (mRestrictionsLock) {
790 Bundle bundle = mBaseUserRestrictions.get(userId);
791 return (bundle != null && bundle.getBoolean(restrictionKey, false));
792 }
793 }
794
795 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700796 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700797 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700798 synchronized (mRestrictionsLock) {
799 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
800 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800801 final Bundle newRestrictions = UserRestrictionsUtils.clone(
802 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700803 newRestrictions.putBoolean(key, value);
804
Fyodor Kupolov82402752015-10-28 14:54:51 -0700805 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700806 }
807 }
808
Makoto Onuki068c54a2015-10-13 14:34:03 -0700809 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800810 * Optionally updating user restrictions, calculate the effective user restrictions and also
811 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700812 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800813 * @param newRestrictions User restrictions to set.
814 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700815 * @param userId target user ID.
816 */
817 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700818 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700819 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800820
821 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
822 mAppliedUserRestrictions.get(userId));
823
824 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700825 if (newRestrictions != null) {
826 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800827 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
828
829 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700830 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
831 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800832
833 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
834 mBaseUserRestrictions.put(userId, newRestrictions);
835 scheduleWriteUser(getUserInfoNoChecks(userId));
836 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700837 }
838
Fyodor Kupolov82402752015-10-28 14:54:51 -0700839 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700840
Makoto Onuki759a7632015-10-28 16:43:10 -0700841 mCachedEffectiveUserRestrictions.put(userId, effective);
842
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800843 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700844 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800845 debug("Applying user restrictions: userId=" + userId
846 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700847 }
848
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800849 if (mAppOpsService != null) { // We skip it until system-ready.
850 final long token = Binder.clearCallingIdentity();
851 try {
852 mAppOpsService.setUserRestrictions(effective, userId);
853 } catch (RemoteException e) {
854 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
855 } finally {
856 Binder.restoreCallingIdentity(token);
857 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700858 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700859
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800860 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700861
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800862 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700863 }
864
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800865 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800866 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800867 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
868 // actually, but we still need some kind of synchronization otherwise we might end up
869 // calling listeners out-of-order, thus "LR".
870
871 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
872 return;
873 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800874
875 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
876 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
877
878 mHandler.post(new Runnable() {
879 @Override
880 public void run() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800881 synchronized (mRestrictionsLock) {
882 UserRestrictionsUtils.applyUserRestrictionsLR(
883 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
884 }
885
Makoto Onukid45a4a22015-11-02 17:17:38 -0800886 final UserRestrictionsListener[] listeners;
887 synchronized (mUserRestrictionsListeners) {
888 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
889 mUserRestrictionsListeners.toArray(listeners);
890 }
891 for (int i = 0; i < listeners.length; i++) {
892 listeners[i].onUserRestrictionsChanged(userId,
893 newRestrictionsFinal, prevRestrictionsFinal);
894 }
895 }
896 });
897 }
898
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800899 // Package private for the inner class.
900 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700901 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700902 }
903
904 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800905 // Package private for the inner class.
906 void applyUserRestrictionsForAllUsersLR() {
907 if (DBG) {
908 debug("applyUserRestrictionsForAllUsersLR");
909 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700910 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700911 mCachedEffectiveUserRestrictions.clear();
912
Makoto Onuki068c54a2015-10-13 14:34:03 -0700913 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
914 // it on a handler.
915 final Runnable r = new Runnable() {
916 @Override
917 public void run() {
918 // Then get the list of running users.
919 final int[] runningUsers;
920 try {
921 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
922 } catch (RemoteException e) {
923 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
924 return;
925 }
926 // Then re-calculate the effective restrictions and apply, only for running users.
927 // It's okay if a new user has started after the getRunningUserIds() call,
928 // because we'll do the same thing (re-calculate the restrictions and apply)
929 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700930 synchronized (mRestrictionsLock) {
931 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800932 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700933 }
934 }
935 }
936 };
937 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700938 }
939
Amith Yamasani258848d2012-08-10 17:06:33 -0700940 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700941 * Check if we've hit the limit of how many users can be created.
942 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700943 private boolean isUserLimitReached() {
944 int count;
945 synchronized (mUsersLock) {
946 count = getAliveUsersExcludingGuestsCountLU();
947 }
948 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700949 }
950
951 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000952 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700953 checkManageUsersPermission("check if more managed profiles can be added.");
954 if (ActivityManager.isLowRamDeviceStatic()) {
955 return false;
956 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700957 if (!mContext.getPackageManager().hasSystemFeature(
958 PackageManager.FEATURE_MANAGED_USERS)) {
959 return false;
960 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100961 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000962 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
963 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
964 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100965 return false;
966 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700967 synchronized(mUsersLock) {
968 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100969 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700970 return false;
971 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000972 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
973 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -0700974 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000975 return usersCountAfterRemoving == 1
976 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700977 }
978 }
979
Fyodor Kupolov82402752015-10-28 14:54:51 -0700980 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700981 int aliveUserCount = 0;
982 final int totalUserCount = mUsers.size();
983 // Skip over users being removed
984 for (int i = 0; i < totalUserCount; i++) {
985 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700986 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700987 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700988 aliveUserCount++;
989 }
990 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700991 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700992 }
993
994 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700995 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700996 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700997 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700998 *
999 * @param message used as message if SecurityException is thrown
1000 * @throws SecurityException if the caller is not system or root
1001 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001002 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001003 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -07001004 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001005 && ActivityManager.checkComponentPermission(
1006 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001007 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1008 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1009 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001010 }
1011
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001012 private static void checkSystemOrRoot(String message) {
1013 final int uid = Binder.getCallingUid();
1014 if (uid != Process.SYSTEM_UID && uid != 0) {
1015 throw new SecurityException("Only system may call: " + message);
1016 }
1017 }
1018
Fyodor Kupolov82402752015-10-28 14:54:51 -07001019 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001020 try {
1021 File dir = new File(mUsersDir, Integer.toString(info.id));
1022 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001023 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001024 if (!dir.exists()) {
1025 dir.mkdir();
1026 FileUtils.setPermissions(
1027 dir.getPath(),
1028 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1029 -1, -1);
1030 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001031 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001032 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1033 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001034 info.iconPath = file.getAbsolutePath();
1035 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001036 try {
1037 os.close();
1038 } catch (IOException ioe) {
1039 // What the ... !
1040 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001041 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001042 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001043 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001044 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001045 }
1046
Amith Yamasani0b285492011-04-14 17:35:23 -07001047 /**
1048 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1049 * cache it elsewhere.
1050 * @return the array of user ids.
1051 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001052 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001053 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001054 return mUserIds;
1055 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001056 }
1057
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001058 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001059 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001060 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001061 return;
1062 }
1063 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001064 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001065 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001066 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001067 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001068 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001069 int type;
1070 while ((type = parser.next()) != XmlPullParser.START_TAG
1071 && type != XmlPullParser.END_DOCUMENT) {
1072 ;
1073 }
1074
1075 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001076 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001077 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001078 return;
1079 }
1080
Amith Yamasani2a003292012-08-14 18:25:45 -07001081 mNextSerialNumber = -1;
1082 if (parser.getName().equals(TAG_USERS)) {
1083 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1084 if (lastSerialNumber != null) {
1085 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1086 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001087 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1088 if (versionNumber != null) {
1089 mUserVersion = Integer.parseInt(versionNumber);
1090 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001091 }
1092
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001093 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1094
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001095 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301096 if (type == XmlPullParser.START_TAG) {
1097 final String name = parser.getName();
1098 if (name.equals(TAG_USER)) {
1099 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001100 UserInfo user = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001101
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301102 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001103 synchronized (mUsersLock) {
1104 mUsers.put(user.id, user);
1105 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1106 mNextSerialNumber = user.id + 1;
1107 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301108 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001109 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301110 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001111 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1112 && type != XmlPullParser.END_TAG) {
1113 if (type == XmlPullParser.START_TAG) {
1114 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001115 synchronized (mGuestRestrictions) {
1116 UserRestrictionsUtils
1117 .readRestrictions(parser, mGuestRestrictions);
1118 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001119 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1120 ) {
1121 UserRestrictionsUtils.readRestrictions(parser,
1122 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001123 }
1124 break;
1125 }
1126 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001127 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001128 }
1129 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001130 synchronized (mRestrictionsLock) {
1131 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1132 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001133 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001134 upgradeIfNecessaryLP();
1135 } catch (IOException | XmlPullParserException e) {
1136 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001137 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001138 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001139 }
1140 }
1141
Amith Yamasani6f34b412012-10-22 18:19:27 -07001142 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001143 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001144 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001145 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001146 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001147 int userVersion = mUserVersion;
1148 if (userVersion < 1) {
1149 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001150 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001151 if ("Primary".equals(user.name)) {
1152 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001153 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001154 }
1155 userVersion = 1;
1156 }
1157
Amith Yamasanibc9625052012-11-15 14:39:18 -08001158 if (userVersion < 2) {
1159 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001160 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001161 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1162 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001163 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001164 }
1165 userVersion = 2;
1166 }
1167
Amith Yamasani350962c2013-08-06 11:18:53 -07001168
Amith Yamasani5e486f52013-08-07 11:06:44 -07001169 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001170 userVersion = 4;
1171 }
1172
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001173 if (userVersion < 5) {
1174 initDefaultGuestRestrictions();
1175 userVersion = 5;
1176 }
1177
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001178 if (userVersion < 6) {
1179 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001180 synchronized (mUsersLock) {
1181 for (int i = 0; i < mUsers.size(); i++) {
1182 UserInfo user = mUsers.valueAt(i);
1183 // In non-split mode, only user 0 can have restricted profiles
1184 if (!splitSystemUser && user.isRestricted()
1185 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1186 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001187 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001188 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001189 }
1190 }
1191 userVersion = 6;
1192 }
1193
Amith Yamasani6f34b412012-10-22 18:19:27 -07001194 if (userVersion < USER_VERSION) {
1195 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1196 + USER_VERSION);
1197 } else {
1198 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001199
1200 if (originalVersion < mUserVersion) {
1201 writeUserListLP();
1202 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001203 }
1204 }
1205
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001206 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001207 int flags = UserInfo.FLAG_INITIALIZED;
1208 // In split system user mode, the admin and primary flags are assigned to the first human
1209 // user.
1210 if (!UserManager.isSplitSystemUser()) {
1211 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1212 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001213 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001214 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001215 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001216 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001217 synchronized (mUsersLock) {
1218 mUsers.put(system.id, system);
1219 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001220 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001221 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001222
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001223 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001224 synchronized (mRestrictionsLock) {
1225 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1226 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001227
Fyodor Kupolov82402752015-10-28 14:54:51 -07001228 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001229 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001230
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001231 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001232 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001233 }
1234
Makoto Onuki9e935a32015-11-06 14:24:24 -08001235 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001236 if (DBG) {
1237 debug("scheduleWriteUser");
1238 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001239 // No need to wrap it within a lock -- worst case, we'll just post the same message
1240 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001241 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1242 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1243 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1244 }
1245 }
1246
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001247 /*
1248 * Writes the user file in this format:
1249 *
1250 * <user flags="20039023" id="0">
1251 * <name>Primary</name>
1252 * </user>
1253 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001254 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001255 if (DBG) {
1256 debug("writeUserLP " + userInfo);
1257 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001258 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001259 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001260 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001261 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001262 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1263
1264 // XmlSerializer serializer = XmlUtils.serializerInstance();
1265 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001266 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001267 serializer.startDocument(null, true);
1268 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1269
1270 serializer.startTag(null, TAG_USER);
1271 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001272 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001273 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001274 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1275 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1276 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001277 if (userInfo.iconPath != null) {
1278 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1279 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001280 if (userInfo.partial) {
1281 serializer.attribute(null, ATTR_PARTIAL, "true");
1282 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001283 if (userInfo.guestToRemove) {
1284 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1285 }
Kenny Guy2a764942014-04-02 13:29:20 +01001286 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1287 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1288 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001289 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001290 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1291 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1292 Integer.toString(userInfo.restrictedProfileParentId));
1293 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001294 serializer.startTag(null, TAG_NAME);
1295 serializer.text(userInfo.name);
1296 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001297 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001298 UserRestrictionsUtils.writeRestrictions(serializer,
1299 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1300 UserRestrictionsUtils.writeRestrictions(serializer,
1301 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1302 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001303 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001304 serializer.endTag(null, TAG_USER);
1305
1306 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001307 userFile.finishWrite(fos);
1308 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001309 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001310 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001311 }
1312 }
1313
1314 /*
1315 * Writes the user list file in this format:
1316 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001317 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001318 * <user id="0"></user>
1319 * <user id="2"></user>
1320 * </users>
1321 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001322 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001323 if (DBG) {
1324 debug("writeUserList");
1325 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001326 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001327 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001328 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001329 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001330 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1331
1332 // XmlSerializer serializer = XmlUtils.serializerInstance();
1333 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001334 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001335 serializer.startDocument(null, true);
1336 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1337
1338 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001339 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001340 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001341
Adam Lesinskieddeb492014-09-08 17:50:03 -07001342 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001343 synchronized (mGuestRestrictions) {
1344 UserRestrictionsUtils
1345 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1346 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301347 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001348 synchronized (mRestrictionsLock) {
1349 UserRestrictionsUtils.writeRestrictions(serializer,
1350 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1351 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001352 int[] userIdsToWrite;
1353 synchronized (mUsersLock) {
1354 userIdsToWrite = new int[mUsers.size()];
1355 for (int i = 0; i < userIdsToWrite.length; i++) {
1356 UserInfo user = mUsers.valueAt(i);
1357 userIdsToWrite[i] = user.id;
1358 }
1359 }
1360 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001361 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001362 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001363 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001364 }
1365
1366 serializer.endTag(null, TAG_USERS);
1367
1368 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001369 userListFile.finishWrite(fos);
1370 } catch (Exception e) {
1371 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001372 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001373 }
1374 }
1375
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001376 private UserInfo readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001377 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001378 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001379 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001380 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001381 long creationTime = 0L;
1382 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001383 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001384 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001385 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001386 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001387 Bundle baseRestrictions = new Bundle();
1388 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001389
1390 FileInputStream fis = null;
1391 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001392 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001393 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001394 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001395 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001396 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001397 int type;
1398 while ((type = parser.next()) != XmlPullParser.START_TAG
1399 && type != XmlPullParser.END_DOCUMENT) {
1400 ;
1401 }
1402
1403 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001404 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001405 return null;
1406 }
1407
1408 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001409 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1410 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001411 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001412 return null;
1413 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001414 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1415 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001416 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001417 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1418 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001419 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1420 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001421 restrictedProfileParentId = readIntAttribute(parser,
1422 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001423 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1424 if ("true".equals(valueString)) {
1425 partial = true;
1426 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001427 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1428 if ("true".equals(valueString)) {
1429 guestToRemove = true;
1430 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001431
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001432 int outerDepth = parser.getDepth();
1433 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1434 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1435 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1436 continue;
1437 }
1438 String tag = parser.getName();
1439 if (TAG_NAME.equals(tag)) {
1440 type = parser.next();
1441 if (type == XmlPullParser.TEXT) {
1442 name = parser.getText();
1443 }
1444 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001445 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1446 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1447 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001448 }
1449 }
1450 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001451
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001452 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001453 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001454 userInfo.creationTime = creationTime;
1455 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001456 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001457 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001458 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001459 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001460 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001461 mBaseUserRestrictions.put(id, baseRestrictions);
1462 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001463 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001464 return userInfo;
1465
1466 } catch (IOException ioe) {
1467 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001468 } finally {
1469 if (fis != null) {
1470 try {
1471 fis.close();
1472 } catch (IOException e) {
1473 }
1474 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001475 }
1476 return null;
1477 }
1478
Amith Yamasani920ace02012-09-20 22:15:37 -07001479 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1480 String valueString = parser.getAttributeValue(null, attr);
1481 if (valueString == null) return defaultValue;
1482 try {
1483 return Integer.parseInt(valueString);
1484 } catch (NumberFormatException nfe) {
1485 return defaultValue;
1486 }
1487 }
1488
1489 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1490 String valueString = parser.getAttributeValue(null, attr);
1491 if (valueString == null) return defaultValue;
1492 try {
1493 return Long.parseLong(valueString);
1494 } catch (NumberFormatException nfe) {
1495 return defaultValue;
1496 }
1497 }
1498
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001499 private boolean isPackageInstalled(String pkg, int userId) {
1500 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1501 PackageManager.GET_UNINSTALLED_PACKAGES,
1502 userId);
1503 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1504 return false;
1505 }
1506 return true;
1507 }
1508
Amith Yamasanib82add22013-07-09 11:24:44 -07001509 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001510 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001511 * Does not do any permissions checking.
1512 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001513 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001514 synchronized (mPackagesLock) {
1515 File dir = Environment.getUserSystemDirectory(userId);
1516 String[] files = dir.list();
1517 if (files == null) return;
1518 for (String fileName : files) {
1519 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1520 File resFile = new File(dir, fileName);
1521 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001522 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001523 }
1524 }
1525 }
1526 }
1527 }
1528
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001529 /**
1530 * Removes the app restrictions file for a specific package and user id, if it exists.
1531 */
1532 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1533 synchronized (mPackagesLock) {
1534 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001535 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001536 if (resFile.exists()) {
1537 resFile.delete();
1538 }
1539 }
1540 }
1541
Kenny Guya52dc3e2014-02-11 15:33:14 +00001542 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001543 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001544 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001545 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001546 }
1547
Amith Yamasani258848d2012-08-10 17:06:33 -07001548 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001549 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001550 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001551 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001552 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001553
Jessica Hummelbe81c802014-04-22 15:49:22 +01001554 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001555 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001556 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1557 return null;
1558 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001559 if (ActivityManager.isLowRamDeviceStatic()) {
1560 return null;
1561 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001562 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001563 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001564 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001565 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001566 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001567 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001568 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001569 synchronized (mPackagesLock) {
1570 UserInfo parent = null;
1571 if (parentId != UserHandle.USER_NULL) {
1572 synchronized (mUsersLock) {
1573 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001574 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001575 if (parent == null) return null;
1576 }
1577 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1578 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1579 return null;
1580 }
1581 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1582 // If we're not adding a guest user or a managed profile and the limit has
1583 // been reached, cannot add a user.
1584 return null;
1585 }
1586 // If we're adding a guest and there already exists one, bail.
1587 if (isGuest && findCurrentGuestUser() != null) {
1588 return null;
1589 }
1590 // In legacy mode, restricted profile's parent can only be the owner user
1591 if (isRestricted && !UserManager.isSplitSystemUser()
1592 && (parentId != UserHandle.USER_SYSTEM)) {
1593 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1594 return null;
1595 }
1596 if (isRestricted && UserManager.isSplitSystemUser()) {
1597 if (parent == null) {
1598 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1599 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001600 return null;
1601 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001602 if (!parent.canHaveProfile()) {
1603 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1604 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001605 return null;
1606 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001607 }
1608 // In split system user mode, we assign the first human user the primary flag.
1609 // And if there is no device owner, we also assign the admin flag to primary user.
1610 if (UserManager.isSplitSystemUser()
1611 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1612 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001613 synchronized (mUsersLock) {
1614 if (!mIsDeviceManaged) {
1615 flags |= UserInfo.FLAG_ADMIN;
1616 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001617 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001618 }
1619 userId = getNextAvailableId();
1620 userInfo = new UserInfo(userId, name, null, flags);
1621 userInfo.serialNumber = mNextSerialNumber++;
1622 long now = System.currentTimeMillis();
1623 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1624 userInfo.partial = true;
1625 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1626 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001627 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001628 }
1629 writeUserListLP();
1630 if (parent != null) {
1631 if (isManagedProfile) {
1632 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1633 parent.profileGroupId = parent.id;
1634 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001635 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001636 userInfo.profileGroupId = parent.profileGroupId;
1637 } else if (isRestricted) {
1638 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1639 parent.restrictedProfileParentId = parent.id;
1640 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001641 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001642 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001643 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001644 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001645 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001646 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1647 storage.createUserKey(userId, userInfo.serialNumber);
1648 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1649 final String volumeUuid = vol.getFsUuid();
1650 try {
1651 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1652 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1653 enforceSerialNumber(userDir, userInfo.serialNumber);
1654 } catch (IOException e) {
1655 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1656 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001657 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001658 mPm.createNewUser(userId);
1659 userInfo.partial = false;
1660 synchronized (mPackagesLock) {
1661 writeUserLP(userInfo);
1662 }
1663 updateUserIds();
1664 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001665 if (isGuest) {
1666 synchronized (mGuestRestrictions) {
1667 restrictions.putAll(mGuestRestrictions);
1668 }
1669 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001670 synchronized (mRestrictionsLock) {
1671 mBaseUserRestrictions.append(userId, restrictions);
1672 }
1673 mPm.newUserCreated(userId);
1674 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1675 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1676 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1677 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001678 } finally {
1679 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001680 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001681 return userInfo;
1682 }
1683
Amith Yamasani0b285492011-04-14 17:35:23 -07001684 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001685 * @hide
1686 */
1687 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1688 checkManageUsersPermission("setupRestrictedProfile");
1689 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1690 if (user == null) {
1691 return null;
1692 }
1693 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1694 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1695 // the putIntForUser() will fail.
1696 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1697 android.provider.Settings.Secure.LOCATION_MODE,
1698 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1699 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1700 return user;
1701 }
1702
1703 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001704 * Find the current guest user. If the Guest user is partial,
1705 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001706 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001707 private UserInfo findCurrentGuestUser() {
1708 synchronized (mUsersLock) {
1709 final int size = mUsers.size();
1710 for (int i = 0; i < size; i++) {
1711 final UserInfo user = mUsers.valueAt(i);
1712 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1713 return user;
1714 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001715 }
1716 }
1717 return null;
1718 }
1719
1720 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001721 * Mark this guest user for deletion to allow us to create another guest
1722 * and switch to that user before actually removing this guest.
1723 * @param userHandle the userid of the current guest
1724 * @return whether the user could be marked for deletion
1725 */
1726 public boolean markGuestForDeletion(int userHandle) {
1727 checkManageUsersPermission("Only the system can remove users");
1728 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1729 UserManager.DISALLOW_REMOVE_USER, false)) {
1730 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1731 return false;
1732 }
1733
1734 long ident = Binder.clearCallingIdentity();
1735 try {
1736 final UserInfo user;
1737 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001738 synchronized (mUsersLock) {
1739 user = mUsers.get(userHandle);
1740 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1741 return false;
1742 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001743 }
1744 if (!user.isGuest()) {
1745 return false;
1746 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001747 // We set this to a guest user that is to be removed. This is a temporary state
1748 // where we are allowed to add new Guest users, even if this one is still not
1749 // removed. This user will still show up in getUserInfo() calls.
1750 // If we don't get around to removing this Guest user, it will be purged on next
1751 // startup.
1752 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001753 // Mark it as disabled, so that it isn't returned any more when
1754 // profiles are queried.
1755 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001756 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001757 }
1758 } finally {
1759 Binder.restoreCallingIdentity(ident);
1760 }
1761 return true;
1762 }
1763
1764 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001765 * Removes a user and all data directories created for that user. This method should be called
1766 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001767 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001768 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001769 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001770 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001771 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1772 UserManager.DISALLOW_REMOVE_USER, false)) {
1773 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1774 return false;
1775 }
1776
Kenny Guyee58b4f2014-05-23 15:19:53 +01001777 long ident = Binder.clearCallingIdentity();
1778 try {
1779 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001780 int currentUser = ActivityManager.getCurrentUser();
1781 if (currentUser == userHandle) {
1782 Log.w(LOG_TAG, "Current user cannot be removed");
1783 return false;
1784 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001785 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001786 synchronized (mUsersLock) {
1787 user = mUsers.get(userHandle);
1788 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1789 return false;
1790 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001791
Fyodor Kupolov82402752015-10-28 14:54:51 -07001792 // We remember deleted user IDs to prevent them from being
1793 // reused during the current boot; they can still be reused
1794 // after a reboot.
1795 mRemovingUserIds.put(userHandle, true);
1796 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001797
Kenny Guyee58b4f2014-05-23 15:19:53 +01001798 try {
1799 mAppOpsService.removeUser(userHandle);
1800 } catch (RemoteException e) {
1801 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1802 }
1803 // Set this to a partially created user, so that the user will be purged
1804 // on next startup, in case the runtime stops now before stopping and
1805 // removing the user completely.
1806 user.partial = true;
1807 // Mark it as disabled, so that it isn't returned any more when
1808 // profiles are queried.
1809 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001810 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001811 }
1812
1813 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1814 && user.isManagedProfile()) {
1815 // Send broadcast to notify system that the user removed was a
1816 // managed user.
1817 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1818 }
1819
1820 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1821 int res;
1822 try {
1823 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1824 new IStopUserCallback.Stub() {
1825 @Override
1826 public void userStopped(int userId) {
1827 finishRemoveUser(userId);
1828 }
1829 @Override
1830 public void userStopAborted(int userId) {
1831 }
1832 });
1833 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001834 return false;
1835 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001836 return res == ActivityManager.USER_OP_SUCCESS;
1837 } finally {
1838 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001839 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001840 }
1841
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001842 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001843 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001844 // Let other services shutdown any activity and clean up their state before completely
1845 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001846 long ident = Binder.clearCallingIdentity();
1847 try {
1848 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1849 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001850 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1851 android.Manifest.permission.MANAGE_USERS,
1852
1853 new BroadcastReceiver() {
1854 @Override
1855 public void onReceive(Context context, Intent intent) {
1856 if (DBG) {
1857 Slog.i(LOG_TAG,
1858 "USER_REMOVED broadcast sent, cleaning up user data "
1859 + userHandle);
1860 }
1861 new Thread() {
1862 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001863 // Clean up any ActivityManager state
1864 LocalServices.getService(ActivityManagerInternal.class)
1865 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001866 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001867 }
1868 }.start();
1869 }
1870 },
1871
1872 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001873 } finally {
1874 Binder.restoreCallingIdentity(ident);
1875 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001876 }
1877
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001878 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001879 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001880 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001881 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001882
1883 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001884 synchronized (mUsersLock) {
1885 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08001886 mIsUserManaged.delete(userHandle);
1887 }
1888 synchronized (mRestrictionsLock) {
1889 mBaseUserRestrictions.remove(userHandle);
1890 mAppliedUserRestrictions.remove(userHandle);
1891 mCachedEffectiveUserRestrictions.remove(userHandle);
1892 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001893 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001894 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001895 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001896 userFile.delete();
1897 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001898 synchronized (mPackagesLock) {
1899 writeUserListLP();
1900 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001901 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001902 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1903 }
1904
Amith Yamasani61f57372012-08-31 12:12:28 -07001905 private void removeDirectoryRecursive(File parent) {
1906 if (parent.isDirectory()) {
1907 String[] files = parent.list();
1908 for (String filename : files) {
1909 File child = new File(parent, filename);
1910 removeDirectoryRecursive(child);
1911 }
1912 }
1913 parent.delete();
1914 }
1915
Kenny Guyf8d3a232014-05-15 16:09:52 +01001916 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001917 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001918 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1919 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001920 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1921 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001922 }
1923
Amith Yamasani2a003292012-08-14 18:25:45 -07001924 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001925 public Bundle getApplicationRestrictions(String packageName) {
1926 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1927 }
1928
1929 @Override
1930 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001931 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001932 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001933 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001934 }
1935 synchronized (mPackagesLock) {
1936 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001937 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001938 }
1939 }
1940
1941 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001942 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001943 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001944 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001945 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001946 if (restrictions == null || restrictions.isEmpty()) {
1947 cleanAppRestrictionsForPackage(packageName, userId);
1948 } else {
1949 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001950 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001951 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001952 }
Robin Lee66e5d962014-04-09 16:44:21 +01001953
Kenny Guyd21b2182014-07-17 16:38:55 +01001954 if (isPackageInstalled(packageName, userId)) {
1955 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1956 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1957 changeIntent.setPackage(packageName);
1958 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1959 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1960 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001961 }
1962
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001963 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001964 mHandler.post(new Runnable() {
1965 @Override
1966 public void run() {
1967 List<ApplicationInfo> apps =
1968 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1969 userHandle).getList();
1970 final long ident = Binder.clearCallingIdentity();
1971 try {
1972 for (ApplicationInfo appInfo : apps) {
1973 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001974 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1975 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001976 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001977 userHandle);
1978 }
1979 }
1980 } finally {
1981 Binder.restoreCallingIdentity(ident);
1982 }
1983 }
1984 });
1985 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001986 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001987 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001988 try {
1989 return mContext.getPackageManager().getApplicationInfo(packageName,
1990 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1991 } catch (NameNotFoundException nnfe) {
1992 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001993 } finally {
1994 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001995 }
1996 }
1997
Fyodor Kupolov82402752015-10-28 14:54:51 -07001998 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001999 AtomicFile restrictionsFile =
2000 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2001 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002002 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002003 }
2004
2005 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002006 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002007 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002008 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002009 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002010 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002011 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002012
2013 FileInputStream fis = null;
2014 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002015 fis = restrictionsFile.openRead();
2016 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002017 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002018 XmlUtils.nextElement(parser);
2019 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002020 Slog.e(LOG_TAG, "Unable to read restrictions file "
2021 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002022 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002023 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002024 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2025 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002026 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002027 } catch (IOException|XmlPullParserException e) {
2028 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002029 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002030 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002031 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002032 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002033 }
2034
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002035 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2036 XmlPullParser parser) throws XmlPullParserException, IOException {
2037 int type = parser.getEventType();
2038 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2039 String key = parser.getAttributeValue(null, ATTR_KEY);
2040 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2041 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2042 if (multiple != null) {
2043 values.clear();
2044 int count = Integer.parseInt(multiple);
2045 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2046 if (type == XmlPullParser.START_TAG
2047 && parser.getName().equals(TAG_VALUE)) {
2048 values.add(parser.nextText().trim());
2049 count--;
2050 }
2051 }
2052 String [] valueStrings = new String[values.size()];
2053 values.toArray(valueStrings);
2054 restrictions.putStringArray(key, valueStrings);
2055 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2056 restrictions.putBundle(key, readBundleEntry(parser, values));
2057 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2058 final int outerDepth = parser.getDepth();
2059 ArrayList<Bundle> bundleList = new ArrayList<>();
2060 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2061 Bundle childBundle = readBundleEntry(parser, values);
2062 bundleList.add(childBundle);
2063 }
2064 restrictions.putParcelableArray(key,
2065 bundleList.toArray(new Bundle[bundleList.size()]));
2066 } else {
2067 String value = parser.nextText().trim();
2068 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2069 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2070 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2071 restrictions.putInt(key, Integer.parseInt(value));
2072 } else {
2073 restrictions.putString(key, value);
2074 }
2075 }
2076 }
2077 }
2078
2079 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2080 throws IOException, XmlPullParserException {
2081 Bundle childBundle = new Bundle();
2082 final int outerDepth = parser.getDepth();
2083 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2084 readEntry(childBundle, values, parser);
2085 }
2086 return childBundle;
2087 }
2088
Fyodor Kupolov82402752015-10-28 14:54:51 -07002089 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002090 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002091 AtomicFile restrictionsFile = new AtomicFile(
2092 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002093 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002094 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002095 }
2096
2097 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002098 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002099 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002100 try {
2101 fos = restrictionsFile.startWrite();
2102 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2103
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002104 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002105 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002106 serializer.startDocument(null, true);
2107 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2108
2109 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002110 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002111 serializer.endTag(null, TAG_RESTRICTIONS);
2112
2113 serializer.endDocument();
2114 restrictionsFile.finishWrite(fos);
2115 } catch (Exception e) {
2116 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002117 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2118 }
2119 }
2120
2121 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2122 throws IOException {
2123 for (String key : restrictions.keySet()) {
2124 Object value = restrictions.get(key);
2125 serializer.startTag(null, TAG_ENTRY);
2126 serializer.attribute(null, ATTR_KEY, key);
2127
2128 if (value instanceof Boolean) {
2129 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2130 serializer.text(value.toString());
2131 } else if (value instanceof Integer) {
2132 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2133 serializer.text(value.toString());
2134 } else if (value == null || value instanceof String) {
2135 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2136 serializer.text(value != null ? (String) value : "");
2137 } else if (value instanceof Bundle) {
2138 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2139 writeBundle((Bundle) value, serializer);
2140 } else if (value instanceof Parcelable[]) {
2141 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2142 Parcelable[] array = (Parcelable[]) value;
2143 for (Parcelable parcelable : array) {
2144 if (!(parcelable instanceof Bundle)) {
2145 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2146 }
2147 serializer.startTag(null, TAG_ENTRY);
2148 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2149 writeBundle((Bundle) parcelable, serializer);
2150 serializer.endTag(null, TAG_ENTRY);
2151 }
2152 } else {
2153 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2154 String[] values = (String[]) value;
2155 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2156 for (String choice : values) {
2157 serializer.startTag(null, TAG_VALUE);
2158 serializer.text(choice != null ? choice : "");
2159 serializer.endTag(null, TAG_VALUE);
2160 }
2161 }
2162 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002163 }
2164 }
2165
2166 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002167 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002168 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002169 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002170 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002171 }
2172 }
2173
2174 @Override
2175 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002176 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002177 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002178 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002179 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002180 }
2181 // Not found
2182 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002183 }
2184 }
2185
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002186 @Override
2187 public long getUserCreationTime(int userHandle) {
2188 int callingUserId = UserHandle.getCallingUserId();
2189 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002190 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002191 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002192 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002193 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002194 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002195 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002196 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002197 }
2198 }
2199 }
2200 if (userInfo == null) {
2201 throw new SecurityException("userHandle can only be the calling user or a managed "
2202 + "profile associated with this user");
2203 }
2204 return userInfo.creationTime;
2205 }
2206
Amith Yamasani0b285492011-04-14 17:35:23 -07002207 /**
2208 * Caches the list of user ids in an array, adjusting the array size when necessary.
2209 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002210 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002211 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002212 synchronized (mUsersLock) {
2213 final int userSize = mUsers.size();
2214 for (int i = 0; i < userSize; i++) {
2215 if (!mUsers.valueAt(i).partial) {
2216 num++;
2217 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002218 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002219 final int[] newUsers = new int[num];
2220 int n = 0;
2221 for (int i = 0; i < userSize; i++) {
2222 if (!mUsers.valueAt(i).partial) {
2223 newUsers[n++] = mUsers.keyAt(i);
2224 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002225 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002226 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002227 }
2228 }
2229
2230 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002231 * Called right before a user starts. This will not be called for the system user.
2232 */
2233 public void onBeforeStartUser(int userId) {
2234 synchronized (mRestrictionsLock) {
2235 applyUserRestrictionsLR(userId);
2236 }
2237 }
2238
2239 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002240 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002241 * @param userId the user that was just foregrounded
2242 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002243 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002244 UserInfo user = getUserInfoNoChecks(userId);
2245 if (user == null || user.partial) {
2246 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2247 return;
2248 }
2249 long now = System.currentTimeMillis();
2250 if (now > EPOCH_PLUS_30_YEARS) {
2251 user.lastLoggedInTime = now;
2252 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002253 }
2254 }
2255
2256 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002257 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002258 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2259 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002260 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002261 private int getNextAvailableId() {
2262 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002263 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002264 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002265 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002266 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002267 }
2268 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002269 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002270 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002271 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002272 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002273
Amith Yamasanifc95e702013-09-26 13:20:17 -07002274 private String packageToRestrictionsFileName(String packageName) {
2275 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2276 }
2277
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002278 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002279 * Enforce that serial number stored in user directory inode matches the
2280 * given expected value. Gracefully sets the serial number if currently
2281 * undefined.
2282 *
2283 * @throws IOException when problem extracting serial number, or serial
2284 * number is mismatched.
2285 */
2286 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2287 final int foundSerial = getSerialNumber(file);
2288 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2289
2290 if (foundSerial == -1) {
2291 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2292 try {
2293 setSerialNumber(file, serialNumber);
2294 } catch (IOException e) {
2295 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2296 }
2297
2298 } else if (foundSerial != serialNumber) {
2299 throw new IOException("Found serial number " + foundSerial
2300 + " doesn't match expected " + serialNumber);
2301 }
2302 }
2303
2304 /**
2305 * Set serial number stored in user directory inode.
2306 *
2307 * @throws IOException if serial number was already set
2308 */
2309 private static void setSerialNumber(File file, int serialNumber)
2310 throws IOException {
2311 try {
2312 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2313 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2314 } catch (ErrnoException e) {
2315 throw e.rethrowAsIOException();
2316 }
2317 }
2318
2319 /**
2320 * Return serial number stored in user directory inode.
2321 *
2322 * @return parsed serial number, or -1 if not set
2323 */
2324 private static int getSerialNumber(File file) throws IOException {
2325 try {
2326 final byte[] buf = new byte[256];
2327 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2328 final String serial = new String(buf, 0, len);
2329 try {
2330 return Integer.parseInt(serial);
2331 } catch (NumberFormatException e) {
2332 throw new IOException("Bad serial number: " + serial);
2333 }
2334 } catch (ErrnoException e) {
2335 if (e.errno == OsConstants.ENODATA) {
2336 return -1;
2337 } else {
2338 throw e.rethrowAsIOException();
2339 }
2340 }
2341 }
2342
Amith Yamasani920ace02012-09-20 22:15:37 -07002343 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002344 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2345 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2346 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2347 }
2348
2349 int onShellCommand(Shell shell, String cmd) {
2350 if (cmd == null) {
2351 return shell.handleDefaultCommands(cmd);
2352 }
2353
2354 final PrintWriter pw = shell.getOutPrintWriter();
2355 try {
2356 switch(cmd) {
2357 case "list":
2358 return runList(pw);
2359 }
2360 } catch (RemoteException e) {
2361 pw.println("Remote exception: " + e);
2362 }
2363 return -1;
2364 }
2365
2366 private int runList(PrintWriter pw) throws RemoteException {
2367 final IActivityManager am = ActivityManagerNative.getDefault();
2368 final List<UserInfo> users = getUsers(false);
2369 if (users == null) {
2370 pw.println("Error: couldn't get users");
2371 return 1;
2372 } else {
2373 pw.println("Users:");
2374 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002375 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002376 pw.println("\t" + users.get(i).toString() + running);
2377 }
2378 return 0;
2379 }
2380 }
2381
2382 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002383 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2384 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2385 != PackageManager.PERMISSION_GRANTED) {
2386 pw.println("Permission Denial: can't dump UserManager from from pid="
2387 + Binder.getCallingPid()
2388 + ", uid=" + Binder.getCallingUid()
2389 + " without permission "
2390 + android.Manifest.permission.DUMP);
2391 return;
2392 }
2393
2394 long now = System.currentTimeMillis();
2395 StringBuilder sb = new StringBuilder();
2396 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002397 synchronized (mUsersLock) {
2398 pw.println("Users:");
2399 for (int i = 0; i < mUsers.size(); i++) {
2400 UserInfo user = mUsers.valueAt(i);
2401 if (user == null) {
2402 continue;
2403 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002404 final int userId = user.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002405 pw.print(" "); pw.print(user);
2406 pw.print(" serialNo="); pw.print(user.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002407 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002408 pw.print(" <removing> ");
2409 }
2410 if (user.partial) {
2411 pw.print(" <partial>");
2412 }
2413 pw.println();
2414 pw.print(" Created: ");
2415 if (user.creationTime == 0) {
2416 pw.println("<unknown>");
2417 } else {
2418 sb.setLength(0);
2419 TimeUtils.formatDuration(now - user.creationTime, sb);
2420 sb.append(" ago");
2421 pw.println(sb);
2422 }
2423 pw.print(" Last logged in: ");
2424 if (user.lastLoggedInTime == 0) {
2425 pw.println("<unknown>");
2426 } else {
2427 sb.setLength(0);
2428 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2429 sb.append(" ago");
2430 pw.println(sb);
2431 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002432 pw.print(" Has profile owner: ");
2433 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002434 pw.println(" Restrictions:");
2435 synchronized (mRestrictionsLock) {
2436 UserRestrictionsUtils.dumpRestrictions(
2437 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002438 pw.println(" Device policy local restrictions:");
2439 UserRestrictionsUtils.dumpRestrictions(
2440 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002441 pw.println(" Effective restrictions:");
2442 UserRestrictionsUtils.dumpRestrictions(
2443 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2444 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002445 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002446 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002447 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002448 pw.println(" Device policy global restrictions:");
2449 synchronized (mRestrictionsLock) {
2450 UserRestrictionsUtils
2451 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2452 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002453 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002454 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002455 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002456 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002457 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002458 synchronized (mUsersLock) {
2459 pw.println();
2460 pw.println(" Device managed: " + mIsDeviceManaged);
2461 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002462 }
2463 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002464
2465 final class MainHandler extends Handler {
2466
2467 @Override
2468 public void handleMessage(Message msg) {
2469 switch (msg.what) {
2470 case WRITE_USER_MSG:
2471 removeMessages(WRITE_USER_MSG, msg.obj);
2472 synchronized (mPackagesLock) {
2473 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002474 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002475 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002476 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002477 }
2478 }
2479 }
2480 }
2481 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002482
2483 /**
2484 * @param userId
2485 * @return whether the user has been initialized yet
2486 */
2487 boolean isInitialized(int userId) {
2488 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2489 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002490
2491 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002492 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002493 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2494 @Nullable Bundle globalRestrictions) {
2495 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2496 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002497 }
2498
2499 @Override
2500 public Bundle getBaseUserRestrictions(int userId) {
2501 synchronized (mRestrictionsLock) {
2502 return mBaseUserRestrictions.get(userId);
2503 }
2504 }
2505
2506 @Override
2507 public void setBaseUserRestrictionsByDpmsForMigration(
2508 int userId, Bundle baseRestrictions) {
2509 synchronized (mRestrictionsLock) {
2510 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002511 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002512 }
2513
Fyodor Kupolov82402752015-10-28 14:54:51 -07002514 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002515 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002516 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002517 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002518 } else {
2519 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2520 }
2521 }
2522 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002523
2524 @Override
2525 public boolean getUserRestriction(int userId, String key) {
2526 return getUserRestrictions(userId).getBoolean(key);
2527 }
2528
2529 @Override
2530 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2531 synchronized (mUserRestrictionsListeners) {
2532 mUserRestrictionsListeners.add(listener);
2533 }
2534 }
2535
2536 @Override
2537 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2538 synchronized (mUserRestrictionsListeners) {
2539 mUserRestrictionsListeners.remove(listener);
2540 }
2541 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002542
2543 @Override
2544 public void setDeviceManaged(boolean isManaged) {
2545 synchronized (mUsersLock) {
2546 mIsDeviceManaged = isManaged;
2547 }
2548 }
2549
2550 @Override
2551 public void setUserManaged(int userId, boolean isManaged) {
2552 synchronized (mUsersLock) {
2553 mIsUserManaged.put(userId, isManaged);
2554 }
2555 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002556 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002557
2558 private class Shell extends ShellCommand {
2559 @Override
2560 public int onCommand(String cmd) {
2561 return onShellCommand(this, cmd);
2562 }
2563
2564 @Override
2565 public void onHelp() {
2566 final PrintWriter pw = getOutPrintWriter();
2567 pw.println("User manager (user) commands:");
2568 pw.println(" help");
2569 pw.println(" Print this help text.");
2570 pw.println("");
2571 pw.println(" list");
2572 pw.println(" Prints all users on the system.");
2573 }
2574 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002575
2576 private static void debug(String message) {
2577 Log.d(LOG_TAG, message +
2578 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2579 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002580}