blob: 7d8dc04ac22ac95d628abce13c2c20a0b325c459 [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
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070019import android.accounts.Account;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
25import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070026import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070028import android.content.Context;
29import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080041import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010042import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070043import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070045import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040046import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070047import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070048import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010049import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070050import android.os.storage.VolumeInfo;
51import android.system.ErrnoException;
52import android.system.Os;
53import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070054import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070055import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070056import android.util.Slog;
57import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080058import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070059import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070060import android.util.Xml;
61
Fyodor Kupolovb5013302015-04-17 17:59:14 -070062import com.google.android.collect.Sets;
63
Fyodor Kupolov262f9952015-03-23 18:55:11 -070064import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040065import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080066import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070067import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070068import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080069
70import org.xmlpull.v1.XmlPullParser;
71import org.xmlpull.v1.XmlPullParserException;
72import org.xmlpull.v1.XmlSerializer;
73
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.io.BufferedOutputStream;
75import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070076import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import java.io.FileOutputStream;
80import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070081import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010082import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import java.util.ArrayList;
84import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070085import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086
Fyodor Kupolov262f9952015-03-23 18:55:11 -070087import libcore.io.IoUtils;
88
Amith Yamasani258848d2012-08-10 17:06:33 -070089public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070090
Amith Yamasani2a003292012-08-14 18:25:45 -070091 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070092
Amith Yamasani16389312012-10-17 21:20:14 -070093 private static final boolean DBG = false;
94
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070097 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070099 private static final String ATTR_CREATION_TIME = "created";
100 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700101 private static final String ATTR_SERIAL_NO = "serialNumber";
102 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700103 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700104 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700105 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100106 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700107 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530108 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800111 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800112 private static final String TAG_ENTRY = "entry";
113 private static final String TAG_VALUE = "value";
114 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700115 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700118 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
119 private static final String ATTR_TYPE_STRING = "s";
120 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700121 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700122 private static final String ATTR_TYPE_BUNDLE = "B";
123 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700124
Amith Yamasani0b285492011-04-14 17:35:23 -0700125 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700127 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100128 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700129
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800130 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700131 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800132
Amith Yamasani634cf312012-10-04 17:34:21 -0700133 private static final int MIN_USER_ID = 10;
134
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700135 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700136
Amith Yamasani920ace02012-09-20 22:15:37 -0700137 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
138
Nicolas Prevotb8186812015-08-06 15:00:03 +0100139 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700140 // without first making sure that the rest of the framework is prepared for it.
141 private static final int MAX_MANAGED_PROFILES = 1;
142
Andres Moralesc5548c02015-08-05 10:23:12 -0700143 /**
144 * Flag indicating whether device credentials are shared among same-user profiles.
145 */
146 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
147
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700148 // Set of user restrictions, which can only be enforced by the system
149 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
150 UserManager.DISALLOW_RECORD_AUDIO);
151
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800152 static final int WRITE_USER_MSG = 1;
153 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530154
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700155 private static final String XATTR_SERIAL = "user.serial";
156
Dianne Hackborn4428e172012-08-24 17:43:05 -0700157 private final Context mContext;
158 private final PackageManagerService mPm;
159 private final Object mInstallLock;
160 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800162 private final Handler mHandler;
163
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700164 private final File mUsersDir;
165 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700166
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800167 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800168 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530169 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800170
171 /**
172 * Set of user IDs being actively removed. Removed IDs linger in this set
173 * for several seconds to work around a VFS caching issue.
174 */
175 // @GuardedBy("mPackagesLock")
176 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177
Amith Yamasani0b285492011-04-14 17:35:23 -0700178 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700179 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700180 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700181
Jason Monk62062992014-05-06 09:55:28 -0400182 private IAppOpsService mAppOpsService;
183
Amith Yamasani258848d2012-08-10 17:06:33 -0700184 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700185
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186 public static UserManagerService getInstance() {
187 synchronized (UserManagerService.class) {
188 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700189 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700190 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191
192 /**
193 * Available for testing purposes.
194 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700195 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700197 }
198
Dianne Hackborn4428e172012-08-24 17:43:05 -0700199 /**
200 * Called by package manager to create the service. This is closely
201 * associated with the package manager, and the given lock is the
202 * package manager's own lock.
203 */
204 UserManagerService(Context context, PackageManagerService pm,
205 Object installLock, Object packagesLock) {
206 this(context, pm, installLock, packagesLock,
207 Environment.getDataDirectory(),
208 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700209 }
210
Dianne Hackborn4428e172012-08-24 17:43:05 -0700211 /**
212 * Available for testing purposes.
213 */
214 private UserManagerService(Context context, PackageManagerService pm,
215 Object installLock, Object packagesLock,
216 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700217 mContext = context;
218 mPm = pm;
219 mInstallLock = installLock;
220 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800221 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700222 synchronized (mInstallLock) {
223 synchronized (mPackagesLock) {
224 mUsersDir = new File(dataDir, USER_INFO_DIR);
225 mUsersDir.mkdirs();
226 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700227 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700228 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700229 FileUtils.setPermissions(mUsersDir.toString(),
230 FileUtils.S_IRWXU|FileUtils.S_IRWXG
231 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
232 -1, -1);
233 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800234 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700235 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700236 sInstance = this;
237 }
238 }
239 }
240
241 void systemReady() {
242 synchronized (mInstallLock) {
243 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700244 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700245 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
Amith Yamasani515d4062015-09-28 11:30:06 -0700246 final int userSize = mUsers.size();
247 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700248 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700249 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700250 partials.add(ui);
251 }
252 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700253 final int partialsSize = partials.size();
254 for (int i = 0; i < partialsSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700256 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700257 + " (name=" + ui.name + ")");
258 removeUserStateLocked(ui.id);
259 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700260 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700261 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700262 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400263 mAppOpsService = IAppOpsService.Stub.asInterface(
264 ServiceManager.getService(Context.APP_OPS_SERVICE));
265 for (int i = 0; i < mUserIds.length; ++i) {
266 try {
267 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
268 } catch (RemoteException e) {
269 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
270 }
271 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700272 }
273
274 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700275 public UserInfo getPrimaryUser() {
276 checkManageUsersPermission("query users");
277 synchronized (mPackagesLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700278 final int userSize = mUsers.size();
279 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700280 UserInfo ui = mUsers.valueAt(i);
281 if (ui.isPrimary()) {
282 return ui;
283 }
284 }
285 }
286 return null;
287 }
288
289 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700290 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700291 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700292 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700293 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700294 final int userSize = mUsers.size();
295 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700296 UserInfo ui = mUsers.valueAt(i);
297 if (ui.partial) {
298 continue;
299 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800300 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700301 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700302 }
Amith Yamasani13593602012-03-22 16:16:17 -0700303 }
304 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700305 }
Amith Yamasani13593602012-03-22 16:16:17 -0700306 }
307
Amith Yamasani258848d2012-08-10 17:06:33 -0700308 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100309 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800310 if (userId != UserHandle.getCallingUserId()) {
311 checkManageUsersPermission("getting profiles related to user " + userId);
312 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700313 final long ident = Binder.clearCallingIdentity();
314 try {
315 synchronized (mPackagesLock) {
316 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100317 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700318 } finally {
319 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000320 }
321 }
322
Amith Yamasanibe465322014-04-24 13:45:17 -0700323 /** Assume permissions already checked and caller's identity cleared */
324 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700325 UserInfo user = getUserInfoLocked(userId);
326 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700327 if (user == null) {
328 // Probably a dying user
329 return users;
330 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700331 final int userSize = mUsers.size();
332 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700333 UserInfo profile = mUsers.valueAt(i);
334 if (!isProfileOf(user, profile)) {
335 continue;
336 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100337 if (enabledOnly && !profile.isEnabled()) {
338 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700339 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700340 if (mRemovingUserIds.get(profile.id)) {
341 continue;
342 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700343 users.add(profile);
344 }
345 return users;
346 }
347
Jessica Hummelbe81c802014-04-22 15:49:22 +0100348 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700349 public int getCredentialOwnerProfile(int userHandle) {
350 checkManageUsersPermission("get the credential owner");
351 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
352 synchronized (mPackagesLock) {
353 UserInfo profileParent = getProfileParentLocked(userHandle);
354 if (profileParent != null) {
355 return profileParent.id;
356 }
357 }
358 }
359
360 return userHandle;
361 }
362
363 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100364 public UserInfo getProfileParent(int userHandle) {
365 checkManageUsersPermission("get the profile parent");
366 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700367 return getProfileParentLocked(userHandle);
368 }
369 }
370
371 private UserInfo getProfileParentLocked(int userHandle) {
372 UserInfo profile = getUserInfoLocked(userHandle);
373 if (profile == null) {
374 return null;
375 }
376 int parentUserId = profile.profileGroupId;
377 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
378 return null;
379 } else {
380 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100381 }
382 }
383
Kenny Guy2a764942014-04-02 13:29:20 +0100384 private boolean isProfileOf(UserInfo user, UserInfo profile) {
385 return user.id == profile.id ||
386 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
387 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000388 }
389
390 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100391 public void setUserEnabled(int userId) {
392 checkManageUsersPermission("enable user");
393 synchronized (mPackagesLock) {
394 UserInfo info = getUserInfoLocked(userId);
395 if (info != null && !info.isEnabled()) {
396 info.flags ^= UserInfo.FLAG_DISABLED;
397 writeUserLocked(info);
398 }
399 }
400 }
401
402 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700403 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700404 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700405 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700406 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700407 }
408 }
409
Amith Yamasani71e6c692013-03-24 17:39:28 -0700410 @Override
411 public boolean isRestricted() {
412 synchronized (mPackagesLock) {
413 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
414 }
415 }
416
Amith Yamasani195263742012-08-21 15:40:12 -0700417 /*
418 * Should be locked on mUsers before calling this.
419 */
420 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700421 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700422 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800423 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700424 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
425 return null;
426 }
427 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700428 }
429
Amith Yamasani236b2b52015-08-18 14:32:14 -0700430 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700431 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700432 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700433 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700434 }
435 }
436
Amith Yamasani258848d2012-08-10 17:06:33 -0700437 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700438 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700439 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700440 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700441 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700442 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700443 if (info == null || info.partial) {
444 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
445 return;
446 }
Amith Yamasani13593602012-03-22 16:16:17 -0700447 if (name != null && !name.equals(info.name)) {
448 info.name = name;
449 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700450 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700451 }
452 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700453 if (changed) {
454 sendUserInfoChangedBroadcast(userId);
455 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700456 }
457
Amith Yamasani258848d2012-08-10 17:06:33 -0700458 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700459 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700460 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400461 long ident = Binder.clearCallingIdentity();
462 try {
463 synchronized (mPackagesLock) {
464 UserInfo info = mUsers.get(userId);
465 if (info == null || info.partial) {
466 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
467 return;
468 }
469 writeBitmapLocked(info, bitmap);
470 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700471 }
Jason Monk9a944532014-07-08 09:31:21 -0400472 sendUserInfoChangedBroadcast(userId);
473 } finally {
474 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700475 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700476 }
477
478 private void sendUserInfoChangedBroadcast(int userId) {
479 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
480 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
481 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700482 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700483 }
484
Amith Yamasani258848d2012-08-10 17:06:33 -0700485 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100486 public ParcelFileDescriptor getUserIcon(int userId) {
487 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700488 synchronized (mPackagesLock) {
489 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700490 if (info == null || info.partial) {
491 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
492 return null;
493 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100494 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
495 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
496 || callingGroupId != info.profileGroupId) {
497 checkManageUsersPermission("get the icon of a user who is not related");
498 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700499 if (info.iconPath == null) {
500 return null;
501 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100502 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700503 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100504
505 try {
506 return ParcelFileDescriptor.open(
507 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
508 } catch (FileNotFoundException e) {
509 Log.e(LOG_TAG, "Couldn't find icon file", e);
510 }
511 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700512 }
513
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700514 public void makeInitialized(int userId) {
515 checkManageUsersPermission("makeInitialized");
516 synchronized (mPackagesLock) {
517 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700518 if (info == null || info.partial) {
519 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
520 }
521 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700522 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800523 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700524 }
525 }
526 }
527
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700528 /**
529 * If default guest restrictions haven't been initialized yet, add the basic
530 * restrictions.
531 */
532 private void initDefaultGuestRestrictions() {
533 if (mGuestRestrictions.isEmpty()) {
534 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800535 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700536 }
537 }
538
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800539 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530540 public Bundle getDefaultGuestRestrictions() {
541 checkManageUsersPermission("getDefaultGuestRestrictions");
542 synchronized (mPackagesLock) {
543 return new Bundle(mGuestRestrictions);
544 }
545 }
546
547 @Override
548 public void setDefaultGuestRestrictions(Bundle restrictions) {
549 checkManageUsersPermission("setDefaultGuestRestrictions");
550 synchronized (mPackagesLock) {
551 mGuestRestrictions.clear();
552 mGuestRestrictions.putAll(restrictions);
553 writeUserListLocked();
554 }
555 }
556
557 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700558 public boolean hasUserRestriction(String restrictionKey, int userId) {
559 synchronized (mPackagesLock) {
560 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700561 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700562 }
563 }
564
565 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800566 public Bundle getUserRestrictions(int userId) {
567 // checkManageUsersPermission("getUserRestrictions");
568
569 synchronized (mPackagesLock) {
570 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700571 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800572 }
573 }
574
575 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700576 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700577 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700578 synchronized (mPackagesLock) {
579 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
580 Bundle restrictions = getUserRestrictions(userId);
581 restrictions.putBoolean(key, value);
582 setUserRestrictionsInternalLocked(restrictions, userId);
583 }
584 }
585 }
586
587 @Override
588 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
589 checkSystemOrRoot("setSystemControlledUserRestriction");
590 synchronized (mPackagesLock) {
591 Bundle restrictions = getUserRestrictions(userId);
592 restrictions.putBoolean(key, value);
593 setUserRestrictionsInternalLocked(restrictions, userId);
594 }
595 }
596
597 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800598 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700599 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700600 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800601
602 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700603 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
604 // Restore the original state of system controlled restrictions from oldUserRestrictions
605 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
606 restrictions.remove(key);
607 if (oldUserRestrictions.containsKey(key)) {
608 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
609 }
Jason Monk62062992014-05-06 09:55:28 -0400610 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700611 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800612 }
613 }
614
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700615 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
616 final Bundle userRestrictions = mUserRestrictions.get(userId);
617 userRestrictions.clear();
618 userRestrictions.putAll(restrictions);
619 long token = Binder.clearCallingIdentity();
620 try {
621 mAppOpsService.setUserRestrictions(userRestrictions, userId);
622 } catch (RemoteException e) {
623 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
624 } finally {
625 Binder.restoreCallingIdentity(token);
626 }
627 scheduleWriteUserLocked(mUsers.get(userId));
628 }
629
Amith Yamasani258848d2012-08-10 17:06:33 -0700630 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700631 * Check if we've hit the limit of how many users can be created.
632 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700633 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700634 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
635 }
636
637 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100638 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700639 checkManageUsersPermission("check if more managed profiles can be added.");
640 if (ActivityManager.isLowRamDeviceStatic()) {
641 return false;
642 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700643 if (!mContext.getPackageManager().hasSystemFeature(
644 PackageManager.FEATURE_MANAGED_USERS)) {
645 return false;
646 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100647 // Limit number of managed profiles that can be created
648 int managedProfilesCount = getProfiles(userId, true).size() - 1;
649 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
650 return false;
651 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700652 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100653 UserInfo userInfo = getUserInfoLocked(userId);
654 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700655 return false;
656 }
657 int usersCount = getAliveUsersExcludingGuestsCountLocked();
658 // We allow creating a managed profile in the special case where there is only one user.
659 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
660 }
661 }
662
663 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700664 int aliveUserCount = 0;
665 final int totalUserCount = mUsers.size();
666 // Skip over users being removed
667 for (int i = 0; i < totalUserCount; i++) {
668 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700669 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700670 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700671 aliveUserCount++;
672 }
673 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700674 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700675 }
676
677 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700678 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700679 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700680 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700681 *
682 * @param message used as message if SecurityException is thrown
683 * @throws SecurityException if the caller is not system or root
684 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700685 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700686 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700687 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400688 && ActivityManager.checkComponentPermission(
689 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700690 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
691 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
692 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400693 }
694
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700695 private static void checkSystemOrRoot(String message) {
696 final int uid = Binder.getCallingUid();
697 if (uid != Process.SYSTEM_UID && uid != 0) {
698 throw new SecurityException("Only system may call: " + message);
699 }
700 }
701
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700702 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700703 try {
704 File dir = new File(mUsersDir, Integer.toString(info.id));
705 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100706 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700707 if (!dir.exists()) {
708 dir.mkdir();
709 FileUtils.setPermissions(
710 dir.getPath(),
711 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
712 -1, -1);
713 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700714 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100715 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
716 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700717 info.iconPath = file.getAbsolutePath();
718 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700719 try {
720 os.close();
721 } catch (IOException ioe) {
722 // What the ... !
723 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100724 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700725 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700726 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700727 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700728 }
729
Amith Yamasani0b285492011-04-14 17:35:23 -0700730 /**
731 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
732 * cache it elsewhere.
733 * @return the array of user ids.
734 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700735 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700736 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700737 return mUserIds;
738 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700739 }
740
Dianne Hackborn4428e172012-08-24 17:43:05 -0700741 int[] getUserIdsLPr() {
742 return mUserIds;
743 }
744
Amith Yamasani13593602012-03-22 16:16:17 -0700745 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700746 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700747 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700748 return;
749 }
750 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700751 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700752 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700753 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700754 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100755 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700756 int type;
757 while ((type = parser.next()) != XmlPullParser.START_TAG
758 && type != XmlPullParser.END_DOCUMENT) {
759 ;
760 }
761
762 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700763 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700764 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700765 return;
766 }
767
Amith Yamasani2a003292012-08-14 18:25:45 -0700768 mNextSerialNumber = -1;
769 if (parser.getName().equals(TAG_USERS)) {
770 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
771 if (lastSerialNumber != null) {
772 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
773 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700774 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
775 if (versionNumber != null) {
776 mUserVersion = Integer.parseInt(versionNumber);
777 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700778 }
779
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700780 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530781 if (type == XmlPullParser.START_TAG) {
782 final String name = parser.getName();
783 if (name.equals(TAG_USER)) {
784 String id = parser.getAttributeValue(null, ATTR_ID);
785 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700786
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530787 if (user != null) {
788 mUsers.put(user.id, user);
789 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
790 mNextSerialNumber = user.id + 1;
791 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700792 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530793 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800794 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
795 && type != XmlPullParser.END_TAG) {
796 if (type == XmlPullParser.START_TAG) {
797 if (parser.getName().equals(TAG_RESTRICTIONS)) {
798 readRestrictionsLocked(parser, mGuestRestrictions);
799 }
800 break;
801 }
802 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700803 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700804 }
805 }
Amith Yamasani13593602012-03-22 16:16:17 -0700806 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700807 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700808 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700809 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700810 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700811 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800812 } finally {
813 if (fis != null) {
814 try {
815 fis.close();
816 } catch (IOException e) {
817 }
818 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700819 }
820 }
821
Amith Yamasani6f34b412012-10-22 18:19:27 -0700822 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800823 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700824 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700825 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700826 int userVersion = mUserVersion;
827 if (userVersion < 1) {
828 // Assign a proper name for the owner, if not initialized correctly before
829 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
830 if ("Primary".equals(user.name)) {
831 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800832 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700833 }
834 userVersion = 1;
835 }
836
Amith Yamasanibc9625052012-11-15 14:39:18 -0800837 if (userVersion < 2) {
838 // Owner should be marked as initialized
839 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
840 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
841 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800842 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800843 }
844 userVersion = 2;
845 }
846
Amith Yamasani350962c2013-08-06 11:18:53 -0700847
Amith Yamasani5e486f52013-08-07 11:06:44 -0700848 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700849 userVersion = 4;
850 }
851
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700852 if (userVersion < 5) {
853 initDefaultGuestRestrictions();
854 userVersion = 5;
855 }
856
Amith Yamasani6f34b412012-10-22 18:19:27 -0700857 if (userVersion < USER_VERSION) {
858 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
859 + USER_VERSION);
860 } else {
861 mUserVersion = userVersion;
862 writeUserListLocked();
863 }
864 }
865
Amith Yamasani13593602012-03-22 16:16:17 -0700866 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700867 int flags = UserInfo.FLAG_INITIALIZED;
868 // In split system user mode, the admin and primary flags are assigned to the first human
869 // user.
870 if (!UserManager.isSplitSystemUser()) {
871 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
872 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700873 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700874 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700875 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700876 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700877 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700878 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400879 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800880
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500881 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700882 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800883
Amith Yamasani13593602012-03-22 16:16:17 -0700884 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700885 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700886
Amith Yamasani13593602012-03-22 16:16:17 -0700887 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700888 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700889 }
890
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800891 private void scheduleWriteUserLocked(UserInfo userInfo) {
892 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
893 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
894 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
895 }
896 }
897
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700898 /*
899 * Writes the user file in this format:
900 *
901 * <user flags="20039023" id="0">
902 * <name>Primary</name>
903 * </user>
904 */
Amith Yamasani13593602012-03-22 16:16:17 -0700905 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700906 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700907 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700908 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700909 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700910 final BufferedOutputStream bos = new BufferedOutputStream(fos);
911
912 // XmlSerializer serializer = XmlUtils.serializerInstance();
913 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100914 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700915 serializer.startDocument(null, true);
916 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
917
918 serializer.startTag(null, TAG_USER);
919 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700920 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700921 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700922 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
923 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
924 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700925 if (userInfo.iconPath != null) {
926 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
927 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700928 if (userInfo.partial) {
929 serializer.attribute(null, ATTR_PARTIAL, "true");
930 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700931 if (userInfo.guestToRemove) {
932 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
933 }
Kenny Guy2a764942014-04-02 13:29:20 +0100934 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
935 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
936 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000937 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700938 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
939 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
940 Integer.toString(userInfo.restrictedProfileParentId));
941 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700942 serializer.startTag(null, TAG_NAME);
943 serializer.text(userInfo.name);
944 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800945 Bundle restrictions = mUserRestrictions.get(userInfo.id);
946 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530947 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800948 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700949 serializer.endTag(null, TAG_USER);
950
951 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700952 userFile.finishWrite(fos);
953 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700954 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700955 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700956 }
957 }
958
959 /*
960 * Writes the user list file in this format:
961 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700962 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700963 * <user id="0"></user>
964 * <user id="2"></user>
965 * </users>
966 */
Amith Yamasani13593602012-03-22 16:16:17 -0700967 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700968 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700969 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700970 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700971 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700972 final BufferedOutputStream bos = new BufferedOutputStream(fos);
973
974 // XmlSerializer serializer = XmlUtils.serializerInstance();
975 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100976 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700977 serializer.startDocument(null, true);
978 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
979
980 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700981 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700982 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700983
Adam Lesinskieddeb492014-09-08 17:50:03 -0700984 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530985 writeRestrictionsLocked(serializer, mGuestRestrictions);
986 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani515d4062015-09-28 11:30:06 -0700987 final int userSize = mUsers.size();
988 for (int i = 0; i < userSize; i++) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700989 UserInfo user = mUsers.valueAt(i);
990 serializer.startTag(null, TAG_USER);
991 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
992 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700993 }
994
995 serializer.endTag(null, TAG_USERS);
996
997 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700998 userListFile.finishWrite(fos);
999 } catch (Exception e) {
1000 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001001 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001002 }
1003 }
1004
Andres Moralesc5548c02015-08-05 10:23:12 -07001005 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301006 throws IOException {
1007 serializer.startTag(null, TAG_RESTRICTIONS);
1008 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1009 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1010 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1011 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1012 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1013 writeBoolean(serializer, restrictions,
1014 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1015 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1016 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1017 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1018 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1019 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1020 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1021 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001022 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301023 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1024 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1025 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1026 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1027 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1028 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1029 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1030 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1031 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001032 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1033 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001034 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001035 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001036 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1037 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001038 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001039 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001040 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301041 serializer.endTag(null, TAG_RESTRICTIONS);
1042 }
1043
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001044 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001045 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001046 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001047 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001048 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001049 long creationTime = 0L;
1050 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001051 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001052 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001053 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001054 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001055 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001056
1057 FileInputStream fis = null;
1058 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001059 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001060 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001061 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001062 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001063 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001064 int type;
1065 while ((type = parser.next()) != XmlPullParser.START_TAG
1066 && type != XmlPullParser.END_DOCUMENT) {
1067 ;
1068 }
1069
1070 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001071 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001072 return null;
1073 }
1074
1075 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001076 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1077 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001078 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001079 return null;
1080 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001081 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1082 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001083 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001084 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1085 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001086 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1087 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001088 restrictedProfileParentId = readIntAttribute(parser,
1089 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001090 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1091 if ("true".equals(valueString)) {
1092 partial = true;
1093 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001094 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1095 if ("true".equals(valueString)) {
1096 guestToRemove = true;
1097 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001098
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001099 int outerDepth = parser.getDepth();
1100 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1101 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1102 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1103 continue;
1104 }
1105 String tag = parser.getName();
1106 if (TAG_NAME.equals(tag)) {
1107 type = parser.next();
1108 if (type == XmlPullParser.TEXT) {
1109 name = parser.getText();
1110 }
1111 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301112 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001113 }
1114 }
1115 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001116
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001117 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001118 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001119 userInfo.creationTime = creationTime;
1120 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001121 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001122 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001123 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001124 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001125 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001126 return userInfo;
1127
1128 } catch (IOException ioe) {
1129 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001130 } finally {
1131 if (fis != null) {
1132 try {
1133 fis.close();
1134 } catch (IOException e) {
1135 }
1136 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001137 }
1138 return null;
1139 }
1140
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301141 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1142 throws IOException {
1143 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1144 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1145 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1146 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1147 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1148 readBoolean(parser, restrictions,
1149 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1150 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1151 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1152 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1153 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1154 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1155 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1156 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001157 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301158 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1159 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1160 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1161 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1162 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1163 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1164 readBoolean(parser, restrictions,
1165 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1166 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1167 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001168 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1169 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001170 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001171 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001172 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1173 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001174 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001175 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001176 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301177 }
1178
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001179 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1180 String restrictionKey) {
1181 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001182 if (value != null) {
1183 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1184 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001185 }
1186
1187 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1188 throws IOException {
1189 if (restrictions.containsKey(restrictionKey)) {
1190 xml.attribute(null, restrictionKey,
1191 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1192 }
1193 }
1194
Amith Yamasani920ace02012-09-20 22:15:37 -07001195 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1196 String valueString = parser.getAttributeValue(null, attr);
1197 if (valueString == null) return defaultValue;
1198 try {
1199 return Integer.parseInt(valueString);
1200 } catch (NumberFormatException nfe) {
1201 return defaultValue;
1202 }
1203 }
1204
1205 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1206 String valueString = parser.getAttributeValue(null, attr);
1207 if (valueString == null) return defaultValue;
1208 try {
1209 return Long.parseLong(valueString);
1210 } catch (NumberFormatException nfe) {
1211 return defaultValue;
1212 }
1213 }
1214
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001215 private boolean isPackageInstalled(String pkg, int userId) {
1216 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1217 PackageManager.GET_UNINSTALLED_PACKAGES,
1218 userId);
1219 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1220 return false;
1221 }
1222 return true;
1223 }
1224
Amith Yamasanib82add22013-07-09 11:24:44 -07001225 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001226 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001227 * Does not do any permissions checking.
1228 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001229 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001230 synchronized (mPackagesLock) {
1231 File dir = Environment.getUserSystemDirectory(userId);
1232 String[] files = dir.list();
1233 if (files == null) return;
1234 for (String fileName : files) {
1235 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1236 File resFile = new File(dir, fileName);
1237 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001238 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001239 }
1240 }
1241 }
1242 }
1243 }
1244
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001245 /**
1246 * Removes the app restrictions file for a specific package and user id, if it exists.
1247 */
1248 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1249 synchronized (mPackagesLock) {
1250 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001251 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001252 if (resFile.exists()) {
1253 resFile.delete();
1254 }
1255 }
1256 }
1257
Kenny Guya52dc3e2014-02-11 15:33:14 +00001258 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001259 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001260 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001261 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001262 }
1263
Amith Yamasani258848d2012-08-10 17:06:33 -07001264 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001265 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001266 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001267 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001268 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001269
Jessica Hummelbe81c802014-04-22 15:49:22 +01001270 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001271 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1272 UserManager.DISALLOW_ADD_USER, false)) {
1273 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1274 return null;
1275 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001276 if (ActivityManager.isLowRamDeviceStatic()) {
1277 return null;
1278 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001279 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001280 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001281 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001282 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001283 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001284 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001285 try {
1286 synchronized (mInstallLock) {
1287 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001288 UserInfo parent = null;
1289 if (parentId != UserHandle.USER_NULL) {
1290 parent = getUserInfoLocked(parentId);
1291 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001292 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001293 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1294 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001295 return null;
1296 }
1297 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1298 // If we're not adding a guest user or a managed profile and the limit has
1299 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001300 return null;
1301 }
1302 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001303 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001304 return null;
1305 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001306 // In legacy mode, restricted profile's parent can only be the owner user
1307 if (isRestricted && !UserManager.isSplitSystemUser()
1308 && (parentId != UserHandle.USER_SYSTEM)) {
1309 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1310 return null;
1311 }
1312 if (isRestricted && UserManager.isSplitSystemUser()) {
1313 if (parent == null) {
1314 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1315 + "specified");
1316 return null;
1317 }
1318 if (!parent.canHaveProfile()) {
1319 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1320 + "created for the specified parent user id " + parentId);
1321 return null;
1322 }
1323 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001324 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001325 // And if there is no device owner, we also assign the admin flag to primary
1326 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001327 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001328 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001329 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001330 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1331 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1332 if (devicePolicyManager == null
1333 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001334 flags |= UserInfo.FLAG_ADMIN;
1335 }
1336 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001337 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001338 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001339 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001340 long now = System.currentTimeMillis();
1341 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001342 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001343 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001344 mUsers.put(userId, userInfo);
1345 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001346 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001347 if (isManagedProfile) {
1348 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1349 parent.profileGroupId = parent.id;
1350 scheduleWriteUserLocked(parent);
1351 }
1352 userInfo.profileGroupId = parent.profileGroupId;
1353 } else if (isRestricted) {
1354 if (!parent.canHaveProfile()) {
1355 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1356 }
1357 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1358 parent.restrictedProfileParentId = parent.id;
1359 scheduleWriteUserLocked(parent);
1360 }
1361 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001362 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001363 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001364 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1365 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1366 final String volumeUuid = vol.getFsUuid();
1367 try {
1368 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1369 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001370 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001371 enforceSerialNumber(userDir, userInfo.serialNumber);
1372 } catch (IOException e) {
1373 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1374 }
1375 }
1376 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001377 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001378 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001379 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001380 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001381 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001382 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001383 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001384 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001385 if (userInfo != null) {
1386 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1387 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1388 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1389 android.Manifest.permission.MANAGE_USERS);
1390 }
1391 } finally {
1392 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001393 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001394 return userInfo;
1395 }
1396
Amith Yamasani0b285492011-04-14 17:35:23 -07001397 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001398 * @hide
1399 */
1400 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1401 checkManageUsersPermission("setupRestrictedProfile");
1402 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1403 if (user == null) {
1404 return null;
1405 }
1406 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1407 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1408 // the putIntForUser() will fail.
1409 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1410 android.provider.Settings.Secure.LOCATION_MODE,
1411 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1412 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1413 return user;
1414 }
1415
1416 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001417 * Find the current guest user. If the Guest user is partial,
1418 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001419 */
1420 private UserInfo findCurrentGuestUserLocked() {
1421 final int size = mUsers.size();
1422 for (int i = 0; i < size; i++) {
1423 final UserInfo user = mUsers.valueAt(i);
1424 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1425 return user;
1426 }
1427 }
1428 return null;
1429 }
1430
1431 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001432 * Mark this guest user for deletion to allow us to create another guest
1433 * and switch to that user before actually removing this guest.
1434 * @param userHandle the userid of the current guest
1435 * @return whether the user could be marked for deletion
1436 */
1437 public boolean markGuestForDeletion(int userHandle) {
1438 checkManageUsersPermission("Only the system can remove users");
1439 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1440 UserManager.DISALLOW_REMOVE_USER, false)) {
1441 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1442 return false;
1443 }
1444
1445 long ident = Binder.clearCallingIdentity();
1446 try {
1447 final UserInfo user;
1448 synchronized (mPackagesLock) {
1449 user = mUsers.get(userHandle);
1450 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1451 return false;
1452 }
1453 if (!user.isGuest()) {
1454 return false;
1455 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001456 // We set this to a guest user that is to be removed. This is a temporary state
1457 // where we are allowed to add new Guest users, even if this one is still not
1458 // removed. This user will still show up in getUserInfo() calls.
1459 // If we don't get around to removing this Guest user, it will be purged on next
1460 // startup.
1461 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001462 // Mark it as disabled, so that it isn't returned any more when
1463 // profiles are queried.
1464 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001465 writeUserLocked(user);
1466 }
1467 } finally {
1468 Binder.restoreCallingIdentity(ident);
1469 }
1470 return true;
1471 }
1472
1473 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001474 * Removes a user and all data directories created for that user. This method should be called
1475 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001476 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001477 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001478 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001479 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001480 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1481 UserManager.DISALLOW_REMOVE_USER, false)) {
1482 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1483 return false;
1484 }
1485
Kenny Guyee58b4f2014-05-23 15:19:53 +01001486 long ident = Binder.clearCallingIdentity();
1487 try {
1488 final UserInfo user;
1489 synchronized (mPackagesLock) {
1490 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001491 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001492 return false;
1493 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001494
1495 // We remember deleted user IDs to prevent them from being
1496 // reused during the current boot; they can still be reused
1497 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001498 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001499
Kenny Guyee58b4f2014-05-23 15:19:53 +01001500 try {
1501 mAppOpsService.removeUser(userHandle);
1502 } catch (RemoteException e) {
1503 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1504 }
1505 // Set this to a partially created user, so that the user will be purged
1506 // on next startup, in case the runtime stops now before stopping and
1507 // removing the user completely.
1508 user.partial = true;
1509 // Mark it as disabled, so that it isn't returned any more when
1510 // profiles are queried.
1511 user.flags |= UserInfo.FLAG_DISABLED;
1512 writeUserLocked(user);
1513 }
1514
1515 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1516 && user.isManagedProfile()) {
1517 // Send broadcast to notify system that the user removed was a
1518 // managed user.
1519 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1520 }
1521
1522 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1523 int res;
1524 try {
1525 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1526 new IStopUserCallback.Stub() {
1527 @Override
1528 public void userStopped(int userId) {
1529 finishRemoveUser(userId);
1530 }
1531 @Override
1532 public void userStopAborted(int userId) {
1533 }
1534 });
1535 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001536 return false;
1537 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001538 return res == ActivityManager.USER_OP_SUCCESS;
1539 } finally {
1540 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001541 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001542 }
1543
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001544 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001545 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001546 // Let other services shutdown any activity and clean up their state before completely
1547 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001548 long ident = Binder.clearCallingIdentity();
1549 try {
1550 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1551 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001552 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1553 android.Manifest.permission.MANAGE_USERS,
1554
1555 new BroadcastReceiver() {
1556 @Override
1557 public void onReceive(Context context, Intent intent) {
1558 if (DBG) {
1559 Slog.i(LOG_TAG,
1560 "USER_REMOVED broadcast sent, cleaning up user data "
1561 + userHandle);
1562 }
1563 new Thread() {
1564 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001565 // Clean up any ActivityManager state
1566 LocalServices.getService(ActivityManagerInternal.class)
1567 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001568 synchronized (mInstallLock) {
1569 synchronized (mPackagesLock) {
1570 removeUserStateLocked(userHandle);
1571 }
1572 }
1573 }
1574 }.start();
1575 }
1576 },
1577
1578 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001579 } finally {
1580 Binder.restoreCallingIdentity(ident);
1581 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001582 }
1583
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001584 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001585 mContext.getSystemService(StorageManager.class)
1586 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001587 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001588 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001589
1590 // Remove this user from the list
1591 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001592 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001593 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001594 userFile.delete();
1595 // Update the user list
1596 writeUserListLocked();
1597 updateUserIdsLocked();
1598 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1599 }
1600
Amith Yamasani61f57372012-08-31 12:12:28 -07001601 private void removeDirectoryRecursive(File parent) {
1602 if (parent.isDirectory()) {
1603 String[] files = parent.list();
1604 for (String filename : files) {
1605 File child = new File(parent, filename);
1606 removeDirectoryRecursive(child);
1607 }
1608 }
1609 parent.delete();
1610 }
1611
Kenny Guyf8d3a232014-05-15 16:09:52 +01001612 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001613 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001614 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1615 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001616 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1617 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001618 }
1619
Amith Yamasani2a003292012-08-14 18:25:45 -07001620 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001621 public Bundle getApplicationRestrictions(String packageName) {
1622 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1623 }
1624
1625 @Override
1626 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001627 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001628 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001629 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001630 }
1631 synchronized (mPackagesLock) {
1632 // Read the restrictions from XML
1633 return readApplicationRestrictionsLocked(packageName, userId);
1634 }
1635 }
1636
1637 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001638 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001639 int userId) {
1640 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001641 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001642 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001643 }
1644 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001645 if (restrictions == null || restrictions.isEmpty()) {
1646 cleanAppRestrictionsForPackage(packageName, userId);
1647 } else {
1648 // Write the restrictions to XML
1649 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1650 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001651 }
Robin Lee66e5d962014-04-09 16:44:21 +01001652
Kenny Guyd21b2182014-07-17 16:38:55 +01001653 if (isPackageInstalled(packageName, userId)) {
1654 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1655 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1656 changeIntent.setPackage(packageName);
1657 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1658 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1659 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001660 }
1661
Amith Yamasani655d0e22013-06-12 14:19:10 -07001662 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001663 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001664 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001665 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001666 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001667 }
1668
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001669 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001670 synchronized (mPackagesLock) {
1671 // Remove all user restrictions
1672 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001673 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001674 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001675 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001676 if (unhideApps) {
1677 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001678 }
1679 }
1680
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001681 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001682 mHandler.post(new Runnable() {
1683 @Override
1684 public void run() {
1685 List<ApplicationInfo> apps =
1686 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1687 userHandle).getList();
1688 final long ident = Binder.clearCallingIdentity();
1689 try {
1690 for (ApplicationInfo appInfo : apps) {
1691 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001692 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1693 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001694 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001695 userHandle);
1696 }
1697 }
1698 } finally {
1699 Binder.restoreCallingIdentity(ident);
1700 }
1701 }
1702 });
1703 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001704 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001705 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001706 try {
1707 return mContext.getPackageManager().getApplicationInfo(packageName,
1708 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1709 } catch (NameNotFoundException nnfe) {
1710 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001711 } finally {
1712 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001713 }
1714 }
1715
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001716 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001717 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001718 AtomicFile restrictionsFile =
1719 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1720 packageToRestrictionsFileName(packageName)));
1721 return readApplicationRestrictionsLocked(restrictionsFile);
1722 }
1723
1724 @VisibleForTesting
1725 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001726 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001727 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001728 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001729 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001730 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001731
1732 FileInputStream fis = null;
1733 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001734 fis = restrictionsFile.openRead();
1735 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001736 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001737 XmlUtils.nextElement(parser);
1738 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001739 Slog.e(LOG_TAG, "Unable to read restrictions file "
1740 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001741 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001742 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001743 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1744 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001745 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001746 } catch (IOException|XmlPullParserException e) {
1747 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001748 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001749 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001750 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001751 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001752 }
1753
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001754 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1755 XmlPullParser parser) throws XmlPullParserException, IOException {
1756 int type = parser.getEventType();
1757 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1758 String key = parser.getAttributeValue(null, ATTR_KEY);
1759 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1760 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1761 if (multiple != null) {
1762 values.clear();
1763 int count = Integer.parseInt(multiple);
1764 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1765 if (type == XmlPullParser.START_TAG
1766 && parser.getName().equals(TAG_VALUE)) {
1767 values.add(parser.nextText().trim());
1768 count--;
1769 }
1770 }
1771 String [] valueStrings = new String[values.size()];
1772 values.toArray(valueStrings);
1773 restrictions.putStringArray(key, valueStrings);
1774 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1775 restrictions.putBundle(key, readBundleEntry(parser, values));
1776 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1777 final int outerDepth = parser.getDepth();
1778 ArrayList<Bundle> bundleList = new ArrayList<>();
1779 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1780 Bundle childBundle = readBundleEntry(parser, values);
1781 bundleList.add(childBundle);
1782 }
1783 restrictions.putParcelableArray(key,
1784 bundleList.toArray(new Bundle[bundleList.size()]));
1785 } else {
1786 String value = parser.nextText().trim();
1787 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1788 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1789 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1790 restrictions.putInt(key, Integer.parseInt(value));
1791 } else {
1792 restrictions.putString(key, value);
1793 }
1794 }
1795 }
1796 }
1797
1798 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1799 throws IOException, XmlPullParserException {
1800 Bundle childBundle = new Bundle();
1801 final int outerDepth = parser.getDepth();
1802 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1803 readEntry(childBundle, values, parser);
1804 }
1805 return childBundle;
1806 }
1807
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001808 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001809 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001810 AtomicFile restrictionsFile = new AtomicFile(
1811 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001812 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001813 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1814 }
1815
1816 @VisibleForTesting
1817 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1818 AtomicFile restrictionsFile) {
1819 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001820 try {
1821 fos = restrictionsFile.startWrite();
1822 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1823
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001824 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001825 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001826 serializer.startDocument(null, true);
1827 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1828
1829 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001830 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001831 serializer.endTag(null, TAG_RESTRICTIONS);
1832
1833 serializer.endDocument();
1834 restrictionsFile.finishWrite(fos);
1835 } catch (Exception e) {
1836 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001837 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1838 }
1839 }
1840
1841 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1842 throws IOException {
1843 for (String key : restrictions.keySet()) {
1844 Object value = restrictions.get(key);
1845 serializer.startTag(null, TAG_ENTRY);
1846 serializer.attribute(null, ATTR_KEY, key);
1847
1848 if (value instanceof Boolean) {
1849 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1850 serializer.text(value.toString());
1851 } else if (value instanceof Integer) {
1852 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1853 serializer.text(value.toString());
1854 } else if (value == null || value instanceof String) {
1855 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1856 serializer.text(value != null ? (String) value : "");
1857 } else if (value instanceof Bundle) {
1858 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1859 writeBundle((Bundle) value, serializer);
1860 } else if (value instanceof Parcelable[]) {
1861 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1862 Parcelable[] array = (Parcelable[]) value;
1863 for (Parcelable parcelable : array) {
1864 if (!(parcelable instanceof Bundle)) {
1865 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1866 }
1867 serializer.startTag(null, TAG_ENTRY);
1868 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1869 writeBundle((Bundle) parcelable, serializer);
1870 serializer.endTag(null, TAG_ENTRY);
1871 }
1872 } else {
1873 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1874 String[] values = (String[]) value;
1875 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1876 for (String choice : values) {
1877 serializer.startTag(null, TAG_VALUE);
1878 serializer.text(choice != null ? choice : "");
1879 serializer.endTag(null, TAG_VALUE);
1880 }
1881 }
1882 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001883 }
1884 }
1885
1886 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001887 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001888 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001889 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001890 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001891 }
1892 }
1893
1894 @Override
1895 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001896 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001897 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001898 UserInfo info = getUserInfoLocked(userId);
1899 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001900 }
1901 // Not found
1902 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001903 }
1904 }
1905
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001906 @Override
1907 public long getUserCreationTime(int userHandle) {
1908 int callingUserId = UserHandle.getCallingUserId();
1909 UserInfo userInfo = null;
1910 synchronized (mPackagesLock) {
1911 if (callingUserId == userHandle) {
1912 userInfo = getUserInfoLocked(userHandle);
1913 } else {
1914 UserInfo parent = getProfileParentLocked(userHandle);
1915 if (parent != null && parent.id == callingUserId) {
1916 userInfo = getUserInfoLocked(userHandle);
1917 }
1918 }
1919 }
1920 if (userInfo == null) {
1921 throw new SecurityException("userHandle can only be the calling user or a managed "
1922 + "profile associated with this user");
1923 }
1924 return userInfo.creationTime;
1925 }
1926
Amith Yamasani0b285492011-04-14 17:35:23 -07001927 /**
1928 * Caches the list of user ids in an array, adjusting the array size when necessary.
1929 */
Amith Yamasani13593602012-03-22 16:16:17 -07001930 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001931 int num = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001932 final int userSize = mUsers.size();
1933 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001934 if (!mUsers.valueAt(i).partial) {
1935 num++;
1936 }
1937 }
Amith Yamasani16389312012-10-17 21:20:14 -07001938 final int[] newUsers = new int[num];
1939 int n = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001940 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001941 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001942 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001943 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001944 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001945 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001946 }
1947
1948 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001949 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001950 * @param userId the user that was just foregrounded
1951 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001952 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001953 synchronized (mPackagesLock) {
1954 UserInfo user = mUsers.get(userId);
1955 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001956 if (user == null || user.partial) {
1957 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1958 return;
1959 }
1960 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001961 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001962 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001963 }
1964 }
1965 }
1966
1967 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001968 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001969 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1970 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001971 * @return
1972 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001973 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001974 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001975 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001976 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001977 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001978 break;
1979 }
1980 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001981 }
Amith Yamasani195263742012-08-21 15:40:12 -07001982 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001983 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001984 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001985
Amith Yamasanifc95e702013-09-26 13:20:17 -07001986 private String packageToRestrictionsFileName(String packageName) {
1987 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1988 }
1989
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001990 /**
1991 * Create new {@code /data/user/[id]} directory and sets default
1992 * permissions.
1993 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001994 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
1995 final StorageManager storage = context.getSystemService(StorageManager.class);
1996 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1997 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001998 }
1999
2000 /**
2001 * Enforce that serial number stored in user directory inode matches the
2002 * given expected value. Gracefully sets the serial number if currently
2003 * undefined.
2004 *
2005 * @throws IOException when problem extracting serial number, or serial
2006 * number is mismatched.
2007 */
2008 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2009 final int foundSerial = getSerialNumber(file);
2010 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2011
2012 if (foundSerial == -1) {
2013 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2014 try {
2015 setSerialNumber(file, serialNumber);
2016 } catch (IOException e) {
2017 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2018 }
2019
2020 } else if (foundSerial != serialNumber) {
2021 throw new IOException("Found serial number " + foundSerial
2022 + " doesn't match expected " + serialNumber);
2023 }
2024 }
2025
2026 /**
2027 * Set serial number stored in user directory inode.
2028 *
2029 * @throws IOException if serial number was already set
2030 */
2031 private static void setSerialNumber(File file, int serialNumber)
2032 throws IOException {
2033 try {
2034 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2035 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2036 } catch (ErrnoException e) {
2037 throw e.rethrowAsIOException();
2038 }
2039 }
2040
2041 /**
2042 * Return serial number stored in user directory inode.
2043 *
2044 * @return parsed serial number, or -1 if not set
2045 */
2046 private static int getSerialNumber(File file) throws IOException {
2047 try {
2048 final byte[] buf = new byte[256];
2049 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2050 final String serial = new String(buf, 0, len);
2051 try {
2052 return Integer.parseInt(serial);
2053 } catch (NumberFormatException e) {
2054 throw new IOException("Bad serial number: " + serial);
2055 }
2056 } catch (ErrnoException e) {
2057 if (e.errno == OsConstants.ENODATA) {
2058 return -1;
2059 } else {
2060 throw e.rethrowAsIOException();
2061 }
2062 }
2063 }
2064
Amith Yamasani920ace02012-09-20 22:15:37 -07002065 @Override
2066 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2067 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2068 != PackageManager.PERMISSION_GRANTED) {
2069 pw.println("Permission Denial: can't dump UserManager from from pid="
2070 + Binder.getCallingPid()
2071 + ", uid=" + Binder.getCallingUid()
2072 + " without permission "
2073 + android.Manifest.permission.DUMP);
2074 return;
2075 }
2076
2077 long now = System.currentTimeMillis();
2078 StringBuilder sb = new StringBuilder();
2079 synchronized (mPackagesLock) {
2080 pw.println("Users:");
2081 for (int i = 0; i < mUsers.size(); i++) {
2082 UserInfo user = mUsers.valueAt(i);
2083 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002084 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002085 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002086 if (user.partial) pw.print(" <partial>");
2087 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002088 pw.print(" Created: ");
2089 if (user.creationTime == 0) {
2090 pw.println("<unknown>");
2091 } else {
2092 sb.setLength(0);
2093 TimeUtils.formatDuration(now - user.creationTime, sb);
2094 sb.append(" ago");
2095 pw.println(sb);
2096 }
2097 pw.print(" Last logged in: ");
2098 if (user.lastLoggedInTime == 0) {
2099 pw.println("<unknown>");
2100 } else {
2101 sb.setLength(0);
2102 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2103 sb.append(" ago");
2104 pw.println(sb);
2105 }
2106 }
2107 }
2108 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002109
2110 final class MainHandler extends Handler {
2111
2112 @Override
2113 public void handleMessage(Message msg) {
2114 switch (msg.what) {
2115 case WRITE_USER_MSG:
2116 removeMessages(WRITE_USER_MSG, msg.obj);
2117 synchronized (mPackagesLock) {
2118 int userId = ((UserInfo) msg.obj).id;
2119 UserInfo userInfo = mUsers.get(userId);
2120 if (userInfo != null) {
2121 writeUserLocked(userInfo);
2122 }
2123 }
2124 }
2125 }
2126 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002127
2128 /**
2129 * @param userId
2130 * @return whether the user has been initialized yet
2131 */
2132 boolean isInitialized(int userId) {
2133 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2134 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002135}