blob: 1924bab6fac64f6b0ae073b05bd51d55c5db5214 [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;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070020import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070021import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070022import android.app.ActivityManagerNative;
23import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070024import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070025import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070026import android.content.Context;
27import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070028import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070029import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080030import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070031import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070032import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070033import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080034import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.os.Environment;
36import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080037import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070038import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080039import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010040import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070041import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070043import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040044import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070045import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070046import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010047import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070048import android.os.storage.VolumeInfo;
49import android.system.ErrnoException;
50import android.system.Os;
51import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070052import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070053import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070054import android.util.Slog;
55import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080056import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070057import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070058import android.util.Xml;
59
Fyodor Kupolovb5013302015-04-17 17:59:14 -070060import com.google.android.collect.Sets;
61
Fyodor Kupolov262f9952015-03-23 18:55:11 -070062import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040063import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080064import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070065import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080066
67import org.xmlpull.v1.XmlPullParser;
68import org.xmlpull.v1.XmlPullParserException;
69import org.xmlpull.v1.XmlSerializer;
70
Amith Yamasani4b2e9342011-03-31 12:38:53 -070071import java.io.BufferedOutputStream;
72import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070073import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070075import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076import java.io.FileOutputStream;
77import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070078import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010079import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.util.ArrayList;
81import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070082import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083
Fyodor Kupolov262f9952015-03-23 18:55:11 -070084import libcore.io.IoUtils;
85
Amith Yamasani258848d2012-08-10 17:06:33 -070086public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070087
Amith Yamasani2a003292012-08-14 18:25:45 -070088 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089
Amith Yamasani16389312012-10-17 21:20:14 -070090 private static final boolean DBG = false;
91
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070094 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070096 private static final String ATTR_CREATION_TIME = "created";
97 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070098 private static final String ATTR_SERIAL_NO = "serialNumber";
99 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700100 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700101 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700102 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100103 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700104 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530105 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800108 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800109 private static final String TAG_ENTRY = "entry";
110 private static final String TAG_VALUE = "value";
111 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700112 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800113 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700115 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
116 private static final String ATTR_TYPE_STRING = "s";
117 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700118 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700119 private static final String ATTR_TYPE_BUNDLE = "B";
120 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700121
Amith Yamasani0b285492011-04-14 17:35:23 -0700122 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700124 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100125 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700128 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800129
Amith Yamasani634cf312012-10-04 17:34:21 -0700130 private static final int MIN_USER_ID = 10;
131
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700132 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700133
Amith Yamasani920ace02012-09-20 22:15:37 -0700134 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
135
Nicolas Prevotb8186812015-08-06 15:00:03 +0100136 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700137 // without first making sure that the rest of the framework is prepared for it.
138 private static final int MAX_MANAGED_PROFILES = 1;
139
Andres Moralesc5548c02015-08-05 10:23:12 -0700140 /**
141 * Flag indicating whether device credentials are shared among same-user profiles.
142 */
143 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
144
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700145 // Set of user restrictions, which can only be enforced by the system
146 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
147 UserManager.DISALLOW_RECORD_AUDIO);
148
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800149 static final int WRITE_USER_MSG = 1;
150 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530151
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700152 private static final String XATTR_SERIAL = "user.serial";
153
Dianne Hackborn4428e172012-08-24 17:43:05 -0700154 private final Context mContext;
155 private final PackageManagerService mPm;
156 private final Object mInstallLock;
157 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700158
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800159 private final Handler mHandler;
160
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private final File mUsersDir;
162 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700163
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800164 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800165 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530166 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800167
168 /**
169 * Set of user IDs being actively removed. Removed IDs linger in this set
170 * for several seconds to work around a VFS caching issue.
171 */
172 // @GuardedBy("mPackagesLock")
173 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700174
Amith Yamasani0b285492011-04-14 17:35:23 -0700175 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700176 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700177 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700178
Jason Monk62062992014-05-06 09:55:28 -0400179 private IAppOpsService mAppOpsService;
180
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700182
Dianne Hackborn4428e172012-08-24 17:43:05 -0700183 public static UserManagerService getInstance() {
184 synchronized (UserManagerService.class) {
185 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700186 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700187 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188
189 /**
190 * Available for testing purposes.
191 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700192 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700193 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700194 }
195
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 /**
197 * Called by package manager to create the service. This is closely
198 * associated with the package manager, and the given lock is the
199 * package manager's own lock.
200 */
201 UserManagerService(Context context, PackageManagerService pm,
202 Object installLock, Object packagesLock) {
203 this(context, pm, installLock, packagesLock,
204 Environment.getDataDirectory(),
205 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700206 }
207
Dianne Hackborn4428e172012-08-24 17:43:05 -0700208 /**
209 * Available for testing purposes.
210 */
211 private UserManagerService(Context context, PackageManagerService pm,
212 Object installLock, Object packagesLock,
213 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700214 mContext = context;
215 mPm = pm;
216 mInstallLock = installLock;
217 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800218 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 synchronized (mInstallLock) {
220 synchronized (mPackagesLock) {
221 mUsersDir = new File(dataDir, USER_INFO_DIR);
222 mUsersDir.mkdirs();
223 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700224 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700225 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700226 FileUtils.setPermissions(mUsersDir.toString(),
227 FileUtils.S_IRWXU|FileUtils.S_IRWXG
228 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
229 -1, -1);
230 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800231 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700232 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700233 sInstance = this;
234 }
235 }
236 }
237
238 void systemReady() {
239 synchronized (mInstallLock) {
240 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700241 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700242 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
243 for (int i = 0; i < mUsers.size(); i++) {
244 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700245 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700246 partials.add(ui);
247 }
248 }
249 for (int i = 0; i < partials.size(); i++) {
250 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700251 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700252 + " (name=" + ui.name + ")");
253 removeUserStateLocked(ui.id);
254 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700256 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700257 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400258 mAppOpsService = IAppOpsService.Stub.asInterface(
259 ServiceManager.getService(Context.APP_OPS_SERVICE));
260 for (int i = 0; i < mUserIds.length; ++i) {
261 try {
262 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
263 } catch (RemoteException e) {
264 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
265 }
266 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 }
268
269 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700270 public UserInfo getPrimaryUser() {
271 checkManageUsersPermission("query users");
272 synchronized (mPackagesLock) {
273 for (int i = 0; i < mUsers.size(); i++) {
274 UserInfo ui = mUsers.valueAt(i);
275 if (ui.isPrimary()) {
276 return ui;
277 }
278 }
279 }
280 return null;
281 }
282
283 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700284 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700285 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700286 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700287 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
288 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700289 UserInfo ui = mUsers.valueAt(i);
290 if (ui.partial) {
291 continue;
292 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800293 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700294 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700295 }
Amith Yamasani13593602012-03-22 16:16:17 -0700296 }
297 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700298 }
Amith Yamasani13593602012-03-22 16:16:17 -0700299 }
300
Amith Yamasani258848d2012-08-10 17:06:33 -0700301 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100302 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800303 if (userId != UserHandle.getCallingUserId()) {
304 checkManageUsersPermission("getting profiles related to user " + userId);
305 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700306 final long ident = Binder.clearCallingIdentity();
307 try {
308 synchronized (mPackagesLock) {
309 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100310 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700311 } finally {
312 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000313 }
314 }
315
Amith Yamasanibe465322014-04-24 13:45:17 -0700316 /** Assume permissions already checked and caller's identity cleared */
317 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700318 UserInfo user = getUserInfoLocked(userId);
319 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700320 if (user == null) {
321 // Probably a dying user
322 return users;
323 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700324 for (int i = 0; i < mUsers.size(); i++) {
325 UserInfo profile = mUsers.valueAt(i);
326 if (!isProfileOf(user, profile)) {
327 continue;
328 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100329 if (enabledOnly && !profile.isEnabled()) {
330 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700331 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700332 if (mRemovingUserIds.get(profile.id)) {
333 continue;
334 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700335 users.add(profile);
336 }
337 return users;
338 }
339
Jessica Hummelbe81c802014-04-22 15:49:22 +0100340 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700341 public int getCredentialOwnerProfile(int userHandle) {
342 checkManageUsersPermission("get the credential owner");
343 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
344 synchronized (mPackagesLock) {
345 UserInfo profileParent = getProfileParentLocked(userHandle);
346 if (profileParent != null) {
347 return profileParent.id;
348 }
349 }
350 }
351
352 return userHandle;
353 }
354
355 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100356 public UserInfo getProfileParent(int userHandle) {
357 checkManageUsersPermission("get the profile parent");
358 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700359 return getProfileParentLocked(userHandle);
360 }
361 }
362
363 private UserInfo getProfileParentLocked(int userHandle) {
364 UserInfo profile = getUserInfoLocked(userHandle);
365 if (profile == null) {
366 return null;
367 }
368 int parentUserId = profile.profileGroupId;
369 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
370 return null;
371 } else {
372 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100373 }
374 }
375
Kenny Guy2a764942014-04-02 13:29:20 +0100376 private boolean isProfileOf(UserInfo user, UserInfo profile) {
377 return user.id == profile.id ||
378 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
379 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000380 }
381
382 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100383 public void setUserEnabled(int userId) {
384 checkManageUsersPermission("enable user");
385 synchronized (mPackagesLock) {
386 UserInfo info = getUserInfoLocked(userId);
387 if (info != null && !info.isEnabled()) {
388 info.flags ^= UserInfo.FLAG_DISABLED;
389 writeUserLocked(info);
390 }
391 }
392 }
393
394 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700396 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700397 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700398 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700399 }
400 }
401
Amith Yamasani71e6c692013-03-24 17:39:28 -0700402 @Override
403 public boolean isRestricted() {
404 synchronized (mPackagesLock) {
405 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
406 }
407 }
408
Amith Yamasani195263742012-08-21 15:40:12 -0700409 /*
410 * Should be locked on mUsers before calling this.
411 */
412 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700413 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700414 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800415 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700416 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
417 return null;
418 }
419 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700420 }
421
Amith Yamasani236b2b52015-08-18 14:32:14 -0700422 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700423 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700424 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700425 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700426 }
427 }
428
Amith Yamasani258848d2012-08-10 17:06:33 -0700429 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700430 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700431 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700432 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700433 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700434 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700435 if (info == null || info.partial) {
436 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
437 return;
438 }
Amith Yamasani13593602012-03-22 16:16:17 -0700439 if (name != null && !name.equals(info.name)) {
440 info.name = name;
441 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700442 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700443 }
444 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700445 if (changed) {
446 sendUserInfoChangedBroadcast(userId);
447 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700448 }
449
Amith Yamasani258848d2012-08-10 17:06:33 -0700450 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700451 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700452 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400453 long ident = Binder.clearCallingIdentity();
454 try {
455 synchronized (mPackagesLock) {
456 UserInfo info = mUsers.get(userId);
457 if (info == null || info.partial) {
458 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
459 return;
460 }
461 writeBitmapLocked(info, bitmap);
462 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700463 }
Jason Monk9a944532014-07-08 09:31:21 -0400464 sendUserInfoChangedBroadcast(userId);
465 } finally {
466 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700467 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700468 }
469
470 private void sendUserInfoChangedBroadcast(int userId) {
471 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
472 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
473 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700474 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700475 }
476
Amith Yamasani258848d2012-08-10 17:06:33 -0700477 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100478 public ParcelFileDescriptor getUserIcon(int userId) {
479 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700480 synchronized (mPackagesLock) {
481 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700482 if (info == null || info.partial) {
483 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
484 return null;
485 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100486 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
487 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
488 || callingGroupId != info.profileGroupId) {
489 checkManageUsersPermission("get the icon of a user who is not related");
490 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700491 if (info.iconPath == null) {
492 return null;
493 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100494 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700495 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100496
497 try {
498 return ParcelFileDescriptor.open(
499 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
500 } catch (FileNotFoundException e) {
501 Log.e(LOG_TAG, "Couldn't find icon file", e);
502 }
503 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700504 }
505
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700506 public void makeInitialized(int userId) {
507 checkManageUsersPermission("makeInitialized");
508 synchronized (mPackagesLock) {
509 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700510 if (info == null || info.partial) {
511 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
512 }
513 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700514 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800515 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700516 }
517 }
518 }
519
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700520 /**
521 * If default guest restrictions haven't been initialized yet, add the basic
522 * restrictions.
523 */
524 private void initDefaultGuestRestrictions() {
525 if (mGuestRestrictions.isEmpty()) {
526 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800527 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700528 }
529 }
530
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800531 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530532 public Bundle getDefaultGuestRestrictions() {
533 checkManageUsersPermission("getDefaultGuestRestrictions");
534 synchronized (mPackagesLock) {
535 return new Bundle(mGuestRestrictions);
536 }
537 }
538
539 @Override
540 public void setDefaultGuestRestrictions(Bundle restrictions) {
541 checkManageUsersPermission("setDefaultGuestRestrictions");
542 synchronized (mPackagesLock) {
543 mGuestRestrictions.clear();
544 mGuestRestrictions.putAll(restrictions);
545 writeUserListLocked();
546 }
547 }
548
549 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700550 public boolean hasUserRestriction(String restrictionKey, int userId) {
551 synchronized (mPackagesLock) {
552 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700553 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700554 }
555 }
556
557 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800558 public Bundle getUserRestrictions(int userId) {
559 // checkManageUsersPermission("getUserRestrictions");
560
561 synchronized (mPackagesLock) {
562 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700563 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800564 }
565 }
566
567 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700568 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700569 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700570 synchronized (mPackagesLock) {
571 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
572 Bundle restrictions = getUserRestrictions(userId);
573 restrictions.putBoolean(key, value);
574 setUserRestrictionsInternalLocked(restrictions, userId);
575 }
576 }
577 }
578
579 @Override
580 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
581 checkSystemOrRoot("setSystemControlledUserRestriction");
582 synchronized (mPackagesLock) {
583 Bundle restrictions = getUserRestrictions(userId);
584 restrictions.putBoolean(key, value);
585 setUserRestrictionsInternalLocked(restrictions, userId);
586 }
587 }
588
589 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800590 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700591 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700592 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800593
594 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700595 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
596 // Restore the original state of system controlled restrictions from oldUserRestrictions
597 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
598 restrictions.remove(key);
599 if (oldUserRestrictions.containsKey(key)) {
600 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
601 }
Jason Monk62062992014-05-06 09:55:28 -0400602 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700603 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800604 }
605 }
606
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700607 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
608 final Bundle userRestrictions = mUserRestrictions.get(userId);
609 userRestrictions.clear();
610 userRestrictions.putAll(restrictions);
611 long token = Binder.clearCallingIdentity();
612 try {
613 mAppOpsService.setUserRestrictions(userRestrictions, userId);
614 } catch (RemoteException e) {
615 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
616 } finally {
617 Binder.restoreCallingIdentity(token);
618 }
619 scheduleWriteUserLocked(mUsers.get(userId));
620 }
621
Amith Yamasani258848d2012-08-10 17:06:33 -0700622 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700623 * Check if we've hit the limit of how many users can be created.
624 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700625 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700626 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
627 }
628
629 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100630 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700631 checkManageUsersPermission("check if more managed profiles can be added.");
632 if (ActivityManager.isLowRamDeviceStatic()) {
633 return false;
634 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700635 if (!mContext.getPackageManager().hasSystemFeature(
636 PackageManager.FEATURE_MANAGED_USERS)) {
637 return false;
638 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100639 // Limit number of managed profiles that can be created
640 int managedProfilesCount = getProfiles(userId, true).size() - 1;
641 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
642 return false;
643 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700644 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100645 UserInfo userInfo = getUserInfoLocked(userId);
646 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700647 return false;
648 }
649 int usersCount = getAliveUsersExcludingGuestsCountLocked();
650 // We allow creating a managed profile in the special case where there is only one user.
651 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
652 }
653 }
654
655 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700656 int aliveUserCount = 0;
657 final int totalUserCount = mUsers.size();
658 // Skip over users being removed
659 for (int i = 0; i < totalUserCount; i++) {
660 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700661 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700662 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700663 aliveUserCount++;
664 }
665 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700666 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700667 }
668
669 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700670 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700671 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700672 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700673 *
674 * @param message used as message if SecurityException is thrown
675 * @throws SecurityException if the caller is not system or root
676 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700677 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700678 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700679 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400680 && ActivityManager.checkComponentPermission(
681 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700682 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
683 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
684 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400685 }
686
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700687 private static void checkSystemOrRoot(String message) {
688 final int uid = Binder.getCallingUid();
689 if (uid != Process.SYSTEM_UID && uid != 0) {
690 throw new SecurityException("Only system may call: " + message);
691 }
692 }
693
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700694 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700695 try {
696 File dir = new File(mUsersDir, Integer.toString(info.id));
697 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100698 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700699 if (!dir.exists()) {
700 dir.mkdir();
701 FileUtils.setPermissions(
702 dir.getPath(),
703 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
704 -1, -1);
705 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700706 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100707 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
708 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700709 info.iconPath = file.getAbsolutePath();
710 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700711 try {
712 os.close();
713 } catch (IOException ioe) {
714 // What the ... !
715 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100716 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700717 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700718 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700719 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700720 }
721
Amith Yamasani0b285492011-04-14 17:35:23 -0700722 /**
723 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
724 * cache it elsewhere.
725 * @return the array of user ids.
726 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700727 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700728 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700729 return mUserIds;
730 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700731 }
732
Dianne Hackborn4428e172012-08-24 17:43:05 -0700733 int[] getUserIdsLPr() {
734 return mUserIds;
735 }
736
Amith Yamasani13593602012-03-22 16:16:17 -0700737 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700738 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700739 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700740 return;
741 }
742 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700743 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700744 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700745 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700746 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100747 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700748 int type;
749 while ((type = parser.next()) != XmlPullParser.START_TAG
750 && type != XmlPullParser.END_DOCUMENT) {
751 ;
752 }
753
754 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700755 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700756 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700757 return;
758 }
759
Amith Yamasani2a003292012-08-14 18:25:45 -0700760 mNextSerialNumber = -1;
761 if (parser.getName().equals(TAG_USERS)) {
762 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
763 if (lastSerialNumber != null) {
764 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
765 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700766 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
767 if (versionNumber != null) {
768 mUserVersion = Integer.parseInt(versionNumber);
769 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700770 }
771
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700772 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530773 if (type == XmlPullParser.START_TAG) {
774 final String name = parser.getName();
775 if (name.equals(TAG_USER)) {
776 String id = parser.getAttributeValue(null, ATTR_ID);
777 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700778
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530779 if (user != null) {
780 mUsers.put(user.id, user);
781 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
782 mNextSerialNumber = user.id + 1;
783 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700784 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530785 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800786 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
787 && type != XmlPullParser.END_TAG) {
788 if (type == XmlPullParser.START_TAG) {
789 if (parser.getName().equals(TAG_RESTRICTIONS)) {
790 readRestrictionsLocked(parser, mGuestRestrictions);
791 }
792 break;
793 }
794 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700795 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700796 }
797 }
Amith Yamasani13593602012-03-22 16:16:17 -0700798 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700799 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700800 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700801 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700802 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700803 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800804 } finally {
805 if (fis != null) {
806 try {
807 fis.close();
808 } catch (IOException e) {
809 }
810 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700811 }
812 }
813
Amith Yamasani6f34b412012-10-22 18:19:27 -0700814 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800815 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700816 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700817 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700818 int userVersion = mUserVersion;
819 if (userVersion < 1) {
820 // Assign a proper name for the owner, if not initialized correctly before
821 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
822 if ("Primary".equals(user.name)) {
823 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800824 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700825 }
826 userVersion = 1;
827 }
828
Amith Yamasanibc9625052012-11-15 14:39:18 -0800829 if (userVersion < 2) {
830 // Owner should be marked as initialized
831 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
832 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
833 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800834 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800835 }
836 userVersion = 2;
837 }
838
Amith Yamasani350962c2013-08-06 11:18:53 -0700839
Amith Yamasani5e486f52013-08-07 11:06:44 -0700840 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700841 userVersion = 4;
842 }
843
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700844 if (userVersion < 5) {
845 initDefaultGuestRestrictions();
846 userVersion = 5;
847 }
848
Amith Yamasani6f34b412012-10-22 18:19:27 -0700849 if (userVersion < USER_VERSION) {
850 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
851 + USER_VERSION);
852 } else {
853 mUserVersion = userVersion;
854 writeUserListLocked();
855 }
856 }
857
Amith Yamasani13593602012-03-22 16:16:17 -0700858 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700859 int flags = UserInfo.FLAG_INITIALIZED;
860 // In split system user mode, the admin and primary flags are assigned to the first human
861 // user.
862 if (!UserManager.isSplitSystemUser()) {
863 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
864 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700865 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700866 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700867 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700868 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700869 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700870 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400871 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800872
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500873 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700874 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800875
Amith Yamasani13593602012-03-22 16:16:17 -0700876 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700877 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700878
Amith Yamasani13593602012-03-22 16:16:17 -0700879 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700880 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700881 }
882
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800883 private void scheduleWriteUserLocked(UserInfo userInfo) {
884 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
885 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
886 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
887 }
888 }
889
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700890 /*
891 * Writes the user file in this format:
892 *
893 * <user flags="20039023" id="0">
894 * <name>Primary</name>
895 * </user>
896 */
Amith Yamasani13593602012-03-22 16:16:17 -0700897 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700898 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700899 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700900 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700901 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700902 final BufferedOutputStream bos = new BufferedOutputStream(fos);
903
904 // XmlSerializer serializer = XmlUtils.serializerInstance();
905 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100906 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700907 serializer.startDocument(null, true);
908 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
909
910 serializer.startTag(null, TAG_USER);
911 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700912 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700913 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700914 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
915 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
916 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700917 if (userInfo.iconPath != null) {
918 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
919 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700920 if (userInfo.partial) {
921 serializer.attribute(null, ATTR_PARTIAL, "true");
922 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700923 if (userInfo.guestToRemove) {
924 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
925 }
Kenny Guy2a764942014-04-02 13:29:20 +0100926 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
927 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
928 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000929 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700930 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
931 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
932 Integer.toString(userInfo.restrictedProfileParentId));
933 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700934 serializer.startTag(null, TAG_NAME);
935 serializer.text(userInfo.name);
936 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800937 Bundle restrictions = mUserRestrictions.get(userInfo.id);
938 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530939 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800940 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700941 serializer.endTag(null, TAG_USER);
942
943 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700944 userFile.finishWrite(fos);
945 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700946 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700947 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700948 }
949 }
950
951 /*
952 * Writes the user list file in this format:
953 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700954 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700955 * <user id="0"></user>
956 * <user id="2"></user>
957 * </users>
958 */
Amith Yamasani13593602012-03-22 16:16:17 -0700959 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700960 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700961 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700962 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700963 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700964 final BufferedOutputStream bos = new BufferedOutputStream(fos);
965
966 // XmlSerializer serializer = XmlUtils.serializerInstance();
967 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100968 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700969 serializer.startDocument(null, true);
970 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
971
972 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700973 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700974 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700975
Adam Lesinskieddeb492014-09-08 17:50:03 -0700976 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530977 writeRestrictionsLocked(serializer, mGuestRestrictions);
978 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700979 for (int i = 0; i < mUsers.size(); i++) {
980 UserInfo user = mUsers.valueAt(i);
981 serializer.startTag(null, TAG_USER);
982 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
983 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700984 }
985
986 serializer.endTag(null, TAG_USERS);
987
988 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700989 userListFile.finishWrite(fos);
990 } catch (Exception e) {
991 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700992 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700993 }
994 }
995
Andres Moralesc5548c02015-08-05 10:23:12 -0700996 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530997 throws IOException {
998 serializer.startTag(null, TAG_RESTRICTIONS);
999 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1000 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1001 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1002 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1003 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1004 writeBoolean(serializer, restrictions,
1005 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1006 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1007 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1008 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1009 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1010 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1011 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1012 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001013 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301014 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1015 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1016 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1017 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1018 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1019 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1020 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1021 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1022 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001023 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1024 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001025 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001026 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001027 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1028 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001029 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001030 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001031 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301032 serializer.endTag(null, TAG_RESTRICTIONS);
1033 }
1034
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001035 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001036 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001037 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001038 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001039 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001040 long creationTime = 0L;
1041 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001042 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001043 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001044 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001045 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001046 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001047
1048 FileInputStream fis = null;
1049 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001050 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001051 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001052 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001053 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001054 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001055 int type;
1056 while ((type = parser.next()) != XmlPullParser.START_TAG
1057 && type != XmlPullParser.END_DOCUMENT) {
1058 ;
1059 }
1060
1061 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001062 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001063 return null;
1064 }
1065
1066 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001067 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1068 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001069 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001070 return null;
1071 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001072 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1073 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001074 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001075 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1076 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001077 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1078 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001079 restrictedProfileParentId = readIntAttribute(parser,
1080 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001081 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1082 if ("true".equals(valueString)) {
1083 partial = true;
1084 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001085 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1086 if ("true".equals(valueString)) {
1087 guestToRemove = true;
1088 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001089
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001090 int outerDepth = parser.getDepth();
1091 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1092 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1093 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1094 continue;
1095 }
1096 String tag = parser.getName();
1097 if (TAG_NAME.equals(tag)) {
1098 type = parser.next();
1099 if (type == XmlPullParser.TEXT) {
1100 name = parser.getText();
1101 }
1102 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301103 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001104 }
1105 }
1106 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001107
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001108 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001109 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001110 userInfo.creationTime = creationTime;
1111 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001112 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001113 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001114 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001115 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001116 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001117 return userInfo;
1118
1119 } catch (IOException ioe) {
1120 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001121 } finally {
1122 if (fis != null) {
1123 try {
1124 fis.close();
1125 } catch (IOException e) {
1126 }
1127 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001128 }
1129 return null;
1130 }
1131
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301132 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1133 throws IOException {
1134 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1135 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1136 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1137 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1138 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1139 readBoolean(parser, restrictions,
1140 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1141 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1142 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1143 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1144 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1145 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1146 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1147 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001148 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301149 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1150 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1151 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1152 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1153 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1154 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1155 readBoolean(parser, restrictions,
1156 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1157 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1158 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001159 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1160 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001161 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001162 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001163 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1164 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001165 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001166 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001167 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301168 }
1169
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001170 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1171 String restrictionKey) {
1172 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001173 if (value != null) {
1174 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1175 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001176 }
1177
1178 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1179 throws IOException {
1180 if (restrictions.containsKey(restrictionKey)) {
1181 xml.attribute(null, restrictionKey,
1182 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1183 }
1184 }
1185
Amith Yamasani920ace02012-09-20 22:15:37 -07001186 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1187 String valueString = parser.getAttributeValue(null, attr);
1188 if (valueString == null) return defaultValue;
1189 try {
1190 return Integer.parseInt(valueString);
1191 } catch (NumberFormatException nfe) {
1192 return defaultValue;
1193 }
1194 }
1195
1196 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1197 String valueString = parser.getAttributeValue(null, attr);
1198 if (valueString == null) return defaultValue;
1199 try {
1200 return Long.parseLong(valueString);
1201 } catch (NumberFormatException nfe) {
1202 return defaultValue;
1203 }
1204 }
1205
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001206 private boolean isPackageInstalled(String pkg, int userId) {
1207 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1208 PackageManager.GET_UNINSTALLED_PACKAGES,
1209 userId);
1210 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1211 return false;
1212 }
1213 return true;
1214 }
1215
Amith Yamasanib82add22013-07-09 11:24:44 -07001216 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001217 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001218 * Does not do any permissions checking.
1219 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001220 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001221 synchronized (mPackagesLock) {
1222 File dir = Environment.getUserSystemDirectory(userId);
1223 String[] files = dir.list();
1224 if (files == null) return;
1225 for (String fileName : files) {
1226 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1227 File resFile = new File(dir, fileName);
1228 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001229 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001230 }
1231 }
1232 }
1233 }
1234 }
1235
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001236 /**
1237 * Removes the app restrictions file for a specific package and user id, if it exists.
1238 */
1239 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1240 synchronized (mPackagesLock) {
1241 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001242 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001243 if (resFile.exists()) {
1244 resFile.delete();
1245 }
1246 }
1247 }
1248
Kenny Guya52dc3e2014-02-11 15:33:14 +00001249 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001250 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001251 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001252 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001253 }
1254
Amith Yamasani258848d2012-08-10 17:06:33 -07001255 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001256 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001257 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001258 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001259 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001260
Jessica Hummelbe81c802014-04-22 15:49:22 +01001261 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001262 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1263 UserManager.DISALLOW_ADD_USER, false)) {
1264 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1265 return null;
1266 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001267 if (ActivityManager.isLowRamDeviceStatic()) {
1268 return null;
1269 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001270 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001271 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001272 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001273 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001274 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001275 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001276 try {
1277 synchronized (mInstallLock) {
1278 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001279 UserInfo parent = null;
1280 if (parentId != UserHandle.USER_NULL) {
1281 parent = getUserInfoLocked(parentId);
1282 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001283 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001284 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1285 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001286 return null;
1287 }
1288 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1289 // If we're not adding a guest user or a managed profile and the limit has
1290 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001291 return null;
1292 }
1293 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001294 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001295 return null;
1296 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001297 // In legacy mode, restricted profile's parent can only be the owner user
1298 if (isRestricted && !UserManager.isSplitSystemUser()
1299 && (parentId != UserHandle.USER_SYSTEM)) {
1300 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1301 return null;
1302 }
1303 if (isRestricted && UserManager.isSplitSystemUser()) {
1304 if (parent == null) {
1305 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1306 + "specified");
1307 return null;
1308 }
1309 if (!parent.canHaveProfile()) {
1310 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1311 + "created for the specified parent user id " + parentId);
1312 return null;
1313 }
1314 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001315 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001316 // And if there is no device owner, we also assign the admin flag to primary
1317 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001318 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001319 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001320 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001321 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1322 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1323 if (devicePolicyManager == null
1324 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001325 flags |= UserInfo.FLAG_ADMIN;
1326 }
1327 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001328 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001329 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001330 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001331 long now = System.currentTimeMillis();
1332 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001333 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001334 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001335 mUsers.put(userId, userInfo);
1336 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001337 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001338 if (isManagedProfile) {
1339 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1340 parent.profileGroupId = parent.id;
1341 scheduleWriteUserLocked(parent);
1342 }
1343 userInfo.profileGroupId = parent.profileGroupId;
1344 } else if (isRestricted) {
1345 if (!parent.canHaveProfile()) {
1346 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1347 }
1348 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1349 parent.restrictedProfileParentId = parent.id;
1350 scheduleWriteUserLocked(parent);
1351 }
1352 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001353 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001354 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001355 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1356 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1357 final String volumeUuid = vol.getFsUuid();
1358 try {
1359 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1360 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001361 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001362 enforceSerialNumber(userDir, userInfo.serialNumber);
1363 } catch (IOException e) {
1364 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1365 }
1366 }
1367 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001368 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001369 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001370 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001371 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001372 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001373 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001374 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001375 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001376 if (userInfo != null) {
1377 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1378 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1379 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1380 android.Manifest.permission.MANAGE_USERS);
1381 }
1382 } finally {
1383 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001384 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001385 return userInfo;
1386 }
1387
Amith Yamasani0b285492011-04-14 17:35:23 -07001388 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001389 * Find the current guest user. If the Guest user is partial,
1390 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001391 */
1392 private UserInfo findCurrentGuestUserLocked() {
1393 final int size = mUsers.size();
1394 for (int i = 0; i < size; i++) {
1395 final UserInfo user = mUsers.valueAt(i);
1396 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1397 return user;
1398 }
1399 }
1400 return null;
1401 }
1402
1403 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001404 * Mark this guest user for deletion to allow us to create another guest
1405 * and switch to that user before actually removing this guest.
1406 * @param userHandle the userid of the current guest
1407 * @return whether the user could be marked for deletion
1408 */
1409 public boolean markGuestForDeletion(int userHandle) {
1410 checkManageUsersPermission("Only the system can remove users");
1411 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1412 UserManager.DISALLOW_REMOVE_USER, false)) {
1413 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1414 return false;
1415 }
1416
1417 long ident = Binder.clearCallingIdentity();
1418 try {
1419 final UserInfo user;
1420 synchronized (mPackagesLock) {
1421 user = mUsers.get(userHandle);
1422 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1423 return false;
1424 }
1425 if (!user.isGuest()) {
1426 return false;
1427 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001428 // We set this to a guest user that is to be removed. This is a temporary state
1429 // where we are allowed to add new Guest users, even if this one is still not
1430 // removed. This user will still show up in getUserInfo() calls.
1431 // If we don't get around to removing this Guest user, it will be purged on next
1432 // startup.
1433 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001434 // Mark it as disabled, so that it isn't returned any more when
1435 // profiles are queried.
1436 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001437 writeUserLocked(user);
1438 }
1439 } finally {
1440 Binder.restoreCallingIdentity(ident);
1441 }
1442 return true;
1443 }
1444
1445 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001446 * Removes a user and all data directories created for that user. This method should be called
1447 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001448 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001449 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001450 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001451 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001452 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1453 UserManager.DISALLOW_REMOVE_USER, false)) {
1454 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1455 return false;
1456 }
1457
Kenny Guyee58b4f2014-05-23 15:19:53 +01001458 long ident = Binder.clearCallingIdentity();
1459 try {
1460 final UserInfo user;
1461 synchronized (mPackagesLock) {
1462 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001463 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001464 return false;
1465 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001466
1467 // We remember deleted user IDs to prevent them from being
1468 // reused during the current boot; they can still be reused
1469 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001470 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001471
Kenny Guyee58b4f2014-05-23 15:19:53 +01001472 try {
1473 mAppOpsService.removeUser(userHandle);
1474 } catch (RemoteException e) {
1475 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1476 }
1477 // Set this to a partially created user, so that the user will be purged
1478 // on next startup, in case the runtime stops now before stopping and
1479 // removing the user completely.
1480 user.partial = true;
1481 // Mark it as disabled, so that it isn't returned any more when
1482 // profiles are queried.
1483 user.flags |= UserInfo.FLAG_DISABLED;
1484 writeUserLocked(user);
1485 }
1486
1487 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1488 && user.isManagedProfile()) {
1489 // Send broadcast to notify system that the user removed was a
1490 // managed user.
1491 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1492 }
1493
1494 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1495 int res;
1496 try {
1497 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1498 new IStopUserCallback.Stub() {
1499 @Override
1500 public void userStopped(int userId) {
1501 finishRemoveUser(userId);
1502 }
1503 @Override
1504 public void userStopAborted(int userId) {
1505 }
1506 });
1507 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001508 return false;
1509 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001510 return res == ActivityManager.USER_OP_SUCCESS;
1511 } finally {
1512 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001513 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001514 }
1515
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001516 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001517 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001518 // Let other services shutdown any activity and clean up their state before completely
1519 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001520 long ident = Binder.clearCallingIdentity();
1521 try {
1522 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1523 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001524 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1525 android.Manifest.permission.MANAGE_USERS,
1526
1527 new BroadcastReceiver() {
1528 @Override
1529 public void onReceive(Context context, Intent intent) {
1530 if (DBG) {
1531 Slog.i(LOG_TAG,
1532 "USER_REMOVED broadcast sent, cleaning up user data "
1533 + userHandle);
1534 }
1535 new Thread() {
1536 public void run() {
1537 synchronized (mInstallLock) {
1538 synchronized (mPackagesLock) {
1539 removeUserStateLocked(userHandle);
1540 }
1541 }
1542 }
1543 }.start();
1544 }
1545 },
1546
1547 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001548 } finally {
1549 Binder.restoreCallingIdentity(ident);
1550 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001551 }
1552
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001553 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001554 mContext.getSystemService(StorageManager.class)
1555 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001556 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001557 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001558
1559 // Remove this user from the list
1560 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001561 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001562 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001563 userFile.delete();
1564 // Update the user list
1565 writeUserListLocked();
1566 updateUserIdsLocked();
1567 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1568 }
1569
Amith Yamasani61f57372012-08-31 12:12:28 -07001570 private void removeDirectoryRecursive(File parent) {
1571 if (parent.isDirectory()) {
1572 String[] files = parent.list();
1573 for (String filename : files) {
1574 File child = new File(parent, filename);
1575 removeDirectoryRecursive(child);
1576 }
1577 }
1578 parent.delete();
1579 }
1580
Kenny Guyf8d3a232014-05-15 16:09:52 +01001581 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001582 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001583 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1584 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001585 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1586 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001587 }
1588
Amith Yamasani2a003292012-08-14 18:25:45 -07001589 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001590 public Bundle getApplicationRestrictions(String packageName) {
1591 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1592 }
1593
1594 @Override
1595 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001596 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001597 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001598 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001599 }
1600 synchronized (mPackagesLock) {
1601 // Read the restrictions from XML
1602 return readApplicationRestrictionsLocked(packageName, userId);
1603 }
1604 }
1605
1606 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001607 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001608 int userId) {
1609 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001610 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001611 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001612 }
1613 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001614 if (restrictions == null || restrictions.isEmpty()) {
1615 cleanAppRestrictionsForPackage(packageName, userId);
1616 } else {
1617 // Write the restrictions to XML
1618 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1619 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001620 }
Robin Lee66e5d962014-04-09 16:44:21 +01001621
Kenny Guyd21b2182014-07-17 16:38:55 +01001622 if (isPackageInstalled(packageName, userId)) {
1623 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1624 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1625 changeIntent.setPackage(packageName);
1626 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1627 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1628 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001629 }
1630
Amith Yamasani655d0e22013-06-12 14:19:10 -07001631 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001632 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001633 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001634 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001635 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001636 }
1637
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001638 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001639 synchronized (mPackagesLock) {
1640 // Remove all user restrictions
1641 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001642 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001643 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001644 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001645 if (unhideApps) {
1646 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001647 }
1648 }
1649
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001650 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001651 mHandler.post(new Runnable() {
1652 @Override
1653 public void run() {
1654 List<ApplicationInfo> apps =
1655 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1656 userHandle).getList();
1657 final long ident = Binder.clearCallingIdentity();
1658 try {
1659 for (ApplicationInfo appInfo : apps) {
1660 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001661 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1662 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001663 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001664 userHandle);
1665 }
1666 }
1667 } finally {
1668 Binder.restoreCallingIdentity(ident);
1669 }
1670 }
1671 });
1672 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001673 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001674 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001675 try {
1676 return mContext.getPackageManager().getApplicationInfo(packageName,
1677 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1678 } catch (NameNotFoundException nnfe) {
1679 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001680 } finally {
1681 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001682 }
1683 }
1684
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001685 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001686 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001687 AtomicFile restrictionsFile =
1688 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1689 packageToRestrictionsFileName(packageName)));
1690 return readApplicationRestrictionsLocked(restrictionsFile);
1691 }
1692
1693 @VisibleForTesting
1694 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001695 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001696 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001697 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001698 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001699 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001700
1701 FileInputStream fis = null;
1702 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001703 fis = restrictionsFile.openRead();
1704 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001705 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001706 XmlUtils.nextElement(parser);
1707 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001708 Slog.e(LOG_TAG, "Unable to read restrictions file "
1709 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001710 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001711 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001712 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1713 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001714 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001715 } catch (IOException|XmlPullParserException e) {
1716 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001717 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001718 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001719 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001720 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001721 }
1722
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001723 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1724 XmlPullParser parser) throws XmlPullParserException, IOException {
1725 int type = parser.getEventType();
1726 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1727 String key = parser.getAttributeValue(null, ATTR_KEY);
1728 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1729 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1730 if (multiple != null) {
1731 values.clear();
1732 int count = Integer.parseInt(multiple);
1733 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1734 if (type == XmlPullParser.START_TAG
1735 && parser.getName().equals(TAG_VALUE)) {
1736 values.add(parser.nextText().trim());
1737 count--;
1738 }
1739 }
1740 String [] valueStrings = new String[values.size()];
1741 values.toArray(valueStrings);
1742 restrictions.putStringArray(key, valueStrings);
1743 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1744 restrictions.putBundle(key, readBundleEntry(parser, values));
1745 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1746 final int outerDepth = parser.getDepth();
1747 ArrayList<Bundle> bundleList = new ArrayList<>();
1748 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1749 Bundle childBundle = readBundleEntry(parser, values);
1750 bundleList.add(childBundle);
1751 }
1752 restrictions.putParcelableArray(key,
1753 bundleList.toArray(new Bundle[bundleList.size()]));
1754 } else {
1755 String value = parser.nextText().trim();
1756 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1757 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1758 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1759 restrictions.putInt(key, Integer.parseInt(value));
1760 } else {
1761 restrictions.putString(key, value);
1762 }
1763 }
1764 }
1765 }
1766
1767 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1768 throws IOException, XmlPullParserException {
1769 Bundle childBundle = new Bundle();
1770 final int outerDepth = parser.getDepth();
1771 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1772 readEntry(childBundle, values, parser);
1773 }
1774 return childBundle;
1775 }
1776
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001777 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001778 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001779 AtomicFile restrictionsFile = new AtomicFile(
1780 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001781 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001782 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1783 }
1784
1785 @VisibleForTesting
1786 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1787 AtomicFile restrictionsFile) {
1788 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001789 try {
1790 fos = restrictionsFile.startWrite();
1791 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1792
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001793 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001794 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001795 serializer.startDocument(null, true);
1796 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1797
1798 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001799 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001800 serializer.endTag(null, TAG_RESTRICTIONS);
1801
1802 serializer.endDocument();
1803 restrictionsFile.finishWrite(fos);
1804 } catch (Exception e) {
1805 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001806 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1807 }
1808 }
1809
1810 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1811 throws IOException {
1812 for (String key : restrictions.keySet()) {
1813 Object value = restrictions.get(key);
1814 serializer.startTag(null, TAG_ENTRY);
1815 serializer.attribute(null, ATTR_KEY, key);
1816
1817 if (value instanceof Boolean) {
1818 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1819 serializer.text(value.toString());
1820 } else if (value instanceof Integer) {
1821 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1822 serializer.text(value.toString());
1823 } else if (value == null || value instanceof String) {
1824 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1825 serializer.text(value != null ? (String) value : "");
1826 } else if (value instanceof Bundle) {
1827 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1828 writeBundle((Bundle) value, serializer);
1829 } else if (value instanceof Parcelable[]) {
1830 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1831 Parcelable[] array = (Parcelable[]) value;
1832 for (Parcelable parcelable : array) {
1833 if (!(parcelable instanceof Bundle)) {
1834 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1835 }
1836 serializer.startTag(null, TAG_ENTRY);
1837 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1838 writeBundle((Bundle) parcelable, serializer);
1839 serializer.endTag(null, TAG_ENTRY);
1840 }
1841 } else {
1842 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1843 String[] values = (String[]) value;
1844 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1845 for (String choice : values) {
1846 serializer.startTag(null, TAG_VALUE);
1847 serializer.text(choice != null ? choice : "");
1848 serializer.endTag(null, TAG_VALUE);
1849 }
1850 }
1851 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001852 }
1853 }
1854
1855 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001856 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001857 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001858 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001859 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001860 }
1861 }
1862
1863 @Override
1864 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001865 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001866 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001867 UserInfo info = getUserInfoLocked(userId);
1868 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001869 }
1870 // Not found
1871 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001872 }
1873 }
1874
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001875 @Override
1876 public long getUserCreationTime(int userHandle) {
1877 int callingUserId = UserHandle.getCallingUserId();
1878 UserInfo userInfo = null;
1879 synchronized (mPackagesLock) {
1880 if (callingUserId == userHandle) {
1881 userInfo = getUserInfoLocked(userHandle);
1882 } else {
1883 UserInfo parent = getProfileParentLocked(userHandle);
1884 if (parent != null && parent.id == callingUserId) {
1885 userInfo = getUserInfoLocked(userHandle);
1886 }
1887 }
1888 }
1889 if (userInfo == null) {
1890 throw new SecurityException("userHandle can only be the calling user or a managed "
1891 + "profile associated with this user");
1892 }
1893 return userInfo.creationTime;
1894 }
1895
Amith Yamasani0b285492011-04-14 17:35:23 -07001896 /**
1897 * Caches the list of user ids in an array, adjusting the array size when necessary.
1898 */
Amith Yamasani13593602012-03-22 16:16:17 -07001899 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001900 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001901 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001902 if (!mUsers.valueAt(i).partial) {
1903 num++;
1904 }
1905 }
Amith Yamasani16389312012-10-17 21:20:14 -07001906 final int[] newUsers = new int[num];
1907 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001908 for (int i = 0; i < mUsers.size(); i++) {
1909 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001910 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001911 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001912 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001913 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001914 }
1915
1916 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001917 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001918 * @param userId the user that was just foregrounded
1919 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001920 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001921 synchronized (mPackagesLock) {
1922 UserInfo user = mUsers.get(userId);
1923 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001924 if (user == null || user.partial) {
1925 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1926 return;
1927 }
1928 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001929 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001930 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001931 }
1932 }
1933 }
1934
1935 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001936 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001937 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1938 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001939 * @return
1940 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001941 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001942 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001943 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001944 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001945 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001946 break;
1947 }
1948 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001949 }
Amith Yamasani195263742012-08-21 15:40:12 -07001950 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001951 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001952 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001953
Amith Yamasanifc95e702013-09-26 13:20:17 -07001954 private String packageToRestrictionsFileName(String packageName) {
1955 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1956 }
1957
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001958 /**
1959 * Create new {@code /data/user/[id]} directory and sets default
1960 * permissions.
1961 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001962 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
1963 final StorageManager storage = context.getSystemService(StorageManager.class);
1964 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1965 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001966 }
1967
1968 /**
1969 * Enforce that serial number stored in user directory inode matches the
1970 * given expected value. Gracefully sets the serial number if currently
1971 * undefined.
1972 *
1973 * @throws IOException when problem extracting serial number, or serial
1974 * number is mismatched.
1975 */
1976 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1977 final int foundSerial = getSerialNumber(file);
1978 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1979
1980 if (foundSerial == -1) {
1981 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1982 try {
1983 setSerialNumber(file, serialNumber);
1984 } catch (IOException e) {
1985 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1986 }
1987
1988 } else if (foundSerial != serialNumber) {
1989 throw new IOException("Found serial number " + foundSerial
1990 + " doesn't match expected " + serialNumber);
1991 }
1992 }
1993
1994 /**
1995 * Set serial number stored in user directory inode.
1996 *
1997 * @throws IOException if serial number was already set
1998 */
1999 private static void setSerialNumber(File file, int serialNumber)
2000 throws IOException {
2001 try {
2002 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2003 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2004 } catch (ErrnoException e) {
2005 throw e.rethrowAsIOException();
2006 }
2007 }
2008
2009 /**
2010 * Return serial number stored in user directory inode.
2011 *
2012 * @return parsed serial number, or -1 if not set
2013 */
2014 private static int getSerialNumber(File file) throws IOException {
2015 try {
2016 final byte[] buf = new byte[256];
2017 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2018 final String serial = new String(buf, 0, len);
2019 try {
2020 return Integer.parseInt(serial);
2021 } catch (NumberFormatException e) {
2022 throw new IOException("Bad serial number: " + serial);
2023 }
2024 } catch (ErrnoException e) {
2025 if (e.errno == OsConstants.ENODATA) {
2026 return -1;
2027 } else {
2028 throw e.rethrowAsIOException();
2029 }
2030 }
2031 }
2032
Amith Yamasani920ace02012-09-20 22:15:37 -07002033 @Override
2034 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2035 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2036 != PackageManager.PERMISSION_GRANTED) {
2037 pw.println("Permission Denial: can't dump UserManager from from pid="
2038 + Binder.getCallingPid()
2039 + ", uid=" + Binder.getCallingUid()
2040 + " without permission "
2041 + android.Manifest.permission.DUMP);
2042 return;
2043 }
2044
2045 long now = System.currentTimeMillis();
2046 StringBuilder sb = new StringBuilder();
2047 synchronized (mPackagesLock) {
2048 pw.println("Users:");
2049 for (int i = 0; i < mUsers.size(); i++) {
2050 UserInfo user = mUsers.valueAt(i);
2051 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002052 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002053 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002054 if (user.partial) pw.print(" <partial>");
2055 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002056 pw.print(" Created: ");
2057 if (user.creationTime == 0) {
2058 pw.println("<unknown>");
2059 } else {
2060 sb.setLength(0);
2061 TimeUtils.formatDuration(now - user.creationTime, sb);
2062 sb.append(" ago");
2063 pw.println(sb);
2064 }
2065 pw.print(" Last logged in: ");
2066 if (user.lastLoggedInTime == 0) {
2067 pw.println("<unknown>");
2068 } else {
2069 sb.setLength(0);
2070 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2071 sb.append(" ago");
2072 pw.println(sb);
2073 }
2074 }
2075 }
2076 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002077
2078 final class MainHandler extends Handler {
2079
2080 @Override
2081 public void handleMessage(Message msg) {
2082 switch (msg.what) {
2083 case WRITE_USER_MSG:
2084 removeMessages(WRITE_USER_MSG, msg.obj);
2085 synchronized (mPackagesLock) {
2086 int userId = ((UserInfo) msg.obj).id;
2087 UserInfo userInfo = mUsers.get(userId);
2088 if (userInfo != null) {
2089 writeUserLocked(userInfo);
2090 }
2091 }
2092 }
2093 }
2094 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002095
2096 /**
2097 * @param userId
2098 * @return whether the user has been initialized yet
2099 */
2100 boolean isInitialized(int userId) {
2101 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2102 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002103}